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

Flutter烹饪应用如何为现有Meal类新增适用用餐人数属性

代码修改方案

你可以根据后续拓展需求选择以下两种实现方式:

方案1:枚举实现(推荐,适配你当前固定1/2/3人的需求,类型安全无非法值)

  1. 新增适用人数枚举,和现有Complexity枚举同级定义:
enum ServingSize {
  onePerson,
  twoPersons,
  threePersons,
}
  1. 在Meal类中新增对应属性:
final ServingSize servings;
  1. 在构造函数中补充该参数配置,如果要兼容旧代码可以加默认值:
const Meal({
  required this.id,
  required this.categories,
  required this.title,
  required this.imageUrl,
  required this.ingredients,
  required this.steps,
  required this.duration,
  required this.complexity,
  // 新增参数,需要必填就加required,不需要就加默认值
  required this.servings,
  // 可选默认值写法:this.servings = ServingSize.twoPersons,
  required this.isGlutenFree,
  required this.isLactoseFree,
  required this.isVegan,
  required this.isVegetarian,
});

方案2:int类型实现(适合后续可能拓展更多人数的场景)

如果后续可能支持3人以上的适用规格,可以直接用int类型,同时加断言限制数值范围:

  1. 新增int类型属性:
final int servings;
  1. 构造函数补充参数和校验:
const Meal({
  required this.id,
  required this.categories,
  required this.title,
  required this.imageUrl,
  required this.ingredients,
  required this.steps,
  required this.duration,
  required this.complexity,
  required this.servings,
  required this.isGlutenFree,
  required this.isLactoseFree,
  required this.isVegan,
  required this.isVegetarian,
}) : assert(servings >= 1 && servings <= 3, '适用人数仅支持1-3人');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 21:45:02