setState如何在更改参数的回调函数中工作

时间:2019-03-31 15:11:30

标签: callback flutter setstate

带有参数的发送图像函数调用(返回函数),如何使用参数设置状态。

Env

[✓] Flutter (Channel stable, v1.2.1, on Mac OS X 10.13.6 17G6029, locale en-CN)
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] iOS toolchain - develop for iOS devices (Xcode 10.1)
[✓] Android Studio (version 3.3)
[✓] VS Code (version 1.32.3)
[✓] Connected device (1 available)

onSendProgress是在uploadImage中定义的函数回调

    var result = await uploadApi.uploadImage(
      context,
      _scaffoldKey,
      imageData,
      onSendProgress,
    );
  void onSendProgress(int count, int total) {
      setState(() {
        uploadPercentage = count / total;
        print(uploadPercentage);
      });
  }

运行代码时,uploadPercentage将使用0到1的一系列值进行控制台输出,就像这样

flutter: 0.25661834269331224
flutter: 0.2566929379358112
flutter: 0.25676753317831025
flutter: 0.2568421284208092
flutter: 0.25691672366330826
flutter: 0.2569913189058073
flutter: 0.25706591414830626
flutter: 0.2571405093908053
flutter: 0.25721510463330427
flutter: 0.2572896998758033
flutter: 0.2573642951183023
...

但在小组件中显示uploadPercentage

Text("Uploading ${uploadPercentage}");

最后只会更改一次(1)

希望结果:

Text("Uploading ${uploadPercentage}");

也显示变化的结果,就像上面的控制台一样

0 个答案:

没有答案