• Flutter_05_FutureBuilder和StreamBuilder


    FutureBuilder代码笔记

    import 'package:flutter/material.dart';
    
    class User {
      String name;
      int age;
    
      User({this.name = 'lzh', this.age = 28});
    
      @override
      String toString() {
        return name;
      }
    }
    
    class FutureBuildWidget extends StatefulWidget {
      const FutureBuildWidget({Key? key}) : super(key: key);
    
      @override
      _FutureBuildWidgetState createState() => _FutureBuildWidgetState();
    }
    
    class _FutureBuildWidgetState extends State<FutureBuildWidget> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(),
          // 设置子组件统一的文本样式
          body: DefaultTextStyle(
            style: TextStyle(fontSize: 40, color: Colors.blue),
            child: Center(
              child: FutureBuilder(
                  // 设置一个初始值
                  // initialData: 100,
                  // 模拟一个2秒的耗时操作
                  future: Future<User>.delayed(
                    Duration(seconds: 2),
                    () => User(),
                  ),
                  builder: (BuildContext context, AsyncSnapshot<User> snapshot) {
                    if (snapshot.hasError) {
                      return Text('${snapshot.error}');
                    }
                    // 1、判断Future的状态是否完成
                    if (snapshot.hasData) {
                      return Text(
                          '${snapshot.data?.name} ${snapshot.data?.age}'); // 2、获取Future返回的数据
                    }
                    // 设置了初始值,就不会走loading了
                    return CircularProgressIndicator();
                  }),
            ),
          ),
        );
      }
    }
    
    

    StreamBuilder代码笔记

    import 'dart:async';
    import 'dart:math';
    
    import 'package:flutter/material.dart';
    
    class StreamBuildWidget extends StatefulWidget {
      @override
      _StreamBuildWidgetState createState() => _StreamBuildWidgetState();
    }
    
    class _StreamBuildWidgetState extends State<StreamBuildWidget> {
      // 创建一个数据流
      final StreamController _streamController = StreamController.broadcast();
    
      // 创建一个Stream数据流
      Stream<DateTime> getDateTimeStream() async* {
        while (true) {
          await Future.delayed(Duration(seconds: 1));
          // 类似Python的yield
          yield DateTime.now();
        }
      }
    
      @override
      void initState() {
        super.initState();
        // 多方监听需要设置为广播数据流
        _streamController.stream.listen((event) {
          print(event);
        });
      }
    
      @override
      void dispose() {
        super.dispose();
        // 页面销毁时,关闭数据流
        _streamController.close();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(),
          floatingActionButton: FloatingActionButton(
            child: Icon(Icons.refresh),
            // 往数据流中放数据
            onPressed: () => _streamController.sink.add(Random().nextInt(2)),
          ),
          body: Center(
              child: Container(
            child: StreamBuilder(
              // 监听自己创建的数据流
              stream: _streamController.stream
                  .where((event) => event is int) // 筛选事件
                  .map((event) => event * 2) // 对事件进行封装
                  .distinct(), // 事件去重
              // 事件没变的时候,build不会重新绘制
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                print('build widget...');
                switch (snapshot.connectionState) {
                  case ConnectionState.none:
                    return Text('none');
                  case ConnectionState.waiting:
                    return Text('waiting');
                  case ConnectionState.active:
                    // 初始有数据的时候的逻辑
                    if (snapshot.hasError) {
                      return Text('${snapshot.error}');
                    } else {
                      return Text('${snapshot.data}');
                    }
                  case ConnectionState.done:
                    return Text('done');
                }
              },
            ),
          )),
        );
      }
    }
    
    
    
  • 相关阅读:
    Linux:CentOS-7配置VMware-15.5与本机IP同网段
    SpringCloud:Zuul路由配置超时问题
    SpringCloud:路由ZUUL的配置详解
    SpringCloud:扩展zuul配置路由访问
    给source insight添加.cc的C++文件后缀识别(转载)
    Linux下共享库嵌套依赖问题 (转载)
    Ubuntu 下编译libjingle-0.6.14 (转载)
    什么是「穷人思维」?
    谁上北大是能力说了算,不该是教育部(转载)
    Installing cmake 2.8.8 or higher on Ubuntu 12.04 (Precise Pangolin) (转载)
  • 原文地址:https://www.cnblogs.com/carp-li/p/15121169.html
Copyright © 2020-2023  润新知