首页 > 解决方案 > image picker and store them into firebase with flutter

问题描述

I am trying to add this future to my app so I wrote this code

 PickedFile _image;
  String _uploadedFileURL;
  final _picker = ImagePicker();
Future getImage(bool isCamera) async {
    PickedFile image;
    if (isCamera) {
      PickedFile image = await _picker.getImage(source: ImageSource.camera);
      setState(() {
        _image = image;
      });
    } else
      PickedFile image = await _picker.getImage(source: ImageSource.gallery);
    setState(() {
      _image = image;
    });
  }

but how to uploaded it in flutter ? I searched a lot but in every code I found there is a mistake because of the updated and in the storage package example I did not find uploading image so, what the last code to upload images?

标签: flutter

解决方案


这就是我一直用来从图像选择器中选择图像然后裁剪选择的图像,然后将其上传到 Firebase 存储的方法。希望这对您有所帮助。需要任何澄清,请发表评论。

    // Crop Selected Image
    Future _cropImage(File selectedFile) async {
      File cropped = await ImageCropper.cropImage(
        sourcePath: selectedFile.path,
        aspectRatio: CropAspectRatio(
          ratioX: 1.0,
          ratioY: 1.0,
        ),
        cropStyle: CropStyle.circle,
      );
      if (cropped != null) {
        setState(
          () {
            _imageFile = cropped;
          },
        );
      }
    }

    // Select Image Via Image Picker
    Future getImage(ImageSource source) async {
      // ignore: deprecated_member_use
      File selected = await ImagePicker.pickImage(source: source);
      if (selected != null) {
        _cropImage(selected);
      }
    }

    // Upload Picture to Firebase
    Future uploadImage(BuildContext context) async {
      String fileName = basename(_imageFile.path);
      Reference firebaseStorageRef =
          FirebaseStorage.instance.ref().child(fileName);
      UploadTask uploadTask = firebaseStorageRef.putFile(_imageFile);
      // ignore: unused_local_variable
      TaskSnapshot taskSnapshot = await uploadTask;
    }

推荐阅读