Can't decode/Parse Json type list<String> with this list<String> type Model in Dart - json

I wanted to create a drop down from json list. I am using app.quicktype.io to covert json to PODO (Plain Old dart Object)
Here is the My JSON data:
[
{
"country_name": "Andorra",
"alpha2_code": "AD",
"country_code": "376",
"states": [
{ "state_name": "Andorra la Vella" },
{ "state_name": "Canillo" }
]
},
]
And here is the PODO (Plain Old Dart Object) I created with app.quicktype.io:
class CountryDetailsModel {
CountryDetailsModel({
this.countryName,
this.alpha2Code,
this.countryCode,
this.states,
});
String countryName;
String alpha2Code;
String countryCode;
List<StateNames> states;
factory CountryDetailsModel.fromJson(Map<String, dynamic> json) =>
CountryDetailsModel(
countryName: json["country_name"],
alpha2Code: json["alpha2_code"],
countryCode: json["country_code"],
states: List<StateNames>.from(
json["states"].map((x) => StateNames.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"country_name": countryName,
"alpha2_code": alpha2Code,
"country_code": countryCode,
"states": List<dynamic>.from(states.map((x) => x.toJson())),
};
}
class StateNames {
StateNames({
this.stateName,
});
String stateName;
factory StateNames.fromJson(Map<String, dynamic> json) => StateNames(
stateName: json["state_name"],
);
Map<String, dynamic> toJson() => {
"state_name": stateName,
};
}

You can copy paste run full code below
In working demo, simulate network delay with 3 seconds
You can use FutureBuilder and use return countryDetailsModelFromJson(jsonString);
code snippet
Future<List<CountryDetailsModel>> getHttp() async {
String jsonString = ...
return countryDetailsModelFromJson(jsonString);
}
...
FutureBuilder(
future: _future,
builder:
(context, AsyncSnapshot<List<CountryDetailsModel>> snapshot) {
...
return DropdownButton<CountryDetailsModel>(
//isDense: true,
hint: Text('Choose'),
value: _selectedValue,
icon: Icon(Icons.check_circle_outline),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.blue[300],
),
onChanged: (CountryDetailsModel newValue) {
setState(() {
_selectedValue = newValue;
});
},
items: snapshot.data
.map<DropdownMenuItem<CountryDetailsModel>>(
(CountryDetailsModel value) {
return DropdownMenuItem<CountryDetailsModel>(
value: value,
child: Text(value.countryName),
);
}).toList(),
);
}
}
})
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
List<CountryDetailsModel> countryDetailsModelFromJson(String str) =>
List<CountryDetailsModel>.from(
json.decode(str).map((x) => CountryDetailsModel.fromJson(x)));
String countryDetailsModelToJson(List<CountryDetailsModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class CountryDetailsModel {
CountryDetailsModel({
this.countryName,
this.alpha2Code,
this.countryCode,
this.states,
});
String countryName;
String alpha2Code;
String countryCode;
List<StateNames> states;
factory CountryDetailsModel.fromJson(Map<String, dynamic> json) =>
CountryDetailsModel(
countryName: json["country_name"],
alpha2Code: json["alpha2_code"],
countryCode: json["country_code"],
states: List<StateNames>.from(
json["states"].map((x) => StateNames.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"country_name": countryName,
"alpha2_code": alpha2Code,
"country_code": countryCode,
"states": List<dynamic>.from(states.map((x) => x.toJson())),
};
}
class StateNames {
StateNames({
this.stateName,
});
String stateName;
factory StateNames.fromJson(Map<String, dynamic> json) => StateNames(
stateName: json["state_name"],
);
Map<String, dynamic> toJson() => {
"state_name": stateName,
};
}
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: MyStatefulWidget(),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
#override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
CountryDetailsModel _selectedValue;
Future<List<CountryDetailsModel>> _future;
Future<List<CountryDetailsModel>> getHttp() async {
String jsonString = '''
[
{
"country_name": "Andorra",
"alpha2_code": "AD",
"country_code": "376",
"states": [
{ "state_name": "Andorra la Vella" },
{ "state_name": "Canillo" },
{ "state_name": "Encamp" },
{ "state_name": "La Massana" },
{ "state_name": "Les Escaldes" },
{ "state_name": "Ordino" },
{ "state_name": "Sant Julia de Loria" }
]
},
{
"country_name": "Azerbaijan",
"alpha2_code": "AZ",
"country_code": "994",
"states": [
{ "state_name": "Abseron" },
{ "state_name": "Baki Sahari" },
{ "state_name": "Ganca" },
{ "state_name": "Ganja" },
{ "state_name": "Kalbacar" },
{ "state_name": "Lankaran" },
{ "state_name": "Mil-Qarabax" },
{ "state_name": "Mugan-Salyan" },
{ "state_name": "Nagorni-Qarabax" },
{ "state_name": "Naxcivan" },
{ "state_name": "Priaraks" },
{ "state_name": "Qazax" },
{ "state_name": "Saki" },
{ "state_name": "Sirvan" },
{ "state_name": "Xacmaz" }
]
}]
''';
return countryDetailsModelFromJson(jsonString);
}
#override
void initState() {
_future = getHttp();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: _future,
builder:
(context, AsyncSnapshot<List<CountryDetailsModel>> 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 DropdownButton<CountryDetailsModel>(
//isDense: true,
hint: Text('Choose'),
value: _selectedValue,
icon: Icon(Icons.check_circle_outline),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.blue[300],
),
onChanged: (CountryDetailsModel newValue) {
setState(() {
_selectedValue = newValue;
});
},
items: snapshot.data
.map<DropdownMenuItem<CountryDetailsModel>>(
(CountryDetailsModel value) {
return DropdownMenuItem<CountryDetailsModel>(
value: value,
child: Text(value.countryName),
);
}).toList(),
);
}
}
}));
}
}

