Flutter http 获取请求json序列化

Posted

技术标签:

【中文标题】Flutter http 获取请求json序列化【英文标题】:Flutter http get request json serialization 【发布时间】:2021-08-05 14:25:49 【问题描述】:

我想发出一个获取请求并将结果转换为对象列表。 其实我是这样做的:

post_model.dart

@JsonSerializable()
class Post 

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

  factory Post.fromJson(Map<String, dynamic> json) => _$PostFromJson(json);
  Map<String, dynamic> toJson() => _$PostToJson(this);

  final int userId;
  final int id;
  final String title;
  final String body;
 

http_service.dart:

class HttpService 
  final String url = 'https://jsonplaceholder.typicode.com';
  final String postsURL = '/posts';
  final Map<String, String> headers = 
    'Content-Type': 'application/json'
  ;


  List<Post> parsePosts(String responseBody) 
    final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
    return parsed.map<Post>((json) => Post.fromJson(json)).toList();
  


  Future<List<Post>> fetchPosts() async 

    final http.Response response = await http.get(Uri.https(url, postsURL));

    if (response.statusCode == 200) 
      return compute(parsePosts,response.body);
     else 
      throw Exception("Failed to load posts $response.statusCode");
    
  



但我在 parsePosts 方法上全部用红色表示。 最后解析一下:

Missing variable type for 'parsed'.
Try adding an explicit type, or remove implicit-dynamic from your analysis options file.dart(implicit_dynamic_variable)

然后返回:

A value of type 'dynamic' can't be returned from the method 'parsePosts' because it has a return type of 'List<Post>'

我只是不明白我做错了什么,因为我在这里遵循了颤振文档: https://flutter.dev/docs/cookbook/networking/background-parsing

感谢您的帮助

【问题讨论】:

【参考方案1】:

前段时间我为那个 API 编写了这段代码:

import 'dart:async';

import 'package:wnetworking/wnetworking.dart';


class Post 
  int? userId, id;
  String? title, body;

  Post.fromJson(Map<String, dynamic> data) 
    userId = data['userId'];
    id = data['id'];
    title = data['title'];
    body = data['body'];
  


class JsonPlaceHolder 
  static const baseUrl = 'https://jsonplaceholder.typicode.com';
  /* ---------------------------------------------------------------------------- */
  static FutureOr<void> _doGet(String path, void doThis(var response)?) async 
    await HttpReqService.getJson(baseUrl + path)
      .then((response) => doThis == null ? print(response) : doThis(response))
      .whenComplete(() => print('\nFetching done!'));
  
  /* ---------------------------------------------------------------------------- */
  static FutureOr<void> _doPost(String path, required Object body, int okCode = 200) async 
    await HttpReqService.post<Map<String, dynamic>>(baseUrl + path, body: body, okCode: okCode)
      .then((response) => print(response))
      .whenComplete(() => print('\nPost sent successfully'));
  
  /* ---------------------------------------------------------------------------- */
  static FutureOr<void> fetchPosts(int? id, bool onlyComments = false, bool useObjList = false) async 
    var path = '/posts/$id ?? ''';
    if (id != null && onlyComments) path += '/comments';
    useObjList 
      ? await _doGet(path, doThis: (response) 
        if (response != null) 
          print((response as List).map<Post>((m) => Post.fromJson(m as Map<String, dynamic>)));
        
      ) 
      : await _doGet(path);
  
  /* ---------------------------------------------------------------------------- */
  static FutureOr<void> fetchComments([int? postId]) => _doGet('/comments$postId != null ? '?postId='+postId.toString() : ''');
  static FutureOr<void> fetchAlbums() => _doGet('/albums');
  static FutureOr<void> fetchPhotos() => _doGet('/photos');
  static FutureOr<void> fetchTodos() => _doGet('/todos');
  static FutureOr<void> fetchUsers() => _doGet('/users');



void main(List<String> args) async 
  // await JsonPlaceHolder.fetchComments(1);
  await JsonPlaceHolder.fetchPosts(useObjList: true);
  print('Finished!');

结果:

(Instance of 'Post', Instance of 'Post', Instance of 'Post', ..., Instance of 'Post', Instance of 'Post')

Fetching done!
Finished!

注意

wnetworking 包尚未准备好发布,它包含与 API 等相关的操作。您可以将 HttpReqService.getJsonHttpReqService.post 分别替换为典型的 http.gethttp.post,但请记住返回值和异常. 使用Uri.parse

【讨论】:

您好,谢谢,但不,我想关注文档,如果他们发布了它应该可以工作【参考方案2】:

这些错误是由于 dart 版本造成的。

另一个用户已在 github 上进行了修复:https://github.com/flutter/website/pull/5798

按照这个 PR,它的工作原理

【讨论】:

以上是关于Flutter http 获取请求json序列化的主要内容,如果未能解决你的问题,请参考以下文章

Flutter实现网络请求

Flutter:为 Http GET 请求发送 JSON 正文

Flutter:使用 dio 包获取请求发送 JSON 正文

Flutter - 网络请求与 json 解析

如何在 Flutter 中使用 JSON 正文发出 http DELETE 请求?

如何将 json 列表传递给 Flutter 中的 http 请求(post)正文?