Flutter中If语句与逻辑表达式失效问题排查
红牌显示逻辑不生效的问题排查与修复
核心问题:条件判断逻辑错误
你Widget代码里的if判断用了逻辑与(&&),但一个type不可能同时等于second-yellow和straight-red两个不同的值,导致这个条件永远不成立,红牌组件永远不会渲染,只会返回空的SizedBox。
修复方案
将判断条件中的&&改为逻辑或(||),只要type是两者中的任意一个,就渲染红牌:
修复后的Widget代码:
SizedBox( height: 11, child: Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: team.bookingSummary!.map((e) { // 替换&&为|| if (e.type == 'second-yellow' || e.type == 'straight-red') { return Row( mainAxisSize: MainAxisSize.min, children: List.generate(e.count!, (index) { return Padding( padding: const EdgeInsets.symmetric( horizontal: 4), child: AspectRatio( aspectRatio: 2 / 3, child: Container( decoration: BoxDecoration( border: Border.all( color: CustomTheme().neutral500, ), borderRadius: BorderRadius.circular(2), color: e.cardType, ), ), ), ); })); } else { return const SizedBox(); } }).toList(), ), ),
额外优化建议(可选)
你的模型类中,straight-red和second-yellow的处理逻辑完全一致,可以合并switch的case,让代码更简洁:
优化后的模型类fromJson方法:
BookingSummary.fromJson(Map<String, dynamic> json) { count = json['count']; type = json['type']; if (type != null) { switch (json['type']) { // 合并两个case,复用同一逻辑 case 'straight-red': case 'second-yellow': cardType = CustomTheme().logMoveDownRed; break; default: cardType = null; } } }
内容的提问来源于stack exchange,提问作者SaDev
相关产品推荐
相关产品推荐

