基于系统明暗模式的动态主题变化

Dynamic Theme Change Based On System's Dark & Light Mode

我一直在研究 flutter 中的动态黑暗和光明模式功能。

当我从系统设置更改移动系统的 dark/light 模式时,我想将应用程序的主题更改为深色主题或浅色主题。

但是,我无法根据移动系统的浅色或深色模式更改应用程序的深色或浅色模式。

我正在使用以下代码。

main.dart

    import 'package:flutter/material.dart';
    import 'package:flutterrookieapp/provider/ThemeProvider.dart';
    import 'package:flutterrookieapp/utils/AppTheme.dart';
    import 'package:provider/provider.dart';

    void main() => runApp(MyApp());

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MultiProvider(
          providers: [
            ChangeNotifierProvider(
              create: (context) => ThemeProvider(
                  MediaQuery.of(context).platformBrightness == Brightness.dark
                      ? darkTheme
                      : lightTheme),
            )
          ],
          child: Consumer<ThemeProvider>(
            builder: (temp, theme, _) {
              return MaterialApp(
                debugShowCheckedModeBanner: false,
                title: 'Flutter Sample',
                theme: MediaQuery.platformBrightnessOf(context) == Brightness.dark
                    ? darkTheme
                    : lightTheme,
                home: HomePage(),
              );
            },
          ),
        );
      }
    }
  }

ThemeProvider.dart

import 'package:flutter/material.dart';

class ThemeProvider with ChangeNotifier {
  ThemeData _themeData;

  ThemeProvider(this._themeData);

  ThemeData getTheme() => _themeData;

  setTheme(ThemeData themeData) async {
    this._themeData = themeData;
    notifyListeners();
  }
}

您可以在 MaterialApp 中使用 darkThemetheme 它总是来自移动系统设置

MaterialApp(
  debugShowCheckedModeBanner: false,
  title: 'Flutter Sample',
  darkTheme: darkTheme,
  theme: lightTheme,
  home: HomePage(),
),