[Flutter]使用主题

时间:2022-06-09
本文章向大家介绍[Flutter]使用主题,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

使用主题可以在App里面共享颜色和字体样式。在Flutter里面有两种方式来使用主题,一种是全局范围的、一种是使用Theme Widget, Theme Widget可以在App的某个部分使用主题。全局的主题其实也就是MaterialAppTheme 做为根widget了。

主题定义好后,就可以在Widgets里面使用了。

创建一个全局主题

MaterialApp 接收一个theme的参数,类型为ThemeData,为App提供统一的颜色和字体。支持的参数可以在这里查看

new MaterialApp(
    title: title,
    theme: new ThemeData(
        brightness: Brightness.dark,
        primaryColor: Colors.lightBlue[800],
    ),
);

创建一个局部主题

如果想为某个页面使用不同于App的风格,可以使用Theme来覆盖App的主题.

new Theme(
    data: new ThemeData(
        accentColor: Colors.yellow,
    ),
    child: new Text('Hello World'),
);

扩展App的主题

如果你不想覆盖所有的样式,可以继承App的主题,只覆盖部分样式,使用copyWith方法。

new Theme(
    data: Theme.of(context).copyWith(accentColor: Colors.yellow),
    child: new Text('use copyWith method'),
);

使用主题

创建好主题后,要如何使用呢,在Widget的构造方法里面通过Theme.of(context)方法来调用。

Theme.of(context) 会查找Widget 树,并返回最近的一个Theme对象。如果父层级上有Theme对象,则返回这个Theme,如果没有,就返回App的Theme

new Container(
    color: Theme.of(context).accentColor,
    chile: new Text(
        'Text with a background color',
        style: Theme.of(context).textTheme.title,
    ),
);

完整例子代码

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appName = 'Custom Themes';

    return new MaterialApp(
      title: appName,
      theme: new ThemeData(
        brightness: Brightness.dark,
        primaryColor: Colors.lightBlue[800],
        accentColor: Colors.cyan[600],
      ),
      home: new MyHomePage(
        title: appName,
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String title;

  MyHomePage({Key key, @required this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(title),
      ),
      body: new Center(
        child: new Container(
          color: Theme.of(context).accentColor,
          child: new Text(
            'Text with a background color',
            style: Theme.of(context).textTheme.title,
          ),
        ),
      ),
      floatingActionButton: new Theme(
        data: Theme.of(context).copyWith(accentColor: Colors.yellow),
        child: new FloatingActionButton(
          onPressed: null,
          child: new Icon(Icons.add),
        ),
      ),
    );
  }
}

关于学习

flutter的学习文章都整理在这个github仓库