简体   繁体   English

未处理的异常:将 object 转换为可编码的 object 失败:“LoginModel”实例

[英]Unhandled Exception: Converting object to an encodable object failed: Instance of 'LoginModel'

Am still learning and understanding the working of flutter, I am trying to save json string whenever a user logins in for the First time, and use the ID and token to call and interact with different API endpoints.我仍在学习和理解 flutter 的工作原理,每当用户第一次登录时,我都会尝试保存 json 字符串,并使用 ID 和令牌来调用不同的 API 端点并与之交互。 Whenever I try to save the json content to Shared Preference I end with error每当我尝试将 json 内容保存到共享首选项时,我都会以错误结束

Unhandled Exception: Converting object to an encodable object failed: Instance of 'LoginModel'未处理的异常:将 object 转换为可编码的 object 失败:“LoginModel”实例

My LoginModel我的登录模型

import 'dart:convert';

LoginModel loginModelFromJson(String str) => LoginModel.fromJson(json.decode(str));

String loginModelToJson(LoginModel data) => json.encode(data.toJson());

class LoginModel {
  LoginModel({
    this.id,
    this.username,
    this.email,
    this.roles,
    this.userid,
    this.surname,
    this.firstname,
    this.telephoneno,
    this.whatsappno,
    this.active,
    this.studyrole,
    this.tokenType,
    this.accessToken,
  });

  int id;
  String username;
  String email;
  List<String> roles;
  String userid;
  String surname;
  String firstname;
  String telephoneno;
  String whatsappno;
  int active;
  String studyrole;
  String tokenType;
  String accessToken;

  factory LoginModel.fromJson(Map<String, dynamic> json) => LoginModel(
    id: json["id"],
    username: json["username"],
    email: json["email"],
    roles: List<String>.from(json["roles"].map((x) => x)),
    userid: json["userid"],
    surname: json["surname"],
    firstname: json["firstname"],
    telephoneno: json["telephoneno"],
    whatsappno: json["whatsappno"],
    active: json["active"],
    studyrole: json["studyrole"],
    tokenType: json["tokenType"],
    accessToken: json["accessToken"],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "username": username,
    "email": email,
    "roles": List<dynamic>.from(roles.map((x) => x)),
    "userid": userid,
    "surname": surname,
    "firstname": firstname,
    "telephoneno": telephoneno,
    "whatsappno": whatsappno,
    "active": active,
    "studyrole": studyrole,
    "tokenType": tokenType,
    "accessToken": accessToken,
  };
}

how am trying to save the Json to shared pref when user clicks on the login button当用户单击登录按钮时,如何尝试将 Json 保存到共享首选项

login(username, password) async {

  SharedPref sharedPref = SharedPref();
  LoginModel userSave = LoginModel();

  final String url = "http://21.76.45.12:80/data/api/auth/signin"; // iOS
  final http.Response response = await http.post(
    url,
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'username': username,
      'password': password,
    }),
  );

  print(response.body);
  sharedPref.save("user", userSave);

 
}

My Login button Widget我的登录按钮小部件

RoundedButton(
                text: "LOGIN",
                press: () async {
                  if (_formKey.currentState.validate()) {
                    progressDialog.show();
                    await login(
                      username,
                      password,
                    );
                    SharedPreferences prefs =
                        await SharedPreferences.getInstance();
                    String token = prefs.getString("accessToken");
                    loadSharedPrefs();
                    print(token);
                    // ignore: null_aware_in_condition
                    if (token == null) {
                      progressDialog.hide();
                      showAlertsDialog(context);
                      // ignore: null_aware_in_condition
                    } else {
                      progressDialog.hide();
                      showAlertzDialog(context);
                    }
                  }
                },
              ),

whenever I try to load the preference I get no data每当我尝试加载首选项时,我都没有得到任何数据

loadSharedPrefs() async {
    try {
      LoginModel user = LoginModel.fromJson(await sharedPref.read("user"));
      Scaffold.of(context).showSnackBar(SnackBar(
          content: new Text("Loaded!"),
          duration: const Duration(milliseconds: 500)));
      setState(() {
        userLoad = user;
      });
    } catch (Excepetion) {
      Scaffold.of(context).showSnackBar(SnackBar(
          content: new Text("Nothing found!"),
          duration: const Duration(milliseconds: 500)));
    }
  }

My SharedPref class我的 SharedPref class

class SharedPref {
  read(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return json.decode(prefs.getString(key));
  }

  save(String key, value) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString(key, json.encode(value));
  }

  remove(String key) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.remove(key);
  }
}

what am I doing wrong such that the JSON is not being saved to shared prefs?我做错了什么,以至于 JSON 没有被保存到共享首选项? Thank you for the help感谢您的帮助

You are not parsing the json anywhere in your code.您没有在代码中的任何位置解析 json。 You are creating an empty object using:您正在创建一个空的 object 使用:

LoginModel userSave = LoginModel();

Which contains null values for the properties and that's why you are getting those exceptions.其中包含属性的 null 值,这就是您遇到这些异常的原因。 You want to parse the json and create the object using:您要解析 json 并使用以下命令创建 object:

LoginModel userSave = loginModelFromJson(response.body);
sharedPref.save("user", userSave);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未处理的异常:将对象转换为可编码对象失败:“产品”实例 - Unhandled Exception: Converting object to an encodable object failed: Instance of 'Product' 未处理的异常:将 object 转换为可编码的 object 失败:“日期时间”实例 - Unhandled Exception: Converting object to an encodable object failed: Instance of 'DateTime' 未处理的异常:将 object 转换为可编码的 object 失败:“TextEditingController”实例 - Unhandled Exception: Converting object to an encodable object failed: Instance of 'TextEditingController' Flutter:未处理的异常:将对象转换为可编码对象失败:“AddProjectModel”的实例 - Flutter: Unhandled Exception: Converting object to an encodable object failed: Instance of 'AddProjectModel' 未处理的异常:将 object 转换为可编码的 object 失败:“测量”实例 - Unhandled Exception: Converting object to an encodable object failed: Instance of 'Mesure' 未处理的异常:将 object 转换为可编码的 object 失败:“XFile”实例 - Unhandled Exception: Converting object to an encodable object failed: Instance of 'XFile' 如何解决未处理的异常:将对象转换为可编码对象失败? - how to solve Unhandled Exception: Converting object to an encodable object failed? 未处理的异常:将对象转换为可编码对象失败:摄影 - Unhandled Exception: Converting object to an encodable object failed: Photography 未处理的异常:将 object 转换为可编码的 object 失败:_LinkedHashMap - Unhandled Exception: Converting object to an encodable object failed: _LinkedHashMap 未处理的异常:DioError [DioErrorType.DEFAULT]:将对象转换为可编码的 object 失败:“DateTime”实例 - Unhandled Exception: DioError [DioErrorType.DEFAULT]: Converting objects to an encodable object failed: Instance of 'DateTime'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM