我一直在研究 Flutter 中的动态明暗模式功能。
当我从系统设置更改移动系统的暗/亮模式时,我想将应用程序的主题更改为暗主题或亮主题。
但是,我无法根据 Mobile System 的亮模式或暗模式更改应用程序的暗模式或亮模式。
我正在使用以下代码。
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();
}
}