Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter access model attribute using dynamic key [duplicate]

Tags:

dart

I'm trying to access a class value by using a variable previously defined in dart, but I keep getting the error the operator [] isn't defined for the class

In Javascript I would access an object value using a variable like this:

let movie = {
  movieTitle : 'Toy Story',
  actor: 'Tom Hanks'
}

let actorName = 'actor';
console.log(movie[actorName]); // <- what I'm trying to replicate in dart
// expected output: Tom Hanks

Here is what I've tried and is throwing that error

class Movie {
  String name;
  String actor;
  String producer;
}

void main() {
  var movieTitle = new Movie();
  movieTitle.name = 'Toy Story';
  movieTitle.actor = 'Tom Hanks';

  print(movieTitle.actor); <- prints out Tom Hanks as expected

  var actorName = 'actor';

  print(movieTitle[actorName]); <- throws error
}

I expect to be able to use a variable on the fly to access the value.

A trivial use case for me would be if I had a a list of Movie classes, where some actors and producers are null, I would like to filter on either non null actors or producer with a function like so:

List values = movieList.where((i) => i.actor != "null").toList(); // returns all Movies in movieList where the actor value isn't the string "null"

var actorIsNull = 'actor';

List values = movieList.where((i) => i[actorisNull] != "null").toList(); // throws error
like image 920
Adam Lichter Avatar asked Nov 17 '22 09:11

Adam Lichter


1 Answers

You can createn a toMap() function in your Movie class and access properties using [] operator

class Movie {
  String name;
  String actor;
  String producer;

  Map<String, dynamic> toMap() {
    return {
      'name': name,
      'actor' : actor,
      'producer' : producer,
    };
  }
}

Now Movie class properties can be accessed as:

Movie movie = Movie();
movie.toMap()['name'];
like image 192
brizzy_p Avatar answered Jun 27 '23 08:06

brizzy_p