how to get complex json data in future builder dart - json

{
"count": 6,
"next": null,
"previous": null,
"results": [
{
"id": 6,
"title": "Java6",
"description": "Java Basic",
"category": {
"id": 1,
"name": "Math"
},
"sub_category": {
"id": 4,
"name": "Test"
},
"tag": "string",
"video": {
"id": 6,
"duration": 10,
"thumbnail": "https://ibb.co/MZkfS7Q",
"link": "https://youtu.be/RgMeVbPbn-Q",
"views": 0
},
"quiz": {
"mcq": [
{
"id": 6,
"question": "q",
"option1": "b",
"option2": "c",
"option3": "d",
"option4": "e",
"answer": 1,
"appears_at": 0
}
]
},
"avg_rating": 1,
"total_number_of_rating": 1
},]}
how can I show this JSON data in future builder in dart
I have tried this way
Future<dynamic> geteducators() async {
String serviceurl = "https://api.spiro.study/latest-videos";
var response = await http.get(serviceurl);
final jsonrespose = json.decode(response.body);
print('title: ${jsonrespose}');
Videos latestVideo = Videos.fromJson(jsonrespose);
return latestVideo.results;
}
#override
void initState() {
super.initState();
_futureeducators = geteducators();
}

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
final response =
await http.get(Uri.parse('https://dog.ceo/api/breeds/image/random'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class Album {
//final int userId;
final String message;
final String status;
// final String region;
// final String country;
// final String title;
Album({
//required this.userId,
required this.message,
required this.status,
// required this.country,
// required this.region,
//required this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
// userId: json['userId'],
message: json['message'],
status: json['status'],
// country: json['country'],
// region: json['region'],
//title: json['total'],
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
#override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(snapshot.data!.status),
Image(image: NetworkImage(snapshot.data!.message))
],
); //Text(snapshot.data!.ip);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
),
),
);
}
}
//in this way you can get json data and show it in grid or list view.

How to use nested future builder for complex json i mean I'm getting name.from same.json in array and other hand I'm getting values from some json but diffrent aaray and array name is similer to uppe

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.

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.

Parsing complex json flutter

