繁体   English   中英

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

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

我仍在学习和理解 flutter 的工作原理,每当用户第一次登录时,我都会尝试保存 json 字符串,并使用 ID 和令牌来调用不同的 API 端点并与之交互。 每当我尝试将 json 内容保存到共享首选项时,我都会以错误结束

未处理的异常:将 object 转换为可编码的 object 失败:“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,
  };
}

当用户单击登录按钮时,如何尝试将 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);

 
}

我的登录按钮小部件

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

每当我尝试加载首选项时,我都没有得到任何数据

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

我的 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);
  }
}

我做错了什么,以至于 JSON 没有被保存到共享首选项? 感谢您的帮助

您没有在代码中的任何位置解析 json。 您正在创建一个空的 object 使用:

LoginModel userSave = LoginModel();

其中包含属性的 null 值,这就是您遇到这些异常的原因。 您要解析 json 并使用以下命令创建 object:

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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM