0

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?

4
  • why do you want to access it using string? is not the current syntax enough for your use case? Commented Feb 29, 2020 at 8:50
  • 1
    and a simple switch case statement can convert those strings into class members if you really want to access class members using string id. Commented Feb 29, 2020 at 8:51
  • I only get name from api without id Commented Feb 29, 2020 at 8:52
  • yes, you can compare the string name using if-else statement or switch statement or crate a map of elements. Commented Feb 29, 2020 at 9:01

2 Answers 2

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];
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.