2

I am implementing a profile picture upload with ImagePicker and put the logic into the onPressed function of a button like this:

    OutlinedButton.icon(
      icon: Icon(Icons.upload),
      label: Text("Select profile picture"),
      onPressed: () async {
        XFile? image = await introVM.imagePicker.pickImage(
            source: ImageSource.gallery,
            imageQuality: 50,
            preferredCameraDevice: CameraDevice.front);
        if (image != null) introVM.setProfilePicture(image!.path);
      },
    );

Everything works fine without errors, but I am getting a lint warning about the async part:

Expected a sync function but got async.

Am I doing it wrong?

Big_Chair
  • 2,781
  • 3
  • 31
  • 58

1 Answers1

2

According to Dart Code Metrics, it is a warning for a Dart code design that avoids calling an asynchronous function where a synchronous is expected.

avoid-passing-async-when-sync-expected

To avoid complaints from linting, there are 2 ways for now.

  1. use then() method
OutlinedButton.icon(
    icon: Icon(Icons.upload),
    label: Text("Select profile picture"),
    onPressed: () {
        introVM.imagePicker.pickImage(
            source: ImageSource.gallery, 
            imageQuality: 50,
            preferredCameraDevice: CameraDevice.front
        ).then((XFile? xFile) {
             if (xFile != null) introVM.setProfilePicture(xFile!.path);
        });
    },
);
  1. Use the anonymous function (I am not preferred that one, and we should convert it into a separate function)
OutlinedButton.icon(
    icon: Icon(Icons.upload),
    label: Text("Select profile picture"),
    onPressed: () {
        // Should move to a separate function
        () async {
            XFile? image = await introVM.imagePicker.pickImage(
                source: ImageSource.gallery,
                imageQuality: 50,
                preferredCameraDevice: CameraDevice.front);
            if (image != null) introVM.setProfilePicture(image!.path);
         };
    },
);
Sowat Kheang
  • 668
  • 2
  • 4
  • 12
  • Thank you, I will try it when I'm home and accept your answer if it works. One question: so I would rewrite this simply to get rid of the warning, but there is no actual functional/safety difference between the `async` and `.then()` version, correct? – Big_Chair May 22 '23 at 08:56
  • Yes, I guess so. And, one more thing, we can look at the lint rule and put it in the analysis_options.yaml file in order to get rid of the warning. – Sowat Kheang May 23 '23 at 02:30