How to use Strings to access class members in Flutter
As described here, you would need have access to the dart:mirrors
pacakage, which is not avaible in Flutter.
A solution that would work in Flutter is creating a helper method. This means that you will have to code in cases for all icon names you want to use. If you do not want to write all of that by hand, you can take a look at a package like reflectable
as mentioned in the GitHub comment or potentially source_gen
or build_runner
, however, I am not sure if the latter two are well suited.
Anyways, what you could also write by hand is a helper function like this:
IconData fontAwesomeIconFromString(String name) {
switch (name) {
case 'suitecase':
return FontAwesomeIcons.suitecase;
case 'gamepad':
return FontAwesomeIcons.gamepad;
// ...
}
}
In your code, you can now use it like this:
String iconfromApi = 'suitcase';
Icon(fontAwesomeIconFromString(iconFromApi));
Santhosh
Updated on December 12, 2022Comments
-
Santhosh over 1 year
I want to set use Strings from an API as Fontawesome icons. I have added the
font_awesome_flutter plugin
.
I need to store the icon name in a variable and then create an object from it. I would imagine it to like this:String iconfromApi = 'suitcase'; Icon(FontAwesomeIcons.iconfromApi);
-
Santhosh almost 5 yearsit sounds good... it suits for less icons.. but in large cases means how can we go..?