How to get a Class name dynamically (from a string) in Dart, then create an instance?

只谈情不闲聊 提交于 2019-12-06 11:27:37

One way to do it, is:

library my_library;

import 'dart:mirrors';

void main() {
  var userInput = 'MyClass';
  var symbol = new Symbol(userInput);
  var myClasses = currentMirrorSystem().findLibrary(#my_library).declarations.values.where((dm) => dm is ClassMirror);
  var cm = myClasses.firstWhere((cm) => cm.simpleName == symbol);
  var instance = cm.newInstance(const Symbol(''), []).reflectee;
}

class MyClass {}

If you compile to JS, you should also look into using @MirrorsUsed otherwise the size of the generated JS will be quite large.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!