如何从API返回的JSON中提取title与description填充到Flutter Text组件
JSON解析及Flutter组件填充实现方案
你需要用到Dart内置的dart:convert库完成解析,无需引入第三方依赖,具体操作如下:
1. 定义数据实体类
创建和JSON结构匹配的实体类,内置fromJson转换方法:
class Post { final int id; final String title; final String description; final DateTime createdAt; final DateTime updatedAt; Post({ required this.id, required this.title, required this.description, required this.createdAt, required this.updatedAt, }); factory Post.fromJson(Map<String, dynamic> json) { return Post( id: json['id'] as int, title: json['title'] as String, description: json['description'] as String, createdAt: DateTime.parse(json['created_at']), updatedAt: DateTime.parse(json['updated_at']), ); } }
2. 解析接口返回的JSON数据
拿到接口响应字符串后,按如下方式转换为实体对象:
import 'dart:convert'; // 此处apiResponseBody为你调用接口获取到的响应字符串 List jsonList = jsonDecode(apiResponseBody); // 你的返回结构为数组,取第一条数据转换为Post实体 Post currentPost = Post.fromJson(jsonList.first); // 如果你是在StatefulWidget中使用,解析完成后调用setState更新状态 setState(() { // 把currentPost赋值给State类的全局属性 this.currentPost = currentPost; });
3. 填充数据到Text组件
修改你现有的组件代码,把解析后的字段填入Text的参数中即可:
Column( children: [ Container( margin: EdgeInsets.only(top: 52.w, right: 25.w, left: 25.w), padding: EdgeInsets.symmetric(horizontal: 20.w), width: 355.w, child: Text( currentPost.title, style: TextStyle(color: Colors.white, fontSize: 29.sp), ), ), Container( margin: EdgeInsets.only(top: 20.w, right: 25.w, left: 25.w), padding: EdgeInsets.symmetric(horizontal: 20.w), width: 319.w, child: Text( currentPost.description, style: TextStyle(color: Colors.white, fontSize: 16.sp), ), ), ], )
如果需要处理加载空状态,可将currentPost定义为可空类型Post? currentPost,Text处使用currentPost?.title ?? '加载中'做占位处理即可。
内容的提问来源于stack exchange,提问作者хэлоу
相关产品推荐
相关产品推荐