Finally I found a solution.
Here is the Process:
List<CountryDetailsModel> countryDetails() {
List<Map> map = CountryData.countryData;
List<CountryDetailsModel> list =
map.map((json) => CountryDetailsModel.fromJson(json)).toList();
return list;
}
And for printing all countries:
countryDetails().
forEach((element) {
print(element.countryName);
});

Related

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

type 'String' is not a subtype of type 'int' of 'index' while getting media fields using the instagram API

i'm trying to get media fields from the instagram api and i'm getting this error
type 'String' is not a subtype of type 'int' of 'index'
here's Homepage.dart :
import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'package:insta_details/models/data.dart';
import 'package:insta_details/utils/custom_dio_mixin.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
static String id = "HomePage";
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with CustomDioMixin {
bool loading = true;
bool error = false;
late Media media;
#override
void initState() {
super.initState();
getData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: loading
? const Center(
child: CircularProgressIndicator(),
)
: error
? const Center(
child: Text('An error has occurred!'),
)
: ListView.builder(
itemBuilder: (context, index) => MediaWidget(
media: media,
),
),
),
);
}
Future<void> getData() async {
try {
final storage = GetStorage();
final token = storage.read("accessToken");
Media? media;
final response = await dio.get(
'https://graph.instagram.com/me/media?fields=id,caption,media_url,timestamp&access_token=$token',
);
print("get data response => ${response.statusCode} ${response.data}");
Media mediadata = Media.fromJson(response.data);
print(mediadata);
} catch (e) {
print("get data failed");
print(e);
setState(() {
error = true;
});
} finally {
setState(() {
loading = false;
});
}
}
}
class MediaWidget extends StatelessWidget {
final Media media;
const MediaWidget({Key? key, required this.media}) : super(key: key);
#override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: 6,
itemBuilder: (context, index) {
return Image.network(media.mediaUrl);
},
);
}
}
and here data.dart :
class Media {
Media({
required this.id,
required this.caption,
required this.mediaUrl,
required this.timestamp,
});
String id;
String caption;
String mediaUrl;
String timestamp;
factory Media.fromJson(Map<String, dynamic> json) => Media(
id: json["data"]["id"] as String,
caption: json["data"]["caption"] as String,
mediaUrl: json["data"]["media_url"] as String,
timestamp: json["data"]["timestamp"] as String,
);
Map<String, dynamic> toJson() => {
"id": id,
"caption": caption,
"media_url": mediaUrl,
"timestamp": timestamp,
};
}
and the log :
I/flutter ( 5699): get data response => 200 {data: [{id: 18106429915287733, caption: cabin in the woods, media_url: https://scontent.cdninstagram.com/v/t51.29350-15/272751472_358111429123560_6575694365508668882_n.jpg?_nc_cat=100&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=0omRv4cUGtwAX8bbmC7&_nc_ht=scontent.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT_fqBkL5ykJXWRj7Rcy4nCnyuXEKh-8o0TX9FJkJ4dcfQ&oe=61FD881A, timestamp: 2022-01-27T11:15:07+0000}, {id: 17917394609104775, caption: Truck, media_url: https://scontent.cdninstagram.com/v/t51.29350-15/272701475_1080001635904581_1705933746471766077_n.jpg?_nc_cat=107&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=ZfSpeg7rHn4AX89PW0c&_nc_ht=scontent.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT_Qbj7zOH-UEzplA9mdIrCHaeb9EBBuz1RjKJclN9Q2RA&oe=61FE9898, timestamp: 2022-01-27T11:14:26+0000}, {id: 17921627228176014, caption: Gaara, media_url: https://scontent.cdninstagram.com/v/t51.29350-15/272660463_892749041374464_5507853711157520506_n.jpg?_nc_cat=101&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=va5seINOs-4AX9vOy4L&_nc_ht=scontent.cdninst
I/flutter ( 5699): get data failed
I/flutter ( 5699): type 'String' is not a subtype of type 'int' of 'index'
my JSON response :
{
"data": [
{
"id": "18106429915287733",
"caption": "cabin in the woods",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272751472_358111429123560_6575694365508668882_n.jpg?_nc_cat=100&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=xXGDvxMsycAAX_U_-55&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT-EuNnLxrBSNirBOl1prRXlHepdhQqUjYRBEv3Zh_Ld6Q&oe=61FD881A",
"username": "parekchampl",
"timestamp": "2022-01-27T11:15:07+0000"
},
{
"id": "17917394609104775",
"caption": "Truck",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272701475_1080001635904581_1705933746471766077_n.jpg?_nc_cat=107&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=ZfSpeg7rHn4AX_J_eQs&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT92hbhb0XK56kxC-_e8kpM6QFLazDH0TDCfdIdEIpNinw&oe=61FC9E58",
"username": "parekchampl",
"timestamp": "2022-01-27T11:14:26+0000"
},
{
"id": "17921627228176014",
"caption": "Gaara",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272660463_892749041374464_5507853711157520506_n.jpg?_nc_cat=101&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=va5seINOs-4AX_SB6jL&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT8rviJ6wbaT0yF1Hq2VprtnQ-W0rARS5oxIr52MIhC0Rw&oe=61FD720B",
"username": "parekchampl",
"timestamp": "2022-01-27T11:13:42+0000"
},
{
"id": "18024346318348836",
"caption": "Marceline",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272807293_686124672409566_4991399943515126026_n.jpg?_nc_cat=106&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=JMfTMSD_1c8AX-m5WDx&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT_P38eDVtcqEYL053wGPkLjhHStLCh7_fgFnCg4LcH1yA&oe=61FD1F82",
"username": "parekchampl",
"timestamp": "2022-01-27T11:13:02+0000"
},
{
"id": "17859174368680579",
"caption": "uchiha shisui",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272721151_749467822692662_5191995429373550055_n.jpg?_nc_cat=111&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=01A68vtgY-kAX-ux6iB&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT9oWtK9VWV8j3c8Ij2YXctIpuh9sC-NJO1BLCwFObDDSA&oe=61FE0B03",
"username": "parekchampl",
"timestamp": "2022-01-27T11:12:35+0000"
},
{
"id": "17917757036265369",
"caption": "Son and Father",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272660947_1107548556714461_1575953024252145708_n.jpg?_nc_cat=100&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=Mzj5Wp9sv_oAX_2Z4Nv&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT8Ywp3DUIemrIoCPajFvivfTG_-AWvEs2fpkngYXUN6Lg&oe=61FE17A1",
"username": "parekchampl",
"timestamp": "2022-01-27T11:11:47+0000"
}
],
"paging": {
"cursors": {
"before": "QVFIUnpEcERJTXdYRjd3SVp3MUo2U25UeWhhdlgxQ2xMY0diR2pYVFhCVl9TUUhlM1hqYllKWUpEWXJtYW5RWW41am1Lc3B4U281TU14ZAFoxSVBkMVRsZAkZAB",
"after": "QVFIUkgtUzExdDNsYzgwUFhGdnRXQlB6N0JkZATVFeU1DVkhzXzduLTF1RklpR1A5MDNMeWVEemtzdE15OVBlYmpYb29mQlVtdDJsX1N2SUcwa2ZAkc21jblZAn"
}
}
}
According to the documentation : https://developers.facebook.com/docs/instagram-basic-display-api/reference/media ,every field is a String
factory Media.fromJson(Map<String, dynamic> json) => Media(
id: json["data"]["id"] as String,
caption: json["data"]["caption"] as String,
mediaUrl: json["data"]["media_url"] as String,
timestamp: json["data"]["timestamp"] as String,
);
Or change to something like below:
factory Media.fromJson(Map<String, dynamic> json) => Media(
id: int.parse(json["data"]["id"] as String),
caption: json["data"]["caption"] as String,
mediaUrl: json["data"]["media_url"] as String,
timestamp: DateTime.parse(json["data"]["timestamp"] as String),
);
The value of your data key is a List not a Map. Here's an example:
const responseData =
{
"data":[
{
"id":"18106429915287733",
"caption":"cabin in the woods",
"media_type":"IMAGE",
"media_url":"https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272751472_358111429123560_6575694365508668882_n.jpg?_nc_cat=100&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=xXGDvxMsycAAX_U_-55&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT-EuNnLxrBSNirBOl1prRXlHepdhQqUjYRBEv3Zh_Ld6Q&oe=61FD881A",
"username":"parekchampl",
"timestamp":"2022-01-27T11:15:07+0000"
},
{
"id":"17917394609104775",
"caption":"Truck",
"media_type":"IMAGE",
"media_url":"https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272701475_1080001635904581_1705933746471766077_n.jpg?_nc_cat=107&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=ZfSpeg7rHn4AX_J_eQs&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT92hbhb0XK56kxC-_e8kpM6QFLazDH0TDCfdIdEIpNinw&oe=61FC9E58",
"username":"parekchampl",
"timestamp":"2022-01-27T11:14:26+0000"
}
]
};
void main() {
final mediaList = responseData["data"]!.map((entry) => Media.fromJson(entry))
.toList();
for (var media in mediaList) {
print(media.id);
}
}
class Media {
Media({
required this.id,
required this.caption,
required this.mediaUrl,
required this.timestamp,
});
int? id;
String caption;
String mediaUrl;
String timestamp;
factory Media.fromJson(Map<String, dynamic> json) {
return Media(
id: int.tryParse(json["id"]),
caption: json["caption"],
mediaUrl: json["media_url"],
timestamp: json["timestamp"],
);
}
Map<String, dynamic> toJson() => {
"id": id.toString(),
"caption": caption,
"media_url": mediaUrl,
"timestamp": timestamp,
};
}
On your model class id is nullable int, but you are receiving id as String.
You can typecast string to int On your Media.fromJson, while the id accept null value, if something wrong happen id will get null value.
factory Media.fromJson(Map<String, dynamic> json) => Media(
id: int.tryParse(json["data"]["id"]),
And for toJson pass id as String
Map<String, dynamic> toJson() => {
"id": id.toString(),
More about int.tryParse.

how to get complex json data in future builder dart

{
"count": 6,
"next": null,
"previous": null,
"results": [
{
"id": 6,
"title": "Java6",
"description": "Java Basic",
"category": {
"id": 1,
"name": "Math"
},
"sub_category": {
"id": 4,
"name": "Test"
},
"tag": "string",
"video": {
"id": 6,
"duration": 10,
"thumbnail": "https://ibb.co/MZkfS7Q",
"link": "https://youtu.be/RgMeVbPbn-Q",
"views": 0
},
"quiz": {
"mcq": [
{
"id": 6,
"question": "q",
"option1": "b",
"option2": "c",
"option3": "d",
"option4": "e",
"answer": 1,
"appears_at": 0
}
]
},
"avg_rating": 1,
"total_number_of_rating": 1
},]}
how can I show this JSON data in future builder in dart
I have tried this way
Future<dynamic> geteducators() async {
String serviceurl = "https://api.spiro.study/latest-videos";
var response = await http.get(serviceurl);
final jsonrespose = json.decode(response.body);
print('title: ${jsonrespose}');
Videos latestVideo = Videos.fromJson(jsonrespose);
return latestVideo.results;
}
#override
void initState() {
super.initState();
_futureeducators = geteducators();
}
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
final response =
await http.get(Uri.parse('https://dog.ceo/api/breeds/image/random'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class Album {
//final int userId;
final String message;
final String status;
// final String region;
// final String country;
// final String title;
Album({
//required this.userId,
required this.message,
required this.status,
// required this.country,
// required this.region,
//required this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
// userId: json['userId'],
message: json['message'],
status: json['status'],
// country: json['country'],
// region: json['region'],
//title: json['total'],
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
#override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(snapshot.data!.status),
Image(image: NetworkImage(snapshot.data!.message))
],
); //Text(snapshot.data!.ip);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
),
),
);
}
}
//in this way you can get json data and show it in grid or list view.
How to use nested future builder for complex json i mean I'm getting name.from same.json in array and other hand I'm getting values from some json but diffrent aaray and array name is similer to uppe

How to decode this response From server? I am stuck on it,The "data" in response is in Maps

My json response from server
{"success":1,"error":[],"data":{"38":{"address_id":"38","firstname":"Raj","lastname":"s","company":"","address_1":"aaaa","address_2":"","postcode":"966666","city":"aa","zone_id":"1234","zone":"Kerewan","zone_code":"KE","country_id":"0","country":"","iso_code_2":"","iso_code_3":"","address_format":"","custom_field":null},"37":{"address_id":"37","firstname":"Raj","lastname":"s","company":"","address_1":"4 kk\t","address_2":"","postcode":"56774\t","city":"Chennai\t","zone_id":"1234","zone":"Kerewan","zone_code":"KE","country_id":"0","country":"","iso_code_2":"","iso_code_3":"","address_format":"","custom_field":null},}}
My minimal Code
List<Address> listAddress;
Future<List<Address>> getAddresList()async {
List<Address> listAddress;
{
try {
var response = await http.post(
"URL",
headers: {"content-type": "application/json", "cookie": cookie});
List<Address> list = [];
if (response.statusCode == 200) {
var data=convert.jsonDecode(response.body);
for (var item in convert.jsonDecode(response.body)) {
list.add(AddressOpencart.fromJson(item) as Address);
}
}
setState(() {
listAddress = list;
print("DDll"+listAddress.toString());
});
} catch (err,trace) {
print(trace.toString());
print(err.toString());
rethrow;
}
}
}
MY Address Model
Address.fromOpencartJson(Map<String, dynamic> json) {
try {
firstName = json['firstname'];
lastName = json['lastname'];
street = json['address_1'];
city = json['city'];
state = json['zone'];
country = json['country'];
phoneNumber = json['phone'];
zipCode = json['postcode'];
} catch (e) {
print(e.toString());
}
}
You can copy paste run full code below
You can use convert map to list with payload.data.forEach((k, v) => list.add(v)); and remove control character \t and display with FutureBuilder
code snippet
var response = http.Response(jsonString, 200);
List<Address> list = [];
if (response.statusCode == 200) {
String jsonStringNoCtrlChar = response.body.replaceAll("\t", "");
var payload = payloadFromJson(jsonStringNoCtrlChar);
payload.data.forEach((k, v) => list.add(v));
return list;
}
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
int success;
List<dynamic> error;
Map<String, Address> data;
Payload({
this.success,
this.error,
this.data,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
success: json["success"],
error: List<dynamic>.from(json["error"].map((x) => x)),
data: Map.from(json["data"])
.map((k, v) => MapEntry<String, Address>(k, Address.fromJson(v))),
);
Map<String, dynamic> toJson() => {
"success": success,
"error": List<dynamic>.from(error.map((x) => x)),
"data": Map.from(data)
.map((k, v) => MapEntry<String, dynamic>(k, v.toJson())),
};
}
class Address {
String addressId;
String firstname;
String lastname;
String company;
String address1;
String address2;
String postcode;
String city;
String zoneId;
String zone;
String zoneCode;
String countryId;
String country;
String isoCode2;
String isoCode3;
String addressFormat;
dynamic customField;
Address({
this.addressId,
this.firstname,
this.lastname,
this.company,
this.address1,
this.address2,
this.postcode,
this.city,
this.zoneId,
this.zone,
this.zoneCode,
this.countryId,
this.country,
this.isoCode2,
this.isoCode3,
this.addressFormat,
this.customField,
});
factory Address.fromJson(Map<String, dynamic> json) => Address(
addressId: json["address_id"],
firstname: json["firstname"],
lastname: json["lastname"],
company: json["company"],
address1: json["address_1"],
address2: json["address_2"],
postcode: json["postcode"],
city: json["city"],
zoneId: json["zone_id"],
zone: json["zone"],
zoneCode: json["zone_code"],
countryId: json["country_id"],
country: json["country"],
isoCode2: json["iso_code_2"],
isoCode3: json["iso_code_3"],
addressFormat: json["address_format"],
customField: json["custom_field"],
);
Map<String, dynamic> toJson() => {
"address_id": addressId,
"firstname": firstname,
"lastname": lastname,
"company": company,
"address_1": address1,
"address_2": address2,
"postcode": postcode,
"city": city,
"zone_id": zoneId,
"zone": zone,
"zone_code": zoneCode,
"country_id": countryId,
"country": country,
"iso_code_2": isoCode2,
"iso_code_3": isoCode3,
"address_format": addressFormat,
"custom_field": customField,
};
}
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<List<Address>> _future;
Future<List<Address>> getAddresList() async {
try {
/*var response = await http.post(
"URL",
headers: {"content-type": "application/json", "cookie": cookie});*/
String jsonString = '''
{"success":1,
"error":[],
"data":
{"38":
{"address_id":"38",
"firstname":"Raj",
"lastname":"s",
"company":"",
"address_1":"aaaa",
"address_2":"",
"postcode":"966666",
"city":"aa",
"zone_id":"1234",
"zone":"Kerewan",
"zone_code":"KE",
"country_id":"0",
"country":"",
"iso_code_2":"",
"iso_code_3":"",
"address_format":"",
"custom_field":null},
"37":{"address_id":"37","firstname":"Raj","lastname":"s","company":"","address_1":"4 kk\t","address_2":"","postcode":"56774\t","city":"Chennai\t","zone_id":"1234","zone":"Kerewan","zone_code":"KE","country_id":"0","country":"","iso_code_2":"","iso_code_3":"","address_format":"","custom_field":null}}
}
''';
var response = http.Response(jsonString, 200);
List<Address> list = [];
if (response.statusCode == 200) {
String jsonStringNoCtrlChar = response.body.replaceAll("\t", "");
var payload = payloadFromJson(jsonStringNoCtrlChar);
payload.data.forEach((k, v) => list.add(v));
return list;
}
} catch (err, trace) {
print(trace.toString());
print(err.toString());
rethrow;
}
}
#override
void initState() {
_future = getAddresList();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: _future,
builder: (context, AsyncSnapshot<List<Address>> 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.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[index].addressId),
Spacer(),
Text(snapshot.data[index].address1),
],
),
));
});
}
}
}));
}
}
You must fix your data parameter in API response. It should be an array of objects.
{
"success": 1,
"error": [
],
"data": [
{
"address_id": "38",
"firstname": "Raj",
"lastname": "s",
"company": "",
"address_1": "aaaa",
"address_2": "",
"postcode": "966666",
"city": "aa",
"zone_id": "1234",
"zone": "Kerewan",
"zone_code": "KE",
"country_id": "0",
"country": "",
"iso_code_2": "",
"iso_code_3": "",
"address_format": "",
"custom_field": null
},
{
"address_id": "37",
"firstname": "Raj",
"lastname": "s",
"company": "",
"address_1": "4 kk\t",
"address_2": "",
"postcode": "56774\t",
"city": "Chennai\t",
"zone_id": "1234",
"zone": "Kerewan",
"zone_code": "KE",
"country_id": "0",
"country": "",
"iso_code_2": "",
"iso_code_3": "",
"address_format": "",
"custom_field": null
}
]
}
Now, your code looks good to me but with few changes in it:
Future<List<Address>> getAddresList()async {
List<Address> listAddress;
try {
var response = await http.post(
"URL",
headers: {"content-type": "application/json", "cookie": cookie});
List<Address> list = List<Address>();
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
for (var item in data["data"]) {
list.add(AddressOpencart.fromJson(item) as Address);
}
}
setState(() {
listAddress = list;
print("DDll"+listAddress.toString());
});
} catch (err,trace) {
print(trace.toString());
print(err.toString());
}
}
Address.fromOpencartJson(Map<String, dynamic> json) :
firstName = json['firstname'],
lastName = json['lastname'],
street = json['address_1'],
city = json['city'],
state = json['zone'],
country = json['country'],
phoneNumber = json['phone'],
zipCode = json['postcode'];

