flutter 无法将参数类型“String”分配给参数类型“Map〈String,dynamic>”

5lhxktic  于 2023-04-22  发布在  Flutter
关注(0)|答案(1)|浏览(164)

使用fromJson
无法将参数类型“String”分配给参数类型“Map〈String,dynamic〉”。

final fetchUserProvider = FutureProvider((ref) {
  const url = 'https://jsonplaceholder.typicode.com/users/1';
  return http
      .get(Uri.parse(url))
      .then((response) => UserModel.fromJson(response.body));//error 
});
class UserModel {
  final int id;
  final String name;
  final String username;

  const UserModel({
    required this.id,
    required this.name,
    required this.username,
  });

  static UserModel fromJson(Map<String, dynamic> json) {
    return UserModel(
      id: json['id'],
      name: json['name'],
      username: json['username'],
    );
  }

  @override
  String toString() => "$id, $name, $username";
}
j9per5c4

j9per5c41#

您需要使用jsonDecode(From dart:convert;)解码响应正文,而从JSON解码,MapfromJson(Map<String, dynamic> json)除外

return http
      .get(Uri.parse(url))
      .then((response) => UserModel.fromJson(jsonDecode(response.body))); // i prefer `await` over `then`

相关问题