使用主題可以在App里面共享顏色和字體樣式。在Flutter里面有兩種方式來使用主題,一種是全局范圍的、一種是使用Theme Widget, Theme Widget可以在App的某個(gè)部分使用主題。全局的主題其實(shí)也就是MaterialApp將 Theme 做為根widget了。
主題定義好后,就可以在Widgets里面使用了。
創(chuàng)建一個(gè)全局主題
MaterialApp 接收一個(gè)theme的參數(shù),類型為ThemeData,為App提供統(tǒng)一的顏色和字體。支持的參數(shù)可以在這里查看
new MaterialApp(
title: title,
theme: new ThemeData(
brightness: Brightness.dark,
primaryColor: Colors.lightBlue[800],
),
);
創(chuàng)建一個(gè)局部主題
如果想為某個(gè)頁面使用不同于App的風(fēng)格,可以使用Theme來覆蓋App的主題.
new Theme(
data: new ThemeData(
accentColor: Colors.yellow,
),
child: new Text('Hello World'),
);
擴(kuò)展App的主題
如果你不想覆蓋所有的樣式,可以繼承App的主題,只覆蓋部分樣式,使用copyWith方法。
new Theme(
data: Theme.of(context).copyWith(accentColor: Colors.yellow),
child: new Text('use copyWith method'),
);
使用主題
創(chuàng)建好主題后,要如何使用呢,在Widget的構(gòu)造方法里面通過Theme.of(context)方法來調(diào)用。
Theme.of(context) 會(huì)查找Widget 樹,并返回最近的一個(gè)Theme對象。如果父層級上有Theme對象,則返回這個(gè)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),
),
),
);
}
}
關(guān)于學(xué)習(xí)
flutter的學(xué)習(xí)文章都整理在這個(gè)github倉庫里