I new used flutter. I have model but i don't understand to call method and retrive data to show in ui(interface). I using packages http post.
this my code model
import 'dart:convert';
MutasiRekResponse myModelFromJson(String str) => MutasiRekResponse.fromJson(json.decode(str));
String myModelToJson(MutasiRekResponse data) => json.encode(data.toJson());
class MutasiRekResponse {
String responseCode;
String responseMessage;
String date;
String time;
List<Content> content;
MutasiRekResponse({
this.responseCode,
this.responseMessage,
this.date,
this.time,
this.content,
});
factory MutasiRekResponse.fromJson(Map<String, dynamic> json) => MutasiRekResponse(
responseCode: json["responseCode"],
responseMessage: json["responseMessage"],
date: json["date"],
time: json["time"],
content: List<Content>.from(json["content"].map((x) => Content.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"responseCode": responseCode,
"responseMessage": responseMessage,
"date": date,
"time": time,
"content": List<dynamic>.from(content.map((x) => x.toJson())),
};
}
class Content {
String postingDate;
String valueDate;
String inputDate;
String inputTime;
String desc;
String noReff;
String amount;
String balance;
Content({
this.postingDate,
this.valueDate,
this.inputDate,
this.inputTime,
this.desc,
this.noReff,
this.amount,
this.balance,
});
factory Content.fromJson(Map<String, dynamic> json) => Content(
postingDate: json["postingDate"],
valueDate: json["valueDate"],
inputDate: json["inputDate"],
inputTime: json["inputTime"],
desc: json["desc"],
noReff: json["noReff"],
amount: json["amount"],
balance: json["balance"],
);
Map<String, dynamic> toJson() => {
"postingDate": postingDate,
"valueDate": valueDate,
"inputDate": inputDate,
"inputTime": inputTime,
"desc": desc,
"noReff": noReff,
"amount": amount,
"balance": balance,
};
}
I am using http post package, please advice code:
static Future<MutasiRekResponse> (String accNumber, String startDate, String endDate) async {
String apiURL = "URL";
var credentials = base64.encode(bytes);
var headers = {
"Content-Type": "application/json",
"Authorization": "Basic $credentials"
};
var requestBody = jsonEncode(
{'accNumber': accNumber, 'startDate': startDate, 'endDate': endDate});
http.Response apiResult =
await http.post(apiURL, body: requestBody, headers: headers);
if (apiResult.statusCode == 200) {
apiResult.body;
} else {
Exception('failed to load data');
}
final jsonObject = json.decode(apiResult.body);
final _postResult = MutasiRekResponse(jsonObject);
return _postResult;
}
how to using correct http.pos and how to call method & retrive data in ui(interface). thank you.
Future - Widget that builds itself based on the latest snapshot of interaction with a Future.
I've added a code snippet for showing a list of contents (desc and date) in a ListView.
Widget contentList() {
return FutureBuilder(
builder: (BuildContext context, AsyncSnapshot<MutasiRekResponse> dataSnapshot) {
if (dataSnapshot.connectionState == ConnectionState.none &&
dataSnapshot.hasData == null) {
return Container(child: Text('Something went wrong'));
}
return ListView.builder(
itemCount: dataSnapshot.data.content.length,
itemBuilder: (context, index) {
return Column(
children: <Widget>[
Text(dataSnapshot.data.content[index].desc);
Text(dataSnapshot.data.content[index].balance);
],
);
},
);
},
future: getMutasiDetails('your account number', '05/03/2020', '10/03/2020), // Your async function
);
}
static Future<MutasiRekResponse> getMutasiDetails(String accNumber, String startDate, String endDate) async {
String apiURL = "your api url";
var credentials = base64.encode(bytes);
var headers = {
"Content-Type": "application/json",
"Authorization": "Basic $credentials"
};
var params = Map<String, dynamic>();
params['accNumber'] = accNumber;
params['startDate'] = startDate;
params['endDate'] = endDate;
http.Response apiResult =
await http.post(apiURL, body: params, headers: headers);
if (apiResult.statusCode == 200) {
return MutasiRekResponse.fromJson(json.decode(apiResult.body));
} else {
throw Exception('failed to load data');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Content List'),
),
body: contentList(),
);
}
Related
In the following image, I am using the post method to send the data, which is successfully done and when the server returns the response which is can be seen in the user's console, now how do I display those responses in text widgets in another class?
This is my Api class where I use post method.
class APIService {
Future<DoctorResponseLoginModels> register(
DoctorRequestLoginModels doctorLoginRequestModels) async {
String url = "http://202.51.75.142:9028/api/PatientMaster/PostPatientLogin";
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var globalToken = sharedPreferences.getString("token");
print("$globalToken");
http.Response response = await http.post(Uri.parse(url),
headers: {
"Content-Type": "application/json",
'Accept': 'application/json',
'Authorization': 'Bearer $globalToken',
},
body: jsonEncode(doctorLoginRequestModels));
var responseJson = json.decode(response.body.toString());
DoctorResponseLoginModels responseModel =
DoctorResponseLoginModels.fromJson(responseJson);
print("This is ${response.body}");
if (response.statusCode == 200) {
sharedPreferences.setInt('code', response.statusCode);
var StatusCode = sharedPreferences.getInt('code');
print("This contains : $StatusCode");
print(response.statusCode);
return DoctorResponseLoginModels.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed');
}
}
}
This is my Request Class model which I sent to server
DoctorRequestLoginModels doctorRequestLoginModelsFromJson(String str) =>
DoctorRequestLoginModels.fromJson(json.decode(str));
String doctorRequestLoginModelsToJson(DoctorRequestLoginModels data) =>
json.encode(data.toJson());
class DoctorRequestLoginModels {
DoctorRequestLoginModels({
required this.code,
required this.username,
required this.password,
});
String code;
String username;
String password;
factory DoctorRequestLoginModels.fromJson(Map<String, dynamic> json) =>
DoctorRequestLoginModels(
code: json["code"],
username: json["username"],
password: json["password"],
);
Map<String, dynamic> toJson() => {
"code": code,
"username": username,
"password": password,
};
}
This is my Response Models class which I need to display in text
DoctorResponseLoginModels doctorResponseLoginModelsFromJson(String str) =>
DoctorResponseLoginModels.fromJson(json.decode(str));
String doctorResponseLoginModelsToJson(DoctorResponseLoginModels data) =>
json.encode(data.toJson());
class DoctorResponseLoginModels {
DoctorResponseLoginModels({
this.doctorId,
this.nmCno,
this.doctorName,
this.contactNo,
this.username,
this.emailId,
this.strEmail,
this.id,
this.intMobile,
this.gender,
this.currentAddress,
this.depId,
this.entryDate,
this.password,
this.code,
this.isActive,
this.hospitalName,
this.department,
this.deviceId,
this.profile,
this.token,
this.role,
});
int? doctorId;
String? nmCno;
String? doctorName;
String? contactNo;
dynamic? username;
String? emailId;
String? strEmail;
int? id;
String? intMobile;
dynamic? gender;
String? currentAddress;
int? depId;
String? entryDate;
dynamic? password;
dynamic? code;
bool? isActive;
dynamic? hospitalName;
dynamic? department;
dynamic? deviceId;
String? profile;
String? token;
String? role;
factory DoctorResponseLoginModels.fromJson(Map<String, dynamic> json) =>
DoctorResponseLoginModels(
doctorId: json["doctorID"],
nmCno: json["nmCno"],
doctorName: json["doctorName"],
contactNo: json["contactNo"],
username: json["username"],
emailId: json["emailID"],
strEmail: json["strEmail"],
id: json["id"],
intMobile: json["intMobile"],
gender: json["gender"],
currentAddress: json["currentAddress"],
depId: json["depId"],
entryDate: json["entryDate"],
password: json["password"],
code: json["code"],
isActive: json["isActive"],
hospitalName: json["hospitalName"],
department: json["department"],
deviceId: json["deviceId"],
profile: json["profile"],
token: json["token"],
role: json["role"],
);
Map<String, dynamic> toJson() => {
"doctorID": doctorId,
"nmCno": nmCno,
"doctorName": doctorName,
"contactNo": contactNo,
"username": username,
"emailID": emailId,
"strEmail": strEmail,
"id": id,
"intMobile": intMobile,
"gender": gender,
"currentAddress": currentAddress,
"depId": depId,
"entryDate": entryDate,
"password": password,
"code": code,
"isActive": isActive,
"hospitalName": hospitalName,
"department": department,
"deviceId": deviceId,
"profile": profile,
"token": token,
"role": role,
};
}
This is where I am using Future Builder to display in Text
return Scaffold(
backgroundColor: const Color.fromRGBO(249, 249, 249, 10),
body: Column(
children: [
Expanded(
child: Container(
height: 150.0,
width: 150.0,
color: Colors.grey.shade100,
child: FutureBuilder<DoctorResponseLoginModels>(
future: APIService().register(DoctorRequestLoginModels(
code: "code", username: "username", password: "password")),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading....');
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
DoctorResponseLoginModels data = snapshot.data!;
return Column(
children: [
Text(data.doctorName!),
],
);
}
}
},
),
)),
],
));
And this is the image of response I get in my console after I use post method and this is the response which I need to display in my text widgets
The correct approach would be to put the API-Class to a Provider.
Access the Instance whenever you need.
You can use FutureBuilder like this:
FutureBuilder<DoctorResponseLoginModels>(
future: APIService().register(...),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading....');
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
DoctorResponseLoginModels data = snapshot.data!;
return Column(
children: [
Text(data.doctorName ?? ''),
Text(data.username?? ''),
],
);
}
}
},
),
I want to get data from API and I tried the link in postman and its working here it is: [ { "Id": "14", "title": "Facebook vs instagram?", }, { "Id": "15", "title": "Facebook vs instagram?", }, { "Id": "16", "title": "Facebook vs instagram?", }, ]
but when I am trying to do a map this error appears : error catch type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List' in type cast.
Here is my code : This error appears in this file and print(recieved) print the same data as postman but the problem in map httpservice.dart:
`
class HttpService {
final String postsURL =
"";
Future<List<Post>> getPosts() async {
var request = http.MultipartRequest("POST", Uri.parse(postsURL));
request.headers.addAll(headers);
List<Post> Posts = [];
try {
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
var response = await http.Response.fromStream(streamedResponse);
final result = jsonDecode(response.body) as List;
List<Post> posts = result
.map(
(dynamic item) => Post.fromJson(item),
)
.toList();
return Posts;
}
}
`
post_model.dart :
`
class Post {
final String Id;
final String title;
Post({
required this.Id,
required this.title,
});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
Id: json['Id'] as String,
title: json['title'] as String,
);
}
}
` post.dart :
class PostsPage extends StatelessWidget {
final HttpService httpService = HttpService();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Posts"),
),
body: FutureBuilder(
future: httpService.getPosts(),
builder: (BuildContext context, AsyncSnapshot<List<Post>> snapshot) {
if (snapshot.hasData) {
List<Post> posts = snapshot.data!;
return ListView(
children: posts
.map(
(Post post) => ListTile(
title: Text(post.title),
subtitle: Text("${post.Id}"),
),
)
.toList(),
);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
);
}
}
The http package gives the data as json in default. You are again trying to decode the decode the response body but the jsonDecode expects string type as parameter.
Simply, all you need to do is remove the jsonDecode
From
final result = jsonDecode(response.body) as List;
to
final result = response.body as Map<String, dynamic>;
Here I get this JSON object from the API and I need to add it to a list and return so that I can get it from the snapshot to display the data.But i get the snapshot.data as null.Please help me to solve this issue.
...
{
"Data": [
{
"product_name": "MACC Tea Master Blend 40 Bags",
"img_url": "1605262901.jpg",
"order_no": "1625809545122",
"category": [
{
"category_name": "01 Box (40 Bags)",
"order_no": "1625809545122",
"qty": "1",
"line_total": "1.79"
}
]
}
],
"ID": "200"
}
...
This is the code on how i tried so far.
...
Future<List<OrderDetails>> fetchMyOrderDetails(order_no) async {
var body = jsonEncode({"order_no": order_no});
print("order_no : " + order_no);
http.Response response = await http.post(
Uri.encodeFull(api + "get_order_details_by_orderno.php"), //url
headers: {"Accept": "application/json"},
body: body);
if (response.statusCode == 200) {
Map<String, dynamic> map = json.decode(response.body);
// var map = json.decode(response.body);
print("response.body : " + "${response.body}");
print("map : " + "${map['Data']}");
List<OrderDetails> orderDetailsList;
orderDetailsList = (json.decode(response.body)['Data'] as List)
.map((i) => OrderDetails.fromJson(i))
.toList();
return orderDetailsList;
} else {
// print("Failed to load categories");
throw Exception('Failed to load the Orders');
}
}
class OrderDetails {
final String product_name;
final String img_url;
final String order_no;
final List<Category> category;
OrderDetails({
this.product_name,
this.img_url,
this.order_no,
this.category,
});
factory OrderDetails.fromJson(Map<String, dynamic> json) {
return OrderDetails(
product_name: json['product_name'] as String,
img_url: json['img_url'] as String,
order_no: json['order_no'] as String,
category: json['category'] as List,
);
}
}
class Category {
final String category_name;
final String qty;
final String line_total;
Category({this.category_name, this.qty, this.line_total});
factory Category.fromJson(Map<String, dynamic> json) {
return Category(
category_name: json['category_name'] as String,
qty: json['qty'] as String,
line_total: json['line_total'] as String,
);
}
}
...
From the below code i try to access the data but the snapshot.data get null and the page is loading.
...
child: FutureBuilder<List<OrderDetails>>(
future: fetchMyOrderDetails(order_no),
builder: (BuildContext context, AsyncSnapshot snapshot) {
print("snapshot data : " + "${snapshot.data}");
if (snapshot.data == null) {
return Container(
child: Center(
child: CircularProgressIndicator(),
),
);
} else {
return Center(
child: Text(snapshot.data.product_name),
);
}
},
),
...
Please update OrderDetails class.
json['category'] as List is List<dynamic> , not List<Category>
factory OrderDetails.fromJson(Map<String, dynamic> json) {
return OrderDetails(
product_name: json['product_name'] as String,
img_url: json['img_url'] as String,
order_no: json['order_no'] as String,
category: (json['category'] == null)
? null
: (json['category'] as List).map(e => Category.fromJson(e)).toList(),
);
}
Future<List<OrderDetails>> fetchMyOrderDetails(order_no) async {
var body = jsonEncode({"order_no": order_no});
print("order_no : " + order_no);
http.Response response = await http.post(
Uri.encodeFull(api + "get_order_details_by_orderno.php"), //url
headers: {"Accept": "application/json"},
body: body);
if (response.statusCode == 200) {
Map<String, dynamic> map = json.decode(response.body);
print("response.body : " + "${response.body}");
print("map : " + "${map['Data']}");
List<OrderDetails> orderDetailsList;
orderDetailsList = (map['Data'] as List)
.map((i) => OrderDetails.fromJson(i))
.toList();
return orderDetailsList;
} else {
// print("Failed to load categories");
throw Exception('Failed to load the Orders');
}
}
I want to get data of each element inside "invoices" to show but I don't know why it has a problem when I try to call "DataAllInvoice" class.
Please help me fix this problem.
Data API
{
"invoices": [
{
"id": 3,
"customer_id": 6,
"customer_name": "Nguyễn Công Phượng",
"creater_id": 2,
"creater_name": "Lê Minh Tuấn",
"create_time": "2021-05-16T10:05:43",
"total": 411107.0,
"description": "ABC",
"manager_confirm_id": 0,
"manager_confirm_name": null,
"manager_confirm_date": null,
"customer_confirm_date": null,
"status_id": 4
},
{
"id": 2,
"customer_id": 3,
"customer_name": "Nguyễn Văn A",
"creater_id": 2,
"creater_name": "Lê Minh Tuấn",
"create_time": "2021-05-14T10:05:43",
"total": 411107.0,
"description": "ABC",
"manager_confirm_id": 0,
"manager_confirm_name": null,
"manager_confirm_date": null,
"customer_confirm_date": null,
"status_id": 1
},
{
"id": 1,
"customer_id": 3,
"customer_name": "Nguyễn Văn A",
"creater_id": 2,
"creater_name": "Lê Minh Tuấn",
"create_time": "2021-05-14T09:28:43",
"total": 222220.0,
"description": "ABC",
"manager_confirm_id": 0,
"manager_confirm_name": null,
"manager_confirm_date": null,
"customer_confirm_date": null,
"status_id": 5
}
],
"total": 3
}
Class to call API
class GetInvoice{
static int statusInvoice;
createInvoice() async {
final response = await http.get(
Uri.parse("http://3.137.137.156:5000/api/rtm/v1/invoice/get-invoice?customer_id=0&pageNum=10&pageNo=1&from=%20&to=2021-05-14%2012%3A00%3A00"),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json',
'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIwMTIzNDU2Nzg4IiwiaWF0IjoxNjIyNjI0MjAyLCJleHAiOjE2MjMyMjkwMDJ9.zkf23Da4-TR5sVZgtXjXvczERhaNT1teeX5k-mQaKK6lbE0l28j5TwY5ZqPL252AEAaT8W1jyEUijG-rQiSu5Q',
},
);
print("Status getApi Invoice:${response.statusCode}");
statusInvoice = response.statusCode;
if (response.statusCode == 200) {
Invoice invoice = Invoice.fromJson(jsonDecode(response.body));
List<DataAllInvoice> _invoice;
for(int i=0;i < invoice.invoices.length;i++){
if(invoice.invoices[i]!=null){
Map<String,dynamic> map=invoice.invoices[i];
_invoice.add(DataAllInvoice.fromJson(map)); ****Not working here****
}
}
return _invoice;
} else {
// throw an exception.
throw Exception('Failed to load data');
}
}
Class have a problem when I try to call - DataAllInvoice class
class DataAllInvoice {
final int id, customer_id, creater_id, total, manager_confirm_id, status_id;
final String customer_name, manager_confirm_name;
final String creater_name, description;
final DateTime create_time, manager_confirm_date, customer_confirm_date;
DataAllInvoice(
{this.id,
this.customer_id,
this.creater_id,
this.total,
this.manager_confirm_id,
this.status_id,
this.customer_name,
this.manager_confirm_name,
this.creater_name,
this.description,
this.create_time,
this.manager_confirm_date,
this.customer_confirm_date
});
factory DataAllInvoice.fromJson(Map<String, dynamic> json) {
return DataAllInvoice(
id: json[" id"],
customer_id: json[" customer_id"],
creater_id: json[" creater_id"],
total: json[" total"],
manager_confirm_id: json[" manager_confirm_id"],
status_id: json[" status_id"],
customer_name: json[" customer_name"],
manager_confirm_name: json[" manager_confirm_name"],
creater_name: json[" creater_name"],
description: json[" description"],
create_time: DateTime.parse(json[" create_time"]),
manager_confirm_date: DateTime.parse(json[" manager_confirm_date"]),
customer_confirm_date: DateTime.parse(json[" customer_confirm_date"]),
);
}
}
Invoice Class
class Invoice {
final List invoices;
final int total;
Invoice({this.invoices, this.total});
factory Invoice.fromJson(Map<String, dynamic> json) {
return Invoice(
invoices: json["invoices"],
total: json["total"],
);
}
}
Try That :
So here Fetch Api Class
Sometime you gotta need to use Uri.parse() to put the URL inside it.
and you have to check the statusCode is equal 200 Otherwise there is problem.
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'DataCardFromApi.dart';
class FetchApi {
static Future<List<Articles>> fetchStory() async {
var url = Uri.parse("https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=c5609b49c9274e89bacde5dcab5c52a2");
http.Response response = await http.get(url);
if (response.statusCode == 200) {
Map<String, dynamic> resMap = jsonDecode(response.body);
List listNews = resMap['articles'];
return listNews.map((e) => Articles.fromJson(e)).toList();
}
return null;
}
}
So the second Step :
you have to copy All Code Of Json and convert to Dart Code via This Link
You will get a code like this :
class NewsModel {
String status;
int totalResults;
List<Articles> articles;
NewsModel({this.status, this.totalResults, this.articles});
NewsModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
totalResults = json['totalResults'];
if (json['articles'] != null) {
articles = new List<Articles>();
json['articles'].forEach((v) {
articles.add(new Articles.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['totalResults'] = this.totalResults;
if (this.articles != null) {
data['articles'] = this.articles.map((v) => v.toJson()).toList();
}
return data;
}
}
class Articles {
Source source;
String author;
String title;
String description;
String url;
String urlToImage;
String publishedAt;
String content;
Articles(
{this.source,
this.author,
this.title,
this.description,
this.url,
this.urlToImage,
this.publishedAt,
this.content});
Articles.fromJson(Map<String, dynamic> json) {
source =
json['source'] != null ? new Source.fromJson(json['source']) : null;
author = json['author'];
title = json['title'];
description = json['description'];
url = json['url'];
urlToImage = json['urlToImage'];
publishedAt = json['publishedAt'];
content = json['content'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.source != null) {
data['source'] = this.source.toJson();
}
data['author'] = this.author;
data['title'] = this.title;
data['description'] = this.description;
data['url'] = this.url;
data['urlToImage'] = this.urlToImage;
data['publishedAt'] = this.publishedAt;
data['content'] = this.content;
return data;
}
}
class Source {
String id;
String name;
Source({this.id, this.name});
Source.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
The Third step :
you have to create a Function loadData like this and after that you will put it inside initState to get data
watch this code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/StoryModel.dart';
import 'Fetch_Api.dart';
import 'New_Page.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<Articles> listModel;
#override
void initState() {
// TODO: implement initState
super.initState();
loadData() ;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(""),
actions: [
Padding(padding: EdgeInsets.only(right: 20.0),child: Icon(Icons.search_rounded))],
backgroundColor: Colors.indigo,
),
body: SafeArea(child: listModel != null ? ListView.builder(
shrinkWrap: true,
itemCount: listModel.length,
itemBuilder: (_ , index){
Articles model = listModel[index] ;
if(model.urlToImage != null)
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
InkWell(
onTap:()=> onPressCallback(model),
child: ClipRRect(
borderRadius: BorderRadius.circular(30.0),
child: Image.network(model.urlToImage,)),),
Text(model.title,style: TextStyle(fontSize: 27.0,fontWeight:FontWeight.bold),),
SizedBox(height: 20,),],
),
) ;
return SizedBox();
}) : Center(child: Text('Loading data ... ')),)
);
}
void loadData() async{
listModel = await FetchApi.fetchStory() ;
setState(() {});
}
void onPressCallback(Articles model) {
Navigator.push(context, MaterialPageRoute(builder: (_) => NewPage(model: model)));
}
}
How can I parse json array nested object to ListView in UI using Flutter?
The API response is
{
"responseCode": "0000",
"responseMessage": "Success",
"date": "20200227",
"time": "115221",
"content": [
{
"postingDate": "20191203",
"valueDate": "20191203",
"inputDate": "20191203",
"inputTime": "214808",
"desc": "BUNGA JATUH TEMPO"
},
]
}
Can you please help me? Thanks a lot!
Just check out this example where I have parsed you JSON locally :
{
"responseCode": "0000",
"responseMessage": "Success",
"date": "20200227",
"time": "115221",
"content": [
{
"postingDate": "20191203",
"valueDate": "20191203",
"inputDate": "20191203",
"inputTime": "214808",
"desc": "BUNGA JATUH TEMPO",
"noReff": "B2100000000026",
"amount": "+20712,33",
"balance": "+6971357445,15"
},
{
"postingDate": "20191203",
"valueDate": "20191203",
"inputDate": "20191203",
"inputTime": "214809",
"desc": "BUNGA JATUH TEMPO",
"noReff": "B2100000000033",
"amount": "+13808,22",
"balance": "+6971371253,37"
}
]
}
below is the model class for the json that you provided.
// To parse this JSON data, do
//
// final myModel = myModelFromJson(jsonString);
import 'dart:convert';
MyModel myModelFromJson(String str) => MyModel.fromJson(json.decode(str));
String myModelToJson(MyModel data) => json.encode(data.toJson());
class MyModel {
String responseCode;
String responseMessage;
String date;
String time;
List<Content> content;
MyModel({
this.responseCode,
this.responseMessage,
this.date,
this.time,
this.content,
});
factory MyModel.fromJson(Map<String, dynamic> json) => MyModel(
responseCode: json["responseCode"],
responseMessage: json["responseMessage"],
date: json["date"],
time: json["time"],
content: List<Content>.from(json["content"].map((x) => Content.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"responseCode": responseCode,
"responseMessage": responseMessage,
"date": date,
"time": time,
"content": List<dynamic>.from(content.map((x) => x.toJson())),
};
}
class Content {
String postingDate;
String valueDate;
String inputDate;
String inputTime;
String desc;
String noReff;
String amount;
String balance;
Content({
this.postingDate,
this.valueDate,
this.inputDate,
this.inputTime,
this.desc,
this.noReff,
this.amount,
this.balance,
});
factory Content.fromJson(Map<String, dynamic> json) => Content(
postingDate: json["postingDate"],
valueDate: json["valueDate"],
inputDate: json["inputDate"],
inputTime: json["inputTime"],
desc: json["desc"],
noReff: json["noReff"],
amount: json["amount"],
balance: json["balance"],
);
Map<String, dynamic> toJson() => {
"postingDate": postingDate,
"valueDate": valueDate,
"inputDate": inputDate,
"inputTime": inputTime,
"desc": desc,
"noReff": noReff,
"amount": amount,
"balance": balance,
};
// remove this method from the model
static Future<MyModel> getMutasiDetails(String accNumber, String startDate, String endDate) async {
String apiURL = urlAPI";
String username = "username";
String password = "password";
var bytes = utf8.encode("$username:$password");
var credentials = base64.encode(bytes);
var headers = {
"Content-Type": "application/json",
"Authorization": "Basic $credentials"
};
var params = Map<String, dynamic>();
params['accNumber'] = accNumber;
params['startDate'] = startDate;
params['endDate'] = endDate;
http.Response apiResult =
await http.post(apiURL, body: params, headers: headers);
if (apiResult.statusCode == 200) {
return MyModel.fromJson(json.decode(apiResult.body));
} else {
throw Exception('failed to load data');
}
}
}
And below is the main file where the listview gets rendered:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sample_project_for_api/model.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
MyModel youModel = new MyModel();
bool _isLoading = false;
#override
void initState() {
super.initState();
getMutasiDetails("0002100000291", "", "").then((value) {
youModel = value;
setState(() {
_isLoading = false;
});
});
}
Future<MyModel> getMutasiDetails(
String accNumber, String startDate, String endDate) async {
setState(() {
_isLoading = true;
});
String apiURL = "urlAPI";
String username = "username";
String password = "password";
var bytes = utf8.encode("$username:$password");
var credentials = base64.encode(bytes);
var headers = {
"Content-Type": "application/json",
"Authorization": "Basic $credentials"
};
var params = Map<String, dynamic>();
params['accNumber'] = accNumber;
params['startDate'] = startDate;
params['endDate'] = endDate;
http.Response apiResult =
await http.post(apiURL, body: params, headers: headers);
if (apiResult.statusCode == 200) {
return myModelFromJson(apiResult.body);
} else {
throw Exception('failed to load data');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _isLoading
? CircularProgressIndicator()
: Container(
child: ListView.builder(
itemCount: youModel.content.length,
itemBuilder: (context, i) {
return Card(
child: Column(
children: <Widget>[
Text(youModel.content[i].amount),
Text(youModel.content[i].balance),
Text(youModel.content[i].inputDate),
Text(youModel.content[i].desc),
],
),
);
})),
);
}
}
First you could take a look at this resource:
https://bezkoder.com/dart-flutter-parse-json-string-array-to-object-list/#DartFlutter_parse_complex_JSON_into_Nested_Object
It will give you a better understanding of the parsing you're trying to do.
Then take a look at this another post:
https://pusher.com/tutorials/flutter-listviews
It will give an idea of how to handle ListViews properly
List<MyModel> list=[];
var requestBody = jsonEncode({'accNumber': accNumber});
http.Response response = await http.post(apiURL, body: requestBody, headers: headers);
if (response.statusCode == 200) {
var data = json.decode(response.body);
print(data);
for (Map<String,dynamic> m in data['content']){
list.add(MyModel.fromJSON(m));
//Replace above line with your model implemtation
}
);
}