在功能之后进行Flutter-call功能

时间:2018-08-17 02:33:16

标签: flutter

我想在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();
       });

  }

但是控制台说,当列表长度= 0时调用function2的imageUrls,因为它在函数1完成之前被调用。 我不知道为什么在功能1之后不调用该功能。 我该怎么做呢?

1 个答案:

答案 0 :(得分:3)

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

通常,请勿在飞镖中使用.forEach。 Dart直接在for关键字上做得很好。

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

for (final image in images) {
  ...
}
相关问题