比较dart中的对象值数组?

时间:2019-07-17 09:19:12

标签: flutter dart

如何比较dart中的对象值数组?

main() {
  var datas = [{'name':'Andrew', 'age':31},{'name':'Dorian', 'age':27}];
  for( var data in datas){
    if(data['age'] > 27 ){
      print(data['age']);
    }
  }
}

由于该代码,我收到了此错误

The operator '>' isn't defined for the class 'Object'.
Try defining the operator '>'.dart(undefined_operator)

1 个答案:

答案 0 :(得分:1)

该错误表明您可以执行比较,因为编译器不知道data['age']的类型,您可以提取值并将其分配给使用as的int变量,将其转换为这个:

var datas = [
  {'name': 'Andrew', 'age': 31},
  {'name': 'Dorian', 'age': 27}
];
for (var data in datas) {
  int age = data['age'] as int;
  if (age > 27) {
    print(age);
  }
}

或者您可以声明指定其类型的数组,而不使用var

List<Map<String, dynamic>> datas = [
  {'name': 'Andrew', 'age': 31},
  {'name': 'Dorian', 'age': 27}
];
for (Map<String, dynamic> data in datas) {
  if (data['age'] > 27) {
    print(data['age']);
  }
}