Flutter烹饪应用如何为现有Meal类新增适用用餐人数属性
代码修改方案
你可以根据后续拓展需求选择以下两种实现方式:
方案1:枚举实现(推荐,适配你当前固定1/2/3人的需求,类型安全无非法值)
- 新增适用人数枚举,和现有
Complexity枚举同级定义:
enum ServingSize { onePerson, twoPersons, threePersons, }
- 在
Meal类中新增对应属性:
final ServingSize servings;
- 在构造函数中补充该参数配置,如果要兼容旧代码可以加默认值:
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类型,同时加断言限制数值范围:
- 新增int类型属性:
final int servings;
- 构造函数补充参数和校验:
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
相关产品推荐
相关产品推荐

