ThemeMode 是 Flutter 提供的一个枚举类,用于控制应用程序的主题模式。它定义了三种模式:
ThemeMode.system:根据系统的设置选择浅色或深色主题。
ThemeMode.light:总是使用浅色主题。
ThemeMode.dark:总是使用深色主题。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// 默认使用系统主题模式
ThemeMode _themeMode = ThemeMode.system;
Widget build(BuildContext context) {
return MaterialApp(
title: 'ThemeMode Example',
theme: ThemeData.light(), // 浅色主题
darkTheme: ThemeData.dark(), // 深色主题
themeMode: _themeMode, // 当前主题模式
home: Scaffold(
appBar: AppBar(title: Text('ThemeMode Example')),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
'Select Theme Mode:',
style: TextStyle(fontSize: 20),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
setState(() {
_themeMode = ThemeMode.light;
});
},
child: Text('Light Mode'),
),
ElevatedButton(
onPressed: () {
setState(() {
_themeMode = ThemeMode.dark;
});
},
child: Text('Dark Mode'),
),
ElevatedButton(
onPressed: () {
setState(() {
_themeMode = ThemeMode.system;
});
},
child: Text('System Mode'),
),
],
),
),
);
}
}
效果 :
------------------------我是分割线--------------------------