Unable to load JSON data to show in ListView - json

I need to get the json array data in flutter app by providing the get method.
The problem that I am facing is that I am not able to put the records in the empty list carList.
but I am getting the array of objects as shown below(POSTMAN) by
print(json.decode(response.body)) // in the file cars.dart
Hence if you could please help me on how to get the response in the List carlist = [];
Car_list.dart file calls the method for the get request.
Please let me know if you require any further information from my end.
Thankyou
POSTMAN
[
{
"id": "1",
"carModel" : "Maruti swift",
"carDescription" : "The car has a top speed of 180 km/hr"
},
{
"id": "1",
"carModel" : "Hyundai santro",
"carDescription" : "The car has a top speed of 150 km/hr"
},
{
"id": "1",
"carModel" : "Hyundai creta",
"carDescription" : "The car has a top speed of 160 km/hr"
}
]
CarsModel.dart
class Cars with ChangeNotifier{
String userId;
String carModel
String carDescription;
Cars(
{
this.userId = '1111',
this.carModel,
this.carDescription,
}
);
factory Cars.fromJSON(Map<String,dynamic> json) => Cars(
userId : json['userId'],
carModel : json['CarModel'],
carDescription : json['carDescription'],
);
toJSON() {
return {
'userId':'111',
'carModel':carModel,
'carDescription' : carDescription
};
}
cars.dart
class CarProvider with ChangeNotifier{
List<Cars> carlist = [
//Sample data to show the format in which the data needs to be shown as the listview gets populated from below records which we are supposed to get from postman
//Cars (
// userid: 1111,
// carModel: 'Maruti Alto',
// carDescription: 'Top speed 140 km/hr'
),
];
Future<void> readListofCars(int id) async {
print(id.toString());
const url = 'http://localhost/userlist';
// {'id': id.toString()
Map<String, String> headers = {
"Content-type": "application/json"};
try
{
final response = await http.get(url,headers: headers);
List<dynamic> bodyCars = jsonDecode(response.body);
List<Cars> loadedCars = bodyCars.map((dynamic item) => new Cars.fromJSON(item)).toList();
/*
for (Map i in bodyCars) {
_notificationitems.add(Cars.fromJSON(i));
}
*/
});
print(response.statusCode);
carlist = loadedCars;
print(json.decode(response.body));
notifyListeners();
}catch (error){
throw error;
}
}
Car_list.dart
class TabScreenCar extends StatefulWidget {
final String userId;
TabScreenCar(this.userId);
#override
_TabScreenCarState createState() => _TabScreenCarState();
}
class _TabScreenCarState extends State<TabScreenCar> {
#override
void didChangeDependencies() {
final id = 1111;
Provider.of<CarProvider>(context).readListofCars(id);
super.didChangeDependencies();
}

In your model class you have incorrect variable to fetch the json data
to make the process simple you can have a look at this link
https://stackoverflow.com/a/58708634/9236994
just paste your json response in https://javiercbk.github.io/json_to_dart/
and use the json model class which will be generated.
your issue will be resolved.
variable which you are using doesn't match with your json response
OR to keep it simple
use below mentioned fromJSON method
factory Cars.fromJSON(Map<String,dynamic> json) => Cars(
userId : json['id'],
carModel : json['carModel'],
carDescription : json['carDescription'],
);
EDIT
I think you are facing issue with setting up the data in your list variable too.
use below shown code to fill the response into list if cars data
List<Cars> loadedCars = List<Cars>();
var data = jsonDecode(response.body);
data.forEach((val) {
loadedCars.add(Cars.fromJSON(val));
}

Related

How do I map a JSON map of list of map from API for HTTP get request

I keep getting this error:
NoSuchMethodError (NoSuchMethodError: The method 'map' was called on null.
Receiver: null
Tried calling: map(Closure: (dynamic) => Name1Name2))
I am trying very hard to solve this error. I am certain I am not mapping the data properly.
My fake REST API from which I'm fetching and sending the data to
"messagesBetweenTwoUsers": {
"Name1Name2": [
{
"senderName": "John",
"message": "How are you doing?"
}
]
}
This is my get messages file
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'messages_model.dart';
Future<List<MessageModel>> getMessages() async {
try {
var getResponse = await http.get(
Uri.parse("http://127.0.0.1:3000/messagesBetweenTwoUsers"),
);
if (getResponse.statusCode == 200) {
String getData = getResponse.body;
var jsonData =
jsonDecode(getData);
var getResult = jsonData["Name1Name2"].map(
(e) => Name1Name2.fromJson(e),
);
//here it throws me an error, in getResult, right when I am using map()
//NoSuchMethodError (NoSuchMethodError: The method 'map' was called on null.
//Receiver: null
//Tried calling: map(Closure: (dynamic) => Name1Name2))
return getResult;
} else {
return [];
}
} catch (error) {
debugPrint("ERROR IN FETCHING FROM GET-MESSAGE-API: $error");
}
return [];
}
My model class
import 'package:meta/meta.dart';
import 'dart:convert';
class MessageModel {
MessageModel({
required this.name1Name2,
});
final List<Name1Name2> name1Name2;
factory MessageModel.fromRawJson(String str) => MessageModel.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory MessageModel.fromJson(Map<String, dynamic> json) => MessageModel(
name1Name2: List<Name1Name2>.from(json["name1name2"].map((x) => Name1Name2.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"name1name2": List<dynamic>.from(name1Name2.map((x) => x.toJson())),
};
}
class Name1Name2 {
Name1Name2({
required this.senderName,
required this.message,
});
final String senderName;
final String message;
factory Name1Name2.fromRawJson(String str) => Name1Name2.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Name1Name2.fromJson(Map<String, dynamic> json) => Name1Name2(
senderName: json["senderName"],
message: json["message"],
);
Map<String, dynamic> toJson() => {
"senderName": senderName,
"message": message,
};
}
You need to learn null safety but let me tell you how to fix your current code. It is simple!
Put a question mark ? before calling .map(). You should do that everywhere. For example, this should be
jsonData["Name1Name2"].map( ......
like this
jsonData["Name1Name2"]?.map( ......
The question mark ? simply check if the value before it is null and return null if it is or process the rest if it isn't.
try it like this
if (getResponse.statusCode == 200) {
String getData = getResponse.body;
var jsonData =
await json.decode(getData);
var getResult = jsonData["Name1Name2"].map(
(e) => Name1Name2.fromJson(e),
);
return getResult;
} else {
return [];
}
dont forget to import 'dart:convert';
This error says you are accessing a key which is not found directly into the JSON data. Looking into your JSON data, you have the key Name1Name2 nested into the messagesBetweenTwoUsers key value. Therefore, in order to access the value of the Name1Name2 key you should call first the messagesBetweenTwoUsers key, like this:
var getResult = jsonData["messagesBetweenTwoUsers"]["Name1Name2"].map(
(e) => Name1Name2.fromJson(e),
);
EDITED:
Use this JSON model instead:
{
"participants": [
{
"senderName": "John",
"receiverName": "Jakiro",
"message": "How are you doing?"
}
]
}
And decode the JSON data like this:
var getResult = (jsonData['participants'] as List).map(
(e) => Name1Name2.fromJson(e),
).toList();
As you are looking/decoding the json is not right, so the following website will help you do it - quicktype. I highly encourage you to explore the website with different options.
As #Mayo Win said. You do need to learn Null Safety feature. Otherwise it make your code prone to error.
From your method getMessages() just call the following -
CustomDataModel customDataModel = customDataModelFromJson(response.bodyString ?? '');

How can I update/add new information to my local JSOn file in Flutter? (without creating any classes)

I made a small application, sort of like a library app where you can add books you've read. So, I have a local JSON file, which looks like this:
[
{
"name": "Harry Potter and the Deathly Hallows",
"author": "J.K. Rowling",
"rating": "4.5",
"category": "Fantasy",
"url": "some url"
},
{
"name": "For Whom The Bell Tolls",
"author": "E. Hemingway",
"rating": "4",
"category": "Novel",
"url": "some url#2"
}
]
In my main.dart file I have a function that reads my JSON file, decodes and loads it in a list named "data":
readData(){
DefaultAssetBundle.of(context).loadString("json/books.json").then((s){
setState(() {
data = json.decode(s);
});
});
}
#override
void initState() {
super.initState();
readData();
}
I can easily add new books to "data" and everything is fine except for one thing, - I don't know how to update/write information to JSON, so the app could show me the updated list with the new book after a restart. I've added. How do I do this? And what should I write into the JSON file, - the updated List with all books or just a Map with a new book?
Answer to NelsonThiago
This code is in "class AddingPageState extends State":
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/books.json');
}
Future<File> writeData(List list) async { // "list" is the updated book-list
final file = await _localFile;
String encodedData = jsonEncode(list);
return file.writeAsString('$encodedData');
}
And I call "writeData" in onPressed function.
It would be better to make this using a local NoSql database like sembast, this way you could add, delete and update your data. But as you are already working with json, You just need to encode your new changed data to json and write to the file again.
To write and read files, instead of using rootBundle read this read and write files.
As I can see from your JSON file, you are storing the Books as a list of JSON objects, which will make things easier.
But your request of solving this without adding new classes is a bit strange because adding a Book class in your case would make things much easier.
So I am going to give you a solution that assumes that you create a new Book class.
Start by reading the file as you are currently doing.
Store the content of the file in a List of dynamic List.
Iterate through the list using the map function, add using the from JSON function in the Book class decode the JSON to a book object, then apply the toList() function on that map.
Return the result to your UI and treat it as any other list.
When you want to add a new Book, create a new object of the book class and add it to your list.
When the user finishes adding, transform the list to a JSON object agian and store it in the file again;
Something like this:
The Book Class:
class Book {
String? name;
String? author;
String? rating;
String? category;
String? url;
Book({
required this.name,
required this.author,
required this.rating,
required this.category,
required this.url,
});
Book.fromJson(Map<String, dynamic> json) {
name = json['name'];
author = json['author'];
rating = json['rating'];
category = json['category'];
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['author'] = this.author;
data['rating'] = this.rating;
data['category'] = this.category;
data['url'] = this.url;
return data;
}
#override
String toString() {
return 'Book(name: $name, author: $author, rating: $rating, category: $category, url: $url)';
}
}
And main function
void main() {
/// read the file the way you like
List<dynamic> list = [
{
"name": "Harry Potter and the Deathly Hallows",
"author": "J.K. Rowling",
"rating": "4.5",
"category": "Fantasy",
"url": "some url"
},
{
"name": "For Whom The Bell Tolls",
"author": "E. Hemingway",
"rating": "4",
"category": "Novel",
"url": "some url#2"
}
];
List<Book> books = list
.map(
(jsonObject) => Book.fromJson(jsonObject),
)
.toList();
print(books);
Book newBook = Book(
name: 'Some Book',
author: 'Some Author',
rating: 'Some rating',
category: 'Some category',
url: 'Some Url');
books.add(newBook);
print(books);
books
.map(
(book) => book.toJson(),
)
.toList();
//Write the the file again to storage or anywhere else
}
See the following example. But it requires to create a class. The sample json file is like below (pretty much similar to your json file) -
[
{"name":"Ash","age":"22","hobby":"golf"},
{"name":"philip","age":"17","hobby":"fishing"},
{"name":"charles","age":"32","hobby":"drawing"},
]
And I am editing the above code answered by Ward Suleiman so that you can read from a local json file and write to it-
import 'dart:io';
import 'dart:convert';
List<Player> players = [];
void main() async{
print("hello world");
final File file = File('D:/Sadi/.../test.json'); //load the json file
await readPlayerData(file); //read data from json file
Player newPlayer = Player( //add a new item to data list
'Samy Brook',
'31',
'cooking'
);
players.add(newPlayer);
print(players.length);
players //convert list data to json
.map(
(player) => player.toJson(),
)
.toList();
file.writeAsStringSync(json.encode(players)); //write (the whole list) to json file
}
Future<void> readPlayerData (File file) async {
String contents = await file.readAsString();
var jsonResponse = jsonDecode(contents);
for(var p in jsonResponse){
Player player = Player(p['name'],p['age'],p['hobby']);
players.add(player);
}
}
And the Player class -
class Player {
late String name;
late String age;
late String hobby;
Player(
this.name,
this.age,
this.hobby,
);
Player.fromJson(Map<String, dynamic> json) {
name = json['name'];
age = json['age'];
hobby = json['hobby'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['age'] = this.age;
data['hobby'] = this.hobby;
return data;
}
}

Flutter : How to parse JSON Array of objects

Can anyone tell me how to parse arrays of object in flutter. When I am parsing the json I am getting error as List is not a subtype of type Map<String, dynamic>.
Below is my json file which needs to be parsed. Please help me to fix this issue.
[
{
"empPayslipsId": "2021012000440",
"month": "Jan",
"description": "Payslip for JAN 2021 (Month End)",
"paymentPeriod": "1/1/2021 12:00:00 AM - 1/31/2021 12:00:00 AM",
"lastAccessBy": "0002\r\n118.200.199.70",
"lastAccessDate": "20210202",
"lastAccessTime": "105706",
"successAccess": "2",
"failAccess": "2"
}
]
Future<void> loadQueryPeriod(int year, var month) async {
String baseURL = '${domainURL}api/PaySlip?year=$year&month=$month';
try {
final response = await http.get(baseURL, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization':
'Bearer ${Provider.of<UserVM>(navigatorKey.currentContext, listen: false).accessToken}',
});
print('UIC PDF response : ${response.body}');
print(
'UIC Token response : ${Provider.of<UserVM>(navigatorKey.currentContext, listen: false).accessToken}');
if (response.statusCode == 200) {
final Map<String, dynamic> data = json.decode(response.body);
print('result type: ${data.runtimeType}');
}
} catch (e) {
print(e);
throw Exception('Download PDF Fail! ${e.toString()}');
}
}
}
Change it to this:
final Map<String, dynamic> data = json.decode(response.body)[0];
This is because your map is inside a list. Look at the square brackets [ ] enclosing your map. The map that you need, is at index[0] of this list.
use this podo class :
// Generated by https://quicktype.io
// To parse this JSON data, do
//
// final sample = sampleFromJson(jsonString);
import 'dart:convert';
List<Sample> sampleFromJson(String str) {
final jsonData = json.decode(str);
return new List<Sample>.from(jsonData.map((x) => Sample.fromJson(x)));
}
String sampleToJson(List<Sample> data) {
final dyn = new List<dynamic>.from(data.map((x) => x.toJson()));
return json.encode(dyn);
}
class Sample {
String empPayslipsId;
String month;
String description;
String paymentPeriod;
String lastAccessBy;
String lastAccessDate;
String lastAccessTime;
String successAccess;
String failAccess;
Sample({
this.empPayslipsId,
this.month,
this.description,
this.paymentPeriod,
this.lastAccessBy,
this.lastAccessDate,
this.lastAccessTime,
this.successAccess,
this.failAccess,
});
factory Sample.fromJson(Map<String, dynamic> json) => new Sample(
empPayslipsId: json["empPayslipsId"],
month: json["month"],
description: json["description"],
paymentPeriod: json["paymentPeriod"],
lastAccessBy: json["lastAccessBy"],
lastAccessDate: json["lastAccessDate"],
lastAccessTime: json["lastAccessTime"],
successAccess: json["successAccess"],
failAccess: json["failAccess"],
);
Map<String, dynamic> toJson() => {
"empPayslipsId": empPayslipsId,
"month": month,
"description": description,
"paymentPeriod": paymentPeriod,
"lastAccessBy": lastAccessBy,
"lastAccessDate": lastAccessDate,
"lastAccessTime": lastAccessTime,
"successAccess": successAccess,
"failAccess": failAccess,
};
}
Now inorder to parse json call,
Sample sample = sampleFromJson(jsonString);
via this you will get the access to sample PODO class and you can access any object you want.
The initial data you received by calling a get request isn't stored in a map, but rather in a list.
You should do something like this to receive your initial data.
if (response.statusCode == 200) {
final List<dynamic> data = json.decode(response.body);
}
From there, they're numerous ways to get the data from your data variable. You can use lists here if you want, for example to get the value of month in the JSON.
final String month = data[0]['month'];
If you'd prefer to use Maps, the syntax it'll look like this
final Map<String, dynamic> endpointData = data[0];
final String responseKey = 'month';
final var result = endpointData[responseKey];
if you have data model you can do it like this
fromJsonList(List<dynamic> jsonList) {
List<YourModel> yourModelList = [];
jsonList.forEach((jsonModel) {
menuModelsOfferList.add(YourModel.fromJson(jsonModel));
});

How to decode large json array in flutter

I have a rather large json file that I have downloaded using my flutter app from a web api that's around 200MB using
final response = Dio().get(uri, options: Options(responseType: ResponseType.plain));
(Using default Dio options also uses json decoding, resulting in an out of memory exception.
This is not directly part of my problem but maybe it helps)
Now the problem starts after obtaining the json string.
When I use jsonDecode on the response body I run out of memory. (maybe the same function Dio uses?)
final data = jsonDecode(response.body); this runs out of memory
The json object itself is an array with a lot of items with a format like this:
[
{"data": {independent data1}},
{"data": {independent data2}},
...
]
and i would be fine just decoding one item at a time instead of everything at once to reduce memory usage. Is there another way to do process all the items in this array? Something like
jsonArrayDecode(response.body, onItemDecode: (item) { /*do stuff with item */ });
Or do I have to write my own json reader that can sequentially decode it?
Thanks to #pskink, I managed to solve my problem. I used the ResponseType.stream from Dio to get stream which can be processed using the reviver function argument from the JsonDecoder. I process all the data in the reviver and ignore the data in the onData function of the listener.
...
final response = await dio.get(uri,
options: Options(responseType: ResponseType.stream);
Function reviver = (key, value) {
if (/*value is element from top level list*/) {
processItem(value);
return null;
}
return value;
}
final completer = Completer();
response.data.stream.cast<List<int>>()
.transform(utf8.decoder)
.transform(JsonDecoder(reviver))
.listen(null, onDone: () { completer.complete(); });
await completer.future;
...
If the problem is really that the data file is very large, then the problem can be solved by not storing unnecessary objects during parsing.
This will only make sense if not all of the data is needed, but only some of the data.
In this case, we are talking about filtering data on the fly, that is, directly during the data parsing process.
Below is a small example of how this can be implemented.
import 'package:fast_json/fast_json_selector.dart' as parser;
import 'package:fast_json/fast_json_selector.dart' show JsonSelectorEvent;
void main(List<String> args) {
// Select users from the list by indexes [2..3] and terminate selection
final users = <User>[];
final level = '{} data [] 0 {}'.split(' ').length;
final elementLevel = '{} data [] 0'.split(' ').length;
void select(JsonSelectorEvent event) {
final levels = event.levels;
if (levels.length == level) {
final index = event.levels[elementLevel - 1] as int;
if (index >= 2 && index <= 3) {
final map = event.lastValue as Map;
final user = User.fromJson(map);
users.add(user);
}
// Free up memory
event.lastValue = null;
if (users.length == 2) {
throw const _TerminateException();
}
}
}
try {
parser.parse(_data, select: select);
} on _TerminateException {
//
}
print(users.join(', '));
}
const _data = '''
{
"success":true,
"data":[
{
"id":1,
"name":"Leanne Graham",
"username":"Bret",
"email":"Sincere#april.biz",
"address":{
"street":"Kulas Light",
"suite":"Apt. 556",
"city":"Gwenborough",
"zipcode":"92998-3874",
"geo":{
"lat":"-37.3159",
"lng":"81.1496"
}
},
"phone":"1-770-736-8031 x56442",
"website":"hildegard.org",
"company":{
"name":"Romaguera-Crona",
"catchPhrase":"Multi-layered client-server neural-net",
"bs":"harness real-time e-markets"
}
},
{
"id":2,
"name":"Ervin Howell",
"username":"Antonette",
"email":"Shanna#melissa.tv",
"address":{
"street":"Victor Plains",
"suite":"Suite 879",
"city":"Wisokyburgh",
"zipcode":"90566-7771",
"geo":{
"lat":"-43.9509",
"lng":"-34.4618"
}
},
"phone":"010-692-6593 x09125",
"website":"anastasia.net",
"company":{
"name":"Deckow-Crist",
"catchPhrase":"Proactive didactic contingency",
"bs":"synergize scalable supply-chains"
}
},
{
"id":3,
"name":"Clementine Bauch",
"username":"Samantha",
"email":"Nathan#yesenia.net",
"address":{
"street":"Douglas Extension",
"suite":"Suite 847",
"city":"McKenziehaven",
"zipcode":"59590-4157",
"geo":{
"lat":"-68.6102",
"lng":"-47.0653"
}
},
"phone":"1-463-123-4447",
"website":"ramiro.info",
"company":{
"name":"Romaguera-Jacobson",
"catchPhrase":"Face to face bifurcated interface",
"bs":"e-enable strategic applications"
}
},
{
"id":4,
"name":"Patricia Lebsack",
"username":"Karianne",
"email":"Julianne.OConner#kory.org",
"address":{
"street":"Hoeger Mall",
"suite":"Apt. 692",
"city":"South Elvis",
"zipcode":"53919-4257",
"geo":{
"lat":"29.4572",
"lng":"-164.2990"
}
},
"phone":"493-170-9623 x156",
"website":"kale.biz",
"company":{
"name":"Robel-Corkery",
"catchPhrase":"Multi-tiered zero tolerance productivity",
"bs":"transition cutting-edge web services"
}
},
{
"id":5,
"name":"Chelsey Dietrich",
"username":"Kamren",
"email":"Lucio_Hettinger#annie.ca",
"address":{
"street":"Skiles Walks",
"suite":"Suite 351",
"city":"Roscoeview",
"zipcode":"33263",
"geo":{
"lat":"-31.8129",
"lng":"62.5342"
}
},
"phone":"(254)954-1289",
"website":"demarco.info",
"company":{
"name":"Keebler LLC",
"catchPhrase":"User-centric fault-tolerant solution",
"bs":"revolutionize end-to-end systems"
}
}
]
}''';
class Company {
final String name;
Company({required this.name});
#override
String toString() {
return name;
}
static Company fromJson(Map json) {
return Company(
name: json['name'] as String,
);
}
}
class User {
final String city;
final int id;
final String name;
User({required this.city, required this.id, required this.name});
#override
String toString() {
return '$id:$name from $city';
}
static User fromJson(Map json) {
return User(
city: json['address']['city'] as String,
id: json['id'] as int,
name: json['name'] as String,
);
}
}
class _TerminateException {
const _TerminateException();
}

How to pass a list of json to body of http request (post) in Flutter?

I have objects that will filled by a user in a form. I parse these objects to json and add that json in a list to pass in body of request. But i cant do this.
incrementListPaymentSlipes(PaymentSlipes objPayment) async {
objPayment.name = "Douglas";
objPayment.personalId = "00000000000";
Map<String, dynamic> json = objPayment.toJson();
listPaymentSlipes.add(jsonEncode(json));
}
var response = await http.post(url, body: {
"payment_slips": listPaymentSlipes,
}
example of correct body:
"payment_slips": [
{
"personal_id": "01888728680",
"name": "Fulano da Silva"
}
]
{"error":"'{{personal_id: 00000000000, name: Douglas}}' é invalido como 'payment_slips'","code":"payment_slips_invalid"}```
You can do it in a very simple way. Create payment.dart file and copy paste the below code classes.
class PaymentList {
PaymentList(this.payments);
List<Payment> payments;
Map<String, dynamic> toJson() => <String, dynamic>{
'payment_slips': payments,
};
}
class Payment {
Payment({this.name, this.personalId});
String name;
String personalId;
Map<String, dynamic> toJson() => <String, dynamic>{
'personal_id': personalId,
'name': name,
};
}
Now you can covert it to the required json format using below code. For example I am creating a dummy list:
final PaymentList paymentList =
PaymentList(List<Payment>.generate(2, (int index) {
return Payment(name: 'Person $index', personalId: '$index');
}));
final String requestBody = json.encoder.convert(paymentList);
The requestBody variable will have the json string as follows:
{"payment_slips": [
{
"personal_id": "0",
"name": "Person 0"
},
{
"personal_id": "1",
"name": "Person 1"
}
]}
Now you can call the api:
var response = await http.post(url, body: requestBody}
Note: Please import the below package, which will be required to access json:
import 'dart:convert';
So it looks like you are not getting the JSON you expect. I have put together some code to show you how to get the body you want.
Link to run in DartPad https://dartpad.dartlang.org/3fde03078e56efe13d31482dea8e5eef
class PaymentSlipes {
String name;
String personaId;
ObjPayment({this.name, this.personaId});
//You create this to convert your object to JSON
Map<String, dynamic> toJson() => {'name': name, 'personaId': personaId};
}
// This method is needed to convert the list of ObjPayment into an Json Array
List encondeToJson(List<PaymentSlipes> list) {
List jsonList = List();
list.map((item) => jsonList.add(item.toJson())).toList();
return jsonList;
}
// This is an example and this code will run in DartPad link above
void main() {
PaymentSlipes objPayment = PaymentSlipes(name: "Douglas", personaId: "123425465");
PaymentSlipes objPayment2 = PaymentSlipes(name: "Dave", personaId: "123425465;
PaymentSlipes objPayment3 = PaymentSlipes(name: "Mike", personaId: "123425465");
var list = [objPayment, objPayment2, objPayment3];
// This is the mapping of the list under the key payment_slips as per your example and the body i would pass to the POST
var finalJson = {"payment_slips": encondeToJson(list)};
print(finalJson);
}