Sil*_*iry 5 dart flutter flutter-layout
所以我在这里尝试获取当前主题,无论是浅色还是深色。所以我可以相应地改变小部件颜色..但是,它不起作用,我使用 if 语句来知道它何时是深色模式..但它总是 False ..这是代码..顺便说一句,它在深色和浅色主题之间切换。 ..但是当我尝试获取当前主题..即使主题更改为黑暗.. if 语句总是显示错误...
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
bool darkModeOn = MediaQuery.of(context).platformBrightness == Brightness.dark;
Color containerColor;
if (darkModeOn == true) {
containerColor = Colors.blueGrey;
print("----------------");
print("dark mode ON");
print("----------------");
} else {
containerColor = Colors.deepPurple;
print("LIGHT mode ON");
}
return Scaffold(
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
//----switch theme---
currentTheme.switchTheme();
},
label: Text(
"Switch theme",
style: TextStyle(
),
),
icon: Icon(Icons.color_lens_outlined),
),
appBar: AppBar(
title: Text("DarkXLight"),
),
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(child: Container(
color: containerColor,
),
),
Expanded(child: Container(
color: Colors.amber,
),
),
],
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
你不能像这样切换主题。MaterialApp您将需要处理否则的逻辑
MediaQuery.of(context).platformBrightness == Brightness.dark;
Run Code Online (Sandbox Code Playgroud)
将始终根据提供给 的内容返回true/ 。falseMaterialApp.themeMode
这是一个入门示例代码。我用过ValueListenableBuilder,但你也可以使用provider。
完整代码:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final ValueNotifier<ThemeMode> _notifier = ValueNotifier(ThemeMode.light);
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<ThemeMode>(
valueListenable: _notifier,
builder: (_, mode, __) {
return MaterialApp(
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: mode, // Decides which theme to show, light or dark.
home: Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () => _notifier.value = mode == ThemeMode.light ? ThemeMode.dark : ThemeMode.light,
child: Text('Toggle Theme'),
),
),
),
);
},
);
}
}
Run Code Online (Sandbox Code Playgroud)
你可以在 initState 中使用它
bool darkModeOn = brightness == Brightness.dark;
or
var brightness = MediaQuery.of(context).platformBrightness;
bool darkModeOn = brightness == Brightness.dark;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23947 次 |
| 最近记录: |