noob question. I'm new to dart/flutter but working on an app where I have to convert a List<LatLng> coordinates to a nested List<List<num>>. So that it can be encoded into a polyline using another helper function.
This is my error:
Error: The argument type 'List<LatLng>' can't be assigned to the parameter type 'List<List<num>>'.
This is where my List<LatLng> is being created from a List<PointLatLng>.
final List<PointLatLng> result =
await polylineGetter.getRouteBetweenCoordinates(
apiKEY,
_curLoc.latitude,
_curLoc.longitude,
geolocation.coordinates.latitude,
geolocation.coordinates.longitude,
);
final List<LatLng> polylineCoordinates = [];
for (var point in result) {
polylineCoordinates
.add(LatLng(point.latitude, point.longitude));
}
How can I convert this to a generic nested List to feed into this helper function from a different library? Below is an example of where I need to convert it with hardcoded values.
final coords = encodePolyline([[38.5, -120.2],[40.7, -120.95],[43.252, -126.453],]);
This is the function I need to use
encodePolyline(List<List<num>> coordinates, {int accuracyExponent = 5}) //encodes a list of coordinates into an encoded polyline stirng
Tried a few things with no luck but not exactly sure what to do. Thanks in advance!
Let's assume coordinates is the List
List<List<int>> result = coordinates.map( (data) => [ data.latitude , data.longitude ] ) ;
Related
I have a function that returns List But in my case I want to read and display float values. However, this function is a system function I can't update it.
My question is how to convert List to List?
This is the code:
characteristic.value.listen((event) async {
var bleData = SetupModeResponse(data: event);
});
Event is by default a List. When I try to declare data as List; I got List cannot assigned to List.
I would be very thankful if you can help me.
you can use the map method on list
like that:
List<int> intList = [1, 2, 3];
List<double> doubleList = intList.map((i) => i.toDouble()).toList();
You can learn more about dart list mapping here map method
This should also work:
List<int> ints = [1,2,3];
List<double> doubles = List.from(ints);
Yo can try this method and see if it works
List<int> num = [1,2,3];
List<double> doubles = List.from(num);
Try the following code:
List<double> doubleList = event.map((i) => i.toDouble()).toList()
List listFinal = [];
So listFinal have values from multiple list inside like below.
[["test: 111-333-5555", "test2: 222-333-4555"], ["test3: 555-333-2222"]]
How do I make this list so that it only extract numbers and separate with comma?
End result should be like
[1113335555, 2223334555, 5553332222]
I can think of trimming or regexp but not sure how to pull this off.
many thanks.
Try this
void main() {
List<String> numberList=[];
List<List<dynamic>> demoList=[["test: 111-333-5555", "test2: 222-333-4555"], ["test3: 555-333-2222"]];
for(int i=0;i<demoList.length;i++){
numberList.addAll(demoList[i].map((e) => e.toString().split(":")[1].replaceAll("-", "")).toList());
}
print(numberList.toString());
}
Here is an example to get you started. This doesn't handle things like malformed input strings. First step is to "flatten" the list with .expand, and then for each element of the flattened iterable use a regex to extract the substring. Other options might include using .substring to extract exactly the last 12 characters of the String.
You can see this in action on dartpad.
void main() {
final input = [
['test: 111-333-5555', 'test2: 222-333-4555'],
['test3: 555-333-2222']
];
final flattened = input.expand((e) => e); // un-nest the lists
// call extractNumber on each element of the flattened iterable,
// then collect to a list
final result = flattened.map(extractNumber).toList();
print(result);
}
final _numberRegExp = RegExp(r'.*: ([\d-]+)$');
int extractNumber(String description) {
var numberString = _numberRegExp.firstMatch(description).group(1);
return int.parse(numberString.replaceAll('-', ''));
}
Let's do this in a simple way.
List<List<String>> inputList = [
["test: 111-333-5555", "test2: 222-333-4555"],
["test3: 555-333-2222"]
];
List resultList = [];
print('Input List : $inputList');
inputList.forEach((subList){
subList.forEach((element){
var temp = element.split(' ')[1].replaceAll('-', '');
resultList.add(temp);
});
});
print('Output List : $resultList');
Here I have taken your list as inputList and stored the result in resultList.
For each element of inputList we get a sub-list. I have converted the elements of that sub-list into the needed format and added those into a List.
Happy Coding :)
I'm trying to assign a Map<string, string> argument to double. If that's even what I have to do. I have no idea how to work with this argument type. Here it is:
await sheet.values.map.column(3)
I'm using this to extract column #3 and all its values from a google sheet via gsheets. This is a nightmare to work with... Anybody know if there's another way to call the column? or if there's a way to convert the Map<string, string> to a single string containing only the values in the column ? In this case, they're coordinate values for longitude or latitude. I'm trying to call these values for plotting in Google maps. Here's the rest of my code:
Iterable markers = [];
var latstr = (sheet.values.map.column(3)); //latitude
var lngstr = (sheet.values.map.column(4)); //longitude
List<dynamic> names = [];
List<double> lat = [];
List<double> lng = [];
for (var i = 0; i < 10; i++) {
names.add(latstr);
lat.add(parse(await sheet.values.map.column(3)); //<--- I have no idea what I'm doing here. Trying to convert to double. very confused.
lng.add(await sheet.values.map.column(4));
}
to add to this, here's the full error:
The argument type 'Map<String, String>' can't be assigned to the
parameter type'double'.
here's how i'm pulling from google sheets:
const _spreadsheetId = 'xxxxxxxxxxxxxx';
final gsheets = GSheets(_credentials);
final ss = await gsheets.spreadsheet(_spreadsheetId);
var sheet = await ss.worksheetByTitle('xxxxxxxxxxxx');
As the document says await sheet.values.map.column(4) gives you a Map<String,String>, but lng is List<double>, so only doubles can be added to it but you are trying to asign a Map<String,String> which results in the error,
//try this to map the map into a map of doubles (mapception), if your okey with using Map instead of a list
Map<double,double> m = (await sheet.values.map.column(4)).map((key, value)=> MapEntry(double.parse(key), double.parse(value)));
parse will throw if it encounters a character which is not a digit
I have a map returned from json.decode of type Map<String,dynamic>
The dynamic part contains another map which I want to have in a separate variable. I managed to do that in the following way:
Map<DateTime, List<DayOffDto>> mapToReturn = Map();
Map<String, dynamic> responseBody = json.decode(
response.body,
reviver: _reviver,
);
if (responseBody == null) {
throw NoDataServerException();
}
responseBody.entries.forEach((element) {
Map map = element.value;
//map.values;
map.entries.forEach((element2) {
mapToReturn[element2.key] = element2.value;
});
});
//mapToReturn contains now the extracted map from responseBody
and the reviver function just does some converting for me
_reviver(dynamic key, dynamic value) {
if (key != null && value is Map && (key as String).contains("-")) {
var object = value;
final DayOffDto dayOffDto = DayOffDto.fromFirebase(
key_firebase: key as String,
parsedJson: value,
rota: rotaParam,
chosenYear: yearParam);
DateTime datetime = Helper.getDateTimeFromDayNumber(
dayOffDto.dayNumber,
dayOffDto.year,
);
Map<DateTime, List<DayOffDto>> internalMap = LinkedHashMap();
internalMap[datetime] = [dayOffDto];
return internalMap;
}
return value;}
I do not think it is the best way of extracting . Any idea for the optimized code?
responseBody.values returns Iterable<V>
so when I do
mapToReturn = responseBody.values i am getting an error
Working with Map can be hard sometimes. I would like to tell you that there is something as easy as mapToReturn = responseBody.values, but as of today, there is not (that I could find).
However, I can give you one small block of code that does the same as your first code block.
As you are not using the keys of your first map, instead of responseBody.entries you should use responseBody.values. So the code block would end up like this:
responseBody.values.forEach((value) {
return value is Map<DateTime, List<DayOffDto>>
? mapToReturn.addAll(value)
: null;
});
And if you are completely sure about the value Type (you should, as you are using a reviver) you can make it only one line of code.
responseBody.values.forEach((value) => mapToReturn.addAll(value));
I hope this can help you!
How to create dynamic variable and how to add list of key,value pair values to it ?(Please read added comments)
Map sample = Map(); // creating sample named dynamic variable
List<TechData> data = [
{"title": 'Android', "date": '10/01/2019'},
{"title": 'Flutter', "date": '10/01/2019'},
{"title": 'Java', "date": '30/10/2019'},
];
sample['Android'] = [{}]; // initializing the dynamic variable
for (var i = 0; i < data.length; i++) { // trying to add value using .add()
if (data[i].title == 'Android') {
sample['Android'].add(data[i]);
}
}
when adding a value using .add() it causing an error as below.
Exception has occurred.
TypeError (type 'TechData' is not a subtype of type 'Map' of 'value')
Can anyone please provide any solution to solve this error?
Map sample; // declared but not initialized
sample['Android'] = 'Android'; // gives you error
If you want to use sample just replace the declaration with below code:
Map sample = Map();
or
Map<String, dynamic> sample = Map<String, dynamic>();
Both approaches are the same, The only change is that the second approach takes only String as key while first takes anything as a key(dynamic).
Update:
The above map can be used as a storage for anything, since the value of the map remains dynamic. Any type of object can be passed as value to this map. Only concern is that when retrieving values make sure to cast it to the same object as the one passed as value.
e.g. :
map['numbers'] = [1,2,3,4]; // will work
map['strings'] = ['1','2','3','4']; // will work as well.
But when you retrieve the values, it will be as following:
var listOfNumbers = map['numbers'];
listOfNumbers will be a list make sure to cast it as int.
var listOfNumbers = map['numbers'].cast<int>();