Can I display datewise JSON data (ListView) in flutter? - json

I want to display JSON data on the date posted, there is a key value of date in the JSON string, Right Now I am printing the entire posted entries and it is really ugly?
I am currently using a flutter calendar weekly view which also disappears off the screen upon the day clicked. (runtime)
This is my Code where I am calling data
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:flutter_calendar_week/flutter_calendar_week.dart';
class WeeklyData extends StatefulWidget {
_WeeklyDataState createState() => _WeeklyDataState();
}
var dt;
List data = [];
class _WeeklyDataState extends State<WeeklyData> {
void fetchData() async {
final uri = Uri.parse('My URL');
final header = {'Content-Type': 'application/json'};
final response = await http.get(uri, headers: header);
if (response.statusCode == 200) {
setState(() {
data = json.decode(response.body);
});
}
}
#override
void initState() {
super.initState();
fetchData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
SizedBox(
height: 20,
),
CalendarWeek(
controller: CalendarWeekController(),
showMonth: true,
height: 100,
minDate: DateTime.now().add(Duration(days: -365)),
maxDate: DateTime.now().add(Duration(days: 365)),
onDatePressed: (DateTime datetime) {
dt = datetime;
},
),
SizedBox(
height: 20,
),
Text("$data"),
],
),
),
);
}
}
The data gets printed fine on the screen but it's too much I want to filter only the entry according to the day clicked on the calendar
[
{
"url": "http://157.90.55.200:8040/lover/1/",
"uuid": "bf47ddad-9362-4a12-af74-f8ad62883c60",
"raddress": "",
"pubkey": "",
"active": true,
"created": "2021-08-15T17:29:42.797000Z",
"updated": "2021-08-15T17:29:42.798000Z",
"day": 0,
"dslp": 0,
"dnpe": 0,
"cm": "string",
"love": 0,
"pain": "string",
"mood": "string",
"diet": "string",
"eln": "string",
"sreq": "string"
},
{
"url": "http://my url/lover/2/",
"uuid": "25254a18-e9c2-4489-b2f6-ff5174d07ee3",
"raddress": null,
"pubkey": null,
........

check and used grouplist package
GroupedListView<ModelClass, String>(
//physics: ScrollPhysics(),
shrinkWrap: true,
elements: listData,
groupBy: (ModelClass e) => '${e.created.subString(0,9)}',
groupSeparatorBuilder: (String groupByValue) => groupByValue!="null"? Container(
padding: EdgeInsets.only(left:30),
width: double.infinity,
color: Colors.grey.withOpacity(0.5),
child: Text(groupByValue)):Container(),
itemBuilder: (context, element) {
return Center(child: Text(element?.mode ?? ""));
},
order: GroupedListOrder.DESC,
)

Related

how to get complex json data in future builder dart

{
"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

flutter json object to to list for dropdown menu

I got json object from API and i have to show this as a dropdown.
Json response
{
"deliveryCharges": {
"_id": "607b156404fb0a0184db98fe",
"businessId": "607b14ef04fb0a0184db98e3",
"createdAt": "2021-04-17T17:05:40.546Z",
"updatedAt": "2021-04-18T10:16:13.633Z",
"__v": 0,
"deliveryZones": {
"Bangladesh": { // country dropdown item 1
"Mirpur": {. // city dropdown item 1
"deliveryCost": "50",
"status": true
}
},
"American Samoa": { // country dropdown item 2
"lost city": { // city dropdown item 2
"deliveryCost": "50",
"status": true
}
}
}
}
}
Here Bangladesh and American Samoa in country drop down
Here Mirpur and lost city in city drop down
I thing i have to change json object to array. But did not found good example.
Advanced thanks
Since
"deliveryZones": {
"Bangladesh": { // country dropdown item 1
"Mirpur": {. // city dropdown item 1
"deliveryCost": "50",
"status": true
}
},
"American Samoa": { // country dropdown item 2
"lost city": { // city dropdown item 2
"deliveryCost": "50",
"status": true
}
}
}
this object will be stored in Map Data structure
you can convert map keys to list
map.keys.toList()
First, declare two variables of an array.
List<String> countryList = [];
List<String> zoneList = [];
After that parse JSON data which is provided from API response.
Map<String, dynamic> decoded = json.decode(response);
for (var colour in decoded.keys) {
List<String>.from(decoded[colour]['deliveryZones'].keys.map((model) {
countryList.add(model);
}));
List<String>.from(decoded[colour]['deliveryZones']['Bangladesh'].keys.map((model) {
zoneList.add(model);
}));
}
Now print and show the output
print("country $countryList");
print("zoneList $zoneList");
So I have Created a sample Example Based on the json that you provided.
json you provided :
{
"deliveryCharges": {
"_id": "607b156404fb0a0184db98fe",
"businessId": "607b14ef04fb0a0184db98e3",
"createdAt": "2021-04-17T17:05:40.546Z",
"updatedAt": "2021-04-18T10:16:13.633Z",
"__v": 0,
"deliveryZones": {
"Bangladesh": {
"Mirpur": {
"deliveryCost": "50",
"status": true
}
},
"American Samoa": {
"lost city": {
"deliveryCost": "50",
"status": true
}
}
}
}
}
Based on the json I have Made an Example :
import 'package:flutter/material.dart';
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
var _isLoading = false;
String countryValue;
List<String> countriesList = [];
List<String> cityList = [];
String cityValue;
#override
void initState() {
super.initState();
getData();
}
getData() async {
setState(() {
_isLoading = true;
});
String data =
await DefaultAssetBundle.of(context).loadString("json/parse.json");
var item = json.decode(data);
item.forEach((key, value) {
print(value["deliveryZones"]);
value["deliveryZones"].forEach((key, value) {
print(key);
countriesList.add(key);
value.forEach((key, value) {
print(key);
cityList.add(key);
});
});
});
setState(() {
_isLoading = false;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Users List "),
),
body: Container(
width: 300,
child: _isLoading
? CircularProgressIndicator()
: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
DropdownButtonHideUnderline(
child: DropdownButton(
hint: Text(
'Choose Country'), // Not necessary for Option 1
value: countryValue,
onChanged: (newValue) {
setState(() {
countryValue = newValue;
});
print(countryValue);
},
items: countriesList.map((String company) {
return DropdownMenuItem(
child: new Text(company),
value: company,
);
}).toList(),
),
),
DropdownButtonHideUnderline(
child: DropdownButton(
hint: Text('Choose City'), // Not necessary for Option 1
value: cityValue,
onChanged: (newValue) {
setState(() {
cityValue = newValue;
});
print(cityValue);
},
items: cityList.map((String company) {
return DropdownMenuItem(
child: new Text(company),
value: company,
);
}).toList(),
),
),
],
),
),
),
);
}
}
Let me know if it works.

