Reputation: 6743
I've successfully displayed a hardcoded JSON with a DataTable, like this:
final List<Map<String, String>> listOfPetrol = [
{"logo": "assets/images/shell.jpg", "location": "Johnson Road 1235", "distance": "0.2 KM", "price":"\$12.45", "facilities":"ATM, Restaurant"},
{"logo": "assets/images/sinopec.jpg", "location": "Hennessy Road", "distance": "0.5 KM", "price":"\$10.00", "facilities":"Toilet"},
{"logo": "assets/images/shell.jpg", "location": "Lockhart Rd", "distance": "0.9 KM", "price":"\$11.20", "facilities":"ATM"}
];
DataTable(
columns: [
DataColumn(label: Text('Logo')),
DataColumn(label: Text('Location')),
DataColumn(label: Text('Distance')),
DataColumn(label: Text('Price')),
DataColumn(label: Text('Facilities')),
],
rows:
listOfPetrol
.map(
((element) => DataRow(
cells: <DataCell>[
DataCell(Image.asset(element["logo"])),
DataCell(Text(element["location"])),
DataCell(Text(element["distance"])),
DataCell(Text(element["price"])),
DataCell(Text(element["facilities"])),
],
)),
)
.toList(),
),
Now, I want fetch the JSON from HTTP API, instead. I already figured out this part. Well... kinda:
FetchPetrolList() async {
var data = await http.get("http://157.230.131.4/gda-api-dev/petrol.php");
var jsonData = json.decode(data.body);
List<PetrolItem> petrolList = [];
for (var u in jsonData) {
PetrolItem petrol = PetrolItem(u["logo"], u["location"], u["distance"], u["price"], u["facilities"]);
petrolList.add(petrol);
print(petrol.logo+" "+petrol.location+" "+petrol.distance+" "+petrol.price+" "+petrol.facilities);
}
}
Then how I pass the JSON to the DataTable? Full code: https://gist.github.com/anta40/5b172d885795c71417f2ed2dccffe50c
Upvotes: 1
Views: 5288
Reputation: 573
You can parse JSON data into a model. There are two ways I use to parse JSON data automatically.
Android studio installs the Flutter JsonBeanFactory plug-in in a simple way, which I won't say here.
Right-click the package directory after installation, and select new
Then select dart bean class File from JSON
Then paste the JSON data into the input box, enter the class name, and click make.
So the entity class is generated.
Upvotes: 1