前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[Flutter]使用主题

[Flutter]使用主题

作者头像
吴老师
发布2018-09-05 11:00:45
1.1K0
发布2018-09-05 11:00:45
举报

使用主题可以在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仓库

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.05.02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 创建一个全局主题
  • 创建一个局部主题
  • 扩展App的主题
  • 使用主题
  • 完整例子代码
  • 关于学习
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档