Sometimes, the problem arise for the structure of JSON and for your Pojo class.
My JSON is as follows:
{"records":[{"name":"noor ","email":"email","mobileNo":187,"feedback":"good"}]}
According to this JSON we have to create the pojo classes right way.
When you paste your JSON it will give you the pojo class in this site: https://javiercbk.github.io/json_to_dart/
You have to give a class name there. With name of question I found the following two pojo classes according to the above JSON:
class Questions {
List<Records>? records;
Questions({this.records});
Questions.fromJson(Map<String, dynamic> json) {
if (json['records'] != null) {
records = <Records>[];
json['records'].forEach((v) {
records!.add(new Records.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.records != null) {
data['records'] = this.records!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Records {
String? name;
String? email;
int? mobileNo;
String? feedback;
Records({this.name, this.email, this.mobileNo, this.feedback});
Records.fromJson(Map<String, dynamic> json) {
name = json['name'];
email = json['email'];
mobileNo = json['mobileNo'];
feedback = json['feedback'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['email'] = this.email;
data['mobileNo'] = this.mobileNo;
data['feedback'] = this.feedback;
return data;
}
}
Now the important part: that convert that record to list. Here is the calling:
Future<List<Records>> getRecordList() async {
return await http.get(Uri.parse(URL)).then((response) {
print(response.body.toString());
Questions questions = Questions.fromJson(json.decode(response.body));
print(questions.records![0].feedback);
List<Records> list_s = [];
for (int i = 0; i < questions.records!.length; i++) {
list_s.add(questions.records![i]);
}
print(list_s[0].name);
return list_s;
});
}
}
And At last the UI part Is :
class _FeedbackListPageState extends State<FeedbackListPage> {
List<Records> list_s = [];
@override
void initState() {
super.initState();
FormController().getRecordList().then((value) {
setState(() {
list_s = value;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: darkGreen,
elevation: 0.0,
titleSpacing: 10.0,
title: Text(widget.title),
centerTitle: true,
leading: InkWell(
onTap: () {
Navigator.pop(context);
},
child: const Icon(
Icons.arrow_back_ios,
color: Colors.black54,
),
),
),
body: ListView.builder(
itemCount: list_s.length,
itemBuilder: (context, index) {
return ListTile(
title: Row(
children: <Widget>[
Icon(Icons.person),
Expanded(
child: Text("${list_s[index].name} (${list_s[index].email})"),
)
],
),
subtitle: Row(
children: <Widget>[
Icon(Icons.message),
Expanded(
child: Text(list_s[index].feedback.toString()),
)
],
),
);
},
),
);
}
}
List<Post> posts = json.decode(response.body).map((Map m)=> Json.fromJson(m)).toList();