dart - Future.wait() 用于多个 future

标签 dart flutter future

我试图在我的设备没有互联网连接时捕获错误。我已经构建了 2 个 future 的方法,1 个用于导入 json,1 个用于查看数据库。我有一个 future builder ,假设在构建 GridView 之前等待两个 future 完成,但由于连接错误,offlineFlashCardList 似乎被过早调用。知道如何让它在调用快照错误之前等待两个 future 完成吗?

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:baby_sound/strings.dart';
import 'package:baby_sound/objects/flashCardList.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'dart:async' show Future;
import 'dart:convert';
import 'package:baby_sound/database/database.dart';
import 'package:baby_sound/objects/network.dart';
import 'package:http/http.dart' as http;

class GridViewWidget extends StatefulWidget{
  @override
  createState() => new GridViewState();

}

class GridViewState extends State<GridViewWidget>{


  List<FlashCardList> flashCardList;
  List<FlashCardList> offlineFlashCardList;



  Future<List<FlashCardList>> fetchFlashCardList() async{
    debugPrint("before response");
    List<FlashCardList> tempFlashCardList;
    final response = await http.get('some json url');
    //checkConnection(url).then((response){
      debugPrint ("after database load, response code: ${response.statusCode}");
      if (response.statusCode == 200) {
        var data = json.decode(response.body);
        var flashCardListData = data["FlashCardList"] as List;
        tempFlashCardList = flashCardListData.map<FlashCardList>((json) => FlashCardList.fromJson(json)).toList();
        for (int i = 0; i < tempFlashCardList.length; i++){
          debugPrint("DBProvider listID: ${await DBProvider.db.getFlashCardList(tempFlashCardList[i].flashCardListID)}, flashCardID: ${tempFlashCardList[i].flashCardListID}");
          if (await DBProvider.db.getFlashCardList(tempFlashCardList[i].flashCardListID) == null){
            DBProvider.db.newFlashCardList(tempFlashCardList[i]);
            debugPrint("Adding ${tempFlashCardList[i].name}}}");
          } else {
            DBProvider.db.updateFlashCardList(tempFlashCardList[i]);
            debugPrint("Updating ${tempFlashCardList[i].name}, getFlashCardList: ${DBProvider.db.getFlashCardList(tempFlashCardList[i].flashCardListID)}");
          }
        }
        flashCardList = tempFlashCardList;
        debugPrint("Standard flashCardList Size: ${flashCardList.length}");
      }

    debugPrint("flashCardList Size Before Return: ${flashCardList.length}");
    return flashCardList;
    }

  Future<List<FlashCardList>> fetchFlashCardListFromDB() async{

    offlineFlashCardList = await DBProvider.db.getAllFlashCardListFromDB();
    debugPrint("fetchFromDB size: ${offlineFlashCardList.length}");
    return offlineFlashCardList;
  }



  @override
  void initState(){
    debugPrint ('debug main.dart');
    super.initState();

  }


  @override
  Widget build(BuildContext context){
    return new Scaffold(
      appBar: new AppBar(
        centerTitle: true,
        title: new Text(Strings.pageTitle),
      ),
      body: FutureBuilder<List<FlashCardList>>(
        future: new Future(() async{
          await fetchFlashCardList();
          await fetchFlashCardListFromDB();
        }),
        builder: (BuildContext context, AsyncSnapshot<List<FlashCardList>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              debugPrint("Snapshot has error: ${snapshot.error}");
              return new GridView.builder(
                  gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                      maxCrossAxisExtent: 200.0,
                      childAspectRatio: 0.5),
                  itemCount: offlineFlashCardList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return _getGridItemUI(context, offlineFlashCardList[index]);
                  });
//              return new Center(child: new CircularProgressIndicator());
            } else {
              debugPrint("Grid ViewBuilder");
              return new GridView.builder(
                  gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                      maxCrossAxisExtent: 200.0,
                      childAspectRatio:0.5),
                  itemCount: flashCardList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return _getGridItemUI(context, flashCardList[index]);
                  });
            }
          }else {
            debugPrint("CircularProgress");
            return new Center(child: new CircularProgressIndicator());
          }
        })
    );
  }

  _getGridItemUI(BuildContext context, FlashCardList item){
    return new InkWell(
      onTap: () {
        _showSnackBar(context, item);
      },
      child: new Card(
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[

              new Image(image: new CachedNetworkImageProvider("https://babymozart.org/babymozartq92C9TLa9UMkulL2m81xHdn9u2R92e1e/image/" + item.image)),
              /*new Expanded(
                child:new Center(
                  child: new Column(
                    children: <Widget>[
                      new SizedBox(height: 8.0),
                      new Expanded(
                        child: AutoSizeText(
                          item.name, maxLines: 1,
                        )
                      )
                    ],
                  ),
                )
              )*/
            ],
        ),
        elevation: 2.0,
        margin: EdgeInsets.all(5.0),
      )
    );
  }

  _showSnackBar(BuildContext context, FlashCardList item){

  }



}

最佳答案

您可以使用 Future.wait等待几个 Future 完成。

body: FutureBuilder<List<FlashCardList>>(
    future: Future.wait([
        fetchFlashCardList(),
        fetchFlashCardListFromDB(),
    ]),

关于dart - Future.wait() 用于多个 future ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54465359/

相关文章:

windows - 如何构建 Windows 应用程序的发布版本?

scala - 从 Future[ List[ A ] ] 获取 head Future 的首选方式

dart - CheckboxListTile 在使用来自 firebase 的实时数据库时不起作用

flutter - Navigator.of(context).pop();使整个屏幕消失,而不是弹出窗口

flutter - 使用Flutter从Firebase Firestore查询中获取单个文档

firebase - 没有为类查询定义 “get”方法

regex - 尝试在Flutter中验证RegEx

flutter - Flutter中Element和RenderObject有什么区别?

c++ - 无法调用 future::get 存储在 map 中的 future

python - `DummyExecutor` 用于 Python 's ` future `