flutter 如何修复此错误:未处理的异常:类型"String"不是类型"Map〈String,dynamic>"的子类型

0aydgbwb  于 2023-02-25  发布在  Flutter
关注(0)|答案(1)|浏览(614)

我不断收到以下错误

[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>

这是我的用户模型

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'],
    );
  }

下面是我的用户控制器,以供参考

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");

    }

我认为这与我如何从服务器收集信息,Json格式信息和它的转换有关,虽然我不能指出确切的解决方案,但这只是我的想法,毫无疑问,我愿意接受更正。

9gm1akwq

9gm1akwq1#

我认为您没有将response.body解析为Map,因为它来自API,是一个字符串。要将它转换为模型,您需要在UserModel.fromJson()方法中传递Map,因为它在模型的工厂方法中接受Map< String, dynamic>

相关问题