【问题标题】:Add json response to a list in flutter将json响应添加到flutter中的列表
【发布时间】:2021-10-11 00:33:00
【问题描述】:

所以我正在使用来自 rest 服务的这个 API,它以以下 json 格式向我发送数据。

API 响应

"data": [
    {
        "id": 3,
        "title": "Lorem Ipsum Post",
        "excerpt": "This is the excerpt for the Lorem Ipsum Post",
        "body": "<p>This is the body of the lorem ipsum post</p>",
        "created_at": "2021-08-03T11:54:52.000000Z",
        "updated_at": "2021-08-03T11:54:52.000000Z"
    },
    {
        "id": 4,
        "title": "My Sample Post",
        "excerpt": "This is the excerpt for the sample Post",
        "body": "<p>This is the body for the sample post, which includes the body.</p>\n                <h2>We can use all kinds of format!</h2>\n                <p>And include a bunch of other stuff.</p>",
        "created_at": "2021-08-03T11:54:52.000000Z",
        "updated_at": "2021-08-03T11:54:52.000000Z"
    },
]

我使用以下方法将来自 api 响应的值插入到我以后需要使用的列表中。

我使用的方法

Future<List<Post>> getAllPosts(String token) async {
final ApiResponse apiResponse = await _apiBaseHelper.get(
    "https://test.sugayo.com/api/cg/posts/limit/3",token);
Post allPost=Post.fromJson(jsonDecode(apiResponse.data));
List<Post> allPostList=[Post(id: allPost.id, subtitle: allPost.subtitle, secondaryText: allPost.secondaryText, body: allPost.body)];
return allPostList;

}

在终端中我收到此错误 错误:需要一个“Map”类型的值,但得到一个“List”类型的值 并且返回的列表为空。请帮助

【问题讨论】:

标签: json list flutter dart


【解决方案1】:

由于响应是一个帖子列表,而不仅仅是一个帖子,你应该得到这样的列表:

Map<String, dynamic> result = json.decode(response.body);
List<Post> posts = List<Post>.from(result['data'].map((dynamic row) => Post.fromJson(row)));

【讨论】:

    【解决方案2】:
    Future<List<Post>> getAllPosts(String token) async {
    
    final ApiResponse apiResponse = await _apiBaseHelper.get(
        "https://test.sugayo.com/api/cg/posts/limit/3",token);
        
    final responsebody=jsonDecode(apiResponse.body) as List;
    
    final allPostList= responsebody['data'].map((e) => Post.fromJson(e)).toList();
    
    return allPostList;
    

    【讨论】:

    • 这是我的答案的复制过去
    猜你喜欢
    • 2023-01-17
    • 2021-09-30
    • 2021-09-02
    • 2019-04-30
    • 1970-01-01
    • 2016-07-30
    • 2013-08-11
    • 2020-01-06
    • 2015-03-16
    相关资源
    最近更新 更多