-2

Here I want the user to be able to upload up to 5 images. But when one uploads less than 5 images it freezes the app and does not upload the document at all.

class ItemInput extends StatefulWidget {
  @override
  _ItemInputState createState() => _ItemInputState();
}

class _ItemInputState extends State<ItemInput> {
  final Firestore database = Firestore.instance;
  //CollectionReference products = Firestore.instance.collection('products');

  TextEditingController nameText = TextEditingController();
  TextEditingController priceText = TextEditingController();
  TextEditingController cellNoText = TextEditingController();
  TextEditingController addText = TextEditingController();
  TextEditingController detailText = TextEditingController();
  TextEditingController pic = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  File _image1;
  File _image2;
  File _image3;
  File _image4;
  File _image5;
  
  static const menuItems = <String>[
    'Car/موتر',
    'motorcycle/ موترسایکل',
    'electronics/الکترونیک',
    'house/ خانه',
    'household/لوازم خانه',
    'mobile/موبایل',
    'Sellect Category/انتخاب بخش',
  ];

  final List<DropdownMenuItem<String>> _dropDownMenuItems = menuItems
      .map((String value) => DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          ))
      .toList();
  
  String _btnselected = "Sellect Category/انتخاب بخش";

  Future getImage1() async {
    var firstImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image1 = firstImage;
    });
  }

  Future getImage2() async {
    var secondImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image2 = secondImage;
    });
  }

  Future getImage3() async {
    var thirdImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image3 = thirdImage;
    });
  }

  Future getImage4() async {
    var forthImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image4 = forthImage;
    });
  }

  Future getImage5() async {
    var fifthImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image5 = fifthImage;
    });
  }

  var imageUrl1;
  var imageUrl2;
  var imageUrl3;
  var imageUrl4;
  var imageUrl5;

  FirebaseStorage storage = FirebaseStorage.instance;

  uploadPic() async {
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image1);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl1 = url;
    return url;
  }

  /////2
  uploadPic2() async {
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image2);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl2 = url;
    return url;
  }

  ////3
  uploadPic3() async {
    
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image3);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl3 = url;
    return url;
  }

  ///4
  uploadPic4() async {
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image4);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl4 = url;
    return url;
  }

  ///5
  uploadPic5() async {
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image5);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl5 = url;
    return url;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Put AD'),
          centerTitle: true,
        ),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(5.0),
            child: Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Form(
                  key: _formKey,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      TextFormField(
                        controller: nameText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.directions_car),
                          hintText: 'Corolla, Mercedes...',
                          labelText: 'Item Name - نام جنس',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: detailText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.description),
                          hintText: 'Description - مشخصات',
                          labelText: 'Description - مشخصات',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: priceText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.attach_money),
                          hintText: 'Enter your item\'s price',
                          labelText: 'Price - قیمت',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: cellNoText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.call),
                          hintText: '0700-000-000',
                          labelText: 'Mobile Number -  شماره تماس',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: addText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.location_city),
                          hintText: 'Enter Your Address',
                          labelText: 'Address - آدرس',
                        ),
                      ),
                      SizedBox(height: 30),
                      Padding(
                        padding: const EdgeInsets.all(5.0),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: <Widget>[
                            //////// dropdown start //////////
                            DropdownButton(
                              hint: Text('Sellect Category'),
                              value: _btnselected,
                              items: this._dropDownMenuItems,
                              onChanged: (String newvalue) {
                                setState(() {
                                  _btnselected = newvalue;
                                });
                              },
                            ),
                            ///////  dropdown end  //////
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                InkWell(
                                  onTap: () async {
                                    await getImage1();
                                  },
                                  child: Container(
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                              BorderRadius.circular(10)),
                                      height: 60,
                                      width: 60,
                                      child: (_image1 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                              _image1,
                                              fit: BoxFit.cover,
                                            )
                                      ),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                     await getImage2();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                              BorderRadius.circular(10)),
                                      child: (_image2 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                              _image2,
                                              fit: BoxFit.fill,
                                            )),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                    await getImage3();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                              BorderRadius.circular(10)),
                                      child: (_image3 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                              _image3,
                                              fit: BoxFit.fill,
                                            )),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                    await getImage4();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                              BorderRadius.circular(10)),
                                      child: (_image4 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                              _image4,
                                              fit: BoxFit.fill,
                                            )),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                    await getImage5();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                              BorderRadius.circular(10)),
                                      child: (_image5 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                              _image5,
                                              fit: BoxFit.fill,
                                            )),
                                ),
                                SizedBox(width: 5),
                              ],
                            ),

                            SizedBox(
                              height: 10,
                            ),
                            RaisedButton.icon(
                                color: Colors.teal,
                                onPressed: () async {
                                  Navigator.pop(
                                    context,
                                  );
                                  switch (_btnselected) {
                                    case 'Car/موتر':
                                      database.collection("car").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url":
                                            (await uploadPic() != null)
                                                ? await uploadPic()
                                                : "null",
                                        "image 2 Url":
                                            (await uploadPic2() != null)
                                                ? await uploadPic2()
                                                : "null",
                                        "image 3 Url":
                                            (await uploadPic3() != null)
                                                ? await uploadPic3()
                                                : "null",
                                        "image 4 Url":
                                            (await uploadPic4() != null)
                                                ? await uploadPic4()
                                                : "null",
                                        "image 5 Url":
                                            (await uploadPic5() != null)
                                                ? await uploadPic5()
                                                : "null",
                                      });

                                      break;
                                    
                                  }
                                  (_image1 != null)
                                      ? uploadPic().then((value) {
                                          DocumentReference docRef = Firestore
                                              .instance
                                              .collection("carPics")
                                              .document();
                                          docRef.setData({"image 1 Url": value},
                                              merge: true);
                                        })
                                      : print("no images");

                                  //2
                                  (_image2 != null)
                                      ? uploadPic2().then((value) {
                                          DocumentReference docRef = Firestore
                                              .instance
                                              .collection("carPics")
                                              .document();
                                          docRef.setData({"image 2 Url": value},
                                              merge: true);
                                        })
                                      : print("no image");

                                  ///3
                                  (_image3 != null)
                                      ? uploadPic3().then((value) {
                                          DocumentReference docRef = Firestore
                                              .instance
                                              .collection("carPics")
                                              .document();
                                          docRef.setData({"image 3 Url": value},
                                              merge: true);
                                        })
                                      : print('no image');

                                  ///4
                                  (_image4 != null)
                                      ? uploadPic4().then((value) {
                                          DocumentReference docRef = Firestore
                                              .instance
                                              .collection("carPics")
                                              .document();
                                          docRef.setData({"image 4 Url": value},
                                              merge: true);
                                        })
                                      : print('no image');

                                  ///5
                                  (_image5 != null)
                                      ? uploadPic5().then((value) {
                                          DocumentReference docRef = Firestore
                                              .instance
                                              .collection("carPics")
                                              .document();
                                          docRef.setData({"image 5 Url": value},
                                              merge: true);
                                        })
                                      : print('npo image');
                                },
                                icon: Icon(
                                  Icons.send,
                                  size: 25,
                                  color: Colors.white,
                                ),
                                label: Text(
                                  'Submit  - برو',
                                  style: TextStyle(
                                      fontSize: 20,
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold),
                                ))
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ));
  }
}

