在这种情况下如何更改小部件的主题?

取消工程师

我不确定我的代码是否适合同时使用主题和 easylocalization,并且我也愿意寻求任何帮助,但我的主要目标是在 MyApp 中创建一个自定义导航栏。当我像下面的示例那样执行此操作时,我无法使用我的主题提供程序更改我的 NavBarItem 主题,因为它在 MaterialApp 之外。我该如何处理这种情况?

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();
  runApp(EasyLocalization(
      supportedLocales: [
        Locale('en'),
        Locale('tr'),
      ],
      path: 'assets/translations',
      saveLocale: true,
      fallbackLocale: Locale('en'),
      child: MyApp()));
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => CustomThemeData(),
      builder: (context, _) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,

          localizationsDelegates: context.localizationDelegates,
          supportedLocales: context.supportedLocales,
          locale: context.locale,
          theme: Provider.of<CustomThemeData>(context).getThemeData,
          home: Scaffold(
            body: _ActivePage,
            bottomNavigationBar: Container(child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  NavBarItem(),
                  NavBarItem(),
                  NavBarItem(),
                ],
              ),),
          ),
          //
        );
      },
    );
  }

  Widget NavBarItem(){}
}
肖元

你可以在下面的代码库中尝试这个,我想你会得到你的解决方案。

主要.dart

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:theme_changer/custom_theme_data.dart';

final callMenuTheme = ThemeData(
  primarySwatch: Colors.orange,
  colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.orange),
  iconTheme: const IconThemeData(
    color: Colors.orange,
  ),
);

final cameraMenuTheme = ThemeData(
  primarySwatch: Colors.red,
  colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.red),
  iconTheme: const IconThemeData(
    color: Colors.red,
  ),
);

final chatMenuTheme = ThemeData(
  primarySwatch: Colors.green,
  colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.green),
  iconTheme: const IconThemeData(
    color: Colors.green,
  ),
);

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();
  runApp(EasyLocalization(
      supportedLocales: const [
        Locale('en'),
        Locale('tr'),
      ],
      path: 'assets/translations',
      saveLocale: true,
      fallbackLocale: const Locale('en'),
      child: ChangeNotifierProvider(
        create: (context) => CustomThemeData(0, callMenuTheme),
        builder: (context, _) {
          return MaterialApp(
            debugShowCheckedModeBanner: false,
            localizationsDelegates: context.localizationDelegates,
            supportedLocales: context.supportedLocales,
            locale: context.locale,
            theme: Provider.of<CustomThemeData>(context).getThemeData(),
            home: const MyApp(),
            //
          );
        },
      )));
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {

    var themeNotifier = Provider.of<CustomThemeData>(context,listen: false);

    List<Widget> _pages = <Widget>[
      const Icon(
        Icons.call,
        size: 150,
      ),
      const Icon(
        Icons.camera,
        size: 150,
      ),
      const Icon(
        Icons.chat,
        size: 150,
      ),
    ];


    void _onItemTapped(int index) async{
      setState(() {
        switch(index) {
          case 0:
            {
              themeNotifier.setNavigationIndexData(0);
              themeNotifier.setThemeData(callMenuTheme);
            }
            break;

          case 1:
            {
              themeNotifier.setNavigationIndexData(1);
              themeNotifier.setThemeData(cameraMenuTheme);
            }
            break;

          case 2:
            {
              themeNotifier.setNavigationIndexData(2);
              themeNotifier.setThemeData(chatMenuTheme);
            }
            break;

          default:
            {
              themeNotifier.setNavigationIndexData(0);
              themeNotifier.setThemeData(callMenuTheme);
            }
            break;
        }
      });
    }

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      localizationsDelegates: context.localizationDelegates,
      supportedLocales: context.supportedLocales,
      locale: context.locale,
      theme: themeNotifier.getThemeData(),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('BottomNavigationBar Demo'),
        ),
        body: Center(
          child: _pages.elementAt(themeNotifier.getNavigationIndexData()),
        ),
        bottomNavigationBar: BottomNavigationBar(
          items: const <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(Icons.call),
              label: 'Calls',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.camera),
              label: 'Camera',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.chat),
              label: 'Chats',
            ),
          ],
          currentIndex: themeNotifier.getNavigationIndexData(),
          onTap: _onItemTapped,
        ),
      ),

    );

  }
}

custom_theme_data.dart

import 'package:flutter/material.dart';

class CustomThemeData with ChangeNotifier {
  ThemeData? _themeData;
  int? _navigationIndex;

  CustomThemeData(this._navigationIndex, this._themeData);

  getNavigationIndexData() => _navigationIndex;

  setNavigationIndexData(int navigationIndex) async {
    _navigationIndex = navigationIndex;
    notifyListeners();
  }

  getThemeData() => _themeData;

  setThemeData(ThemeData themeData) async {
    _themeData = themeData;
    notifyListeners();
  }
}

如果您需要对该项目有更好的了解,这里是该项目的 GitHub 链接。此外,您将检查此项目屏幕截图1、2、3

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章