簡體   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