Simple JSON data fetch and show in screen the data is showing in print but while showing in screen its giving error of NoSuchMethodErrorClass 'ResponsiveObjectSettingByUser' has no instance method 'car' receiver: Instance,
GET FUNCTION
Future<ResponseObjectSettingByUser> _list;
final String _url = '<LINK>';
Future<ResponseObjectSettingByUser> getUserSettings() async {
ResponseObjectSettingByUser responseData = null;
var response = await http
.get(_url + '<link>', headers: {
"Authorization":
'Bearer <TOKEN>',
});
var responseJson = json.decode(response.body);
if (response.statusCode == 200) {
responseJson = settingByUserModel(response.body);
print(responseJson.toJson().toString());
}
return responseJson;
}
Initilize
#override
void initState() {
super.initState();
_list = getUserSettings();
}
MODEL CLASS (ResponseObjectSettingByUser)
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
ResponseObjectSettingByUser settingByUserModel(String str) => ResponseObjectSettingByUser.fromJson(json.decode(str));
String welcomeToJson(ResponseObjectSettingByUser data) => json.encode(data.toJson());
class ResponseObjectSettingByUser {
ResponseObjectSettingByUser({
this.array,
});
Array array;
factory ResponseObjectSettingByUser.fromJson(Map<String, dynamic> json) => ResponseObjectSettingByUser(
array: Array.fromJson(json["array"]),
);
Map<String, dynamic> toJson() => {
"array": array.toJson(),
};
}
class Array {
Array({
this.car,
});
List<Car> car;
factory Array.fromJson(Map<String, dynamic> json) => Array(
car: List<Car>.from(json["car"].map((x) => Car.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"car": List<dynamic>.from(car.map((x) => x.toJson())),
};
}
class Car {
Car({
this.id,
this.name,
this.numberKmsMin,
this.numberKmsMax,
this.priceMin,
this.priceMax,
this.powerHorseMin,
this.powerHorseMax,
this.status,
this.isSaved,
this.markId,
this.markName,
this.markImageUrl,
this.modelId,
this.modelName,
this.modelImageUrl,
this.bodyworkId,
this.bodyworkName,
this.fuelId,
this.fuelName,
this.motorizationId,
this.motorizationName,
this.rimsId,
this.rimsName,
this.serieId,
this.serieName,
this.interiorEquipmentId,
this.interiorEquipmentName,
this.upholsteryId,
this.upholsteryName,
this.upholsteryLeatherFabricName,
this.iluminationId,
this.iluminationName,
this.externalEquipmentId,
this.externalEquipmentName,
this.dateStartMin,
this.dateEndMax,
this.settings,
});
int id;
String name;
String numberKmsMin;
String numberKmsMax;
String priceMin;
String priceMax;
String powerHorseMin;
String powerHorseMax;
String status;
int isSaved;
int markId;
String markName;
String markImageUrl;
int modelId;
String modelName;
String modelImageUrl;
int bodyworkId;
String bodyworkName;
int fuelId;
String fuelName;
int motorizationId;
String motorizationName;
dynamic rimsId;
dynamic rimsName;
int serieId;
String serieName;
int interiorEquipmentId;
String interiorEquipmentName;
int upholsteryId;
String upholsteryName;
String upholsteryLeatherFabricName;
int iluminationId;
String iluminationName;
int externalEquipmentId;
String externalEquipmentName;
String dateStartMin;
String dateEndMax;
List<Setting> settings;
factory Car.fromJson(Map<String, dynamic> json) => Car(
id: json["id"],
name: json["name"],
numberKmsMin: json["number_kms_min"],
numberKmsMax: json["number_kms_max"],
priceMin: json["price_min"],
priceMax: json["price_max"],
powerHorseMin: json["power_horse_min"],
powerHorseMax: json["power_horse_max"],
status: json["status"],
isSaved: json["is_saved"],
markId: json["mark_id"],
markName: json["mark_name"],
markImageUrl: json["mark_image_url"],
modelId: json["model_id"],
modelName: json["model_name"],
modelImageUrl: json["model_image_url"],
bodyworkId: json["bodywork_id"],
bodyworkName: json["bodywork_name"],
fuelId: json["fuel_id"],
fuelName: json["fuel_name"],
motorizationId: json["Motorization_id"],
motorizationName: json["Motorization_name"],
rimsId: json["rims_id"],
rimsName: json["rims_name"],
serieId: json["serie_id"],
serieName: json["serie_name"],
interiorEquipmentId: json["Interior_equipment_id"],
interiorEquipmentName: json["Interior_equipment_name"],
upholsteryId: json["Upholstery_id"],
upholsteryName: json["Upholstery_name"],
upholsteryLeatherFabricName: json["Upholstery_Leather_fabric_name"],
iluminationId: json["ilumination_id"],
iluminationName: json["ilumination_name"],
externalEquipmentId: json["external_equipment_id"],
externalEquipmentName: json["external_equipment_name"],
dateStartMin: json["date_start_min"],
dateEndMax: json["date_end_max"],
settings: json["settings"] == null ? null : List<Setting>.from(json["settings"].map((x) => Setting.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"number_kms_min": numberKmsMin,
"number_kms_max": numberKmsMax,
"price_min": priceMin,
"price_max": priceMax,
"power_horse_min": powerHorseMin,
"power_horse_max": powerHorseMax,
"status": status,
"is_saved": isSaved,
"mark_id": markId,
"mark_name": markName,
"mark_image_url": markImageUrl,
"model_id": modelId,
"model_name": modelName,
"model_image_url": modelImageUrl,
"bodywork_id": bodyworkId,
"bodywork_name": bodyworkName,
"fuel_id": fuelId,
"fuel_name": fuelName,
"Motorization_id": motorizationId,
"Motorization_name": motorizationName,
"rims_id": rimsId,
"rims_name": rimsName,
"serie_id": serieId,
"serie_name": serieName,
"Interior_equipment_id": interiorEquipmentId,
"Interior_equipment_name": interiorEquipmentName,
"Upholstery_id": upholsteryId,
"Upholstery_name": upholsteryName,
"Upholstery_Leather_fabric_name": upholsteryLeatherFabricName,
"ilumination_id": iluminationId,
"ilumination_name": iluminationName,
"external_equipment_id": externalEquipmentId,
"external_equipment_name": externalEquipmentName,
"date_start_min": dateStartMin,
"date_end_max": dateEndMax,
"settings": settings == null ? null : List<dynamic>.from(settings.map((x) => x.toJson())),
};
}
class Setting {
Setting({
this.id,
this.name,
});
int id;
String name;
factory Setting.fromJson(Map<String, dynamic> json) => Setting(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
To show data on screen using
child: FutureBuilder(
future: getUserSettings(),
builder: (BuildContext context,
AsyncSnapshot snapshot) {
final countries = snapshot.data;
if (snapshot.data == null) {
//IF NULL
return Container(
child: Center(
child: Text("Loading..."),
),
);
} else {
return Stack(
children: [
Container(
child: Text(snapshot.data.Car[0].id)
),
),
],
);
}
},
),
JSON Data is like this.
{
"array": {
"car": [
{
"id": 131,
"name": "120",
"number_kms_min": "1000",
"number_kms_max": "10000",
"price_min": "10000",
"price_max": "1000",
"power_horse_min": "100",
"power_horse_max": "120",
"status": "1",
"is_saved": 0,
"mark_id": 1,
"mark_name": "BMW",
"mark_image_url": "https://cdn0.iconfinder.com/data/icons/car-brands/550/BMW_logo-512.png",
"model_id": 1,
"model_name": "Serie 1",
"model_image_url": "https://www.bmw.pt/content/dam/bmw/common/all-models/1-series/5-door/2019/navigation/bmw-1-series-modelfinder.png",
"bodywork_id": 1,
"bodywork_name": "Coupé",
"fuel_id": 1,
"fuel_name": "Gasolina",
"Motorization_id": 1,
"Motorization_name": "Manual",
"rims_id": 1,
"rims_name": "Preto fosco\r\n5 raios",
"serie_id": 1,
"serie_name": "120",
"Interior_equipment_id": 1,
"Interior_equipment_name": "Bancos desportivos\r\n",
"Upholstery_id": 1,
"Upholstery_name": "Preto",
"Upholstery_Leather_fabric_name": "Preto",
"ilumination_id": 1,
"ilumination_name": "Iluminação ambiente",
"external_equipment_id": 1,
"external_equipment_name": "Para-choques desportivos",
"date_start_min": "03/18",
"date_end_max": "09/19"
},
{
"id": 121,
"name": "120",
"number_kms_min": "1000",
"number_kms_max": "10000",
"price_min": "10000",
"price_max": "1000",
"power_horse_min": "100",
"power_horse_max": "120",
"status": "1",
"is_saved": 0,
"mark_id": 1,
"mark_name": "BMW",
"mark_image_url": "https://cdn0.iconfinder.com/data/icons/car-brands/550/BMW_logo-512.png",
"model_id": 1,
"model_name": "Serie 1",
"model_image_url": "https://www.bmw.pt/content/dam/bmw/common/all-models/1-series/5-door/2019/navigation/bmw-1-series-modelfinder.png",
"bodywork_id": 1,
"bodywork_name": "Coupé",
"fuel_id": 1,
"fuel_name": "Gasolina",
"Motorization_id": 1,
"Motorization_name": "Manual",
"rims_id": 1,
"rims_name": "Preto fosco\r\n5 raios",
"serie_id": 1,
"serie_name": "120",
"Interior_equipment_id": 1,
"Interior_equipment_name": "Bancos desportivos\r\n",
"Upholstery_id": 1,
"Upholstery_name": "Preto",
"Upholstery_Leather_fabric_name": "Preto",
"ilumination_id": 1,
"ilumination_name": "Iluminação ambiente",
"external_equipment_id": 1,
"external_equipment_name": "Para-choques desportivos",
"date_start_min": "03/18",
"date_end_max": "09/19"
},
{
"id": 111,
"name": "120",
"number_kms_min": "1000",
"number_kms_max": "10000",
"price_min": "10000",
"price_max": "1000",
"power_horse_min": "100",
"power_horse_max": "120",
"status": "1",
"is_saved": 0,
"mark_id": 1,
"mark_name": "BMW",
"mark_image_url": "https://cdn0.iconfinder.com/data/icons/car-brands/550/BMW_logo-512.png",
"model_id": 1,
"model_name": "Serie 1",
"model_image_url": "https://www.bmw.pt/content/dam/bmw/common/all-models/1-series/5-door/2019/navigation/bmw-1-series-modelfinder.png",
"bodywork_id": 1,
"bodywork_name": "Coupé",
"fuel_id": 1,
"fuel_name": "Gasolina",
"Motorization_id": 1,
"Motorization_name": "Manual",
"rims_id": 1,
"rims_name": "Preto fosco\r\n5 raios",
"serie_id": 1,
"serie_name": "120",
"Interior_equipment_id": 1,
"Interior_equipment_name": "Bancos desportivos\r\n",
"Upholstery_id": 1,
"Upholstery_name": "Preto",
"Upholstery_Leather_fabric_name": "Preto",
"ilumination_id": 1,
"ilumination_name": "Iluminação ambiente",
"external_equipment_id": 1,
"external_equipment_name": "Para-choques desportivos",
"date_start_min": "03/18",
"date_end_max": "09/19"
}
]
}
}
You can copy paste run full code below
You can use AsyncSnapshot<ResponseObjectSettingByUser> and check connectionState and use snapshot.data.array.car.length in ListView
code snippet
FutureBuilder(
future: _list,
builder:
(context, AsyncSnapshot<ResponseObjectSettingByUser> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data.array.car.length,
itemBuilder: (context, index) {
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
ResponseObjectSettingByUser settingByUserModel(String str) =>
ResponseObjectSettingByUser.fromJson(json.decode(str));
String welcomeToJson(ResponseObjectSettingByUser data) =>
json.encode(data.toJson());
class ResponseObjectSettingByUser {
ResponseObjectSettingByUser({
this.array,
});
Array array;
factory ResponseObjectSettingByUser.fromJson(Map<String, dynamic> json) =>
ResponseObjectSettingByUser(
array: Array.fromJson(json["array"]),
);
Map<String, dynamic> toJson() => {
"array": array.toJson(),
};
}
class Array {
Array({
this.car,
});
List<Car> car;
factory Array.fromJson(Map<String, dynamic> json) => Array(
car: List<Car>.from(json["car"].map((x) => Car.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"car": List<dynamic>.from(car.map((x) => x.toJson())),
};
}
class Car {
Car({
this.id,
this.name,
this.numberKmsMin,
this.numberKmsMax,
this.priceMin,
this.priceMax,
this.powerHorseMin,
this.powerHorseMax,
this.status,
this.isSaved,
this.markId,
this.markName,
this.markImageUrl,
this.modelId,
this.modelName,
this.modelImageUrl,
this.bodyworkId,
this.bodyworkName,
this.fuelId,
this.fuelName,
this.motorizationId,
this.motorizationName,
this.rimsId,
this.rimsName,
this.serieId,
this.serieName,
this.interiorEquipmentId,
this.interiorEquipmentName,
this.upholsteryId,
this.upholsteryName,
this.upholsteryLeatherFabricName,
this.iluminationId,
this.iluminationName,
this.externalEquipmentId,
this.externalEquipmentName,
this.dateStartMin,
this.dateEndMax,
this.settings,
});
int id;
String name;
String numberKmsMin;
String numberKmsMax;
String priceMin;
String priceMax;
String powerHorseMin;
String powerHorseMax;
String status;
int isSaved;
int markId;
String markName;
String markImageUrl;
int modelId;
String modelName;
String modelImageUrl;
int bodyworkId;
String bodyworkName;
int fuelId;
String fuelName;
int motorizationId;
String motorizationName;
dynamic rimsId;
dynamic rimsName;
int serieId;
String serieName;
int interiorEquipmentId;
String interiorEquipmentName;
int upholsteryId;
String upholsteryName;
String upholsteryLeatherFabricName;
int iluminationId;
String iluminationName;
int externalEquipmentId;
String externalEquipmentName;
String dateStartMin;
String dateEndMax;
List<Setting> settings;
factory Car.fromJson(Map<String, dynamic> json) => Car(
id: json["id"],
name: json["name"],
numberKmsMin: json["number_kms_min"],
numberKmsMax: json["number_kms_max"],
priceMin: json["price_min"],
priceMax: json["price_max"],
powerHorseMin: json["power_horse_min"],
powerHorseMax: json["power_horse_max"],
status: json["status"],
isSaved: json["is_saved"],
markId: json["mark_id"],
markName: json["mark_name"],
markImageUrl: json["mark_image_url"],
modelId: json["model_id"],
modelName: json["model_name"],
modelImageUrl: json["model_image_url"],
bodyworkId: json["bodywork_id"],
bodyworkName: json["bodywork_name"],
fuelId: json["fuel_id"],
fuelName: json["fuel_name"],
motorizationId: json["Motorization_id"],
motorizationName: json["Motorization_name"],
rimsId: json["rims_id"],
rimsName: json["rims_name"],
serieId: json["serie_id"],
serieName: json["serie_name"],
interiorEquipmentId: json["Interior_equipment_id"],
interiorEquipmentName: json["Interior_equipment_name"],
upholsteryId: json["Upholstery_id"],
upholsteryName: json["Upholstery_name"],
upholsteryLeatherFabricName: json["Upholstery_Leather_fabric_name"],
iluminationId: json["ilumination_id"],
iluminationName: json["ilumination_name"],
externalEquipmentId: json["external_equipment_id"],
externalEquipmentName: json["external_equipment_name"],
dateStartMin: json["date_start_min"],
dateEndMax: json["date_end_max"],
settings: json["settings"] == null
? null
: List<Setting>.from(
json["settings"].map((x) => Setting.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"number_kms_min": numberKmsMin,
"number_kms_max": numberKmsMax,
"price_min": priceMin,
"price_max": priceMax,
"power_horse_min": powerHorseMin,
"power_horse_max": powerHorseMax,
"status": status,
"is_saved": isSaved,
"mark_id": markId,
"mark_name": markName,
"mark_image_url": markImageUrl,
"model_id": modelId,
"model_name": modelName,
"model_image_url": modelImageUrl,
"bodywork_id": bodyworkId,
"bodywork_name": bodyworkName,
"fuel_id": fuelId,
"fuel_name": fuelName,
"Motorization_id": motorizationId,
"Motorization_name": motorizationName,
"rims_id": rimsId,
"rims_name": rimsName,
"serie_id": serieId,
"serie_name": serieName,
"Interior_equipment_id": interiorEquipmentId,
"Interior_equipment_name": interiorEquipmentName,
"Upholstery_id": upholsteryId,
"Upholstery_name": upholsteryName,
"Upholstery_Leather_fabric_name": upholsteryLeatherFabricName,
"ilumination_id": iluminationId,
"ilumination_name": iluminationName,
"external_equipment_id": externalEquipmentId,
"external_equipment_name": externalEquipmentName,
"date_start_min": dateStartMin,
"date_end_max": dateEndMax,
"settings": settings == null
? null
: List<dynamic>.from(settings.map((x) => x.toJson())),
};
}
class Setting {
Setting({
this.id,
this.name,
});
int id;
String name;
factory Setting.fromJson(Map<String, dynamic> json) => Setting(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<ResponseObjectSettingByUser> _list;
Future<ResponseObjectSettingByUser> getUserSettings() async {
ResponseObjectSettingByUser responseData = null;
/*var response = await http
.get(_url + '<link>', headers: {
"Authorization":
'Bearer <TOKEN>',
});*/
String jsonString = '''
{
"array": {
"car": [
{
"id": 131,
"name": "120",
"number_kms_min": "1000",
"number_kms_max": "10000",
"price_min": "10000",
"price_max": "1000",
"power_horse_min": "100",
"power_horse_max": "120",
"status": "1",
"is_saved": 0,
"mark_id": 1,
"mark_name": "BMW",
"mark_image_url": "https://cdn0.iconfinder.com/data/icons/car-brands/550/BMW_logo-512.png",
"model_id": 1,
"model_name": "Serie 1",
"model_image_url": "https://www.bmw.pt/content/dam/bmw/common/all-models/1-series/5-door/2019/navigation/bmw-1-series-modelfinder.png",
"bodywork_id": 1,
"bodywork_name": "Coupé",
"fuel_id": 1,
"fuel_name": "Gasolina",
"Motorization_id": 1,
"Motorization_name": "Manual",
"rims_id": 1,
"rims_name": "Preto fosco\r\n5 raios",
"serie_id": 1,
"serie_name": "120",
"Interior_equipment_id": 1,
"Interior_equipment_name": "Bancos desportivos\r\n",
"Upholstery_id": 1,
"Upholstery_name": "Preto",
"Upholstery_Leather_fabric_name": "Preto",
"ilumination_id": 1,
"ilumination_name": "Iluminação ambiente",
"external_equipment_id": 1,
"external_equipment_name": "Para-choques desportivos",
"date_start_min": "03/18",
"date_end_max": "09/19"
},
{
"id": 121,
"name": "120",
"number_kms_min": "1000",
"number_kms_max": "10000",
"price_min": "10000",
"price_max": "1000",
"power_horse_min": "100",
"power_horse_max": "120",
"status": "1",
"is_saved": 0,
"mark_id": 1,
"mark_name": "BMW",
"mark_image_url": "https://cdn0.iconfinder.com/data/icons/car-brands/550/BMW_logo-512.png",
"model_id": 1,
"model_name": "Serie 1",
"model_image_url": "https://www.bmw.pt/content/dam/bmw/common/all-models/1-series/5-door/2019/navigation/bmw-1-series-modelfinder.png",
"bodywork_id": 1,
"bodywork_name": "Coupé",
"fuel_id": 1,
"fuel_name": "Gasolina",
"Motorization_id": 1,
"Motorization_name": "Manual",
"rims_id": 1,
"rims_name": "Preto fosco\r\n5 raios",
"serie_id": 1,
"serie_name": "120",
"Interior_equipment_id": 1,
"Interior_equipment_name": "Bancos desportivos\r\n",
"Upholstery_id": 1,
"Upholstery_name": "Preto",
"Upholstery_Leather_fabric_name": "Preto",
"ilumination_id": 1,
"ilumination_name": "Iluminação ambiente",
"external_equipment_id": 1,
"external_equipment_name": "Para-choques desportivos",
"date_start_min": "03/18",
"date_end_max": "09/19"
},
{
"id": 111,
"name": "120",
"number_kms_min": "1000",
"number_kms_max": "10000",
"price_min": "10000",
"price_max": "1000",
"power_horse_min": "100",
"power_horse_max": "120",
"status": "1",
"is_saved": 0,
"mark_id": 1,
"mark_name": "BMW",
"mark_image_url": "https://cdn0.iconfinder.com/data/icons/car-brands/550/BMW_logo-512.png",
"model_id": 1,
"model_name": "Serie 1",
"model_image_url": "https://www.bmw.pt/content/dam/bmw/common/all-models/1-series/5-door/2019/navigation/bmw-1-series-modelfinder.png",
"bodywork_id": 1,
"bodywork_name": "Coupé",
"fuel_id": 1,
"fuel_name": "Gasolina",
"Motorization_id": 1,
"Motorization_name": "Manual",
"rims_id": 1,
"rims_name": "Preto fosco\r\n5 raios",
"serie_id": 1,
"serie_name": "120",
"Interior_equipment_id": 1,
"Interior_equipment_name": "Bancos desportivos\r\n",
"Upholstery_id": 1,
"Upholstery_name": "Preto",
"Upholstery_Leather_fabric_name": "Preto",
"ilumination_id": 1,
"ilumination_name": "Iluminação ambiente",
"external_equipment_id": 1,
"external_equipment_name": "Para-choques desportivos",
"date_start_min": "03/18",
"date_end_max": "09/19"
}
]
}
}
''';
http.Response response = http.Response(jsonString, 200);
if (response.statusCode == 200) {
String postProcessing =
response.body.replaceAll('\n', "").replaceAll('\r', "");
var responseJson = settingByUserModel(postProcessing);
print(responseJson.toJson().toString());
return responseJson;
}
}
#override
void initState() {
_list = getUserSettings();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: _list,
builder:
(context, AsyncSnapshot<ResponseObjectSettingByUser> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data.array.car.length,
itemBuilder: (context, index) {
return Card(
elevation: 6.0,
child: Padding(
padding: const EdgeInsets.only(
top: 6.0,
bottom: 6.0,
left: 8.0,
right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(snapshot
.data.array.car[index].markName),
Spacer(),
Text(snapshot
.data.array.car[index].id.toString()),
],
),
));
});
}
}
}));
}
}
Related
Hi I have a json corresponding to that I need to fetch data but no data is being shown on the screen don't know why most probably Implementation is wrong
class TestScreen extends StatefulWidget {
const TestScreen({Key? key}) : super(key: key);
#override
State<TestScreen> createState() => _TestScreenState();
}
class _TestScreenState extends State<TestScreen> {
List<AppDetails> details = [];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: kBackgroundColor,
title: Text(
'Home',
style: Theme.of(context).textTheme.headline2,
),
),
body: Expanded(
child: ListView.builder(
itemCount: details.length,
itemBuilder: (context, index) {
final detail = details[index];
return buildProduct(detail);
}),
),
);
}
}
Widget buildProduct(AppDetails detail) => Column(
children: [Center(child: Text('${detail.benefits}'))],
);
Above is My Implementation
{
"name": "TestingApp",
"category": "Production",
"subcategory": "Productivity",
"imageUrl": "Testing-Banner.jpg",
"logo": "PI.png",
"description": "Testing is an application for easy & effective Inspection",
"appDetails": [{
"systemOverview": "https:url.com",
"multiDeviceSupport": [{
"label": "Multi-Device"
},
{
"label": "Multi-Lingual"
},
{
"label": "Multi-Database"
}
],
"mainFeatures": [{
"label": "Testing"
},
{
"label": "Ease"
},
{
"label": "Select failure "
},
{
"label": "Add comments & take evidence Pictures"
},
{
"label": "Send results to central system"
},
{
"label": "Search/view "
}
],
"benefits": [{
"label": "Easy & quick solution "
},
{
"label": "Go paperless "
},
{
"label": "Lower costs"
},
{
"label": "Improve quality/safety"
},
{
"label": "Configurable on hand-held devices and tablets"
},
{
"label": "Electronic notifications to corresponding personnel’s"
}
]
}]
}
Following is a json sample
I need to show all the benefits similarly all the multidevice support Or can say all the app details but in different kind of a container.
any help would be great.
is this what you want?
try this code or try on dartpad
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MaterialApp(home: TestScreen()));
}
class TestScreen extends StatefulWidget {
const TestScreen({Key? key}) : super(key: key);
#override
State<TestScreen> createState() => _TestScreenState();
}
class _TestScreenState extends State<TestScreen> {
List<AppDetails>? details = [];
final Map<String, dynamic> json = {
"name": "TestingApp",
"category": "Production",
"subcategory": "Productivity",
"imageUrl": "Testing-Banner.jpg",
"logo": "PI.png",
"description": "Testing is an application for easy & effective Inspection",
"appDetails": [
{
"systemOverview": "https:url.com",
"multiDeviceSupport": [
{"label": "Multi-Device"},
{"label": "Multi-Lingual"},
{"label": "Multi-Database"}
],
"mainFeatures": [
{"label": "Testing"},
{"label": "Ease"},
{"label": "Select failure "},
{"label": "Add comments & take evidence Pictures"},
{"label": "Send results to central system"},
{"label": "Search/view "}
],
"benefits": [
{"label": "Easy & quick solution "},
{"label": "Go paperless "},
{"label": "Lower costs"},
{"label": "Improve quality/safety"},
{"label": "Configurable on hand-held devices and tablets"},
{"label": "Electronic notifications to corresponding personnel’s"}
]
}
]
};
#override
void initState() {
super.initState();
final data = AppDetailModel.fromJson(json);
details = data.appDetails;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.blue,
title: const Text('Home'),
),
body: SizedBox(
child: ListView.builder(
itemCount: details?.length,
itemBuilder: (context, index) {
final detail = details?[index];
return buildProduct(detail);
},
),
),
);
}
}
Widget buildProduct(AppDetails? detail) => Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: (detail?.benefits ?? []).map((e) {
final index = (detail?.benefits ?? []).indexOf(e);
return Row(
children: [
SizedBox(width: 20, child: Text('${index + 1}.')),
Text('${e.label}'),
],
);
}).toList(),
),
);
class AppDetailModel {
String? name;
String? category;
String? subcategory;
String? imageUrl;
String? logo;
String? description;
List<AppDetails>? appDetails;
AppDetailModel(
{this.name,
this.category,
this.subcategory,
this.imageUrl,
this.logo,
this.description,
this.appDetails});
AppDetailModel.fromJson(Map<String, dynamic> json) {
name = json['name'];
category = json['category'];
subcategory = json['subcategory'];
imageUrl = json['imageUrl'];
logo = json['logo'];
description = json['description'];
if (json['appDetails'] != null) {
appDetails = <AppDetails>[];
json['appDetails'].forEach((v) {
appDetails!.add(AppDetails.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['name'] = name;
data['category'] = category;
data['subcategory'] = subcategory;
data['imageUrl'] = imageUrl;
data['logo'] = logo;
data['description'] = description;
if (appDetails != null) {
data['appDetails'] = appDetails!.map((v) => v.toJson()).toList();
}
return data;
}
}
class AppDetails {
String? systemOverview;
List<Label>? multiDeviceSupport;
List<Label>? mainFeatures;
List<Label>? benefits;
AppDetails(
{this.systemOverview,
this.multiDeviceSupport,
this.mainFeatures,
this.benefits});
AppDetails.fromJson(Map<String, dynamic> json) {
systemOverview = json['systemOverview'];
if (json['multiDeviceSupport'] != null) {
multiDeviceSupport = <Label>[];
json['multiDeviceSupport'].forEach((v) {
multiDeviceSupport!.add(Label.fromJson(v));
});
}
if (json['mainFeatures'] != null) {
mainFeatures = <Label>[];
json['mainFeatures'].forEach((v) {
mainFeatures!.add(Label.fromJson(v));
});
}
if (json['benefits'] != null) {
benefits = <Label>[];
json['benefits'].forEach((v) {
benefits!.add(Label.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['systemOverview'] = systemOverview;
if (multiDeviceSupport != null) {
data['multiDeviceSupport'] =
multiDeviceSupport!.map((v) => v.toJson()).toList();
}
if (mainFeatures != null) {
data['mainFeatures'] = mainFeatures!.map((v) => v.toJson()).toList();
}
if (benefits != null) {
data['benefits'] = benefits!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Label {
String? label;
Label({this.label});
Label.fromJson(Map<String, dynamic> json) {
label = json['label'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['label'] = label;
return data;
}
}
Hello I have a question regarding filtering of nested json response from an API.
Suppose I have this sample JSON response from an API:
{
"results": {
"data": {
"parentName": "Vic",
"parentFamName": "Lo",
"children": [
{
"childName": "Mark",
"childCount": 2,
"grandChildren": [
{
"grandChildName": "Kent",
"grandChildAge": 4,
"isBoy": true,
},
{
"grandChildName": "Chris",
"grandChildAge": 8
"isBoy": true,
}]
},
{
"childName": "Kim",
"childCount": 3,
"grandChildren": [
{
"grandChildName": "Martin",
"grandChildAge": 6,
"isBoy": true,
},
{
"grandChildName": "Thesa",
"grandChildAge": 4
"isBoy": false,
},
{
"grandChildName": "Beck",
"grandChildAge": 2,
"isBoy": false,
}]
}]
}
}
}
then ill be decoding the response by:
final jsonResponse = jsonDecode(jsonString.body);
final parentResponse = jsonResponse['results']['data'];
But before I display it in a ListView.builder,
how do I filter the parenetResponse wherein it will only include "isBoy" = true?
like the final data response to display would be:
{
"results": {
"data": {
"parentName": "Vic",
"parentFamName": "Lo",
"children": [
{
"childName": "Mark",
"childCount": 2,
"grandChildren": [
{
"grandChildName": "Kent",
"grandChildAge": 4,
"isBoy": true,
},
{
"grandChildName": "Chris",
"grandChildAge": 8
"isBoy": true,
}]
},
{
"childName": "Kim",
"childCount": 3,
"grandChildren": [
{
"grandChildName": "Martin",
"grandChildAge": 6,
"isBoy": true,
},
]
}]
}
}
}
Thank you for any help!
First create model class to parse your json:
class ParentModel {
final String parentName;
final List<ChildrenModel> children;
ParentModel({required this.parentName, required this.children});
static ParentModel fromJson(Map<String, dynamic> json) {
var children = json['children'] as List;
return ParentModel(
parentName: json['parentName'],
children: children.map((e) => ChildrenModel.fromJson(e)).toList());
}
}
class ChildrenModel {
final int count;
final String name;
final List<GrandChildModel> grandChildren;
ChildrenModel({
required this.count,
required this.name,
required this.grandChildren,
});
static ChildrenModel fromJson(Map<String, dynamic> json) {
var grandChildren = json["grandChildren"] as List;
return ChildrenModel(
count: json['childCount'],
name: json['childName'],
grandChildren:
grandChildren.map((e) => GrandChildModel.fromJson(e)).toList());
}
}
class GrandChildModel {
final int age;
final String name;
final bool isBoy;
GrandChildModel({required this.age, required this.name, required this.isBoy});
static GrandChildModel fromJson(Map<String, dynamic> json) {
return GrandChildModel(
age: json['grandChildAge'],
name: json['grandChildName'],
isBoy: json['isBoy']);
}
}
then use this to show the boy grandChildren:
class TestParent extends StatefulWidget {
const TestParent({super.key});
#override
State<TestParent> createState() => _TestParentState();
}
class _TestParentState extends State<TestParent> {
#override
Widget build(BuildContext context) {
final parentResponse = jsonResponse['results']!['data'];
var parent = ParentModel.fromJson(parentResponse!);
return Scaffold(
appBar: AppBar(title: Text("Testing")),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: parent.children.length,
itemBuilder: (context, index) {
return ListView.builder(
shrinkWrap: true,
itemCount: parent.children[index].grandChildren.length,
itemBuilder: (context, i) {
var grandChild = parent.children[index].grandChildren[i];
if (grandChild.isBoy) {
return Text(grandChild.name);
} else {
return SizedBox();
}
},
);
},
),
)
],
),
);
}
}
Note that here jsonResponse is your json;
result:
Without making model classes you could simply modify the response like this:
parentResponse['children'] = parentResponse['children']
.map((child) => child
..['grandChildren'] = child['grandChildren']
.where((grandChild) => grandChild['isBoy'] as bool)
.toList())
.toList();
I want to access up to the "model" key parameter in my listview builder for the provided json format in flutter but I don't know how can I access them
I want to access the child object model
What the json will look like:
[
{
"vehicle": "roadways",
"id": "10000",
"category": {
"500": {
"id": "500",
"name": "Bike",
"icon": "http://example.com/bike.jpg",
"model": [
{
"id": "510",
"name": "Harley"
},
{
"id": "520",
"name": "Kawasaki"
}
]
},
"50": {
"id": "50",
"name": "Car",
"icon": "http://example.com/car.jpg",
}
},
},
{
"vehicle": "waterways",
"id": "20000",
"category": {
"600": {
"id": "600",
"name": "Ship",
"icon": "http://example.com/ship.jpg",
"model": [
{
"id": "610",
"name": "model_1"
},
{
"id": "520",
"name": "model_2"
}
]
},
"700": {
"id": "700",
"name": "model_3",
"icon": "http://example.com/car.jpg",
}
},
}
]
var data = jsonDecode("yourJosnString");
ListView.builder(
itemCount: data.length,
itemBuilder: (context, i) {
var data1 = data[i]["category"];
String firstKey = data1.keys.first;
var model = data1[firstKey];
return Column(
children: [
for (i = 0; i < model.length; i++) ...[
Text(
model["name"],
)
]
],
);
},
),
you should first make an object for this json, like this:
class Vehicle {
final String name;
final VehicleCategory category;
Vehicle({#required this.name, #required this.category});
static List<Vehicle> fromJson(List _list) {
List<Vehicle> result = [];
for (var item in _list) {
var address = Vehicle(
name: item['id'] as String,
category: VehicleCategory.fromJson(
item['category']['500'] as Map<String, Object> ?? {}),
);
result.add(address);
}
return result;
}
}
class VehicleCategory {
final String name;
final String icon;
final List<VehicleModel> model;
VehicleCategory(
{#required this.name, #required this.icon, #required this.model});
static VehicleCategory fromJson(Map<String, Object> _json) {
return VehicleCategory(
name: _json['name'] as String ?? '',
icon: _json['icon'] as String ?? '',
model:
VehicleModel.fromJson(_json['model'] as List ?? []));
}
}
class VehicleModel {
final String name;
final String id;
VehicleModel({#required this.name, #required this.id});
static List<VehicleModel> fromJson(List _list) {
List<VehicleModel> result = [];
for (var item in _list) {
var address = VehicleModel(
name: item['name'] as String,
id: item['id'] as String,
);
result.add(address);
}
return result;
}
}
then use it like this:
List<Vehicle> _list = Vehicle.fromJson(_myJson);
return ListView.builder(
itemCount: _list.length,
itemBuilder: (context, i) {
return Column(
children: [
ListView.builder(
itemCount: _list[i].category.model.length,
itemBuilder: (context, j) {
return Text(_list[i].category.model[j].name);
},
)
],
);
},
);
i have a super long json file to be parsed but once i fetch it in a FutureBuilder it keeps erroring that i used a null check operator on a null value, to me seems like i don't know the logic..!
here's the simplified json:
{
"city": {
"Name": "oklahoma",
"Month": [
{
"number": "01",
"day": [
{
"number": "01",
"employee": "jesse m."
},
{
"number": "02",
"employee": "john s."
},
{
"number": "03",
"name": "tyler r."
}
]
},
{
"number": "02",
"day": [
{
"number": "01",
"employee": "mat w."
},
{
"number": "02",
"employee": "may j."
},
{
"number": "03",
"name": "eric r."
}
]
}
]
}
}
note that i have one city and the json has the data of every individual days throughout the whole year
and here's the model:
// To parse this JSON data, do
//
// final company = companyFromJson(jsonString);
import 'dart:convert';
company companyFromJson(String str) => company.fromJson(json.decode(str));
String companyToJson(company data) => json.encode(data.toJson());
class company {
company({
required this.city,
});
City city;
factory company.fromJson(Map<String, dynamic> json) => company(
city: City.fromJson(json["city"]),
);
Map<String, dynamic> toJson() => {
"city": city.toJson(),
};
}
class City {
City({
required this.name,
required this.month,
});
String name;
List<Month> month;
factory City.fromJson(Map<String, dynamic> json) => City(
name: json["Name"],
month: List<Month>.from(json["Month"].map((x) => Month.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Name": name,
"Month": List<dynamic>.from(month.map((x) => x.toJson())),
};
}
class Month {
Month({
required this.number,
required this.day,
});
String number;
List<Day> day;
factory Month.fromJson(Map<String, dynamic> json) => Month(
number: json["number"],
day: List<Day>.from(json["day"].map((x) => Day.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"number": number,
"day": List<dynamic>.from(day.map((x) => x.toJson())),
};
}
class Day {
Day({
required this.number,
required this.employee
});
String number;
String employee;
factory Day.fromJson(Map<String, dynamic> json) => Day(
number: json["number"],
employee: json["employee"]
);
Map<String, dynamic> toJson() => {
"number": number,
"employee": employee
};
}
this is the parsing method:
Future<List<Day>> getCompanyEmployee () async {
String jsonString = await DefaultAssetBundle.of(context).loadString('assets/json/OklahomaEmployee.json');
List<dynamic> result = jsonDecode(jsonString);
List<Day> Company = result.map((e) => Day.fromJson(e)).toList();
return Company;
}
this is the implementation:
FutureBuilder<List<Day>>(
future: getCompanyEmployee(),
builder: (context, snapshot) {
var itemList = snapshot.data;
return GridView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
),
itemCount: itemList!.length,
itemBuilder: (BuildContext context, index) {
var itemData = itemList[index];
return ClipRRect(
borderRadius: BorderRadius.circular(25),
child: Container(
height: 10,
color: Colors.white,
width: 10,
child: Center(
child: Column(
children: [
Text(
'employee',
style: TextStyle(fontSize: 15),
),
Text(itemData.employee),
Image.asset(
'assets/Pictures/employees.png',
height: 70,
)
],
),
),
),
);
},
);
},
)
In your FutureBuilder, you just assume the future has already completed. The point of a FutureBuilder is that it has not and you need to deal with that.
You need to account for the fact that your Futurebuilder needs to build something even if the future has not yet completed. The simplest thing to make that happen is to show a CircularProgressIndicator as long as you don't have data.
See What is a Future and how do I use it? for an example of how to do that.
I'm able to parse the JSON using following code,
Map<String, dynamic> map = jsonDecode(response.body); // import 'dart:convert';
List<dynamic> datalist = map['data'];
I got List dynamic but i need data list
My problem is if I get product items in data list then how should i parse the JSON. I got stuck here.
When it comes to nested array of JSON, how to parse it.
**
{
"status": 0,
"message": "Product Not Found",
"data": [{
"id": "1",
"product_name": "Pet 0.5",
"qty": "500",
"unit": "ml",
"product_img": "SRC.jpg",
"description": "sgsdgdfhdfhh",
"sale_price": "100",
"donation_amt": "10"
},
{
"id": "7",
"product_name": "Pet 1l",
"qty": "1",
"unit": "l",
"product_img": "SRC1.jpg",
"description": "dgdg",
"sale_price": "20",
"donation_amt": "1"
}
]
}
**
My dart code for the JSON
class ProductList {
int status;
String message;
List<Data> data;
ProductList({this.status, this.message, this.data});
ProductList.fromJson(Map<String, dynamic> json) {
status = json['status'];
message = json['message'];
if (json['data'] != null) {
data = new List<Data>();
json['data'].forEach((v) {
data.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['message'] = this.message;
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
String id;
String productName;
String qty;
String unit;
String productImg;
String description;
String salePrice;
String donationAmt;
Data(
{this.id,
this.productName,
this.qty,
this.unit,
this.productImg,
this.description,
this.salePrice,
this.donationAmt});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
productName = json['product_name'];
qty = json['qty'];
unit = json['unit'];
productImg = json['product_img'];
description = json['description'];
salePrice = json['sale_price'];
donationAmt = json['donation_amt'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['product_name'] = this.productName;
data['qty'] = this.qty;
data['unit'] = this.unit;
data['product_img'] = this.productImg;
data['description'] = this.description;
data['sale_price'] = this.salePrice;
data['donation_amt'] = this.donationAmt;
return data;
}
}
This is the code below for the drop down list. We need to populate the drop down with the product name and id. The product name and id fields are there in the data part of the JSON
Padding(
padding: const EdgeInsets.fromLTRB(25.0, 20.0, 0, 0),
child: Container(
width: 160,
height: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
border: Border.all(
color: Colors.red,
style: BorderStyle.solid,
width: 0.80),
),
child: DropdownButton<Product>(
value: selectedUser,
icon: Padding(
padding: const EdgeInsets.only(left:15.0),
child: Icon(Icons.arrow_drop_down),
),
iconSize: 25,
underline: SizedBox(),
onChanged: (Product newValue) {
setState(() {
selectedUser = newValue;
});
},
items: users.map((Product user) {
return DropdownMenuItem<Product>(
value: user,
child: Padding(
padding:
const EdgeInsets.only(left: 10.0),
child: Text(
user.name,
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
);
}).toList()),
),
),
So as you Described i have made some changes and loaded you json locally, you can make a api call and then everything is the same:
{
"status": 0,
"message": "Product Not Found",
"data": [
{
"id": "1",
"product_name": "Pet 0.5",
"qty": "500",
"unit": "ml",
"product_img": "SRC.jpg",
"description": "sgsdgdfhdfhh",
"sale_price": "100",
"donation_amt": "10"
},
{
"id": "7",
"product_name": "Pet 1l",
"qty": "1",
"unit": "l",
"product_img": "SRC1.jpg",
"description": "dgdg",
"sale_price": "20",
"donation_amt": "1"
}
]
}
json you provided
// To parse this JSON data, do
//
// final productList = productListFromJson(jsonString);
import 'dart:convert';
ProductList productListFromJson(String str) =>
ProductList.fromJson(json.decode(str));
String productListToJson(ProductList data) => json.encode(data.toJson());
class ProductList {
int status;
String message;
List<Datum> data;
ProductList({
this.status,
this.message,
this.data,
});
factory ProductList.fromJson(Map<String, dynamic> json) => ProductList(
status: json["status"],
message: json["message"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
String id;
String productName;
String qty;
String unit;
String productImg;
String description;
String salePrice;
String donationAmt;
Datum({
this.id,
this.productName,
this.qty,
this.unit,
this.productImg,
this.description,
this.salePrice,
this.donationAmt,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
productName: json["product_name"],
qty: json["qty"],
unit: json["unit"],
productImg: json["product_img"],
description: json["description"],
salePrice: json["sale_price"],
donationAmt: json["donation_amt"],
);
Map<String, dynamic> toJson() => {
"id": id,
"product_name": productName,
"qty": qty,
"unit": unit,
"product_img": productImg,
"description": description,
"sale_price": salePrice,
"donation_amt": donationAmt,
};
}
creating the model class for the json
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sample_testing_project/models.dart';
main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _currentSelectedValue;
List<Datum> data = List();
bool _isLoading = false;
String selectedUser;
#override
void initState() {
// TODO: implement initState
super.initState();
loadYourData();
}
Future<String> loadFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
loadYourData() async {
setState(() {
_isLoading = true;
});
// Loading your json locally you can make an api call, when you get the response just pass it to the productListFromJson method
String jsonString = await loadFromAssets();
final productList = productListFromJson(jsonString);
data = productList.data;
setState(() {
_isLoading = false;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: _isLoading
? Text('Loading')
: Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(25.0, 20.0, 0, 0),
child: Container(
width: 160,
height: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
border: Border.all(
color: Colors.red,
style: BorderStyle.solid,
width: 0.80),
),
child: DropdownButton(
value: selectedUser,
isExpanded: true,
icon: Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Icon(Icons.arrow_drop_down),
),
iconSize: 25,
underline: SizedBox(),
onChanged: (newValue) {
setState(() {
selectedUser = newValue;
});
},
hint: Padding(
padding: const EdgeInsets.all(8.0),
child: Text('Select'),
),
items: data.map((data) {
return DropdownMenuItem(
value: data.id,
child: Padding(
padding: const EdgeInsets.only(left: 10.0),
child: Text(
data.id + ':' + data.productName,
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
);
}).toList()),
),
),
),
),
);
}
}
check out the changes that i have made using your same ui.
Let me know if its working.
Thanks.
Remember: "JSON is not 'nested.'" When you're given a JSON string, you decode it and this gives you a data-structure ... which very well might be "nested." How to handle that correctly is up to you.
Always treat JSON (or YAML, or XML) as a "black box." Use the utilities provided in the language to encode, decode and parse them.