Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Icon, based on JSON string value?

Tags:

json

flutter

dart

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',
},
like image 911
Anandh Krishnan Avatar asked Sep 14 '25 06:09

Anandh Krishnan


1 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.

  • Flutter_iconpicker

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;
  }
like image 152
yaguarete Avatar answered Sep 16 '25 20:09

yaguarete