accessing object values using variable as a key

前端 未结 2 1474
野趣味
野趣味 2021-01-24 04:58

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

<
相关标签:
2条回答
  • 2021-01-24 05:23

    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'];
    
    0 讨论(0)
  • 2021-01-24 05:48

    You cannot access class members by a string containing their name. (Except with mirrors - outside the scope of this answer.)

    You could remove the class altogether and just use a Map<String, String>.

    Map<String, String> movie = {
      'movieTitle': 'Toy Story',
      'actor': 'Tom Hanks',
    }
    

    You could add some bool methods on the class.

    bool hasNoActor() => actor == null;
    ...
    List values = movieList.where((m) => !m.hasNoActor()).toList();
    

    Or, you could pass a lambda to your mapper.

      Movie movieTitle = Movie()
        ..name = 'Toy Story'
        ..actor = 'Tom Hanks';
    
      Function hasActor = (Movie m) => m.actor != null;
      List values = movieList.where(hasActor).toList();
    
    0 讨论(0)
提交回复
热议问题