How to set Icon based on JSON string value?

223

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;
  }
Share:
223
Anandh Krishnan
Author by

Anandh Krishnan

Well, I’ve been working on mobile app development for four years now, Had my own projects, coded mostly in Android-Java and Flutter.

Updated on December 19, 2022

Comments

  • Anandh Krishnan
    Anandh Krishnan over 1 year

    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',
    },
    
  • Anandh Krishnan
    Anandh Krishnan about 2 years
    No, Its not possible, Only the icon name wil come
  • Anandh Krishnan
    Anandh Krishnan about 2 years
    is there any other way ?