在没有大量 "if-then" 逻辑的情况下实现图标文本映射

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

更新:此问题中提到的功能列表的长度因特定餐厅而异。并非每家餐厅都具有相同的功能或相同数量的功能。

我正在我的 flutter 应用程序中创建一个餐厅功能列表,每个功能都有一个不同的图标。这些不一定是唯一的,因为有一些基于功能的重复(例如任何带有“菜单”returns 和 food 图标的东西)。

我目前将此设置为一长串基于 feature 的 if-then 查找(见下文)。当前系统有一个回退图标,表示给定功能没有映射到它的功能。 我们在应用商店中更新应用程序之前在后台添加功能,因此需要一种方法来处理尚无图标的新功能。

我相信一定有更好的方法使用 map 或新的 class。感谢您的帮助!

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

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

生成的小部件如下所示: Screenshot of restFeatureList

像这样:

//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());

您可以使用地图将功能和图标存储在一起,并 gridView.Builder 创建列表(需要对结果进行一些调整):


     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']),
                      ],
                    );
                  },
                ),
              ),
            ),
          ),
        );