You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter开发中无需大量if-then逻辑实现餐厅功能与图标映射方案咨询

方案1:轻量Map实现(适合规则简单无需额外配置的场景)

把关键词和对应图标的映射关系存在Map中统一维护,相比大量堆叠的三目运算可读性和可维护性高很多,注意把长关键词放在映射前侧,避免短关键词提前命中导致匹配错误。

// 定义关键词-图标映射规则
final Map<String, IconData> featureIconMap = {
  'game day': Icons.sports,
  'family': Icons.family_restroom_rounded,
  'menu': Icons.food_bank,
  'delivery': Icons.delivery_dining,
  // 后续新增匹配规则直接在当前Map中添加即可
};

// 封装图标匹配工具方法
IconData getFeatureIcon(String featureName) {
  final lowerFeature = featureName.toLowerCase();
  for (final entry in featureIconMap.entries) {
    if (lowerFeature.contains(entry.key.toLowerCase())) {
      return entry.value;
    }
  }
  // 兜底返回默认图标
  return Icons.info_outline_rounded;
}

调用方式:

Icon(getFeatureIcon(loadedRestaurant.restFeatureList![index].toString()))

方案2:自定义配置类实现(适合需要扩展更多属性的场景)

如果后续需要给功能项额外配置图标颜色、提示文案、跳转逻辑等属性,可以用自定义类存储匹配规则,扩展性更强:

// 定义功能项匹配规则类
class RestaurantFeatureRule {
  final String matchKeyword;
  final IconData icon;
  final Color? iconColor;
  final String? tooltip;

  const RestaurantFeatureRule({
    required this.matchKeyword,
    required this.icon,
    this.iconColor,
    this.tooltip,
  });
}

// 定义规则列表,优先级高的规则放在前侧
final List<RestaurantFeatureRule> featureRules = [
  RestaurantFeatureRule(
    matchKeyword: 'game day',
    icon: Icons.sports,
    iconColor: Colors.orange,
    tooltip: '赛事观赛专区',
  ),
  RestaurantFeatureRule(
    matchKeyword: 'family',
    icon: Icons.family_restroom_rounded,
    iconColor: Colors.blue,
    tooltip: '亲子友好门店',
  ),
  RestaurantFeatureRule(
    matchKeyword: 'menu',
    icon: Icons.food_bank,
    tooltip: '支持电子菜单',
  ),
];

// 封装匹配方法
RestaurantFeatureRule getFeatureConfig(String featureName) {
  final lowerFeature = featureName.toLowerCase();
  for (final rule in featureRules) {
    if (lowerFeature.contains(rule.matchKeyword.toLowerCase())) {
      return rule;
    }
  }
  // 兜底默认规则
  return const RestaurantFeatureRule(
    matchKeyword: 'default',
    icon: Icons.info_outline_rounded,
    tooltip: '其他服务',
  );
}

调用时可以直接拿到所有配置项:

final config = getFeatureConfig(loadedRestaurant.restFeatureList![index].toString());
return Tooltip(
  message: config.tooltip ?? '',
  child: Icon(config.icon, color: config.iconColor ?? Colors.grey),
);

两种方案都天然适配后端提前新增功能的场景:未匹配到的新增功能会自动走兜底逻辑,下次应用发版时在规则集合中添加对应配置即可生效,不需要修改核心匹配逻辑。

内容的提问来源于stack exchange,提问作者flutteRguy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:54:08