【问题标题】:What to use instead of await in initState() method?在 initState() 方法中使用什么来代替 await?
【发布时间】:2020-10-25 12:28:12
【问题描述】:

我收到此错误

“未来”类型的值不能分配给 “双”类型的变量。 因为我们不能在 initState() 方法中使用异步。

class _SettingsState extends State<Settings> {
  bool _isSwitched = false;
  double _sliderValue = 0;

  @override
  void initState() async {
    _sliderValue = _getInterval();
    super.initState();
  }
...

Future<double> _getInterval() async { ...

但是如果我们尝试在 initState() 中使用 await,那么我们会收到消息

而不是直接在内部等待异步工作 initState,调用一个单独的方法来完成这项工作而无需等待 它。

如何在 initState 中使用 _getInterval,即从它接收未来值,而不等待它?

【问题讨论】:

  • 然后使用Future.then()方法
  • @Rozerro 你得到答案了吗?

标签: flutter


【解决方案1】:

如果你想运行这段代码_sliderValue = _getInterval();,你可以把它放在一个单独的方法里

void myMethod() async{
   _sliderValue = await _getInterval();
}

然后在 initState 方法中调用它,如下所示:

@override
  void initState() async {
    super.initState();
    myMethod();
  }

【讨论】:

  • 你打败了我;)
  • initState 方法不能异步
  • initState 不能是异步的,但是你可以使用 Future 进入 initState 方法
  • 如果你得到你的答案,请投票并批准我的答案(-;
【解决方案2】:

只需调用_getInterval 方法而不等待它并将其更改为而不是返回值分配给方法末尾的_sliderValue(可能也调用setState

【讨论】:

    猜你喜欢
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2011-10-02
    • 2011-10-12
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多