Reputation: 191
I have a list made up of maps in the following format below
List<dynamic> data = [];
data = [
{'name': 'Name', type: 'STRING',},
{'name': 'Age', type: 'INTEGER'},
{'name': 'Weight', type: 'FLOAT'},
{'name': 'IsMagic', type: 'BOOLEAN'},
];
I am trying to send it over the internet in JSON format by using the .toJson() but i keep getting the error
The method 'toJson' isn't defined for the type 'List'.
this was how i went about it
Future creatingTable() async {
var url = Uri.parse(
'https://us-central1-denance-cbf3f.cloudfunctions.net/api/create_table');
var response =
await http.post(
url,
body: data.toJson(),
headers: < String, String > {
'Content-Type': 'application/json; charset=UTF-8',
},
);
print(
'Response status: ${response.statusCode}');
print(
'Response body: ${response.body}');
}
how do i resolve the problem?
Upvotes: 0
Views: 2686
Reputation: 663
Actually the error says it all. List class doesn't have toJson
method defined in it. toJson
and fromJson
methods are functions that we define to regarding classes as developers. For example an entity like Car
can have these methods.
class Car {
final String brand;
Car({this.brand});
Map<String, dynamic> toJson() => {'brand': brand};
factory Car.fromJson(Map<String, dynamic> json) =>
Car(brand: json['brand']);
}
For your question's answer, if you want to pass the array directly as a json, what you can do is pass data to jsonEncode
function from dart:convert
and it will convert your array to json string. Usage: jsonEncode(data)
.
Upvotes: 0
Reputation: 16
Try to use jsonEncode from dart:convert
List<dynamic> data = [];
data = [
{'name': 'Name', 'type': 'STRING',},
{'name': 'Age', 'type': 'INTEGER'},
{'name': 'Weight', 'type': 'FLOAT'},
{'name': 'IsMagic', 'type': 'BOOLEAN'},
];
dynamic body = jsonEncode(data);
Upvotes: 0
Reputation: 519
You should import 'dart:convert'
and use jsonEncode(data)
:
import 'dart:convert';
Future creatingTable() async {
var url = Uri.parse(
'https://us-central1-denance-cbf3f.cloudfunctions.net/api/create_table');
var response =
await http.post(
url,
body: jsonEncode(data),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
},
);
print(
'Response status: ${response.statusCode}');
print(
'Response body: ${response.body}');
}
Upvotes: 1