官方文檔有三句話 記得注意
- 要創(chuàng)建一個自定義有狀態(tài)widget,需創(chuàng)建兩個類:
StatefulWidget和State- 狀態(tài)對象包含
widget的狀態(tài)和build()方法。- 當(dāng)
widget的狀態(tài)改變時,狀態(tài)對象調(diào)用setState(),告訴框架重繪widget
標準寫法
class FavoriteWidget extends StatefulWidget {
@override
_FavoriteWidgetState createState() => new _FavoriteWidgetState();
}
緊跟著state和build 還有setState
class _FavoriteWidgetState extends State<FavoriteWidget> {
bool _isFavorited = true;
int _favoriteCount = 41;
void _toggleFavorite() {
setState(() {
// If the lake is currently favorited, unfavorite it.
if (_isFavorited) {
_favoriteCount -= 1;
_isFavorited = false;
// Otherwise, favorite it.
} else {
_favoriteCount += 1;
_isFavorited = true;
}
});
}
@override
Widget build(BuildContext context) {
return new Row(
mainAxisSize: MainAxisSize.min,
children: [
new Container(
padding: new EdgeInsets.all(0.0),
child: new IconButton(
icon: (_isFavorited
? new Icon(Icons.star)
: new Icon(Icons.star_border)),
color: Colors.red[500],
onPressed: _toggleFavorite,
),
),
new SizedBox(
width: 18.0,
child: new Container(
child: new Text('$_favoriteCount'),
),
),
],
);
}
}
注意:有時候我們看到
setState()的方法 ,不要認為是錯了 ,因為內(nèi)部調(diào)用了子類的setState(),外部沒有顯示而已 。