gpt4 book ai didi

flutter - 如何在单击 IconButton 时将主题更改为深色?

转载 作者:行者123 更新时间:2023-12-02 01:36:48 37 4
gpt4 key购买 nike

在我的应用程序中,在 appBar 中,有一个按钮可以将主题更改为深色。我需要创建功能提供者。如何实现?我只需要将脚手架颜色更改为黑色,将文本颜色更改为白色。我的 main.dart:

Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
textTheme: const TextTheme(
headline1: TextStyle(fontSize: 50.0, fontWeight: FontWeight.bold),
headline5: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
subtitle2: TextStyle(fontSize: 10.0, color: Colors.black),
bodyText1: TextStyle(fontSize: 14.0, color: Colors.black),
),
),
home: const HomeScreen(),
);
}

我的开关按钮:

appBar: AppBar(
title: const Text('Flutter theme config'),
centerTitle: true,
actions: [
IconButton(
onPressed: () {

},
icon: const Icon(Icons.dark_mode),
)
],
),

主题提供者:

class ThemeProvider extends ChangeNotifier {

}

最佳答案

你可以尝试这样的事情:

首先,我们为整个应用程序全局提供我们的 Provider,然后在属性 theme 中:我们监听变化。

** 主要 **

void main() async {
runApp(
MultiProvider( // create the provider
providers: [
ChangeNotifierProvider(
create: (_) => ThemeProvider(),
)
],
child: const MyApp(),
),
);
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Material App',
initialRoute: HomeScreen.routerName,
routes: {
},
theme: Provider.of<ThemeProvider>(context).currentTheme, // listen to the current theme
);
}
}

在provider中我们只会有两个功能,一个切换到LightMode,另一个切换到DarkMode,然后我们把它添加到currentTheme 变量,它是在 ma​​in

中监听的变量

** 主题提供者 **

class ThemeProvider extends ChangeNotifier {
ThemeData? currentTheme;

setLightMode() {
currentTheme = ThemeData(
brightness: Brightness.light, // LightMode
scaffoldBackgroundColor: Colors.red,
[...] // more attributes
);
notifyListeners();
}

setDarkmode() {
currentTheme = ThemeData(
brightness: Brightness.dark, // DarkMode
scaffoldBackgroundColor: Colors.green,
[...] // more attributes
);
notifyListeners();
}
}

最后我们创建一个StatefulWidget来改变isDarkMode变量来调用provider

** 按钮主页 **

class _HomeScreenState extends State<SettingsScreen> {
bool isDarkmode = false; // new variable

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Settings"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: IconButton(
onPressed: () {
final themeProvider =
Provider.of<ThemeProvider>(context, listen: false); // get the provider, listen false is necessary cause is in a function

setState(() {
isDarkmode = !isDarkmode;
}); // change the variable

isDarkmode // call the functions
? themeProvider.setDarkmode()
: themeProvider.setLightMode();
},
icon: const Icon(Icons.dark_mode),
),
),
);
}
}

关于flutter - 如何在单击 IconButton 时将主题更改为深色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72259040/

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