1

How to comparing array of object value in dart?

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

because with that code i got this error

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

1 Answer 1

1

The error says that you can not perform the comparison because the compiler doesn't know the type of data['age'], you can extract the value and assign it to an int variable using as to cast it like this:

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);
  }
}

Or you can declare the array specifying its type instead of using 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']);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.