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

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'];

Related

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

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

Parsing Json data in flutter

Hi I have a json corresponding to that I need to fetch data but no data is being shown on the screen don't know why most probably Implementation is wrong
class TestScreen extends StatefulWidget {
const TestScreen({Key? key}) : super(key: key);
#override
State<TestScreen> createState() => _TestScreenState();
}
class _TestScreenState extends State<TestScreen> {
List<AppDetails> details = [];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: kBackgroundColor,
title: Text(
'Home',
style: Theme.of(context).textTheme.headline2,
),
),
body: Expanded(
child: ListView.builder(
itemCount: details.length,
itemBuilder: (context, index) {
final detail = details[index];
return buildProduct(detail);
}),
),
);
}
}
Widget buildProduct(AppDetails detail) => Column(
children: [Center(child: Text('${detail.benefits}'))],
);
Above is My Implementation
{
"name": "TestingApp",
"category": "Production",
"subcategory": "Productivity",
"imageUrl": "Testing-Banner.jpg",
"logo": "PI.png",
"description": "Testing is an application for easy & effective Inspection",
"appDetails": [{
"systemOverview": "https:url.com",
"multiDeviceSupport": [{
"label": "Multi-Device"
},
{
"label": "Multi-Lingual"
},
{
"label": "Multi-Database"
}
],
"mainFeatures": [{
"label": "Testing"
},
{
"label": "Ease"
},
{
"label": "Select failure "
},
{
"label": "Add comments & take evidence Pictures"
},
{
"label": "Send results to central system"
},
{
"label": "Search/view "
}
],
"benefits": [{
"label": "Easy & quick solution "
},
{
"label": "Go paperless "
},
{
"label": "Lower costs"
},
{
"label": "Improve quality/safety"
},
{
"label": "Configurable on hand-held devices and tablets"
},
{
"label": "Electronic notifications to corresponding personnel’s"
}
]
}]
}
Following is a json sample
I need to show all the benefits similarly all the multidevice support Or can say all the app details but in different kind of a container.
any help would be great.
is this what you want?
try this code or try on dartpad
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MaterialApp(home: TestScreen()));
}
class TestScreen extends StatefulWidget {
const TestScreen({Key? key}) : super(key: key);
#override
State<TestScreen> createState() => _TestScreenState();
}
class _TestScreenState extends State<TestScreen> {
List<AppDetails>? details = [];
final Map<String, dynamic> json = {
"name": "TestingApp",
"category": "Production",
"subcategory": "Productivity",
"imageUrl": "Testing-Banner.jpg",
"logo": "PI.png",
"description": "Testing is an application for easy & effective Inspection",
"appDetails": [
{
"systemOverview": "https:url.com",
"multiDeviceSupport": [
{"label": "Multi-Device"},
{"label": "Multi-Lingual"},
{"label": "Multi-Database"}
],
"mainFeatures": [
{"label": "Testing"},
{"label": "Ease"},
{"label": "Select failure "},
{"label": "Add comments & take evidence Pictures"},
{"label": "Send results to central system"},
{"label": "Search/view "}
],
"benefits": [
{"label": "Easy & quick solution "},
{"label": "Go paperless "},
{"label": "Lower costs"},
{"label": "Improve quality/safety"},
{"label": "Configurable on hand-held devices and tablets"},
{"label": "Electronic notifications to corresponding personnel’s"}
]
}
]
};
#override
void initState() {
super.initState();
final data = AppDetailModel.fromJson(json);
details = data.appDetails;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.blue,
title: const Text('Home'),
),
body: SizedBox(
child: ListView.builder(
itemCount: details?.length,
itemBuilder: (context, index) {
final detail = details?[index];
return buildProduct(detail);
},
),
),
);
}
}
Widget buildProduct(AppDetails? detail) => Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: (detail?.benefits ?? []).map((e) {
final index = (detail?.benefits ?? []).indexOf(e);
return Row(
children: [
SizedBox(width: 20, child: Text('${index + 1}.')),
Text('${e.label}'),
],
);
}).toList(),
),
);
class AppDetailModel {
String? name;
String? category;
String? subcategory;
String? imageUrl;
String? logo;
String? description;
List<AppDetails>? appDetails;
AppDetailModel(
{this.name,
this.category,
this.subcategory,
this.imageUrl,
this.logo,
this.description,
this.appDetails});
AppDetailModel.fromJson(Map<String, dynamic> json) {
name = json['name'];
category = json['category'];
subcategory = json['subcategory'];
imageUrl = json['imageUrl'];
logo = json['logo'];
description = json['description'];
if (json['appDetails'] != null) {
appDetails = <AppDetails>[];
json['appDetails'].forEach((v) {
appDetails!.add(AppDetails.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['name'] = name;
data['category'] = category;
data['subcategory'] = subcategory;
data['imageUrl'] = imageUrl;
data['logo'] = logo;
data['description'] = description;
if (appDetails != null) {
data['appDetails'] = appDetails!.map((v) => v.toJson()).toList();
}
return data;
}
}
class AppDetails {
String? systemOverview;
List<Label>? multiDeviceSupport;
List<Label>? mainFeatures;
List<Label>? benefits;
AppDetails(
{this.systemOverview,
this.multiDeviceSupport,
this.mainFeatures,
this.benefits});
AppDetails.fromJson(Map<String, dynamic> json) {
systemOverview = json['systemOverview'];
if (json['multiDeviceSupport'] != null) {
multiDeviceSupport = <Label>[];
json['multiDeviceSupport'].forEach((v) {
multiDeviceSupport!.add(Label.fromJson(v));
});
}
if (json['mainFeatures'] != null) {
mainFeatures = <Label>[];
json['mainFeatures'].forEach((v) {
mainFeatures!.add(Label.fromJson(v));
});
}
if (json['benefits'] != null) {
benefits = <Label>[];
json['benefits'].forEach((v) {
benefits!.add(Label.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['systemOverview'] = systemOverview;
if (multiDeviceSupport != null) {
data['multiDeviceSupport'] =
multiDeviceSupport!.map((v) => v.toJson()).toList();
}
if (mainFeatures != null) {
data['mainFeatures'] = mainFeatures!.map((v) => v.toJson()).toList();
}
if (benefits != null) {
data['benefits'] = benefits!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Label {
String? label;
Label({this.label});
Label.fromJson(Map<String, dynamic> json) {
label = json['label'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['label'] = label;
return data;
}
}

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

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

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),
),
],
);
},
),
),
);
}
}

Flutter fetch data from the internet

I'm trying to get some information from here such as name,avatar_url,stargazers_count and description
{
"total_count": 18689015,
"incomplete_results": true,
"items": [
{
"id": 215415332,
"node_id": "MDEwOlJlcG9zaXRvcnkyMTU0MTUzMzI=",
"name": "HackingNeuralNetworks",
"full_name": "Kayzaks/HackingNeuralNetworks",
"private": false,
"owner": {
"login": "Kayzaks",
"id": 11071537,
"node_id": "MDQ6VXNlcjExMDcxNTM3",
"avatar_url": "https://avatars1.githubusercontent.com/u/11071537?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/Kayzaks",
"html_url": "https://github.com/Kayzaks",
"followers_url": "https://api.github.com/users/Kayzaks/followers",
"following_url": "https://api.github.com/users/Kayzaks/following{/other_user}",
"gists_url": "https://api.github.com/users/Kayzaks/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Kayzaks/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Kayzaks/subscriptions",
"organizations_url": "https://api.github.com/users/Kayzaks/orgs",
"repos_url": "https://api.github.com/users/Kayzaks/repos",
"events_url": "https://api.github.com/users/Kayzaks/events{/privacy}",
"received_events_url": "https://api.github.com/users/Kayzaks/received_events",
"type": "User",
"site_admin": false
},
"html_url": "https://github.com/Kayzaks/HackingNeuralNetworks",
"description": "A small course on exploiting and defending neural networks",
"fork": false,
....
....
At run time I get this message error :
type _internalLine HashMap<String , dynamic> is not a subtype of type List<dynamic> in type cast
here's the full code :
RepoItem:
class RepoItem {
Owner owner;
String name;
String stargazers_count;
String description;
RepoItem._({this.owner, this.name, this.stargazers_count, this.description});
factory RepoItem.fromJson(Map<String, dynamic> json) {
return new RepoItem._(
owner: json['owner'],
name: json['name'],
stargazers_count: json['stargazers_count'],
description: json['description']);
}
}
PageState:
class _MyHomePageState extends State<MyHomePage> {
List<RepoItem> list = List();
var isLoading = false;
Future<List<RepoItem>> _fetchData() async {
final response = await http.get(
"https://api.github.com/search/repositories?q=created:%3E2018-10-22&sort=stars&order=desc");
list = (json.decode(response.body) as List)
.map((data) => new RepoItem.fromJson(data.body))
.toList();
return list;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
child: FutureBuilder(
future: _fetchData(),
builder: (BuildContext context, AsyncSnapshot asyncSnapshot) {
if (asyncSnapshot.hasError) {
return Container(
child: Center(
child: Text(asyncSnapshot.error.toString()),
),
);
}
if (asyncSnapshot.data == null) {
return Container(
child: Center(
child: Text("Loading ..."),
),
);
} else {
return ListView.builder(
itemCount: asyncSnapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(asyncSnapshot.data[index].name),
leading: CircleAvatar(
backgroundImage: NetworkImage(
asyncSnapshot.data[index].owner.avatar_url),
),
subtitle: Text(asyncSnapshot.data[index].description),
);
},
);
}
},
),
),
);
}
}
You can copy paste run full code below
You can parse with payloadFromJson, you can see Payload class in full code
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
...
var items = snapshot.data.items;
return ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(items[index].name),
leading: CircleAvatar(
backgroundImage:
NetworkImage(items[index].owner.avatarUrl),
),
subtitle: Text(items[index].description),
);
},
);
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
String totalCount;
bool incompleteResults;
List<Item> items;
Payload({
this.totalCount,
this.incompleteResults,
this.items,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
totalCount: json["total_count"].toString(),
incompleteResults: json["incomplete_results"],
items: List<Item>.from(json["items"].map((x) => Item.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"total_count": totalCount,
"incomplete_results": incompleteResults,
"items": List<dynamic>.from(items.map((x) => x.toJson())),
};
}
class Item {
String id;
String nodeId;
String name;
String fullName;
bool private;
Owner owner;
String htmlUrl;
String description;
bool fork;
String url;
String forksUrl;
String keysUrl;
String collaboratorsUrl;
String teamsUrl;
String hooksUrl;
String issueEventsUrl;
String eventsUrl;
String assigneesUrl;
String branchesUrl;
String tagsUrl;
String blobsUrl;
String gitTagsUrl;
String gitRefsUrl;
String treesUrl;
String statusesUrl;
String languagesUrl;
String stargazersUrl;
String contributorsUrl;
String subscribersUrl;
String subscriptionUrl;
String commitsUrl;
String gitCommitsUrl;
String commentsUrl;
String issueCommentUrl;
String contentsUrl;
String compareUrl;
String mergesUrl;
String archiveUrl;
String downloadsUrl;
String issuesUrl;
String pullsUrl;
String milestonesUrl;
String notificationsUrl;
String labelsUrl;
String releasesUrl;
String deploymentsUrl;
DateTime createdAt;
DateTime updatedAt;
DateTime pushedAt;
String gitUrl;
String sshUrl;
String cloneUrl;
String svnUrl;
String homepage;
int size;
int stargazersCount;
int watchersCount;
String language;
bool hasIssues;
bool hasProjects;
bool hasDownloads;
bool hasWiki;
bool hasPages;
int forksCount;
dynamic mirrorUrl;
bool archived;
bool disabled;
int openIssuesCount;
License license;
int forks;
int openIssues;
int watchers;
DefaultBranch defaultBranch;
double score;
Item({
this.id,
this.nodeId,
this.name,
this.fullName,
this.private,
this.owner,
this.htmlUrl,
this.description,
this.fork,
this.url,
this.forksUrl,
this.keysUrl,
this.collaboratorsUrl,
this.teamsUrl,
this.hooksUrl,
this.issueEventsUrl,
this.eventsUrl,
this.assigneesUrl,
this.branchesUrl,
this.tagsUrl,
this.blobsUrl,
this.gitTagsUrl,
this.gitRefsUrl,
this.treesUrl,
this.statusesUrl,
this.languagesUrl,
this.stargazersUrl,
this.contributorsUrl,
this.subscribersUrl,
this.subscriptionUrl,
this.commitsUrl,
this.gitCommitsUrl,
this.commentsUrl,
this.issueCommentUrl,
this.contentsUrl,
this.compareUrl,
this.mergesUrl,
this.archiveUrl,
this.downloadsUrl,
this.issuesUrl,
this.pullsUrl,
this.milestonesUrl,
this.notificationsUrl,
this.labelsUrl,
this.releasesUrl,
this.deploymentsUrl,
this.createdAt,
this.updatedAt,
this.pushedAt,
this.gitUrl,
this.sshUrl,
this.cloneUrl,
this.svnUrl,
this.homepage,
this.size,
this.stargazersCount,
this.watchersCount,
this.language,
this.hasIssues,
this.hasProjects,
this.hasDownloads,
this.hasWiki,
this.hasPages,
this.forksCount,
this.mirrorUrl,
this.archived,
this.disabled,
this.openIssuesCount,
this.license,
this.forks,
this.openIssues,
this.watchers,
this.defaultBranch,
this.score,
});
factory Item.fromJson(Map<String, dynamic> json) => Item(
id: json["id"].toString(),
nodeId: json["node_id"],
name: json["name"],
fullName: json["full_name"],
private: json["private"],
owner: Owner.fromJson(json["owner"]),
htmlUrl: json["html_url"],
description: json["description"] == null ? null : json["description"],
fork: json["fork"],
url: json["url"],
forksUrl: json["forks_url"],
keysUrl: json["keys_url"],
collaboratorsUrl: json["collaborators_url"],
teamsUrl: json["teams_url"],
hooksUrl: json["hooks_url"],
issueEventsUrl: json["issue_events_url"],
eventsUrl: json["events_url"],
assigneesUrl: json["assignees_url"],
branchesUrl: json["branches_url"],
tagsUrl: json["tags_url"],
blobsUrl: json["blobs_url"],
gitTagsUrl: json["git_tags_url"],
gitRefsUrl: json["git_refs_url"],
treesUrl: json["trees_url"],
statusesUrl: json["statuses_url"],
languagesUrl: json["languages_url"],
stargazersUrl: json["stargazers_url"],
contributorsUrl: json["contributors_url"],
subscribersUrl: json["subscribers_url"],
subscriptionUrl: json["subscription_url"],
commitsUrl: json["commits_url"],
gitCommitsUrl: json["git_commits_url"],
commentsUrl: json["comments_url"],
issueCommentUrl: json["issue_comment_url"],
contentsUrl: json["contents_url"],
compareUrl: json["compare_url"],
mergesUrl: json["merges_url"],
archiveUrl: json["archive_url"],
downloadsUrl: json["downloads_url"],
issuesUrl: json["issues_url"],
pullsUrl: json["pulls_url"],
milestonesUrl: json["milestones_url"],
notificationsUrl: json["notifications_url"],
labelsUrl: json["labels_url"],
releasesUrl: json["releases_url"],
deploymentsUrl: json["deployments_url"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
pushedAt: DateTime.parse(json["pushed_at"]),
gitUrl: json["git_url"],
sshUrl: json["ssh_url"],
cloneUrl: json["clone_url"],
svnUrl: json["svn_url"],
homepage: json["homepage"] == null ? null : json["homepage"],
size: json["size"],
stargazersCount: json["stargazers_count"],
watchersCount: json["watchers_count"],
language: json["language"] == null ? null : json["language"],
hasIssues: json["has_issues"],
hasProjects: json["has_projects"],
hasDownloads: json["has_downloads"],
hasWiki: json["has_wiki"],
hasPages: json["has_pages"],
forksCount: json["forks_count"],
mirrorUrl: json["mirror_url"],
archived: json["archived"],
disabled: json["disabled"],
openIssuesCount: json["open_issues_count"],
license:
json["license"] == null ? null : License.fromJson(json["license"]),
forks: json["forks"],
openIssues: json["open_issues"],
watchers: json["watchers"],
defaultBranch: defaultBranchValues.map[json["default_branch"]],
score: json["score"],
);
Map<String, dynamic> toJson() => {
"id": id,
"node_id": nodeId,
"name": name,
"full_name": fullName,
"private": private,
"owner": owner.toJson(),
"html_url": htmlUrl,
"description": description == null ? null : description,
"fork": fork,
"url": url,
"forks_url": forksUrl,
"keys_url": keysUrl,
"collaborators_url": collaboratorsUrl,
"teams_url": teamsUrl,
"hooks_url": hooksUrl,
"issue_events_url": issueEventsUrl,
"events_url": eventsUrl,
"assignees_url": assigneesUrl,
"branches_url": branchesUrl,
"tags_url": tagsUrl,
"blobs_url": blobsUrl,
"git_tags_url": gitTagsUrl,
"git_refs_url": gitRefsUrl,
"trees_url": treesUrl,
"statuses_url": statusesUrl,
"languages_url": languagesUrl,
"stargazers_url": stargazersUrl,
"contributors_url": contributorsUrl,
"subscribers_url": subscribersUrl,
"subscription_url": subscriptionUrl,
"commits_url": commitsUrl,
"git_commits_url": gitCommitsUrl,
"comments_url": commentsUrl,
"issue_comment_url": issueCommentUrl,
"contents_url": contentsUrl,
"compare_url": compareUrl,
"merges_url": mergesUrl,
"archive_url": archiveUrl,
"downloads_url": downloadsUrl,
"issues_url": issuesUrl,
"pulls_url": pullsUrl,
"milestones_url": milestonesUrl,
"notifications_url": notificationsUrl,
"labels_url": labelsUrl,
"releases_url": releasesUrl,
"deployments_url": deploymentsUrl,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
"pushed_at": pushedAt.toIso8601String(),
"git_url": gitUrl,
"ssh_url": sshUrl,
"clone_url": cloneUrl,
"svn_url": svnUrl,
"homepage": homepage == null ? null : homepage,
"size": size,
"stargazers_count": stargazersCount,
"watchers_count": watchersCount,
"language": language == null ? null : language,
"has_issues": hasIssues,
"has_projects": hasProjects,
"has_downloads": hasDownloads,
"has_wiki": hasWiki,
"has_pages": hasPages,
"forks_count": forksCount,
"mirror_url": mirrorUrl,
"archived": archived,
"disabled": disabled,
"open_issues_count": openIssuesCount,
"license": license == null ? null : license.toJson(),
"forks": forks,
"open_issues": openIssues,
"watchers": watchers,
"default_branch": defaultBranchValues.reverse[defaultBranch],
"score": score,
};
}
enum DefaultBranch { MASTER }
final defaultBranchValues = EnumValues({"master": DefaultBranch.MASTER});
class License {
String key;
String name;
String spdxId;
String url;
String nodeId;
License({
this.key,
this.name,
this.spdxId,
this.url,
this.nodeId,
});
factory License.fromJson(Map<String, dynamic> json) => License(
key: json["key"],
name: json["name"],
spdxId: json["spdx_id"],
url: json["url"] == null ? null : json["url"],
nodeId: json["node_id"],
);
Map<String, dynamic> toJson() => {
"key": key,
"name": name,
"spdx_id": spdxId,
"url": url == null ? null : url,
"node_id": nodeId,
};
}
class Owner {
String login;
String id;
String nodeId;
String avatarUrl;
String gravatarId;
String url;
String htmlUrl;
String followersUrl;
String followingUrl;
String gistsUrl;
String starredUrl;
String subscriptionsUrl;
String organizationsUrl;
String reposUrl;
String eventsUrl;
String receivedEventsUrl;
Type type;
bool siteAdmin;
Owner({
this.login,
this.id,
this.nodeId,
this.avatarUrl,
this.gravatarId,
this.url,
this.htmlUrl,
this.followersUrl,
this.followingUrl,
this.gistsUrl,
this.starredUrl,
this.subscriptionsUrl,
this.organizationsUrl,
this.reposUrl,
this.eventsUrl,
this.receivedEventsUrl,
this.type,
this.siteAdmin,
});
factory Owner.fromJson(Map<String, dynamic> json) => Owner(
login: json["login"],
id: json["id"].toString(),
nodeId: json["node_id"],
avatarUrl: json["avatar_url"],
gravatarId: json["gravatar_id"],
url: json["url"],
htmlUrl: json["html_url"],
followersUrl: json["followers_url"],
followingUrl: json["following_url"],
gistsUrl: json["gists_url"],
starredUrl: json["starred_url"],
subscriptionsUrl: json["subscriptions_url"],
organizationsUrl: json["organizations_url"],
reposUrl: json["repos_url"],
eventsUrl: json["events_url"],
receivedEventsUrl: json["received_events_url"],
type: typeValues.map[json["type"]],
siteAdmin: json["site_admin"],
);
Map<String, dynamic> toJson() => {
"login": login,
"id": id,
"node_id": nodeId,
"avatar_url": avatarUrl,
"gravatar_id": gravatarId,
"url": url,
"html_url": htmlUrl,
"followers_url": followersUrl,
"following_url": followingUrl,
"gists_url": gistsUrl,
"starred_url": starredUrl,
"subscriptions_url": subscriptionsUrl,
"organizations_url": organizationsUrl,
"repos_url": reposUrl,
"events_url": eventsUrl,
"received_events_url": receivedEventsUrl,
"type": typeValues.reverse[type],
"site_admin": siteAdmin,
};
}
enum Type { USER, ORGANIZATION }
final typeValues =
EnumValues({"Organization": Type.ORGANIZATION, "User": Type.USER});
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
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> {
static final String URL = "https://corona.lmao.ninja/countries";
Future _future;
Future<Payload> _fetchData() async {
final response = await http.get(
"https://api.github.com/search/repositories?q=created:%3E2018-10-22&sort=stars&order=desc");
var list = payloadFromJson(response.body);
return list;
}
#override
void initState() {
// TODO: implement initState
super.initState();
_future = _fetchData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder<Payload>(
future: _future,
builder: (BuildContext context, AsyncSnapshot<Payload> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Input a URL to start');
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 {
var items = snapshot.data.items;
return ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(items[index].name),
leading: CircleAvatar(
backgroundImage:
NetworkImage(items[index].owner.avatarUrl),
),
subtitle: Text(items[index].description),
);
},
);
}
}
}));
}
}