skip to Main Content

When i click on camera icon in stack widget and also it is unable to update image it show this error.It also not upload image to database nor it chaange the url** [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value E/flutter (28471): #0 _profileState.geturl (package:ecommerce/Auth/profile.dart:25:59) E/flutter (28471): **
I want to update image but facing error please solve it..

Code For Imagepicker

Future image(BuildContext context) async{
  showModalBottomSheet(
    elevation: 5,
    enableDrag: true,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.only(
        topLeft: Radius.circular(20),
        topRight: Radius.circular(20),
      ),
    ),
    context: context,
    builder: (BuildContext context) {
      return Container(
        height: 200,
        child: Column(
          children: [
            ///Gallery
            ListTile(
              leading: Icon(Icons.browse_gallery),
              title: Text("Pick image from gallery"),
              onTap: () async{
                final gallery=await ImagePicker().pickImage(source: ImageSource.gallery);
if (gallery!=null) {
  ScaffoldMessenger.of(context).showSnackBar(SnackBar(
    content: Text("Image Picked successfull",style: TextStyle(color: Colors.redAccent),
    ),duration: Duration(seconds: 5),
  ));
} else {
  ScaffoldMessenger.of(context).showSnackBar(SnackBar(
    content: Text("Please pick image for further proccess",style: TextStyle(color: Colors.redAccent),
    ),duration: Duration(seconds: 5),
  ));
}

Code For updating Url

Future geturl(context)async{
  final id=DateTime.now().toString();
  final reference=FirebaseFirestore.instance.collection("user3");
await image(context);
  final storage.Reference ref =
  storage.FirebaseStorage.instance.ref('/images'+id);
  final storage.UploadTask uploadTask = ref.putFile(_image!.absolute);
  await Future.value(uploadTask);
  final  downurl=await ref.getDownloadURL();
  print(FirebaseAuth.instance.currentUser!.uid);
  reference.doc(FirebaseAuth.instance.currentUser!.uid).update(
      {
        "imageurl":downurl.toString(),
      }
  ).then((value) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text("Updated successfully",style: TextStyle(color: Colors.redAccent),
      ),duration: Duration(seconds: 5),
    ));
  }).catchError((e){
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text("${e.message}",style: TextStyle(color: Colors.redAccent),
      ),duration: Duration(seconds: 5),
    ));
  });
}

For displaying image in flutter app

Stack(

                          alignment: Alignment.bottomRight,
                          children: [
                            CircleAvatar(
                              radius: 70,
                              backgroundImage:_image!=null?FileImage(_image!.absolute) : NetworkImage(snapshot.data!.docs[index]["imageurl"]) as ImageProvider,
                            ),
                             InkWell(
                                 onTap: (){
geturl(context);
                                 },
                                 child: Icon(Icons.add_a_photo,size: 30,)),
                          ],
                        ),

Please solve I am facing this error for Last couple of days

2

Answers


  1. I think that this line is causing the problem:

    final storage.UploadTask uploadTask = ref.putFile(_image!.absolute);
    

    Because _image is probably null. Where do you assign a value to the variable _image?

    EDIT:

    how I would fix this:

    you have one method pickImage that shows the bottom modal sheet and allows the user to pick an image. if the user picks an image, you call a method that saves the picked image to firebase, in this case the method is called: saveImage

    void pickImage(BuildContext context) {
        showModalBottomSheet(
          elevation: 5,
          enableDrag: true,
          isDismissible: false,
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20),
              topRight: Radius.circular(20),
            ),
          ),
          context: context,
          builder: (BuildContext context) {
            return Container(
              height: 200,
              child: Column(
                children: [
                  ListTile(
                    leading: Icon(Icons.browse_gallery),
                    title: Text("Pick image from gallery"),
                    onTap: () async {
                      XFile? pickedImage = await ImagePicker().pickImage(source: ImageSource.gallery);
                      if (pickedImage != null) {
                        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                          content: Text(
                            "Image Picked successfull",
                            style: TextStyle(color: Colors.redAccent),
                          ),
                          duration: Duration(seconds: 5),
                        ));
                        var image = Image.memory(await pickedImage.readAsBytes());
                        // save image to firebase
                        saveImage(context, image);
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                          content: Text(
                            "Please pick image for further proccess",
                            style: TextStyle(color: Colors.redAccent),
                          ),
                          duration: Duration(seconds: 5),
                        ));
                      }
                    },
                  ),
                ],
              ),
            );
          },
        );
      }
    

    method that saves the image to firebase:

    Future saveImage(context, _image) async {
        final id = DateTime.now().toString();
        final reference=FirebaseFirestore.instance.collection("user3");
        final storage.Reference ref =
        storage.FirebaseStorage.instance.ref('/images'+id);
        final storage.UploadTask uploadTask = ref.putFile(_image!.absolute);
        await Future.value(uploadTask);
        final  downurl=await ref.getDownloadURL();
        print(FirebaseAuth.instance.currentUser!.uid);
        reference.doc(FirebaseAuth.instance.currentUser!.uid).update(
            {
              "imageurl":downurl.toString(),
            }
        ).then((value) {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(
            content: Text("Updated successfully",style: TextStyle(color: Colors.redAccent),
            ),duration: Duration(seconds: 5),
          ));
        }).catchError((e){
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(
            content: Text("${e.message}",style: TextStyle(color: Colors.redAccent),
            ),duration: Duration(seconds: 5),
          ));
        });
      }
    
    Login or Signup to reply.
  2. You need to declare the image variable null by adding "?".

    Example: DataType image?

    Then display like this

     image!=null ? CircleAvatar(
                              radius: 70,
                              backgroundImage: FileImage(_image!.absolute) ,
                            ): CircleAvatar(
                              radius: 70,
                              backgroundImage: NetworkImage(snapshot.data!.docs[index]["imageurl"])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search