Flutter基础(前端教程①④-data.map和assignAll和fromJson和toList)

发布于:2025-07-21 ⋅ 阅读:(14) ⋅ 点赞:(0)

1. data.map((item) => ...)

作用:遍历一个列表,把每个元素「转换」成另一种形式。
类比:就像工厂的流水线,每个产品经过加工变成新的样子。

// 原始数据
final numbers = [1, 2, 3];

// 把每个数字变成它的平方
final squared = numbers.map((num) => num * num);

print(squared); // 输出: (1, 4, 9)

在你的代码中
把 JSON 对象列表 → 转换为 Post 模型列表。

final jsonList = [{"id":1,"title":"post1"},{"id":2,"title":"post2"}];

// 把每个 JSON 对象转换为 Post 实例
final posts = jsonList.map((item) => Post.fromJson(item));

2. assignAll()

作用:把一个新列表「替换」掉 GetX 控制器里的旧列表,并触发 UI 更新。
类比:就像给书架换一批新书,换完后马上通知所有人来看。

// 假设 controller.posts 是 RxList<Post>
final newPosts = [Post(id:1, title:"..."), Post(id:2, title:"...")];

// 替换旧列表并通知 UI 更新
controller.posts.assignAll(newPosts);

对比普通赋值

// 普通赋值:不会触发 UI 更新
controller.posts = newPosts; // ❌ 错误

// 使用 assignAll:触发 UI 更新
controller.posts.assignAll(newPosts); // ✅ 正确

3. fromJson()

作用:把 JSON 数据(Map)「解析」成 Dart 对象。
类比:就像把说明书翻译成你能看懂的语言。

class Post {
  final int id;
  final String title;

  Post({required this.id, required this.title});

  // 工厂方法:从 JSON 解析
  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],       // 从 JSON 中取 id 字段
      title: json['title'], // 从 JSON 中取 title 字段
    );
  }
}

// 使用示例
final json = {"id": 1, "title": "Hello"};
final post = Post.fromJson(json);

print(post.title); // 输出: Hello

4. toList()

作用:把 map() 后的结果「转换」成真正的列表(List)。
类比:就像把生产线上的产品装箱打包,变成可以直接用的商品。

// 原始数据
final numbers = [1, 2, 3];

// 先 map 转换,再 toList 装箱
final squaredList = numbers
  .map((num) => num * num) // 转换为 (1, 4, 9)
  .toList();              // 转换为 [1, 4, 9]

print(squaredList); // 输出: [1, 4, 9](注意中括号)

1. 原始数据(JSON 列表)

假设从 API 获取的原始数据是这样的:

final jsonList = [
  {"id": 1, "title": "Post 1"},
  {"id": 2, "title": "Post 2"}
]; // 这是一个 List<Map<String, dynamic>>
2. map() 转换过程

map() 会遍历列表中的每个 JSON 对象(Map),并通过 fromJson() 转换为 Post 对象:

jsonList.map((item) => Post.fromJson(item))

// 等价于:
[
  Post.fromJson({"id": 1, "title": "Post 1"}),
  Post.fromJson({"id": 2, "title": "Post 2"})
]

// 转换后得到:
(Post(id:1, title:"Post 1"), Post(id:2, title:"Post 2"))

注意:此时的结果是一个 Iterable<Post>(用小括号表示),还不是真正的 List

3. toList() 最终转换

toList() 会把 Iterable<Post> 变成真正的 List<Post>

(Post(id:1, title:"Post 1"), Post(id:2, title:"Post 2"))
  .toList()

// 最终得到:
[Post(id:1, title:"Post 1"), Post(id:2, title:"Post 2")]

为什么需要 toList()

  1. map() 的返回值是 Iterable
    Dart 中的 map() 方法返回的是 Iterable,这是一个更通用的集合接口,不支持 List 的所有操作(如 add()remove())。

  2. ListView 要求 List 类型
    Flutter 的 ListView.builder() 需要传入 List 类型的数据:

ListView.builder(
  itemCount: posts.length, // 必须是 List 才能用 .length
  itemBuilder: (context, index) => Text(posts[index].title),
);

GetX 的 assignAll() 也要求 List

controller.posts.assignAll(posts); // 必须传入 List<Post>