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:
              }
            },
          ),
        ],
      ),
    );
  }
}
    原文作者:Ajanuw
    原文地址: https://www.cnblogs.com/ajanuw/p/10906061.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