how to upload multiple images as array in flutter firebase

Viewed 37

hi I'm working on a commerce project and in this project i have a create product screen where client can create his own product sale screen I've been able to create sale screen perfectly I can upload 1 product image and information about the product but I can not find any solution for the multiple image uploading to firebase storage and then add their link to the firestore as an array.

I would really appreciate it if anyone have a solution for this

my create product screen code:

    void uploadFunction(List<XFile> _images) {
    for (int i = 0; i < _images.length; i++) {
      var imageUrl = uploadFile(_images[i]);
      _arrImageUrls.add(imageUrl.toString());
    }
  }

  Future<String> uploadFile(XFile _image) async {
    Reference reference =
        FirebaseStorage.instance.ref().child("cars_photos").child(_image.name);
    UploadTask uploadTask = reference.putFile(File(_image.path));
    await uploadTask.whenComplete(() {});
    return await reference.getDownloadURL();
  }

  final ImagePicker imagePicker = ImagePicker();
  List<XFile>? imageFileList = [];
  List<String> _arrImageUrls = [];

  Future<void> selectImages() async {
    final List<XFile>? selectedImages = await imagePicker.pickMultiImage();
    if (selectedImages!.isNotEmpty) {
      imageFileList!.addAll(selectedImages);
    }

    setState(() {
      imageFileList = selectedImages;
    });
  }

  void sellProduct() async {
    if (_addProductFormKey.currentState!.validate()) {
      final user = FirebaseAuth.instance.currentUser!.uid;

      final top = uploadFunction(imageFileList!);

      await FirebaseFirestore.instance.collection("cars").add({
        'salerid': user,
        'carmodel': carModelController.text.trim(),
        'carname': carNameController.text.trim(),
        'price': double.parse(priceController.text.trim()),
        'year': double.parse(yearController.text.trim()),
        'kilometer': double.parse(kmController.text.trim()),
        'category': categoryController.text.trim(),
        'images': _arrImageUrls,
      });
      Navigator.of(context, rootNavigator: true).pop();
    }
  }
0 Answers
Related