How do I search through data in flutter app

I am new to flutter and I was following a tutorial that shows how to search through data. I cannot recreate that using my own example. I would like to know how to search through data in a ListView from this json data.
{
"success": "true",
"data": [
{
"id": 1,
"name": "football"
},
{
"id": 2,
"name": "rugby"
},
{
"id": 3,
"name": "basketball"
},
{
"id": 4,
"name": "hockey"
},
{
"id": 5,
"name": "tennis"
},
{
"id": 6,
"name": "golf"
}
]
}
Displayed using this code
if (snapshot.hasData) {
return ListView.builder(
itemCount: sports.games.length,
itemBuilder: (context, index) {
if (sports.games.length > 0) {
final x = sports.games[index];
final y = sports.games[index].id.toString();
return ListTile(
title: Text(y),
subtitle: Text(x.name),
);
}
},
);
}
},
First your JSON file will return as a Map, according to this answer at
Unhandled Exception: InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>
for your problem, here is the solution. First you need create a model like this, can be place at separate file or can be place at same file too
class Sports {
int id;
String name;
Sports({
this.id,
this.name,
});
factory Sports.fromJson(Map<String, dynamic> json) {
return Sports(id: json['id'], name: json['name']);
}
}
than here it's the main.dart
import 'package:aberdeen/model.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyApp> {
TextEditingController controller = new TextEditingController();
List<Sports> array = [];
List<Sports> _filtered = [];
List<Sports> _null_filtered = [];
String jsonTest =
'{"success": "true","data": [{"id": 1,"name": "football"},{"id": 2,"name": "rugby"},{"id": 3,"name": "basketball"},{"id": 4,"name": "hockey"},{"id": 5,"name": "tennis"},{"id": 6,"name": "golf"}]}';
void initState() {
super.initState();
test();
}
void _alterfilter(String query) {
List<Sports> dummySearchList = [];
dummySearchList.addAll(_filtered);
if (query.isNotEmpty) {
List<Sports> dummyListData = [];
dummySearchList.forEach((item) {
if (item.name.contains(query)) { //if you want to search it order by id you can change item.name.contains to item.id.contains
dummyListData.add(item);
}
});
setState(() {
_filtered.clear();
_filtered.addAll(dummyListData); //dummyListData will place all the data that match at your search bar
});
return;
} else {
setState(() {
_filtered.clear();
_filtered.addAll(_null_filtered); //_null_filtered will place all the data if search bar was empty after enter a words
});
}
}
Future<Sports> test() async {
Map<String, dynamic> tagObjsJson = json.decode(jsonTest);
List<dynamic> data = tagObjsJson["data"];
setState(() {
for (Map Data in data) {
array.add(Sports.fromJson(Data));
}
_filtered.addAll(array);
_null_filtered.addAll(array);
for (int a = 0; a < _filtered.length; a++) {
print(_filtered[a].name);
}
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Container(
alignment: Alignment.center,
child: Container(
margin: const EdgeInsets.only(top: 50),
width: 300,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
border: Border.all(
width: 1,
color: Color.fromRGBO(11, 189, 180, 1),
style: BorderStyle.solid)),
child: TextField(
decoration: InputDecoration(
hintText: 'Search your data',
contentPadding: EdgeInsets.all(15),
border: InputBorder.none),
controller: controller,
onChanged: (value) {
_alterfilter(value);
},
),
),
),
],
),
Expanded(
child: Container(
margin: const EdgeInsets.all(20),
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: _filtered.length,
itemBuilder: (context, index) {
if (array.length > 0) {
final x = _filtered[index];
final y = _filtered[index].id.toString();
return ListTile(
title: Text(y),
subtitle: Text(x.name),
);
}
},
),
))
],
),
),
));
}
}
Sorry mate if my english was very bad but tell me if you got confused

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