Flutter fetch data from the internet - json

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

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

Stuck in CircularProgressIndicator when Fetching data from json API in flutter

I'm debugging an app on my physical device to fetch data from a json API but it keeps showing the CircularProgressIndicator as you see . Still a beginner and I've been trying to solve this for 3 days countinously . Thanks in advance, the code is below
here
main.dart code
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:json/pages/homePage.dart';
void main() {
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.dumpErrorToConsole(details);
if (kReleaseMode) exit(1);
};
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(),
);
}
}
homePage.dart file
import 'package:json/models/bcNewsModel.dart';
import 'package:json/services/api_manager.dart';
class HomePage extends StatefulWidget {
#override
MyHomePage createState() => MyHomePage();
// TODO: implement createState
}
class MyHomePage extends State<HomePage> {
Future<Bitcoin> _bcNews;
#override
void initeState() {
_bcNews = API_Manager().BCNews();
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text('BitCoin App'),
),
body: Container(
child: FutureBuilder<Bitcoin>(
future: _bcNews,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.articles.length,
// ignore: missing_return
itemBuilder: (context, index) {
var article = snapshot.data.articles[index];
Container(
height: 100,
child: Row(
children: <Widget>[
Image.network(article.urlToImage),
],
),
);
});
} else
return Center(child: CircularProgressIndicator());
},
),
));
}
}
api_manager.dart file
Bitcoin bitcoinFromJson(String str) => Bitcoin.fromJson(json.decode(str));
String bitcoinToJson(Bitcoin data) => json.encode(data.toJson());
class Bitcoin {
Bitcoin({
this.status,
this.totalResults,
this.articles,
});
String status;
int totalResults;
List<Article> articles;
factory Bitcoin.fromJson(Map<String, dynamic> json) => Bitcoin(
status: json["status"],
totalResults: json["totalResults"],
articles: List<Article>.from(
json["articles"].map((x) => Article.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"totalResults": totalResults,
"articles": List<dynamic>.from(articles.map((x) => x.toJson())),
};
}
class Article {
Article({
this.source,
this.author,
this.title,
this.description,
this.url,
this.urlToImage,
this.publishedAt,
this.content,
});
Source source;
String author;
String title;
String description;
String url;
String urlToImage;
DateTime publishedAt;
String content;
factory Article.fromJson(Map<String, dynamic> json) => Article(
source: Source.fromJson(json["source"]),
author: json["author"],
title: json["title"],
description: json["description"],
url: json["url"],
urlToImage: json["urlToImage"],
publishedAt: DateTime.parse(json["publishedAt"]),
content: json["content"],
);
Map<String, dynamic> toJson() => {
"source": source.toJson(),
"author": author,
"title": title,
"description": description,
"url": url,
"urlToImage": urlToImage,
"publishedAt": publishedAt.toIso8601String(),
"content": content,
};
}
class Source {
Source({
this.id,
this.name,
});
String id;
String name;
factory Source.fromJson(Map<String, dynamic> json) => Source(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
Could the problem be with my physical device ?
Since you are trying to request this information, check in your manifest if you have enabled access to the internet. Otherwise, it will keep on blocking the requests.

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

How to parse a graphql response in flutter

I am trying to parse my graphql response from my neo4j-graphql backend in my flutter app. I am using the flutter_graphql plugin to make queries to the back end. However, when I try to parse the response(JSON) I am getting 'LinkHashMap is not a subtype of Users Map.'
I tried modifying my serializing classes that will parse the response but to no available .below is the JSON response from neo4j graphql
/*I HAVE EDITED THE JSON RESPONSE. THE FULL JSON RESPONSE FROM THE SERVER IS AS BELOW*/
{
"data": {
"User": [
{
"userId": 1,
"city": "NewYork",
"country": "User",
"captionType": "User",
"state": "New York",
"firstName": "example2",
"lastname": "example",
"email": "example2#gmail.com"
}
]
},
"extensions": {
"type": "READ_ONLY"
}
}
below are the classes that represent the above response
#JsonSerializable()
class User {
final int userId;
final String email ;
final String country ;
final String firstName;
final String gender ;
final String city ;
final String dateOfBirth ;
final String state;
final String captionType;
final String lastname;
User({this.userId,this.email,this.country,this.firstName,this.gender,this.dateOfBirth,this.state,this.captionType,this.city,this.lastname});
factory User.fromJson(Map<String,dynamic> json)=> _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
class Users{
final List<User>users;
Users({this.users});
factory Users.fromJson(Map<String, dynamic> parsedJson){
var list = parsedJson['users'] as List;
List<User> usersList = list.map((i) => User.fromJson(i)).toList();
return Users(
users: usersList
);
}
}
//below is the graphql configuration in my seperate GraphQl.dart file
class GraphQLConfiguration {
static HttpLink httpLink = HttpLink(
uri: "http://localhost:7474/graphql/",
headers: {
HttpHeaders.authorizationHeader: ************",
},
);
static final AuthLink authLink = AuthLink(
getToken: () async => 'Bearer <YOUR_PERSONAL_ACCESS_TOKEN>',
// OR
// getToken: () => 'Bearer <YOUR_PERSONAL_ACCESS_TOKEN>',
);
static ValueNotifier<GraphQLClient> initailizeClient() {
ValueNotifier<GraphQLClient> client = ValueNotifier(
GraphQLClient(
cache: InMemoryCache(),
link: httpLink,
),
);
return client;
}
static GraphQLClient clientToQuery() {
return GraphQLClient(
cache: OptimisticCache(
dataIdFromObject: typenameDataIdFromObject),
link: httpLink,
);
}
}
//below is my main.dart file where am trying to parse the response
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: true,
title: 'Flutter Graphql Client',
theme: ThemeData(
primarySwatch: Colors.blue,
),
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (context) => MyHomePage(), //RootPage(auth: new Auth(),),
},
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Widget listViewWidget(List<Users> users) {
return MediaQuery.removePadding(
context: context, removeTop: true,
child: ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
return Container(
child: Column(
children: <Widget>[
Text('users:$users'),
],
),
);
}),
);
}
String readUser = """
query{
User(userId:1){
userId
city
country
captionType
state
firstName
lastname
email
}
}
""";
#override
Widget build(BuildContext context) {
return GraphQLProvider(
client: GraphQLConfiguration.initailizeClient(),
child: CacheProvider(
child: Scaffold(
appBar: AppBar(
title: Text('Flutter Graphql Client'),
),
body:Query(
options: QueryOptions(
document: readUser),
builder: (QueryResult result, {VoidCallback refetch, FetchMore fetchMore}) {
if (result.errors!= null) {
print('$result.errors');
return Text(result.errors.toString());
} if (result.errors== null){
print(('$result'));
print(('${result.data}'));
} if (result.loading){
return Center(
child: CupertinoActivityIndicator(
radius: 13.0,
));
}
return listViewWidget(result.data);
},
)
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: Icon(Icons.add),
),
),
));
}
}
I am expecting the info to be parsed through the Users class and displayed through the listViewWidget. However I am getting'LinkHashMap is not a subtype of Users Map.'
You can parse any JSON using https://app.quicktype.io/, below is the model class for your JSON
// To parse this JSON data, do
//
// final responseModel = responseModelFromJson(jsonString);
import 'dart:convert';
ResponseModel responseModelFromJson(String str) => ResponseModel.fromJson(json.decode(str));
String responseModelToJson(ResponseModel data) => json.encode(data.toJson());
class ResponseModel {
Data data;
Extensions extensions;
ResponseModel({
this.data,
this.extensions,
});
factory ResponseModel.fromJson(Map<String, dynamic> json) => ResponseModel(
data: json["data"] == null ? null : Data.fromJson(json["data"]),
extensions: json["extensions"] == null ? null : Extensions.fromJson(json["extensions"]),
);
Map<String, dynamic> toJson() => {
"data": data == null ? null : data.toJson(),
"extensions": extensions == null ? null : extensions.toJson(),
};
}
class Data {
List<User> user;
Data({
this.user,
});
factory Data.fromJson(Map<String, dynamic> json) => Data(
user: json["User"] == null ? null : List<User>.from(json["User"].map((x) => User.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"User": user == null ? null : List<dynamic>.from(user.map((x) => x.toJson())),
};
}
class User {
int userId;
String city;
String country;
String captionType;
String state;
String firstName;
String lastname;
String email;
User({
this.userId,
this.city,
this.country,
this.captionType,
this.state,
this.firstName,
this.lastname,
this.email,
});
factory User.fromJson(Map<String, dynamic> json) => User(
userId: json["userId"] == null ? null : json["userId"],
city: json["city"] == null ? null : json["city"],
country: json["country"] == null ? null : json["country"],
captionType: json["captionType"] == null ? null : json["captionType"],
state: json["state"] == null ? null : json["state"],
firstName: json["firstName"] == null ? null : json["firstName"],
lastname: json["lastname"] == null ? null : json["lastname"],
email: json["email"] == null ? null : json["email"],
);
Map<String, dynamic> toJson() => {
"userId": userId == null ? null : userId,
"city": city == null ? null : city,
"country": country == null ? null : country,
"captionType": captionType == null ? null : captionType,
"state": state == null ? null : state,
"firstName": firstName == null ? null : firstName,
"lastname": lastname == null ? null : lastname,
"email": email == null ? null : email,
};
}
class Extensions {
String type;
Extensions({
this.type,
});
factory Extensions.fromJson(Map<String, dynamic> json) => Extensions(
type: json["type"] == null ? null : json["type"],
);
Map<String, dynamic> toJson() => {
"type": type == null ? null : type,
};
}
use this code to parse your response
ResponseModel responseModel = responseModelFromJson(result.data);
return listViewWidget(responseModel.data.user);