I am using firebase realtime database for my project, and when i read information from the database, I get an Object as an output.
final databaseInstance = FirebaseDatabase.instance;
final posts = await databaseInstance.ref("Posts").once();
print(posts.snapshot.value);
The result I get is {Test Post: {Description: testing 123123, Date: 19 Dec}}
. However, I do not want it in this form. How should I read it such that i can read the data such that when I want the date I only get 19 Dec?
CodePudding user response:
Oops I actually found an answer to my problem. The problem with it was that when firebase realtime database was returning the result to me, it was not really is json.
So I has to convert it to json by myself using the function jsonEncode(data)
.
When code was run, {Test Post: {Description: testing 123123, Date: 19 Dec}}
to {"Test Post":{"Description":"testing 123123","Date":"19 Dec"}}
, which solves my problem as I could just take have ['Test Post']
behind the variable.
CodePudding user response:
you can create a class called post that has Description and date variables like so:
class Post{
final String description, date;
Post({
required this.description,
required this.date,
});
factory Post.fromJson(json){
return Post(
description: json['description'],
date: json['date'],
);
}
}
now when you get the snapshot simply use it like this:
var result = posts.snapshot.value;
final post = Post.fromJson(result['Test Post']);
and you can use post.date
to get your date