'flutter parsing JSON from firebase
I just started learning about flutter and try to use ScopedModel and I get stuck at parsing JSON, everything works until I try to get List of detail simulation but everything that I try just fails
this is my class for project and simulation
class Project {
String idProject;
List images;
List<Simulations> simulation;
Project({
@required this.idProject,
@required this.images,
@required this.simulation
});
}
class Simulations{
String period;
int profitProject;
int roi;
Simulations({
@required this.period,
@required this.profitProject,
@required this.roi
});
}
I made a separate class to get detail for simulation
this is a sample from JSON that I get from the firebase
{
"1554182068913": {
"idProject": "project id 1",
"images": [
1554181958565,
1554181955542,
1554181960876],
"simulation": [
{
"periode": "year 1",
"profitProject": 300000,
"roi": 5,
"uniqueKey": "YyCWbHjvm"
},
{
"periode": "year 1",
"profitProject": 100000,
"roi": 3,
"uniqueKey": "CvyU4SjrX"
},
{
"periode": "year 1",
"profitProject": 2000000,
"roi": 10,
"uniqueKey": "Tb_Qr5CIA"
}
],
}
}
I made function to get the data
Future<Null> fetchProjects() {
return http.get("JSON link")
.then<Null>((http.Response response) {
final List<Project> fetchedProjectList = [];
final Map<String, dynamic> projectListData = json.decode(response.body);
if (projectListData == null) {
_isLoading = false;
notifyListeners();
return;
}
projectListData.forEach((String projectId, dynamic projectData) {
final Project project = Project(
title: projectData['title'],
location: projectData['location'],
images: projectData['images'],
simulation: ???
);
fetchedProjectList.add(project);
}
Solution 1:[1]
What's missing here is JSON serialization. You need to convert the response to a Dart object, similar to what has been demonstrated on this guide. In Project class, you can add a fromJson()
constructor to map the data.
factory Project.fromJson(Map<String, dynamic> json) {
return Project(
idProject: json['idProject'],
images: json['images'],
simulation: json['simulation'],
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Omatt |