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;
}
}
I am currently having issues when trying to print my Varients class (below) I do need to continue to add the nested objects later on but want to address this issue before I do.
So I can return response.body but when I print Varient.fromJson(i).varients I get Failed, no response.
JSON
{
"varients":[
{
"ProductId":"CMK8866",
"Colour":"Mid Blue Wash",
"Sizes":[
"4",
"6",
"8",
"10",
"12",
"14",
"16"
],
"image":"https://cdn-img.prettylittlething.com/2/5/2/4/252476b6dcf258958d52438b19b811d76da60dc0_CMK8866_1.jpg?imwidth=120",
"price":"28.00",
"name":"Mid Blue Wash Long Leg Straight Jeans",
"retailer":"prettylittlething"
},
{
"ProductId":"CMG0839",
"Colour":"Light Blue Wash",
"Sizes":[
"4",
"6",
"8",
"10",
"12",
"14",
"16"
],
"image":"https://cdn-img.prettylittlething.com/f/7/d/f/f7dfd26d523507c2f2e6697e408d932c8e0fac76_cmg0839_1.jpg?imwidth=120",
"price":"28.00",
"name":"Light Wash Long Leg Straight Jeans",
"retailer":"prettylittlething"
},
{
"ProductId":"CMQ3243",
"Colour":"Off White",
"Sizes":[
"4",
"6",
"8",
"10",
"12",
"14",
"16"
],
"image":"https://cdn-img.prettylittlething.com/d/9/0/2/d902d215e155a61d4cfc8999d714430f5fda01f9_CMK8867_1.jpg?imwidth=120",
"price":"28.00",
"name":"Off White Contrast Stitch Long Leg Straight Jeans",
"retailer":"prettylittlething"
},
{
"ProductId":"CMQ3245",
"Colour":"Stone",
"Sizes":[
"4",
"6",
"8",
"10",
"12",
"14",
"16"
],
"image":"https://cdn-img.prettylittlething.com/f/f/f/8/fff81a83fae46694dda3fcfef04d28508de64fdc_cmq3243_1.jpg?imwidth=120",
"price":"22.00",
"name":"Off White Long Leg Straight Jeans",
"retailer":"prettylittlething"
},
{
"ProductId":"CMQ3642",
"Colour":"Ecru",
"Sizes":[
"4",
"6",
"8",
"10",
"12",
"14",
"16"
],
"image":"https://cdn-img.prettylittlething.com/7/7/0/4/77046819c17f097804383b4fda0e0fda56b35239_cmq3245_1.jpg?imwidth=120",
"price":"28.00",
"name":"Stone Long Leg Straight Jeans",
"retailer":"prettylittlething"
},
{
"ProductId":"CMS6181",
"Colour":"Teal",
"Sizes":[
"4",
"6",
"8",
"10",
"12",
"14",
"16"
],
"image":"https://cdn-img.prettylittlething.com/0/6/0/7/0607455b765c3aed0356be8dafab301182919d2f_cmq3642_1.jpg?imwidth=120",
"price":"21.00",
"name":"Ecru With Contrast Stitch Long Leg Straight Jeans",
"retailer":"prettylittlething"
},
{
"ProductId":"CMS6180",
"Colour":"Chocolate",
"Sizes":[
"4",
"6",
"8",
"10",
"12",
"14",
"16"
],
"image":"https://cdn-img.prettylittlething.com/5/5/9/6/559602e94377d0ebbc5f222b30bbb96ec3104bf8_cms6181_1.jpg?imwidth=120",
"price":"25.00",
"name":"Teal Long Leg Straight Jean",
"retailer":"prettylittlething"
}
]
}
Code
Future<dynamic> requestProductMonitor() async {
final product_link = productIDEditingController.text;
var url = Uri.parse(
"http://5.226.139.20:8000/getvarient/?url=https://www.prettylittlething.com/mid-blue-wash-long-leg-straight-jeans.html");
http.Response response = await http.get(url);
try {
if (response.statusCode == 200) {
var jsonResponse = convert.jsonDecode(response.body);
print("this is the Json Response $jsonResponse");
setState(() {
for (Map<String, dynamic> i in jsonResponse) {
listModel1.add(Varient.fromJson(i));
//var test = Varient.fromJson(i).varients;
//print("This is the varients $test");
//product_size.add(User.fromJson(i).name);
}
});
showDropDown();
} else {
print("Error");
}
} catch (exp) {
print("Failed, no response");
}
}
This is my Varients class:
List<Varient> modelUserFromJson(String str) =>
List<Varient>.from(json.decode(str).map((x) => Varient.fromJson(x)));
String modelUserToJson(List<Varient> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Varient {
String varients;
Varient({
required this.varients,
});
factory Varient.fromJson(Map<String, dynamic> json) => Varient(
varients: json["varients"],
);
Map<String, dynamic> toJson() => {
"varients": varients,
};
}
Wondering if anyone has any ideas ?
main.dart
import 'package:flutter/material.dart';
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
void main() {
runApp(
const MaterialApp(debugShowCheckedModeBanner: false, home: MyApp()),
);
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
dynamic varient;
requestProductMonitor() async {
final response = await http.get(Uri.parse(
"http://5.226.139.20:8000/getvarient/?url=https://www.prettylittlething.com/mid-blue-wash-long-leg-straight-jeans.html"));
if (response.statusCode == 200) {
var jsonResponse = convert.jsonDecode(response.body);
varient = await jsonResponse["varients"];
} else {
print('Request failed with status: ${response.statusCode}.');
}
}
#override
void initState() {
requestProductMonitor();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Center(
child: FutureBuilder(
future: requestProductMonitor(), // async work
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const Text('Loading....');
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return GridView.builder(
gridDelegate:
const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 350,
mainAxisSpacing: 1,
crossAxisSpacing: 10),
scrollDirection: Axis.vertical,
itemCount: varient.length,
itemBuilder: (BuildContext context, int index) {
List<String> sizes =
varient[index]["Sizes"].cast<String>();
return Wrap(
alignment: WrapAlignment.center,
children: [
Image.network(
varient[index]["image"],
fit: BoxFit.cover,
),
Text(varient[index]["name"]),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
sizes.isEmpty
? const Text("No Size Available")
: const Text("Available Sizes: "),
sizes.isNotEmpty
? DropdownButton<String>(
items: sizes.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Center(child: Text(value)),
);
}).toList(),
onChanged: (_) {},
)
: const SizedBox(),
],
)
],
);
});
}
}
},
),
));
}
}
This is your desired output, the sizes are now shown in a drop-down menu and can read data from the JSON to get name and image.
When loading data from json I got some problem. I think the problem is in fetching the data.
Any idea what's going on?
I'm not best Flutter developer it's more like hobby so try to be easygoing.
Here is error:
The following NoSuchMethodError was thrown building RulesCard(dirty,
dependencies: [_LocalizationsScope-[GlobalKey#806d5],
_InheritedTheme], state: _RulesCardState#471f3):
The getter 'campusRulesList' was called on null. Receiver: null Tried calling:
campusRulesList
The relevant error-causing widget was: RulesCard
file:///H:/Projekty/kampus_sggw/lib/global_widgets/side_drawer.dart:43:57
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 _RulesCardState.build (package:kampus_sggw/screens/map_screen/rules_card.dart:69:53)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4684:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4567:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4739:11) ...
════════════════════════════════════════════════════════════════════════════
E/flutter (18750): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)]
Unhandled Exception: Unable to load asset:
assets/json/campus_rules_pl.json E/flutter (18750): #0
PlatformAssetBundle.load
(package:flutter/src/services/asset_bundle.dart:227:7) E/flutter
(18750): E/flutter (18750): #1
AssetBundle.loadString
(package:flutter/src/services/asset_bundle.dart:68:27) E/flutter
(18750): E/flutter (18750): #2
_RulesCardState.loadFromJson (package:kampus_sggw/screens/map_screen/rules_card.dart:31:54)
E/flutter (18750): E/flutter (18750): #3
_RulesCardState.initState. (package:kampus_sggw/screens/map_screen/rules_card.dart:23:21)
E/flutter (18750): E/flutter (18750):
rules_card.dart where the Widget is defined:
class RulesCard extends StatefulWidget {
#override
_RulesCardState createState() => _RulesCardState();
}
class _RulesCardState extends State<RulesCard> {
CampusRules rulesListPL;
CampusRules rulesListEn;
#override
initState() {
WidgetsBinding.instance.addPostFrameCallback((_) async
{
rulesListPL = await this.loadFromJson();
print(rulesListPL);
});
super.initState();
}
Future<CampusRules> loadFromJson() async {
Map<String, dynamic> campusRulesMap = jsonDecode(await CampusRules.getJsonSting());
final campusRules = CampusRules.fromJson(campusRulesMap);
return campusRules;
}
#override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
Container(
height: 90.0,
child: DrawerHeader(
child: Text(
LocaleKeys.campus_rules.tr(),
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headline3
),
decoration: BoxDecoration(
color: Theme.of(context).bannerTheme.backgroundColor
),
),
),
for (CampusRule campusRule in rulesListPL.campusRulesList)
SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: buildListTitle(context, campusRule),
),
],
),
);
}
Widget buildListTitle(BuildContext context, CampusRule rule) => ExpansionTile(
title: Text(
rule.rule,
style: Theme.of(context).textTheme.headline4,
),
children: [
for (CampusSubRule subRule in rule.subRulesList)
ListTile(
title:
Text(
subRule.subRule,
style: Theme.of(context).textTheme.headline4,
),
)
],
);
}
campus_rules.dart where is defined the model of CampusRules object:
import 'package:flutter/services.dart';
import 'package:json_annotation/json_annotation.dart';
part 'campus_rules.g.dart';
#JsonSerializable()
class CampusRules {
String name;
String lang;
List<CampusRule> campusRulesList;
CampusRules(
this.name,
this.lang,
this.campusRulesList,
);
factory CampusRules.fromJson(Map<String, dynamic> json) =>
_$CampusRulesFromJson(json);
static Future<String> getJsonSting() {
return rootBundle.loadString('assets/json/campus_rules_pl.json');
}
}
#JsonSerializable()
class CampusRule {
int ruleNumber;
String rule;
List<CampusSubRule> subRulesList;
CampusRule(
this.ruleNumber,
this.rule,
this.subRulesList,
);
factory CampusRule.fromJson(Map<String, dynamic> json) =>
_$CampusRuleFromJson(json);
}
#JsonSerializable()
class CampusSubRule {
int subRuleNumber;
String subRule;
CampusSubRule(
this.subRuleNumber,
this.subRule,
);
factory CampusSubRule.fromJson(Map<String, dynamic> json) =>
_$CampusSubRuleFromJson(json);
}
campus_rules.g.dart where is the auto generated code for Serialization
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'campus_rules.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
CampusRules _$CampusRulesFromJson(Map<String, dynamic> json) {
return CampusRules(
json['name'] as String,
json['lang'] as String,
(json['campusRulesList'] as List)
?.map((e) =>
e == null ? null : CampusRule.fromJson(e as Map<String, dynamic>))
?.toList(),
);
}
Map<String, dynamic> _$CampusRulesToJson(CampusRules instance) =>
<String, dynamic>{
'name': instance.name,
'lang': instance.lang,
'campusRulesList': instance.campusRulesList,
};
CampusRule _$CampusRuleFromJson(Map<String, dynamic> json) {
return CampusRule(
json['ruleNumber'] as int,
json['rule'] as String,
(json['subRulesList'] as List)
?.map((e) => e == null
? null
: CampusSubRule.fromJson(e as Map<String, dynamic>))
?.toList(),
);
}
Map<String, dynamic> _$CampusRuleToJson(CampusRule instance) =>
<String, dynamic>{
'ruleNumber': instance.ruleNumber,
'rule': instance.rule,
'subRulesList': instance.subRulesList,
};
CampusSubRule _$CampusSubRuleFromJson(Map<String, dynamic> json) {
return CampusSubRule(
json['subRuleNumber'] as int,
json['subRule'] as String,
);
}
Map<String, dynamic> _$CampusSubRuleToJson(CampusSubRule instance) =>
<String, dynamic>{
'subRuleNumber': instance.subRuleNumber,
'subRule': instance.subRule,
};
And the json file:
{
"name": "campus_rules",
"lang": "pl",
"campusRulesList": [
{
"ruleNumber": "1",
"rule": "I. Kampus Uczelni jest terenem ogólnodostępnym w godz. od 6:00 do 22:00. W pozostałym przedziale czasowym na terenie Kampusu mogą przebywać tylko osob do tego uprawnione:",
"subRulesList": [
{
"subRuleNumber": "1",
"subRule": "1) pracownicy Uczelni (a także osoby im towarzyszące) oraz osoby wykonujące prace zlecone na rzecz Uczelni posiadające indywidualne zezwolenia;"
},
{
"subRuleNumber": "2",
"subRule": "2) studenci i doktoranci SGGW oraz osoby im towarzyszące;"
},
{
"subRuleNumber": "3",
"subRule": "3) mieszkańcy domów studenckich. Domu Asystenckiego i Pokoi Gościnnych Ikar;"
},
{
"subRuleNumber": "3",
"subRule": "4) osoby korzystające z obiektów usługowych na terenie Kampusu do czasu ich zamknięcia."
}
]
},
{
"ruleNumber": "2",
"rule": "II. Każdy kto przebywa na terenie Kampusu SGGW zobowiązany jest do:",
"subRulesList": [
{
"subRuleNumber": "1",
"subRule": "1) przestrzegania ogólnie przyjętych norm postępowania w zakresie relacji międzyludzkich:"
},
{
"subRuleNumber": "2",
"subRule": "2) przestrzegania zasad poszanowania mienia wspólnego Uczelni, poszanowania zieleni, a zwłaszcza niezaśmiecania Kampusu;"
},
{
"subRuleNumber": "3",
"subRule": "3) właściwego korzystania z urządzeń, instalacji oraz wyposażenia budynków z uwzględnieniem ich przeznaczenia;"
},
{
"subRuleNumber": "4",
"subRule": "4) właściwego korzystania z dróg transportu samochodowego, parkingów dla samochodów oraz chodników dla pieszych;"
},
{
"subRuleNumber": "5",
"subRule": "5) zachowania zwykłych i nakazanych środków ostrożności przy trzymaniu psów oraz przy trzymaniu innych zwierząt."
}
]
},
{
"ruleNumber": "3",
"rule": "III. Na terenie Kampusu zabrania się:",
"subRulesList": [
{
"subRuleNumber": "1",
"subRule": "1) zakłócania porządku publicznego, agresywnego, napastliwego i nieobyczajnego zachowania oraz niszczenia mienia Uczelni;"
},
{
"subRuleNumber": "2",
"subRule": "2) spożywania alkoholu (nie dotyczy lokali konsumpcyjnych znajdujących się na terenie Kampusu SGGW oraz wydarzeń okazjonalnych lub cyklicznych organizowanychna terenie Kampusu SGGW, pod warunkiem wyrażenia przez Władze Uczelni zgody na spożywanie alkoholu podczas takiego wydarzenia), przebywania w stanie nietrzeźwym oraz pod wpływem innych środków odurzających;"
},
{
"subRuleNumber": "3",
"subRule": "3) wnoszenia i posiadania broni (z wyłączeniem osób pełniących służbę ochrony) i innych przedmiotów mogących stanowić zagrożenie bezpieczeństwa, w szczególności: materiałów wybuchowych, wyrobów pirotechnicznych, środków odurzających lub psychotropowych;"
},
{
"subRuleNumber": "4",
"subRule": "4) organizowania ognisk;"
},
{
"subRuleNumber": "5",
"subRule": "5) grillowania poza miejscami do tego wyznaczonymi;"
},
{
"subRuleNumber": "6",
"subRule": "6) wyprowadzania psów bez smyczy i kagańców oraz pozastawiania ich bez opieki;"
},
{
"subRuleNumber": "7",
"subRule": "7) parkowania pojazdów poza wyznaczonymi miejscami;"
},
{
"subRuleNumber": "8",
"subRule": "8) prowadzenia handlu obwoźnego i akwizycji bez zgody Władz Uczelni."
}
]
},
{
"ruleNumber": "4",
"rule": "VII. Osoby odpowiedzialne za sprawowanie nadzoru na terenie Kampusu SGGW. a szczególnie pracownicy Straży Akademickiej oraz monitoringu obiektów są uprawnione i zobowiązane do:",
"subRulesList": [
{
"subRuleNumber": "1",
"subRule": "1) ograniczania wstępu na teren Kampusu osobom nieupoważnionym, a w przypadku ujawnienia naruszeń postanowień Regulaminu żądania opuszczenia terenu Kampusu;"
},
{
"subRuleNumber": "2",
"subRule": "2) zwracania szczególnej uwagi na osoby, które swoim zachowaniem budzą uzasadnione podejrzenia zakłócenia porządku publicznego i reagowania w sytuacjach zagrożenia;"
},
{
"subRuleNumber": "3",
"subRule": "3) współdziałania, zgodnie z Prawem o Szkolnictwie Wyższym i Statutem Uczelni, w zakresie bezpieczeństwa z właściwymi terenowo jednostkami Policji. Straży Miejskiej, a w przypadku jakiegokolwiek zagrożenia wezwania grup interwencyjnych czy innych służb miejskich lub ratunkowych (Straż Pożarna. Pogotowie Ratunkowe);"
},
{
"subRuleNumber": "4",
"subRule": "4) kontrolowania uprawnień do przebywania na terenie Kampusu SGGW."
}
]
}
]
}
You're trying to access rulesListPL without waiting for loadFromJson() to complete and assign the result to it. So, you need a loading state:
#override
Widget build(BuildContext context) {
// If rulesListPL has not initialized yet
if (rulesListPL == null) {
// Display your loading screen instead
return Center(
child: CircularProgressIndicator(),
);
}
return Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
Container(
height: 90.0,
child: DrawerHeader(
child: Text(LocaleKeys.campus_rules.tr(),
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headline3),
decoration: BoxDecoration(
color: Theme.of(context).bannerTheme.backgroundColor),
),
),
for (CampusRule campusRule in rulesListPL.campusRulesList)
SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: buildListTitle(context, campusRule),
),
],
),
);
}
Thanks to Stewie answer I added some code to handle refresh after it is loaded:
class _RulesCardState extends State<RulesCard> with TickerProviderStateMixin{
CampusRules rulesListPL;
CampusRules rulesListEn;
AnimationController controller;
#override
initState() {
WidgetsBinding.instance.addPostFrameCallback((_) async
{
rulesListPL = await this.loadFromJson();
print(rulesListPL);
});
controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 5),
)..addListener(() {
setState(() {});
});
controller.repeat(reverse: true);
super.initState();
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
Future<CampusRules> loadFromJson() async {
Map<String, dynamic> campusRulesMap = jsonDecode(await CampusRules.getJsonSting());
final campusRules = CampusRules.fromJson(campusRulesMap);
return campusRules;
}
#override
Widget build(BuildContext context) {
// If rulesListPL has not initialized yet
if (rulesListPL == null) {
// Display your loading screen instead
return Center(
child: CircularProgressIndicator(
value: controller.value,
),
);
}
return Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
Container(
height: 90.0,
child: DrawerHeader(
child: Text(
LocaleKeys.campus_rules.tr(),
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headline3
),
decoration: BoxDecoration(
color: Theme.of(context).bannerTheme.backgroundColor
),
),
),
for (CampusRule campusRule in rulesListPL.campusRulesList)
SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: buildListTitle(context, campusRule),
),
],
),
);
}
Creating tabs with types and need to display in Corresponding TabView..
var listOfItem = [
{
"types": "ARABIAN",
"restaurants": [
{
"name": "ZauZau Restaurants",
"location": "Mascat, Oman",
"kms": "1.0 kms"
},
{
"name": "MauMau Restaurants",
"location": "Calicut, Oman",
"kms": "2.0 kms"
},
{
"name": "ChaCha Restaurants",
"location": "Charat, Oman",
"kms": "2.5 kms"
},
]
},
{
"types": "COFFEE SHOP",
"restaurants": [
{
"name": "ZauZau Restaurants",
"location": "Mascat, Oman",
"kms": "1.0 kms"
},
]
},
];
This is my list of objects
I am accessing its "restaurants" by
listOfItem.asMap().entries.map((e) => print(e.value['restaurants'])).toList();
And I need to map that particular List
Trying long time. I didn't get any idea on this
BTW I am new to coding..
Quick answer
You can nest two mapping of your JSON data:
listOfItem.map((category) => Column(
children: (category['restaurants'] as List<Map<String, dynamic>>)
.map((restaurant) => Text(restaurant['name'])).toList()
).toList();
Remember to use toList() as a map operation does not return a List but an Iterable.
Basic Full Solution
Here is a first solution based on your data and the Flutter Tabs.
Full source code:
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomePage(),
),
);
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: data.length,
child: Scaffold(
appBar: AppBar(
title: Text('Restaurants'),
bottom: TabBar(
tabs: data.map((category) => Tab(text: category['types'])).toList(),
),
),
body: TabBarView(
children: data
.map((category) => ListView(
children:
(category['restaurants'] as List<Map<String, dynamic>>)
.map(
(restaurant) => ListTile(
title: Text(restaurant['name']),
subtitle: Text(restaurant['location']),
),
)
.toList(),
))
.toList(),
),
),
);
}
}
final data = [
{
"types": "ARABIAN",
"restaurants": [
{
"name": "ZauZau Restaurants",
"location": "Mascat, Oman",
"kms": "1.0 kms"
},
{
"name": "MauMau Restaurants",
"location": "Calicut, Oman",
"kms": "2.0 kms"
},
{
"name": "ChaCha Restaurants",
"location": "Charat, Oman",
"kms": "2.5 kms"
},
]
},
{
"types": "COFFEE SHOP",
"restaurants": [
{
"name": "ZauZau Restaurants",
"location": "Mascat, Oman",
"kms": "1.0 kms"
},
]
},
];
Advanced Full Solution
And here is a second solution providing exactly the same visual but managing specific Domain Entities Restaurant & RestaurantCategory.
It introduces concepts such as State Management and JSON Serialization.
Full source code:
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
part '66318447.tabs.freezed.dart';
part '66318447.tabs.g.dart';
void main() {
runApp(
ProviderScope(
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomePage(),
),
),
);
}
class HomePage extends HookWidget {
#override
Widget build(BuildContext context) {
final data = useProvider(dataProvider).state;
return DefaultTabController(
length: data.length,
child: Scaffold(
appBar: AppBar(
title: Text('Restaurants'),
bottom: TabBar(
tabs: data.map((category) => Tab(text: category.name)).toList(),
),
),
body: TabBarView(
children: data
.map((category) => ListView(
children: category.restaurants
.map(
(restaurant) => ListTile(
title: Text(restaurant.name),
subtitle: Text(
'${restaurant.location} (${restaurant.kms} away)'),
),
)
.toList(),
))
.toList(),
),
),
);
}
}
final dataProvider = StateProvider<List<RestaurantCategory>>(
(ref) => data.map((json) => RestaurantCategory.fromJson(json)).toList());
#freezed
abstract class Restaurant with _$Restaurant {
const factory Restaurant(String name, String location, String kms) =
_Restaurant;
factory Restaurant.fromJson(Map<String, dynamic> json) =>
_$RestaurantFromJson(json);
}
#freezed
abstract class RestaurantCategory with _$RestaurantCategory {
const factory RestaurantCategory(String name, List<Restaurant> restaurants) =
_RestaurantCategory;
factory RestaurantCategory.fromJson(Map<String, dynamic> json) =>
_$RestaurantCategoryFromJson(json);
}
final data = [
{
"name": "ARABIAN",
"restaurants": [
{
"name": "ZauZau Restaurants",
"location": "Mascat, Oman",
"kms": "1.0 kms"
},
{
"name": "MauMau Restaurants",
"location": "Calicut, Oman",
"kms": "2.0 kms"
},
{
"name": "ChaCha Restaurants",
"location": "Charat, Oman",
"kms": "2.5 kms"
},
]
},
{
"name": "COFFEE SHOP",
"restaurants": [
{
"name": "ZauZau Restaurants",
"location": "Mascat, Oman",
"kms": "1.0 kms"
},
]
},
];
Try this loop:
for (final x in listOfItem){
//x is the current object here
for (final y in x["restaurants"]){
//y is the current restaurant
print(y["property you want"]);
}
}
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()),
],
),
));
});
}
}
}));
}
}