简体   繁体   中英

how to get a string for a class property name in dart?

i want to do use the model's properties such as: Animal.id as a param to a function or use some extension method to be able to "id". similarly, i'd like to use Animal.title in that way to get "title" as a returned value. how could i do this with my class to get a string for any given property name?

  int _id;
  String _title;

  Animal(this._id, this._title);

  int get id => _id;
  String get title => _title;
}

the usage case is being able to query without having autocomplete on my model's property names in a string for sql querying:

List<Map> results = await db.query("Animal",
        columns: Set. ["id", "title"],
        where:  'id = ?',
        whereArgs: [id]);

Using the dart:mirrors package you can dynamically access your class properties and invoke methods using their string names.

https://api.dart.dev/stable/2.4.0/dart-mirrors/dart-mirrors-library.html


import 'dart:mirrors';

class Animal {
  int _id;
  String _title;

  Animal(this._id, this._title);

  int get id => _id;
  String get title => _title;
}

main() {
  var r = reflect(Animal(1, 'Dog'));

  print(r.getField(Symbol('id')).reflectee);
  print(r.getField(Symbol('title')).reflectee);
}

import 'dart:mirrors';

class MyClass {
  int i, j;
  void my_method() {  }

  int sum() => i + j;

  MyClass(this.i, this.j);

  static noise() => 42;

  static var s;
}

main() {
  MyClass myClass = new MyClass(3, 4);
  InstanceMirror myClassInstanceMirror = reflect(myClass);

  ClassMirror MyClassMirror = myClassInstanceMirror.type;

  InstanceMirror res = myClassInstanceMirror.invoke(#sum, []);
  print('sum = ${res.reflectee}');

  var f = MyClassMirror.invoke(#noise, []);
  print('noise = $f');

  print('\nMethods:');  
  Iterable<DeclarationMirror> decls =
      MyClassMirror.declarations.values.where(
        (dm) => dm is MethodMirror && dm.isRegularMethod);
  decls.forEach((MethodMirror mm) {
    print(MirrorSystem.getName(mm.simpleName));
  });

  print('\nAll declarations:');
  for (var k in MyClassMirror.declarations.keys) {
    print(MirrorSystem.getName(k));
  }

  MyClassMirror.setField(#s, 91);
  print(MyClass.s);
}

the output:

sum = 7
noise = InstanceMirror on 42

Methods:
my_method

sum

noise

All declarations:
i
j
s
my_method

sum
noise
MyClass
91

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM