在我的应用程序中,在应用程序栏中,有一个按钮可以将主题更改为深色。我需要创建功能提供者。如何实施?我只需要将支架颜色更改为黑色,将文本颜色更改为白色。我的 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(),
);
}Run Code Online (Sandbox Code Playgroud)
我的开关按钮:
appBar: AppBar(
title: const Text('Flutter theme config'),
centerTitle: true,
actions: [
IconButton(
onPressed: () {
},
icon: const Icon(Icons.dark_mode),
)
],
),Run Code Online (Sandbox Code Playgroud)
主题提供者:
class ThemeProvider extends ChangeNotifier {
}Run Code Online (Sandbox Code Playgroud)
你可以尝试这样的事情:
首先,我们为整个应用程序全局提供我们的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
);
}
}
Run Code Online (Sandbox Code Playgroud)
在提供程序中,我们只有两个函数,一个用于切换到LightMode,另一个用于切换到DarkMode,然后我们将其添加到currentTheme变量中,该变量是在main中侦听的变量
** 主题提供者 **
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();
}
}
Run Code Online (Sandbox Code Playgroud)
最后我们创建一个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),
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2515 次 |
| 最近记录: |