FutureBuilder

作者: imuzi | 来源:发表于2019-01-11 13:43 被阅读11次

    Flutter和Dart是异步的,使用Dart的Futures可以管理IO,不用担心线程死锁等问题,但是如何在使用Widget时也使用异步操作呢?
    Flutter提供了FutureBuilder来进行处理,FutureBuilder可以很容易的得到当前Widget的状态,并选择在加载数据时显示的内容.以及在可以使用时显示的内容.

    在这里插入图片描述

    首先给FutureBuilder设置future一个网络请求,,builder可以获取到当前的操作是那种状态,比如已完成.根据不同的状态来显示不同的内容.

    import 'package:flutter/material.dart';
    import 'dart:io';
    
    class GoogleFutureBuilder extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        var httpClient = new HttpClient();
        Widget waiting = Column(
          children: <Widget>[
            Text('waiting'),
            Icon(Icons.cloud_download),
          ],
        );
        Widget active = Column(
          children: <Widget>[
            Text('active'),
            Icon(Icons.access_time),
          ],
        );
        Widget error = Column(
          children: <Widget>[
            Text('error'),
            Icon(Icons.error),
          ],
        );
        Widget done = Column(
          children: <Widget>[
            Text('done'),
            Icon(Icons.done),
          ],
        );
        Widget none = Column(
          children: <Widget>[
            Text('none'),
            Icon(Icons.filter_none),
          ],
        );
        return FutureBuilder(
          future: httpClient.getUrl(Uri.parse('http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9')),
          builder: (context, snap) {
            if (snap.connectionState == ConnectionState.done) {
              if (snap.hasError) {
                return error;
              }
              return done;
            } else if (snap.connectionState == ConnectionState.active) {
              return active;
            } else if (snap.connectionState == ConnectionState.waiting) {
              return waiting;
            } else if (snap.connectionState == ConnectionState.none) {
              return none;
            }
          },
        );
      }
    }
    

    我的博客
    代码github

    相关文章

      网友评论

        本文标题:FutureBuilder

        本文链接:https://www.haomeiwen.com/subject/dtlxdqtx.html