Dart - error doing deserialization of FCM Json notification - json

I have an app made in flutter 1.22.2, and I'm putting together a "Notification Center" view. When the notification arrives at the device, it arrives in json format, and I'm trying to make a decode, to display it in this view.
fcm.configure(
onMessage: (message) async {
try {
print("onMessage: $message");
PushDecode.fromJson(message);
print(PushDecode().notification.title);
} catch (e) {
print(e);
}
return message;
},
onLaunch: (message) async {
print("onLaunch: $message");
},
onResume: (message) async {
print("onResume: $message");
},
);
My decode class:
// final pushDecode = pushDecodeFromJson(jsonString);
import 'dart:convert';
PushDecode pushDecodeFromJson(String str) => PushDecode.fromJson(json.decode(str));
String pushDecodeToJson(PushDecode data) => json.encode(data.toJson());
class PushDecode {
PushDecode({
this.data,
this.notification,
});
Data data;
PushNotification notification;
factory PushDecode.fromJson(Map<dynamic, dynamic> json) => PushDecode(
data: Data.fromJson(json["data"]),
notification: PushNotification.fromJson(json["notification"]),
);
Map<dynamic, dynamic> toJson() => {
"data": data.toJson(),
"notification": notification.toJson(),
};
}
class Data {
Data({
this.title,
this.message,
});
String title;
String message;
factory Data.fromJson(Map<dynamic, dynamic> json) => Data(
title: json["title"],
message: json["message"],
);
Map<dynamic, dynamic> toJson() => {
"title": title,
"message": message,
};
}
class PushNotification {
PushNotification({
this.body,
this.title,
});
String body;
String title;
factory PushNotification.fromJson(Map<dynamic, dynamic> json) =>
PushNotification(
body: json["body"],
title: json["title"],
);
Map<dynamic, dynamic> toJson() => {
"body": body,
"title": title,
};
}
I have received this error when I run the code.
I/flutter (xx): onMessage: {notification: {title: Test one, body: Test one body}, data: {title: number 1, message: number too}}
I/flutter (xx): NoSuchMethodError: The getter 'title' was called on null.
I/flutter (xx): Receiver: null
I/flutter (xx): Tried calling: title
What happens is that the onMessage () try goes straight through the decode class, and the error pops up, returning null, what should I do?

Try using PushDecode.fromJson(jsonDecode(message.data));
You might be getting it as a string.

Related

How can I fetch data in API without giving this error

I want to retrieve some data in API, but that's giving an error . How can i get List of all posts
This is my DataModel class:
class DataModel {
DataModel({
required this.id,
required this.title,
required this.body,
});
int id;
String title;
String body;
factory DataModel.fromJson(Map<String, dynamic> json) => DataModel(
id: json["id"],
title: json["title"],
body: json["body"],
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"body": body,
};
}
And this is my get future data function:
Future<DataModel?> getData(context) async {
DataModel? result;
try {
final response = await http.get(
Uri.parse("https://someapi.com/posts"),); // this is example api for security
if (response.statusCode == 200) {
final data = json.decode(response.body);
result = DataModel.fromJson(data);
} else {
// ignore: avoid_print
print("error");
}
} catch (e) {
log(e.toString());
}
return result;
}
That's giving me an error like that:
type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
I think in the reponse you are getting a list of items which has to be used like the following
var list = json.decode(response.body);
List<DataModel> result = list.map((i) => DataModel.fromJSON(i)).toList();
return result;
And the method will return
Future<List<DataModel>>?

convert it to list flutter firebase

this is my database image
import 'dart:convert';
class ReviewcountInfo{
List<String> uid;
ReviewcountInfo({
required this.uid,
})
List<String> toList() {
return
}
factory ReviewcountInfo.fromMap(Map<String, dynamic> map) {
return ReviewcountInfo(
uid: ['uid'] ?? 0,
);}
String toJson() => json.encode(toList());
factory ReviewcountInfo.fromJson(String source) =>
ReviewcountInfo.fromMap(json.decode(source));
}
I want to get data in the form of an array from firebase, how can I get it?
I don't know how to fill 'List toList()','factory ReviewcountInfo' part.
class BrandingInfo {
num price;
BrandingInfo({
required this.price,
});
Map<String, dynamic> toMap() {
return {
'price': price,
};
}
factory BrandingInfo.fromMap(Map<String, dynamic> map) {
return BrandingInfo(
price: map['price'] ?? 0,
);
}
String toJson() => json.encode(toMap());
factory BrandingInfo.fromJson(String source) =>
BrandingInfo.fromMap(json.decode(source));
}
this is my example Code
I am coding by referring to the code above.
try this model
import 'dart:convert';
List<ReviewCount> reviewCountFromJson(String str) => List<ReviewCount>.from(json.decode(str).map((x) => ReviewCount.fromJson(x)));
String reviewCountToJson(List<ReviewCount> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class ReviewCount {
ReviewCount({
this.reviewcount,
});
final Reviewcount? reviewcount;
factory ReviewCount.fromJson(Map<String, dynamic> json) => ReviewCount(
reviewcount: json["reviewcount"] == null ? null : Reviewcount.fromJson(json["reviewcount"]),
);
Map<String, dynamic> toJson() => {
"reviewcount": reviewcount == null ? null : reviewcount.toJson(),
};
}
class Reviewcount {
Reviewcount({
this.uid,
});
final List<String>? uid;
factory Reviewcount.fromJson(Map<String, dynamic> json) => Reviewcount(
uid: json["uid"] == null ? null : List<String>.from(json["uid"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"uid": uid == null ? null : List<dynamic>.from(uid!.map((x) => x)),
};
}
then for getting the data from firestore
Future<Reviewcount> getuidList({String? pathDocuid}) async{
final response = await FirebaseFirestore.instance.collection("service").doc(pathDocuid!).get();
final mapItFirst = response.data() as Map<String,dynamic>;
// but first print the data using log so you can see if it
// gettingdata
log("${mapItFirst['reviewcount']}");
log("${mapItFirst['reviewcount']['uid']}");
return Reviewcount.fromJson(mapItFirst["reviewcount"]);
}
try this if it works if not mention me.

How to display different different data form in Json response?

I'm successfully got responded from my API , also able to display Status and Message in my App.
But How to display Name & EncUserId as it is inside UserData
Here is my JSON response in Postman
{
"Status": "1",
"Message": "You are Logged in successfully",
"UserData": {
"Name": "qwerty#gmail.com",
"EncUserId": "GO9gj3aSUKCpxE3AMSbh/A=="
}
}
Im Displaying my Json response in my App in this format
Text("Status: ${widget.response.status}"),
Text("Message: ${widget.response.message}"),
Here is API model
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: json["UserData"] == null? null:UserData.fromJson(json["UserData"] as Map<String, dynamic>),
);
}
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"],
);
}
This will work
Text("name: ${widget.response.userData.name}"),
Text("encUserId: ${widget.response.userData.encUserId}")

