Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 未处理的异常:将对象转换为可编码对象失败:';LoginModel';_Flutter_Dart - Fatal编程技术网

Flutter 未处理的异常:将对象转换为可编码对象失败:';LoginModel';

Flutter 未处理的异常:将对象转换为可编码对象失败:';LoginModel';,flutter,dart,Flutter,Dart,我仍在学习和理解flatter的工作原理,我试图在用户首次登录时保存json字符串,并使用ID和令牌调用不同的API端点并与之交互。每当我尝试将json内容保存到共享首选项时,我都会以错误结束 未处理的异常:将对象转换为可编码对象失败: “LoginModel”的实例 我的登录模型 import 'dart:convert'; LoginModel loginModelFromJson(String str) => LoginModel.fromJson(json.decode(str)

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

未处理的异常:将对象转换为可编码对象失败: “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,
  };
}
每当我尝试加载首选项时,都不会得到任何数据

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 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没有保存到共享pref?感谢您的帮助

您没有在代码的任何地方解析json。您正在使用以下命令创建空对象:

LoginModel userSave=LoginModel();
它包含属性的空值,这就是为什么会出现这些异常。您希望解析json并使用以下方法创建对象:

LoginModel userSave=loginModelFromJson(response.body);
sharedPref.save(“用户”,userSave);

每当我尝试访问accessToken时,我都会得到null,
String token=userLoad.accessToken;打印(代币)
@blackbird检查您是否从响应中获取accesstoken,以及您是否使用了正确的密钥来解析它
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)));
    }
  }
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);
  }
}