如何在Map<String, dynamic>中存入List<Friend>的全部元素?
问题描述
现有以下Dart类定义:
class A { String? name; List<Friend> friends = []; A(this.name, this.friends); } class Friend { String? name; int? age; Map<String, dynamic> toMap() { return { "name" : this.name, "age" : this.age }; } Friend(this.name, this.age); }
我想要生成一个包含friends列表的Map<String, dynamic>,预期格式如下:
{ "name" : name, "friends" : [for(var f in friends) f.toMap()] }
但实际生成的Map里friends列表始终只有一个元素,而且列表长度不固定,没法逐个用索引添加元素。请问怎么才能把列表里的所有元素都存入Map?
解决方案
你可以用List.map()方法批量将Friend对象转为Map,再把转换后的结果转成List,这样就能确保所有元素都被处理。
在A类里新增一个toMap()方法来实现这个逻辑:
class A { String? name; List<Friend> friends = []; A(this.name, this.friends); Map<String, dynamic> toMap() { return { "name": name, "friends": friends.map((friend) => friend.toMap()).toList(), }; } }
关于你遇到的单元素问题
你写的[for(var f in friends) f.toMap()]这个集合字面量语法本身是正确的,出现仅一个元素的情况,大概率是因为你初始化A对象时传入的friends列表本身就只有一个元素,或者在生成Map之前不小心修改了friends列表的内容。
测试验证
void main() { // 创建多个Friend实例 final alice = Friend("Alice", 25); final bob = Friend("Bob", 28); final charlie = Friend("Charlie", 30); // 初始化A对象,传入包含三个Friend的列表 final person = A("John", [alice, bob, charlie]); // 转换为Map final result = person.toMap(); print(result); }
输出结果会包含所有三个好友的数据:
{name: John, friends: [{name: Alice, age: 25}, {name: Bob, age: 28}, {name: Charlie, age: 30}]}
内容的提问来源于stack exchange,提问作者yolo
相关产品推荐
相关产品推荐

