Flutter Dart - dynamically get a property of a class

7,516

Further to Suman's answer I recommend exposing a method that converts the object to a map and retrieves the property if it's there.

For example:


class Person {
  String name;
  int age;

  Person({this.age, this.name});

  Map<String, dynamic> _toMap() {
    return {
      'name': name,
      'age': age,
    };
  }

  dynamic get(String propertyName) {
    var _mapRep = _toMap();
    if (_mapRep.containsKey(propertyName)) {
      return _mapRep[propertyName];
    }
    throw ArgumentError('propery not found');
  }
}

main() {
  Person person = Person(age: 10, name: 'Bob');

  print(person.name); // 'Bob'

  print(person.get('name')); // 'Bob'
  print(person.get('age')); // 10

  // wrong property name
  print(person.get('wrong')); // throws error
}


Share:
7,516
Mehran Ishanian
Author by

Mehran Ishanian

Updated on December 15, 2022

Comments

  • Mehran Ishanian
    Mehran Ishanian over 1 year

    I would like to get the property of a class by passing a String name. How can I do that?

    class A {
      String fName ='Hello';
    }
    
    main() {
    A a = A();
    String var1='fName'; // name of property of A class
    
    print (a.fName); // it is working fine
    
    print (a.$var1); // it is giving error that no getter in A class. but I want to pass var1 and automatically get the associate property
    
    }