我一直在研究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();
}
}
你可以用在 MaterialApp
的 darkTheme
或 theme
它总是从手机系统设置
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Sample',
darkTheme: darkTheme,
theme: lightTheme,
home: HomePage(),
),