flutter rest api get json - 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());
}
},
)

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

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.

Flutter Nested array?

I have these JSON data
[
{
"student_id": 1,
"studentid": 1204,
"password": "demo",
"name": "Amber",
"level": "student",
"course_name": [
"Math",
"History"
]
}
]
Kindly show me the code to to achieve this :
Actually you have a JSON array (only one index), should be something like:
myArray[0].course_name.forEach(course => console.log(course));
data[index].courseName[0]
https://app.quicktype.io/ for right "model"
model.dart
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
List<Welcome> welcomeFromJson(String str) => List<Welcome>.from(json.decode(str).map((x) => Welcome.fromJson(x)));
String welcomeToJson(List<Welcome> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Welcome {
int studentId;
int studentid;
String password;
String name;
String level;
List<String> courseName;
Welcome({
this.studentId,
this.studentid,
this.password,
this.name,
this.level,
this.courseName,
});
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
studentId: json["student_id"] == null ? null : json["student_id"],
studentid: json["studentid"] == null ? null : json["studentid"],
password: json["password"] == null ? null : json["password"],
name: json["name"] == null ? null : json["name"],
level: json["level"] == null ? null : json["level"],
courseName: json["course_name"] == null ? null : List<String>.from(json["course_name"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"student_id": studentId == null ? null : studentId,
"studentid": studentid == null ? null : studentid,
"password": password == null ? null : password,
"name": name == null ? null : name,
"level": level == null ? null : level,
"course_name": courseName == null ? null : List<dynamic>.from(courseName.map((x) => x)),
};
}
main.dart
var jsonString = [
{
"student_id": 1,
"studentid": 1204,
"password": "demo",
"name": "Amber",
"level": "student",
"course_name": ["Math", "History"]
}
];
List<Welcome> hui = welcomeFromJson(json.encode(jsonString));
print(hui[0].courseName[0]);
Try this now
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(new MaterialApp(
home: new HomePage(),
));
}
class HomePage extends StatefulWidget {
#override
HomePageState createState() => new HomePageState();
}
class HomePageState extends State<HomePage> {
List data;
bool isLoading = false;
Future<String> getData({isShowLoading: true}) async {
// refreshKey.currentState?.show(atTop: false);
//await Future.delayed(Duration(seconds: 2));
if (isShowLoading) {
setState(() {
isLoading = true;
});
}
var response = await http.get(
Uri.encodeFull("https://ikns.info/api/nested-array.php"),
headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
if (isShowLoading) {
setState(() {
isLoading = false;
});
}
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
if (mounted) {
setState(() {
data = jsonDecode(response.body);
});
}
return "Success!";
}
var refreshKey = GlobalKey<RefreshIndicatorState>();
#override
void initState() {
super.initState();
this.getData();
}
Future<Null> _onRefresh() async {
await getData(isShowLoading: false);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Parsing List of Strings"),
),
body: isLoading
? Center(
child: Text('Loading...'),
)
: RefreshIndicator(
key: refreshKey,
child: new ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
List<dynamic> items = data[index]["course_name"];
return GestureDetector(
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => DetailsPage(
todo: Todo.fromJson(data[index]),
),
),
);
},
child: new Card(
child: Column(
children: <Widget>[
Container(
child: new Text(data[index]["name"]),
),
Column(
children: List.generate(items.length, (index) {
return Text(
"${items[index]}",
style: TextStyle(color: Colors.red),
);
}),
),
],
),
),
);
},
),
onRefresh: _onRefresh,
),
);
}
}
class Todo {
final String name;
Todo(this.name);
Todo.fromJson(Map<String, dynamic> json) : name = json['name'];
}
class DetailsPage extends StatelessWidget {
final Todo todo;
DetailsPage({Key key, #required this.todo}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text(todo.name),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Text(todo.name),
),
);
}
}
UPDATE
OnClick Math, pass Math to the other screen (same for history)
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(new MaterialApp(
home: new HomePage(),
));
}
class HomePage extends StatefulWidget {
#override
HomePageState createState() => new HomePageState();
}
class HomePageState extends State<HomePage> {
List data;
bool isLoading = false;
Future<String> getData({isShowLoading: true}) async {
// refreshKey.currentState?.show(atTop: false);
//await Future.delayed(Duration(seconds: 2));
if (isShowLoading) {
setState(() {
isLoading = true;
});
}
var response = await http.get(
Uri.encodeFull("https://ikns.info/api/nested-array.php"),
headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
if (isShowLoading) {
setState(() {
isLoading = false;
});
}
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
if (mounted) {
setState(() {
data = jsonDecode(response.body);
});
}
return "Success!";
}
var refreshKey = GlobalKey<RefreshIndicatorState>();
#override
void initState() {
super.initState();
this.getData();
}
Future<Null> _onRefresh() async {
await getData(isShowLoading: false);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Parsing List of Strings"),
),
body: isLoading
? Center(
child: Text('Loading...'),
)
: RefreshIndicator(
key: refreshKey,
child: new ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
List<dynamic> items = data[index]["course_name"];
return new Card(
child: Column(
children: <Widget>[
Container(
child: new Text(data[index]["name"]),
),
Column(
children: List.generate(items.length, (index) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => DetailsPage(
todo: Todo(items[index].toString()),
),
),
);
},
child: Text(
"${items[index]}",
style: TextStyle(color: Colors.red),
),
);
}),
),
],
),
);
},
),
onRefresh: _onRefresh,
),
);
}
}
class Todo {
final String name;
Todo(this.name);
Todo.fromJson(Map<String, dynamic> json) : name = json['name'];
}
class DetailsPage extends StatelessWidget {
final Todo todo;
DetailsPage({Key key, #required this.todo}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text(todo.name),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Text(todo.name),
),
);
}
}

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

how to load Json to flutter listview

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