概述

StatefulWidget是Flutter中View与Model交互的基本方式。

首先,在Flutter的UI中一切皆为Widget。有些Widget是静态的视图,一旦初始化就不会再改变。而有些Widget需要根据服务端下发的数据,根据用户的行为做出改动。这类Widget就叫作StatefulWidget。

这里需要强调的一点是:并不是只有StatefulWidget可以动态改变样式,准确地说是:只有StatefulWidge可以发起样式改变的事件。

基本使用

先看一个简单的例子:

  1. class FavoriteWidget extends StatefulWidget {
  2. @override
  3. State<StatefulWidget> createState() => new _FavoriteWidgetState();
  4. }
  5. class _FavoriteWidgetState extends State {
  6. var _isFavorited = true; // 是否喜欢
  7. var _favoriteCount = 41; // 喜欢个数
  8. _toggleFavorite() {
  9. setState((){
  10. if(_isFavorited) {
  11. _favoriteCount -= 1;
  12. } else {
  13. _favoriteCount += 1;
  14. }
  15. _isFavorited = !_isFavorited;
  16. });
  17. }
  18. @override
  19. Widget build(BuildContext context) {
  20. return new Row(
  21. mainAxisAlignment: MainAxisAlignment.center,
  22. mainAxisSize: MainAxisSize.min,
  23. children: <Widget>[
  24. new Container(
  25. padding: const EdgeInsets.all(0.0),
  26. margin: const EdgeInsets.all(0.0),
  27. child: new IconButton(icon: (_isFavorited ? new Icon(Icons.star) : new Icon(Icons.star_border)), onPressed: _toggleFavorite, color: Colors.red),
  28. ),
  29. new SizedBox(
  30. width: 18.0,
  31. child: new Container(
  32. child: new Text("$_favoriteCount"),
  33. ),
  34. )
  35. ],
  36. );
  37. }
  38. }

我们可以看到,一个StatefulWidget通常有一个State与之配合。当我们继承一个StatefulWidget,我们需要实现createState方法,来产生一个State。而State则需要实现build方法,来产生一个Widget。此时产生的Widget,才是真正的会动态变化的Widget。

从上面的例子中,我们可以看到,_FavoriteWidgetState在build Widget时,IconButton会根据_isFavorited选择icon。

同时,State包含方法setState,当我们调用它时,State就会重新build Widget。通过这样的方式,达到界面动态刷新的目的。

在上面的例子中,IconButton在onPressed时,会调用_toggleFavorite。

  1. _toggleFavorite() {
  2. setState((){
  3. if(_isFavorited) {
  4. _favoriteCount -= 1;
  5. } else {
  6. _favoriteCount += 1;
  7. }
  8. _isFavorited = !_isFavorited;
  9. });
  10. }

_toggleFavorite会调用setState,并改变_isFavorited的值。当setState被调用时,State就会再调用一次build方法,重新渲染之前生成的Widget。


再看一个相对复杂的例子:

  1. class _TapBoxB extends StatelessWidget { // 此时子控件是Stateless的
  2. // var active = false;
  3. final active;
  4. final ValueChanged<bool> onChanged;
  5. _TapBoxB({Key key, this.active: false, @required this.onChanged})
  6. : super(key: key);
  7. void _handleTap() {
  8. onChanged(!active);
  9. }
  10. @override
  11. Widget build(BuildContext context) {
  12. // TODO: implement build
  13. return new GestureDetector(
  14. onTap: _handleTap,
  15. child: new Container(
  16. child: new Center(
  17. child: new Text(
  18. active ? 'Active' : 'Inactive',
  19. style: new TextStyle(fontSize: 32.0, color: Colors.white),
  20. ),
  21. ),
  22. width: 200.0,
  23. height: 200.0,
  24. decoration: new BoxDecoration(
  25. color: active ? Colors.lightGreen[700] : Colors.grey[600]),
  26. ),
  27. );
  28. }
  29. }
  30. class ParentWidget extends StatefulWidget {
  31. @override
  32. State<StatefulWidget> createState() {
  33. // TODO: implement createState
  34. return new _ParentWidgetState();
  35. }
  36. }
  37. class _ParentWidgetState extends State<ParentWidget> {
  38. var _active = false;
  39. _handleTapboxChanged(bool newValue) {
  40. setState(() {
  41. _active = newValue;
  42. });
  43. }
  44. @override
  45. Widget build(BuildContext context) {
  46. // TODO: implement build
  47. return new Container(
  48. child: new _TapBoxB(
  49. active: _active, // 传值
  50. onChanged: _handleTapboxChanged, // 回调,用于触发回调
  51. ),
  52. );
  53. }
  54. }

其实这里唯一有所不同的是,State的build方法,产生了一个_TapBoxB。_TapBoxB将_active和_handleTapboxChanged作为参数传入。然后在内部调用_handleTapboxChanged

  1. _handleTapboxChanged(bool newValue) {
  2. setState(() {
  3. _active = newValue;
  4. });
  5. }

_handleTapboxChanged再调用setState去重新build Widget。

我们再看_TapBoxB的代码会发现:

  1. class _TapBoxB extends StatelessWidget { // 此时子控件是Stateless的
  2. // var active = false;
  3. final active;
  4. final ValueChanged<bool> onChanged;
  5. _TapBoxB({Key key, this.active: false, @required this.onChanged})
  6. : super(key: key);
  7. void _handleTap() {
  8. onChanged(!active);
  9. }
  10. @override
  11. Widget build(BuildContext context) {
  12. // TODO: implement build
  13. return new GestureDetector(
  14. onTap: _handleTap,
  15. child: new Container(
  16. child: new Center(
  17. child: new Text(
  18. active ? 'Active' : 'Inactive',
  19. style: new TextStyle(fontSize: 32.0, color: Colors.white),
  20. ),
  21. ),
  22. width: 200.0,
  23. height: 200.0,
  24. decoration: new BoxDecoration(
  25. color: active ? Colors.lightGreen[700] : Colors.grey[600]),
  26. ),
  27. );
  28. }
  29. }

_TapBoxB会在onTap时,调用_handleTap,再调用onChanged(!active)从而调用到父控件的_handleTapboxChanged,通过父控件的setState,重建自己进行动态更新。

这里值得注意的是_TapBoxB其实是一个StatelessWidget。那么它为什么也可以更新呢?

其实StatefulWidget不仅仅会更新自己,还会让子Widget全部重建。所以我们在创建布局时需要慎用StatefulWidget,因为每一次更新state,它都会更新所有子节点。

StatefulWidget的生命周期

Flutter-StatefulWidget - 图1

总结

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

如有问题,欢迎指正。