【问题标题】:How to resolve an error from passing a Future<dynamic> instance as a parameter?如何解决将 Future<dynamic> 实例作为参数传递的错误?
【发布时间】:2019-12-29 00:56:48
【问题描述】:

我得到错误:

I/flutter ( 4091): The following NoSuchMethodError was thrown building Builder:
I/flutter ( 4091): Class 'Future' has no instance method '[]'.
I/flutter ( 4091): Receiver: Instance of 'Future'
I/flutter ( 4091): Tried calling: []("main")

并追溯到:

void updateUI(dynamic weatherData) {
    setState(() {
      if (weather Data==null) {
      //error checking code that's not called; weatherData object isn't null
      }

      temperature = weatherData['main']['temp'];
      weatherMessage = weather.getMessage(temperature);
      var condition = weatherData['weather'][0]['id'];
      weatherIcon = weather.getWeatherIcon(condition);
      cityName = weatherData['name'];
    });
  }

变量在别处初始化。这个问题与我显然不了解 Flutter Futures 和/或异步编程有关。 weatherData 对象是从 openWeatherMaps API 中提取的 JSON 字符串。如果我在创建它的地方调用print(weatherData),我会得到预期的 JSON 字符串。如果我在上面的方法中调用print(weatherData),我会得到`Instance of Future'。

【问题讨论】:

    标签: asynchronous flutter dart


    【解决方案1】:

    看起来你正在传递一个需要解决才能使用它的未来。

    void updateUI(Future<dynamic> weatherDataFuture) async {
      final weatherData = await weatherDataFuture;
      ...
    

    【讨论】:

    • 感谢您的回复。你的建议给我一个错误说type 'Future&lt;dynamic&gt;' is not a subtype of type 'Future&lt;Map&lt;String, dynamic&gt;&gt;'
    • 对不起,改成Future&lt;dynamic&gt;。
    • 做到了。谢谢!
    【解决方案2】:

    这个错误的实际问题是取数据的方法没有标记为await。例如

    NetworkHelper networkHelper = new NetworkHelper(url);
    
    var weatherData = await networkHelper.getData();
    

    在上面,networkHelper被标记为await。

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 2022-01-20
      • 1970-01-01
      • 2020-08-19
      • 2011-03-29
      • 2019-09-08
      • 2013-12-17
      • 2013-06-23
      • 1970-01-01
      相关资源
      最近更新 更多