I have response from server:
[
[
"2014",
"01",
"01"
],
[
"2015",
"01",
"01"
],
[
"2016",
"01",
"01"
]
]
I want to convert them to List.
This is what I create:
final response = await _dio.get(
"api/v1/calendar/holidays");
List<dynamic> list = response.data;
List<String> calendarList = List();
var dateList =
list.map((i) => ((a) => calendarList.add(a.toString()))).toList();
return calendarList;
but this returns me list of strings. Any ideas?
var result = response.data
.map((e) => DateTime.parse('${e[0]}-${e[1]}-${e[2]}'))
.toList();
If response.data is the list you posted in your question this should work.
var dateList = response.data[0].map((l) => DateTime(l[0], l[1], l]2])).toList()
You might need
var dateList = jsonDecode(response.data)[0].map((l) => DateTime(l[0], l[1], l]2])).toList()
depending on what format response.data actually is.
Related
This is my code to make the call, a POST. Until now I only needed to send one product in each post.
But, I wanted to start sending my list of products in just one POST.
Future DadosPagamento() async {
await Future.delayed(const Duration(milliseconds: 200));
var headers = {'Authorization': 'Bearer Gns2DfakHnjd9id', 'Content-Type': 'application/json'};
var request = http.Request(
'POST', Uri.parse('http://appdnz.ddns/APP1/Products'));
request.body = json.encode(
[
{
"OrderState": "",
"LineID": "1",
"ClientID": idCliente,
"ProductReference": ref,
"Color": color,
"Size": size,
"Quantity": quantity,
"UnitPriceWithoutTax": precoSemTax,
"ShippingAmount": envioPreco,
"OrderReference": "",
"CarrierID": idTrans,
"Comments": comentario,
"ProductDescription": descricaoProd,
"ShippingName": envioNome,
},
],
);
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
} else {
print(response.reasonPhrase);
}
}
example of what i want to send
request.body = json.encode(
[
{
"Lineid" = "1",
"Reference"= "xpto",
"Quantity"= "1"
....
}
,
{
"Lineid" = "2",
"Reference" = "xpto2",
"Quantity" = "5"
...
}
,
{
"Lineid" = "3",
"Reference" = "xpto3",
"Quantity" = "6"
...
}
]
)
In the research I did, I realized that it might work if I create a list and put it in json.encode(list), I don't know if it's the best way or if there aren't any more ways.
Thanks
I have a Dart class that I am using as a node class for a tree data structure.
My goal here is to encode objects of this class and its child nodes recursively.
I have a toJson() method that takes the child Nodes List and calls jsonencode on them.
class Node{
String name;
Map<String, String> attributes;
List<Node> children = List<Node>();
Node(this.name, attributes) {
this.attributes = attributes;
this.children = List<Node>();
}
Node.fromJson(Map<dynamic,dynamic> _map) {
this.name = _map['name'];
this.children = new List<Node>();
this.attributes = _map['attributes'][0];
for(var i = 0; i < _map['children'].length;i++){
Node temp = new Node.fromJson(_map['children'][i]);
this.addChild(temp);
}
}
Map<String, dynamic> toJson() => {
'name': name,
'attributes': [attributes],
'children': [
...this.children.map(jsonEncode)
]
};
}
I have a unit test i created to test this functionality:
Node nodeMap = {
"name": "Name",
"attributes": [
{"#htag1": "tagval1"}
],
"children": [
{
"name": "NameChild1",
"attributes": [
{"#htag2": "tagval2"}
],
"children": []
},
{
"name": "NameChild2",
"attributes": [
{"#htag3": "tagval3"}
],
"children": []
}
]
};
UNode unodeInst = new UNode.fromJson(nodeMap);
// Act
var nodeCreate = nodeInst.toJson();
// Assert
expect(nodeCreate, equals(nodeMap));
Here is the output of my unit test
Expected: {
'name': 'Name',
'attributes': [{'#htag1': 'tagval1'}],
'children': [
{
'name': 'NameChild1',
'attributes': [{'#htag2': 'tagval2'}],
'children': []
},
{
'name': 'NameChild2',
'attributes': [{'#htag3': 'tagval3'}],
'children': []
}
]
}
Actual: {
'name': 'Name',
'attributes': [{'#htag1': 'tagval1'}],
'children': [
'{"name":"NameChild1","attributes":[{"#htag2":"tagval2"}],"children":[]}',
'{"name":"NameChild2","attributes":[{"#htag3":"tagval3"}],"children":[]}'
]
}
Which: at location ['children'][0] is '{"name":"NameChild1","attributes":[{"#htag2":"tagval2"}],"children":[]}' which expected a map
As you see its not encoding my object correctly.
I believe this is happening because when i reclusively call jsonencode this method returns a string that is placed into the children array.
I believe part of my problem is that i dont fully understand the d diffrence between jsonencode() and toJson().
It is my understanding that jsonencode() calls toJson().. but jsonencode() returns a string and toJson() returns a Map<String, dynamic>.. so i think what i want here is to call toJson() recursively and not jsonencode.
Does this sound correct?
But i cannot figure out how to do this on a list in this situation.
I have tried the following
...this.children.map(this.toJson())
but i get "The argument type 'Map<String, dynamic>' can't be assigned to the parameter type 'dynamic Function(Node)'"
...this.children.forEach((element) {element.toJson()})
but i get "Spread elements in list or set literals must implement 'Iterable'"
Does this mean i have to implement the Iterable interface in my class?
You're just using the map method incorrectly. Use the following instead.
[
...this.children.map((e) => e.toJson())
]
It's also unnecessary to use spread with a literal list or use this. You can simplify the code to just
children.map((e) => e.toJson()).toList()
I have a map like this
Map<String, bool> siSelectedDef = {"1": true, "2": true, "3": false};
I want to loop through the map and check for the key which has a value true, and I want to add those keys inside a List<Map<String, Object>> must
i.e
must contains
[
{
"si" : "1"
},
{
"si" : "2"
}
]
can anyone help me in this, Thanks!
Map<String, dynamic> data = {'a': true, 'b': false, 'c': true};
List<Map<String, dynamic>> _list = [];
data.forEach((key, value) {
if (value) {
_list.add({'si': key});
}
});
print(_list);
please check official doc for more detailed info and other stuffs you can do with Map
I'm trying to build a page showing Open Street Map with routes. I've set up the OSM, and the routes/polylines should be added through a list of LatLng objects (an object consisting of two doubles marking the latitude and longitude of points connected by a line). What I want to do is fetch the user's location, and then get the latitudes and longitudes of the path along the route from the user's location to some other location, through the use of the Graphhopper API.
JSON returned from the API is as follows:
{
"hints":{
"visited_nodes.average":"40.0",
"visited_nodes.sum":"40"
},
"info":{
"copyrights":[
"GraphHopper",
"OpenStreetMap contributors"
],
"took":5
},
"paths":[
{
"distance":689.229,
"weight":408.670174,
"time":496240,
"transfers":0,
"points_encoded":false,
"bbox":[
15.23345,
44.103858,
15.238698,
44.105704
],
"points":{
"type":"LineString",
"coordinates":[
[
15.238079,
44.103858
],
[
15.238369,
44.104135
],
[
15.238698,
44.104337
],
[
15.238349,
44.104658
],
[
15.238155,
44.104889
],
[
15.237904,
44.105114
],
[
15.237713,
44.105236
],
[
15.237051,
44.105388
],
[
15.236858,
44.105457
],
[
15.236894,
44.105388
],
[
15.236866,
44.105314
],
[
15.236739,
44.105209
],
[
15.235663,
44.104713
],
[
15.234928,
44.105129
],
[
15.234886,
44.105037
],
[
15.234913,
44.10476
],
[
15.234786,
44.10476
],
[
15.234449,
44.105039
],
[
15.23355,
44.105704
],
[
15.23345,
44.105639
]
]
},
"legs":[
],
"details":{
},
"ascend":2.619999408721924,
"descend":3.4739990234375,
"snapped_waypoints":{
"type":"LineString",
"coordinates":[
[
15.238079,
44.103858
],
[
15.23345,
44.105639
]
]
}
}
]
}
Basically, I need to create a list of LatLng objects from this JSON ( an example: [LatLng(15.236866, 44.105314), LatLng(15.23355, 44.105704)] ), but, sadly, I have no clue how to do this. Any help, advice or guidance would be greatly appreciated.
I've tried searching through the web and hacking some code together, but I'm afraid that it didn't prove to be of much help.
Future<Points> _fetchCoordinates() async {
final response = await http.get(
'https://graphhopper.com/api/1/route?point=44.1035042,15.2385878&point=44.105091,15.2318734&vehicle=foot&locale=hr&key=<API_KEY>&points_encoded=false&instructions=false',
);
if (response.statusCode == 200) {
return Points.fromJson(json.decode(response.body));
} else {
throw Exception('Error');
}
}
class Points {
List<List<double>> coordinates;
Points({this.coordinates});
factory Points.fromJson(Map<String, dynamic> json) => Points(
coordinates: List<List<double>>.from(json["paths"]["points"]
["coordinates"]
.map((x) => List<double>.from(x.map((x) => x.toDouble())))));
Map<String, dynamic> toJson() => {
"coordinates": List<dynamic>.from(
coordinates.map((x) => List<dynamic>.from(x.map((x) => x))))
};
}
class Routing extends StatelessWidget {
#override
Widget build(BuildContext context) {
return FutureBuilder<Points>(
future: _fetchCoordinates(),
builder: (context, snapshot) {
final List coordinates =
snapshot.hasData ? snapshot.data.coordinates : <LatLng>[];
if (snapshot.hasData) {
return MyCustomMap(
lat: 44.1035042,
lng: 15.2385878,
points: <List of LatLng objects, for example: [LatLng(41.234,
43.465)]>,
);
} else if (snapshot.hasError) {
return [...]
} else
return [...]
},
);
}
}
It appears that there's some error in my code; statement that's returned is located in the "else if (snapshot.hasError)" clause.
Define a LatLng class like this:
class LatLng {
double lat;
double lng;
LatLng(this.lat, this.lng);
}
then you can decode the json like this:
Map<String, dynamic> decoded = json.decode(j);
List<dynamic> co1 = decoded['paths'][0]['points']['coordinates'];
List<LatLng> coords = co1.map((pair) => LatLng(pair[0], pair[1])).toList();
You could still have a Points class that wrapped the List<LatLng>...
Given the following JSON string
[
{
"popular": []
},
{
"recommended": [
"privacy",
"security",
"IFTTT",
"mobile",
"location",
"Pocket",
"advertising",
"Instapaper",
"data",
"surveillance"
]
}
]
How would I go about converting this to List<Map<String, List<String>>> without overusing dynamic?
This is what I have currently:
response // List<dynamic>
.map((i) => (i as Map<String, dynamic>).map((String key, dynamic value) =>
MapEntry<String, List<String>>(key, List<String>.from(value))))
.toList();
This is about as minimal as I can get it - the static type is correctly List<Map<String, List<String>>> with only a bit of repetition with the as casts.
var typed = (response as List) //skip this `as` if it's already a List
.map((v) => (v as Map)
.map((k, v) => MapEntry<String, List<String>>(k, List.from(v))))
.toList();
Inference fills in the rest for you.