Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a property by this name in String?

Tags:

flutter

dart

I want to access to a property by the name si string format.

If I have a class like that:

class PrefsState {
  String a;

  PrefsState({
    this.a,

  })

How can I do something like that:

PrefsState test= PrefsState(a: "it is a test");
String key = "a";

print(test[key]);

Of course is not working. There is a way to do that in Dart ?

like image 535
Darkjeff Avatar asked Mar 31 '19 21:03

Darkjeff


1 Answers

Unfortunately, you cannot use reflection/mirrors in flutter. What you can do, which is tedious, is use maps.

class PrefsState { 
   String a; 
   const PrefsState({ this.a, });
   dynamic getProp(String key) => <String, dynamic>{
    'a' : a,
    }[key];
}

It's probably better to build the map in the constructor, but if you want const constructors then you'll have to settle for this. Likely won't make much of a difference unless you have a million parameters anyway. Then you use it like so:

PrefsState test= PrefsState(a: "it is a test");
String key = "a"; 
print(test.getProp(key));

I don't think there is a less cumbersome way of doing this, but would love to be proven wrong :-)

like image 157
Cyclonus Avatar answered Nov 15 '22 10:11

Cyclonus