Flutter Widget采用現代響應式框架構建,這是從 React 中獲得的靈感,中心思想是用widget構建你的UI。 Widget描述了他們的視圖在給定其當前配置和狀態(tài)時應該看起來像什么。當widget的狀態(tài)發(fā)生變化時,widget會重新構建UI,Flutter會對比前后變化的不同, 以確定底層渲染樹從一個狀態(tài)轉換到下一個狀態(tài)所需的最小更改(譯者語:類似于React/Vue中虛擬DOM的diff算法)。
注意: 如果您想通過代碼來深入了解Flutter,請查看 構建Flutter布局 和 為Flutter App添加交互功能。
一個最簡單的Flutter應用程序,只需一個widget即可!如下面示例:將一個widget傳給runApp函數即可:
import 'package:flutter/material.dart';
void main() {
runApp(
new Center(
child: new Text(
'Hello, world!',
textDirection: TextDirection.ltr,
),
),
);
}
該runApp函數接受給定的Widget并使其成為widget樹的根。 在此示例中,widget樹由兩個widget:Center(及其子widget)和Text組成??蚣軓娭聘鵺idget覆蓋整個屏幕,這意味著文本“Hello, world”會居中顯示在屏幕上。文本顯示的方向需要在Text實例中指定,當使用MaterialApp時,文本的方向將自動設定,稍后將進行演示。
在編寫應用程序時,通常會創(chuàng)建新的widget,這些widget是無狀態(tài)的StatelessWidget或者是有狀態(tài)的StatefulWidget, 具體的選擇取決于您的widget是否需要管理一些狀態(tài)。widget的主要工作是實現一個build函數,用以構建自身。一個widget通常由一些較低級別widget組成。Flutter框架將依次構建這些widget,直到構建到最底層的子widget時,這些最低層的widget通常為RenderObject,它會計算并描述widget的幾何形狀。
主要文章: widget概述-布局模型
Flutter有一套豐富、強大的基礎widget,其中以下是很常用的:
以下是一些簡單的Widget,它們可以組合出其它的Widget:
import 'package:flutter/material.dart';
class MyAppBar extends StatelessWidget {
MyAppBar({this.title});
// Widget子類中的字段往往都會定義為"final"
final Widget title;
@override
Widget build(BuildContext context) {
return new Container(
height: 56.0, // 單位是邏輯上的像素(并非真實的像素,類似于瀏覽器中的像素)
padding: const EdgeInsets.symmetric(horizontal: 8.0),
decoration: new BoxDecoration(color: Colors.blue[500]),
// Row 是水平方向的線性布局(linear layout)
child: new Row(
//列表項的類型是 <Widget>
children: <Widget>[
new IconButton(
icon: new Icon(Icons.menu),
tooltip: 'Navigation menu',
onPressed: null, // null 會禁用 button
),
// Expanded expands its child to fill the available space.
new Expanded(
child: title,
),
new IconButton(
icon: new Icon(Icons.search),
tooltip: 'Search',
onPressed: null,
),
],
),
);
}
}
class MyScaffold extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Material 是UI呈現的“一張紙”
return new Material(
// Column is 垂直方向的線性布局.
child: new Column(
children: <Widget>[
new MyAppBar(
title: new Text(
'Example title',
style: Theme.of(context).primaryTextTheme.title,
),
),
new Expanded(
child: new Center(
child: new Text('Hello, world!'),
),
),
],
),
);
}
}
void main() {
runApp(new MaterialApp(
title: 'My app', // used by the OS task switcher
home: new MyScaffold(),
));
}
請確保在pubspec.yaml文件中,將flutter的值設置為:uses-material-design: true。這允許我們可以使用一組預定義Material icons。
name: my_app
flutter:
uses-material-design: true
為了繼承主題數據,widget需要位于MaterialApp內才能正常顯示, 因此我們使用MaterialApp來運行該應用。
在MyAppBar中創(chuàng)建一個Container,高度為56像素(像素單位獨立于設備,為邏輯像素),其左側和右側均有8像素的填充。在容器內部, MyAppBar使用Row 布局來排列其子項。 中間的title widget被標記為Expanded, ,這意味著它會填充尚未被其他子項占用的的剩余可用空間。Expanded可以擁有多個children, 然后使用flex參數來確定他們占用剩余空間的比例。
MyScaffold 通過一個Column widget,在垂直方向排列其子項。在Column的頂部,放置了一個MyAppBar實例,將一個Text widget作為其標題傳遞給應用程序欄。將widget作為參數傳遞給其他widget是一種強大的技術,可以讓您創(chuàng)建各種復雜的widget。最后,MyScaffold使用了一個Expanded來填充剩余的空間,正中間包含一條message。
主要文章: Widgets 總覽 - Material 組件
Flutter提供了許多widgets,可幫助您構建遵循Material Design的應用程序。Material應用程序以MaterialApp widget開始, 該widget在應用程序的根部創(chuàng)建了一些有用的widget,其中包括一個Navigator, 它管理由字符串標識的Widget棧(即頁面路由棧)。Navigator可以讓您的應用程序在頁面之間的平滑的過渡。 是否使用MaterialApp完全是可選的,但是使用它是一個很好的做法。
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
title: 'Flutter Tutorial',
home: new TutorialHome(),
));
}
class TutorialHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
//Scaffold是Material中主要的布局組件.
return new Scaffold(
appBar: new AppBar(
leading: new IconButton(
icon: new Icon(Icons.menu),
tooltip: 'Navigation menu',
onPressed: null,
),
title: new Text('Example title'),
actions: <Widget>[
new IconButton(
icon: new Icon(Icons.search),
tooltip: 'Search',
onPressed: null,
),
],
),
//body占屏幕的大部分
body: new Center(
child: new Text('Hello, world!'),
),
floatingActionButton: new FloatingActionButton(
tooltip: 'Add', // used by assistive technologies
child: new Icon(Icons.add),
onPressed: null,
),
);
}
}
現在我們已經從MyAppBar和MyScaffold切換到了AppBar和 Scaffold widget, 我們的應用程序現在看起來已經有一些“Material”了!例如,應用欄有一個陰影,標題文本會自動繼承正確的樣式。我們還添加了一個浮動操作按鈕,以便進行相應的操作處理。
請注意,我們再次將widget作為參數傳遞給其他widget。該 Scaffold widget 需要許多不同的widget的作為命名參數,其中的每一個被放置在Scaffold布局中相應的位置。 同樣,AppBar 中,我們給參數leading、actions、title分別傳一個widget。 這種模式在整個框架中會經常出現,這也可能是您在設計自己的widget時會考慮到一點。
主要文章: Flutter中的手勢
大多數應用程序包括某種形式與系統(tǒng)的交互。構建交互式應用程序的第一步是檢測輸入手勢。讓我們通過創(chuàng)建一個簡單的按鈕來了解它的工作原理:
class MyButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new GestureDetector(
onTap: () {
print('MyButton was tapped!');
},
child: new Container(
height: 36.0,
padding: const EdgeInsets.all(8.0),
margin: const EdgeInsets.symmetric(horizontal: 8.0),
decoration: new BoxDecoration(
borderRadius: new BorderRadius.circular(5.0),
color: Colors.lightGreen[500],
),
child: new Center(
child: new Text('Engage'),
),
),
);
}
}
該GestureDetector widget并不具有顯示效果,而是檢測由用戶做出的手勢。 當用戶點擊Container時, GestureDetector會調用它的onTap回調, 在回調中,將消息打印到控制臺。您可以使用GestureDetector來檢測各種輸入手勢,包括點擊、拖動和縮放。
許多widget都會使用一個GestureDetector為其他widget提供可選的回調。 例如,IconButton、 RaisedButton、 和FloatingActionButton ,它們都有一個onPressed回調,它會在用戶點擊該widget時被觸發(fā)。
主要文章: StatefulWidget, State.setState
到目前為止,我們只使用了無狀態(tài)的widget。無狀態(tài)widget從它們的父widget接收參數, 它們被存儲在final型的成員變量中。 當一個widget被要求構建時,它使用這些存儲的值作為參數來構建widget。
為了構建更復雜的體驗 - 例如,以更有趣的方式對用戶輸入做出反應 - 應用程序通常會攜帶一些狀態(tài)。 Flutter使用StatefulWidgets來滿足這種需求。StatefulWidgets是特殊的widget,它知道如何生成State對象,然后用它來保持狀態(tài)。 思考下面這個簡單的例子,其中使用了前面提到RaisedButton:
class Counter extends StatefulWidget {
// This class is the configuration for the state. It holds the
// values (in this nothing) provided by the parent and used by the build
// method of the State. Fields in a Widget subclass are always marked "final".
@override
_CounterState createState() => new _CounterState();
}
class _CounterState extends State<Counter> {
int _counter = 0;
void _increment() {
setState(() {
// This call to setState tells the Flutter framework that
// something has changed in this State, which causes it to rerun
// the build method below so that the display can reflect the
// updated values. If we changed _counter without calling
// setState(), then the build method would not be called again,
// and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance
// as done by the _increment method above.
// The Flutter framework has been optimized to make rerunning
// build methods fast, so that you can just rebuild anything that
// needs updating rather than having to individually change
// instances of widgets.
return new Row(
children: <Widget>[
new RaisedButton(
onPressed: _increment,
child: new Text('Increment'),
),
new Text('Count: $_counter'),
],
);
}
}
您可能想知道為什么StatefulWidget和State是單獨的對象。在Flutter中,這兩種類型的對象具有不同的生命周期: Widget是臨時對象,用于構建當前狀態(tài)下的應用程序,而State對象在多次調用build()之間保持不變,允許它們記住信息(狀態(tài))。
上面的例子接受用戶點擊,并在點擊時使_counter自增,然后直接在其build方法中使用_counter值。在更復雜的應用程序中,widget結構層次的不同部分可能有不同的職責; 例如,一個widget可能呈現一個復雜的用戶界面,其目標是收集特定信息(如日期或位置),而另一個widget可能會使用該信息來更改整體的顯示。
在Flutter中,事件流是“向上”傳遞的,而狀態(tài)流是“向下”傳遞的(譯者語:這類似于React/Vue中父子組件通信的方式:子widget到父widget是通過事件通信,而父到子是通過狀態(tài)),重定向這一流程的共同父元素是State。讓我們看看這個稍微復雜的例子是如何工作的:
class CounterDisplay extends StatelessWidget {
CounterDisplay({this.count});
final int count;
@override
Widget build(BuildContext context) {
return new Text('Count: $count');
}
}
class CounterIncrementor extends StatelessWidget {
CounterIncrementor({this.onPressed});
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return new RaisedButton(
onPressed: onPressed,
child: new Text('Increment'),
);
}
}
class Counter extends StatefulWidget {
@override
_CounterState createState() => new _CounterState();
}
class _CounterState extends State<Counter> {
int _counter = 0;
void _increment() {
setState(() {
++_counter;
});
}
@override
Widget build(BuildContext context) {
return new Row(children: <Widget>[
new CounterIncrementor(onPressed: _increment),
new CounterDisplay(count: _counter),
]);
}
}
注意我們是如何創(chuàng)建了兩個新的無狀態(tài)widget的!我們清晰地分離了 顯示 計數器(CounterDisplay)和 更改 計數器(CounterIncrementor)的邏輯。 盡管最終效果與前一個示例相同,但責任分離允許將復雜性邏輯封裝在各個widget中,同時保持父項的簡單性。
讓我們考慮一個更完整的例子,將上面介紹的概念匯集在一起??。我們假設一個購物應用程序,該應用程序顯示出售的各種產品,并維護一個購物車。 我們先來定義ShoppingListItem:
class Product {
const Product({this.name});
final String name;
}
typedef void CartChangedCallback(Product product, bool inCart);
class ShoppingListItem extends StatelessWidget {
ShoppingListItem({Product product, this.inCart, this.onCartChanged})
: product = product,
super(key: new ObjectKey(product));
final Product product;
final bool inCart;
final CartChangedCallback onCartChanged;
Color _getColor(BuildContext context) {
// The theme depends on the BuildContext because different parts of the tree
// can have different themes. The BuildContext indicates where the build is
// taking place and therefore which theme to use.
return inCart ? Colors.black54 : Theme.of(context).primaryColor;
}
TextStyle _getTextStyle(BuildContext context) {
if (!inCart) return null;
return new TextStyle(
color: Colors.black54,
decoration: TextDecoration.lineThrough,
);
}
@override
Widget build(BuildContext context) {
return new ListTile(
onTap: () {
onCartChanged(product, !inCart);
},
leading: new CircleAvatar(
backgroundColor: _getColor(context),
child: new Text(product.name[0]),
),
title: new Text(product.name, style: _getTextStyle(context)),
);
}
}
該ShoppingListItem widget是無狀態(tài)的。它將其在構造函??數中接收到的值存儲在final成員變量中,然后在build函數中使用它們。 例如,inCart布爾值表示在兩種視覺展示效果之間切換:一個使用當前主題的主色,另一個使用灰色。
當用戶點擊列表項時,widget不會直接修改其inCart的值。相反,widget會調用其父widget給它的onCartChanged回調函數。 此模式可讓您在widget層次結構中存儲更高的狀態(tài),從而使狀態(tài)持續(xù)更長的時間。在極端情況下,存儲傳給runApp應用程序的widget的狀態(tài)將在的整個生命周期中持續(xù)存在。
當父項收到onCartChanged回調時,父項將更新其內部狀態(tài),這將觸發(fā)父項使用新inCart值重建ShoppingListItem新實例。 雖然父項ShoppingListItem在重建時創(chuàng)建了一個新實例,但該操作開銷很小,因為Flutter框架會將新構建的widget與先前構建的widget進行比較,并僅將差異部分應用于底層RenderObject。
我們來看看父widget存儲可變狀態(tài)的示例:
class ShoppingList extends StatefulWidget {
ShoppingList({Key key, this.products}) : super(key: key);
final List<Product> products;
// The framework calls createState the first time a widget appears at a given
// location in the tree. If the parent rebuilds and uses the same type of
// widget (with the same key), the framework will re-use the State object
// instead of creating a new State object.
@override
_ShoppingListState createState() => new _ShoppingListState();
}
class _ShoppingListState extends State<ShoppingList> {
Set<Product> _shoppingCart = new Set<Product>();
void _handleCartChanged(Product product, bool inCart) {
setState(() {
// When user changes what is in the cart, we need to change _shoppingCart
// inside a setState call to trigger a rebuild. The framework then calls
// build, below, which updates the visual appearance of the app.
if (inCart)
_shoppingCart.add(product);
else
_shoppingCart.remove(product);
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Shopping List'),
),
body: new ListView(
padding: new EdgeInsets.symmetric(vertical: 8.0),
children: widget.products.map((Product product) {
return new ShoppingListItem(
product: product,
inCart: _shoppingCart.contains(product),
onCartChanged: _handleCartChanged,
);
}).toList(),
),
);
}
}
void main() {
runApp(new MaterialApp(
title: 'Shopping App',
home: new ShoppingList(
products: <Product>[
new Product(name: 'Eggs'),
new Product(name: 'Flour'),
new Product(name: 'Chocolate chips'),
],
),
));
}
ShoppingList類繼承自StatefulWidget,這意味著這個widget可以存儲狀態(tài)。 當ShoppingList首次插入到樹中時,框架會調用其 createState 函數以創(chuàng)建一個新的_ShoppingListState實例來與該樹中的相應位置關聯(lián)(請注意,我們通常命名State子類時帶一個下劃線,這表示其是私有的)。 當這個widget的父級重建時,父級將創(chuàng)建一個新的ShoppingList實例,但是Flutter框架將重用已經在樹中的_ShoppingListState實例,而不是再次調用createState創(chuàng)建一個新的。
要訪問當前ShoppingList的屬性,_ShoppingListState可以使用它的widget屬性。 如果父級重建并創(chuàng)建一個新的ShoppingList,那么 _ShoppingListState也將用新的widget值重建(譯者語:這里原文檔有錯誤,應該是_ShoppingListState不會重新構建,但其widget的屬性會更新為新構建的widget)。 如果希望在widget屬性更改時收到通知,則可以覆蓋didUpdateWidget函數,以便將舊的oldWidget與當前widget進行比較。
處理onCartChanged回調時,_ShoppingListState通過添加或刪除產品來改變其內部_shoppingCart狀態(tài)。 為了通知框架它改變了它的內部狀態(tài),需要調用setState。調用setState將該widget標記為”dirty”(臟的),并且計劃在下次應用程序需要更新屏幕時重新構建它。 如果在修改widget的內部狀態(tài)后忘記調用setState,框架將不知道您的widget是”dirty”(臟的),并且可能不會調用widget的build方法,這意味著用戶界面可能不會更新以展示新的狀態(tài)。
通過以這種方式管理狀態(tài),您不需要編寫用于創(chuàng)建和更新子widget的單獨代碼。相反,您只需實現可以處理這兩種情況的build函數。
主要文章: State
在StatefulWidget調用createState之后,框架將新的狀態(tài)對象插入樹中,然后調用狀態(tài)對象的initState。 子類化State可以重寫initState,以完成僅需要執(zhí)行一次的工作。 例如,您可以重寫initState以配置動畫或訂閱platform services。initState的實現中需要調用super.initState。
當一個狀態(tài)對象不再需要時,框架調用狀態(tài)對象的dispose。 您可以覆蓋該dispose方法來執(zhí)行清理工作。例如,您可以覆蓋dispose取消定時器或取消訂閱platform services。 dispose典型的實現是直接調用super.dispose。
主要文章: Key_
您可以使用key來控制框架將在widget重建時與哪些其他widget匹配。默認情況下,框架根據它們的runtimeType和它們的顯示順序來匹配。 使用key時,框架要求兩個widget具有相同的key和runtimeType。
Key在構建相同類型widget的多個實例時很有用。例如,ShoppingList構建足夠的ShoppingListItem實例以填充其可見區(qū)域:
主要文章: GlobalKey
您可以使用全局key來唯一標識子widget。全局key在整個widget層次結構中必須是全局唯一的,這與局部key不同,后者只需要在同級中唯一。由于它們是全局唯一的,因此可以使用全局key來檢索與widget關聯(lián)的狀態(tài)。
更多建議: