码迷,mamicode.com
首页 > 其他好文 > 详细

Flutter: FutureBuilder获取异步数据

时间:2019-05-22 16:04:18      阅读:577      评论:0      收藏:0      [点我收藏+]

标签:future   over   listview   lse   ack   block   done   text   mat   

和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获取异步数据

标签:future   over   listview   lse   ack   block   done   text   mat   

原文地址:https://www.cnblogs.com/ajanuw/p/10906061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!