flutterasync-awaitflutter-onpressed

Flutter ImagePicker - Getting image asynchronously in onPressed shows lint warning


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?


Solution

  • 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);
             };
        },
    );