【问题标题】:How to make your code stop executing next line until a function finishes its work in flutter?如何让你的代码停止执行下一行,直到一个函数完成它的工作?
【发布时间】:2021-01-15 23:16:16
【问题描述】:

我有一个云存储,我通过从我的应用程序上传数据来存储数据。而且我还有一个云存储数据库,用于存储这些上传文件的文件名和 url。我面临的问题是我的代码试图在上传数据/文件之前收集 url,因此它崩溃了。所以我希望我的代码停在那里完成任务并转到下一行。我什至在我的代码中使用了 async/await,但它仍然没有帮助。

这是我的代码:-

 Future savingfile(List<int> asset, String name) async {
    StorageReference reference = FirebaseStorage.instance.ref().child(name);
    StorageUploadTask uploadTask = reference.putData(asset);
    String url = await (await uploadTask.onComplete).ref.getDownloadURL();
    //print(url);
    //documentFileUpload(url);
    return url;
 }
 getfilelink(String s) async {
    StorageReference ref = FirebaseStorage.instance.ref().child('$s');
    String url = (await ref.getDownloadURL()).toString();

    return url;
  }
 saveeverything(List filechosen) async {
    for (int i = 0; i < filechosen.length; i++) {
      await savingfile(filechosen[i].readAsBytesSync(), filenames[i]);
    }
  }

void updatedata() async {
    ..... //some more codes are here.

    await saveeverything(filechosen); //i want my code to wait and finish the task over here and go to next line.

    String fileurl = "", filedetails = "";
      if (filenames.length == 0) {
          filedetails = "none";
          fileurl = "none";
        } else {
          for (int i = 0; i < filenames.length; i++) {
            filedetails += filenames[i].toString() + " ";
          }
          for (int i = 0; i < filenames.length; i++) {
            String t =  getfilelink(filenames[i]) + " ";
            fileurl += t;
          }
        }
    
    await notices.add({
      "event": notice,
      "date": date,
      "description": detail,
      "index": ds.docs.length + 1,
      "files": filedetails,
      "url": fileurl
    });
}

这是我的代码,希望你能理解。

这是我得到的错误

E/flutter ( 4499): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: NoSuchMethodError: Class 'Future<dynamic>' has no instance method '+'.
E/flutter ( 4499): Receiver: Instance of 'Future<dynamic>'
E/flutter ( 4499): Tried calling: +(" ")

谢谢!

【问题讨论】:

  • 我没明白你的意思
  • 我没有任何 analysis_options.yaml 文件.. 我找不到它
  • 您的错误来自于:getfilelink(filenames[i]) + " "getfilelinkasync,所以它返回一个Future,在你可以使用+ 之前,它必须是awaited。 (另外,你应该为你的函数声明返回类型。)

标签: firebase flutter dart google-cloud-firestore firebase-storage


【解决方案1】:

您的 updatedata 函数必须是 Future 类型(不确定这是否有效,或者是否必须是 Future 才能返回一些结果。

在你的有状态/更少的类中,你终于等待未来的到来,所以像

Widget build(BuildContext context) {
    return FutureBuilder( 
            future: _yourFuture,
            builder: (context, snapshot) { 

【讨论】:

  • 我的代码不会在开始时运行,它会在点击按钮后运行,所以我没有任何小部件,而且我也没有什么要构建的,是否可以没有未来的建设者?
  • 您可以将 FutureBuilder 放在输出小部件的前面,例如 builder: (context, snapshot) { Text(myFutureText);} 在加载完成之前,您可能希望在这个地方。
  • 如果这有帮助,接受或支持答案会很好:-)
猜你喜欢
  • 1970-01-01
  • 2021-12-20
  • 2017-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 2019-02-16
相关资源
最近更新 更多