概述
StatefulWidget是Flutter中View与Model交互的基本方式。
首先,在Flutter的UI中一切皆为Widget。有些Widget是静态的视图,一旦初始化就不会再改变。而有些Widget需要根据服务端下发的数据,根据用户的行为做出改动。这类Widget就叫作StatefulWidget。
这里需要强调的一点是:并不是只有StatefulWidget可以动态改变样式,准确地说是:只有StatefulWidge可以发起样式改变的事件。
基本使用
先看一个简单的例子:
class FavoriteWidget extends StatefulWidget {@overrideState<StatefulWidget> createState() => new _FavoriteWidgetState();}class _FavoriteWidgetState extends State {var _isFavorited = true; // 是否喜欢var _favoriteCount = 41; // 喜欢个数_toggleFavorite() {setState((){if(_isFavorited) {_favoriteCount -= 1;} else {_favoriteCount += 1;}_isFavorited = !_isFavorited;});}@overrideWidget build(BuildContext context) {return new Row(mainAxisAlignment: MainAxisAlignment.center,mainAxisSize: MainAxisSize.min,children: <Widget>[new Container(padding: const EdgeInsets.all(0.0),margin: const EdgeInsets.all(0.0),child: new IconButton(icon: (_isFavorited ? new Icon(Icons.star) : new Icon(Icons.star_border)), onPressed: _toggleFavorite, color: Colors.red),),new SizedBox(width: 18.0,child: new Container(child: new Text("$_favoriteCount"),),)],);}}
我们可以看到,一个StatefulWidget通常有一个State与之配合。当我们继承一个StatefulWidget,我们需要实现createState方法,来产生一个State。而State则需要实现build方法,来产生一个Widget。此时产生的Widget,才是真正的会动态变化的Widget。
从上面的例子中,我们可以看到,_FavoriteWidgetState在build Widget时,IconButton会根据_isFavorited选择icon。
同时,State包含方法setState,当我们调用它时,State就会重新build Widget。通过这样的方式,达到界面动态刷新的目的。
在上面的例子中,IconButton在onPressed时,会调用_toggleFavorite。
_toggleFavorite() {setState((){if(_isFavorited) {_favoriteCount -= 1;} else {_favoriteCount += 1;}_isFavorited = !_isFavorited;});}
_toggleFavorite会调用setState,并改变_isFavorited的值。当setState被调用时,State就会再调用一次build方法,重新渲染之前生成的Widget。
再看一个相对复杂的例子:
class _TapBoxB extends StatelessWidget { // 此时子控件是Stateless的// var active = false;final active;final ValueChanged<bool> onChanged;_TapBoxB({Key key, this.active: false, @required this.onChanged}): super(key: key);void _handleTap() {onChanged(!active);}@overrideWidget build(BuildContext context) {// TODO: implement buildreturn new GestureDetector(onTap: _handleTap,child: new Container(child: new Center(child: new Text(active ? 'Active' : 'Inactive',style: new TextStyle(fontSize: 32.0, color: Colors.white),),),width: 200.0,height: 200.0,decoration: new BoxDecoration(color: active ? Colors.lightGreen[700] : Colors.grey[600]),),);}}class ParentWidget extends StatefulWidget {@overrideState<StatefulWidget> createState() {// TODO: implement createStatereturn new _ParentWidgetState();}}class _ParentWidgetState extends State<ParentWidget> {var _active = false;_handleTapboxChanged(bool newValue) {setState(() {_active = newValue;});}@overrideWidget build(BuildContext context) {// TODO: implement buildreturn new Container(child: new _TapBoxB(active: _active, // 传值onChanged: _handleTapboxChanged, // 回调,用于触发回调),);}}
其实这里唯一有所不同的是,State的build方法,产生了一个_TapBoxB。_TapBoxB将_active和_handleTapboxChanged作为参数传入。然后在内部调用_handleTapboxChanged
_handleTapboxChanged(bool newValue) {setState(() {_active = newValue;});}
_handleTapboxChanged再调用setState去重新build Widget。
我们再看_TapBoxB的代码会发现:
class _TapBoxB extends StatelessWidget { // 此时子控件是Stateless的// var active = false;final active;final ValueChanged<bool> onChanged;_TapBoxB({Key key, this.active: false, @required this.onChanged}): super(key: key);void _handleTap() {onChanged(!active);}@overrideWidget build(BuildContext context) {// TODO: implement buildreturn new GestureDetector(onTap: _handleTap,child: new Container(child: new Center(child: new Text(active ? 'Active' : 'Inactive',style: new TextStyle(fontSize: 32.0, color: Colors.white),),),width: 200.0,height: 200.0,decoration: new BoxDecoration(color: active ? Colors.lightGreen[700] : Colors.grey[600]),),);}}
_TapBoxB会在onTap时,调用_handleTap,再调用onChanged(!active)从而调用到父控件的_handleTapboxChanged,通过父控件的setState,重建自己进行动态更新。
这里值得注意的是_TapBoxB其实是一个StatelessWidget。那么它为什么也可以更新呢?
其实StatefulWidget不仅仅会更新自己,还会让子Widget全部重建。所以我们在创建布局时需要慎用StatefulWidget,因为每一次更新state,它都会更新所有子节点。
StatefulWidget的生命周期

总结
StatefulWidget承担了Flutter视图动态更新的功能。在使用中,良好的布局可以极大提升整个布局在重新渲染时的性能。它的更新机制与Android开发很不相同,与React Native非常接近。
如有问题,欢迎指正。
