【发布时间】:2021-10-14 08:34:24
【问题描述】:
我试图在用户登录后显示我的 json 响应。当用户输入正确的信息时,它会在我的应用程序中成功显示响应。但是当用户输入错误的凭据时,应用程序会崩溃 当用户输入错误信息时,这是我的 json 响应。它应该在我的应用显示中显示 Status=0(或我想要显示的任何响应
I/flutter (16426): {"Status":"0","Message":"Wrong Password provided","UserData":null}
这是我在用户按下登录按钮时的 API 调用
Future<void> login() async{
var jsonResponse = null;
if (passwordontroller.text.isNotEmpty && emailController.text.isNotEmpty) {
var response = await http.post(Uri.parse("http://jhhjhjhjhjhjhj"),
body: ({
'LoginId': emailController.text,
'Password': passwordontroller.text
}));
if (response.statusCode == 200) {
print("Correct");
print(response.body);
jsonResponse = json.decode(response.body.toString());
print(jsonResponse);
Navigator.push(context, MaterialPageRoute(builder: (context)=>AfterLoginResPage(response: ApiResponse.fromJson(jsonResponse))));
}
else {
print("Wronggooooooooooooooooooooooooooo");
print(response.body);
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Invalid credentials")));
}
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Blank field is not allowed")));
}
}
我的模型课
class ApiResponse {
ApiResponse({
required this.status,
required this.message,
required this.userData,
});
String status;
String message;
UserData userData;
factory ApiResponse.fromJson(Map<String, dynamic> json) => ApiResponse(
status: json["Status"],
message: json["Message"],
//userData: UserData.fromJson(json["UserData"]),
userData: json["UserData"] == null? null:UserData.fromJson(json["UserData"]), //======== Updated
);
}
class UserData {
UserData({
required this.name,
required this.encUserId,
});
String name;
String encUserId;
factory UserData.fromJson(Map<String, dynamic> json) => UserData(
name: json["Name"],
encUserId: json["EncUserId"],
);
}
然后在这里我显示我的响应,当用户输入正确的凭据时,该响应已成功执行。但是在输入错误的凭据时崩溃了
children: [
Text("Status: ${widget.response.status}"),
Text("Message: ${widget.response.message}"),
我面临的另一个问题,这里我能够显示状态和消息如果我还想显示Name 和EncUserId 怎么办?
这是我在输入正确信息后在邮递员中的 json 响应
{
"Status": "1",
"Message": "You are Logged in successfully",
"UserData": {
"Name": "tuhinroy881@gmail.com",
"EncUserId": "bbA/HajfPdswT0fhhiMvEg=="
}
}
.
【问题讨论】:
-
把你所有的build方法,在错误信息后
response.body的输出是什么? -
response.body 在我的控制台
I/flutter (16426): {"Status":"0","Message":"Wrong Password provided","UserData":null}中打印没有问题,这是正确的,当我在登录中输入错误信息时。但是我的应用程序崩溃了,它的显示NoSuchMethodError: The method '[]被调用为空。接收者:null.尝试调用:[]("Name") ` -
用
userData: json["UserData"] == null? null:UserData.fromJson(json["UserData"]),替换userData: UserData.fromJson(json["UserData"]), -
试试
userData: json["UserData"] == null? null:UserData.fromJson(json["UserData"]) as Map<String, dynamic>), -
试试
UserData? userData;和userData: json["UserData"] == null? null:UserData.fromJson(json["UserData"] as Map<String, dynamic>)