Dart中map方法遍历列表无控制台输出?问题排查与解决
问题分析与解决
问题出在map方法的使用,和async-await无关。
Dart中的map方法是惰性执行的——它只会返回一个迭代器对象,不会自动遍历执行回调里的代码。你当前的代码只是创建了这个迭代器,但没有触发它的遍历逻辑,所以print(e)根本没被执行。
可行的解决方式
方式一:用forEach替代map
如果你的需求只是遍历列表执行打印操作(不需要生成新的集合),forEach是更直接的选择,它会立即遍历每个元素并执行回调:
lists.forEach((e) { print(e); });
方式二:强制触发map的迭代
如果一定要用map,可以调用toList()、toSet()这类方法,强制迭代并生成新集合,这样回调里的代码就会执行:
lists.map((e){ print(e); }).toList();
额外优化:重写toString()
如果IconList类没重写toString(),打印出来的结果会是Instance of 'IconList',看不到具体数据。建议给类添加toString方法:
class IconList { String iconPass; int status; String memo; DateTime createdAt; String title; String? subTitle; IconList({ required this.iconPass, required this.status, required this.memo, required this.createdAt, required this.title, this.subTitle, }); @override String toString() { return 'IconList(iconPass: $iconPass, status: $status, memo: $memo, createdAt: $createdAt, title: $title, subTitle: $subTitle)'; } }
内容的提问来源于stack exchange,提问作者SugiuraY
相关产品推荐
相关产品推荐

