【问题标题】:Flutter rebuilds widget without waiting for code executionFlutter 无需等待代码执行即可重建小部件
【发布时间】:2021-06-11 20:23:28
【问题描述】:

我有上传图片到服务器的功能。但是,小部件在图像上传时开始重建,并且在图像上传后不执行代码。

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

这是打印语句在控制台上的输出

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

从上面可以看出,没有执行其他代码,并且小部件已自行重建。我可能做错了什么?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    _imageFile = _picker.getImage(source: ImageSource.camera); 不对,getImage 是一个Asynchronous 函数,所以你需要等待它完成。

    这样做 - _imageFile = await _picker.getImage(source: ImageSource.camera);

    如果您想使用then,请这样做, _picker.getImage(source: ImageSource.camera).then((image)...your code...)

    【讨论】:

    • 谢谢。将其更改为 async/await 而不是 'then' 有效。
    • 您也可以使用then,但您的then 实现有点错误。我已经更新了我的答案,所以它可以使用。
    【解决方案2】:

    那是因为当您使用 _imageFile = _picker.getImage(source: ImageSource.camera); 时,_imageFile 结果将在未来出现,并且您的下一个代码将被执行。

    您可以使用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();
        }
      },
    

    或继续使用then,稍作改动:

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

    查看await & then的解释:Async/Await/then in Dart/Flutter

    【讨论】:

    • 谢谢。我正在使用异步/等待。您可以编辑您的答案以将“文件”的所有引用更改为“_imageFile”。
    猜你喜欢
    • 2021-06-05
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多