0

I am trying to work out how a user can upload a eg a profile image and have this store in firebase. this is the code I have so far which shows the image picker but I cannot get the path nor have the image uploaded

dynamic _showSelectImageDialog() {
    return Platform.isIOS ? _iosBottomSheet() : _androidDialog();
  }

  Future _iosBottomSheet() async => showCupertinoModalPopup(
        context: context,
        builder: (context) {
          return CupertinoActionSheet(
            // title: Text('Add Photo'),
            actions: <Widget>[
              CupertinoActionSheetAction(
                onPressed: () => _upload(ImageSource.camera),
                child: const Text('Take Photo'),
              ),
              CupertinoActionSheetAction(
                onPressed: () => _upload(ImageSource.gallery),
                child: const Text('Choose Photo'),
              ),
            ],
            cancelButton: CupertinoActionSheetAction(
              onPressed: () => Navigator.pop(context),
              child: const Text('Cancel'),
            ),
          );
        },
      );

  _androidDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return SimpleDialog(
          title: const Text('Add Photo'),
          children: <Widget>[
            SimpleDialogOption(
              onPressed: () => _upload(ImageSource.camera),
              child: const Text('Take Photo'),
            ),
            SimpleDialogOption(
              onPressed: () => _upload(ImageSource.gallery),
              child: const Text('Choose From Gallery'),
            ),
            SimpleDialogOption(
              onPressed: () => Navigator.pop(context),
              child: const Text(
                'Cancel',
                style: TextStyle(
                  color: Colors.redAccent,
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  // Select and image from the gallery or take a picture with the camera
  // Then upload to Firebase Storage

  _upload(ImageSource source) async {
    var picker = ImagePicker();
    PickedFile pickedImage;
    try {
      pickedImage = (await picker.pickImage(source: source, maxWidth: 1920))
          as PickedFile;

      File imageFile = File(pickedImage.path);

      try {
        // Uploading the selected image with some custom meta data
        await storageRef
            .child('uploads/user/avatar/${widget.user.id}/$imageFile.jpg')
            .putFile(imageFile);
        print(imageFile);
        // Refresh the UI
        setState(() {});
      } on FirebaseException {
        // print(error);
      }
    } catch (err) {
      print(err);
    }
    Navigator.pop(context);
  }

_displayProfileImage() {
    // No new profile image
    if (_profileImage == null) {
      // No existing profile image
      if (widget.user.profileImageUrl.isEmpty) {
        // Display placeholder
        return AssetImage('assets/images/user_placeholder.jpg');
      } else {
        // User profile image exists
        return CachedNetworkImageProvider(widget.user.profileImageUrl);
      }
    } else {
      // New profile image
      return FileImage(File(_profileImage.path));
    }
  }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Boss Nass
  • 3,384
  • 9
  • 48
  • 90

1 Answers1

2

1) Pick image using image picker

Put this package in your pubspec.yaml

image_picker: ^0.8.4+4

2) Use this code to pick image

image = await _picker.pickImage(source: ImageSource.gallery);

3) save the image in firebase cloud and get the image URL

Put these packages in your pubspec.yaml

cloud_firestore: ^3.1.0
firebase_storage: ^10.1.0
firebase_core: ^1.10.0

Use this code to upload the image to cloud storage

var imageFile = File(image!.path);
                      String fileName = basename(imageFile.path);
                      FirebaseStorage storage = FirebaseStorage.instance;
                      Reference ref =
                          storage.ref().child("Image-" + productname.text);

Use this code to get the URL

UploadTask uploadTask = ref.putFile(imageFile);
                      await uploadTask.whenComplete(() async {
                        var url = await ref.getDownloadURL();
                        image_url = url.toString();
                      }).catchError((onError) {
                        print(onError);
                      });

4) Finally add image url to firebase database

Code to add data to firebase database

Map<String, dynamic> demodata = {
      "image_url": imageurl
    };
    CollectionReference collectionreference =
        FirebaseFirestore.instance.collection(image);
    collectionreference.add(demodata);
Alan Bosco
  • 737
  • 5
  • 20