accessing object values using variable as a key

前端 未结 2 1475
野趣味
野趣味 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 toMap() {
        return {
          'name': name,
          'actor' : actor,
          'producer' : producer,
        };
      }
    }
    

    Now Movie class properties can be accessed as:

    Movie movie = Movie();
    movie.toMap()['name'];
    

提交回复
热议问题