0

I have a function to upload image to the server. However the widgets starts rebuilding while the image is being uploaded and does not execute code after image is uploaded.

InkWell(
  child: Icon(
    Icons.camera,
    size: 50,
    color: Colors.red[400],
  ),
  onTap: () {
    _imageFile =
        _picker.getImage(source: ImageSource.camera);
    _imageFile.then((file) async {
      if (file != null) {
        fileName = file.path.toString();
        var res = await Auth.uploadImage(file);
        print("Response for image upload is : ");
        print(res);
        await setUserData();
      }
    });
  },
)

This is the output on the console from print statements

I/flutter (10171): Calling build Method
I/Timeline(10171): Timeline: Activity_launch_request time:68831133
I/flutter (10171): Uploading image to server
I/flutter (10171): Calling build Method
I/flutter (10171): Image uploaded successfully

As can be seen above no other code is executed and the widget has rebuilt itself. What am I possibly doing wrong?

Monu Yadav
  • 519
  • 2
  • 17

2 Answers2

2

_imageFile = _picker.getImage(source: ImageSource.camera); its not right, getImage is an Asynchronous function so you need to wait for it to finish.

do this - _imageFile = await _picker.getImage(source: ImageSource.camera);

If you want to use then do it like this, _picker.getImage(source: ImageSource.camera).then((image)...your code...)

M.M.Hasibuzzaman
  • 1,015
  • 5
  • 10
1

That's because when you're using _imageFile = _picker.getImage(source: ImageSource.camera); the _imageFile result will come in the future and your next code is executed.

You can fixed the problem either using await:

 onTap: () async {
    _imageFile =
        await _picker.getImage(source: ImageSource.camera);
    if (_imageFile != null) {
        fileName = file.path.toString();
        var res = await Auth.uploadImage(file);
        print("Response for image upload is : ");
        print(res);
        await setUserData();
    }
  },

Or keep using then with a slight change:

  onTap: () {
    _picker.getImage(source: ImageSource.camera)
           .then((file) async {
             if (file != null) {
               fileName = file.path.toString();
               var res = await Auth.uploadImage(file);
               print("Response for image upload is : ");
               print(res);
               await setUserData();
           }
        });
  },

See explanation about await & then: Async/Await/then in Dart/Flutter

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
  • 1
    Thank you. I'm using async/await. You can edit your answer to change all references of "file" to "_imageFile". – Monu Yadav Mar 14 '21 at 11:26