Flutter教程- Async(三) FutureBuilder组件案例详解


发文时间:2022年04月14日 16:56:32     编辑:Aaron      标签:Flutter异步(Async) 图文详解系列 1031


深入介绍FutureBuilder组件,主要用于跟踪future的变化并自动重绘。每次重绘时,AsyncSnapshot会描述future的最新动态等等。

Flutter FutureBuilder组件案例

import 'dart:async';

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Aaron FutureBuilder Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Aaron FutureBuilder Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  int _counter = 0;
  void _incrementCounter() async {
    setState(() {
      this._counter++;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: FutureBuilder(
          future: Future.delayed(Duration(seconds: 2), () => Future.value('我要在过2秒才显示哦')),
          initialData: 1111,//snapshot.data的初始值  - 用了和这个可以不用去判断waiting
          // future: Future.delayed(Duration(seconds: 2), () => throw '模拟数据获取发生错误'),
          //context 代表这上下文  snapshot储存着当前Future的状态
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            //TODO  一、 较为繁琐的写法 (便于新手理解)
            //数据还在加载中
            if(snapshot.connectionState == ConnectionState.waiting){
              return  CircularProgressIndicator();//显示一个转圈圈的动画效果
            }
            //数据加载完毕
            if(snapshot.connectionState == ConnectionState.done){
              //可能存在获取数据出错的场景
              if(snapshot.hasError){
                return Text('${snapshot.error}');
              }
              return Text('${snapshot.data}');
            }

            //当前 future:value 无值
            if(snapshot.connectionState == ConnectionState.none){
              return Text('当前Future无值');
            }

            //对于FutureBuilder而言一定要有一个默认的return的值
            return Text('不会不存在值!!'); // throw '不会不存在值!!';

            /*
                //TODO 二、简写
              //直接判断有无错误 有的话直接显示- 通过源码可知在flutter中data的值在完成时值或错误信息不会为空
              if(snapshot.hasError){
                return Text('${snapshot.error}');
              }

              if(snapshot.hasData){
                return Text('${snapshot.data}');
              }
              //默认显示转圈圈的效果
              return  CircularProgressIndicator();//显示一个转圈圈的动画效果
             */
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class TestBox extends StatefulWidget {
  final Color color;
  TestBox(this.color, {Key key}) : super(key: key);

  @override
  _TestBoxState createState() => _TestBoxState();
}

class _TestBoxState extends State {
  int count = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
        width: 150,
        height: 150,
        color: widget.color,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('$count', style: TextStyle(color: Colors.white)),
            IconButton(
              onPressed: () {
                setState(() {
                  print('当前值发生改变 ${count}');
                  count++;
                });
              },
              icon: Icon(Icons.add),
            )
          ],
        ));
  }
}

image.png

 

若无特殊说明,此文章为博主原创。
写稿不易,如需转载,请注明出处: https://www.aaroner.cn/art/53.html




SITE MAP

  FOLLOW US