Flutter 入门 - 状态管理

Dart4Flutter – 01 – 变量、类型和函数

Dart4Flutter – 02 –控制流 和异常

Dart4Flutter – 03 – 类和泛型

Dart4Flutter – 04 – 异步和库

Dart4Flutter – 拾遗01 – flutter-dart环境搭建

Dart4Flutter – 不可变性

Flutter入门 – 状态管理

Flutter 入门实例1

Flutter 入门 – Container 属性详解

Flutter 入门-本地访问-MethodChannel

Flutter 实例 – 加载更多的ListView

Flutter 实例 – 从本地到Flutter通信 – Event Channels

flutter是一个新的跨平台框架,使用Dart语言开发。转移到新的平台,其中有一个问题:状态管理。

  • 怎样将状态沿着组件向下传递
  • 状态改变,怎么样刷新UI
  • 怎样在不同界面跳转以及状态同步

开始

因为我们要演示在不同的界面跳转,所以现在我们创建两个文件MyHomePage.dartMySecondPage.dart .

我们例子具体如下:

  • 在MyHomePage增加counter的值
  • 跳转到MySecondPage。
  • 在MySecondPage界面减少counter的值。

看起来似乎很简单,但是我们要找到一个方法,可以使counter在两个界面之间同步。

假设现在counter=0;当我们在MyHomePage将counter增加到2,然后跳转到MySecondPage界面,显示的counter也必须是2.

同时,假设我们在MySecondPage界面递减两次counter,这时当用户跳转到MyHomePage,counter也应该是0。

这就是状态管理。

假设您已经知道setState()机制,用来更新UI的机制。现在我们看看具体怎么做。

main.dart 如下:

import 'package:flutter/material.dart';
import 'package:flutter_redux_example/screens/MyHomePage.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
  
  @override
  _MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
  int counter;
  @override
  void initState() {
    super.initState();
    counter = counter ?? 0;
  }
  void _decrementCounter(_) {
    setState(() {
      counter--;
      print('decrement: $counter');
    });
  }
  
  void _incrementCounter(_) {
    setState(() {
      counter++;
      print('increment: $counter');
    });
  }
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(
        title: 'My Home Page',
        counter: counter,
        decrementCounter: _decrementCounter,
        incrementCounter: _incrementCounter,
      ),
    );
  }
}
复制代码

如上所示, _decrementCounter() 和 _incrementCounter()分别是递增和递减counter的方法,我们将他们当做MyHomePage的构造函数。

MyHomePage.dart 如下:

import 'package:flutter/material.dart';
import 'package:flutter_redux_example/screens/MySecondPage.dart';
class MyHomePage extends StatefulWidget {
  MyHomePage({
    Key key,
    this.title,
    this.counter,
    this.decrementCounter,
    this.incrementCounter
  }) : super(key: key);
  final String title;
  final int counter;
  final ValueChanged<void> decrementCounter;
  final ValueChanged<void> incrementCounter;
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  void _onPressed() {
    widget.incrementCounter(null);
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text('You have pushed the button this many times:'),
            new Text(
              widget.counter.toString(),
              style: Theme.of(context).textTheme.display1,
            ),
            new RaisedButton(
              child: new Text('Next Screen'),
              onPressed: () {
                Navigator.push(
                  context,
                  new MaterialPageRoute(
                    builder: (context) => new MySecondPage(
                      widget.decrementCounter,
                      title: 'My Second Page',
                      counter: widget.counter,
                    ),
                  ),
                );
              },
            )
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _onPressed,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ),
    );
  }
}
复制代码

如上所示,我们将decrementCounter()作为MySecondPage构造函数的参数,向下传递。

MySecondPage.dart 文件如下所示:

import 'package:flutter/material.dart';

class MySecondPage extends StatefulWidget {
  MySecondPage(
    this.decrementCounter, 
    {Key key, this.title, this.counter}
  ): super(key: key);
  final String title;
  final int counter;
  final ValueChanged<void> decrementCounter;
  @override
  _MySecondPageState createState() => new _MySecondPageState();
}
class _MySecondPageState extends State<MySecondPage> {
  void onPressed() {
    widget.decrementCounter(null);
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text('You have pushed the button this many times :'),
            new Text(
              super.widget.counter.toString(),
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
    floatingActionButton: new FloatingActionButton(
      onPressed: onPressed,
      tooltip: 'Decrement',
      child: new Icon(Icons.indeterminate_check_box),
      backgroundColor: Colors.red),
    );
  }
}
复制代码

总结

如果您了解react,上面的内容比较容易理解。

flutter中的StatefulWidgetStatelessWidget对应react中的ComponentPureComponent。flutter中称为Widget的,react称为Component

参考

    原文作者:weixin_33729196
    原文地址: https://blog.csdn.net/weixin_33729196/article/details/88008435
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