Flutter StreamBuilder implements partial refresh Widget

Stream is an event stream or pipeline. It is based on the event stream driver design code, then listens for subscription events, and processes responses to event transformations.

Stream is divided into single subscription stream and broadcast stream. Single subscription stream only allows one listener to be set before sending the completion event, and only starts to generate events after setting the listener on the stream. After canceling the listener, it will stop sending events.

The core usage code is:


The Demo effect of this page is as follows

Program entrance

main() {
  runApp(MaterialApp(
    //不显示 debug标签
    debugShowCheckedModeBanner: false,
    //显示的首页面
    home: DemoStreamBuilder(),
  ));
}

DemoStreamBuilder main page


///代码清单
class DemoStreamBuilder extends StatefulWidget {
  @override
  _DemoStreamBuilderState createState() => _DemoStreamBuilderState();
}

class _DemoStreamBuilderState extends State<DemoStreamBuilder> {

  int _count = 0;
  //流Stream 控制器
  StreamController<int> _streamController = StreamController();

  @override
  void dispose() {
    //销毁
    _streamController.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    //
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          _count++;
          //发送消息
          _streamController.add(_count);
        },
      ),
      appBar: AppBar(
        title: Text("StreamBuilder"),
      ),
      body: Container(
        padding: EdgeInsets.all(30),
        child: Column(
          children: [
            //接收消息
            StreamBuilder<int>(
              //初始值
              initialData: _count,
              //绑定Stream
              stream: _streamController.stream,
              builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                return Text("测试使用 ${snapshot.data}");
              },
            ),

            Text("测试使用"),
            Text("测试使用"),
          ],
        ),
      ),
    );
  }
}

Flutter StatefulBuilder is used to implement local data refresh

1 Function Description
is used to realize the function of partial data refresh. The official website description is as follows:

  • A platonic widget that both has state and calls a closure to obtain its child widget.
  • The StateSetter function passed to the builder is used to invoke a rebuild instead of a typical State’s State.setState.
  • Since the builder is re-invoked when the StateSetter is called, any variables that represent state should be kept outside the builder function. outside.

2 Basic use of core code

class DemoStatefulBuilderPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //状态构建器
      body: buildStatefulBuilder(),
    );
  }
}
int _count = 0;
  StatefulBuilder buildStatefulBuilder() {
    return StatefulBuilder(
      //构建状态改变的Widget
      builder: (BuildContext context, void Function(void Function()) setState) {
        //居中
        return Center(
          //手势识别
          child: GestureDetector(
            child: Text("早起的年轻人 $_count"),
            //单击事件
            onTap: () {
              //刷新当前  StatefulBuilder 中的状态
              setState(() {
                _count++;
              });
            },
          ),
        );
      },
    );
  }

Flutter implements partial refresh

When a widget needs to be refreshed, we can do so by calling the widget's setState method. SetState will then call the State's build method to rebuild it.

//请求刷新
  setState((){
    
  });


  #State<T extends StatefulWidget>
  @override
  Widget build(BuildContext context) {
    //构建新的Widget
    return new Text(_text);
  }

Then, if we can expose return new Text(_text) in the build method, we can implement a universal partial refresh Widget.

Implementation plan


1. Interface callback, expose return new Text(_text);:
Implemented with typedef function

//定义函数别名
 typedef BuildWidget = Widget Function();

Pass the function alias BuildWidget as a parameter to the State.build method

Complete code

import 'package:flutter/material.dart';

//封装 通用局部刷新工具类
//定义函数别名
typedef BuildWidget = Widget Function();

class PartRefreshWidget extends StatefulWidget {

  PartRefreshWidget(Key key, this._child): super(key: key);
  BuildWidget _child;

  @override
  State<StatefulWidget> createState() {
    return PartRefreshWidgetState(_child);
  }

}

class PartRefreshWidgetState extends State<PartRefreshWidget> {

  BuildWidget child;

  PartRefreshWidgetState(this.child);

  @override
  Widget build(BuildContext context) {
    return child.call();
  }

  void update() {
    print('update');
    setState(() {

    });
  }
  
}

use:

import 'package:flutter/material.dart';

import 'PartRefreshWidget.dart';

class GlobalKeyDemo extends StatefulWidget {
  @override
  _GlobalKeyDemoState createState() => _GlobalKeyDemoState();
}

class _GlobalKeyDemoState extends State<GlobalKeyDemo> {
  int _count = 0;

  //使用1 创建GlobalKey
  GlobalKey<PartRefreshWidgetState> globalKey = new GlobalKey();

  @override
  Widget build(BuildContext context) {
    print('----------------build');

    return Scaffold(
        appBar: AppBar(
          title: Text("inheritedWidget"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              //使用2 创建通用局部刷新widget
              PartRefreshWidget(globalKey, () {
                ///创建需要局部刷新的widget
                return Text(
                  '变化的:$_count',
                  style: TextStyle(color: Colors.green),
                );
              }),
              Text('不变的: $_count'),
              RaisedButton(
                onPressed: () {
                  //点击
                  _count++;
                  //使用3调用刷新方法
                  globalKey.currentState.update();
                },
              ),
            ],
          ),
        )
    );
  }
}

Results as shown below:

Guess you like

Origin blog.csdn.net/jdsjlzx/article/details/134313601
Recommended