Json Status=0 not displaying

I'm trying to show my json response after user login. It successfully displaying response in my app when user put correct info. But the app getting crashed when user putting wrong credentials
Here is my json response when user put wrong info. It should displaying Status=0 in my app display(or whatever response I want to display
I/flutter (16426): {"Status":"0","Message":"Wrong Password provided","UserData":null}
Here is my API call when user press the login button
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")));
}
}
My Model class
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"],
);
}
And then here I'm displaying my response which is successfully getting executed when User putting correct credentials. but got crashed when putting wrong credentials
children: [
Text("Status: ${widget.response.status}"),
Text("Message: ${widget.response.message}"),
one more problem I'm facing ,here im able to display status and message What If I want to display Name & EncUserId also?.
here is my json response in postman after putting right info
{
"Status": "1",
"Message": "You are Logged in successfully",
"UserData": {
"Name": "tuhinroy881#gmail.com",
"EncUserId": "bbA/HajfPdswT0fhhiMvEg=="
}
}
.
Since null safety is enabled, you need to change UserData userData to UserData? userData; and userData: json["UserData"] == null? null:UserData.fromJson(json["UserData"] as Map<String, dynamic>)
Your problem is that you are trying to parse UserData while your error response doesn't have any UserData related information.
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: json["UserData"] == null? null:UserData.fromJson(json["UserData"]),
);
}

JSON Parse not parsing in Flutter if some object is empty

I have a signup form and the backend is PHP. PHP returning success, error data as JSON.
Below is my JSONParse file.
import 'dart:convert';
Signup signupFromJson(String str) => Signup.fromJson(json.decode(str));
String signupToJson(Signup data) => json.encode(data.toJson());
class Signup {
Errors errors;
bool success;
Signup({
this.errors,
this.success,
});
factory Signup.fromJson(Map<String, dynamic> json) => Signup(
errors: Errors.fromJson(json["errors"]),
success: json["success"],
);
Map<String, dynamic> toJson() => {
"errors": errors.toJson(),
"success": success,
};
}
class Errors {
String password1;
String email1;
String name;
Errors({
this.password1,
this.email1,
this.name,
});
factory Errors.fromJson(Map<String, dynamic> json) => Errors(
password1: json["Password1"],
email1: json["Email1"],
name: json["Name"],
);
Map<String, dynamic> toJson() => {
"Password1": password1,
"Email1": email1,
"Name": name,
};
}
Here is sample JSON Data.
If login is failed due to some condition not met.
{"errors":{"Email1":"Email could not be empty",
"Password1":"Password could not be empty",
"Name":"Your name must be between 3 to 30 characters!"},
"success":false}
If login successful
{"success":false}
My JSONParse is working properly if condition not met. I mean it retuning all the errors and Success false.
But if login is successful then it is not working, by checking more I found data is coming fine from PHP.
Signup signupFromJson(String str) => Signup.fromJson(json.decode(str)); - Data is coming in str variable.
factory Signup.fromJson(Map<String, dynamic> json) => Signup(
errors: Errors.fromJson(json["errors"]), -- If error is nulll then it is not checking the success.
success: json["success"],
);
The issue coming here when errors are null then it moved out didn't goto the success section.
What am I doing wrong here?
If you get success then you will not get errors, so you have to check null aware where you are passing to error class too.
In Signup.fromJson :
errors: Errors.fromJson(json["errors"] ?? {}),
In Error Class
factory Errors.fromJson(Map<String, dynamic> json) => Errors(
password1: json["Password1"] ?? '',
email1: json["Email1"] ?? '',
name: json["Name"] ?? '',
);