一、多主题
1.主题(UI风格、样式、皮肤)
- 主题风格可通过theme来定义,从而实现整个APP风格的统一
- 一旦设置了主题,那么应用程序中的某些Widget,就会直接使用主题的样式
2.组件
- ThemeData
- Brightness(Brightness.light|Brightness.dark)
- primaryColor|accentColor
- buttonTheme|cardTheme|iconTheme|textTheme
- Theme(声明局部主题)
- Theme.of(context)获取上下文中的主题信息
二、适配终端
1.声明不同的主题
2.使用主题
- theme:CustomTheme.lightTheme
- darkTheme:CustomTheme.darkTheme
- theme:ThemeData.light()
- darkTheme:ThemeData.dark()
3.查看效果
三、代码
main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: CustomTheme.lightTheme,
darkTheme: CustomTheme.darkTheme,
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("learn1"),
leading: Icon(Icons.menu),
actions: [Icon(Icons.settings)],
elevation: 10.0,
centerTitle: true,
),
body: ThemeDemo(),
);
}
}
class ThemeDemo extends StatelessWidget {
const ThemeDemo({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Text(
'Theme Example',
style: Theme.of(context).textTheme.subtitle1,
),
ElevatedButton(onPressed: () {}, child: Text('按钮')),
Icon(Icons.person),
Icon(Icons.access_alarm),
Icon(
Icons.access_alarm,
color: Theme.of(context).accentColor,
),
Theme(
data: ThemeData(
iconTheme: const IconThemeData(color: Colors.blue, size: 60),
),
child: Icon(Icons.person)),
Card(
child: Column(
children: const [
ListTile(
leading: Icon(
Icons.accessible_forward_sharp,
size: 50,
),
title: Text(
"OTTO",
style: TextStyle(fontSize: 20),
),
subtitle: Text(
"吉吉国王",
style: TextStyle(fontSize: 20),
),
),
Divider(),
ListTile(
title: Text(
"电话:000000000",
style: TextStyle(fontSize: 20),
),
),
ListTile(
title: Text(
"地址:xxxxxxx",
style: TextStyle(fontSize: 20),
),
)
],
),
),
],
),
);
}
}
class CustomTheme {
static const double _CardBorderWidth = 10;
static const double _CardElevation = 20;
static final ThemeData lightTheme = ThemeData(
primaryColor: Colors.red,
cardTheme: CardTheme(
color: Colors.red[100],
shape: Border.all(width: _CardBorderWidth, color: Colors.red),
elevation: _CardElevation));
static final ThemeData darkTheme = ThemeData(
primaryColor: Colors.grey,
cardTheme: CardTheme(
color: Colors.grey[100],
shape: Border.all(width: _CardBorderWidth, color: Colors.black45),
elevation: _CardElevation),
);
}
四、效果