'如果你想根据你的系统模式在你的应用程序中使用暗/亮模式,假设终端设备支持-MaterialApp有一个theme属性,它代表' System light theme' 其中darkTheme 属性代表'系统暗模式'。我创建了一个名为 AppTheme 的类,我在其中初始化了 2 个 static final ThemeData 对象:
class AppTheme {
static final ThemeData lightTeme = ThemeData(
//Theme light
brightness: Brightness.light,
primaryColor: Colors.white,
accentColor: Colors.black,
inputDecorationTheme: InputDecorationTheme(
labelStyle: TextStyle(color: Colors.black),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(color: Colors.black)),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(color: Colors.black))),
buttonTheme: ButtonThemeData(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: BorderSide(color: Colors.black)),
),
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity);
static final ThemeData darkTheme = ThemeData(
brightness: Brightness.dark,
primaryColor: Colors.black,
accentColor: Colors.white,
inputDecorationTheme: InputDecorationTheme(
labelStyle: TextStyle(color: Colors.white),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(color: Colors.white)),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(color: Colors.white))),
buttonTheme: ButtonThemeData(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: BorderSide(color: Colors.white)),
),
//Button Theme Light
visualDensity: VisualDensity.adaptivePlatformDensity);
}
您可以在 MaterialApp 小部件中访问它们:
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate
],
supportedLocales: S.delegate.supportedLocales,
theme: AppTheme.lightTeme,
darkTheme: AppTheme.darkTheme,
home: HomeworkDiaryApp(),
);
}
您不必担心您的应用程序处理更改。一旦您更改系统暗模式,它会自动执行(在我的真实设备上测试三星 Galaxy s8 就像一个魅力)
我认为,当人们今天最常使用的所有手机都具有系统暗模式或亮模式时,实施“仅在应用中的暗模式和亮模式”是自相矛盾的!