Future.wait() 用于多个 future

2023-11-30

当我的设备没有互联网连接时,我试图捕获错误。我构建了 2 个未来方法,1 个用于导入 json,1 个用于查看数据库。我有一个未来的构建器,它应该在构建网格视图之前等待两个未来完成,但似乎由于连接错误而过早地调用了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完成。

body: FutureBuilder<List<FlashCardList>>(
    future: Future.wait([
        fetchFlashCardList(),
        fetchFlashCardListFromDB(),
    ]),
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Future.wait() 用于多个 future 的相关文章

随机推荐

  • 即使 OkHttp 不是依赖项,OkHttp 连接泄漏日志行也是如此

    当我使用我的应用程序时 我不断在 Logcat 中看到以下日志行 19098 19147
  • 关闭后如何清除dialog/xmlfragment内容? [复制]

    这个问题在这里已经有答案了 我的对话框定义为document onOpenDialog function var oView this getView var oDialog oView byId helloDialog create di
  • 如何通知 GCC 不要使用特定寄存器

    假设我有一个非常大的源代码并打算制作rdx在执行期间完全未使用寄存器 即在生成汇编代码时 我想要的只是通知我的编译器 GCC 它不应该使用rdx at all 注 注册rdx这只是一个例子 我对任何可用的 Intel x86 寄存器都满意
  • 我的类名与 Ruby 的类名冲突

    我的模块中有一个名为 Date 的类 但是当我想使用用 ruby 打包的 Date 类时 它会使用我的 Date 类 module Mymod class ClassA class Date lt Mymod ClassA require
  • 控制CPU利用率

    在运行时如何控制CPU利用率是明智的 轮询CPU负载并插入睡眠 我推荐操作系统功能 Windows 上有用于此目的的性能计数器和 WinAPI 函数 这是一个使用的示例性能计数器 from BCL 团队博客 foreach Process
  • 将 pyqtgraph 绘图嵌入到 QT .ui 中?

    首先 我希望您对我有一些耐心 因为我是此类项目的新手 我也希望不要问愚蠢的问题 话虽这么说 我的主要目标是为树莓派 3 创建一个 UI 它将感应电池和太阳能电池板的电压 电流等 由于我正在研究树莓派并且对Python3有一些了解 所以我决定
  • 从基于文本的表输出中提取列

    qfarm load命令显示我的服务器的负载 输出 PS gt qfarm load Server Name Server Load Load Throttling Load Logon Mode SERVER 01 400 0 Allow
  • Windows 10 上使用 IE 的量角器失败 - 错误代码 199

    我无法让量角器在 Windows 10 上使用 IE 11 它说Unable to create new service InternetExplorerDriverService并且存在代码 199 我尝试过旧的重新安装 升级节点 npm
  • 如何使用 Power Query 有效地密集表中的排名组

    我一直在尝试最简单的方法对具有组或类别的数据对以下数据进行密集排名 我已经问过类似的问题来对数据进行排名 但这是针对分组数据的 我希望对分数列进行排名 如下所示 使得最高的数字占据第一位置 第一 第二大的数字占据第二位 依此类推 如果有平局
  • 如何使用 Swift 1.2 确定 NS_ENUM 是否为未记录的值

    例如 定义了以下 NS Enum typedef NS ENUM NSInteger Type TypeNone 0 TypeA 1 var x 2 if let type Type Type rawValue x Swift 1 2 ex
  • 从服务器向客户端发送浮点数

    我在用TCP IP套接字编程 我有一个浮点值存储在变量中ret val在我的服务器代码中 我想将其发送给正在等待接收它的客户端 我该怎么做 如果您知道客户端和服务器是同一平台等 您可以简单地使用sizeof float 确定缓冲区大小并从浮
  • Project Tango:坐标系之间的转换和合并点云

    我正在尝试转换采样并存储在 XYZij 数据中的点云 根据document 将相机空间中的数据存储到世界坐标系中 以便可以合并它们 我用于 Tango 监听器的帧对有COORDINATE FRAME START OF SERVICE作为基础
  • 循环中 Plotly 中的 add_trace [重复]

    这个问题在这里已经有答案了 我想在循环中绘制多个轨迹 而不覆盖所有以前的轨迹 In 这个帖子从 2015 年开始 提出了在循环中添加跟踪的解决方案 通过设置evaluate TRUE在plot ly或add trace函数中 然而 从 20
  • 如何使用 forge 加密和解密 pdf blob 并将其存储在 localStorage 中?

    我试图加密一个 pdf 文件 Blob 并将其存储在 localStorage 中 并在离线时读取和解密它 我的应用程序是用 AngularJS 编写的 加密是用forge 这是我下载pdf文件的代码 http get url header
  • 无法过滤使用 Angular 2 中的 Http get 访问的 (MatSelect) 中的数据

    我使用带有输入字段和选择的 Angular Material 创建了一个简单的 Angular 应用程序 在我的选择中 我使用 HTTP get 请求访问数据accountdetails json它位于我的资产文件夹中 我已对选择应用了搜索
  • 为什么我无法在手机浏览器中输入网址来查看我的实时网站?

    我使用一个名为实时服务器在 Visual Studio 代码中 当我实时运行时 浏览器会打开 网址为http 127 0 0 1 5500 index html 为什么我无法在手机浏览器上打开此网址来查看手机上的实时站点 有没有办法做到这一
  • Android 中如何检测平板设备?

    我正在尝试将我为智能手机开发的应用程序移植到平板电脑上 并进行少量修改 Android中有API可以检测设备是否是平板电脑吗 我可以通过比较屏幕尺寸来做到这一点 但是检测平板电脑的正确方法是什么 我认为 API 中没有任何特定标志 基于 G
  • 如何在ECS任务定义命令中转义逗号

    我有 docker 镜像和命令 celery A bits payment tracking app app worker l debug Q celery reports concurrency 3 它在 docker 和 docker
  • 在电子中打开pdf文件

    我需要构建一个应用程序 用户可以在应用程序中打开 PDF 文件 即不通过打开新的浏览器窗口 我需要实现一个后退按钮 可能还需要在 PDF 上实现一些覆盖 有谁知道在 Electron 中是否有一个好的方法来做到这一点 如果您对 Chrome
  • Future.wait() 用于多个 future

    当我的设备没有互联网连接时 我试图捕获错误 我构建了 2 个未来方法 1 个用于导入 json 1 个用于查看数据库 我有一个未来的构建器 它应该在构建网格视图之前等待两个未来完成 但似乎由于连接错误而过早地调用了offlineFlashC