Flutter: FutureBuilder获取异步数据

Posted ajanuw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter: FutureBuilder获取异步数据相关的知识,希望对你有一定的参考价值。

和WEB前端的Apollo差不多

import 'package:flutter/material.dart';

void main() => runApp(Myapp());

class Myapp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: MyHome());
  }
}

class MyHome extends StatefulWidget {
  @override
  _MyHomeState createState() => _MyHomeState();
}

class _MyHomeState extends State<MyHome> {
  Future<String> _getData() async {
    await Future.delayed(Duration(seconds: 2));
    // return '异步数据';
    return Future.error('测试错误');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ListView'),
      ),
      body: ListView(
        children: <Widget>[
          FutureBuilder(
            future: _getData(),
            builder: (BuildContext context, AsyncSnapshot<String> s) {
              switch (s.connectionState) {
                case ConnectionState.none:
                  return Text('1. 当前未连接到任何异步计算');
                  break;
                case ConnectionState.waiting:
                  // 连接到异步计算并等待交互
                  return Text('2. 加载中。。。');
                  break;
                case ConnectionState.active:
                  return Text('3. 连接到活动的异步计算');
                  break;
                case ConnectionState.active:
                  return Text('4. 连接到终止的异步计算');
                  break;
                case ConnectionState.done:
                  if (s.hasError) {
                    return Text('Error: ${s.error}');
                  } else {
                    return Text(s.data);
                  }
                  break;
                default:
              }
            },
          ),
        ],
      ),
    );
  }
}

以上是关于Flutter: FutureBuilder获取异步数据的主要内容,如果未能解决你的问题,请参考以下文章

Flutter:防止抽屉在 FutureBuilder 内滑动时始终刷新

Flutter:FutureBuilder 中的异步调用

如何创建一个 Flutter Futurebuilder 函数来显示从 JSON 中获取的字符串数组?

Flutter Futurebuilder 快照为空

Flutter - 提取到 FutureBuilder 的 JSON 反序列化数据返回空值

Flutter Futurebuilder 被修改