Home > Net >  Implementing icon-text mapping without a lot of "if-then" logic
Implementing icon-text mapping without a lot of "if-then" logic

Time:11-08

I'm creating a list of restaurant of features in my flutter app with a distinct icon for each. These aren't necessarily unique, as there is some repetition based on the feature (e.g. anything with "menu" returns a food icon).

I currently have this set up as a long series of if-then lookups based on the feature (see below), but surely there has to be a better way using a map or new class. Thanks for the help!

loadedRestaurant.restFeatureList![index].toString().toLowerCase().contains('family')
        ? Icons.family_restroom_rounded

: loadedRestaurant.restFeatureList![index].toString().toLowerCase().contains('game day') 
        ? Icons.sports
...

The resulting widget looks like this: Screenshot of restFeatureList

CodePudding user response:

something like this:

//mapping in some utils for example
final featureIcons = <String, IconData>{
      "family": Icons.family_restroom_rounded,
    }.entries;

    IconData getFeatureIcon(String feature) {
      return featureIcons
          .firstWhereOrNull((key) => key.key.toLowerCase().contains(feature))
          ?.value;
    }

// in your UI
    getFeatureIcon(loadedRestaurant.restFeatureList![index].toString());

CodePudding user response:

You can use an Map to store the feature an icon together and and gridView.Builder to create the list (need some tweaking with the result):


     List restFeatureList = [
          {'feature': "family", "icon": Icons.family_restroom_rounded},
          {'feature': "game_day", "icon": Icons.sports},
          {'feature': "veggie", "icon": Icons.park},
          {'feature': "outdoor", "icon": Icons.outdoor_grill}
        ];
    
        return Scaffold(
          backgroundColor: Colors.blue,
          body: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Center(
              child: Container(
                width: 200,
                height: 200,
                color: Colors.white,
                child: GridView.builder(
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                  ),
                  itemCount: restFeatureList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Row(
                      children: <Widget>[
                        Text('${restFeatureList[index]['feature']}'),
                        Icon(restFeatureList[index]['icon']),
                      ],
                    );
                  },
                ),
              ),
            ),
          ),
        );

  • Related