How to set Icon based on JSON string value?

Viewed 648

I will get the icon name from the backend as part of a JSON.

How can I set the icon based on the JSON value?

The JSON will have more than 500 different values, so I can't use a switch or if/else.

This is what the JSON looks like:

{
  'name': 'Address',
  'icon': 'fa-address-card-o',
},
{
  'name': 'Attendance',
  'icon': 'fa-clock-o',
},
{
  'name': 'Facebook',
  'icon': 'fa-facebook',
},
{
  'name': 'Campaign',
  'icon': 'fa-bullhorn',
},
{
  'name': 'Calls',
  'icon': 'fa-phone-square',
},
3 Answers

If you are the owner of the backend that sends the JSON, you can modify it in order to send codePoints instead of string.

Example:

{
  'name': 'Sports',
  'icon': '0xe1dc',
},
{
  'name': 'Politics',
  'icon': '0xe2d3',
},
{
  'name': 'Science',
  'icon': '0xe6d9',
},

Then serialise the JSON to return the IconData

IconData getIconData(Map<String, dynamic> icon) {
  return IconData(
    icon['icon'],
    fontFamily: 'MaterialIcons'
  );
}

You can the invoke the function on demand:

Icon(getIconData(yourJSONContainingIcons));

You may read more about it in the following link

There's a very nice package I use myself, the downside and greatness depending on your needs is that it comes with several fontFamily Icons (LineAwesome, FontAwesome) leafing your app size.

This is great if you want the user to have bast alternatives of icons to choose from, bellow you can find a quick snippet on how to use it:

Future<IconData?> pickIcon() async {
    await Notifications().bubble(
        text: 'It might take few seconds, loading ${[
      IconPack.lineAwesomeIcons,
      IconPack.material,
      IconPack.fontAwesomeIcons
    ].length} icons.');

    final icon = await FlutterIconPicker.showIconPicker(
      Get.context!,
      adaptiveDialog: true,
      showTooltips: true,
      showSearchBar: true,
      iconPickerShape:
          RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      iconSize: 18,
      crossAxisSpacing: 10,
      iconPackModes: [
        IconPack.lineAwesomeIcons,
        IconPack.material,
        IconPack.fontAwesomeIcons
      ],
      title: TextWidget(
        text: 'pick_icon',
        font: 'Roboto',
      ),
    );

    return icon;
  }

You can't invoke Icon constants using String, here's the relevant thread on GitHub.

Since the API you're using already hosts the icon names to be used, you may want to consider having the backend team send the icon's location as well on their API, returning wherever the icon is hosted. Your app can then download the icon to be used.

Flutter can't access icons similar to how it's done on web. The icons used in Flutter is bundled with the SDK.

If you already know the set of possible icons, you can create a (big) map of the icon strings to the corresponding icon, and then use the returned icon string as a key to look up the map.

Related