【问题标题】:Is it possible to add multiple images to Firebase Database with Firebase Storage? - Flutter是否可以使用 Firebase 存储将多个图像添加到 Firebase 数据库? - 颤振
【发布时间】:2021-12-09 03:53:44
【问题描述】:

在我的 Flutter 应用程序中,我希望用户将数据和图像上传到 Firebase 数据库,我已经成功地做到了。问题是,当我上传多张图片时,Firebase 存储中的一个 URL 被提供给数据库集合,但没有其他图片。有没有办法在一个集合中获取所有图像 URL?

我用于发送数据的 Flutter 代码:

var title = '';
var pageNo = 0;
var description = '';
var imgUrl;

Future sendData() async {
//Add the TextFormField data to the database
hwFormData
    .add({
      'title': title,
      'pageNo': pageNo,
      'description': description,
      'imgUrl': _uploadedFileUrl
    })
    .then((value) => print('Form data sent'))
    .catchError((error) => print('Failed to send data: $error'));
 _key.currentState!.reset();

//Send Images
firebase_storage.Reference ref;
for (var img in _image) {
  ref = firebase_storage.FirebaseStorage.instance
      .ref()
      .child('hwImages/${Path.basename(img.path)}');
  await ref.putFile(img).whenComplete(() async {
    await ref.getDownloadURL().then((value) {
      hwFormData.add({'imgUrl': value});
      setState(() {
        _uploadedFileUrl = value;
        imgUrl = value;
      });
    });
  });
 }
}

【问题讨论】:

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


    【解决方案1】:

    已找到解决方案。必须将 imgUrl 更改为 List 值,然后在 for 循环中让 imgUrl 添加该值。

    新代码:

    //TextFormField data
    var title = '';
    var pageNo = 0;
    var description = '';
    List<String> imgUrl = [];
    
    Future sendData() async {
    //Send Images
    firebase_storage.Reference ref;
    for (var img in _image) {
      ref = firebase_storage.FirebaseStorage.instance
          .ref()
          .child('hwImages/${Path.basename(img.path)}');
      await ref.putFile(img).whenComplete(() async {
        await ref.getDownloadURL().then((value) {
          hwFormData.add({'imgUrl': value});
          imgUrl.add(value);
        });
      });
    }
    
    //Add the TextFormField data to the database
    hwFormData
        .add({
          'title': title,
          'pageNo': pageNo,
          'description': description,
          'imgUrl': imgUrl
        })
        .then((value) => print('Form data sent'))
        .catchError((error) => print('Failed to send data: $error'));
    //Resets the form data to null after it has been sent to the database
    _key.currentState!.reset();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2021-04-07
      • 2019-01-19
      • 2018-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多