flutter改变主题颜色

阳光穿透心脏的1/2处 2021-09-19 07:42 761阅读 0赞
  1. /****
  2. *
  3. * 改变主题颜色
  4. *
  5. *
  6. */
  7. import 'package:flutter/material.dart';
  8. void main()=>runApp(MyApp());
  9. class MyApp extends StatelessWidget {
  10. @override
  11. Widget build(BuildContext context){
  12. return MaterialApp(
  13. title: 'Flutter Demo',
  14. theme: ThemeData(
  15. primarySwatch: Colors.blue,
  16. ),
  17. home:ThemeTestRoute(),
  18. );
  19. }
  20. }
  21. class ThemeTestRoute extends StatefulWidget{
  22. @override
  23. _ThemeTestRouteState createState()=>new _ThemeTestRouteState();
  24. }
  25. class _ThemeTestRouteState extends State<ThemeTestRoute>{
  26. Color _themeColor = Colors.teal;//当前主题颜色
  27. @override
  28. Widget build(BuildContext context) {
  29. ThemeData themeData = Theme.of(context);
  30. return Theme(
  31. data:ThemeData(
  32. primarySwatch: _themeColor,//用于导航栏。floatingActionButton
  33. iconTheme: IconThemeData(color: _themeColor)//用于icon颜色
  34. ),
  35. child: Scaffold(
  36. appBar: AppBar(title:Text('主题变色')),
  37. body: Column(
  38. mainAxisAlignment: MainAxisAlignment.center,
  39. children: <Widget>[
  40. //第一行Icon使用主题中的iconTheme
  41. Row(
  42. mainAxisAlignment: MainAxisAlignment.center,
  43. children: <Widget>[
  44. Icon(Icons.favorite),
  45. Text(" 颜色跟随主题")
  46. ]
  47. ),
  48. //为第二行Icon自定义颜色(固定为黑色)
  49. Theme(
  50. data: themeData.copyWith(
  51. iconTheme: themeData.iconTheme.copyWith(
  52. color: Colors.black
  53. ),
  54. ),
  55. child: Row(
  56. mainAxisAlignment: MainAxisAlignment.center,
  57. children: <Widget>[
  58. Icon(Icons.favorite),
  59. Text(" 颜色固定黑色")
  60. ]
  61. ),
  62. ),
  63. ],
  64. ),
  65. floatingActionButton: FloatingActionButton(
  66. onPressed: ()=>//主题切换
  67. setState(()=>
  68. _themeColor = _themeColor ==Colors.teal? Colors.blue:Colors.teal
  69. ),
  70. child: Icon(Icons.palette),
  71. ),
  72. ),
  73. );
  74. }
  75. }

发表评论

表情:
评论列表 (有 0 条评论,761人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Flutter 切换主题

    在flutter中,ThemeData 来统一管理主题的配置信息。 ThemeData 涵盖了 Material Design 规范的可自定义部分样式,比如应用明暗模式 br