gpt4 book ai didi

flutter - 如何在 Flutter 中更改主题?

转载 作者:行者123 更新时间:2023-12-02 18:43:16 24 4
gpt4 key购买 nike

所以我在这里尝试获取当前主题,无论是浅色还是深色。所以我可以相应地更改小部件颜色..但是,它不起作用,我使用 if 语句来知道什么时候是暗模式。但它总是假的..这是代码..顺便说一下,它在深色和浅色主题之间切换..但是当我尝试获取当前主题时..即使主题变为黑暗..if 语句总是显示 false...

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,
),
),
],
),
),
);
}
}

最佳答案

你不能那样切换主题。您将需要处理 MaterialApp 中的逻辑,否则

MediaQuery.of(context).platformBrightness == Brightness.dark;

将始终根据提供给 MaterialApp.themeMode 的内容返回 true/false

这是开始的示例代码。我使用了 ValueListenableBuilder,但您也可以使用 provider

enter image description here


完整代码:

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'),
),
),
),
);
},
);
}
}

关于flutter - 如何在 Flutter 中更改主题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67794181/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com