美文网首页Flutter探索之旅
Flutter探索之旅之主题

Flutter探索之旅之主题

作者: 麦子涛 | 来源:发表于2018-06-29 17:17 被阅读145次

主题可以使APP拥有统一的样式,如颜色和字体等,它决定了APP的展示效果。在Flutter中,我们可以定义全局主题或者Widgets局部主题。

全局主题

全局主题就是通过MaterialApp的构造函数,为theme提供ThemeData,使得整个应用有一个统一的主题,从而共享颜色和字体等。

import 'package:flutter/material.dart';
class CustomTheme extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Custom Theme',
      theme: new ThemeData(
        brightness: Brightness.light,
        primaryColor: Colors.lightBlue[800],
        accentColor: Colors.cyan[600],
      ),
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('主题'),
        ),
        body: new Center(
          child: new Text('Hello Flutter'),
        ),
        floatingActionButton: new FloatingActionButton(
          onPressed: (){},
          child: new Icon(Icons.add),
        ),
      ),
    );
  }
}

在上述代码中,通过为MaterialApp的构造函数的theme设置了ThemeData,这就为整个应用设置了一个统一的主题,效果如下:


01.png

局部主题

如果应用中某个Widget不想使用全局样式,而是想自定义样式,我们可以创建一个新的Themed对象,然后将这些样式封装在一个ThemeData中,将ThemeData赋值给Theme对象的data属性,将Widget赋值给Theme对象的Child属性。

  • 自定义ThemeData
       // floatingActionButton: new FloatingActionButton(
       //   onPressed: (){},
       //   child: new Icon(Icons.add),
       // ),
       floatingActionButton: new Theme(
         data: new ThemeData(
           accentColor: Colors.yellow,
         ),
         child: new FloatingActionButton(
             onPressed: (){},
             child: new Icon(Icons.add),
         ),

效果图如下:


02.png

可以看出,自定义的floatingActionButton的样式已经生效。

  • 扩展父主题
    除了上面那种自定义外,我们还可以扩展服主题,如以下代码:
  // floatingActionButton: new Theme(
        //   data: new ThemeData(
        //     accentColor: Colors.yellow,
        //   ),
        //   child: new FloatingActionButton(
        //       onPressed: (){},
        //       child: new Icon(Icons.add),
        //   ),
          floatingActionButton: new Theme(
          data: Theme.of(context).copyWith(accentColor: Colors.yellow)
          child: new FloatingActionButton(
              onPressed: (){},
              child: new Icon(Icons.add),
          ),

Theme.of(context)将查找Widget树并返回树中最近的Theme。如果我们的Widget之上有一个单独的Theme定义,则返回该值。如果不是,则返回App主题。 事实上,FloatingActionButton真是通过这种方式找到accentColor的!
效果跟上图一样。

相关文章

网友评论

    本文标题:Flutter探索之旅之主题

    本文链接:https://www.haomeiwen.com/subject/tauoyftx.html