【问题标题】:How to return value from this function??? in flutter如何从这个函数返回值???飘飘然
【发布时间】:2021-08-14 06:24:50
【问题描述】:
Future<String> uploadFile(String filePath) async {
    File file = File(filePath);
    final fileName = basename(filePath);
    try {
      firebase_storage.TaskSnapshot taskSnapshot = await firebase_storage.FirebaseStorage.instance
          .ref("news/$fileName")
          .putFile(file);
      await taskSnapshot.ref.getDownloadURL().then(
            (value) {
              print("Done: $value");
              return value;
            }

      );
      
      return "123";
    } on firebase_core.FirebaseException catch (e) {
      print(e);
      return "#";
    }
  }

uploadFile 返回 123,因为之后会打印该值,如何在返回“123”之前从该函数返回值??

【问题讨论】:

  • return await taskSnapshot.ref.... 当然删除 return "123";

标签: flutter function dart try-catch


【解决方案1】:

您需要等待getDownloadUrl() 任务然后返回它的值,而不是使用.then(...)

Future<String> uploadFile(String filePath) async {
  File file = File(filePath);
  final fileName = basename(filePath);
  try {
    firebase_storage.TaskSnapshot taskSnapshot = await firebase_storage
        .FirebaseStorage.instance
        .ref("news/$fileName")
        .putFile(file);
    final url = await taskSnapshot.ref.getDownloadURL();
    return url;
  } on firebase_storage.FirebaseException catch (e) {
    print(e);
    return "#";
  }
}

【讨论】:

    猜你喜欢
    • 2019-11-28
    • 2021-09-12
    • 2020-12-09
    • 2019-07-14
    • 2022-01-06
    • 2020-11-29
    • 1970-01-01
    • 2019-08-28
    • 2021-01-20
    相关资源
    最近更新 更多