How to display in widget the complex JSON using flutter?

My problem is i don't know how to display the Object inside the Object of JSON.
But i already display the Outer Object like name, usermae etc. And i want to display the object inside the Address and Geo. Im new to JSON and flutter please guide me
i read this but i dont know what i need here
the code is from here
JSON OUTPUT json is from here
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
]
MODEL
i generate my model in here
import 'dart:convert';
List<UserModel> userModelFromJson(String str) =>
List<UserModel>.from(json.decode(str).map((x) => UserModel.fromJson(x)));
String userModelToJson(List<UserModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class UserModel {
int id;
String name;
String username;
String email;
Address address;
String phone;
String website;
Company company;
UserModel({
this.id,
this.name,
this.username,
this.email,
this.address,
this.phone,
this.website,
this.company,
});
factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(
id: json["id"],
name: json["name"],
username: json["username"],
email: json["email"],
address: Address.fromJson(json["address"]),
phone: json["phone"],
website: json["website"],
company: Company.fromJson(json["company"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"username": username,
"email": email,
"address": address.toJson(),
"phone": phone,
"website": website,
"company": company.toJson(),
};
}
class Address {
String street;
String suite;
String city;
String zipcode;
Geo geo;
Address({
this.street,
this.suite,
this.city,
this.zipcode,
this.geo,
});
factory Address.fromJson(Map<String, dynamic> json) => Address(
street: json["street"],
suite: json["suite"],
city: json["city"],
zipcode: json["zipcode"],
geo: Geo.fromJson(json["geo"]),
);
Map<String, dynamic> toJson() => {
"street": street,
"suite": suite,
"city": city,
"zipcode": zipcode,
"geo": geo.toJson(),
};
}
class Geo {
String lat;
String lng;
Geo({
this.lat,
this.lng,
});
factory Geo.fromJson(Map<String, dynamic> json) => Geo(
lat: json["lat"],
lng: json["lng"],
);
Map<String, dynamic> toJson() => {
"lat": lat,
"lng": lng,
};
}
class Company {
String name;
String catchPhrase;
String bs;
Company({
this.name,
this.catchPhrase,
this.bs,
});
factory Company.fromJson(Map<String, dynamic> json) => Company(
name: json["name"],
catchPhrase: json["catchPhrase"],
bs: json["bs"],
);
Map<String, dynamic> toJson() => {
"name": name,
"catchPhrase": catchPhrase,
"bs": bs,
};
}
Services.dart
class Services {
static const String url = 'https://jsonplaceholder.typicode.com/users';
static Future<List<UserModel>> getUsers() async {
try {
final response = await http.get(url);
if (200 == response.statusCode) {
final List<UserModel> users = userModelFromJson(response.body);
return users;
} else {
return List<UserModel>();
}
} catch (e) {
return List<UserModel>();
}
}
}
HomeView.dart
class _HomeViewState extends State<HomeView> {
List<UserModel> _users;
bool _loading;
#override
void initState() {
super.initState();
_loading = true;
Services.getUsers().then((users) {
setState(() {
_users = users;
_loading = false;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_loading ? 'Loading...' : 'Users'),
),
body: Container(
color: Colors.white,
child: ListView.builder(
itemCount: _users == null ? 0 : _users.length,
itemBuilder: (context, index) {
UserModel user = _users[index];
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
ListTile(
title: Text(user.name),
subtitle: Text(user.email),
trailing: Text(user.phone),
),
],
);
},
),
),
);
}
}
Thank you for your kindness
The model that you create is correct, you have (Good habit) only to check the objects inside your model before you parse them
UserModel.fromJson(Map<String, dynamic> json) {
// ...
address =
json['address'] != null ? new Address.fromJson(json['address']) : null;
company =
json['company'] != null ? new Company.fromJson(json['company']) : null;
// ...
}
On your service class use the fetch way that is set on flutter documentation to simplify your code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<UserModel>> fetchUsers(http.Client client) async {
final response =
await client.get('https://jsonplaceholder.typicode.com/users');
return parseUsers(response.body);
}
List<UserModel> parseUsers(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<UserModel>((json) => UserModel.fromJson(json)).toList();
}
and once you get the data from json you can access to every object based on the hierarchy inside the json, in your case the stateful widget would look like, where i replace the name and the phone with latitude inside the geo and city inside the address
class _HomeViewState extends State<HomeView> {
List<UserModel> _users;
bool _loading;
#override
void initState() {
super.initState();
_loading = true;
fetchUsers(http.Client()).then((users) {
setState(() {
_users = users;
_loading = false;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_loading ? 'Loading...' : 'Users'),
),
body: Container(
color: Colors.white,
child: ListView.builder(
itemCount: _users == null ? 0 : _users.length,
itemBuilder: (context, index) {
UserModel user = _users[index];
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
ListTile(
title: Text(user.name),
subtitle: Text(user.address.geo.lat),
trailing: Text(user.address.city),
),
],
);
},
),
),
);
}
}
I hope this help
You can copy paste run full code below
You can directly assign attribute
code snippet
title: Text('${user.name} ${user.address.city} ${user.address.geo.lat}'),
working demo
full code
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
List<UserModel> userModelFromJson(String str) =>
List<UserModel>.from(json.decode(str).map((x) => UserModel.fromJson(x)));
String userModelToJson(List<UserModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class UserModel {
int id;
String name;
String username;
String email;
Address address;
String phone;
String website;
Company company;
UserModel({
this.id,
this.name,
this.username,
this.email,
this.address,
this.phone,
this.website,
this.company,
});
factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(
id: json["id"],
name: json["name"],
username: json["username"],
email: json["email"],
address: Address.fromJson(json["address"]),
phone: json["phone"],
website: json["website"],
company: Company.fromJson(json["company"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"username": username,
"email": email,
"address": address.toJson(),
"phone": phone,
"website": website,
"company": company.toJson(),
};
}
class Address {
String street;
String suite;
String city;
String zipcode;
Geo geo;
Address({
this.street,
this.suite,
this.city,
this.zipcode,
this.geo,
});
factory Address.fromJson(Map<String, dynamic> json) => Address(
street: json["street"],
suite: json["suite"],
city: json["city"],
zipcode: json["zipcode"],
geo: Geo.fromJson(json["geo"]),
);
Map<String, dynamic> toJson() => {
"street": street,
"suite": suite,
"city": city,
"zipcode": zipcode,
"geo": geo.toJson(),
};
}
class Geo {
String lat;
String lng;
Geo({
this.lat,
this.lng,
});
factory Geo.fromJson(Map<String, dynamic> json) => Geo(
lat: json["lat"],
lng: json["lng"],
);
Map<String, dynamic> toJson() => {
"lat": lat,
"lng": lng,
};
}
class Company {
String name;
String catchPhrase;
String bs;
Company({
this.name,
this.catchPhrase,
this.bs,
});
factory Company.fromJson(Map<String, dynamic> json) => Company(
name: json["name"],
catchPhrase: json["catchPhrase"],
bs: json["bs"],
);
Map<String, dynamic> toJson() => {
"name": name,
"catchPhrase": catchPhrase,
"bs": bs,
};
}
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: HomeView(title: 'Flutter Demo Home Page'),
);
}
}
class Services {
static const String url = 'https://jsonplaceholder.typicode.com/users';
static Future<List<UserModel>> getUsers() async {
try {
final response = await http.get(url);
if (200 == response.statusCode) {
final List<UserModel> users = userModelFromJson(response.body);
return users;
} else {
return List<UserModel>();
}
} catch (e) {
return List<UserModel>();
}
}
}
class HomeView extends StatefulWidget {
HomeView({Key key, this.title}) : super(key: key);
final String title;
#override
_HomeViewState createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
List<UserModel> _users;
bool _loading;
#override
void initState() {
super.initState();
_loading = true;
Services.getUsers().then((users) {
setState(() {
_users = users;
_loading = false;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_loading ? 'Loading...' : 'Users'),
),
body: Container(
color: Colors.white,
child: ListView.builder(
itemCount: _users == null ? 0 : _users.length,
itemBuilder: (context, index) {
UserModel user = _users[index];
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
ListTile(
title: Text('${user.name} ${user.address.city} ${user.address.geo.lat}'),
subtitle: Text(user.email),
trailing: Text(user.phone),
),
],
);
},
),
),
);
}
}