我正在使用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警告:

应为同步函数,但获得了异步.

我做错了吗?

推荐答案

根据DART代码度量,这是对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);
         };
    },
);

Flutter相关问答推荐

修复容器`Text`和容器表单之间的重叠

在Riverpod ConsumerWidget中使用文本编辑控制器

如何在凌晨12点显示00:00(24小时格式)而不是在Flutter 中显示24:00

如何让一个名为ONTAP的回调函数、另一个名为onTapDown的回调函数和另一个名为onTapUp的回调函数不重叠?

下拉图标未居中

Flutter 蜂窝单元测试

为什么Build_Runner的输出为0?

来自FirebaseAuth的错误DisplayName和邮箱在Flutter应用程序中给出错误

我想创建一个可滚动的堆叠列表项,每个项都朝向屏幕

为Android生成时出现Flutter 错误:给定资源值的<;COLOR&>无效

dart /长笛中的返回早期模式和拆分方法

按一下按钮即可更新 fl_chart

如何使自动焦点位于已经有一些文本的 TextField 的第一行?

如何从flutter连接PostgreSQL数据库?

如何在Flutter中的textField中在可编辑文本和前缀图标之间添加空格?

Flutter - firebase_auth_web 5.4.0 依赖于 intl ^0.17.0 但我必须使用更高版本 (intl ^0.18.0)

我想在文本结束后显示分隔线.它会在第一行、第二行或第三行结束

在 Flutter 中使用 HardwareKeyboard 时所有键都没有响应

我们什么时候在flutter中初始化一个provider?

Flutter MQTT - 发布到主题 1 并收听主题 2