Here is all of the code for taking input from user, i have deleted the import statements and some other useless stuff to make it clean for you guys to be able to read the code better. i hope somebody will find the flaw. How can I upload less than 5 images at a time?

5
  • 1
    We'd need to see a lot more code than just the class. How are you uploading it? Are the uploadPic functions asynchronous, and why do you have 5 different ones instead of one that takes the image number as a parameter? Does the database have a setting that will cause it to an error on less than 5 images in the upload? Jul 11, 2020 at 9:35
  • why you make 5 upload function? it can be just 1 function and just send the parameter
    – Ray Coder
    Jul 11, 2020 at 9:35
  • you can do like store image as an array in a document. so it will dynamically store the image. No matter how much you select the image Jul 11, 2020 at 10:23
  • Welcome to Stack Overflow! I edited the title of your question to include more detail about your problem. I also fixed indentation in your code sample so that it is more readable. Please edit in the function declaration for uploading the images. Just one of them is probably good enough assuming they're all similar. Good luck! Jul 11, 2020 at 13:51
  • there are 5 functions cuz every image is selected manually one by one
    – Mt Khalifa
    Jul 11, 2020 at 14:41

2 Answers 2

0

You're forgetting await on the null check of each of the uploading functions. You're checking if the returned Future is null, not the value of the Future. Simply adding await to the beginning of each null check would solve the issue. Ex.

