Stuck with json in flutter - json

I dont know the problem is because when debuging there isn't error info but the value of json is empty when I print info.lenght
class _HomePageState extends State<HomePage> {
List info = [];
_initData(){
DefaultAssetBundle.of(context).loadString("json/info.json").then((value){
info = jsonDecode(value);
});
}
#override
void iniState(){
super.initState();
_initData();
}
and below is my json code in json/info.json
[
{
"title": "Glue",
"img": "assets/ex1.png"
},
{
"title": "Abs",
"img": "assets/ex2.png"
},
{
"title": "Legs",
"img": "assets/ex3.png"
},
{
"title": "Arms",
"img": "assets/ex4.png"
}
]
and how to we print the img and title value of json in dart?

You have to first create a model class for your json response.
// To parse this JSON data, do
//
// final jsonModel = jsonModelFromJson(jsonString);
import 'dart:convert';
List<JsonModel> jsonModelFromJson(String str) => List<JsonModel>.from(json.decode(str).map((x) => JsonModel.fromJson(x)));
String jsonModelToJson(List<JsonModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class JsonModel {
JsonModel({
this.title,
this.img,
});
String title;
String img;
factory JsonModel.fromJson(Map<String, dynamic> json) => JsonModel(
title: json["title"] == null ? null : json["title"],
img: json["img"] == null ? null : json["img"],
);
Map<String, dynamic> toJson() => {
"title": title == null ? null : title,
"img": img == null ? null : img,
};
}
then just use this model class to decode your json file.
var result = JsonModel.fromJson(jsonResponse);
Later, you can just use
result.title or result.img to get the data

You have to add your json file into pubspec.yaml file.
flutter:
assets:
- json/info.json
Before loading page view, you should load values from your json file and assign a list in initState. After that, you can use list as map by [index][header].
class JsonResult extends StatefulWidget {
const JsonResult({Key? key}) : super(key: key);
#override
_JsonResultState createState() => _JsonResultState();
}
class _JsonResultState extends State<JsonResult> {
var jsonList = [];
#override
void initState() {
rootBundle.loadString("json/info.json").then((value) {
jsonList = json.decode(value);
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ListView.builder(
itemBuilder: (context, index) {
return ListTile(
leading: Image.asset(jsonList[index]["img"]),
title: Text(jsonList[index]["title"]),
);
},
itemCount: jsonList.length,
),
),
);
}
}

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

How to pick and show particular values from json with dart (flutter)?

I am an absolute beginner and would appreciate your help very much.
My json is as follows:
[
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.humidity",
"val": 73,
"ts": 1661671736783,
"ack": true
},
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.temperature",
"val": 16.8,
"ts": 1661671736782,
"ack": true
},
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.weatherCondition",
"val": "CLEAR",
"ts": 1661671736783,
"ack": true
},
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.weatherDayTime",
"val": "DAY",
"ts": 1661671736783,
"ack": true
},
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.windDirection",
"val": 10,
"ts": 1661671736784,
"ack": true
},
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.windSpeed",
"val": 18.503999999999998,
"ts": 1661671736784,
"ack": true
}
]
When I want to pick and show a particular value, e.g. for humidity, I get the following error:
type 'String' is not a subtype of 'int' of 'index'
My dart-code is as follows:
class EinzelwerteList {
final List<Wetter> einzelwerte;
EinzelwerteList({
required this.einzelwerte,
});
factory EinzelwerteList.fromJson(List<dynamic> parsedJson) {
List<Wetter> einzelwerte = <Wetter>[];
einzelwerte = parsedJson.map((i) => Wetter.fromJson(i)).toList();
return new EinzelwerteList(einzelwerte: einzelwerte);
}
}
class Wetter {
final String id;
final Int val;
final Int ts;
final Bool ack;
Wetter({
required this.id,
required this.val,
required this.ts,
required this.ack,
});
factory Wetter.fromJson(Map<String, dynamic> json) {
return Wetter(
id: json['id'].toString(),
val: json['val'],
ts: json['ts'],
ack: json['ack']);
}
}
Future<Wetter> fetchWetter() async {
final response = await http.get(Uri.parse(
'http://192.168.178.37:8087/getBulk/hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.humidity,hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.temperature,hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.weatherCondition,hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.weatherDayTime,hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.windDirection,hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.windSpeed'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
var dataDecoded = jsonDecode(response.body);
var humidity = dataDecoded['einzelwerte'][0]['val'].toString();
debugPrint(humidity);
return Wetter.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load Wetter');
}
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Wetter> futureWetter;
#override
void initState() {
super.initState();
futureWetter = fetchWetter();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.green,
//scaffoldBackgroundColor:
),
home: Scaffold(
appBar: AppBar(
title: const Text('Micha lernt Flutter & Dart'),
),
body: Center(
child: FutureBuilder<Wetter>(
future: futureWetter,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.val.toString());
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return Container();
},
),
),
),
);
}
}
What do I do wrong?
As I said I am a total newbie and try to learn. So please be patient even if I ask dumb question.
Best regards.
There are multiple problems but the specific problem you are getting right now is the following piece of code:
var dataDecoded = jsonDecode(response.body);
var humidity = dataDecoded['einzelwerte'][0]['val'].toString();
The JSON does not contain a Map as the first level but instead a List. So you are getting an error since a List expects an int inside the [] while you are providing a String.
Another problem, you are going to have later, is that you are using the wrong types in your Wetter class. The types Int and Bool comes from dart:ffi and is meant to be used if you are integrating with native C code.
You should instead use int and bool.
A third problem is that val in your JSON contains a mix of types. So in your example you can see it is sometimes double and other times int and sometime String... the mix of int and double can be solved by use the num type but you need to add some custom handling for the String.

