flutter/dart value from Map - flutter

I want to get a single value from a nested map.
In this case, the value of the postal_code: 52034
Map:
{plus_code: {compound_code: QW8C+JTA ExampleTown, ExampleCountry, global_code: 8FFGDSC+JTA},
results: [
{address_components: [{long_name: 31, short_name: 31, types: [street_number]},
{long_name: ExampleRoute, short_name: ExampleRoute, types: [route]},
{long_name: ExampleTown, short_name: ExampleTown, types: [locality, political]},
{long_name: ExampleCountry, short_name: DE, types: [country, political]},
{long_name: 52034, short_name: 52034, types: [postal_code]}
],
formatted_address: ExampleRoute 31, 52034 ExampleTown, ExampleCountry, geometry: {location: {lat: 12.345678, lng: 12.345678}, locati
maybe something like:
print(data["results"][0]["address_components"]...???..);

for (var i = 0; i < data["results"][0]["address_components"].length; i++) {
if(data["results"][0]["address_components"][i]["types"].toString() == "[postal_code]"){
print(data["results"][0]["address_components"][i]["long_name"].toString(););
}
}

Related

How to sort a list of objects when a button is clicked in flutter?

I am new to flutter and I am in need of some help.
I have a list of objects here.
List<ProductOrdered> myList = [product1, product2, product3];
This is how the three ProductOrdered objects looks like:
ProductOrdered product1 = ProductOrdered(
name: 'Caramida 16x16 chestie, rosu, chestie chestie chestie ',
price: '4.99',
supplierName: 'Dedeman Leroy Merlin',
nr: '12345678',
day: '08',
month: '02',
year: '2002',
total: '31.99',
category: 'Solide',
);
ProductOrdered product2 = ProductOrdered(
name: 'Ciment 16x16 chestie, rosu, chestie chestie chestie ',
price: '3.99',
supplierName: 'Dedeman',
nr: '21345678',
day: '09',
month: '02',
year: '2002',
total: '41.99',
category: 'Prafoase',
);
ProductOrdered product3 = ProductOrdered(
name: 'Tigla 16x16 chestie, rosu, chestie chestie chestie ',
price: '5.99',
supplierName: 'Leroy Merlin',
nr: '31245678',
day: '10',
month: '02',
year: '2002',
total: '51.99',
category: 'Acoperis',
);
And I would like to sort the elements in this list by their prices, when a button is clicked. First time the button is clicked I want to make it ascending, second time descending. However I got stuck at the first part.
I defined a method
_onSortPrice(list) {
setState(() {
list.sort((a, b) => a.price.compareTo(b.price));
});
}
And I called it when the button was clicked
TextButton(
onPressed: () {
_onSortPrice(myList);
},
Nothing happens when I click it. I tried to remove the SetState from the funcion or used just sort method outside the button to see if the page starts with the objects sorted, and it does.
Thanks for reading.
You have set the price as String in the model. So, convert the string to double in the comparision.
list.sort((a, b) => double.parse(a.price).compareTo(double.parse(b.price)));

Dart extension - The method 'xxx' isn't defined for the type 'xxx'

I've made this extension on an enumm which has a static function toSelectList(), but when I try to use the extension, the toSelectList() is not recognised. I have had this issue before in VSCode, so I understand the IDE may sometimes show a warning, but the warning should go away and this time it isn't. The only fix that has worked is to use the extension and not use the original enum being extended. My code:
The enum and extension (grocery_item_categories_enum.dart):
import 'package:vepo/src/presentation/widgets/form_widgets/select/common/card_select_list_item/card_select_list_item.dart';
enum GroceryItemCategoryEnum {
meat,
dairy,
baking,
condiments,
cooking,
confectionary,
dessert,
healthFood,
}
extension GroceryItemCategoryExtension on GroceryItemCategoryEnum {
static const items = {
GroceryItemCategoryEnum.meat:
CardSelectListItem(label: 'Meat', id: 1, iconCodePoint: 0xf814),
GroceryItemCategoryEnum.dairy:
CardSelectListItem(label: 'Dairy', id: 2, iconCodePoint: 0xf7f0),
GroceryItemCategoryEnum.baking:
CardSelectListItem(label: 'Baking', id: 3, iconCodePoint: 0xf563),
GroceryItemCategoryEnum.condiments:
CardSelectListItem(label: 'Condiments', id: 4, iconCodePoint: 0xf72f),
GroceryItemCategoryEnum.cooking:
CardSelectListItem(label: 'Cooking', id: 5, iconCodePoint: 0xe01d),
GroceryItemCategoryEnum.confectionary: CardSelectListItem(
label: 'Confectionary', id: 6, iconCodePoint: 0xf819),
GroceryItemCategoryEnum.dessert:
CardSelectListItem(label: 'Dessert', id: 7, iconCodePoint: 0xf810),
GroceryItemCategoryEnum.healthFood:
CardSelectListItem(label: 'Health Food', id: 8, iconCodePoint: 0xf787),
};
CardSelectListItem get item => items[this];
static List<CardSelectListItem> toSelectList() {
return const [
CardSelectListItem(label: 'Meat', id: 1, iconCodePoint: 0xf814),
CardSelectListItem(label: 'Dairy', id: 2, iconCodePoint: 0xf7f0),
CardSelectListItem(label: 'Baking', id: 3, iconCodePoint: 0xf563),
CardSelectListItem(label: 'Condiments', id: 4, iconCodePoint: 0xf72f),
CardSelectListItem(label: 'Cooking', id: 5, iconCodePoint: 0xe01d),
CardSelectListItem(label: 'Confectionary', id: 6, iconCodePoint: 0xf819),
CardSelectListItem(label: 'Dessert', id: 7, iconCodePoint: 0xf810),
CardSelectListItem(label: 'Health Food', id: 8, iconCodePoint: 0xf787),
];
}
}
Trying to use it:
import 'package:vepo/src/domain/constants/grocery_item_categories_enum.dart';
#override
List<Widget> createItemCategoriesFormWidgets({BuildContext context}) {
return [
VpSelectMultipleCards(listItems: GroceryItemCategoryEnum.toSelectList())
];
}
compile time error:
The argument type 'dynamic' can't be assigned to the parameter type 'List<CardSelectListItem>'.dart(argument_type_not_assignable)
The method 'toSelectList' isn't defined for the type 'GroceryItemCategoryEnum'.
Try correcting the name to the name of an existing method, or defining a method named 'toSelectList'.dart(undefined_method)
How do I use this extension method toSelectList() without the IDE showing an error.
You can declare static methods in an extension, but they are static on the extension itself.
You should therefore call toSelectList() on GroceryItemCategoryExtension and not on GroceryItemCategory.
Basic example on String:
void main() {
// print(String.getMyString());
// The method 'getMyString' isn't defined for the type 'String'
print(StringX.getMyString());
}
extension StringX on String {
static String getMyString() => "MyString";
}

Flutter Only valid value is 0: 1 If i remove the 'value':

I am simply splitting the values of string but it's showing the error
My code
List<Map<String, String>> divideString(String wording) {
final policies = wording.split('|').where((w) => w != '');
var displayData = <Map<String, String>>[];
policies.forEach((policy) {
final splited = policy.split('=');
final displayPolicy = <String, String>{
'name': splited[0],
'value': splited[1]
};
displayData.add(displayPolicy);
});
return displayData;
}
if I remove 'value': splited[1] its working fine I think in some places 'value': splited[1] is empty so maybe its showing error?
String something looks like this
I/flutter (14910): INPATIENT & DAYCARE||||||||||PRE-AUTHORIZATION=MANDATORY AT NON-PANEL HOSPITALS|||||HOSPITAL NETWORK=220+ FACILITIES NATIONWIDE|||||EMERGENCY HOTLINE NOS.=ROUND THE CLOCK|||||ACCIDENTAL EMERGENCIES=25% ENHANCEMENT IN AVAILABLE INPATIENT LIMITS|||||PRE-HOSPITALIZATION=30 DAYS BEFORE HOSPITALIZATION|||||POST-HOSPITALIZATION=30 DAYS AFTER HOSPITALIZATION|||||DAYCARE PROCEDURES=UNLIMITED|||||ICU CONFINEMENT=UNLIMITED|||||DENTAL TREATMENT=WHEN REQD. DUE TO ACCIDENT FOR PAIN RELIEF ONLY|||||LOCAL AMBULANCE=TO AND BETWEEN HOSPITALS|||||CATARACT SURGERY=COVERED WITH STANDARD FOLDABLE LENS ONLY|||||SPECIALIZED INVESTIGATIONS=COVERED e.g., CT Scan, MRI, ECHO etc.|||||VACCINATIONS=1ST DOSE COVERED AT BIRTH|||||MATERNITY BENEFITS||||||||||PRE / POST NATAL EXPENSES=10% OF MAT. or PKR 2,000/- WHICHEVER IS LESS|||||CIRCUMCISION BENEFIT=10% OF MAT. or PKR 2,000/- WHICHEVER IS LESS|||||DELIVERY BY MIDWIFE PKR.5000/-|||||SPECIAL BENEFITS||||||||||HEPATITIS TREATMENT=COVERED|||||CONGENITAL CONDITIONS=NOT COVERED|||||PRE EXISTI
What I am doing is break the line when this symbol shows "|" and split it when "=" symbol show but the issue is somewhere = sign isn't available
Try this:
List<Map<String, String>> divideString(String wording) {
List<String> policies = wording.split('|');
List<Map<String, String>> displayData = [];
policies.forEach((policy) {
final List<String> splited = policy.split('=');
// If an '=' sign is present, the length will be == 2
if(splited.length == 2){
final displayPolicy = <String, String>{
'name': splited[0],
'value': splited[1]
};
displayData.add(displayPolicy);
}
});
print('======= output, line by line =======');
displayData.forEach((item) => print(item));
print('\n');
print('======= returned data, unformatted =======');
print(displayData);
return displayData;
}
Output:
======= output, line by line =======
{name: PRE-AUTHORIZATION, value: MANDATORY AT NON-PANEL HOSPITALS}
{name: HOSPITAL NETWORK, value: 220+ FACILITIES NATIONWIDE}
{name: EMERGENCY HOTLINE NOS., value: ROUND THE CLOCK}
{name: ACCIDENTAL EMERGENCIES, value: 25% ENHANCEMENT IN AVAILABLE INPATIENT LIMITS}
{name: PRE-HOSPITALIZATION, value: 30 DAYS BEFORE HOSPITALIZATION}
{name: POST-HOSPITALIZATION, value: 30 DAYS AFTER HOSPITALIZATION}
{name: DAYCARE PROCEDURES, value: UNLIMITED}
{name: ICU CONFINEMENT, value: UNLIMITED}
{name: DENTAL TREATMENT, value: WHEN REQD. DUE TO ACCIDENT FOR PAIN RELIEF ONLY}
{name: LOCAL AMBULANCE, value: TO AND BETWEEN HOSPITALS}
{name: CATARACT SURGERY, value: COVERED WITH STANDARD FOLDABLE LENS ONLY}
{name: SPECIALIZED INVESTIGATIONS, value: COVERED e.g., CT Scan, MRI, ECHO etc.}
{name: VACCINATIONS, value: 1ST DOSE COVERED AT BIRTH}
{name: PRE / POST NATAL EXPENSES, value: 10% OF MAT. or PKR 2,000/- WHICHEVER IS LESS}
{name: CIRCUMCISION BENEFIT, value: 10% OF MAT. or PKR 2,000/- WHICHEVER IS LESS}
{name: HEPATITIS TREATMENT, value: COVERED}
{name: CONGENITAL CONDITIONS, value: NOT COVERED}
======= returned data, unformatted =======
[{name: PRE-AUTHORIZATION, value: MANDATORY AT NON-PANEL HOSPITALS}, {name: HOSPITAL NETWORK, value: 220+ FACILITIES NATIONWIDE}, {name: EMERGENCY HOTLINE NOS., value: ROUND THE CLOCK}, {name: ACCIDENTAL EMERGENCIES, value: 25% ENHANCEMENT IN AVAILABLE INPATIENT LIMITS}, {name: PRE-HOSPITALIZATION, value: 30 DAYS BEFORE HOSPITALIZATION}, {name: POST-HOSPITALIZATION, value: 30 DAYS AFTER HOSPITALIZATION}, {name: DAYCARE PROCEDURES, value: UNLIMITED}, {name: ICU CONFINEMENT, value: UNLIMITED}, {name: DENTAL TREATMENT, value: WHEN REQD. DUE TO ACCIDENT FOR PAIN RELIEF ONLY}, {name: LOCAL AMBULANCE, value: TO AND BETWEEN HOSPITALS}, {name: CATARACT SURGERY, value: COVERED WITH STANDARD FOLDABLE LENS ONLY}, {name: SPECIALIZED INVESTIGATIONS, value: COVERED e.g., CT Scan, MRI, ECHO etc.}, {name: VACCINATIONS, value: 1ST DOSE COVERED AT BIRTH}, {name: PRE / POST NATAL EXPENSES, value: 10% OF MAT. or PKR 2,000/- WHICHEVER IS LESS}, {name: CIRCUMCISION BENEFIT, value: 10% OF MAT. or PKR 2,000/- WHICHEVER IS LESS}, {name: HEPATITIS TREATMENT, value: COVERED}, {name: CONGENITAL CONDITIONS, value: NOT COVERED}]
modifiy your code like this to see where the problem is.
List<Map<String, String>> divideString(String wording) {
final policies = wording.split('|').where((w) => w != '');
var displayData = <Map<String, String>>[];
policies.forEach((policy) {
if(policy.contains('=')){
final splited = policy.split('=');
final displayPolicy = <String, String>{
'name': splited[0],
'value': splited[1]
};
displayData.add(displayPolicy);
}else{
print('no suitable data in ' + policy);
}
});
return displayData;
}

Leaflet Routing API: retrieve the legs data

I use the Leaflet Routing API, connected to Mapbox, to display a route with several waypoints.
Now, I have to retrieve the distance and the time between these waypoints for some calculations...
I see that the api.mapbox.com/directions API (called via Leaflet) receives as result an array of legs between my waypoints, and all data I need (legs'' distance and duration):
routes: [,…]
0: {legs: [{summary: "A 35, D 415", weight: 4813.6, duration: 4594.8,…},…], weight_name: "routability",…}
distance: 447598.9
duration: 22889.300000000003
legs: [{summary: "A 35, D 415", weight: 4813.6, duration: 4594.8,…},…]
0: {summary: "A 35, D 415", weight: 4813.6, duration: 4594.8,…}
distance: 101906.2
duration: 4594.8
steps: [{intersections: [{out: 0, entry: [true], bearings: [301], location: [7.761832, 48.592052]},…],…},…]
summary: "A 35, D 415"
1: {summary: "D 18bis, D 1bis", weight: 2070.1, duration: 1890.6,…}
distance: 28743.3
duration: 1890.6
steps: [{intersections: [{out: 0, entry: [true], bearings: [310], location: [7.538932, 47.928985]}],…},…]
summary: "D 18bis, D 1bis"
weight: 2070.1
2: {summary: "D 83, N 66", weight: 5097, duration: 4510.1,…}
...
I catch this result with a "routesfound" event, but I don't retrieve the legs from the result set:
{route: {…}, alternatives: Array(0), type: "routeselected", target: e, sourceTarget: e}
alternatives: []
route:
coordinates: (8188) [M, M, M, M, M, M, M, M, …]
inputWaypoints: (6) [e, e, e, e, e, e]
instructions: (104) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
name: "A 35, D 415, D 18bis, D 1bis, D 83, N 66, Rue du Ballon d'Alsace, D 465, La Comtoise, L'Alsacienne"
properties: {isSimplified: true}
routesIndex: 0
summary:
totalDistance: 447598.9
totalTime: 22889.300000000003
__proto__: Object
waypointIndices: (6) [0, 1611, 2100, 3485, 5808, 8187]
waypoints: (6) [e, e, e, e, e, e]
__proto__: Object
sourceTarget: e {options: {…}, _router: e, _plan: e, _requestCount: 1, _formatter: e, …}
target: e {options: {…}, _router: e, _plan: e, _requestCount: 1, _formatter: e, …}
type: "routeselected"
Is there a way to access the native result via Leaflet, or am I forced to do a duplicate call to the Mapbox API to bypass Leaflet ?
I have the same problem and I tried to get the response of the router. After digging into the code I found the _pendingRequest that hold the router XML HTTP request
ACTIVE_DAY_ROUTE = L.Routing.control({
show: false,
waypoints: routeWaypoints,
router: ROUTER,
routeWhileDragging: false,
draggableWaypoints: false,
lineOptions: {
styles: [{
color: ROUTE_COLOR,
opacity: ROUTE_OPACITY,
weight: 4
}]
},
createMarker: function() {
return null;
}
});
console.log(ACTIVE_DAY_ROUTE._pendingRequest.response);
I succeed to get it on console.log but can't get the response attribute (perhaps because it is pending or finished when I try to get the value)
UPDATE:
I hacked the _convertRoute method to include legs in it
var result = {
name: '',
coordinates: [],
instructions: [],
legs: '', // HACK HERE
summary: {
totalDistance: responseRoute.distance,
totalTime: responseRoute.duration
}
},
result.legs = responseRoute.legs; // HACK HERE - Affect leg

Map Reduce Mongodb Node JS native driver

I'm working with the Mongodb native driver using a Map reduce function. Basically I have a mediaId as a key and want to count how many medias loaded and started per mediaId.
So what I've done was:
var map = function(){
emit(this.media.id, {
count: 1,
played: 0,
ph: this.project.id,
title: this.media.title,
media: this.media.id,
origin: this.origin,
thumbnail: this.media.thumbnail,
mediaDuration: this.media.mediaDuration,
state: this.state
});
};
var reduce = function(k, vals) {
result = {
count: 0,
played: 0,
ph: '',
title: '',
media: '',
origin: '',
thumbnail: '',
mediaDuration: 0,
state: ''
};
vals.forEach(function(doc){
result.count += doc.count;
result.ph = doc.ph;
result.title = doc.title;
result.media = doc.media;
result.thumbnail = doc.thumbnail;
result.mediaDuration = doc.mediaDuration;
result.state = doc.state;
result.origin = doc.origin;
if(doc.state === "started") {
result.played += 1;
}
});
return result;
};
In my test collection I have 2 different mediaIds. One with 553 objects and another one with just 1 object. I've putted all in the "started" state to test this so basically the number of count should be equal to the number of played.
When I run the Map/Reduce function it returns to me ( I used the "toArray" function of the mongodb native driver):
[ { _id: '12398asdsa9802193810asd120',
value:
{ count: 1,
played: 0,
ph: '123213ased12231',
title: 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
media: '1xxxxxxxxxxxxxxxxxxxxxxxxxxx1',
origin: 'http://www.google.com',
thumbnail: 'http://cache.ohinternet.com/images/0/0e/Forever_Alone.png',
mediaDuration: 12321321,
state: 'started' } },
{ _id: '2c9f94b42f5b5114012f5b92ea430066',
value:
{ count: 553,
played: 155,
ph: '316',
title: 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
media: '2xxxxxxxxxxxxxxxxxxxxxxxxxxx2',
origin: 'http://localhost:9000/views/index.html',
thumbnail: null,
mediaDuration: null,
state: 'started' } } ]
It seems that one I have just one object the reduce function isn't called ( I did some tests with another collection with more than 100 mediaIds and the behavior was identical. Does anyone have an idea of what is wrong with that?
Thanks A LOT for your time,
Cheers.
I sort of solved the "issue".
I did the filter on the Map Function and not on the Reduce function. Something like this:
var map = function(){
if(this.media.state==="started") {
var played = 1;
}else{var played = 0;}
emit(this.media.id, {
count: 1,
played: played,
ph: this.project.id,
title: this.media.title,
media: this.media.id,
origin: this.origin,
thumbnail: this.media.thumbnail,
mediaDuration: this.media.mediaDuration,
state: this.state
});
};
Hope it helps anyone that is having the same "problem"