You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中返回Post模型列表?

如何在Flutter中将JSON响应转换为Post模型列表

没问题,我来一步步教你搞定在Flutter里把你提供的JSON响应转换成Post模型列表的事儿,这样你就能在代码里轻松使用这些数据了~

第一步:定义Post模型类

首先你得创建一个和JSON结构对应的Post类,包含所有需要的字段,再实现一个fromJson构造函数,用来把单个JSON对象转换成Post实例;如果之后需要把Post对象转回JSON,也可以加上toJson方法。

class Post {
  final int userId;
  final int id;
  final String title;
  final String body;

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

  // 从JSON对象生成Post实例
  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      userId: json['userId'] as int,
      id: json['id'] as int,
      title: json['title'] as String,
      body: json['body'] as String,
    );
  }

  // 可选:将Post实例转回JSON
  Map<String, dynamic> toJson() {
    return {
      'userId': userId,
      'id': id,
      'title': title,
      'body': body,
    };
  }
}

第二步:解析JSON列表并转换为Post列表

接下来,你需要先获取到JSON响应(通常通过网络请求,比如用http包),然后把JSON字符串解码成列表,再逐个转成Post对象。

示例网络请求与解析代码

import 'dart:convert';
import 'package:http/http.dart' as http;

// 异步获取并解析Posts的方法
Future<List<Post>> fetchPosts() async {
  // 替换成你的实际API地址,示例用JSONPlaceholder的接口
  final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));

  if (response.statusCode == 200) {
    // 把JSON字符串解码成动态列表
    List<dynamic> jsonPosts = json.decode(response.body);
    // 遍历列表,将每个JSON对象转成Post实例,最后返回Post列表
    return jsonPosts.map((postJson) => Post.fromJson(postJson)).toList();
  } else {
    // 请求失败时抛出异常,方便后续处理错误
    throw Exception('加载帖子失败,请稍后重试');
  }
}

第三步:在UI中使用Post列表

你可以用FutureBuilder来处理异步获取的Post列表,在UI里展示数据:

class PostsScreen extends StatefulWidget {
  const PostsScreen({super.key});

  @override
  State<PostsScreen> createState() => _PostsScreenState();
}

class _PostsScreenState extends State<PostsScreen> {
  late Future<List<Post>> futurePosts;

  @override
  void initState() {
    super.initState();
    // 初始化时发起请求
    futurePosts = fetchPosts();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('帖子列表')),
      body: FutureBuilder<List<Post>>(
        future: futurePosts,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            // 数据加载成功,展示列表
            return ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) {
                final post = snapshot.data![index];
                return ListTile(
                  title: Text(post.title),
                  subtitle: Text(post.body),
                  leading: CircleAvatar(child: Text('${post.userId}')),
                );
              },
            );
          } else if (snapshot.hasError) {
            // 加载失败,展示错误信息
            return Center(child: Text('出错了:${snapshot.error}'));
          }
          // 加载中,展示加载指示器
          return const Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

进阶:用json_serializable自动生成序列化代码

如果你的项目比较复杂,手动写fromJson和toJson容易出错,推荐使用json_serializable包来自动生成这些代码:

  1. 在pubspec.yaml中添加依赖:
dependencies:
  json_annotation: ^4.8.1

dev_dependencies:
  build_runner: ^2.4.4
  json_serializable: ^6.7.0
  1. 修改Post类:
import 'package:json_annotation/json_annotation.dart';

// 这个文件会由build_runner自动生成,不用手动创建
part 'post.g.dart';

@JsonSerializable()
class Post {
  final int userId;
  final int id;
  final String title;
  final String body;

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

  // 自动生成的fromJson方法
  factory Post.fromJson(Map<String, dynamic> json) => _$PostFromJson(json);

  // 自动生成的toJson方法
  Map<String, dynamic> toJson() => _$PostToJson(this);
}
  1. 运行命令生成代码:
flutter pub run build_runner build

这样就不用手动维护序列化代码啦,省心又不容易出错~

内容的提问来源于stack exchange,提问作者Syed Babar Khurshid Anwer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 06:37:26