颤抖的api休息,身体长

时间:2019-06-06 16:25:20

标签: post flutter dart

当我调用rest API时,出现错误:

I/flutter (25698): {user: {firstName: Jérémy, lastName: Gachon, pseudo: jerem, email: exemple@gmail.com, password: Abcd1234, birthDateDay: 24, birthDateMonth: 12, birthDateYear: 2004, language: fr}}
I/flutter (25698): gg1
I/flutter (25698): type '_InternalLinkedHashMap<String, String>' is not a subtype of type 'String' in type cast

这是我的代码:

Future<User> handleSignup(String email, String password, String pseudo,
  String firstName, String lastName, String birthDate) async {
var finalBirthDate = birthDate.split("/");
Map userDataFormated = {
  "user": {
    "firstName": firstName,
    "lastName": lastName,
    "pseudo": pseudo,
    "email": email,
    "password": password,
    "birthDateDay": finalBirthDate[0],
    "birthDateMonth": finalBirthDate[1],
    "birthDateYear": finalBirthDate[2],
    "language": 'fr'
  }
};
print(userDataFormated);
try {
  print("gg1");
  var res = await http.post(globals.apiUrl + "auth/createUser/", body: userDataFormated);
  print("gg2");
  print(res);
  if (res.statusCode == 201) {
    final map = convert.jsonDecode(res.body);
    final User user = new User.fromMap(map);
    return user;
  } else {
    print(res);
      }
    } catch (e) {
      print(e);
    }
  }

当我在人体图中将地图放置在用户中时,编译器不接受。 谢谢你。

2 个答案:

答案 0 :(得分:0)

跳到解决方案

问题

  

_InternalLinkedHashMap'不是强制类型转换中'String'类型的子类型

步骤1:阅读http.post代码

https://github.com/dart-lang/http/blob/master/lib/http.dart

Future<Response> post(url,
    {Map<String, String> headers, body, Encoding encoding})

步骤2:注意评论

  

[body]设置请求的主体。它可以是[String],[List]或   一张地图]。如果是字符串,则使用[encoding]和   用作请求的正文。请求的内容类型将   默认为“文本/纯文本”。

第3步:

Map <字符串,Map <字符串,字符串>>不等于map <字符串,字符串>

解决方案

导入dart:转换

import 'dart:convert' as convert;

使用convert.json.encode

body: convert.json.encode(userDataFormated)

答案 1 :(得分:0)

过时的:

var res = await http.post(url, body: convert.json.encode(userDataFormated), headers: {"Content-type": "application/json", "Accept": "application/json"});