I'm trying to Integrate the API using model. Let say I have a book screen, so I'm trying to get its API data using model. my model looks like this.
class Book {
final int id;
final String phone;
final String name;
final String relation;
final String updated_at;
final String created_at;
final int userId;
Book(
{required this.id,
required this.name,
required this.phone,
required this.relation,
required this.created_at,
// required this.image,
required this.updated_at,
required this.userId,
});
factory Book.fromJson(Map<String, dynamic> json) => Book(
id: json['user_id'],
name: json['contact_person'],
relation: json['relation'],
phone: json['phone'],
updated_at: json['updated_at'],
created_at: json['created_at'],
userId: json['id']
);
Map<String, dynamic> toJson() => {
'user_id': userId,
'contact_person': phone,
'relation': relation,
'name': name,
'created_at':created_at,
'updated_at':updated_at,
'id':id,
};
}
calling this api like this
Future<List<Book>> getBook() async {
List<Book> _bookList =[];
Map<String, String> headers = {
"Content-type": "application/json",
'Authorization': 'Bearer $token',
};
var url = Uri.parse(ApiPath.getAllEmergenceyContactUrl);
final response = await http.get(url, headers: headers);
if (response.statusCode == 200) {
Map<String, dynamic> map = json.decode(response.body);
List<dynamic> data = map["user"];
if(data.length>0){
for(int i=0;i<data.length;i++){
if(data[i]!=null){
Map<String,dynamic> map=data[i];
_bookList.add(Book.fromJson(map));
debugPrint('Id-------${map['contact_person']}'); //this print the correct data
}
}
}
print(_bookList);
return _bookList;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
print(_bookList); this give me this output
[Instance of 'Book', Instance of 'Book']
and calling in User Interface like this
List<Book> books = [];
getAllEmergenceyContacts()async{
var books = await services.getBook();
}
i can't able to get the the when using the books in listview builder, please help me out.
my json data look like this
{
"status": 1,
"message": "your emergency contacts",
"user": [
{
"id": 10,
"user_id": 49,
"contact_person": "ABC",
"relation": "DSVKJDSB",
"phone": "sdfsdf",
"image": "emergency/1735686398652391.png",
"created_at": "2022-06-15T07:52:19.000000Z",
"updated_at": "2022-06-15T07:52:19.000000Z"
},
]}
and i want user array data from it.
I optimized your code and fix your problem. You can try it and tell me if have any problem
Model
import 'dart:convert';
Book bookFromJson(String str) => Book.fromJson(json.decode(str));
String bookToJson(Book data) => json.encode(data.toJson());
class Book {
Book({
this.status,
this.message,
this.user,
});
int status;
String message;
List<User> user;
factory Book.fromJson(Map<String, dynamic> json) => Book(
status: json["status"],
message: json["message"],
user: List<User>.from(json["user"].map((x) => User.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"message": message,
"user": List<dynamic>.from(user.map((x) => x.toJson())),
};
}
class User {
User({
this.id,
this.userId,
this.contactPerson,
this.relation,
this.phone,
this.image,
this.createdAt,
this.updatedAt,
});
int id;
int userId;
String contactPerson;
String relation;
String phone;
String image;
DateTime createdAt;
DateTime updatedAt;
factory User.fromJson(Map<String, dynamic> json) => User(
id: json["id"],
userId: json["user_id"],
contactPerson: json["contact_person"],
relation: json["relation"],
phone: json["phone"],
image: json["image"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"user_id": userId,
"contact_person": contactPerson,
"relation": relation,
"phone": phone,
"image": image,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
Call API
Future getBook() async {
Map<String, String> headers = {
"Content-type": "application/json",
'Authorization': 'Bearer $token',
};
var url = Uri.parse(ApiPath.getAllEmergenceyContactUrl);
final response = await http.get(url, headers: headers);
if (response.statusCode == 200) {
return bookFromJson(response.body).user;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
Calling in ui screen
List<Book> books = [];
getAllEmergenceyContacts()async{
books = await services.getBook();
setState((){});
}
Listview builder
ListView.builder(
itemCount: books.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(books[index].name),
);
},
),
print(_bookList); this gives you this output [Instance of 'Book', Instance of 'Book'] because you try to print every Book class instance
You declare List<Book> _bookList =[]; , where _bookList holds Book Class as a child.
At first, Fetch the books from API
List<Book> books = [];
getAllEmergenceyContacts()async{
var books = await services.getBook();
}
Then, you Should place all the books inside List view builder like the following way
ListView.builder(
itemCount: books.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(books[index].name),
);
},
),
Related
hello permission to ask I'm trying to get the API to then display and the response is 200 ok. but when I try to display it on the screen the following error occurs
this is a function to get data from API
Future<Datum> getPaketKuliah() async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
final response = await http.get(
Uri.parse(
'$url/auth/mhs_siakad/perwalian/get_paket',
),
headers: {
'Authorization': 'Bearer $token',
},
);
print(response.statusCode);
print(response.body);
if (response.statusCode == 200) {
return Datum.fromJson(jsonDecode(response.body));
} else {
throw Exception();
}
}
and I want to display it on the page using FutureBuilder
Container(
child: FutureBuilder<Datum>(
future: AuthProvider().getPaketKuliah(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.kelas);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
and lastly this is the model class I want to take to display on the
page
// To parse this JSON data, do
//
// final getPaket = getPaketFromJson(jsonString);
import 'dart:convert';
GetPaket getPaketFromJson(String str) => GetPaket.fromJson(json.decode(str));
String getPaketToJson(GetPaket data) => json.encode(data.toJson());
class GetPaket {
GetPaket({
required this.status,
required this.code,
required this.data,
});
String status;
String code;
Map<String, Datum> data;
factory GetPaket.fromJson(Map<String, dynamic> json) => GetPaket(
status: json["status"],
code: json["code"],
data: Map.from(json["data"])
.map((k, v) => MapEntry<String, Datum>(k, Datum.fromJson(v))),
);
Map<String, dynamic> toJson() => {
"status": status,
"code": code,
"data": Map.from(data)
.map((k, v) => MapEntry<String, dynamic>(k, v.toJson())),
};
}
class Datum {
Datum({
this.id,
this.idDosen,
this.idMk,
required this.nidn,
this.dosen,
this.idKelasKuliah,
this.kelasKuliah,
this.prodi,
this.kelas,
this.semester,
this.kelompokKelas,
required this.kode,
this.sks,
this.jumlahKelas,
this.matakuliah,
this.smt,
this.bobotSks,
this.rencanaPertemuan,
this.jenisEvaluasi,
required this.createdAt,
required this.updatedAt,
this.createdBy,
this.updatedBy,
});
String? id;
String? idDosen;
String? idMk;
dynamic nidn;
String? dosen;
String? idKelasKuliah;
String? kelasKuliah;
String? prodi;
String? kelas;
String? semester;
String? kelompokKelas;
dynamic kode;
int? sks;
int? jumlahKelas;
String? matakuliah;
String? smt;
int? bobotSks;
int? rencanaPertemuan;
String? jenisEvaluasi;
DateTime createdAt;
DateTime updatedAt;
String? createdBy;
String? updatedBy;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
idDosen: json["id_dosen"],
idMk: json["id_mk"],
nidn: json["nidn"],
dosen: json["dosen"],
idKelasKuliah: json["id_kelas_kuliah"],
kelasKuliah: json["kelas_kuliah"],
prodi: json["prodi"],
kelas: json["kelas"],
semester: json["semester"],
kelompokKelas: json["kelompok_kelas"],
kode: json["kode"],
sks: json["sks"],
jumlahKelas: json["jumlah_kelas"],
matakuliah: json["matakuliah"],
smt: json["smt"],
bobotSks: json["bobot_sks"],
rencanaPertemuan: json["rencana_pertemuan"],
jenisEvaluasi: json["jenis_evaluasi"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
createdBy: json["created_by"],
updatedBy: json["updated_by"],
);
Map<String, dynamic> toJson() => {
"id": id,
"id_dosen": idDosen,
"id_mk": idMk,
"nidn": nidn,
"dosen": dosen,
"id_kelas_kuliah": idKelasKuliah,
"kelas_kuliah": kelasKuliah,
"prodi": prodi,
"kelas": kelas,
"semester": semester,
"kelompok_kelas": kelompokKelas,
"kode": kode,
"sks": sks,
"jumlah_kelas": jumlahKelas,
"matakuliah": matakuliah,
"smt": smt,
"bobot_sks": bobotSks,
"rencana_pertemuan": rencanaPertemuan,
"jenis_evaluasi": jenisEvaluasi,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
"created_by": createdBy,
"updated_by": updatedBy,
};
}
and this is the json response
I highly recommend using library like json_serilizable to generate factory fromJson
factory Paket.romJson(Map<String, dynamic> json) => Paket(
status: json['status'] as String,
code: json['code'] as String,
data: (json['data'] as Map<String, dynamic>).map(
(k, e) => MapEntry(k, Datum.fromJson(e as Map<String, dynamic>)),
),
);
As provided api response corresponds to GetPaket class not Datum class you need to change getPaketKuliah method to
Future<Datum> getPaketKuliah() async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
final response = await http.get(
Uri.parse(
'$url/auth/mhs_siakad/perwalian/get_paket',
),
headers: {
'Authorization': 'Bearer $token',
},
);
print(response.statusCode);
print(response.body);
if (response.statusCode == 200) {
// --return Datum.fromJson(jsonDecode(response.body));
final paket = GetPaket.fromJson(jsonDecode(response.body));
// -- return Datum.fromJson(paket.data.entries.first.value);
return paket.data.entries.first.value;
} else {
throw Exception();
}
}
I have a two textfields; (body and user), which i want to parse their data to my json(nested). but the exception is being thrown instead
The snippet below is my JSON representation
{
"id": 27,
"user": {
"username": "admin"
},
"body": "Saturday morning",
"updated": "2022-07-30T06:48:53.009515Z",
"created": "2022-07-30T06:48:53.009515Z"
},
below is how i am sending the data
Future<Note> createNote(String body, String username) async {
final response = await http.post(
noteUrl,
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, dynamic>{
'body': body,
'user': username,
}),
);
if (response.statusCode == 201) {
return Note.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to create note');
}
}
this is where i am calling the function to send the data
ElevatedButton(
onPressed: () {
createNote(_bodyController.text, _userController.text);
Navigator.popAndPushNamed(context, '/');
},
child: Text('submit'),
)
Below snippet is my model class(flutter)
import 'dart:convert';
List<Note> noteFromJson(String str) =>
List<Note>.from(json.decode(str).map((x) => Note.fromJson(x)));
String noteToJson(List<Note> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Note {
Note({
this.id,
required this.body,
this.updated,
this.created,
this.user,
});
int? id;
String body;
DateTime? updated;
DateTime? created;
User? user;
factory Note.fromJson(Map<String, dynamic> json) => Note(
id: json["id"],
body: json["body"] as String,
updated: DateTime.parse(json["updated"]),
created: DateTime.parse(json["created"]),
user: User.fromJson(json["user"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"body": body,
"updated": updated?.toIso8601String(),
"created": created?.toIso8601String(),
"user": user?.toJson()
};
}
List<User> userFromJson(String str) =>
List<User>.from(json.decode(str).map((x) => User.fromJson(x)));
String userToJson(List<User> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class User {
User({
this.id,
required this.username,
this.password,
this.email,
});
String? id;
String username;
String? password;
String? email;
factory User.fromJson(Map<String, dynamic> json) => User(
id: json["id"],
username: json["username"],
password: json["password"],
email: json["email"],
);
Map<String, dynamic> toJson() => {
"id": id,
"username": username,
"password": password,
"email": email,
};
}
I am making a search in ListView.builder where data is coming in JSON data
I am not getting the error what it wants to say the searchmodel is not a subtype of type List.
or should I go with another approach to work with search in listview.builder
here is my model
import 'dart:convert';
SearchModel searchModelFromJson(String str) =>
SearchModel.fromJson(json.decode(str));
String searchModelToJson(SearchModel data) => json.encode(data.toJson());
class SearchModel {
SearchModel({
required this.data,
required this.meta,
});
final List<Datum> data;
final Meta meta;
factory SearchModel.fromJson(Map<String, dynamic> json) => SearchModel(
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
meta: Meta.fromJson(json["meta"]),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"meta": meta.toJson(),
};
}
class Datum {
Datum({
required this.id,
required this.attributes,
});
int? id;
Attributes? attributes;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
attributes: Attributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes?.toJson(),
};
}
class Attributes {
Attributes({
required this.name,
required this.mobile,
required this.createdAt,
required this.updatedAt,
required this.shopEmail,
required this.shopUniqueId,
});
String? name;
String? mobile;
String? createdAt;
String? updatedAt;
String? shopEmail;
String? shopUniqueId;
factory Attributes.fromJson(Map<String, dynamic> json) => Attributes(
name: json["name"],
mobile: json["mobile"],
createdAt: json["createdAt"],
updatedAt: json["updatedAt"],
shopEmail: json["shopEmail"],
shopUniqueId: json["shopUniqueId"],
);
Map<String, dynamic> toJson() => {
"name": name,
"mobile": mobile,
"createdAt": createdAt,
"updatedAt": updatedAt,
"shopEmail": shopEmail,
"shopUniqueId": shopUniqueId,
};
}
class Meta {
Meta();
factory Meta.fromJson(Map<String, dynamic> json) => Meta(
);
Map<String, dynamic> toJson() => {
};
}
here is my controller
class FetchSearch {
static Future<SearchModel> getUserList(String? query) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String? jwt = prefs.getString('jwt');
var response = await http.get(
Uri.parse(searchUrl),
headers: <String,String> {
'Authorization' : 'Bearer $jwt'
},
);
if (response.statusCode == 200) {
print(response.statusCode);
var stringResponse = response.body;
print(stringResponse);
return SearchModel.fromJson(jsonDecode(stringResponse));
// Map<String,dynamic> search = json.decode(response.body);
// print(search);
// List<dynamic> data = map["data"];
// return search.map((json) => Attributes.fromJson(json)).toList();
}
else {
throw Exception();
}
and here is my variables and init function
int _currentPage = 0, _index = 0;
List<SearchModel> searchItem = [];
String query = '';
Future init() async {
final users = await FetchSearch.getUserList(query);
setState(() => this.searchItem = users as List<SearchModel>);
}
hi stackers i have a problem with returning nested data in array object using flutter, the data has shown but i cant get what i want to get i have a response like this from my backend
"meta": {
"code": 200,
"status": "success",
"message": "Data list transaksi berhasil diambil"
},
"data": {
"current_page": 1,
"data": [
{
"id": 1,
"users_id": 1,
"invoice": "INV38972",
"seat_number": 2,
"total_price": 1000,
"payment_method": "TUNAI",
"status": "PENDING",
"items": [
{
"id": 1,
"menus_id": 1,
"transactions_id": 1,
"quantity": 5,
"menus": {
"id": 1,
"name": "Adidas NMD",
"price": 200,
"description": "Ini adalah sepatu sport",
"categories_id": 1,
}
}
]
}
],
}
}
response above is from my backend that success fully return in my response print() in flutter but i want to get the nested data in items.menus its return error Class'_InternalLinkedHashMap<String, dynamic>'has no instance getter 'menus'
for better understanding my question ill provide full model, provider and my services
this is my service getOrderList() function that i call in the futureBuilder
var url = '$baseUrl/transaction';
var headers = {
'Content-type': 'application/json',
'Authorization': 'Bearer ${userModel.token}'
};
var response = await http.get(Uri.parse(url), headers: headers);
// print(response.body);
// print('berhasil get kategori');
if (response.statusCode == 200) {
List data = json.decode(response.body)['data']['data'];
List<TransactionModel> transaction = [];
for (var item in data) {
transaction.add(TransactionModel.fromJson(item));
}
// print(transaction);
return transaction;
} else {
throw Exception('Gagal get Categori');
}
}
and this is my model code
class TransactionModel {
int id;
int users_id;
String invoice;
int seat_number;
double total_price;
String payment_method;
String status;
List items;
// List menu;
TransactionModel({
this.id,
this.users_id,
this.invoice,
this.seat_number,
this.total_price,
this.payment_method,
this.status,
this.items,
// this.menu,
});
TransactionModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
users_id = json['users_id'];
invoice = json['invoice'];
seat_number = json['seat_number'];
total_price = double.parse(json['total_price'].toString());
payment_method = json['payment_method'];
status = json['status'];
items = json['items'];
// menu = json['items']['menus'];
}
Map<String, dynamic> toJson() {
return {
'id': id,
'users_id': users_id,
'invoice': invoice,
'seat_number': seat_number,
'items': items,
'total_price': total_price,
'payment_method': payment_method,
'status': status,
// 'menu': menu,
};
}
}
i already change the model data and try much method but its still not working, thats all on my code what should i do to call items.menus in result ?
It seems to be a problem within the model, you can use a json to dart to make model class from raw json. Keep the fetching logic as it is.
Json
{
"id": 1,
"users_id": 1,
"invoice": "INV38972",
"seat_number": 2,
"total_price": 1000,
"payment_method": "TUNAI",
"status": "PENDING",
"items": [
{
"id": 1,
"menus_id": 1,
"transactions_id": 1,
"quantity": 5,
"menus": {
"id": 1,
"name": "Adidas NMD",
"price": 200,
"description": "Ini adalah sepatu sport",
"categories_id": 1
}
}
]
}
Model class
// To parse this JSON data, do
//
// final transactionModel = transactionModelFromMap(jsonString);
import 'dart:convert';
class TransactionModel {
TransactionModel({
this.id,
this.usersId,
this.invoice,
this.seatNumber,
this.totalPrice,
this.paymentMethod,
this.status,
this.items,
});
final int id;
final int usersId;
final String invoice;
final int seatNumber;
final int totalPrice;
final String paymentMethod;
final String status;
final List<Item> items;
factory TransactionModel.fromJson(String str) => TransactionModel.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory TransactionModel.fromMap(Map<String, dynamic> json) => TransactionModel(
id: json["id"],
usersId: json["users_id"],
invoice: json["invoice"],
seatNumber: json["seat_number"],
totalPrice: json["total_price"],
paymentMethod: json["payment_method"],
status: json["status"],
items: List<Item>.from(json["items"].map((x) => Item.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"id": id,
"users_id": usersId,
"invoice": invoice,
"seat_number": seatNumber,
"total_price": totalPrice,
"payment_method": paymentMethod,
"status": status,
"items": List<dynamic>.from(items.map((x) => x.toMap())),
};
}
class Item {
Item({
this.id,
this.menusId,
this.transactionsId,
this.quantity,
this.menus,
});
final int id;
final int menusId;
final int transactionsId;
final int quantity;
final Menus menus;
factory Item.fromJson(String str) => Item.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Item.fromMap(Map<String, dynamic> json) => Item(
id: json["id"],
menusId: json["menus_id"],
transactionsId: json["transactions_id"],
quantity: json["quantity"],
menus: Menus.fromMap(json["menus"]),
);
Map<String, dynamic> toMap() => {
"id": id,
"menus_id": menusId,
"transactions_id": transactionsId,
"quantity": quantity,
"menus": menus.toMap(),
};
}
class Menus {
Menus({
this.id,
this.name,
this.price,
this.description,
this.categoriesId,
});
final int id;
final String name;
final int price;
final String description;
final int categoriesId;
factory Menus.fromJson(String str) => Menus.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Menus.fromMap(Map<String, dynamic> json) => Menus(
id: json["id"],
name: json["name"],
price: json["price"],
description: json["description"],
categoriesId: json["categories_id"],
);
Map<String, dynamic> toMap() => {
"id": id,
"name": name,
"price": price,
"description": description,
"categories_id": categoriesId,
};
}
I am having this type of response from API
{
"success": 1,
"data": [
{
"id": 539,
"user_id": 3115,
"amount": 5788,
"payment_gateway": "bank",
"message": "chchhb",
"status": "waiting",
"source": "everyone",
"created_ts": "2019-12-19 13:41:17",
"processed_ts": null
},
]
}
this is my model.dart
class Model {
final String status;
final List<String> data;
Model({
this.status,
this.data
});
factory Model.fromJson(Map<String, dynamic> parsedJson) {
var data = parsedJson['data'];
List<String> dataList = data.cast<String>();
return Model(
status: parsedJson['status'],
data: dataList
);
}
}
This is how I am fetching data from the model
Future<List<String>> getWithdrawals() async {
final userModel = Provider.of<UserModel>(context);
var userId = userModel.user.id;
Map<String, String> requestHeaders = {'Content-type': 'application/json'};
var body = {
'id': userId,
};
final response = await http.post(url);
if (response.statusCode == 200){
var jsonresponse = json.decode(response.body);
var withdrawals = WithdrawalModel.fromJson(jsonresponse);
return withdrawals.data;
} else {
print("Error" + response.body);
return null;
}
}
I am not able to display the data on the screen It is giving me an error like
type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' in typecast
In FutureBuilder<List> I am not able to get data
I don't know where I am doing a mistake Please help...
I think your response type is not correct currently it's List<String> but it should be like List<Details> and you need to create another model class named Details (Or you can change the name).
You just put your response here. It will generate dart class models for you.
NOTE: you have to remove extra comma from your response to use model generator then your response will be like.
{
"success": 1,
"data": [
{
"id": 539,
"user_id": 3115,
"amount": 5788,
"payment_gateway": "bank",
"message": "chchhb",
"status": "waiting",
"source": "everyone",
"created_ts": "2019-12-19 13:41:17",
"processed_ts": null
}
]
}
Edit:
For example in your above model just change List type string to Details(Model) and vise-versa :
class Model {
final String status;
final List<Details> data; // Update string with model
}
Try this method
Future <PaymentReply> getPayment() async {
final userModel = Provider.of<UserModel>(context);
var userId = userModel.user.id;
try {
final response = await http.post(url,
headers: {
HttpHeaders.contentTypeHeader: "application/json"
},
body: '{\'id\':\''+ userId+'\'}', // You are not sending body in your code so check if it needs to be sent.
);
print(response.body); //CHECK IF THIS IS CORRECT RESPONSE AS EXPECTED
PaymentReply reply = paymentReplyFromJson(response.body);
return reply;
}on Exception catch (e){
print(e);
return PaymentReply();
}
}
with my modal
// To parse this JSON data, do
//
// final paymentReply = paymentReplyFromJson(jsonString);
import 'dart:convert';
PaymentReply paymentReplyFromJson(String str) => PaymentReply.fromJson(json.decode(str));
String paymentReplyToJson(PaymentReply data) => json.encode(data.toJson());
class PaymentReply {
int success;
List<Datum> data;
PaymentReply({
this.success,
this.data,
});
factory PaymentReply.fromJson(Map<String, dynamic> json) => PaymentReply(
success: json["success"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"success": success,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
int id;
int userId;
int amount;
String paymentGateway;
String message;
String status;
String source;
String createdTs;
String processedTs;
Datum({
this.id,
this.userId,
this.amount,
this.paymentGateway,
this.message,
this.status,
this.source,
this.createdTs,
this.processedTs,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
userId: json["user_id"],
amount: json["amount"],
paymentGateway: json["payment_gateway"],
message: json["message"],
status: json["status"],
source: json["source"],
createdTs: json["created_ts"],
processedTs: json["processed_ts"],
);
Map<String, dynamic> toJson() => {
"id": id,
"user_id": userId,
"amount": amount,
"payment_gateway": paymentGateway,
"message": message,
"status": status,
"source": source,
"created_ts": createdTs,
"processed_ts": processedTs,
};
}
My model was incorrect.
Solved by this model...
class WithdrawalModel {
final String status;
final String amount;
final List<Data> data;
WithdrawalModel({
this.status,
this.amount,
this.data
});
factory WithdrawalModel.fromJson(Map<String, dynamic> parsedJson) {
var list = parsedJson['data'] as List;
List<Data> dataList = list.map((i) => Data.fromJson(i)).toList();
return WithdrawalModel(
status: parsedJson['status'],
amount: parsedJson['amount'],
data: dataList
);
}
}
class Data {
int id;
int amount;
String message;
String status;
String source;
String createdTs;
Data({
this.id,
this.amount,
this.message,
this.status,
this.source,
this.createdTs
});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
amount = json['amount'];
message = json['message'];
status = json['status'];
source = json['source'];
createdTs = json['created_ts'];
}
}