how to load Json to flutter listview - json

I'm new to flutter and I'm developing a flutter app where I have to show in a listView the data on the database.
I get the data in JSON format.
{
"data": [
{
"id": “1”,
"testo": "Fare la spesa",
"stato": "1"
},
{
"id": “2”,
"testo": "Portare fuori il cane",
"stato": "1"
},
{
"id": “3”,
"testo": “jhon”,
"stato": "0"
}
]
}
The problem is that I don't load the data, I can't understand how to do it.
I should read 'Data' with an array but I don't know how to do it.
Can anyone help me figure out how to do it?
Thanks for your help.
PS. I tried this tutorial
Main.dart
Future<Post> fetchPost() async {
final response =
await http.get('http://simone.fabriziolerose.it/index.php/Hello/dispdataflutter');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
class Post {
final int id;
final String title;
final String body;
Post({ this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'],
title: json['testo'],
body: json['stato'],
);
}
}
void main() => runApp(MyApp(post: fetchPost()));
class MyApp extends StatelessWidget {
final Future<Post> post;
MyApp({Key key, this.post}) : super(key: key);
#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<Post>(
future: post,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
),
),
);
}
}

I'd rather return List of Post from fetchPost(), like below :
Future<List<Post>> fetchPost() async {
final response = await http.get('http://simone.fabriziolerose.it/index.php/Hello/dispdataflutter');
if (response.statusCode == 200) {
List responseList = json.decode(response.body);
return responseList.map((data)=>Post.fromJson(data)).toList();
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
and use ListView.builder instead like this
List<Post> post;
child: ListView.builder(
itemCount: post.length,
physics: BouncingScrollPhysics(),
padding: EdgeInsets.all(0),
itemBuilder: (context, index){
return ListAdapter(
id: post[index].id,
title: post[index].title,
body: post[index].body
);
},
)

Related

Fetch data from multiple api but display it in the same future builder

So I have multiple API but I can't display the data in the same future builder. Does anyone know what is going on?
Future<List> fetchData() async {
String url = 'someAPI';
final preferences = await SharedPreferences.getInstance();
final key = 'token';
final value = preferences.get(key);
var response = await http.get(Uri.parse(url), headers: {
'Conten-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $value '
});
log(response.body);
if (response.statusCode == 200) {
return [
// Album.fromJson(jsonDecode(response.body)),
for (final item in jsonDecode(response.body)) Album.fromJson(item),
];
} else {
throw Exception('Failed to load album');
}
}
Future<List> fetchDataDetail(String id) async {
String url2 = 'someAPI2' + id;
final preferences = await SharedPreferences.getInstance();
final key = 'token';
final value = preferences.get(key);
var response2 = await http.get(Uri.parse(url2), headers: {
'Conten-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $value '
});
log(response2.body);
if (response2.statusCode == 200) {
return [
// ReadData.fromJson(jsonDecode(response2.body)),
for (final item in jsonDecode(response2.body)) ReadData.fromJson(item),
// List<Map<String, dynamic>>.from(json.decode(response2.body)[ReadData])
];
} else {
throw Exception('Failed to load album');
}
}`
This is my UI for displaying the data that I fetch
class EmployeeList extends StatefulWidget {
const EmployeeList({Key? key}) : super(key: key);
static String id = 'employee';
#override
State<EmployeeList> createState() => _EmployeeListState();
}
class _EmployeeListState extends State<EmployeeList> {
late Future<List> futureAlbum;
late Future<List> futureReadData;
List<Album>? album;
List<ReadData>? readData;
#override
void initState() {
super.initState();
futureAlbum = fetchData();
futureReadData = fetchDataDetail(toString());
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Daftar Pegawai'),
backgroundColor: Color(0xFFF8B400),
),
body: SafeArea(
child: FutureBuilder<List>(
future: Future.wait([futureAlbum, futureReadData]),
initialData: [],
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return ListView(
children: [
ListView.builder(
shrinkWrap: true,
physics: ScrollPhysics(),
itemCount: snapshot.data!.length,
itemBuilder: (BuildContext context, int index) => ListTile(
onTap: (() {
print('${snapshot.data![index].Personal}');
}),
leading: CircleAvatar(
backgroundColor: Colors.blue,
),
title: Row(
children: [
Expanded(
child: Text('${snapshot.data![index].namaLengkap}'),
),
SizedBox(width: 25),
Expanded(
child: Text('${snapshot.data![index].id}'),
),
],
),
),
),
],
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Center(
child: CircularProgressIndicator(),
);
},
),
),
);
}
}
This is the class from 1st API
class Album {
Album({
required this.id,
required this.namaLengkap,
});
int? id;
String? namaLengkap;
factory Album.fromJson(Map<String, dynamic> json) => Album(
id: json["id"],
namaLengkap: json["nama_lengkap"],
);
Map<String, dynamic> toJson() => {
"id": id,
"nama_lengkap": namaLengkap,
};
}
This is the class from the 2nd API
class ReadData {
ReadData({
required this.personal,
required this.riwayat,
});
Personal personal;
List<Riwayat> riwayat;
factory ReadData.fromJson(Map<String, dynamic> json) => ReadData(
personal: Personal.fromJson(json["personal"]),
riwayat:
List<Riwayat>.from(json["riwayat"].map((x) => Riwayat.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"personal": personal.toJson(),
"riwayat": List<dynamic>.from(riwayat.map((x) => x.toJson())),
};
}
Also, this is the error message
Exception has occurred.
_TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable')
This error appeared in the second API when I tried to return it.

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 rest api get json

I just started using flutter. I have a rest api service that I wrote with nodejs. below is producing the output "result.json". I am trying to access this with flutter.
Connecting to the server.
Getting json data from server.
But I cannot take this into card. can you help me ?
Customers.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:hasta_takip/models/customers_model.dart';
import 'package:http/http.dart' as http;
class Customers extends StatefulWidget {
#override
_CustomersState createState() => _CustomersState();
}
class _CustomersState extends State<Customers> {
Future<List<CustomersModel>> _fetchCustomers() async {
var response = await http.get("http://localhost:3000/customers");
if (response.statusCode == 200) {
return (json.decode(response.body))
.map((e) => CustomersModel.fromJson(e))
.toList();
} else {
throw Exception("not connected ${response.statusCode}");
}
}
#override
void initState() {
super.initState();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Customer list"),
),
body: FutureBuilder(
future: _fetchCustomers(),
builder: (BuildContext context,
AsyncSnapshot<List<CustomersModel>> snapshot) {
print(snapshot.data);
if (snapshot.hasData) {
print(snapshot);
return ListView.builder(
//itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return ListTile();
});
} else {
return Center(child: CircularProgressIndicator());
}
},
),
);
}
}
CustomersModel.dart
import 'dart:convert';
CustomersModel customersModelFromJson(String str) => CustomersModel.fromJson(json.decode(str));
String customersModelToJson(CustomersModel data) => json.encode(data.toJson());
class CustomersModel {
CustomersModel({
this.result,
});
List<Result> result;
factory CustomersModel.fromJson(Map<String, dynamic> json) => CustomersModel(
result: List<Result>.from(json["result"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"result": List<dynamic>.from(result.map((x) => x.toJson())),
};
}
class Result {
Result({
this.id,
this.customerName,
this.customerLastname,
});
int id;
String customerName;
String customerLastname;
factory Result.fromJson(Map<String, dynamic> json) => Result(
id: json["id"],
customerName: json["customer_name"],
customerLastname: json["customer_lastname"],
);
Map<String, dynamic> toJson() => {
"id": id,
"customer_name": customerName,
"customer_lastname": customerLastname,
};
}
Result.json
{
"result": [
{
"id": 1,
"customer_name": "John",
"customer_lastname": "simon"
},
{
"id": 2,
"customer_name": "peter",
"customer_lastname": "bratt"
}
]
}
Change the _fetchCustomer() with below
Future<CustomersModel> _fetchCustomers() async { // this line
var response = await http.get("http://localhost:3000/customers");
if (response.statusCode == 200) {
return customersModelFromJson(response.body); // this line
} else {
throw Exception("not connected ${response.statusCode}");
}
}
And change your FutureBuilder with below
FutureBuilder(
future: _fetchCustomers(),
builder: (BuildContext context,
AsyncSnapshot<CustomersModel> snapshot) { // this line
print(snapshot.data);
if (snapshot.hasData) {
print(snapshot);
return ListView.builder(
itemCount: snapshot.data.result.length, // this line
itemBuilder: (context, index) {
return ListTile();
});
} else {
return Center(child: CircularProgressIndicator());
}
},
)

Fetch complex format data in list with dart language

I'm just trying to fetch data via api in list but getting exception while debugging Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
Here is my demo json_api.
First I created model class for data which I'm getting then decleared variables according to api data.
Then created method to fetch data in the type of list of Model class objects.
then created Widget tree and add StreamBuilder with the list type model class objects, to display data.
CODE:
Model Class:
class Results {
String kind;
List<Item> items;
int totalItems;
Results({
this.kind,
this.items,
this.totalItems,
});
factory Results.fromJson(Map<String, dynamic> json) => new Results(
kind: json["kind"],
items: new List<Item>.from(json["items"].map((x) => Item.fromJson(x))),
totalItems: json["totalItems"],
);
Map<String, dynamic> toJson() => {
"kind": kind,
"items": new List<dynamic>.from(items.map((x) => x.toJson())),
"totalItems": totalItems,
};
}
class Item {
String id;
String kind;
String selfLink;
Item({
this.id,
this.kind,
this.selfLink,
});
factory Item.fromJson(Map<String, dynamic> json) => new Item(
id: json["id"],
kind: json["kind"],
selfLink: json["selfLink"],
);
Map<String, dynamic> toJson() => {
"id": id,
"kind": kind,
"selfLink": selfLink,
};
}
Method for get data in list of Model class objects:
Future<List<Results>> fetchData()async{
List<Results> results = new List<Results>();
final response = await http.get(url);
if(response.statusCode == 200 || json !=null){
List jsonParsed = json.decode(response.body).cast<Map<String, dynamic>>();
for (int i = 0; i < jsonParsed.length; i++) {
results.add(new Results.fromJson(jsonParsed[i]));
}
return results;
}else{
print('Request failed with status: ${response.statusCode}');
Fluttertoast.showToast(msg: "Request failed with status: ${response.statusCode}");
throw Exception('Failed to load post');
}
}
My Widget Tree with StreamBuilder:
body: Center(
child:FutureBuilder<List<Results>>(
future:fetchData(),
builder: (context, snapshot){
if(snapshot.hasData){
return
//Center(child:Text(snapshot.data.items[0].id) ,);
ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, int i){
return Column(
children: <Widget>[
ListTile(
leading: CircleAvatar(
child: Text(snapshot.data[i].items[i].id),
),
title: Text(snapshot.data[i].totalItems.toString()),
subtitle: Text(snapshot.data[i].kind) ,
),
Divider(color: Colors.grey,)
],
);
},
);
}else if(snapshot.hasError){
return Center(child: Text("${snapshot.error}"),);
}else{
return Center(child: CircularProgressIndicator(),);
}
},
),
),
Where Am i doing wrong.
try this,
Future<Results> fetchData() async {
Results results = new Results();
final response = await http
.get('https://www.googleapis.com/books/v1/volumes?q=%7Bhttp%7D');
if (response.statusCode == 200 || json != null) {
Map jsonParsed = json.decode(response.body);
results = Results.fromJson(jsonParsed);
return results;
} else {
print('Request failed with status: ${response.statusCode}');
throw Exception('Failed to load post');
}
}
#override
void initState() {
// TODO: implement initState
super.initState();
fetchData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Tiitle'),
),
body: Center(
child: FutureBuilder<Results>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return
//Center(child:Text(snapshot.data.items[0].id) ,);
ListView.builder(
itemCount: snapshot.data.items.length,
itemBuilder: (context, int i) {
return Column(
children: <Widget>[
ListTile(
leading: CircleAvatar(
child: Text(snapshot.data.totalItems.toString()),
),
title: Text(snapshot.data.items[i].id),
subtitle: Text(snapshot.data.items[i].kind),
),
Divider(
color: Colors.grey,
)
],
);
},
);
} else if (snapshot.hasError) {
return Center(
child: Text("${snapshot.error}"),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
));
}

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