可通过Theme.of获取ThemeData对象。也可以指定主题应用于Theme的后代组件。

相关组件

MaterialApp CupertinoTheme

文字样式-ThemeData#TextTheme

子组件可以通过ThemeData.of获取主题的数据进行使用。
image.png

  1. import 'package:flutter/material.dart';
  2. class TextThemeDemo extends StatelessWidget {
  3. @override
  4. Widget build(BuildContext context) {
  5. var queryData = Theme.of(context).textTheme;
  6. var styles = {
  7. "headline: ": queryData.headline,
  8. "title: ": queryData.title,
  9. "subhead: ": queryData.subhead,
  10. "subtitle: ": queryData.body1,
  11. "body2: ": queryData.body2,
  12. "button: ": queryData.button,
  13. "overline: ": queryData.overline,
  14. "subtitle: ": queryData.subtitle,
  15. "button: ": queryData.caption,
  16. "display1: ": queryData.display1,
  17. "display2: ": queryData.display2,
  18. "display3: ": queryData.display3,
  19. "display4: ": queryData.display4,
  20. };
  21. return Container(
  22. child: Column(
  23. children: styles.keys.map((e) => buildItem(e, styles[e])).toList(),
  24. ),
  25. );
  26. }
  27. Widget buildItem(String e, TextStyle style) => Column(
  28. children: <Widget>[
  29. Padding(
  30. padding: const EdgeInsets.all(8.0),
  31. child: Row(
  32. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  33. children: <Widget>[
  34. Text(
  35. e,
  36. style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
  37. ),
  38. Text(
  39. "@toly",
  40. style: style,
  41. )
  42. ],
  43. ),
  44. ),
  45. Divider(
  46. height: 1,
  47. )
  48. ],
  49. );
  50. }

Theme的用法

使用Theme,可以指定非常多的属性作为主题,这些属性将应用于所有的后代组件,如指定字体、滑块、卡片、文字、分割线、按钮等属性。
image.png

import 'package:flutter/material.dart';
class CustomTheme extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Theme(
        data: ThemeData(
            cardTheme: CardTheme(color: Colors.red, elevation: 4),
            dividerTheme: DividerThemeData(
                color: Colors.blue,
                thickness: 2
            ),
            sliderTheme: SliderThemeData(
              thumbColor: Colors.red,
              activeTrackColor: Colors.green,
              inactiveTrackColor: Colors.grey,
            )),
        child: Wrap(
            crossAxisAlignment: WrapCrossAlignment.center,
            children: <Widget>[
              Card(
                child: Container(
                  width: 50,
                  height: 50,
                  color: Colors.transparent,
                ),
              ),
              Container(
                  width: 150,
                  child: Slider(value: 0.8, onChanged: (v) => {})),
              Container(  width: 150,child: Divider())
            ]));
  }
}