accessing object values using variable as a key

前端 未结 2 1476
野趣味
野趣味 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: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.

    Map 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();
    

提交回复
热议问题