Related
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
I'm try ti create a list from a json but it throws me the error: "List is not subtype of type Map<string, dynamic>".
The first part of code is where I am trying to create the list bwhich is in a widget that is called to the main widget.On the second block of code is where I do the fetch and recives an endpoint and then returns the response back and the last one is the structure of the json.
import 'package:flutter/material.dart';
import 'package:eshop/models/products.dart';
import 'package:eshop/function/fetch.dart';
const endPoint = 'https://sistemas.cruzperez.com/flutter/jsonPrueba.json';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Future<Product> futureProduct;
#override
void initState() {
super.initState();
futureProduct = getData(endPoint);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar:AppBar(
title: Text('Eshop'),
automaticallyImplyLeading: false,
actions: <Widget>[
IconButton(icon: Icon(Icons.shopping_cart, color: Colors.white), onPressed: (){})
],
),
body: Center(
child: Container(
child: Column(
children: <Widget>[
listJson(futureProduct)
],
),
)
),
);
}
}
Widget listJson(futureProduct){
return Container(
child: FutureBuilder<Product>(
future: futureProduct,
builder: (context, snapshot){
if(snapshot.hasData){
return Text(snapshot.data.nombre);
}else if(snapshot.hasError){
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
),
);
}
import 'dart:async';
import 'package:http/http.dart' as http;
import 'package:eshop/models/products.dart';
Future<Product> getData(endPoint) async{
final response = await http.get(endPoint);
if (response.statusCode == 200) {
return Product.fromJson(json.decode(response.body));
}else{
throw Exception('Error a cargar json');
}
}
class Product{
final int idSucursal;
final int idProducto;
final String nombre;
final String categoria;
final int precio;
final int disponible;
final String descripcion;
final String imgUrl;
Product({
this.idSucursal,
this.idProducto,
this.nombre,
this.categoria,
this.precio,
this.disponible,
this.descripcion,
this.imgUrl
});
factory Product.fromJson(Map<String, dynamic> json){
return Product(
idSucursal: json['id_sucursal'],
idProducto: json['id_producto'],
nombre: json['nombre'],
categoria: json['categoria'],
precio: json['precio'],
disponible: json['disponible'],
descripcion: json['descripcion'],
imgUrl: json['img_url'],
);
}
}
You can copy paste run full code below
Step 1: You need to use List<Product> and parse with productFromJson
List<Product> productFromJson(String str) =>
List<Product>.from(json.decode(str).map((x) => Product.fromJson(x)));
Step 2: You can display data with ListView
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Card(
elevation: 6.0,
child: Padding(
padding: const EdgeInsets.only(
top: 6.0, bottom: 6.0, left: 8.0, right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(snapshot.data[index].nombre.toString()),
],
),
));
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
List<Product> productFromJson(String str) =>
List<Product>.from(json.decode(str).map((x) => Product.fromJson(x)));
String productToJson(List<Product> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Product {
Product({
this.idSucrsal,
this.idProducto,
this.nombre,
this.categoria,
this.precio,
this.disponible,
this.descripcion,
this.imgUrl,
});
int idSucrsal;
int idProducto;
String nombre;
Categoria categoria;
int precio;
int disponible;
String descripcion;
String imgUrl;
factory Product.fromJson(Map<String, dynamic> json) => Product(
idSucrsal: json["id_sucrsal"],
idProducto: json["id_producto"],
nombre: json["nombre"],
categoria: categoriaValues.map[json["categoria"]],
precio: json["precio"],
disponible: json["disponible"],
descripcion: json["descripcion"],
imgUrl: json["img_url"],
);
Map<String, dynamic> toJson() => {
"id_sucrsal": idSucrsal,
"id_producto": idProducto,
"nombre": nombre,
"categoria": categoriaValues.reverse[categoria],
"precio": precio,
"disponible": disponible,
"descripcion": descripcion,
"img_url": imgUrl,
};
}
enum Categoria { RES, CERDO, EMBUTIDO }
final categoriaValues = EnumValues({
"cerdo": Categoria.CERDO,
"embutido": Categoria.EMBUTIDO,
"res": Categoria.RES
});
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
const endPoint = 'https://sistemas.cruzperez.com/flutter/jsonPrueba.json';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Future<List<Product>> futureProduct;
Future<List<Product>> getData(endPoint) async {
final response = await http.get(endPoint);
if (response.statusCode == 200) {
return productFromJson(response.body);
} else {
throw Exception('Error a cargar json');
}
}
#override
void initState() {
super.initState();
futureProduct = getData(endPoint);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Eshop'),
automaticallyImplyLeading: false,
actions: <Widget>[
IconButton(
icon: Icon(Icons.shopping_cart, color: Colors.white),
onPressed: () {})
],
),
body: Center(
child: Container(
child: Column(
children: <Widget>[Expanded(child: listJson(futureProduct))],
),
)),
);
}
}
Widget listJson(futureProduct) {
return Container(
child: FutureBuilder<List<Product>>(
future: futureProduct,
builder: (context, AsyncSnapshot<List<Product>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Card(
elevation: 6.0,
child: Padding(
padding: const EdgeInsets.only(
top: 6.0, bottom: 6.0, left: 8.0, right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(snapshot.data[index].nombre.toString()),
],
),
));
});
}
}
},
),
);
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(),
);
}
}
I have JSON data file that looks like this, as you can see the email is a list itself:
[
{
"index": 0,
"about": "text text text",
"email": [
"kjdkffsk#skfjsd.com",
"kjdkffsk#skfjsd.com",
],
"name": "sample name",
"picture": "https://kdjfksfjsdklfs.com"
},
{
"index": 1,
"about": "text text text",
"email": [
"kjdkffsk#skfjsd.com",
"kjdkffsk#skfjsd.com",
],
"name": "sample name ",
"picture": "https://kdjfksfjsdklfs.com"
},
{
"index": 2,
"about": "text text text",
"email": [
"kjdkffsk#skfjsd.com",
"kjdkffsk#skfjsd.com",
],
"name": "sample name",
"picture": "https://kdjfksfjsdklfs.com"
}
]
My code is the following, which is basically a listview builder that gets data from the above JSON. Now when the list is clicked it navigate to the next page where I need to show details of this user.
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
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(title: 'Users'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
Future _data;
class _MyHomePageState extends State<MyHomePage> {
Future<List<User>> _getUsers() async {
var data =
await DefaultAssetBundle.of(context).loadString("assets/test.json");
var jsonData = json.decode(data);
List<User> users = [];
for (var u in jsonData) {
User user =
User(u["index"], u["about"], u["name"], u["email"], u["picture"]);
users.add(user);
}
print(users.length);
return users;
}
#override
void initState() {
super.initState();
_data = _getUsers();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Container(
child: FutureBuilder(
future: _data,
builder: (BuildContext context, AsyncSnapshot snapshot) {
print(snapshot.data);
if (snapshot.data == null) {
return Container(child: Center(child: Text("Loading...")));
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: CircleAvatar(
backgroundImage:
NetworkImage(snapshot.data[index].picture),
),
title: Text(snapshot.data[index].name),
// subtitle: Text(snapshot.data[index].email),
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) =>
DetailPage(snapshot.data[index])));
},
);
},
);
}
},
),
),
);
}
}
class DetailPage extends StatelessWidget {
final User user;
DetailPage(this.user);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(user.name),
),
body: Container(
child: Text(user.about),
),
);
}
}
class User {
final int index;
final String about;
final String name;
final String email;
final String picture;
User(this.index, this.about, this.name, this.email, this.picture);
}
I wanted to create Listview Builder in the second page for name and the email so that all the emails listed under the name.
can someone help I am not able to generate the second page list especially the email list.
Just check out this example and let me know if it works for you:
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:json_parsing_example/models.dart';
// To parse this JSON data, do
//
// final user = userFromJson(jsonString);
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(title: 'Users'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
Future _data;
class _MyHomePageState extends State<MyHomePage> {
Future<List<User>> _getUsers() async {
var data =
await DefaultAssetBundle.of(context).loadString("json/parse.json");
return userFromJson(data);
}
#override
void initState() {
super.initState();
_data = _getUsers();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Container(
child: FutureBuilder<List<User>>(
future: _data,
builder: (BuildContext context, AsyncSnapshot snapshot) {
print(snapshot.data);
if (snapshot.data == null) {
return Container(child: Center(child: Text("Loading...")));
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: CircleAvatar(
backgroundImage:
NetworkImage(snapshot.data[index].picture),
),
title: Text(snapshot.data[index].name),
// subtitle: Text(snapshot.data[index].email),
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) =>
DetailPage(snapshot.data[index])));
},
);
},
);
}
},
),
),
);
}
}
class DetailPage extends StatefulWidget {
final User user;
DetailPage(this.user);
#override
_DetailPageState createState() => _DetailPageState();
}
class _DetailPageState extends State<DetailPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.user.name),
),
body: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
widget.user.name,
style: TextStyle(fontSize: 20),
),
),
ListView.builder(
shrinkWrap: true,
itemCount: widget.user.email.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(widget.user.email[index]),
));
},
),
],
),
),
);
}
}
Your model class :
// To parse this JSON data, do
//
// final user = userFromJson(jsonString);
import 'dart:convert';
List<User> userFromJson(String str) => List<User>.from(json.decode(str).map((x) => User.fromJson(x)));
String userToJson(List<User> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class User {
User({
this.index,
this.about,
this.email,
this.name,
this.picture,
});
int index;
String about;
List<String> email;
String name;
String picture;
factory User.fromJson(Map<String, dynamic> json) => User(
index: json["index"],
about: json["about"],
email: List<String>.from(json["email"].map((x) => x)),
name: json["name"],
picture: json["picture"],
);
Map<String, dynamic> toJson() => {
"index": index,
"about": about,
"email": List<dynamic>.from(email.map((x) => x)),
"name": name,
"picture": picture,
};
}
First of all:
You can use either
moor/moor_flutter moor flutter_moor
OR
built_value built_value
To map the json String and generate fromJson/toJson functions.
Example using moor:
First, create a moor database (if you have any question I am glad to answer).
Second, this would be the class you should use.
import 'dart:convert';
import 'package:db/moordb/database.dart';
import 'package:json_annotation/json_annotation.dart' as json;
import 'package:moor/moor.dart';
part 'user.g.dart';
#DataClassName("User")
class Users extends Table {
IntColumn get id => integer().nullable().autoIncrement()();
#JsonKey("index")
IntColumn get index => text().nullable()();
#JsonKey("about")
TextColumn get about => text().nullable()();
#JsonKey("email")
TextColumn get emails => text().map(const EmailConverter()).nullable()();
#JsonKey("name")
TextColumn get name => text().nullable()();
#JsonKey("picture")
TextColumn get picture => text().nullable()();
#override
Set<Column> get primaryKey => {id};
}
class EmailConverter extends TypeConverter<List<String>, String> {
const EmailConverter ();
#override
List<String> mapToDart(String fromDb) {
if (fromDb == null) {
return null;
}
List _emails = List<String>();
(jsonDecode(fromDb)).forEach((value) {
_emails.add(value);
});
return _emails;
}
#override
String mapToSql(List<dynamic> value) {
if (value == null) {
return null;
}
return jsonEncode(value);
}
}
Second:
It is preferred that you send the User object through:
Navigator arguments Navigation
or
An Inherited Widget Inherited Widget
In your case you are passing the object to the widget directly.
In conclusion, it is obvious that the String field email in your User object is not being populated by the decoded data which contains the emails in a List. (since you are using the Class User).
Note: lose the new keyword since it is no longer required in Dart 2
Below is my full code, the only thing you need to do to run it is adding "http: any" to dependencies in pubspec.yaml.
What the code does is grab JSON input from source, and for each entry in the json feed create a card. Now for each question, I want the user to provide an answer, so when I add the button to the bottom, it brings up a popup box showing the answers (which I'll later post back to my server).
It would look something like:
Q1: "three"
Q2: "thirty"
Q3: "Some movie character"
Q4: "Walter White"
(I'll do the validation to my answers later)
My json is posted below the 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<Question>> fetchQuestions(http.Client client) async {
final response =
await client.get('https://jsonblob.com/api/jsonBlob/a5885973-7f02-11ea-b97d-097037d3b153');
// Use the compute function to run parsePhotos in a separate isolate
return compute(parseQuestion, response.body);
}
// A function that will convert a response body into a List<Photo>
List<Question> parseQuestion(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Question>((json) => Question.fromJson(json)).toList();
}
class Question {
final int id;
final String question;
final String answer;
Question({this.id, this.question, this.answer});
factory Question.fromJson(Map<String, dynamic> json) {
return Question(
id: json['id'] as int,
question: json['question'] as String,
answer: json['answer'] 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: Padding(
child: FutureBuilder<List<Question>>(
future: fetchQuestions(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? QuestionList(questions: snapshot.data)
: Center(child: CircularProgressIndicator());
},
),
padding: EdgeInsets.fromLTRB(1.0, 10.0, 1.0, 10.0),
),
);
}
}
class QuestionList extends StatelessWidget {
final List<Question> questions;
QuestionList({Key key, this.questions}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: questions.length,
itemBuilder: (context, index) {
return Column(
children: <Widget>[
Container(
constraints: BoxConstraints.expand(
height: Theme.of(context).textTheme.display1.fontSize * 1.1 +
200.0,
),
color: Colors.blueGrey,
alignment: Alignment.center,
child: Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
title: Text(questions[index].id.toString()),
subtitle: Text(questions[index].question),
),
new TextFormField(
decoration: new InputDecoration(
labelText: "Answer Question",
fillColor: Colors.white,
border: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(25.0),
borderSide: new BorderSide(
),
),
),
validator: (val) {
if(val.length==0) {
return "Type your answer here";
}else{
return null;
}
},
keyboardType: TextInputType.text,
style: new TextStyle(
fontFamily: "Poppins",
),
),
/*
// make buttons use the appropriate styles for cards
ButtonBar(
children: <Widget>[
RaisedButton(
color: Colors.lightBlue,
hoverColor: Colors.blue,
child: const Text('Open'),
onPressed: () {/* ... */},
),
],
),
*/
],
),
)),
],
);
},
);
}
}
[
{
"id" : 1,
"question" : "what is one plus two",
"answer": "three"
},
{
"id" : 2,
"question" : "what is five times 6",
"answer": "thirty"
},
{
"id" : 3,
"question" : "Who said show me the money",
"answer": "Cuba Gooding Jnr"
},
{
"id" : 4,
"question" : "who said I am the danger",
"answer": "Walter White"
}
]
Consider attaching a TextEditingController to the TextFormField through the controller property. You can access the text currently in the TextField using the controller's text field.
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,),
],
);
},
);
}
}