Getx flutter when i change theme from light to dark mode and then return to light mode its not returning my custom theme its load old app bar background even theme changes enter image description here

ThemeData lightTheme = ThemeData(
  useMaterial3: true,
  backgroundColor: Colors.white,
  appBarTheme: AppBarTheme(
    elevation: 1000,
    backgroundColor: Colors.white,
  )
);
ThemeData darkTheme = ThemeData.dark().copyWith(primaryColor: Colors.red);

Getx flutter when i change theme from light to dark mode and then return to light mode its not returning my custom theme its load old app bar background even theme changes


class _MyMaterialAppState extends State<MyMaterialApp> {

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      title: appName,
      theme: lightTheme,
      darkTheme: darkTheme,
      translations: Languages(),
      locale: Get.deviceLocale,
      fallbackLocale: const Locale('en', 'US'),
      home: const MyHomePage(),
    );
  }
}

推荐答案

这可能是因为build方法中的GetMaterialApp小部件.因为小部件每次更新时都会调用build方法,这意味着您的定制主题将被覆盖.您可以这样做:

class _MyMaterialAppState extends State<MyMaterialApp> {

  GetxController<ThemeData> _themeController = GetxController(lightTheme);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<GetxController<ThemeData>>(
      init: _themeController,
      builder: (_, theme) {
        return GetMaterialApp(
          debugShowCheckedModeBanner: false,
          title: appName,
          theme: theme.value,
          darkTheme: darkTheme,
          translations: Languages(),
          locale: Get.deviceLocale,
          fallbackLocale: const Locale('en', 'US'),
          home: const MyHomePage(),
        );
      },
    );
  }
}

此代码使用GetBuilder侦听_themeController和更新theme属性的更改. 更改主题的步骤:

_themeController.updateValue(newTheme)

Flutter相关问答推荐

类型flatter doctor get zsh:未找到命令:macO中flatter

如何使用新的Riverpod语法将依赖传递给AsyncNotifier?

Dexing时出错.将Flutter 升级到3.19.0后

自定义ItemBuilderFlutter

有没有可能不在BlocBuilder中重新构建内容?

如何在Flutter 安全存储器中存储对象值?

不要跨同步间隔使用BuildContext

在 Flutter 中滑动关闭 PageView.builder 时出现问题

要禁用按钮上的通知声音,请点击Flutter

Flutter 使用扩展的 TextField 定位小部件

Flutter:如何在 bottomsheet 中创建一个日期 Select 器,如下图所示

Elevated 和 Outlined 按钮之间的动画

如何删除或隐藏覆盖

Flutter 错误:OutletListModel类型的值不能分配给List类型的变量?

使用 Riverpod 和 copyWith 方法更新数据类中列表中变量的值

为什么将 bloc 提供程序放在单独的文件/类中会引发错误?

在 CircleAvatar 中放置芯片

将 onSaved(value) 从自定义 TextFormField 小部件传递给另一个?

Flutter 平台通道将多数据传递给 windows 功能

Textfield 和 MasonryGrid 给出错误(垂直视口的高度没有限制)