How to implement listview from nested json data using http request in flutter?

I am new in flutter. i want to using http request for nested json data and want to show that data in listview. i made http request for get data. and i got 200. but problem is how to return my response for nested json data and show these data to listview? i read many documents but not properly understood. can anyone teach me how to implement this and if i made any wrong, what kind of wrong?
from json i also want to show "count", "idEmployee", "fullname" in my listview.
N.B: this api and token is just for test purpose.
Nested Json Data
{
"success": true,
"data": {
"count": 261,
"data": [
{
"idEmployee": 3588,
"avatar": null,
"fullName": "Moodle Connection Test",
"officeID": "1003588",
"email": "",
"designation": "Senior Executive",
"department": "Accounts",
"mobileNumber": "",
"workStation": "Work Station 12",
"businessUnit": "CDA"
}
],
}
}
ListAlbum Model Class
class ListAlbum {
final int? idEmployee;
final String? avatar;
final String? fullName;
final String? officeID;
final String? email;
final String? designation;
final String? department;
final String? mobileNumber;
final String? workStation;
final String? businessUnit;
ListAlbum({
this.idEmployee,
this.avatar,
this.fullName,
this.officeID,
this.email,
this.designation,
this.department,
this.mobileNumber,
this.workStation,
this.businessUnit,
});
factory ListAlbum.fromJson(Map<String, dynamic> json) {
return ListAlbum(
idEmployee: json['idEmployee'],
avatar: json['avatar'],
fullName: json['fullName'],
officeID: json['officeID'],
email: json['email'],
designation: json['designation'],
department: json['department'],
mobileNumber: json['mobileNumber'],
workStation: json['workStation'],
businessUnit: json['businessUnit'],
);
}
}
Api Calling
Future<List<ListAlbum>> listData() async {
final response = await http.post(
Uri.parse('https://portal-api.jomakhata.com/api/getOrganizationData'),
headers: {
'Content-Type': 'application/json',
'Accept': '*/*',
'Authorization':
'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjMxNDYyNTE3LCJleHAiOjE2MzE1NDg5MTcsIm5iZiI6MTYzMTQ2MjUxNywianRpIjoiY2tXUVAya3RsdEJvTHd4QyJ9.9wkcg2n6XgWC1lAj2ZAwHJFMZIVbtg7cmo_jUN86rBo',
},
body: jsonEncode(<String, String>{
'limit': 5.toString(),
'orderBy': 'idEmployee',
'orderType': 'DESC'
}),
);
if (response.statusCode == 200) {
print(response.statusCode);
print("ok");
print(response.body);
return // here how to return for nested json data?
} else {
throw Exception('Failed to create album.');
}
}
List View
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
late Future<List<ListAlbum>> futureAlbum;
#override
void initState() {
super.initState();
futureAlbum = listData();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Create Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: Center(
child: FutureBuilder<List<ListAlbum>>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
print(snapshot.data);
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
final ListAlbum item = snapshot.data![index];
return ListTile(
title: Text(item.fullName!),
subtitle: Text(item.designation!),
);
},
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
),
),
);
}
}
Ok, first of all, I sure hope this line :
Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjMxNDYyNTE3LCJleHAiOjE2MzE1NDg5MTcsIm5iZiI6MTYzMTQ2MjUxNywianRpIjoiY2tXUVAya3RsdEJvTHd4QyJ9.9wkcg2n6XgWC1lAj2ZAwHJFMZIVbtg7cmo_jUN86rBo
Is not actually your authentication credentials because it would take very little effort to decode that, and it would compromise your entire application.
Now, regarding your question, I might be wrong, but if I recall correctly, the http package will return a JSON response as a String, so first things first convert it to json using:
Map<String, dynamic> json = jsonDecode(response.data);
Then you can use a map method to return the models:
return json['data']['data'].map<ListAlbum>((value) => ListAlbum.fromJson(value));
Haven't tested it, but I believe that should work.

