Raph117
Raph117

Reputation: 3821

Retrieve class parameter using a string in Dart

Let's say that I have a class in Dart that looks like this:

class Hello {

  final name;

  Hello({this.name});

}

I could create an instance of this class using:

var x = new Hello(name: "General Kenobi");

In Javascript, I could retrieve the name property with syntax like this:

console.log(x["name"]);

Is there a way to do the equivalent in Dart? I.e

print(x["name"]); 

I've looked at the docs and can't find anything, would appreciate help from someone who knows. Many thanks.

Upvotes: 1

Views: 374

Answers (1)

Owczar
Owczar

Reputation: 2593

The easiest way is to create a method, which converts a class to Map and overload [] operator:

class Hello {
  final name;

  Hello({this.name});

  Map<String, dynamic> toMap() => {'name': name};

  operator [](String field) => toMap()[field];
}

Upvotes: 1

Related Questions