You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Dart类型转换错误:String无法转为Map<String, dynamic>

错误排查:type 'String' is not a subtype of type 'Map<String, dynamic>'

错误日志

[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>'
#0      UserController.getUserInfo (package:smarthnb/controllers/user_controller.dart:29:48)
<asynchronous suspension>

相关代码

User Model代码

class UserModel{
  int id;
  String name;
  String email;
  String phone;
  int orderCount;

  UserModel({
    required this.id,
    required this.name,
    required this.email,
    required this.phone,
    required this.orderCount,
  });
  factory UserModel.fromJson (Map<String, dynamic> json){
    return UserModel(
        id:json['id'],
        name:json['f_name'],
        email:json['email'],
        phone:json['phone'],
        orderCount:json['order_count'],
    );
  }
}

User Controller代码

class UserController extends GetxController implements GetxService {
  final UserRepo userRepo;

  UserController({
    required this.userRepo,
  });

  bool _isLoading = false;
  late UserModel _userModel;

  bool get isLoading => _isLoading;
  UserModel get userModel =>_userModel;

  Future<ResponseModel> getUserInfo() async{
    _isLoading = true;
    update();
    Response response = await userRepo.getUserInfo();
    late ResponseModel responseModel;

    if(response.statusCode == 200){
      _userModel = UserModel.fromJson(response.body);
      responseModel = ResponseModel(true,"successfully");
    }
  }
}

问题原因与修复方案

核心问题

错误直接指向UserModel.fromJson(response.body)这一行——服务器返回的response.body是字符串类型,但fromJson方法需要的是Map<String, dynamic>类型,类型不匹配导致崩溃。

具体修复步骤

  1. 解析JSON字符串为Map
    先导入dart:convert包,然后将返回的字符串解析成Map:

    // 在getUserInfo方法的if分支里修改
    if(response.statusCode == 200){
      // 把字符串转成Map
      Map<String, dynamic> userJson = jsonDecode(response.body);
      _userModel = UserModel.fromJson(userJson);
      responseModel = ResponseModel(true,"successfully");
    }
    
  2. 检查服务器返回的JSON结构
    如果服务器返回的是嵌套结构(比如{"data": {"id":1, "f_name":"xxx", ...}}),需要先提取对应字段再解析:

    Map<String, dynamic> responseJson = jsonDecode(response.body);
    // 取出嵌套的用户数据
    Map<String, dynamic> userJson = responseJson['data'];
    _userModel = UserModel.fromJson(userJson);
    
  3. 添加异常处理避免崩溃
    给解析逻辑加上try-catch,并完善状态更新:

    Future<ResponseModel> getUserInfo() async{
      _isLoading = true;
      update();
      Response response = await userRepo.getUserInfo();
      late ResponseModel responseModel;
    
      try {
        if(response.statusCode == 200){
          Map<String, dynamic> userJson = jsonDecode(response.body);
          // 若有嵌套结构则打开下面的注释
          // userJson = userJson['data'];
          _userModel = UserModel.fromJson(userJson);
          responseModel = ResponseModel(true,"successfully");
        } else {
          responseModel = ResponseModel(false, response.statusMessage ?? "请求失败");
        }
      } catch(e) {
        responseModel = ResponseModel(false, "解析错误: ${e.toString()}");
        print(e);
      } finally {
        _isLoading = false;
        update();
      }
      return responseModel;
    }
    

内容的提问来源于stack exchange,提问作者User_tensile_scoop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 03:05:19