Flutter学习笔记(三)-- 事件交互和State管理

先来看看准备界面:
image.png

目标是修改图中红色实线框中的喜欢和不喜欢的五角星的修改,以及数字的修改。
在修改之前,有必要先了解一些相关的信息。

知识点

前面简单的提到过,有些Widget是Statful(有状态的),而其他的一些是Stateless(无状态的)。比如继承自StatefulWidget的有Checkbox、Radio、Slider、Form等,这些Widget用户都是可以做一些交互的,同样的继承自StatelessWidget的Widget有Text、Icon等。有状态和无状态的主要区别在于:有状态的Widget在其内部都有一个state用来标记是否发生了变化,然后调用setState()方法来更新自己。

创建Stateful Widget

关键点:
1、创建一个Stateful Widget需要两个类,分别继承自StateFulWidget和State
2、state对象包含了widget的state和widget的build()方法
3、当widget的state改变了的时候,state对象会调用setState()方法,告诉框架去重绘widget。

到这里,其实也可以明白,只有Stateful的Widget才能修改其内容,所以要想实现上面的目标,必须将原来的Icon和Text这两个Stateless的Widget替换成Stateful类型的Widget。
所以我们必须实现两个Stateful类型的Widget,没个Widget都应该包含下面两个点:

  • 一个StatefulWidget的子类,并且实现了createState()方法;
  • 一个State的子类,并且实现了build()方法。
如果足够留意,会发现主函数里就是一个StatefulWidget。

代码

搞清楚了上面的,然后结合官方文档,基础的架子如下:

class FavoriteWidget extends StatefulWidget { @override State<StatefulWidget> createState() => new _FavoriteWidgetState(); } class _FavoriteWidgetState extends State { @override Widget build(BuildContext context) { // TODO: implement build return null; } } 

完整的代码如下所示:

class FavoriteWidget extends StatefulWidget { @override State<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; }); } @override Widget 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"), ), ) ], ); } } 
注意:为什么上面的Text要用SizedBox包裹起来呢?如果不写width可以吗?(主要是为了解决跳动的问题)

最后,拿这个widget去替换原来代码的相应位置的内容。

上面说到的对state的管理是交给了FavoriteWidget,即当前Widget去管理,而实际情况中,对state的管理可以有很多种办法,接下来会慢慢学习!

状态管理

最通用的有三种方式:
1、Widget自己管理State
2、父类管理State
3、混合管理
那么如何确定使用哪种管理方式呢,这里有两个建议:
1、如果是和用户数据相关的,建议用父类来管理
2、如果是为了审美,比如动画,建议Widget自己管理

1、自己管理State

这种方式比较直接,也比较好理解,因为都是在自己的环境下处理,所以直接贴出代码:

class _TapboxA extends StatefulWidget { @override State<StatefulWidget> createState() => new _TapboxAState(); } class _TapboxAState extends State<_TapboxA> { var _active = false; _handleTap() { setState(() { _active = !_active; }); } @override Widget build(BuildContext context) { // TODO: implement build return new GestureDetector( onTap: _handleTap, child: new Container( width: 200.0, height: 200.0, color: _active ? Colors.lightGreen[700] : Colors.grey[600], // decoration: new BoxDecoration( // color: _active ? Colors.lightGreen[700] : Colors.grey[600] // ), child: new Center( child: new Text( _active ? 'Active' : 'Inactive', style: new TextStyle(fontSize: 32.0, color: Colors.white), ), ), ), ); } } 

2、父控件控制State

该控制的核心在于:回调。父控件通过传递参数控制子控件的展示,子控件通过函数的回调,改变父控件的值,然后父控件调用setState()方法再反馈到具体的子控件的展示上。
具体的代码如下:

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); } @override Widget build(BuildContext context) { // TODO: implement build return 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 { @override State<StatefulWidget> createState() { // TODO: implement createState return new _ParentWidgetState(); } } class _ParentWidgetState extends State<ParentWidget> { var _active = false; _handleTapboxChanged(bool newValue) { setState(() { _active = newValue; }); } @override Widget build(BuildContext context) { // TODO: implement build return new Container( child: new _TapBoxB( active: _active, // 传值 onChanged: _handleTapboxChanged, // 回调,用于触发回调 ), ); } } 

3、混合管理

通俗讲,就是上面两种的柔和,父控件控制一些自己需要的State,子控件控制一些自己的State。
代码如下:

class _ParentWidget extends StatefulWidget { bool active = false; @override State<StatefulWidget> createState() => new _ParentWidgetState(); } class _ParentWidgetState extends State<_ParentWidget> { void _handleTapboxChanged(bool newValue) { setState(() { widget.active = newValue; }); } @override Widget build(BuildContext context) { // TODO: implement build return new Container( child: new TapboxC(onChanged: _handleTapboxChanged, active: widget.active), ); } } class TapboxC extends StatefulWidget { final bool _active; bool _highlight = false; final ValueChanged<bool> onChanged; TapboxC({Key key, bool active, @required this.onChanged}) :this._active = active, super(key: key) { } @override State<StatefulWidget> createState() => new _TapboxCState(); } class _TapboxCState extends State<TapboxC> { void _handleTap() { widget.onChanged(!widget._active); } void _handleTapDown(TapDownDetails details) { setState((){ widget._highlight = true; }); } void _handleTapUp(TapUpDetails details) { setState((){ widget._highlight = false; }); } void _handleTapCancel(){ setState((){ widget._highlight = false; }); } @override Widget build(BuildContext context) { // TODO: implement build return new GestureDetector( onTap: _handleTap, onTapDown: _handleTapDown, onTapUp: _handleTapUp, onTapCancel: _handleTapCancel, child: new Container( width: 200.0, height: 200.0, decoration: new BoxDecoration( color: widget._active ? Colors.lightGreen[700] : Colors.grey[600], border: widget._highlight ? new Border.all(color: Colors.teal[700], width: 10.0) : null, ), ), ); } } 

这里与官方的代码相比,我把所有的和state相关的都放到了Widget类里。(但是,其实这么写是有问题的,可以自己想想,将在下一节分析)

至此,Flutter里的State的管理和事件交互也做了简单的了解了,对于我来说,还是不甚了解。重要的还在于多看多写。

猜你喜欢

转载自www.cnblogs.com/Free-Thinker/p/10528947.html