"image 1 Url": (await uploadPic() != null)
    ? await uploadPic()
    : "null",

However, for efficiency, you should handle the uploading logic outside of the add method of the database. Ex.

String image1 = (await uploadPic()) ?? 'null';
...
database.collection("car").add({
  ...
  "image 1 Url": image1,
  ...
});

As others have said in the comments there isn't a need for 5 different upload functions, but if you want to keep it that way, it should be fine.

6
  • i did , doesn't help, gives the error Exception has occurred. NoSuchMethodError (NoSuchMethodError: The getter 'path' was called on null. Receiver: null Tried calling: path)
    – Mt Khalifa
    Jul 12, 2020 at 5:34
  • It likely helped, but there are other issues in your code._image1(or another image) must've been null. I can't give you a solution to that without more context. Jul 12, 2020 at 5:42
  • ok there is it all . now you can see all of it. @Christopher
    – Mt Khalifa
    Jul 12, 2020 at 6:33
  • @MtKhalifa Why do you have a switch-case with only 1 case? You're not doing a null check of each image in database.collection("car").add like you are in other places. This really should be done inside the function as your code is becoming very messy. Jul 12, 2020 at 14:21
  • there are other cases in switch statement, i cut them so the be cleaner here, and i do check for null now, so did you find a way to upload less images? @Christopher Moore
    – Mt Khalifa
    Jul 13, 2020 at 5:16
-1

this is how you do it . thanks to @Niteesh

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/rendering.dart';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:image_picker/image_picker.dart';

class ItemInput extends StatefulWidget {
  @override
  _ItemInputState createState() => _ItemInputState();
}

class _ItemInputState extends State<ItemInput> {
  final Firestore database = Firestore.instance;
  //CollectionReference products = Firestore.instance.collection('products');

  TextEditingController nameText = TextEditingController();
  TextEditingController priceText = TextEditingController();
  TextEditingController cellNoText = TextEditingController();
  TextEditingController addText = TextEditingController();
  TextEditingController detailText = TextEditingController();
  TextEditingController pic = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  File _image1;
  File _image2;
  File _image3;
  File _image4;
  File _image5;
  //String nall;

  static const menuItems = <String>[
    'Car/موتر',
    'motorcycle/ موترسایکل',
    'electronics/الکترونیک',
    'house/ خانه',
    'household/لوازم خانه',
    'mobile/موبایل',
    'Sellect Category/انتخاب بخش',
  ];

  final List<DropdownMenuItem<String>> _dropDownMenuItems = menuItems
      .map((String value) => DropdownMenuItem<String>(
    value: value,
    child: Text(value),
  ))
      .toList();

  String _btnselected = "Sellect Category/انتخاب بخش";

