如何在Dart和Flutter中实现用户输入列表与色觉预设列表的对比?
问题说明
需要将用户输入的列表与normalList、protanList、deutanList、tritanList四个预设列表对比,匹配规则如下:
- 输入为1-15的正确顺序 → 输出Normal
- 输入匹配
[15,14,1,2,13,12,3,4,11,10,5,6,9,8,7]→ 输出Protan - 输入匹配另外两个预设列表时,分别输出Deutan和Tritan
目前现有代码逻辑不完整,需要完善。
现有代码
late List<Box> opaqueBoxes = []; //to be filled //assume opaqueBoxes being input by user here //the result method is to compare the outcome of the result String result() { String result = ''; if (listEquals(normalList, opaqueBoxes)) { result = "Normal"; } else { result = "Protan"; } if (kDebugMode) { print(result); } return result; } //here is the list of the correct one var normalList = [ "1", "2", "3", "4", "5", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" ]; var protanList = [ "15", "14", "1", "2", "13", "12", "3", "4", "11", "10", "5", "6", "9", "8", "7" ]; var deutanList = [ "1", "15", "2", "3", "14", "13", "4", "12", "5", "6", "11", "10", "7", "9", "8" ]; var tritanList = [ "1", "2", "3", "4", "5", "6", "7", "15", "8", "14", "9", "13", "10", "11", "12" ];
完善方案及代码
核心修改点
- 类型统一:
opaqueBoxes是List<Box>类型,预设列表是List<String>,需先将用户输入转换为字符串列表再对比(假设Box类有text属性存储数字)。 - 修复预设列表错误:原
normalList存在重复的"5",修正为正确的1-15序列。 - 完善判断逻辑:补充
Deutan和Tritan的匹配分支,增加无匹配时的默认返回值。 - 优化结构:用Map存储预设列表与结果的映射,提升可维护性。
完整代码
import 'package:flutter/foundation.dart'; // 假设你的Box类定义如下,若实际属性不同需对应调整 class Box { final String text; Box(this.text); } late List<Box> opaqueBoxes = []; // 用户输入的Box列表 // 修正后的预设列表 final normalList = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" ]; final protanList = [ "15", "14", "1", "2", "13", "12", "3", "4", "11", "10", "5", "6", "9", "8", "7" ]; final deutanList = [ "1", "15", "2", "3", "14", "13", "4", "12", "5", "6", "11", "10", "7", "9", "8" ]; final tritanList = [ "1", "2", "3", "4", "5", "6", "7", "15", "8", "14", "9", "13", "10", "11", "12" ]; // 映射表:预设列表 → 对应结果 final listResultMap = { normalList: "Normal", protanList: "Protan", deutanList: "Deutan", tritanList: "Tritan", }; String result() { // 将用户输入的Box列表转为字符串列表 final userInputStrings = opaqueBoxes.map((box) => box.text).toList(); // 遍历映射表查找匹配项 for (final entry in listResultMap.entries) { if (listEquals(entry.key, userInputStrings)) { final matchedResult = entry.value; if (kDebugMode) { print(matchedResult); } return matchedResult; } } // 无匹配时返回默认值 final defaultResult = "Unknown"; if (kDebugMode) { print(defaultResult); } return defaultResult; }
注意事项
- 若
Box类存储数字的属性不是text,请修改box.text为实际属性名(比如box.number.toString()如果存储的是数字类型)。 - 若需要调整匹配规则或新增类型,只需在
listResultMap中添加新的键值对即可。
内容的提问来源于stack exchange,提问作者grizzzzzy
相关产品推荐
相关产品推荐

