showing key along side data json - json

Hi I have a dynamic json the details in it changes in every product so I wanna show keys along side their corresponding data
any example would be great I am struggling with this. sample json in appDetails wanna show all the keys like systemoverview,benefits, mainFeatures and their data.
In next product it will be changed but appdetails will remain same.
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": [
{"item1": "Multi-Device"},
{"item2": "Multi-Lingual"},
{"item3": "Multi-Database"}
],
"mainFeatures": [
{"feature1": "Testing"},
{"feature2": "Ease"},
{"feature3": "Select failure "}
],
"benefits": [
{"benfits1": "Easy & quick solution "},
{"benefits2": "Go paperless "},
personnel’s"}
]
}
]
};
#override
void initState() {
super.initState();
final data = AppDetailModel.fromJson(json);
details = data.appDetails;
List<AppDetails>? parseCategorizedBooksJson(Map<String, dynamic> json) => [
for (var detai in json.values)
for (var de in detai) AppDetails.fromJson(de)
];
}
#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;
}
}
```
currently What I am doing right now

so taking your example:
final map = {
"appDetails": [
{
"systemOverview": "https:url.com",
"multiDeviceSupport": [
{"label": "Multi-Device"}
],
"mainFeatures": [
{"label": "Testing"}
],
"benefits": [
{"label": "Easy & quick solution "},
{"label": "Go paperless "}
]
}
]
};
we can get both the key and value using the entries like this:
map!["appDetails"]![0].entries.forEach((e) {
print("${e.key}, ${e.value}");
});
This code will print this result:
systemOverview, https:url.com
multiDeviceSupport, [{label: Multi-Device}]
mainFeatures, [{label: Testing}]
benefits, [{label: Easy & quick solution }, {label: Go paperless }]
it will print the key along with it's value, you can use this sample to achieve your result.

print all keys of JSON data
var data = convert.jsonDecode(response.body);
print(data.keys.toList());

you can do somthing like this
Column(children:
data['appDetails']
.map(
(system) => Column(
children: system.entries
.map<Widget>(
(systemeEntry) => systemeEntry.value is String
? Row(
children: [
Text("${systemeEntry.key}: "),
Expanded(child: Text(systemeEntry.value)),
],
)
: systemeEntry.value is List
? Row(
children: [
Text(" ${systemeEntry.key} => "),
Expanded(
child: Column(
children:
systemeEntry.value is List
? systemeEntry.value
.map<Widget>(
(detail) => Column(
children: [
...detail
.entries
.map(
(detailEntry) =>
Row(
children: [
Text(" ${detailEntry.key}: "),
Text(detailEntry.value),
]),
)
.toList()
]),
)
.toList()
: [const SizedBox()],
),
)
],
)
: const SizedBox(),
)
.toList(),
),
)
.toList(),
)

Related

How can i pass this complex Json MAP Data into flutter Listview

i am new to flutter, and i meet this API with complex "MAP" json. What i want is to display the list of countries with their details in flutter listview, How can i achieve that? Most of answers explain about "LIST" json.
{
"status": "Request is successful",
"message": null,
"data": {
"page": 1,
"last_page": 125,
"page_size": 2,
"countries": [
{
"id": "1",
"attributes": {
"name": "Grenada",
"code": "GD",
"subregion": "Caribbean",
"flag": "https://flagcdn.com/gd.svg",
"postalcode": "",
"latitude": "12.11666666",
"longitude": "-61.66666666",
"createdAt": "2023-01-11T22:15:40.000000Z",
"updatedAt": "2023-01-11T22:15:40.000000Z"
}
},
{
"id": "2",
"attributes": {
"name": "Malaysia",
"code": "MY",
"subregion": "South-Eastern Asia",
"flag": "https://flagcdn.com/my.svg",
"postalcode": "^(\\d{5})$",
"latitude": "2.5",
"longitude": "112.5",
"createdAt": "2023-01-11T22:15:40.000000Z",
"updatedAt": "2023-01-11T22:15:40.000000Z"
}
}
]
}
}
I found this GitHub project with these files json, modelClass Mainclass which relate with the concept but mine is has got one extra braces (map) so i do not know how to achieve the goal.
if there any suggestion or best way to code please help me.
this is how they created in model class but, but it does not work with me.
class Product {
final List<Result> results;
Product({this.results});
factory Product.fromJson(Map<String, dynamic> data) {
var list = data['data']['result'] as List;
List<Result> resultList = list.map((e) => Result.fromJson(e)).toList();
return Product(
results: resultList,
);
}
}
what i have done is
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
var data_from_link;
getData() async {
final String link = 'myurl';
data_from_link = await http.get(Uri.parse(link), headers: {"Accept": "application/json"});
final res = jsonDecode(data_from_link.body) as Map<String, dynamic>;
final List<Country> list= (res['data']['countries'] as List<dynamic>).map((e) => Country.fromJson(e))
.toList();
}
#override
void initState() {
super.initState();
getData();
}
#override
Widget build(BuildContext context) {
final res = jsonDecode(data_from_link.body) as Map<String, dynamic>;
final List<Country> list= (res['data']['countries'] as List<dynamic>).map((e) => Country.fromJson(e))
.toList();
return ListView.builder(
itemCount: list.length,
itemBuilder: (_, i) => ListTile(
title: Text(
list![i].attributes.name,
),
subtitle: Text(list![i].attributes.code),
)
);
}
}
You can create two classes for Country and Attribute
class Country {
const Country({required this.id, required this.attributes});
/// Creates a Country from Json map
factory Country.fromJson(Map<String, dynamic> json) => Country(
id: json['id'] as String,
attribute:
Attribute.fromJson(json['attributes'] as Map<String, dynamic>),
);
/// A description for id
final String id;
final Attribute attributes;
}
class Attribute {
const Attribute({
required this.name,
required this.code,
required this.createdAt,
required this.updatedAt,
});
/// Creates a Attribute from Json map
factory Attribute.fromJson(Map<String, dynamic> json) => Attribute(
name: json['name'] as String,
code: json['code'] as String,
createdAt: DateTime.parse(json['createdAt'] as String),
updatedAt: DateTime.parse(json['updatedAt'] as String),
);
final String name;
final String code;
final DateTime createdAt;
final DateTime updatedAt;
}
when decoding:
final res = jsonDecode(json) as Map<String, dynamic>;
final List<Country> list = (res['data']['countries'] as
List<dynamic>)
.map((e) => Country.fromJson(e))
.toList();
Thank you but how can i print or call data from country attribute
after decoding because when i try something like Print
(list.country.attribute.name) . I fail. My goal is to display on
Listview
You can use it like this:
ListView.builder(
itemCount: list.length,
itemBuilder: (_, i) => ListTile(
title: Text(
list[i].attributes.name,
),
subtitle: Text(list[i].attributes.code),
)),
UPDATE
import 'package:flutter/material.dart';
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
late Future<List<Country>> futureList;
Future<List<Country>?> getData() async {
final String link = 'yoururl';
final res = await http
.get(Uri.parse(link), headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
final List<Country> list = (res['data']['countries'] as List<dynamic>)
.map((e) => Country.fromJson(e))
.toList();
return list;
} else {
throw Exception('Failed to fetch data');
}
}
#override
void initState() {
super.initState();
futureList = getData();
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: futureList,
builder: (context, snapshot) {
if (snapshot.hasData) {
final list = snapshot.data;
return ListView.builder(
itemCount: list!.length,
itemBuilder: (_, i) => ListTile(
title: Text(
list![i].attributes.name,
),
subtitle: Text(list![i].attributes.code),
),
);
} else if (snapshot.hasError) {
return const Text('error fetching data');
}
return const CircularProgressIndicator();
},
);
}
}

Parsing Json data in flutter

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;
}
}

Show nested JSON from API in single Page with multiple lists

Im new in Flutter and i'm struggeling with a nested JSON from API which data i want to show in one single page.
I get this JSON from a URL and decode it in a class, which is working fine:
{
"service1": [
{
"firstname": "Peter",
"lastname": "Smith"
},
{
"firstname": "Paul",
"lastname": "Johnson"
}
],
"service2": [
{
"firstname": "Mary",
"lastname": "Williams"
},
{
"firstname": "Guy",
"lastname": "Brown"
}
]
}
Classes:
/*------------------------------
staff.dart
------------------------------*/
import 'dart:convert';
class Staff {
String? service;
String? firstname;
String? lastname;
Staff({this.service, this.firstname, this.lastname});
factory Staff.fromMap(Map<String, dynamic> data) => Staff(
service: data['service'] as String?,
firstname: data['firstname'] as String?,
lastname: data['lastname'] as String?,
);
Map<String, dynamic> toMap() => {
'service': '',
'firstname': firstname,
'lastname': lastname,
};
/// Parses the string and returns the resulting Json object.
factory Staff.fromJson(String data) {
return Staff.fromMap(json.decode(data) as Map<String, dynamic>);
}
/// Converts [Staff] to a JSON string.
String toJson() => json.encode(toMap());
}
/*------------------------------
servicedesk.dart
------------------------------*/
import 'dart:convert';
import 'staff.dart';
class ServiceDesk {
List<Staff>? service1;
List<Staff>? service2;
ServiceDesk({
this.service1,
this.service2,
});
factory ServiceDesk.fromMap(Map<String, dynamic> data) => ServiceDesk(
service1: (data['service1'] as List<dynamic>?)
?.map((e) => Staff.fromMap(e as Map<String, dynamic>))
.toList(),
service2: (data['service2'] as List<dynamic>?)
?.map((e) => Staff.fromMap(e as Map<String, dynamic>))
.toList(),
);
Map<String, dynamic> toMap() => {
'service1': service1?.map((e) => e.toMap()).toList(),
'service2': service2?.map((e) => e.toMap()).toList(),
};
/// Parses the string and returns the resulting Json object as [ServiceDesk].
factory ServiceDesk.fromJson(String data) {
var object = ServiceDesk.fromMap(json.decode(data) as Map<String, dynamic>);
object.b1!.insert(0, Staff(service: 'Title for Service1'));
object.b2!.insert(0, Staff(service: 'Title for Service2'));
return object;
}
/// Converts to a JSON string.
String toJson() => json.encode(toMap());
}
That's the code i have (Pseudocode between):
// PSEUDOCODE!!
Widget ListWithService(List<Staff>? entry) {
return ListView.builder(
itemCount: entry!.length,
padding: const EdgeInsets.all(2.0),
itemBuilder: (context, position) {
final item = entry[position];
if (item.service != null) {
return ListTile(
title: Text(
'${item.service}',
style: Theme.of(context).textTheme.headline5,
),
);
} else {
return ListTile(
title: Text(
'${item.firstname} ${item.lastname}',
style: Theme.of(context).textTheme.bodyText1,
),
);
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Service Desk'),
),
body: FutureBuilder<sdclass.ServiceDesk>(
future: getData(),
builder: (context, snapshot) {
if (snapshot.hasData == true) {
return [
ListWithService(snapshot.data.service1),
ListWithSercice(snapshot.data.service1);
] // PSEUDOCODE!!
} else if (snapshot.hasError) {
return const Icon(
Icons.error_outline,
color: Colors.red,
size: 60,
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
}
),
);
}
What i would have at the end should look like this on the full page:
Title for Service1 (Headline)
Peter Smith
Paul Johnson
Title for Service2 (Headline)
Mary Williams
Guy Brown
Could someone help me with the code to get it work?
Update Code
Thanks for your updated example. I tested it in my code. First, everything looks fine. But wenn i switch to the screen with the json, i get a error:
Expected a value of type 'FutureOr<Map<String, List<Map<String, String>>>>', but got one of type '_JsonMap'
import 'dart:convert';
import 'dart:core';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class ServiceDesk extends StatelessWidget {
const ServiceDesk({Key? key}) : super(key: key);
Future<Map<String, List<Map<String, String>>>> getData() async {
String link = "https://url-to-json-file.json";
final res = await http
.get(Uri.parse(link), headers: {"Accept": "application/json"});
if (res.statusCode == 200) {
var utf8decoded = utf8.decode(res.body.toString().codeUnits);
var decoded = json.decode(utf8decoded);
return decoded;
} else {
throw Exception('Failed to load JSON');
}
}
Widget listViewWidget(
Iterable<MapEntry<String, List<Map<String, String>>>> entries) {
return ListView.builder(
itemCount: entries.length,
padding: const EdgeInsets.all(2.0),
itemBuilder: (context, index) {
final entry = entries.elementAt(index);
final key = entry.key;
final values = entry.value;
return Column(
children: [
ListTile(
title: Text(
'Title for $key',
style: Theme.of(context).textTheme.headline5,
),
),
for (var person in values)
ListTile(
title: Text(
'${person["firstname"]} ${person["lastname"]}',
style: Theme.of(context).textTheme.bodyText1,
),
),
],
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Service Desk'),
),
body: FutureBuilder(
future: getData(),
builder: (_,
AsyncSnapshot<Map<String, List<Map<String, String>>>> snapshot) {
if (snapshot.hasData == true) {
final entries = snapshot.data?.entries ?? {};
return listViewWidget(entries);
} else if (snapshot.hasError) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Icon(
Icons.error_outline,
color: Colors.red,
size: 60,
),
Text("Fehler: ${snapshot.error}"),
],
));
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
}),
);
}
}
In the Dart language, you can use for loop in the list, it makes it easier to work with Flutter UI.
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const RootView(),
);
}
}
class RootView extends StatelessWidget {
const RootView({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextButton(
child: const Text('GO TO SAFF SERVICE'),
onPressed: () {
Navigator.push(context, Home.route());
},
),
),
);
}
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
static Route route() {
return CupertinoPageRoute(builder: (_) => const Home());
}
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
late Future<StaffService> staffService;
#override
void initState() {
staffService = getStaffService();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Services')),
body: Center(
child: FutureBuilder<StaffService>(
future: staffService,
builder: (_, snapshot) {
if (snapshot.hasData) {
final saff = snapshot.data!;
return ListView(
children: [
if (saff.service1.isNotEmpty)
StaffServiceTile(
title: Text(
'Title for Service 1',
style: Theme.of(context).textTheme.headline5,
),
services: saff.service1,
),
if (saff.service2.isNotEmpty)
StaffServiceTile(
title: Text(
'Title for Service 2',
style: Theme.of(context).textTheme.headline5,
),
services: saff.service2,
),
],
);
} else if (snapshot.hasError) {
return const Text('Error on loaad data. Try again later.');
} else {
return const CircularProgressIndicator();
}
},
),
),
);
}
}
class StaffServiceTile extends StatelessWidget {
const StaffServiceTile({
Key? key,
required this.title,
required this.services,
}) : super(key: key);
final Widget title;
final List<Service> services;
#override
Widget build(BuildContext context) {
return Column(
children: [
ListTile(title: title),
for (var person in services)
ListTile(
title: Text(
'${person.firstname} ${person.lastname}',
),
),
],
);
}
}
class StaffService {
StaffService({this.service1 = const [], this.service2 = const []});
List<Service> service1, service2;
factory StaffService.fromJson(String str) {
return StaffService.fromMap(json.decode(str));
}
String toJson() => json.encode(toMap());
factory StaffService.fromMap(Map<String, dynamic> json) => StaffService(
service1: List<Service>.from(json["service1"].map((x) => Service.fromMap(x))),
service2: List<Service>.from(json["service2"].map((x) => Service.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"service1": List<dynamic>.from(service1.map((x) => x.toMap())),
"service2": List<dynamic>.from(service2.map((x) => x.toMap())),
};
}
class Service {
Service({this.firstname, this.lastname});
String? firstname, lastname;
factory Service.fromJson(String str) => Service.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Service.fromMap(Map<String, dynamic> json) => Service(
firstname: json["firstname"],
lastname: json["lastname"],
);
Map<String, dynamic> toMap() => {
"firstname": firstname,
"lastname": lastname,
};
}
Future<StaffService> getStaffService() async {
await Future.delayed(const Duration(seconds: 2));
return StaffService.fromMap(data); // <- use fromJson if you load data from the JSON.
}
final data = <String, List<Map<String, String>>>{
"service1": [
{"firstname": "Peter", "lastname": "Smith"},
{"firstname": "Paul", "lastname": "Johnson"}
],
"service2": [
{"firstname": "Mary", "lastname": "Williams"},
{"firstname": "Guy", "lastname": "Brown"}
]
};
Copy and paste in the DartPad to test it.

How to parse a complex Json value in flutter?

I have a JSON which is a combination of simple and complicated structures.Anyhow you can have a look at it.All I want is to get the "playlist_url": value and display it a listview builder.Along with that I want to parse for 2 text values which I am able to do.But the url part is where I am not able to resolve
The JSON structure(it is too long,thats y I have given the link): https://docs.google.com/document/d/1saJN3MQvG55M1ipf42-65Etowi_kW80gkrosU6vBb5o/edit?usp=sharing
The PODO file:
// To parse this JSON data, do
//
// final homePage = homePageFromJson(jsonString);
import 'dart:convert';
HomePage homePageFromJson(String str) => HomePage.fromJson(json.decode(str));
String homePageToJson(HomePage data) => json.encode(data.toJson());
class HomePage {
HomePage({
this.series,
this.homeBanners,
this.liveChannels,
this.publishers,
this.musicCategories,
this.musicPlaylists,
this.movies,
});
List<HomeBanner> series;
List<HomeBanner> homeBanners;
List<LiveChannel> liveChannels;
List<Publisher> publishers;
List<Music> musicCategories;
Music musicPlaylists;
List<HomeBanner> movies;
factory HomePage.fromJson(Map<String, dynamic> json) => HomePage(
series: List<HomeBanner>.from(
json["series"].map((x) => HomeBanner.fromJson(x))),
homeBanners: List<HomeBanner>.from(
json["home_banners"].map((x) => HomeBanner.fromJson(x))),
liveChannels: List<LiveChannel>.from(
json["live_channels"].map((x) => LiveChannel.fromJson(x))),
publishers: List<Publisher>.from(
json["publishers"].map((x) => Publisher.fromJson(x))),
musicCategories: List<Music>.from(
json["music_categories"].map((x) => Music.fromJson(x))),
musicPlaylists: Music.fromJson(json["music_playlists"]),
movies: List<HomeBanner>.from(
json["movies"].map((x) => HomeBanner.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"series": List<dynamic>.from(series.map((x) => x.toJson())),
"home_banners": List<dynamic>.from(homeBanners.map((x) => x.toJson())),
"live_channels":
List<dynamic>.from(liveChannels.map((x) => x.toJson())),
"publishers": List<dynamic>.from(publishers.map((x) => x.toJson())),
"music_categories":
List<dynamic>.from(musicCategories.map((x) => x.toJson())),
"music_playlists": musicPlaylists.toJson(),
"movies": List<dynamic>.from(movies.map((x) => x.toJson())),
};
}
class HomeBanner {
HomeBanner({
this.movieId,
this.title,
this.tags,
this.genres,
this.thumbnail,
this.posterLink,
this.platform,
this.worldwide,
this.createdAt,
this.seriesId,
});
String movieId;
String title;
List<String> tags;
List<String> genres;
List<String> thumbnail;
String posterLink;
Platform platform;
double worldwide;
DateTime createdAt;
String seriesId;
factory HomeBanner.fromJson(Map<String, dynamic> json) => HomeBanner(
movieId: json["movie_id"] == null ? null : json["movie_id"],
title: json["title"],
tags: List<String>.from(json["tags"].map((x) => x)),
genres: List<String>.from(json["genres"].map((x) => x)),
thumbnail: List<String>.from(json["thumbnail"].map((x) => x)),
posterLink: json["poster_link"],
platform: platformValues.map[json["platform"]],
worldwide: json["WORLDWIDE"],
createdAt: DateTime.parse(json["createdAt"]),
seriesId: json["series_id"] == null ? null : json["series_id"],
);
Map<String, dynamic> toJson() => {
"movie_id": movieId == null ? null : movieId,
"title": title,
"tags": List<dynamic>.from(tags.map((x) => x)),
"genres": List<dynamic>.from(genres.map((x) => x)),
"thumbnail": List<dynamic>.from(thumbnail.map((x) => x)),
"poster_link": posterLink,
"platform": platformValues.reverse[platform],
"WORLDWIDE": worldwide,
"createdAt": createdAt.toIso8601String(),
"series_id": seriesId == null ? null : seriesId,
};
}
enum Platform { YOUTUBE, DISCOVERYPLUS }
final platformValues = EnumValues(
{"discoveryplus": Platform.DISCOVERYPLUS, "youtube": Platform.YOUTUBE});
class LiveChannel {
LiveChannel({
this.keyId,
this.postContent,
this.publisherId,
this.publisherName,
this.publisherProfilePic,
this.publisherDesc,
this.downvotesCount,
this.upvotesCount,
});
String keyId;
PostContent postContent;
String publisherId;
String publisherName;
String publisherProfilePic;
String publisherDesc;
int downvotesCount;
int upvotesCount;
factory LiveChannel.fromJson(Map<String, dynamic> json) => LiveChannel(
keyId: json["key_id"],
postContent: PostContent.fromJson(json["post_content"]),
publisherId: json["publisher_id"],
publisherName: json["publisher_name"],
publisherProfilePic: json["publisher_profile_pic"],
publisherDesc: json["publisher_desc"],
downvotesCount: json["downvotes_count"],
upvotesCount: json["upvotes_count"],
);
Map<String, dynamic> toJson() => {
"key_id": keyId,
"post_content": postContent.toJson(),
"publisher_id": publisherId,
"publisher_name": publisherName,
"publisher_profile_pic": publisherProfilePic,
"publisher_desc": publisherDesc,
"downvotes_count": downvotesCount,
"upvotes_count": upvotesCount,
};
}
class PostContent {
PostContent({
this.shortcode,
this.platformVideoLink,
this.caption,
this.description,
});
String shortcode;
String platformVideoLink;
String caption;
String description;
factory PostContent.fromJson(Map<String, dynamic> json) => PostContent(
shortcode: json["shortcode"],
platformVideoLink: json["platform_videoLink"],
caption: json["caption"],
description: json["description"],
);
Map<String, dynamic> toJson() => {
"shortcode": shortcode,
"platform_videoLink": platformVideoLink,
"caption": caption,
"description": description,
};
}
class Music {
Music({
this.id,
this.country,
this.categoryId,
this.categoryName,
this.categoryIcons,
this.playlists,
});
dynamic id;
String country;
String categoryId;
String categoryName;
List<CategoryIcon> categoryIcons;
List<Playlist> playlists;
factory Music.fromJson(Map<String, dynamic> json) => Music(
id: json["_id"],
country: json["country"],
categoryId: json["category_id"],
categoryName: json["category_name"],
categoryIcons: List<CategoryIcon>.from(
json["category_icons"].map((x) => CategoryIcon.fromJson(x))),
playlists: List<Playlist>.from(
json["playlists"].map((x) => Playlist.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"_id": id,
"country": country,
"category_id": categoryId,
"category_name": categoryName,
"category_icons":
List<dynamic>.from(categoryIcons.map((x) => x.toJson())),
"playlists": List<dynamic>.from(playlists.map((x) => x.toJson())),
};
}
class CategoryIcon {
CategoryIcon({
this.height,
this.url,
this.width,
});
int height;
String url;
int width;
factory CategoryIcon.fromJson(Map<String, dynamic> json) => CategoryIcon(
height: json["height"] == null ? null : json["height"],
url: json["url"],
width: json["width"] == null ? null : json["width"],
);
Map<String, dynamic> toJson() => {
"height": height == null ? null : height,
"url": url,
"width": width == null ? null : width,
};
}
class Playlist {
Playlist({
this.playlistName,
this.playlistDescription,
this.playlistUrl,
this.playlistTotalTracks,
this.playlistImages,
this.playlistFollowers,
this.playlistId,
});
String playlistName;
String playlistDescription;
String playlistUrl;
int playlistTotalTracks;
List<CategoryIcon> playlistImages;
int playlistFollowers;
String playlistId;
factory Playlist.fromJson(Map<String, dynamic> json) => Playlist(
playlistName: json["playlist_name"],
playlistDescription: json["playlist_description"],
playlistUrl: json["playlist_url"],
playlistTotalTracks: json["playlist_total_tracks"],
playlistImages: List<CategoryIcon>.from(
json["playlist_images"].map((x) => CategoryIcon.fromJson(x))),
playlistFollowers: json["playlist_followers"],
playlistId: json["playlist_id"],
);
Map<String, dynamic> toJson() => {
"playlist_name": playlistName,
"playlist_description": playlistDescription,
"playlist_url": playlistUrl,
"playlist_total_tracks": playlistTotalTracks,
"playlist_images":
List<dynamic>.from(playlistImages.map((x) => x.toJson())),
"playlist_followers": playlistFollowers,
"playlist_id": playlistId,
};
}
class Publisher {
Publisher({
this.platform,
this.username,
this.fullName,
this.profilePicUrl,
this.content,
this.keyId,
});
Platform platform;
String username;
String fullName;
String profilePicUrl;
Content content;
String keyId;
factory Publisher.fromJson(Map<String, dynamic> json) => Publisher(
platform: platformValues.map[json["platform"]],
username: json["username"],
fullName: json["full_name"],
profilePicUrl: json["profile_pic_url"],
content: Content.fromJson(json["content"]),
keyId: json["key_id"],
);
Map<String, dynamic> toJson() => {
"platform": platformValues.reverse[platform],
"username": username,
"full_name": fullName,
"profile_pic_url": profilePicUrl,
"content": content.toJson(),
"key_id": keyId,
};
}
class Content {
Content({
this.description,
});
String description;
factory Content.fromJson(Map<String, dynamic> json) => Content(
description: json["description"],
);
Map<String, dynamic> toJson() => {
"description": description,
};
}
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
The class called services where I am trying to parse the playlist_url.I am able to parse the playlist name and the number of videos of it(the count of it)
class Services {
static const String url =
"https://livetvapi.apyhi.com/api/v2/home?pageLocation=home&countries=IN&app_version=13&"
"user_id=44edc2c905ae163f&package_id=livetv.movies.freemovies.watchtv.tvshows&os_platform=android";
static Future<List<String>> loadDataForPlaylistDetailsForButtomTitle() async {
var res = await http
.get(url, headers: {'Authorization': dartJsonWebTokenGenerator()});
if (res.statusCode == 200) {
print("response is there");
final homePage = homePageFromJson(res.body);
Playlist playListObject = new Playlist();
List<String> lst_names = [];
for (playListObject in homePage.musicPlaylists.playlists)
lst_names.add(playListObject.playlistName);
print("Buttom titles");
print(lst_names);
return lst_names;
} else {
print("no response");
return null;
}
}
static Future<List<String>> loadDataForPlaylistDetailsForCount() async {
var res = await http
.get(url, headers: {'Authorization': dartJsonWebTokenGenerator()});
if (res.statusCode == 200) {
print("response is there");
final homePage = homePageFromJson(res.body);
Playlist playListObject = new Playlist();
List<String> lst_names = [];
for (playListObject in homePage.musicPlaylists.playlists)
lst_names.add(playListObject.playlistTotalTracks.toString());
print("count");
print(lst_names);
return lst_names;
} else {
print("no response");
return null;
}
}
static Future<List<Playlist>> loadDataForPlaylistDetailsForImageUrl() async {
var res = await http
.get(url, headers: {'Authorization': dartJsonWebTokenGenerator()});
if (res.statusCode == 200) {
print("response is there");
final homePage = homePageFromJson(res.body);
Music musicObject = new Music();
List<Playlist> playlistObj = homePage.musicPlaylists.playlists;
print("category icon object returned");
return playlistObj;
} else {
print("no response");
return null;
}
}
}
This is the main file where I am trying to display in listView.First the data is loaded in initstate and then stored in arrays.But for the last one (the url stuff)I tried with the object it self as things became complicated
#override
void initState() {
// TODO: implement initState
super.initState();
Services.loadDataForPlaylistDetailsForButtomTitle().then((playListNames) {
setState(() {
_playListNames = playListNames ;
});
});
Services.loadDataForPlaylistDetailsForButtomTitle().then((playListCount) {
setState(() {
_playListtotalTracks = playListCount ;
});
});
Services.loadDataForPlaylistDetailsForImageUrl().then((objUrl) {
setState(() {
_obj = objUrl ;
});
});
}
The code for listView Builder:
Container(
height: MediaQuery.of(context).size.height * 0.41,
color: Colors.black,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: _playListImageUrls.length,
itemBuilder: (BuildContext context, int index) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
height: MediaQuery.of(context).size.height * 0.34,
child: PhysicalModel(
clipBehavior: Clip.antiAliasWithSaveLayer,
color: Colors.black,
shape: BoxShape.rectangle,
borderRadius: BorderRadius.only(
topRight: Radius.circular(35),
bottomRight: Radius.circular(35)),
child: FadeInImage.assetNetwork(
width: MediaQuery.of(context).size.width * 0.285,
image: _obj[index].playlistImages[index].url,
placeholder: cupertinoActivityIndicator,
fit: BoxFit.fill,
),
),
),
Container(
margin: EdgeInsets.fromLTRB(15, 15, 0, 0),
height: MediaQuery.of(context).size.height * 0.03,
child: Text(
_playListNames[index],
style: TextStyle(color: Colors.white),
)),
Container(
margin: EdgeInsets.fromLTRB(15, 0, 0, 0),
height: MediaQuery.of(context).size.height * 0.02,
child: Text(
_playListtotalTracks[index],
style: TextStyle(color: Colors.white),
))
],
),
),
),
Also I find myself repeating this structures many times.Any suggestions to improvise would be equally welcomed.
I have finally found the solution.The whole point where I was doing the mistake was assuming things as a list of object,rather it was a list of list of single object.
The following modifications were made:
In service file
static Future<List<String>> loadDataForPlaylistDetailsForImageUrl() async {
var res = await http
.get(url, headers: {'Authorization': dartJsonWebTokenGenerator()});
if (res.statusCode == 200) {
print("response is thereeeeeeeee");
final homePage = homePageFromJson(res.body);
Playlist playListObject = new Playlist();
List<String> urlList = [];
List<dynamic> lst_names = [];
for (playListObject in homePage.musicPlaylists.playlists) {
lst_names.add(playListObject.playlistImages);
print(lst_names);
}
//lst_names=
print("objjjjjjjjjjjjjjjjjjjj");
for (var listobj in lst_names) {
for (var obj in listobj) {
print(obj.url.toString());
urlList.add(obj.url.toString());
}
}
return urlList;
} else {
print("no response");
return null;
}
}
Also in main file:
FadeInImage.assetNetwork(
width: MediaQuery.of(context).size.width * 0.285,
image: _musicPlaylistImgUrlList[index],
//_categoryIconfor[index].url,
//_obj[index].playlistImages[index].url,
placeholder: cupertinoActivityIndicator,
fit: BoxFit.none,
),

How to Parse Nested JSON

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.