  Future getImage1() async {
    var firstImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image1 = firstImage;
    });
  }

  Future getImage2() async {
    var secondImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image2 = secondImage;
    });
  }

  Future getImage3() async {
    var thirdImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image3 = thirdImage;
    });
  }

  Future getImage4() async {
    var forthImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image4 = forthImage;
    });
  }

  Future getImage5() async {
    var fifthImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image5 = fifthImage;
    });
  }

  String imageUrl1;
  String imageUrl2;
  String imageUrl3;
  String imageUrl4;
  String imageUrl5;

  FirebaseStorage storage = FirebaseStorage.instance;

  uploadPic() async {
    //String fileName = path.basename(_image1.path);
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image1);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl1 = url;
    return url;
  }

  /////2
  uploadPic2() async {
    //String fileName = path.basename(_image2.path);
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image2);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl2 = url;
    return url;
  }

  ////3
  uploadPic3() async {
    //String fileName = path.basename(_image3.path);
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image3);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl3 = url;
    return url;
  }

  ///4
  uploadPic4() async {
    //  String fileName = path.basename(_image4.path);
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image4);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl4 = url;
    return url;
  }

  ///5
  uploadPic5() async {
    //String fileName = path.basename(_image5.path);
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image5);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl5 = url;
    return url;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Put AD'),
          centerTitle: true,
        ),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(5.0),
            child: Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Form(
                  key: _formKey,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      TextFormField(
                        controller: nameText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.directions_car),
                          hintText: 'Corolla, Mercedes...',
                          labelText: 'Item Name - نام جنس',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: detailText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.description),
                          hintText: 'Description - مشخصات',
                          labelText: 'Description - مشخصات',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: priceText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.attach_money),
                          hintText: 'Enter your item\'s price',
                          labelText: 'Price - قیمت',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: cellNoText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.call),
                          hintText: '0700-000-000',
                          labelText: 'Mobile Number -  شماره تماس',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: addText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.location_city),
                          hintText: 'Enter Your Address',
                          labelText: 'Address - آدرس',
                        ),
                      ),
                      SizedBox(height: 30),
                      Padding(
                        padding: const EdgeInsets.all(5.0),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: <Widget>[
                            //////// dropdown start //////////
                            DropdownButton(
                              hint: Text('Sellect Category'),
                              value: _btnselected,
                              items: this._dropDownMenuItems,
                              onChanged: (String newvalue) {
                                setState(() {
                                  _btnselected = newvalue;
                                });
                              },
                            ),
                            ///////  dropdown end  //////
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                InkWell(
                                  onTap: () async {
                                    //image.getImage(source: ImageSource.gallery);
                                    await getImage1();
                                  },
                                  child: Container(
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                          BorderRadius.circular(10)),
                                      height: 60,
                                      width: 60,
                                      child: (_image1 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                        _image1,
                                        fit: BoxFit.cover,
                                      )

                                    // : Icon(Icons.add_a_photo, size: 30),
                                  ),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                    // image.getImage(source: ImageSource.gallery);
                                    await getImage2();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                          BorderRadius.circular(10)),
                                      child: (_image2 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                        _image2,
                                        fit: BoxFit.fill,
                                      )),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                    // image.getImage(source: ImageSource.gallery);
                                    await getImage3();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                          BorderRadius.circular(10)),
                                      child: (_image3 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                        _image3,
                                        fit: BoxFit.fill,
                                      )),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                    // image.getImage(source: ImageSource.gallery);
                                    await getImage4();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                          BorderRadius.circular(10)),
                                      child: (_image4 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                        _image4,
                                        fit: BoxFit.fill,
                                      )),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                    // image.getImage(source: ImageSource.gallery);
                                    await getImage5();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                          BorderRadius.circular(10)),
                                      child: (_image5 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                        _image5,
                                        fit: BoxFit.fill,
                                      )),
                                ),
                                SizedBox(width: 5),
                              ],
                            ),

                            SizedBox(
                              height: 10,
                            ),
                            RaisedButton.icon(
                                color: Colors.teal,
                                onPressed: () async {
                                  Navigator.pop(
                                    context,
                                  );
                                  switch (_btnselected) {
                                    case 'Car/موتر':
                                      database.collection("car").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url":
                                        (_image1 != null)
                                            ? await uploadPic()
                                            : null,
                                        "image 2 Url":
                                        (_image2 != null)
                                            ? await uploadPic2()
                                            : null,
                                        "image 3 Url":
                                        (_image3 != null)
                                            ? await uploadPic3()
                                            : null,
                                        "image 4 Url":
                                        (_image4 != null)
                                            ? await uploadPic4()
                                            : null,
                                        "image 5 Url":
                                        (_image5 != null)
                                            ? await uploadPic5()
                                            : null,
                                      });

                                      break;
                                    case 'motorcycle/ موترسایکل':
                                      database.collection("motorcycle").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url": _image1 != null ? _image1.path : null,
                                        "image 2 Url": _image2 != null ? _image2.path : null,
                                        "image 3 Url": _image3 != null ? _image3.path : null,
                                        "image 4 Url": _image4 != null ? _image4.path : null,
                                        "image 5 Url": _image5 != null ? _image5.path : null,
                                      });
                                      break;

                                    case 'electronics/الکترونیک':
                                      database.collection("electronics").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url": _image1 != null ? _image1.path : null,
                                        "image 2 Url": _image2 != null ? _image2.path : null,
                                        "image 3 Url": _image3 != null ? _image3.path : null,
                                        "image 4 Url": _image4 != null ? _image4.path : null,
                                        "image 5 Url": _image5 != null ? _image5.path : null,
                                      });
                                      break;

                                    case 'house/ خانه':
                                      database.collection("house").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url": _image1 != null ? _image1.path : null,
                                        "image 2 Url": _image2 != null ? _image2.path : null,
                                        "image 3 Url": _image3 != null ? _image3.path : null,
                                        "image 4 Url": _image4 != null ? _image4.path : null,
                                        "image 5 Url": _image5 != null ? _image5.path : null,
                                      });
                                      break;

                                    case 'household/لوازم خانه':
                                      database.collection("household").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url": _image1 != null ? _image1.path : null,
                                        "image 2 Url": _image2 != null ? _image2.path : null,
                                        "image 3 Url": _image3 != null ? _image3.path : null,
                                        "image 4 Url": _image4 != null ? _image4.path : null,
                                        "image 5 Url": _image5 != null ? _image5.path : null,
                                      });
                                      break;

                                    case 'mobile/موبایل':
                                      database.collection("mobile").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url": _image1 != null ? _image1.path : null,
                                        "image 2 Url": _image2 != null ? _image2.path : null,
                                        "image 3 Url": _image3 != null ? _image3.path : null,
                                        "image 4 Url": _image4 != null ? _image4.path : null,
                                        "image 5 Url": _image5 != null ? _image5.path : null,
                                      });
                                      break;
                                  }
                                  if(_image1 != null)
                                  uploadPic().then((value) {
                                    DocumentReference docRef = Firestore
                                        .instance
                                        .collection("carPics")
                                        .document();
                                    docRef.setData({"image 1 Url": value},
                                        merge: true);
                                  });

                                  //2
                                  if(_image2 != null)
                                  uploadPic2().then((value) {
                                    DocumentReference docRef = Firestore
                                        .instance
                                        .collection("carPics")
                                        .document();
                                    docRef.setData({"image 2 Url": value},
                                        merge: true);
                                  });

                                  //3
                                  if(_image3 != null)
                                  uploadPic3().then((value) {
                                    DocumentReference docRef = Firestore
                                        .instance
                                        .collection("carPics")
                                        .document();
                                    docRef.setData({"image 3 Url": value},
                                        merge: true);
                                  });

                                  //4
                                  if(_image4 != null)
                                  uploadPic4().then((value) {
                                    DocumentReference docRef = Firestore
                                        .instance
                                        .collection("carPics")
                                        .document();
                                    docRef.setData({"image 4 Url": value},
                                        merge: true);
                                  });

                                  //5
                                  if(_image5 != null)
                                  uploadPic5().then((value) {
                                    DocumentReference docRef = Firestore
                                        .instance
                                        .collection("carPics")
                                        .document();
                                    docRef.setData({"image 5 Url": value},
                                        merge: true);
                                  });
                                },
                                icon: Icon(
                                  Icons.send,
                                  size: 25,
                                  color: Colors.white,
                                ),
                                label: Text(
                                  'Submit  - برو',
                                  style: TextStyle(
                                      fontSize: 20,
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold),
                                ))
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ));
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.