flutter问题深入研究(11):StatefulWidget
2019-10-23 本文已影响0人
super_chao
官方文档有三句话 记得注意
- 要创建一个自定义有状态widget,需创建两个类:
StatefulWidget
和State
- 状态对象包含
widget
的状态和build()
方法。- 当
widget
的状态改变时,状态对象调用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()
的方法 ,不要认为是错了 ,因为内部调用了子类的setState()
,外部没有显示而已 。