【问题标题】:Flutter: the operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'Flutter:没有为“Object”类型定义运算符“[]”。尝试定义运算符'[]'
【发布时间】:2021-04-03 15:18:15
【问题描述】:

如何获取嵌套对象值? print(_user.userLocation()['location']); 返回{country: Eesti, city: Tallin}

所以,我尝试使用_user.userLocation()['location']['city'] 来获取值Tallinn。但是,我得到了

The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'.

print(_user.userLocation()) print(_user.location().runtimeType); 返回

location: {
   country: Eesti,
   city: Tallinn,
}

flutter: _InternalLinkedHashMap<String, dynamic>

我尝试将变量设置为var a = _user.location()['location'],然后设置为a['city']。但是,这并不奏效。

【问题讨论】:

  • 请检查我添加的答案

标签: flutter dart


【解决方案1】:

你应该这样尝试,

var a = _user.userLocation() as Map;
print(a['location]['city']);

我这里的问题是 dart 的 type inference 无法自动识别类型。所以它给出了错误。但是上面的解决方案应该可以工作

【讨论】:

  • 有什么方法可以从一开始就设置as Map;?我正在使用Get和final UserInfoController _userInfoController = Get.find();,如果可能的话,我想在顶部导入它们时说明它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 1970-01-01
  • 2021-06-11
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多