簡體   English   中英

Flutter 無需等待代碼執行即可重建小部件

[英]Flutter rebuilds widget without waiting for code execution

我有一個 function 將圖像上傳到服務器。 但是,小部件在圖像上傳時開始重建,並且在圖像上傳后不執行代碼。

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

這是來自打印語句的控制台上的 output

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

如上所示,沒有執行其他代碼,並且小部件已自行重建。 我可能做錯了什么?

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

這樣做 - _imageFile = await _picker.getImage(source: ImageSource.camera);

如果你想使用then這樣做, _picker.getImage(source: ImageSource.camera).then((image)...your code...)

那是因為當你使用_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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM