Fetch complex format data in list with dart language - json

I'm just trying to fetch data via api in list but getting exception while debugging Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
Here is my demo json_api.
First I created model class for data which I'm getting then decleared variables according to api data.
Then created method to fetch data in the type of list of Model class objects.
then created Widget tree and add StreamBuilder with the list type model class objects, to display data.
CODE:
Model Class:
class Results {
String kind;
List<Item> items;
int totalItems;
Results({
this.kind,
this.items,
this.totalItems,
});
factory Results.fromJson(Map<String, dynamic> json) => new Results(
kind: json["kind"],
items: new List<Item>.from(json["items"].map((x) => Item.fromJson(x))),
totalItems: json["totalItems"],
);
Map<String, dynamic> toJson() => {
"kind": kind,
"items": new List<dynamic>.from(items.map((x) => x.toJson())),
"totalItems": totalItems,
};
}
class Item {
String id;
String kind;
String selfLink;
Item({
this.id,
this.kind,
this.selfLink,
});
factory Item.fromJson(Map<String, dynamic> json) => new Item(
id: json["id"],
kind: json["kind"],
selfLink: json["selfLink"],
);
Map<String, dynamic> toJson() => {
"id": id,
"kind": kind,
"selfLink": selfLink,
};
}
Method for get data in list of Model class objects:
Future<List<Results>> fetchData()async{
List<Results> results = new List<Results>();
final response = await http.get(url);
if(response.statusCode == 200 || json !=null){
List jsonParsed = json.decode(response.body).cast<Map<String, dynamic>>();
for (int i = 0; i < jsonParsed.length; i++) {
results.add(new Results.fromJson(jsonParsed[i]));
}
return results;
}else{
print('Request failed with status: ${response.statusCode}');
Fluttertoast.showToast(msg: "Request failed with status: ${response.statusCode}");
throw Exception('Failed to load post');
}
}
My Widget Tree with StreamBuilder:
body: Center(
child:FutureBuilder<List<Results>>(
future:fetchData(),
builder: (context, snapshot){
if(snapshot.hasData){
return
//Center(child:Text(snapshot.data.items[0].id) ,);
ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, int i){
return Column(
children: <Widget>[
ListTile(
leading: CircleAvatar(
child: Text(snapshot.data[i].items[i].id),
),
title: Text(snapshot.data[i].totalItems.toString()),
subtitle: Text(snapshot.data[i].kind) ,
),
Divider(color: Colors.grey,)
],
);
},
);
}else if(snapshot.hasError){
return Center(child: Text("${snapshot.error}"),);
}else{
return Center(child: CircularProgressIndicator(),);
}
},
),
),
Where Am i doing wrong.

try this,
Future<Results> fetchData() async {
Results results = new Results();
final response = await http
.get('https://www.googleapis.com/books/v1/volumes?q=%7Bhttp%7D');
if (response.statusCode == 200 || json != null) {
Map jsonParsed = json.decode(response.body);
results = Results.fromJson(jsonParsed);
return results;
} else {
print('Request failed with status: ${response.statusCode}');
throw Exception('Failed to load post');
}
}
#override
void initState() {
// TODO: implement initState
super.initState();
fetchData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Tiitle'),
),
body: Center(
child: FutureBuilder<Results>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return
//Center(child:Text(snapshot.data.items[0].id) ,);
ListView.builder(
itemCount: snapshot.data.items.length,
itemBuilder: (context, int i) {
return Column(
children: <Widget>[
ListTile(
leading: CircleAvatar(
child: Text(snapshot.data.totalItems.toString()),
),
title: Text(snapshot.data.items[i].id),
subtitle: Text(snapshot.data.items[i].kind),
),
Divider(
color: Colors.grey,
)
],
);
},
);
} else if (snapshot.hasError) {
return Center(
child: Text("${snapshot.error}"),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
));
}

Related

Fetch data from multiple api but display it in the same future builder

So I have multiple API but I can't display the data in the same future builder. Does anyone know what is going on?
Future<List> fetchData() async {
String url = 'someAPI';
final preferences = await SharedPreferences.getInstance();
final key = 'token';
final value = preferences.get(key);
var response = await http.get(Uri.parse(url), headers: {
'Conten-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $value '
});
log(response.body);
if (response.statusCode == 200) {
return [
// Album.fromJson(jsonDecode(response.body)),
for (final item in jsonDecode(response.body)) Album.fromJson(item),
];
} else {
throw Exception('Failed to load album');
}
}
Future<List> fetchDataDetail(String id) async {
String url2 = 'someAPI2' + id;
final preferences = await SharedPreferences.getInstance();
final key = 'token';
final value = preferences.get(key);
var response2 = await http.get(Uri.parse(url2), headers: {
'Conten-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $value '
});
log(response2.body);
if (response2.statusCode == 200) {
return [
// ReadData.fromJson(jsonDecode(response2.body)),
for (final item in jsonDecode(response2.body)) ReadData.fromJson(item),
// List<Map<String, dynamic>>.from(json.decode(response2.body)[ReadData])
];
} else {
throw Exception('Failed to load album');
}
}`
This is my UI for displaying the data that I fetch
class EmployeeList extends StatefulWidget {
const EmployeeList({Key? key}) : super(key: key);
static String id = 'employee';
#override
State<EmployeeList> createState() => _EmployeeListState();
}
class _EmployeeListState extends State<EmployeeList> {
late Future<List> futureAlbum;
late Future<List> futureReadData;
List<Album>? album;
List<ReadData>? readData;
#override
void initState() {
super.initState();
futureAlbum = fetchData();
futureReadData = fetchDataDetail(toString());
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Daftar Pegawai'),
backgroundColor: Color(0xFFF8B400),
),
body: SafeArea(
child: FutureBuilder<List>(
future: Future.wait([futureAlbum, futureReadData]),
initialData: [],
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return ListView(
children: [
ListView.builder(
shrinkWrap: true,
physics: ScrollPhysics(),
itemCount: snapshot.data!.length,
itemBuilder: (BuildContext context, int index) => ListTile(
onTap: (() {
print('${snapshot.data![index].Personal}');
}),
leading: CircleAvatar(
backgroundColor: Colors.blue,
),
title: Row(
children: [
Expanded(
child: Text('${snapshot.data![index].namaLengkap}'),
),
SizedBox(width: 25),
Expanded(
child: Text('${snapshot.data![index].id}'),
),
],
),
),
),
],
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Center(
child: CircularProgressIndicator(),
);
},
),
),
);
}
}
This is the class from 1st API
class Album {
Album({
required this.id,
required this.namaLengkap,
});
int? id;
String? namaLengkap;
factory Album.fromJson(Map<String, dynamic> json) => Album(
id: json["id"],
namaLengkap: json["nama_lengkap"],
);
Map<String, dynamic> toJson() => {
"id": id,
"nama_lengkap": namaLengkap,
};
}
This is the class from the 2nd API
class ReadData {
ReadData({
required this.personal,
required this.riwayat,
});
Personal personal;
List<Riwayat> riwayat;
factory ReadData.fromJson(Map<String, dynamic> json) => ReadData(
personal: Personal.fromJson(json["personal"]),
riwayat:
List<Riwayat>.from(json["riwayat"].map((x) => Riwayat.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"personal": personal.toJson(),
"riwayat": List<dynamic>.from(riwayat.map((x) => x.toJson())),
};
}
Also, this is the error message
Exception has occurred.
_TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable')
This error appeared in the second API when I tried to return it.

There should be exactly one item with [DropdownButton]'s value: Instance of 'Partner'

My dropdown working as expected . but when I selected a item my app crashing with error
There should be exactly one item with [DropdownButton]'s value: Instance of 'Partner'.
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
First I declare my variable in class
class _MultipleTestBookingState extends State<MultipleTestBooking> {
Partner? _selectedLab;
Datum? _selectedTest;
....................
declare with Partner?_selectedLab; because my dropdown menu takes in a list of Partners
Then using this variable to show the selected value in my dropdown
Container(
child: FutureBuilder<List<Partner>>(
future: AllPathLab(),
builder:
(BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState !=ConnectionState.done) {
return CircularProgressIndicator();
}
if (snapshot.hasError) {
return Text("Somthing went wrong");
}
if (snapshot.hasData) {
return DropdownButton<Partner>(
value: _selectedLab,
hint: Text("Select Lab"),
items: snapshot.data.map((Partner data) =>
DropdownMenuItem<Partner>(
child: Text("${data.partnerName}"),
value: data,
)
).toList().cast<DropdownMenuItem<Partner>>(),
onChanged: (value){
setState(() {
_selectedLab=value;
encLabId = value!.encPartnerId;
GetTestByLab();
});
}
);
}
return Text("Waiting for Internet Connection");
},
),
),
Full code with my JSON response
So from the data that you provided i have created the code below:
import 'package:date_time_picker/date_time_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/Patner.dart';
import 'package:flutter_app/dataModel.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
const MyApp({Key key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Partner _selectedLab;
Datum _selectedTest;
Future getAllPathLabResults;
Future getTestByLabResult;
String encLabId = '';
void initState() {
super.initState();
getAllPathLabResults = allPathLab();
getTestByLabResult = getTestByLab();
}
String _selectedDate = DateTime.now().toString();
Future<List<Partner>> allPathLab() async {
String jsonData = jsonstring;
final model = modelFromJson(jsonData);
print("This is the list length : ${model.partner.length}");
List<Partner> arrData = model.partner;
// this Future is for sample as you will be fetching the api data remove this one
Future.delayed(Duration(seconds: 3));
return arrData;
}
Future<List<Datum>> getTestByLab() async {
print("This is the Id :$encLabId");
_selectedTest = null;
var response = await http.post(
Uri.parse("http://medbo.digitalicon.in/api/medboapi/GetTestByLab"),
body: ({"EncId": encLabId}));
if (response.statusCode == 200) {
final dataModel = dataModelFromJson(response.body);
print(dataModel.data.length);
for (final item in dataModel.data) {
print("This is hte test name :${item.testName}");
}
List<Datum> arrData = dataModel.data;
return arrData;
}
return [];
}
#override
Widget build(BuildContext context) {
var screenWidth = MediaQuery.of(context).size.width;
var screenHeight = MediaQuery.of(context).size.height;
var blockSizeHorizontal = (screenWidth / 100);
var blockSizeVertical = (screenHeight / 100);
return Scaffold(
body: SafeArea(
child: Container(
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
title: Text("Booking Information",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: blockSizeHorizontal * 5,
fontFamily: 'Poppins',
color: Theme.of(context).primaryColor,
)),
subtitle: Text("Preferred Visit Date"),
),
),
Container(
margin: EdgeInsets.only(left: 20),
padding: EdgeInsets.only(left: 0, right: 150),
decoration: BoxDecoration(
color: Colors.lightBlue[50],
borderRadius: BorderRadius.all(Radius.circular(12)),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: DateTimePicker(
initialValue: DateTime.now().toString(),
//initialValue:'', // initialValue or controller.text can be null, empty or a DateTime string otherwise it will throw an error.
type: DateTimePickerType.date,
dateLabelText: 'Select Date',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: blockSizeHorizontal * 3.5,
fontFamily: 'Poppins',
color: Colors.green,
letterSpacing: 2.0,
),
firstDate: DateTime.now(),
lastDate: DateTime.now().add(Duration(days: 30)),
// This will add one year from current date
validator: (value) {
return null;
},
onChanged: (value) {
if (value.isNotEmpty) {
setState(() {
_selectedDate = value;
});
}
},
onSaved: (value) {
if (value.isNotEmpty) {
_selectedDate = value;
}
},
),
),
),
ListTile(
title: Text(
"Select Pathological Lab",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: blockSizeHorizontal * 4.0,
fontFamily: 'Poppins',
color: Theme.of(context).primaryColor,
),
),
),
Container(
child: FutureBuilder<List<Partner>>(
future: getAllPathLabResults,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return CircularProgressIndicator();
}
if (snapshot.hasError) {
return Text("Somthing went wrong");
}
if (snapshot.hasData) {
List<Partner> data =
snapshot.hasData ? snapshot.data : [];
return DropdownButton<Partner>(
value: _selectedLab,
hint: Text("Select Lab"),
//underline: SizedBox(),
//isExpanded: true,
items: data
.map((Partner data) => DropdownMenuItem<Partner>(
child: Text("${data.partnerName}"),
value: data,
))
.toList()
.cast<DropdownMenuItem<Partner>>(),
onChanged: (value) {
setState(() {
_selectedLab = value;
encLabId = value.encPartnerId;
getTestByLabResult = getTestByLab();
});
//GetTestByLab(value!.encPartnerId); // passing encid to my next API function
// GetTestByLab();
},
);
}
return Text("Waiting for Internet Connection");
},
),
),
//=========================================================== Dependent drop down===================================
ListTile(
title: Text(
"Test Name",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: blockSizeHorizontal * 4.0,
fontFamily: 'Poppins',
color: Theme.of(context).primaryColor,
),
),
),
Container(
child: FutureBuilder<List<Datum>>(
future: getTestByLabResult,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return CircularProgressIndicator();
}
if (snapshot.hasError) {
return Text("Select a Lab for your Test");
}
if (snapshot.hasData) {
List<Datum> data = snapshot.hasData ? snapshot.data : [];
return DropdownButton<Datum>(
value: _selectedTest,
hint: Text(""),
//underline: SizedBox(),
//isExpanded: true,
items: data
.map((Datum data) => DropdownMenuItem<Datum>(
child: Text("${data.testName}"),
value: data,
))
.toList()
.cast<DropdownMenuItem<Datum>>(),
onChanged: (value) {
print("This is the value : ${value.testName}");
setState(() {
_selectedTest = value;
});
//GetTestByLab(value!.encPartnerId); // passing encid to my next API function
});
}
return Text("Waiting for Internet Connection");
},
),
),
],
),
),
),
);
}
}
// used this as a sample
String jsonstring = '''{
"Status": "1",
"Message": "",
"Partner": [
{
"EncPartnerId": "IujyQXg8KZg8asLvK/FS7g==",
"PartnerName": "dasfdsf"
},
{
"EncPartnerId": "pEl2B9kuumKRxIxLJO76eQ==",
"PartnerName": "partner172"
},
{
"EncPartnerId": "eYwtNBXR6P/JDtsIwr+Bvw==",
"PartnerName": "nnkb"
},
{
"EncPartnerId": "kFgorcFF0G6RQD4W+LwWnQ==",
"PartnerName": "nnkjj"
},
{
"EncPartnerId": "U4exk+vfMGrn7cjNUa/PBw==",
"PartnerName": "mahadev"
},
{
"EncPartnerId": "tqkaSjTFgDf0612mp9mbsQ==",
"PartnerName": null
},
{
"EncPartnerId": "0aruO0FbYOu5IerRBxdT8w==",
"PartnerName": "Suraksha Diagnostics"
},
{
"EncPartnerId": "65gtodyhbtdInTsJWr1ZkA==",
"PartnerName": "Rasomoy pvt. Hospital"
},
{
"EncPartnerId": "LEuT1eIlpLEMAAkZme3wpQ==",
"PartnerName": "Tangra medical House"
},
{
"EncPartnerId": "q8O8YMzYKXSB4RtkX4k7Lw==",
"PartnerName": "Partner new"
}
]
}''';
Models for the apis:
// To parse this JSON data, do
//
// final model = modelFromJson(jsonString);
import 'dart:convert';
Model modelFromJson(String str) => Model.fromJson(json.decode(str));
String modelToJson(Model data) => json.encode(data.toJson());
class Model {
Model({
this.status,
this.message,
this.partner,
});
String status;
String message;
List<Partner> partner;
factory Model.fromJson(Map<String, dynamic> json) => Model(
status: json["Status"],
message: json["Message"],
partner:
List<Partner>.from(json["Partner"].map((x) => Partner.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Status": status,
"Message": message,
"Partner": List<dynamic>.from(partner.map((x) => x.toJson())),
};
}
class Partner {
Partner({
this.encPartnerId,
this.partnerName,
});
String encPartnerId;
String partnerName;
factory Partner.fromJson(Map<String, dynamic> json) => Partner(
encPartnerId: json["EncPartnerId"],
partnerName: json["PartnerName"] == null ? null : json["PartnerName"],
);
Map<String, dynamic> toJson() => {
"EncPartnerId": encPartnerId,
"PartnerName": partnerName == null ? null : partnerName,
};
}
second api parsing model
// To parse this JSON data, do
//
// final dataModel = dataModelFromJson(jsonString);
import 'dart:convert';
DataModel dataModelFromJson(String str) => DataModel.fromJson(json.decode(str));
String dataModelToJson(DataModel data) => json.encode(data.toJson());
class DataModel {
DataModel({
this.status,
this.message,
this.data,
});
String status;
String message;
List<Datum> data;
factory DataModel.fromJson(Map<String, dynamic> json) => DataModel(
status: json["Status"],
message: json["Message"],
data: json["Data"] == null
? []
: List<Datum>.from(json["Data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Status": status,
"Message": message,
"Data":
data == null ? [] : List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
Datum({
this.testId,
this.encTestId,
this.testName,
this.noOfPartner,
this.testFee,
this.discountedFee,
this.bookingFee,
this.reportTime,
this.note,
this.createBy,
this.createDate,
this.modBy,
this.modDate,
this.activeStatus,
this.permission,
});
String testId;
dynamic encTestId;
String testName;
dynamic noOfPartner;
dynamic testFee;
dynamic discountedFee;
dynamic bookingFee;
dynamic reportTime;
dynamic note;
dynamic createBy;
dynamic createDate;
dynamic modBy;
dynamic modDate;
dynamic activeStatus;
dynamic permission;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
testId: json["TestId"],
encTestId: json["EncTestId"],
testName: json["TestName"],
noOfPartner: json["NoOfPartner"],
testFee: json["TestFee"],
discountedFee: json["DiscountedFee"],
bookingFee: json["BookingFee"],
reportTime: json["ReportTime"],
note: json["Note"],
createBy: json["CreateBy"],
createDate: json["CreateDate"],
modBy: json["ModBy"],
modDate: json["ModDate"],
activeStatus: json["ActiveStatus"],
permission: json["Permission"],
);
Map<String, dynamic> toJson() => {
"TestId": testId,
"EncTestId": encTestId,
"TestName": testName,
"NoOfPartner": noOfPartner,
"TestFee": testFee,
"DiscountedFee": discountedFee,
"BookingFee": bookingFee,
"ReportTime": reportTime,
"Note": note,
"CreateBy": createBy,
"CreateDate": createDate,
"ModBy": modBy,
"ModDate": modDate,
"ActiveStatus": activeStatus,
"Permission": permission,
};
}
So when you initially fetch the data based on the id and select the second dropdown. now when you change the lab you have the make the selected text to null.
and you are are also using the futurebuilder method in wrong manner as there is setstate getting called it is creating multiple rebuids and giving error.
please run the code and check if its working.

Listview with images list not populating Flutter

I want to show images from Json into list. I do not know why it is not parsing images correctly. I am trying to get image from nested list but always it shows error of type list is not type of list.
https://imgur.com/AVGNSdl
My Json is like this
[
{
"PhoneNo": "030780229",
"VehicleNo": "1838",
"Features": "1111",
"Category": "Sedan",
"carsalingImage": [
{
"PhoneNo": "030780229",
"VehicleNo": "1838",
"ImageURL": "data:image/png;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBsRXhpZgAASUkqAAgAAAADADEBAgAHAAAA",
"Id": 0
},
{
"PhoneNo": "030780229",
"VehicleNo": "1838",
"ImageURL": "data:image/png;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBsRXhpZgAASUkqAAgAAAADADEBAgAHAAAA",
"Id": 0
}
]
My build function is
Uint8List _bytesImage;
List<CarSaleImage> userList;
Widget build(BuildContext context) {
return FutureBuilder<List<CarModel>>(
future: _fetchNewVehicles(),
builder: (context, snapshot) {
if (snapshot.hasData) {
List<CarModel> data = snapshot.data;
return _showlistView(data);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
);
}
Future<List<CarModel>> _fetchNewVehicles() async {
final response = await http.get(uri);
print(uri);
if (response.statusCode == 200) {
// setState(() {
List jsonResponse = json.decode(response.body);
//
userList = (jsonResponse[0]['carsalingImage'])
.map((itemWord) => CarSaleImage.fromJson(itemWord))
.toList();
print(userList.length);
//
return jsonResponse.map((c) => new CarModel.fromJson(c)).toList();
// });
} else {
throw Exception('Failed to load data from API');
}
}
ListView _showlistView(data) {
return ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (context, index) {
return _itemBuilder(
context,
index,
data[index].manufacturerName ??
'' + "Model: " + data[index].model ??
'' + "year: " + data[index].year + '');
});
}
Widget _itemBuilder(BuildContext context, int index, String texts) {
return InkWell(
child: Card(
child: Column(children: <Widget>[
SizedBox(
height: 200.0,
child: ListView.builder(
physics: ClampingScrollPhysics(),
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: userList.length,
itemBuilder: (BuildContext context, int index) => Card(
child: Container(
width: MediaQuery.of(context).size.width - 40,
child: Center(
child: Image(
image:
returnImg(userList[index].imageUrl.toString())
.image))),
),
),
),
Text(
'Demo Headline 2',
),
Container(
height: 50,
child: Text(
"${texts}",
style: TextStyle(
fontWeight: FontWeight.w500,
color: Colors.orange,
),
),
),
])),
onTap: () {
print(texts);
});
}
Image returnImg(String bytesData) {
_bytesImage = base64.decode(bytesData.split(',').last);
return Image.memory(_bytesImage);
}
My Model classes are
CarModel carVecFromJson(String str) => CarModel.fromJson(json.decode(str));
String carVecToJson(CarModel data) => json.encode(data.toJson());
class CarModel {
CarModel({
this.phoneNo,
this.vehicleNo,
this.features,
this.category,
this.carsalingImage,
});
String phoneNo;
String vehicleNo;
String features;
String category;
List<CarSaleImage> carsalingImage;
factory CarModel.fromJson(Map<String, dynamic> json) => CarModel(
phoneNo: json["PhoneNo"],
vehicleNo: json["VehicleNo"],
features: json["Features"],
category: json["Category"],
carsalingImage: List<CarSaleImage>.from(
json["carsalingImage"].map((x) => CarSaleImage.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"PhoneNo": phoneNo,
"VehicleNo": vehicleNo,
"Features": features,
"Category": category,
"carsalingImage":
List<dynamic>.from(carsalingImage.map((x) => x.toJson())),
};
}
class CarSaleImage {
CarSaleImage({
this.phoneNo,
this.vehicleNo,
this.imageUrl,
this.id,
});
String phoneNo;
String vehicleNo;
String imageUrl;
int id;
factory CarSaleImage.fromJson(Map<String, dynamic> json) => CarSaleImage(
phoneNo: json["PhoneNo"],
vehicleNo: json["VehicleNo"],
imageUrl: json["ImageURL"],
id: json["Id"],
);
Map<String, dynamic> toJson() => {
"PhoneNo": phoneNo,
"VehicleNo": vehicleNo,
"ImageURL": imageUrl,
"Id": id,
};
}
How to resolve this issue. Any help ?
Please update CarModel and try again.
factory CarModel.fromJson(Map<String, dynamic> json) => CarModel(
phoneNo: json["PhoneNo"],
vehicleNo: json["VehicleNo"],
features: json["Features"],
category: json["Category"],
carsalingImage:
json["carsalingImage"].map((x) => CarSaleImage.fromJson(x)).toList(),
);
Map<String, dynamic> toJson() => {
"PhoneNo": phoneNo,
"VehicleNo": vehicleNo,
"Features": features,
"Category": category,
"carsalingImage": carsalingImage.map((x) => x.toJson()).toList(),
};

Flutter Nested array?

I have these JSON data
[
{
"student_id": 1,
"studentid": 1204,
"password": "demo",
"name": "Amber",
"level": "student",
"course_name": [
"Math",
"History"
]
}
]
Kindly show me the code to to achieve this :
Actually you have a JSON array (only one index), should be something like:
myArray[0].course_name.forEach(course => console.log(course));
data[index].courseName[0]
https://app.quicktype.io/ for right "model"
model.dart
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
List<Welcome> welcomeFromJson(String str) => List<Welcome>.from(json.decode(str).map((x) => Welcome.fromJson(x)));
String welcomeToJson(List<Welcome> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Welcome {
int studentId;
int studentid;
String password;
String name;
String level;
List<String> courseName;
Welcome({
this.studentId,
this.studentid,
this.password,
this.name,
this.level,
this.courseName,
});
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
studentId: json["student_id"] == null ? null : json["student_id"],
studentid: json["studentid"] == null ? null : json["studentid"],
password: json["password"] == null ? null : json["password"],
name: json["name"] == null ? null : json["name"],
level: json["level"] == null ? null : json["level"],
courseName: json["course_name"] == null ? null : List<String>.from(json["course_name"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"student_id": studentId == null ? null : studentId,
"studentid": studentid == null ? null : studentid,
"password": password == null ? null : password,
"name": name == null ? null : name,
"level": level == null ? null : level,
"course_name": courseName == null ? null : List<dynamic>.from(courseName.map((x) => x)),
};
}
main.dart
var jsonString = [
{
"student_id": 1,
"studentid": 1204,
"password": "demo",
"name": "Amber",
"level": "student",
"course_name": ["Math", "History"]
}
];
List<Welcome> hui = welcomeFromJson(json.encode(jsonString));
print(hui[0].courseName[0]);
Try this now
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(new MaterialApp(
home: new HomePage(),
));
}
class HomePage extends StatefulWidget {
#override
HomePageState createState() => new HomePageState();
}
class HomePageState extends State<HomePage> {
List data;
bool isLoading = false;
Future<String> getData({isShowLoading: true}) async {
// refreshKey.currentState?.show(atTop: false);
//await Future.delayed(Duration(seconds: 2));
if (isShowLoading) {
setState(() {
isLoading = true;
});
}
var response = await http.get(
Uri.encodeFull("https://ikns.info/api/nested-array.php"),
headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
if (isShowLoading) {
setState(() {
isLoading = false;
});
}
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
if (mounted) {
setState(() {
data = jsonDecode(response.body);
});
}
return "Success!";
}
var refreshKey = GlobalKey<RefreshIndicatorState>();
#override
void initState() {
super.initState();
this.getData();
}
Future<Null> _onRefresh() async {
await getData(isShowLoading: false);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Parsing List of Strings"),
),
body: isLoading
? Center(
child: Text('Loading...'),
)
: RefreshIndicator(
key: refreshKey,
child: new ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
List<dynamic> items = data[index]["course_name"];
return GestureDetector(
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => DetailsPage(
todo: Todo.fromJson(data[index]),
),
),
);
},
child: new Card(
child: Column(
children: <Widget>[
Container(
child: new Text(data[index]["name"]),
),
Column(
children: List.generate(items.length, (index) {
return Text(
"${items[index]}",
style: TextStyle(color: Colors.red),
);
}),
),
],
),
),
);
},
),
onRefresh: _onRefresh,
),
);
}
}
class Todo {
final String name;
Todo(this.name);
Todo.fromJson(Map<String, dynamic> json) : name = json['name'];
}
class DetailsPage extends StatelessWidget {
final Todo todo;
DetailsPage({Key key, #required this.todo}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text(todo.name),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Text(todo.name),
),
);
}
}
UPDATE
OnClick Math, pass Math to the other screen (same for history)
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(new MaterialApp(
home: new HomePage(),
));
}
class HomePage extends StatefulWidget {
#override
HomePageState createState() => new HomePageState();
}
class HomePageState extends State<HomePage> {
List data;
bool isLoading = false;
Future<String> getData({isShowLoading: true}) async {
// refreshKey.currentState?.show(atTop: false);
//await Future.delayed(Duration(seconds: 2));
if (isShowLoading) {
setState(() {
isLoading = true;
});
}
var response = await http.get(
Uri.encodeFull("https://ikns.info/api/nested-array.php"),
headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
if (isShowLoading) {
setState(() {
isLoading = false;
});
}
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
if (mounted) {
setState(() {
data = jsonDecode(response.body);
});
}
return "Success!";
}
var refreshKey = GlobalKey<RefreshIndicatorState>();
#override
void initState() {
super.initState();
this.getData();
}
Future<Null> _onRefresh() async {
await getData(isShowLoading: false);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Parsing List of Strings"),
),
body: isLoading
? Center(
child: Text('Loading...'),
)
: RefreshIndicator(
key: refreshKey,
child: new ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
List<dynamic> items = data[index]["course_name"];
return new Card(
child: Column(
children: <Widget>[
Container(
child: new Text(data[index]["name"]),
),
Column(
children: List.generate(items.length, (index) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => DetailsPage(
todo: Todo(items[index].toString()),
),
),
);
},
child: Text(
"${items[index]}",
style: TextStyle(color: Colors.red),
),
);
}),
),
],
),
);
},
),
onRefresh: _onRefresh,
),
);
}
}
class Todo {
final String name;
Todo(this.name);
Todo.fromJson(Map<String, dynamic> json) : name = json['name'];
}
class DetailsPage extends StatelessWidget {
final Todo todo;
DetailsPage({Key key, #required this.todo}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text(todo.name),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Text(todo.name),
),
);
}
}

how to load Json to flutter listview

I'm new to flutter and I'm developing a flutter app where I have to show in a listView the data on the database.
I get the data in JSON format.
{
"data": [
{
"id": “1”,
"testo": "Fare la spesa",
"stato": "1"
},
{
"id": “2”,
"testo": "Portare fuori il cane",
"stato": "1"
},
{
"id": “3”,
"testo": “jhon”,
"stato": "0"
}
]
}
The problem is that I don't load the data, I can't understand how to do it.
I should read 'Data' with an array but I don't know how to do it.
Can anyone help me figure out how to do it?
Thanks for your help.
PS. I tried this tutorial
Main.dart
Future<Post> fetchPost() async {
final response =
await http.get('http://simone.fabriziolerose.it/index.php/Hello/dispdataflutter');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
class Post {
final int id;
final String title;
final String body;
Post({ this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'],
title: json['testo'],
body: json['stato'],
);
}
}
void main() => runApp(MyApp(post: fetchPost()));
class MyApp extends StatelessWidget {
final Future<Post> post;
MyApp({Key key, this.post}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Post>(
future: post,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
),
),
);
}
}
I'd rather return List of Post from fetchPost(), like below :
Future<List<Post>> fetchPost() async {
final response = await http.get('http://simone.fabriziolerose.it/index.php/Hello/dispdataflutter');
if (response.statusCode == 200) {
List responseList = json.decode(response.body);
return responseList.map((data)=>Post.fromJson(data)).toList();
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
and use ListView.builder instead like this
List<Post> post;
child: ListView.builder(
itemCount: post.length,
physics: BouncingScrollPhysics(),
padding: EdgeInsets.all(0),
itemBuilder: (context, index){
return ListAdapter(
id: post[index].id,
title: post[index].title,
body: post[index].body
);
},
)