如何在 Flutter 中使用字符串访问 class 个成员
How to use Strings to access class members in Flutter
我想设置使用 API 中的字符串作为 Fontawesome 图标。我添加了 font_awesome_flutter plugin
.
我需要将图标名称存储在一个变量中,然后从中创建一个对象。我会想象它是这样的:
String iconfromApi = 'suitcase';
Icon(FontAwesomeIcons.iconfromApi);
作为 described here,您需要访问 dart:mirrors
包,这在 Flutter 中不可用。
适用于 Flutter 的解决方案是创建辅助方法。这意味着您必须为要使用的所有图标名称编写案例代码。如果你不想手写所有这些,你可以看看像reflectable
as mentioned in the GitHub comment or potentially source_gen
or build_runner
这样的包,但是,我不确定后两者是否适合。
反正你也可以手写一个这样的辅助函数:
IconData fontAwesomeIconFromString(String name) {
switch (name) {
case 'suitecase':
return FontAwesomeIcons.suitecase;
case 'gamepad':
return FontAwesomeIcons.gamepad;
// ...
}
}
在您的代码中,您现在可以像这样使用它:
String iconfromApi = 'suitcase';
Icon(fontAwesomeIconFromString(iconFromApi));
我想设置使用 API 中的字符串作为 Fontawesome 图标。我添加了 font_awesome_flutter plugin
.
我需要将图标名称存储在一个变量中,然后从中创建一个对象。我会想象它是这样的:
String iconfromApi = 'suitcase';
Icon(FontAwesomeIcons.iconfromApi);
作为 described here,您需要访问 dart:mirrors
包,这在 Flutter 中不可用。
适用于 Flutter 的解决方案是创建辅助方法。这意味着您必须为要使用的所有图标名称编写案例代码。如果你不想手写所有这些,你可以看看像reflectable
as mentioned in the GitHub comment or potentially source_gen
or build_runner
这样的包,但是,我不确定后两者是否适合。
反正你也可以手写一个这样的辅助函数:
IconData fontAwesomeIconFromString(String name) {
switch (name) {
case 'suitecase':
return FontAwesomeIcons.suitecase;
case 'gamepad':
return FontAwesomeIcons.gamepad;
// ...
}
}
在您的代码中,您现在可以像这样使用它:
String iconfromApi = 'suitcase';
Icon(fontAwesomeIconFromString(iconFromApi));