Theme
主题即在我们的应用程序中共享颜色和字体样式,比如导航栏颜色、标题字体、Icon样式等
实现
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: ThemeTestRoute(),
);
}
}
class ThemeTestRoute extends StatefulWidget {
_ThemeTestRouteState createState() => new _ThemeTestRouteState();
}
class _ThemeTestRouteState extends State<ThemeTestRoute> {
Color _themeColor = Colors.teal; //当前路由主题色
Widget build(BuildContext context) {
ThemeData themeData = Theme.of(context);
return Theme(
data: ThemeData(
primarySwatch: _themeColor, //用于导航栏、FloatingActionButton的背景色等
iconTheme: IconThemeData(color: _themeColor) //用于Icon颜色
),
child: Scaffold(
appBar: AppBar(title: Text("主题测试")),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
//第一行Icon使用主题中的iconTheme
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.favorite),
Icon(Icons.airport_shuttle),
Text(" 颜色跟随主题")
]
),
//为第二行Icon自定义颜色(固定为黑色)
Theme(
data: themeData.copyWith(
iconTheme: themeData.iconTheme.copyWith(
color: Colors.black
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.favorite),
Icon(Icons.airport_shuttle),
Text(" 颜色固定黑色")
]
),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () => //切换主题
setState(() =>
_themeColor =
_themeColor == Colors.teal ? Colors.blue : Colors.teal
),
child: Icon(Icons.palette)
),
),
);
}
}
切换效果:
summary
学习效率愈加下降,看来还是需要从官方文档啃着走,推荐一个官方中文Flutter网站:
https://flutter-io.cn/ 上面有许多中文学习资源:
当然中文文档(https://flutter-io.cn/docs)目前的开发几乎没有开始,只是翻译了个目录,所以中文文档还是可以看Flutter中文网:https://flutterchina.club/docs/