how to implement json array nested in ui flutter - flutter

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

Related

how can i call data from a model class which in list model flutter

I am trying to get data from my model but I am not getting the data in text widget.After receiving data from JSON I am using model to save data I am able to print data after API call in function but not when I tried to get data from model inside widget.I am using provider but receiving null value from model I am not getting exactly how to achieve this task following is my JSON object
{
"statusCode": 200,
"success": true,
"messages": [],
"data": [
{
"id": 36,
"title": "Muhurtam",
"filename": "Muhurtam.jpg",
"mimetype": "image/jpeg",
"directcalling": 1,
"parentid": null,
"subcat": [
{
"id": 50,
"title": "abc",
"filename": "abc.png",
"mimetype": "image/png",
"directcalling": 0,
"parentid": 36,
"subcat": []
}
]
I had created model class for the above json below is my model
Model
import 'package:flutter/material.dart';
class Categories with ChangeNotifier {
Categories({
this.statusCode,
this.success,
this.messages,
this.data,
});
late final int? statusCode;
late final bool? success;
late final List<dynamic>? messages;
late final List<Data>? data;
Categories.fromJson(Map<String, dynamic> json) {
statusCode = json['statusCode'];
success = json['success'];
messages = List.castFrom<dynamic, dynamic>(json['messages']);
data = List.from(json['data']).map((e) => Data.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['statusCode'] = statusCode;
_data['success'] = success;
_data['messages'] = messages;
_data['data'] = data!.map((e) => e.toJson()).toList();
return _data;
}
List get items {
// if (_showFavoritesOnly) {
// return _items.where((prodItem) => prodItem.isFavorite).toList();
// }
return [...data!];
}
}
class Data extends ChangeNotifier {
Data({
this.id,
this.title,
this.filename,
this.mimetype,
this.directcalling,
this.parentid,
this.subcat,
});
late final int? id;
late final String? title;
late final String? filename;
late final String? mimetype;
late final int? directcalling;
late final Null parentid;
late final List<Subcat>? subcat;
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
filename = json['filename'];
mimetype = json['mimetype'];
directcalling = json['directcalling'];
parentid = null;
subcat = List.from(json['subcat']).map((e) => Subcat.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
// _data['id'] = id;
_data['title'] = title;
_data['filename'] = filename;
// _data['mimetype'] = mimetype;
_data['directcalling'] = directcalling;
// _data['parentid'] = parentid;
// _data['subcat'] = subcat.map((e) => e.toJson()).toList();
return _data;
}
}
class Subcat {
Subcat({
required this.id,
required this.title,
required this.filename,
required this.mimetype,
required this.directcalling,
required this.parentid,
required this.subcat,
});
late final int id;
late final String title;
late final String filename;
late final String mimetype;
late final int directcalling;
late final int parentid;
late final List<dynamic> subcat;
Subcat.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
filename = json['filename'];
mimetype = json['mimetype'];
directcalling = json['directcalling'];
parentid = json['parentid'];
subcat = List.castFrom<dynamic, dynamic>(json['subcat']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
//_data['id'] = id;
_data['title'] = title;
_data['filename'] = filename;
//_data['mimetype'] = mimetype;
_data['directcalling'] = directcalling;
//_data['parentid'] = parentid;
//_data['subcat'] = subcat;
return _data;
}
}
following is my widget where I want to check data inside my model.i am not getting exactly how to call data which is inside model
Widget build(BuildContext context) {
var image = Provider.of<FlutterFunctions>(context, listen: false);
var cat = Provider.of<Category>(context, listen: false).categories;
return Scaffold(
appBar: AppBar(),
drawer: const AppDrawer(),
body: Text("${cat?.data == null ? "there is no data" : cat!.statusCode}")
Api Conversion
class Category with ChangeNotifier {
Categories? categories;
Future<void> getCatogories(BuildContext cont) async {
final url = PurohitApi().baseUrl + PurohitApi().getcategory;
try {
final client = RetryClient(
http.Client(),
retries: 4,
when: (response) {
return response.statusCode == 401 ? true : false;
},
onRetry: (req, res, retryCount) async {
//print('retry started $token');
if (retryCount == 0 && res?.statusCode == 401) {
var accessToken = await Provider.of<Auth>(cont, listen: false)
.restoreAccessToken();
// Only this block can run (once) until done
req.headers['Authorization'] = accessToken;
}
},
);
var response = await client.get(
Uri.parse(url),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
);
Map<String, dynamic> categoryTypes = json.decode(response.body);
categories = Categories.fromJson(categoryTypes);
notifyListeners();
} catch (e) {
print(e);
}
}
}
You are using Provider the wrong way. Your models such as Categories,Data etc. should not extend ChangeNotifier. You have to make Provider class which uses ChangeNotifier which will have your model data and provide it somewhere to use it with Provider.of<ProviderName>(context, listen: false). Something like this:
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (ctx) => CategoriesProvider(),
child: MaterialApp(
home: Sample(),
),
);
}
}
class CategoriesProvider with ChangeNotifier {
Categories? categories;
Future<void> getCatogories() async {
Map<String, dynamic> categoryTypes = {
"statusCode": 200,
"success": true,
"messages": [],
"data": [
{
"id": 36,
"title": "Muhurtam",
"filename": "Muhurtam.jpg",
"mimetype": "image/jpeg",
"directcalling": 1,
"parentid": null,
"subcat": [
{
"id": 50,
"title": "abc",
"filename": "abc.png",
"mimetype": "image/png",
"directcalling": 0,
"parentid": 36,
"subcat": []
}
]
}
]
};
categories = Categories.fromJson(categoryTypes);
notifyListeners();
}
}
class Sample extends StatefulWidget {
const Sample({Key? key}) : super(key: key);
#override
State<Sample> createState() => _SampleState();
}
class _SampleState extends State<Sample> {
#override
void initState() {
Provider.of<CategoriesProvider>(context, listen: false).getCatogories();
super.initState();
}
#override
Widget build(BuildContext context) {
var cat = Provider.of<CategoriesProvider>(context, listen: false).categories;
return Scaffold(
appBar: AppBar(),
drawer: const Drawer(),
body: Text("${cat?.data == null ? "there is no data" : cat!.statusCode}"),
);
}
}

How to fetch multiple data from api call and bind to a flutter widget

I will really be happy for my question to be answered. i don't really know how to display all fetched data in a widget in flutter, i am only getting a single data.
This is how my Api response looks like
{
"cartItems": [
{
"product": {
"_id": "61b0a14b4ce2a01b914ab953",
"name": "Total1",
"size": "1kg",
"price": 700,
"isLPG": true
},
"vendor": "61a72ffd8eab8af9af4cc2e7",
"vendorName": "Total Energies",
"vendorLogo": "/public/8-_5NKVjs-total-logo2.png",
"quantity": 2,
"price": 1400,
"type": "Refil",
"_id": "61c99030eebcb51e0f2a9a37"
},
{
"product": {
"_id": "61b0a18c4ce2a01b914ab959",
"name": "Total3",
"size": "3kg",
"price": 1800,
"isLPG": true
},
"vendor": "61a72ffd8eab8af9af4cc2e7",
"vendorName": "Total Energies",
"vendorLogo": "/public/8-_5NKVjs-total-logo2.png",
"quantity": 1,
"price": 1800,
"type": "Refil",
"_id": "61c9903feebcb51e0f2a9a3d"
},
{
"product": {
"_id": "61aa6cb89b2046e5116fabc4",
"name": "NNPC",
"size": "15kg",
"price": 17000,
"isLPG": true
},
"vendor": "61bde0f39dfb5060de241d24",
"vendorName": "NNPC NG",
"vendorLogo": "/public/o7452L7tJ-nnpc-logo.png",
"quantity": 3,
"price": 51000,
"type": "Refil",
"_id": "61c99067eebcb51e0f2a9a51"
}
]
}
This is the generated model
class GetCartItems {
List<CartItems>? cartItems;
GetCartItems({this.cartItems});
GetCartItems.fromJson(Map<String, dynamic> json) {
if (json['cartItems'] != null) {
cartItems = <CartItems>[];
json['cartItems'].forEach((v) {
cartItems!.add(new CartItems.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.cartItems != null) {
data['cartItems'] = this.cartItems!.map((v) => v.toJson()).toList();
}
return data;
}
}
class CartItems {
Product? product;
String? vendor;
String? vendorName;
String? vendorLogo;
int? quantity;
int? price;
String? type;
String? sId;
CartItems(
{this.product,
this.vendor,
this.vendorName,
this.vendorLogo,
this.quantity,
this.price,
this.type,
this.sId});
CartItems.fromJson(Map<String, dynamic> json) {
product =
json['product'] != null ? new Product.fromJson(json['product']) : null;
vendor = json['vendor'];
vendorName = json['vendorName'];
vendorLogo = json['vendorLogo'];
quantity = json['quantity'];
price = json['price'];
type = json['type'];
sId = json['_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.product != null) {
data['product'] = this.product!.toJson();
}
data['vendor'] = this.vendor;
data['vendorName'] = this.vendorName;
data['vendorLogo'] = this.vendorLogo;
data['quantity'] = this.quantity;
data['price'] = this.price;
data['type'] = this.type;
data['_id'] = this.sId;
return data;
}
}
class Product {
String? sId;
String? name;
String? size;
int? price;
bool? isLPG;
Product({this.sId, this.name, this.size, this.price, this.isLPG});
Product.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
name = json['name'];
size = json['size'];
price = json['price'];
isLPG = json['isLPG'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
data['name'] = this.name;
data['size'] = this.size;
data['price'] = this.price;
data['isLPG'] = this.isLPG;
return data;
}
}
This is my controller class
class GCP extends GetxController {
var log = Logger();
FlutterSecureStorage storage = FlutterSecureStorage();
var getCartItems = GetCartItems();
#override
void onInit() {
// TODO: implement onInit
super.onInit();
getCartItems2();
}
void getCartItems2() async {
try {
String? token = await storage.read(key: "token");
String postURL = NetworkHandler().baseurl + ApiUtil.getCartItems;
Map<String, String> headers = {
"Authorization": "Bearer $token",
'Content-Type': 'application/json;charset=UTF-8',
'Charset': 'utf-8'
};
var response = await http.get(Uri.parse(postURL), headers: headers);
if (response.statusCode == 200) {
var body = jsonDecode(response.body);
getCartItems = GetCartItems.fromJson(body);
update();
} else {
print('Something went wrong');
}
} catch (ex) {
print({ex, 'An error occured, cannot get cart items'});
}
}
}
This is my view, where i am displaying just a single data
import 'package:flutter/material.dart';
import 'package:gasapp_customer/src/controllers/GetCartPostController.dart';
import 'package:get/get.dart';
class GetCart extends StatelessWidget {
final gcp = Get.put(GCP());
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child:
Text(gcp.getCartItems.cartItems![0].product!.name.toString()),
),
],
),
),
);
}
}
So my question is how can i display all the data from my response?
You can use ListView or GridView. If the widget that you will show will be same for all instances except the data provided to it, use GridView.builder.
for more info on ListView and GridView, go to:
https://api.flutter.dev/flutter/widgets/GridView-class.html
https://api.flutter.dev/flutter/widgets/ListView-class.html

