Flutter中StatefulWidget控件状态管理的两种方式

Flutter 有两种状态控件:StatelessWidget、StatefulWidget,对于有可变状态控件的管理,官方文档是写了有3种模式:控件自己管理状态、交给父控件管理状态以及混合管理。我个人初学对于自己管理比较好理解,对于父控件管理理解起来有点困难,所以只能多看多学。这里写一下两种状态管理的方式和代码,加深自己的印象,尤其是父控件管理方式。

项目说明:两种方式实现一个容器盒子,点击的时候切换颜色和显示内容。我将把这两个盒子做到一个页面,虽然最终效果是一样的,但是实现方式不同。

一、控件自身管理自己的状态

/*
TapBoxA 是自身widget管理自己状态
 */
class TapBoxA extends StatefulWidget {
  @override
  _TapBoxAState createState() {
    return new _TapBoxAState();
  }
}
 
class _TapBoxAState extends State<TapBoxA> {
  bool _aActive = false;
 
  void _aActiveChanged() {
    setState(() {
      if (_aActive) {
        _aActive = false;
      } else {
        _aActive = true;
      }
    });
  }
 
  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: _aActiveChanged,
      child: new Center(
        child: new Container(
          alignment: Alignment.center,
          width: 200.0,
          height: 200.0,
          child: new Text(
            _aActive ? 'Active' : 'Inactive',
            style: new TextStyle(fontSize: 50.0, color: Colors.white),
          ),
          decoration: new BoxDecoration(
              color: _aActive ? Colors.green[400] : Colors.grey),
        ),
      ),
    );
  }
}

二、由父控件管理子控件的状态
子控件自身是无状态的控件,但是父控件会在子控件发生变化以后得知这一更新,并进行状态的更新以及控件的重绘。

/*
TapBoxB 是父widget管理子widget状态;
TapBoxB 继承自无状态控件,不管理任何状态
 */
class TapBoxB extends StatelessWidget {
  TapBoxB({Key key, this.bActive: false, this.onChanged}) : super(key: key);
  final bActive;
  final ValueChanged<bool> onChanged;
 
  void _bActiveChanged() {
    onChanged(!bActive);
  }
 
  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: _bActiveChanged,
      child: new Center(
        child: new Container(
          alignment: Alignment.center,
          width: 200.0,
          height: 200.0,
          child: new Text(
            bActive ? 'Active' : 'Inactive',
            style: new TextStyle(fontSize: 50.0, color: Colors.white),
          ),
          decoration: new BoxDecoration(
              color: bActive ? Colors.green[400] : Colors.grey),
        ),
      ),
    );
  }
}
 
/*
ParentWidget类是TapBoxB的父类
他会得知盒子是否被点击从而管理盒子的状态,通过setState更新展示内容
 */
class ParentWidgetB extends StatefulWidget {
  @override
  _ParentWidgetBState createState() {
    return new _ParentWidgetBState();
  }
}
 
class _ParentWidgetBState extends State<ParentWidgetB> {
  bool _bActive = false;
 
  void _handleTapBoxBChanged(bool value) {
    setState(() {
      _bActive = value;
    });
  }
 
  @override
  Widget build(BuildContext context) {
    return new TapBoxB(
      bActive: _bActive,
      onChanged: _handleTapBoxBChanged,
    );
  }
}

最后是代码整合,把上面两个不同方式实现盒子点击状态更改的代码在一个APP里展示出来

import 'package:flutter/material.dart';
 
void main() => runApp(new MyApp());
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'TapBox',
      theme: new ThemeData(primaryColor: Colors.white),
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('TapBox'),
        ),
        body: new Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            new TapBoxA(),
            new ParentWidgetB(),
          ],
        ),
      ),
    );
  }
}

运行后首页显示如下:

《Flutter中StatefulWidget控件状态管理的两种方式》 状态管理实现1.png

点击后效果如下(实现方式不同):

《Flutter中StatefulWidget控件状态管理的两种方式》 Screenshot_20180913-105838.png

    原文作者:走路不穿鞋oO
    原文地址: https://www.jianshu.com/p/767036bd9ecc
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