问题
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