使用变量作为键访问对象值 [英] accessing object values using variable as a key

查看:71
本文介绍了使用变量作为键访问对象值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以前在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

在Java语言中,我将使用如下变量访问对象值:

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


推荐答案

包含其名称的字符串。 (带镜子-不在此答案范围内。)

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

您可以完全删除该类,而只需使用 Map< String,String>

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

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

您可以在类中添加一些 bool 方法。

You could add some bool methods on the class.

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

或者,您可以将lambda传递给映射器。

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

这篇关于使用变量作为键访问对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