Flutter, how to get data array of object and show to ListView.builder?

im new in flutter and i want to get my data from localhost phpmydmin.
here is my json:
{
"status": true,
"message": "Data ditemukan",
"data": [
{
"id": "1",
"username": "admin",
"password": "d033e22ae348aeb5660fc2140aec35850c4da997",
"nama": "admin",
"token": "2a5c97cb31308b8d818da33a041fa47d"
},
{
"id": "3",
"username": "sani",
"password": "86862f0600c8b9829d9ca9c8aaca3f0727b44b6e",
"nama": "Sani Sandhika",
"token": "661e23835d27f9d45cf371f59533f163"
},
{
"id": "4",
"username": "seno",
"password": "d61a4fe61485d6437b698c11635d8fb8c5b79d2f",
"nama": "Seno",
"token": "7b9f0f54ca01c323bc810206adcaa38c"
},
{
"id": "5",
"username": "username",
"password": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8",
"nama": "nama",
"token": null
}
]
}
and here is my UserModel:
import 'dart:convert';
List<User> allUsers(String str) {
final jsonData = json.decode(str);
return new List<User>.from(jsonData.map((x) => User.fromJson(x)));
}
class User {
bool status;
String message;
List<Data> data;
User({
this.status,
this.message,
this.data,
});
factory User.fromJson(Map<String, dynamic> parsedJson) {
var list = parsedJson['data'] as List;
print(list.runtimeType);
List<Data> dataList = list.map((i) => Data.fromJson(i)).toList();
return User(
status: parsedJson['status'],
message: parsedJson['message'],
data: dataList,
);
}
}
class Data {
final int id;
final String nama;
final String username;
Data({
this.id,
this.nama,
this.username,
});
factory Data.fromJson(Map<String, dynamic> parsedJson) {
return Data(
id: parsedJson['id'],
nama: parsedJson['nama'],
username: parsedJson['username'],
);
}
}
this is my RestApi:
import 'package:flutter_rest_api_crud/models/models.dart';
import 'package:http/http.dart' as http;
class RestApi {
String url = 'http://192.168.1.5/gizi/user/';
Future<List<User>> getUsers() async {
final response = await http.get('$url/user');
print(response.body);
return allUsers(response.body);
}
}
and last here is my HomeScreen:
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
HomeScreen({Key key}) : super(key: key);
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
);
}
}
And i want to get my data inside "data" from localhost phpmyadmin. and put it on ListView.builder. and i don't know what the next step to implement the listview to my homescreen.
anyone can help me ?
You can hit the API endpoint after initializing the Widget:
List<User> _users = [];
#override
void initState() {
super.initState();
_load();
}
void _load() async {
List<User> users =
await RestApi.getUsers(); // load the users on Widget init
setState(() => _users = users);
}
Then display a nested ListView to display each User's Data:
return Scaffold(
appBar: AppBar(),
body: new ListView.builder(
itemCount: _users.length,
itemBuilder: (BuildContext ctxt, int i) {
return new Card(
child: Column(
children: [
Text(_users[i].username),
ListView.builder(
itemCount: _users[i].data.length,
itemBuilder: (BuildContext ctx, int j) {
return Text(_users[i]
.data[j]
.username); // display username as an example
},
),
],
),
);
},
),
);
Follows a full example:
class _HomeScreenState extends State<HomeScreen> {
List<User> _users = [];
#override
void initState() {
super.initState();
_load();
}
void _load() async {
List<User> users =
await RestApi.getUsers(); // load the users on Widget init
setState(() => _users = users);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: new ListView.builder(
itemCount: _users.length,
itemBuilder: (BuildContext ctxt, int i) {
return new Card(
child: Column(
children: [
Text(_users[i].username),
ListView.builder(
itemCount: _users[i].data.length,
itemBuilder: (BuildContext ctx, int j) {
return Text(_users[i]
.data[j]
.username); // display username as an example
},
),
],
),
);
},
),
);
}
}
As your app gets more complicated, I'd suggest checking out different State Management strategies, such as BLoC.

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