【问题标题】:Casting Future<List<String>> to a List<String> throws an exception in Flutter将 Future<List<String>> 转换为 List<String> 会在 Flutter 中引发异常
【发布时间】:2022-06-15 20:09:30
【问题描述】:

我有这个功能:

  Future<List<String>> _readJson(String path) async {
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path + '/' + path;
    String response = await File(appDocPath).readAsString();

    final data = await (json.decode(response) as List<dynamic>).cast<String>();

    return data;
  }

如您所见,输出为Future&lt;List&lt;String&gt;&gt;。我想将此函数的输出分配给这样的新列表(以便能够遍历元素:

  void _function(Map<dynamic, dynamic> playbackData) {
    ...

    List<String> jsonList = readJSON('landmarks.json') as List<String>;

    for(int i = 0; i <= jsonList.length - 1; ++i){
      print(jsonList[i]);
    }
  }

但这是我的错误:

[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'Future<List<String>>' is not a subtype of type 'List<String>' in type cast

我知道输出是一个未来的字符串列表,但我故意将其转换为一个字符串列表。我哪里错了?

【问题讨论】:

  • 不知道为什么你有第二个await。您是否尝试将您的 final data 行替换为:final data = (json.decode(response) as List&lt;dynamic&gt;).cast&lt;String&gt;();

标签: flutter dart


猜你喜欢
  • 2021-01-21
  • 1970-01-01
  • 2019-11-20
  • 2015-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 2019-02-16
相关资源
最近更新 更多