【问题标题】:Flutter- call function after functionFlutter-函数后调用函数
【发布时间】:2018-08-17 02:33:15
【问题描述】:

我想在 function1 完成后调用 function2。 为此,我确实这样做了。

这是功能1。

  Future _uploadImages() async {
    setState(() {isUploading = true;});

    images.forEach((image) async {

      await image.requestThumbnail(300, 300).then((_) async {
        final int date = DateTime.now().millisecondsSinceEpoch;
        final String storageId = '$date$uid';

      final StorageReference ref =
          FirebaseStorage.instance.ref().child('images').child(storageId);

        final file = image.thumbData.buffer.asUint8List();

       StorageUploadTask uploadTask = ref.putData(file);

      Uri downloadUrl = (await uploadTask.future).downloadUrl;

      final String url = downloadUrl.toString();

      imageUrls.add(url);

      });

     });

  }

这是功能2

    Future _writeImageInfo() async {
    await _uploadImages().then((_) async {
     await Firestore.instance.collection('post').document(uid).setData({
        'imageUrls': imageUrls,
      }).then((_) { 
        Navigator.of(context).pop();
       });

  }

但是控制台说函数 2 的 imageUrls 在列表长度 = 0 时被调用,因为它是在函数 1 完成之前调用的。 我不知道为什么在函数 1 之后没有调用该函数。 我怎样才能做到这一点?

【问题讨论】:

标签: flutter


【解决方案1】:

这是因为您的images.forEach.forEach 不适用于异步回调。因此它不会等待每个 foreach 结束来继续该功能。

一般来说,无论如何都不要在飞镖中使用.forEach。 Dart 直接在 for 关键字上做得很好。

所以最终,您应该执行以下操作:

for (final image in images) {
  ...
}

【讨论】:

  • 谢谢我不再使用 forEach。现在它抱怨这个[dart] The type 'List<Asset>' used in the 'for' loop must implement Stream.你知道发生了什么吗?
  • 我的错我的错,await for 不需要。一个简单的for 就足够了。固定
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-29
  • 2021-05-03
  • 2023-03-05
  • 2020-01-04
  • 2021-03-04
  • 1970-01-01
相关资源
最近更新 更多