Cannot get data API Flutter

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 call method and retrive json array nested in flutter

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

How to fetch json data and separate it based on a Parameter?

I have a json object here -
{
"error": "0",
"message": "Got it!",
"data": [
{
"status": false,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "cciigcigc",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
}
]
}
I want to fetch it based on the ["data"]["status"] parameter; if the status is false, return a seperate list and if the status is true, return another list. I have tried to modify my current fetch method this way -
Future<List<Post>> gettask(bool identifier) async { // the identifier can be set to true and false
List<Post> statusComplete;
List<Post> statusInComplete;
String link = baseURL + fetchTodoByDate;
// print("printing from get task = $setter");
Stopwatch stopwatchbefore = new Stopwatch()..start();
var res = await http.post(Uri.encodeFull(link), headers: {"Accept": "application/json", }, body: {"date" : setter.toString()});
print('fetch executed in ${stopwatchbefore.elapsed}');
if (res.statusCode == 200) {
Stopwatch stopwatchafter = new Stopwatch()
..start();
var data = json.decode(res.body);
var rest = data["data"] as List;
if(identifier == true){
statusComplete = rest.map<Post>((json) {
// need help in implementing logic here
return Post.fromJson(json);
}).toList();
return statusComplete;
}else if(identifier == false){
statusInComplete = rest.map<Post>((json) {
// need help in implementing logic here
return Post.fromJson(json);
}).toList();
return statusInComplete;
}
print('statuscode executed in ${stopwatchafter.elapsed}');
Future.delayed(Duration(seconds: 5));
}
// print("List Size: ${list.length}");
}
This is the first time I am trying to fetch and separate the data this way. I have tried to look at some tutorials but none seemed to be satisfying my case.
Could i get some suggestion on how to fetch the data and then separate it based on a parameter?
check out the example below which will give the basic idea how the flow works.
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:json_parsing/models.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Datum> dataList = List();
bool _isLoading = false;
Future<String> loadFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
Future loadyourData() async {
setState(() {
_isLoading = true;
});
// this is the local json that i have loaded from the assets folder
// you can make the http call here and else everything later is the same.
String jsonString = await loadFromAssets();
final yourData = dataFromJson(jsonString);
dataList = yourData.data;
var statusComplete = dataList.where((i) => i.status == true).toList();
for (int i = 0; i < statusComplete.length; i++) {
print('This is the list for true status :${statusComplete[i].title}');
}
var statusInComplete = dataList.where((i) => i.status == false).toList();
print(statusInComplete[0].title);
setState(() {
_isLoading = false;
});
}
#override
void initState() {
super.initState();
loadyourData();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container(
child: _isLoading
? CircularProgressIndicator()
: new ListView.builder(
itemCount: dataList.length,
itemBuilder: (BuildContext ctxt, int index) {
return new Text(dataList[index].status.toString());
}),
)),
);
}
}
below is the model class
// To parse this JSON data, do
//
// final data = dataFromJson(jsonString);
import 'dart:convert';
Data dataFromJson(String str) => Data.fromJson(json.decode(str));
String dataToJson(Data data) => json.encode(data.toJson());
class Data {
String error;
String message;
List<Datum> data;
Data({
this.error,
this.message,
this.data,
});
factory Data.fromJson(Map<String, dynamic> json) => Data(
error: json["error"],
message: json["message"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"error": error,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
bool status;
String id;
String groupId;
DateTime date;
String title;
int priority;
String description;
List<dynamic> tasks;
DateTime createdDate;
int v;
Datum({
this.status,
this.id,
this.groupId,
this.date,
this.title,
this.priority,
this.description,
this.tasks,
this.createdDate,
this.v,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
status: json["status"],
id: json["_id"],
groupId: json["group_id"],
date: DateTime.parse(json["date"]),
title: json["title"],
priority: json["priority"],
description: json["description"],
tasks: List<dynamic>.from(json["tasks"].map((x) => x)),
createdDate: DateTime.parse(json["created_date"]),
v: json["__v"],
);
Map<String, dynamic> toJson() => {
"status": status,
"_id": id,
"group_id": groupId,
"date": date.toIso8601String(),
"title": title,
"priority": priority,
"description": description,
"tasks": List<dynamic>.from(tasks.map((x) => x)),
"created_date": createdDate.toIso8601String(),
"__v": v,
};
}
and this is the json that you specified
{
"error": "0",
"message": "Got it!",
"data": [
{
"status": false,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "first",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
},
{
"status": true,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "second",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
},
{
"status": true,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "third",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
}
]
}
Try this model class
import 'dart:convert';
Jsonmodel jsonmodelFromJson(String str) => Jsonmodel.fromJson(json.decode(str));
String jsonmodelToJson(Jsonmodel data) => json.encode(data.toJson());
class Jsonmodel {
String error;
String message;
List<Datum> data;
Jsonmodel({
this.error,
this.message,
this.data,
});
factory Jsonmodel.fromJson(Map<String, dynamic> json) => Jsonmodel(
error: json["error"],
message: json["message"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"error": error,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
bool status;
String id;
String groupId;
DateTime date;
String title;
int priority;
String description;
List<dynamic> tasks;
DateTime createdDate;
int v;
Datum({
this.status,
this.id,
this.groupId,
this.date,
this.title,
this.priority,
this.description,
this.tasks,
this.createdDate,
this.v,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
status: json["status"],
id: json["_id"],
groupId: json["group_id"],
date: DateTime.parse(json["date"]),
title: json["title"],
priority: json["priority"],
description: json["description"],
tasks: List<dynamic>.from(json["tasks"].map((x) => x)),
createdDate: DateTime.parse(json["created_date"]),
v: json["__v"],
);
Map<String, dynamic> toJson() => {
"status": status,
"_id": id,
"group_id": groupId,
"date": date.toIso8601String(),
"title": title,
"priority": priority,
"description": description,
"tasks": List<dynamic>.from(tasks.map((x) => x)),
"created_date": createdDate.toIso8601String(),
"__v": v,
};
}
use like this
var res = await http.post(Uri.encodeFull(link), headers: {"Accept":
"application/json", }, body: {"date" : setter.toString()});
Jsonmodel modeldata = jsonmodelFromJson(res);
// do your stuff
modeldata.data.foreach((data){
if(data.status){
//do your stuff
}else{
//do your stuff
}
});