使用Riverpod调用fromJson时遇类型错误:String无法赋值给Map<String,dynamic>
解决fromJson类型不匹配错误
错误原因很明确:http.get返回的response.body是JSON格式的字符串,但你的UserModel.fromJson方法要求的参数类型是Map<String, dynamic>,直接传递字符串就会触发类型不匹配报错。
解决方案
- 导入
dart:convert包,用jsonDecode方法将JSON字符串解析为Map<String, dynamic> - 先校验响应状态码,确保请求成功后再解析,避免无效JSON导致的异常
修改后的代码
1. 更新FutureProvider代码
import 'dart:convert'; // 新增导入 import 'package:http/http.dart' as http; import 'package:flutter_riverpod/flutter_riverpod.dart'; final fetchUserProvider = FutureProvider((ref) { const url = 'https://jsonplaceholder.typicode.com/users/1'; return http.get(Uri.parse(url)).then((response) { // 先验证请求是否成功 if (response.statusCode == 200) { // 将JSON字符串解析为Map类型 final jsonData = jsonDecode(response.body) as Map<String, dynamic>; return UserModel.fromJson(jsonData); } else { // 请求失败时抛出异常,方便上层处理错误 throw Exception('请求失败,状态码:${response.statusCode}'); } }); });
2. 优化UserModel(可选,更符合Dart惯例)
可以把静态方法改为factory构造函数,这是Dart中处理JSON解析的常用写法:
class UserModel { final int id; final String name; final String username; const UserModel({ required this.id, required this.name, required this.username, }); // 替换为factory构造函数 factory UserModel.fromJson(Map<String, dynamic> json) { return UserModel( id: json['id'] as int, name: json['name'] as String, username: json['username'] as String, ); } @override String toString() => "$id, $name, $username"; }
这样修改后,就能正确将响应体的JSON字符串转换为Map,再传递给fromJson完成模型解析,解决类型不匹配的问题。
内容的提问来源于stack exchange,提问作者Mohammed M
相关产品推荐
相关产品推荐

