Flutter ImagePicker -在onPressed中异步获取图像显示lint警告

ztigrdn8  于 2023-05-23  发布在  Flutter
关注(0)|答案(1)|浏览(134)

我正在用ImagePicker实现一个个人资料图片上传,并将逻辑放入一个按钮的onPressed函数中,如下所示:

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

一切正常,没有错误,但我得到了一个关于async部分的lint警告:
需要一个同步函数,但获得异步。
我做错了吗?

igetnqfo

igetnqfo1#

根据Dart Code Metrics,这是对Dart代码设计的警告,避免在预期同步的情况下调用异步函数。
avoid-passing-async-when-sync-expected
为了避免抱怨,现在有两种方法。
1.使用then()方法

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.使用匿名函数(我不喜欢这个函数,我们应该把它转换成一个单独的函数)

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

相关问题