I've come across a problem which I cannot figure out. I'm trying to display single event on my home screen which is next upcoming by date. That event comes from list of events in the api.
Currently I am using listview.builder to display those events however when I set item count to 1 I cannot get the next event by date to be displayed. I was trying to display all events in listview.builder and then filter but I couldn't get it to work.
I need to display events in that order but they need to be shown 1 by 1 based on todays time. So when current time is the same as the events time next event will be shown:
firstImage
And this is what I'm getting when the itemCount is 1. This is the last event from the list
which I tried to reverse but no success. secondImage
This is code for the ListView.builder
ListView.builder(
reverse: true,
shrinkWrap: true,
physics: ClampingScrollPhysics(),
// itemCount: 1,
itemCount: 1,
itemBuilder: (context, index) {
var x = eventController.event.value!.data![index];
DateTime formattedStartDate = new DateFormat('yyyy-MM-dd hh:mm')
.parse(eventController
.event.value!.data![index].eventStartDate
.toString());
DateTime splitStartDate = new DateTime(
formattedStartDate.year,
formattedStartDate.month,
formattedStartDate.day,
formattedStartDate.hour,
formattedStartDate.minute);
DateTime today = DateTime.now();
bool isAfter = splitStartDate.isAfter(today);
return Column(
children: [
isAfter == true
? GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EventDetails(
event: eventController
.event.value!.data![index])));
},
child: EventTileMain(
eventController.event.value!.data![index]))
: Container()
],
);
});
This is model calss of event:
// To parse this JSON data, do
//
// final event = eventFromJson(jsonString);
import 'dart:convert';
Event eventFromJson(String str) => Event.fromJson(json.decode(str));
String eventToJson(Event data) => json.encode(data.toJson());
class Event {
Event({
this.success,
this.data,
this.code,
this.count,
});
bool? success;
List<Datum>? data;
int? code;
int? count;
factory Event.fromJson(Map<String, dynamic> json) => Event(
success: json["success"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
code: json["code"],
count: json["count"],
);
Map<String, dynamic> toJson() => {
"success": success,
"data": List<dynamic>.from(data!.map((x) => x.toJson())),
"code": code,
"count": count,
};
}
class Datum {
Datum({
this.id,
this.postTitle,
this.postContent,
this.postName,
this.postUrl,
this.organizer,
this.venue,
this.category,
this.speaker,
this.eventStartDate,
this.eventEndDate,
this.eventDate,
this.featuredImage,
});
String? id;
String? postTitle;
String? postContent;
String? postName;
String? postUrl;
List<Category>? organizer;
List<Category>? venue;
List<Category>? category;
dynamic speaker;
String? eventStartDate;
String? eventEndDate;
DateTime? eventDate;
String? featuredImage;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["ID"],
postTitle: json["post_title"],
postContent: json["post_content"],
postName: json["post_name"],
postUrl: json["post_url"],
organizer: List<Category>.from(json["organizer"].map((x) => Category.fromJson(x))),
venue: List<Category>.from(json["venue"].map((x) => Category.fromJson(x))),
category: List<Category>.from(json["category"].map((x) => Category.fromJson(x))),
speaker: json["speaker"],
eventStartDate: json["event_start_date"],
eventEndDate: json["event_end_date"],
eventDate: DateTime.parse(json["event_date"]),
featuredImage: json["featured_image"],
);
Map<String, dynamic> toJson() => {
"ID": id,
"post_title": postTitle,
"post_content": postContent,
"post_name": postName,
"post_url": postUrl,
"organizer": List<dynamic>.from(organizer!.map((x) => x.toJson())),
"venue": List<dynamic>.from(venue!.map((x) => x.toJson())),
"category": List<dynamic>.from(category!.map((x) => x.toJson())),
"speaker": speaker,
"event_start_date": eventStartDate,
"event_end_date": eventEndDate,
"event_date": eventDate!.toIso8601String(),
"featured_image": featuredImage,
};
}
class Category {
Category({
this.id,
this.name,
});
int? id;
Name? name;
factory Category.fromJson(Map<String, dynamic> json) => Category(
id: json["id"],
name: nameValues.map[json["name"]],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": nameValues.reverse![name],
};
}
enum Name { AUDITORIUM, SEMINAR, XPOSURE, XPOSURE_INTERNATIONAL_PHOTOGRAPHY_FESTIVAL, TOR_SEIDEL, XPOSURE_AUDITORIUM }
final nameValues = EnumValues({
"Auditorium": Name.AUDITORIUM,
"Seminar": Name.SEMINAR,
"Tor Seidel": Name.TOR_SEIDEL,
"Xposure": Name.XPOSURE,
"Xposure Auditorium": Name.XPOSURE_AUDITORIUM,
"Xposure International Photography Festival": Name.XPOSURE_INTERNATIONAL_PHOTOGRAPHY_FESTIVAL
});
class EnumValues<T> {
Map<String, T> map;
Map<T, String>? reverseMap;
EnumValues(this.map);
Map<T, String>? get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
API call
class EventApi {
static var client = http.Client();
static Future<Event?> fetchEvents() async {
final response = await client.get(Uri.parse(
'https://xposure.ae/api/v1/events/'));
// 'https://xposure.ae/wp-json/wp/auditorium/v1/events'));
if (response.statusCode == 200) {
var jsonString = response.body;
return eventFromJson(jsonString);
} else {
return null;
}
}
}
If you need more information please let me know.
you can try this:
ListView.builder(
reverse: true,
shrinkWrap: true,
physics: ClampingScrollPhysics(),
// itemCount: 1,
itemCount: 1,
itemBuilder: (context, index) {
var now = DateTime.now();
Datum? closestEvent;
eventController.event.value!.data!.forEach((element) {
var elementDate =
DateFormat('yyyy-MM-dd hh:mm').parse(element.eventStartDate);
if (closestEvent == null) {
if (elementDate.isAfter(now)) {
closestEvent = element;
}
} else {
var closestDate = DateFormat('yyyy-MM-dd hh:mm').parse(closestEvent!.eventStartDate);
if (elementDate.isAfter(now) && elementDate.isBefore(closestDate)) {
closestEvent = element;
}
}
});
return Column(
children: [
isAfter == true
? GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EventDetails(
event: closestEvent)));
},
child: EventTileMain(
closestEvent))
: Container()
],
);
});
you can simply make a widget function and remove your listview, like this:
Widget buildEventWidget(BuildContext context){
var now = DateTime.now();
Datum? closestEvent;
eventController.event.value!.data!.forEach((element) {
var elementDate =
DateFormat('yyyy-MM-dd hh:mm').parse(element.eventStartDate);
if (closestEvent == null) {
if (elementDate.isAfter(now)) {
closestEvent = element;
}
} else {
var closestDate = DateFormat('yyyy-MM-dd hh:mm').parse(closestEvent!.eventStartDate);
if (elementDate.isAfter(now) && elementDate.isBefore(closestDate)) {
closestEvent = element;
}
}
});
return Column(
children: [
isAfter == true
? GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EventDetails(
event: closestEvent)));
},
child: EventTileMain(
closestEvent))
: Container()
],
);
}
Related
The below given code in my response which I need to display in Listview builder, now I need the data of name which in inside result, how do i fetch it and display it in text?
{
"message": "sucess",
"error": false,
"code": 200,
"result": [
{
"id": 1,
"name": "Lab Report"
},
{
"id": 2,
"name": "News"
},
{
"id": 3,
"name": "X-ray"
},
{
"id": 8,
"name": "Blood Test"
}
],
"status": 200
}
And below is my model class of the response now I want the data which is inside of result and need to display in Listview builder
import 'dart:convert';
PostFromJson postFromJsonFromJson(String str) => PostFromJson.fromJson(json.decode(str));
String postFromJsonToJson(PostFromJson data) => json.encode(data.toJson());
class PostFromJson {
PostFromJson({
this.message,
this.error,
this.code,
required this.result,
this.status,
});
String? message;
bool? error;
int? code;
List<Result> result;
int? status;
factory PostFromJson.fromJson(Map<String, dynamic> json) => PostFromJson(
message: json["message"],
error: json["error"],
code: json["code"],
result: List<Result>.from(json["result"].map((x) => Result.fromJson(x))),
status: json["status"],
);
Map<String, dynamic> toJson() => {
"message": message,
"error": error,
"code": code,
"result": List<dynamic>.from(result.map((x) => x.toJson())),
"status": status,
};
}
class Result {
Result({
this.id,
this.name,
});
int? id;
String? name;
factory Result.fromJson(Map<String, dynamic> json) => Result(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
Use this model
class Response{
final String message;
final bool error;
final int code;
final List<Result> result;
final int status;
const Response({required this.message,required this.error, required this.code,required this.result,required this.status});
factory Response.fromJson(Map<String, dynamic> json) {
List<Result> data = [];
data = json["result"]
.map<Result>((json) => Result.fromJson(json))
.toList();
return Response(
message:json['message'],
error: json['error'],
code: json['code'],
result: data,
status: json['status']
);
}
}
class Result{
final int id;
final String name;
const Result({ required this.id,required this.name});
factory Result.fromJson(Map<String, dynamic> json) {
return Result(
id: json['code'],
name:json['name'],
);
}
}
and declare a variable
Response? responseData;
set the api response in the responseData as Response
responseData = Response.fromJson(jsonDecode(response.body));
You can access the name inside the result like this,
responseData.result[index].name
Listview builder will be
return Container(
child: Column(
children: [
ListView.builder(
shrinkWrap: true,
itemCount: responseData?.result.length,
itemBuilder: (context,index) =>options(context,index)
)
],
),
);
Widget options(BuildContext context, int index){
return Text(responseData.result[index].name);
}
final name = data['result'][0].name;
final id = data['result'][0].id;
There are a lot of resources available online on how to fetching data, parsing, modeling, and showing in the UI (from API).
Here's one official doc from Flutter: https://docs.flutter.dev/cookbook/networking/fetch-data
EDIT (after adding the model):
final response = await http.get("url");
final post = postFromJsonFromJson(response);
//Use list with ListView.builder(...)
final results = post.result; //List<Result>
You must be getting the data from model you created, you can use your model like this
class MyWidget extends StatelessWidget {
PostFromJson data;
MyWidget(this.data);
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: data.result.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: const Icon(Icons.list),
title: Text(data.result[index].id.toString()));
});
}
}
I am a newbie in the world of flutter and GetX package and I am trying to create a simple app using my API and I have only JSON API and a model how to create my controller and response data??
Here is my JSON response data from the API
{
"isSuccess": true,
"datacount": 77,
"data": [
{
"provinceID": 1,
"provinceNameEN": "Bangkok",
"geoID": 2
},
{
"provinceID": 2,
"provinceNameEN": "Samut Prakan",
"geoID": 2
}
],
"error": {
"code": null,
"messageToDeveloper": null,
"messageToUser": null
}
}
And this is my model
// To parse this JSON data, do
//
// final provicesModel = provicesModelFromJson(jsonString);
import 'dart:convert';
ProvicesModel provicesModelFromJson(String str) => ProvicesModel.fromJson(json.decode(str));
String provicesModelToJson(ProvicesModel data) => json.encode(data.toJson());
class ProvicesModel {
ProvicesModel({
this.isSuccess,
this.datacount,
this.data,
this.error,
});
bool isSuccess;
int datacount;
List<Datum> data;
Error error;
factory ProvicesModel.fromJson(Map<String, dynamic> json) => ProvicesModel(
isSuccess: json["isSuccess"],
datacount: json["datacount"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
error: Error.fromJson(json["error"]),
);
Map<String, dynamic> toJson() => {
"isSuccess": isSuccess,
"datacount": datacount,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"error": error.toJson(),
};
}
class Datum {
Datum({
this.provinceId,
this.provinceNameEn,
this.geoId,
});
int provinceId;
String provinceNameEn;
int geoId;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
provinceId: json["provinceID"],
provinceNameEn: json["provinceNameEN"],
geoId: json["geoID"],
);
Map<String, dynamic> toJson() => {
"provinceID": provinceId,
"provinceNameEN": provinceNameEn,
"geoID": geoId,
};
}
class Error {
Error({
this.code,
this.messageToDeveloper,
this.messageToUser,
});
dynamic code;
dynamic messageToDeveloper;
dynamic messageToUser;
factory Error.fromJson(Map<String, dynamic> json) => Error(
code: json["code"],
messageToDeveloper: json["messageToDeveloper"],
messageToUser: json["messageToUser"],
);
Map<String, dynamic> toJson() => {
"code": code,
"messageToDeveloper": messageToDeveloper,
"messageToUser": messageToUser,
};
}
This is my services
import 'package:dio/dio.dart';
class ProvinceService {
var dio = Dio();
Future<dynamic> provinceService() async {
return await dio.get(
'URL');
}
}
This is my Controller
class RegisterController extends GetxController {
var provicesList = <ProvicesModel>[].obs;
void fetchprovices() async {
ProvinceService request = ProvinceService();
request.provinceService().then((value) {
if (value.statusCode == 200) {
for (var item in value.data) {
<<< Have Error _TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable')>>>
provicesList.add(ProvicesModel.fromJson(item));
}
} else {
print('Backend error');
}
}).catchError((onError) {
printError();
});
}
}
This is my page response
class Register extends StatefulWidget {
const Register({Key? key}) : super(key: key);
#override
State<Register> createState() => _RegisterState();
}
class _RegisterState extends State<Register> {
#override
void initState() {
registerController.fetchprovices();
super.initState();
}
final registerController = Get.put(RegisterController());
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Expanded(child: GetX<RegisterController>(
builder: (controller) {
return ListView.builder(
itemCount: controller.provicesList.length,
itemBuilder: (context, index) {
return ListTile(
title: Text('${controller.provicesList[index].datacount}'),
subtitle: Text(
'${controller.provicesList[index].data[index].provinceNameEn}'),
);
},
);
},
))
],
),
);
}
}
Refer this for more info :-> getx_dio_example
/////
var provicesList = ProvicesModel().obs;
void fetchprovices() async {
ProvinceService request = ProvinceService();
request.provinceService().then((value) {
if (value.statusCode == 200) {
final response = ProvicesModel.fromJson(value.data);
provicesList.value = response;
} else {
print('Backend error');
}
}).catchError((onError) {
printError();
});
}
///
return ListView.builder(
itemCount: controller.provicesList.data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text('${controller.provicesList.datacount}'),
subtitle: Text(
'${controller.provicesList.data[index].provinceNameEn}'),
);
},
);
Occurs exception when I get the chapter list.
So how can I solve this problem?
Please help.
Here is my API response.
{
"success": 1,
"chapter": [
{
"chapter_id": "609cb13f497e3",
"chapter_name": "test",
"subject_id": "5e32874c714fa",
"medium_id": "5d15938aa1344",
"standard_id": "5d1594e283e1a",
"material": null,
"textbook": null,
"test_paper": null,
"test_paper_solution": null,
"subject_memory_map": null,
"active": "1"
}
]
}
The model class which I created in chapter_model.dart file.
// To parse this JSON data, do
//
// final chapterBySubjectModel = chapterBySubjectModelFromJson(jsonString);
import 'dart:convert';
ChapterBySubjectModel chapterBySubjectModelFromJson(String str) => ChapterBySubjectModel.fromJson(json.decode(str));
String chapterBySubjectModelToJson(ChapterBySubjectModel data) => json.encode(data.toJson());
class ChapterBySubjectModel {
ChapterBySubjectModel({
required this.success,
required this.chapter,
});
int success;
List<Chapter> chapter;
factory ChapterBySubjectModel.fromJson(Map<String, dynamic> json) => ChapterBySubjectModel(
success: json["success"],
chapter: List<Chapter>.from(json["chapter"].map((x) => Chapter.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"success": success,
"chapter": List<dynamic>.from(chapter.map((x) => x.toJson())),
};
}
class Chapter {
Chapter({
required this.chapterId,
required this.chapterName,
required this.subjectId,
required this.mediumId,
required this.standardId,
this.material,
this.textbook,
this.testPaper,
this.testPaperSolution,
this.subjectMemoryMap,
required this.active,
});
String chapterId;
String chapterName;
String subjectId;
String mediumId;
String standardId;
dynamic material;
dynamic textbook;
dynamic testPaper;
dynamic testPaperSolution;
dynamic subjectMemoryMap;
String active;
factory Chapter.fromJson(Map<String, dynamic> json) => Chapter(
chapterId: json["chapter_id"],
chapterName: json["chapter_name"],
subjectId: json["subject_id"],
mediumId: json["medium_id"],
standardId: json["standard_id"],
material: json["material"],
textbook: json["textbook"],
testPaper: json["test_paper"],
testPaperSolution: json["test_paper_solution"],
subjectMemoryMap: json["subject_memory_map"],
active: json["active"],
);
Map<String, dynamic> toJson() => {
"chapter_id": chapterId,
"chapter_name": chapterName,
"subject_id": subjectId,
"medium_id": mediumId,
"standard_id": standardId,
"material": material,
"textbook": textbook,
"test_paper": testPaper,
"test_paper_solution": testPaperSolution,
"subject_memory_map": subjectMemoryMap,
"active": active,
};
}
Method which i Created in api_manager.dart file.
Future<List<Chapter>> getChapterBySubject() async {
final chapterUrl =
'$baseUrl/subject/get_by_user_plan?user_id=609cab2cd5b6c&order_id=1620889722609cd07a601af469889697609cab2cd5b6c&standard_id=5d1594e283e1a&medium_id=5d15938aa1344';
final response = await http.get(Uri.parse(chapterUrl));
if (response.statusCode == 200) {
final chapterData = chapterBySubjectModelFromJson(response.body);
final List<Chapter> chapters = chapterData.chapter;
print(chapters);
return chapters;
} else {
return <Chapter>[];
}
}
And view as below in chapter_widget.dart file.
class _ChapterWidgetState extends State<ChapterWidget> {
late bool _loading;
var _chapters = <Chapter>[];
#override
void initState() {
super.initState();
_loading = true;
ApiManager().getChapterBySubject().then((chapters) {
setState(() {
_chapters = chapters;
_loading = false;
});
});
}
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: null == _chapters ? 0 : _chapters.length,
//itemCount: _chapters.length,
itemBuilder: (context, index) {
Chapter chapter = _chapters[index];
return Container(
padding: EdgeInsets.all(8),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: InkWell(
//child: Image.asset("assets/logos/listbackground.png"),
child: Text(chapter.chapterName),
),
),
),
);
});
}
}
It throws an Exception in Model Class in below line.
List<Chapter>.from(json["chapter"].map((x) => Chapter.fromJson(x))),
You set chapter as required but it seems API says it can be null. So, you should convert your parameters from required to nullable like this:
import 'dart:convert';
ChapterBySubjectModel chapterBySubjectModelFromJson(String str) => ChapterBySubjectModel.fromJson(json.decode(str));
String chapterBySubjectModelToJson(ChapterBySubjectModel data) => json.encode(data.toJson());
class ChapterBySubjectModel {
ChapterBySubjectModel({
this.success,
this.chapter,
});
int success;
List<Chapter> chapter;
factory ChapterBySubjectModel.fromJson(Map<String, dynamic> json) => ChapterBySubjectModel(
success: json["success"] == null ? null : json["success"],
chapter: json["chapter"] == null ? null : List<Chapter>.from(json["chapter"].map((x) => Chapter.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"success": success == null ? null : success,
"chapter": chapter == null ? null : List<Chapter>.from(chapter.map((x) => x)),
};
}
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)));
}
}
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(),
);
}