根据系统的明暗模式,动态改变主题。

问题描述 投票:0回答:1

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

我想在系统设置中改变移动系统的暗光模式时,将应用程序的主题改为暗主题或亮主题。

但是,我无法根据移动系统的明暗模式来改变应用程序的暗或亮模式。

我使用的是下面的代码。

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();
  }
}
flutter flutter-layout flutter-provider flutter-theme
1个回答
1
投票

你可以用在 MaterialAppdarkThemetheme它总是从手机系统设置

MaterialApp(
  debugShowCheckedModeBanner: false,
  title: 'Flutter Sample',
  darkTheme: darkTheme,
  theme: lightTheme,
  home: HomePage(),
),
© www.soinside.com 2019 - 2024. All rights reserved.