【问题标题】:flutter: operator '[]' isn't defined for the class 'Future<Map>'颤振:未为类“Future<Map>”定义运算符“[]”
【发布时间】:2020-03-05 21:29:19
【问题描述】:

当我尝试访问文件中的某些数据时出现此错误

the operator '[]' isn't defined for the class 'Future<Map>'

我该如何解决这个问题?

Future<Map<dynamic, dynamic>> get getData async {
  final newData = await readFile().then((Map<dynamic, dynamic> value) {
    return value;
  });
  return newData;
}

final int time = getData['startTime']; // <--- error

【问题讨论】:

  • final int time = await getData['startTime'];
  • 谢谢,但这似乎没有解决它
  • final int time = (await getData)['startTime']; 你应该阅读一下 Future 和异步编程是如何工作的。
  • 尝试(await getData)['startTime'] 或将其分成两行:var myMap = await getData; final time = myMap['startTime'];
  • 谢谢,成功了!

标签: flutter


【解决方案1】:

您收到该错误的原因是因为getDataFuture,而不是Map - 可以使用[]。正如前面在 cmets 中提到的,getData 异步函数只会在使用 await 关键字执行 getData 之后返回 Map。您可以在 guide 上阅读有关使用 Dart 进行异步编程的更多详细信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 2020-11-16
    • 2020-12-28
    • 2021-01-03
    • 2021-03-23
    • 1970-01-01
    • 2021-09-15
    相关资源
    最近更新 更多