How to access to element of a class by string name in flutter

不羁的心 提交于 2021-02-04 08:26:57

问题


I get name of font awesome from api that I want to access element of font_awesome_flutter package but I know it in C# but I do not know in flutter: received from server:

{
  "fontawesomeName":"breadSlice"
} 

in font_awesome package I can access its element by below

 IconButton(
            icon: FaIcon(FontAwesomeIcons.breadSlice),
             onPressed: () { print("Pressed"); }
           )

But How do I access element of object with string name in flutter?


回答1:


This is not possible in Flutter because reflection is disabled. The only way is to create a mapping. For example:

const Map<String, IconData> map = {
  "breadSlice": FontAwesomeIcons.breadSlice,
};

IconData getIcon(String iconName) {
  return map[iconName];
}



回答2:


Getting elements by their name in a string is called "reflection". I vaguely remember that regular Dart had it but Flutter's Dart did not.

However, this package may be helpful: https://pub.dev/packages/reflectable



来源:https://stackoverflow.com/questions/60463365/how-to-access-to-element-of-a-class-by-string-name-in-flutter

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