Home > Blockchain >  Make widget drawn with ternary operator update when variable updates
Make widget drawn with ternary operator update when variable updates

Time:04-09

I have a container in my flutter project that loads the image selected by the flutter image_picker package. If the value is null, it load a placeholder image and text that says to upload an image.

GestureDetector(
                  onTap: () async {
                    setState(() {
                      _pickImage();
                    });
                  },
                  child: photo != null
                      ? Image.file(
                          File(
                            photo!.path.toString(),
                          ),
                        )
                      : Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(15),
                            color: const Color(0xff303434),
                          ),
                          height: 200,
                          width: double.infinity,
                          child: Center(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Image.asset('assets/images/camera.png'),
                                Text(
                                  'Upload Image',
                                  style: GoogleFonts.poppins(
                                    color: Colors.white,
                                    fontSize: 15,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                ),

The function to pick the image is:

void _pickImage() async {
      setState(() async {
        final ImagePicker _picker = ImagePicker();
        photo = await _picker.pickImage(
          source: ImageSource.camera,
          imageQuality: 90,
        );
        if (photo == null) return;
      });
    }

The issue is that when I select an image, it will only display in the container when I hot reload my project, and if I choose another image after, I need to hot restart to update the image in the container. How do I fix this issue and make the image in the container upload automatically when I select and image, rather than having to hot restart?

CodePudding user response:

You need to move all the code out of setState, and remove async.

CodePudding user response:

move everything out the setState and call set state after it, with nothing in it, not with async :D

  • Related