Flutter:List.map()中用if语句返回Widget遇类型不匹配问题解决
解决Flutter中Wrap组件children类型不匹配问题
问题原因
你这段代码里,map遍历listTask时,只有当e.day!.contains(value)为真时才返回Padding组件,不满足条件的元素会默认返回null,最终toList()得到的是List<Padding?>类型,但Wrap的children要求是List<Widget>(不允许包含null),所以触发了类型不匹配的错误。
解决方案
方案一:先过滤再转换(推荐)
先用where筛选出符合条件的元素,再对这些元素做map转换,这样最终生成的List里不会有null,类型完全匹配:
listTask.where((e) => e.day!.contains(value)).map((e) { return Padding( padding: const EdgeInsets.all(4.0), child: Container( decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.black), height: 20, width: 20, ), ); }).toList()
方案二:给else分支返回空Widget
如果需要保留遍历的所有元素(哪怕不满足条件),可以在if的else分支返回一个不可见的空Widget,确保每个遍历都返回Widget类型:
listTask.map((e) { if (e.day!.contains(value)) return Padding( padding: const EdgeInsets.all(4.0), child: Container( decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.black), height: 20, width: 20, ), ); return const SizedBox.shrink(); // 不占空间的空Widget }).toList()
方案三:过滤map结果中的null
导入dart:collection后,用nonNulls过滤掉map返回结果里的null值:
import 'dart:collection'; // 你的代码部分 listTask.map((e) { if (e.day!.contains(value)) return Padding( padding: const EdgeInsets.all(4.0), child: Container( decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.black), height: 20, width: 20, ), ); }).nonNulls.toList()
内容的提问来源于stack exchange,提问作者Knighthuy
相关产品推荐
相关产品推荐