I am trying to parse a complex json file into my application
I am getting an error Exception: type 'String' is not a subtype of type 'int' in type cast. I don't understand where this is happening and how to fix it
Code
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<Character>> fetchCharacters(http.Client client) async {
final response =
await client.get('http://swapi.dev/api/people/');
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parseCharacter, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Character> parseCharacter(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Character>((json) => Character.fromJson(json)).toList();
}
class Character {
final String name;
final int height;
final int mass;
final String hairColor;
final String skinColor;
Character({this.name, this.height, this.mass, this.hairColor, this.skinColor});
factory Character.fromJson(Map<String, dynamic> json) {
return Character(
name: json['name'] as String,
height: json['height'] as int,
mass: json['mass'] as int,
hairColor: json['hair_color'] as String,
skinColor: json['skin_color'] as String,
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final appTitle = 'Isolate Demo';
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: FutureBuilder<List<Character>>(
future: fetchCharacters(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? PhotosList(character: snapshot.data)
: Center(child: CircularProgressIndicator());
},
),
);
}
}
class PhotosList extends StatelessWidget {
final List<Character> character;
PhotosList({Key key, this.character}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: character.length,
itemBuilder: (context, index) {
return Card(
elevation: 5,
margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
child: Container(
padding: EdgeInsets.all(15),
child: ListTile(
title: Text(
character[index].name,
style: TextStyle(fontSize: 18, color: Colors.black),
),
onTap: () {},
),
),
);
},
);
}
}
json file
"count": 82,
"next": "http://swapi.dev/api/people/?page=2",
"previous": null,
"results": [
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "http://swapi.dev/api/planets/1/",
"films": [
"http://swapi.dev/api/films/1/",
"http://swapi.dev/api/films/2/",
"http://swapi.dev/api/films/3/",
"http://swapi.dev/api/films/6/"
],
"species": [],
"vehicles": [
"http://swapi.dev/api/vehicles/14/",
"http://swapi.dev/api/vehicles/30/"
],
"starships": [
"http://swapi.dev/api/starships/12/",
"http://swapi.dev/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "http://swapi.dev/api/people/1/"
}
]
} ```
just remove as int that you added In your Constructor and use parseInt( json['mass'] ) and parseInt( json['height'] )
parseInt() is a function in dart to convert number string in type int to integer number can use in calculations and like that
check this also : https://dev.to/wangonya/how-you-turn-a-string-into-a-number-or-vice-versa-with-dart-392h

returning a widget based on the json result from POST method in flutter

my dashboard.dart look like this
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:abc/utils/connection_config.dart';
import 'package:abc/screens/loginpage.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/cupertino.dart';
class Dash extends StatefulWidget {
#override
DashState createState() => DashState();
}
class DashState extends State<Dash> {
Future reportList;
#override
void initState() {
super.initState();
reportList = getDashboardData();
}
getDashboardData() async {
var fromtime = 1567449000000;
var totime = 1567770486144;
var mtype = "internet";
http.Response response = await http.post(dashboardURL,
headers: {"Content-type": "application/json"},
body: json.encode({
"fromTime": fromtime,
"mtype": mtype,
"must": [
{"msg_status": "0"}
],
"toTime": totime
}));
switch (response.statusCode) {
case 200:
String dashboardResult = response.body;
var collection = json.decode(dashboardResult);
return collection;
break;
case 403:
case 401:
return null;
default:
return 1;
}
}
Widget getContents(BuildContext context, var data) { //here I want to return the widget for each entry in hits array
Widget _widget;
_widget = SingleChildScrollView(
child: SingleChildScrollView(
child: Container(
child: ,
),
),
);
return _widget;
}
//function that iterates over the list
getRefreshScaffold() {
return Center(
child: RaisedButton(
onPressed: () {
setState(() {
reportList = getDashboardData();
});
},
child: Text('Refresh, Network issues.'),
),
);
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: reportList,
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
case ConnectionState.active:
return Center(
child: CircularProgressIndicator(),
);
case ConnectionState.done:
var data = snapshot.data;
if (snapshot.hasData && !snapshot.hasError) {
return Container(
child: getContents(context, snapshot.data),
);
} else if (data == null) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text("Timeout! Log back in to continue"),
Padding(
padding: EdgeInsets.all(25.0),
),
RaisedButton(
onPressed: () {
setState(() {
token = null;
});
Navigator.of(context).pushReplacement(
CupertinoPageRoute(
builder: (BuildContext context) => LoginPage()),
);
},
child: Text('Login Again!'),
),
],
),
);
} else {
getRefreshScaffold();
}
}
},
);
}
}
Here I am hitting an api that gives the json there i need to loop over the following ,
{
..... some other data
"hitsArray": [
{
"tt": 1567566438144,
"status": "0",
"count": 2257056,
"status_count": 2257053
},
{
"tt": 1567566438144,
"status": "1",
"count": 2257056,
"status_count": 3
}
],
...some other data
}
what iam trying to do is to loop over the hitsarray in the json result and to display each entry in a widget.
but i am not getting how to loop over the json data and assign an widget to display it, I tried my best but not able to get it.
paste your json string to https://app.quicktype.io/ and you can get correct parsing logic and you can display with ListView
you can modify delay during to simulate network delay.
await new Future.delayed(new Duration(seconds: 10));
if your json string look like this
[
{
"tt": 1567566438144,
"status": "0",
"count": 2257056,
"status_count": 2257053
}
,
{
"tt": 1567566438144,
"status": "1",
"count": 2257056,
"status_count": 3
}
]
logic from quicktype
// To parse this JSON data, do
//
// final hitsArray = hitsArrayFromJson(jsonString);
import 'dart:convert';
List<HitsArray> hitsArrayFromJson(String str) => List<HitsArray>.from(json.decode(str).map((x) => HitsArray.fromJson(x)));
String hitsArrayToJson(List<HitsArray> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class HitsArray {
int tt;
String status;
int count;
int statusCount;
HitsArray({
this.tt,
this.status,
this.count,
this.statusCount,
});
factory HitsArray.fromJson(Map<String, dynamic> json) => HitsArray(
tt: json["tt"],
status: json["status"],
count: json["count"],
statusCount: json["status_count"],
);
Map<String, dynamic> toJson() => {
"tt": tt,
"status": status,
"count": count,
"status_count": statusCount,
};
}
demo full code display with FutureBuilder and ListView
import 'dart:async';
import 'package:flutter/material.dart';
// To parse this JSON data, do
//
// final hitsArray = hitsArrayFromJson(jsonString);
import 'dart:convert';
List<HitsArray> hitsArrayFromJson(String str) => List<HitsArray>.from(json.decode(str).map((x) => HitsArray.fromJson(x)));
String hitsArrayToJson(List<HitsArray> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class HitsArray {
int tt;
String status;
int count;
int statusCount;
HitsArray({
this.tt,
this.status,
this.count,
this.statusCount,
});
factory HitsArray.fromJson(Map<String, dynamic> json) => HitsArray(
tt: json["tt"],
status: json["status"],
count: json["count"],
statusCount: json["status_count"],
);
Map<String, dynamic> toJson() => {
"tt": tt,
"status": status,
"count": count,
"status_count": statusCount,
};
}
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
var futureBuilder = new FutureBuilder(
future: _getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return new Text('loading...');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return createListView(context, snapshot);
}
},
);
return new Scaffold(
appBar: new AppBar(
title: new Text("Home Page"),
),
body: futureBuilder,
);
}
Future<List<HitsArray>> _getData() async {
String jsonString = ' [ { "tt": 1567566438144, "status": "0", "count": 2257056, "status_count": 2257053 } , { "tt": 1567566438144, "status": "1", "count": 2257056, "status_count": 3 } ]';
var values = hitsArrayFromJson(jsonString);
//throw new Exception("Danger Will Robinson!!!");
await new Future.delayed(new Duration(seconds: 1));
return values;
}
Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
List<HitsArray> values = snapshot.data;
return new ListView.builder(
itemCount: values.length,
itemBuilder: (BuildContext context, int index) {
return new Column(
children: <Widget>[
new ListTile(
title: new Text(' count ${values[index].count.toString()}'),
subtitle: new Text('status count ${values[index].statusCount.toString()}'),
),
new Divider(height: 2.0,),
],
);
},
);
}
}