我有一個 Flutter 模型用戶
class User {
String id;
String name;
String email;
String image;
User({
this.id = "",
this.name = "",
this.email = "",
this.image = "",
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
name: json['name'],
email: json['email'],
image: json['image'],
);
}
Map toMap() {
var map = Map<String, dynamic>();
map['id'] = id;
map['name'] = name;
map['email'] = email;
map['image'] = image;
return map;
}
}
我有一個 flutter LoginResult 在我登錄時呼叫用戶模型
import 'User.dart';
class LoginResult {
String message;
String? token;
User? user;
LoginResult({
this.message = "",
this.token,
this.user,
});
factory LoginResult.fromJson(Map<String, dynamic> json) {
if (json['user'] != null) {
return LoginResult(
message: json['message'],
user: User.fromJson(json['user']),
token: json['token'],
);
} else {
return LoginResult(
message: json['message'],
token: json['token'],
);
}
}
Map toMap() {
var map = Map<String, dynamic>();
map['message'] = message;
map['user'] = user;
map['token'] = token;
return map;
}
}
當我登錄時,LoginResults 中的決議回應正文對這個結果 json 作業正常
{
"message": "logged in success",
"user": {
"rol": 100,
"image": "83f124c1-5a46-469c-8de7-11a90c506a44.jpg",
"_id": "6105c3c8bf76720bfa2e31e9",
"name": "Guillermo Canales Justo",
"email": "[email protected]",
"password": "$2b$10$Z5.RMoRHeyKt7cdFrtubbOzEGjGvHhU19UQEV.mA/ZSunIXqKhYz.",
"__v": 48,
"created": "2021-09-18T06:52:40.995Z",
"id": "6105c3c8bf76720bfa2e31e9"
},
"token": "eyJhbGciOiJIUzI..."
}
但是當我更新組態檔用戶并回傳此 json 時,User.fromJson(json_decode(response.body))回傳 properties null。
email:null
id:null
image:null
name:null
hashCode:258164629
runtimeType:Type (User)
有了這個 json 回應
{
"user": {
"rol": 100,
"image": "595ccd2c-1c37-42a7-904f-fdc73b5f89b0.jpg",
"_id": "6105c3c8bf76720bfa2e31e9",
"name": "Guillermo Canales",
"email": "[email protected]",
"password": "$2b$10$Z5.RMoRHey...",
"__v": 48,
"created": "2021-09-18T06:52:40.995Z",
"id": "6105c3c8bf76720bfa2e31e9"
}
}
我無法理解第二次決議有什么問題。
uj5u.com熱心網友回復:
您必須從 json 中獲取用戶。
改變這一行
User.fromJson(json_decode(response.body))
到
User.fromJson(json_decode(response.body)['user'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/341215.html
