Map<string, string> argument - flutter

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

Related

Flutter & Dart : how to retrive map field data from firestore?

Maps key is dynamic key, so i cant set a class to use fromjson method,
Map<String, double> rating;
i set the data , it working;
data['rating'] = json.encode(this.rating);
i try to get data, not working;
rating = jsonDecode(json['rating']);
igot the error:
Expected a value of type 'Map<String, double>', but got one of type 'String'
how can i get the data as Map ?
json.encode turns it into a string. I believe you actually want to just do
data['rating'] = this.rating;
instead of
data['rating'] = json.encode(this.rating);
here is the solution;
i used this;
data['rating'] = FieldValue.arrayUnion([this.rating]);
instead of
data['rating'] = json.encode(this.rating);
or
data['rating'] = this.rating; //both not working
for getting data; (I don't like this solution, but worked)
var asd = json["rating"] as List;
Map qwee = asd[0];
String rtkey = qwee.keys.toList()[0].toString();
double rtvalue = qwee.values.toList()[0];
rating = {rtkey: rtvalue} ;

How do I create a Map of int and list?

I feel like I missed something, as this question seems so easy to answer. However, I haven't found anything on stack overflow or in the dart docs.
What I've tried:
var list = Map<int, List<int>>();
list[0] = [];
or
var list = Map<int, List<int>>();
list[0] = List<int> listOne;
The docs didn't help much:
https://dart.dev/guides/language/language-tour#maps
And a similar question doesn't seem to exist.
How can I solve this problem. Do I need to use a workaround?
Greetings.
Map of int and list
var listMapping = Map<int, List<int>>();
listMapping[0] = [];
listMapping[33] = [12, 0, 345, -23, 999999];
listMapping[45] = List<int>();
listMapping[45].add(101);
listMapping[45].add(109);
print(listMapping[33]);
// A map doesn't store things in a asequencial data structure e.g. List or array
// Hence it doesn't implement Iterable and hence it can not be traversed like below
/*for(List<int> list in listMapping){
print(list);
}*/
List of List
If the integer key in your case is just to store the index and will always be sequencial e.g. 0,1,2,3... then a better solution would be a List of a Lists
var myLists = List<List<int>>()
myLists.add([1,2,45,56,78]);
var aNewList = [22,33,44,55];
myLists.add(aNewList);
The first one looked fine
Im not sure if I am understanding you correctly, but your first attempt worked for me in the DartPad. I only renamed it to map, as it is a map which contains lists.
var map = Map<int, List<int>>();
map[0] = [];
You could also declare it as a final, as the variable itself doesn't get reassigned
final map = Map<int, List<int>>();
map[0] = [];
Give it a type annotation, if it helps you
final Map<int,List<int>> map = Map<int, List<int>>();
map[0] = [];
The second code snippet does not work
var list = Map<int, List<int>>();
//you cannot name a value you want to assign
list[0] = List<int> listOne;
Maybe this is what you were going for:
var list = Map<int, List<int>>();
final listOne = <int>[];
list[0] = listOne
Map literals
This is the way I would do it
final map = {0: []};
//or for added clarity
final Map<int,List<int>> map = <int,List<int>>{0: []};
Simple operations with the map and its keys (int) and values (List)
//assign new array to different keys
map[0] = [0,1,2,3,4];
map[2] = <int>[];
map[4] = <int>[0,3];
//remove all values with an array length smaller than two
map.removeWhere((key,value)=>value.length<2);
//remove value at key 0
map.remove(0);
//clear map
map.clear();
[NOTE] If you want to reassign a completely new map to map, you would have to declare it non final
Map<int, List<int>> map = Map<int, List<int>> ();
map[0] = [10,0];
map[1] = [];
Learn more about dart maps

Encoding polyline from List LatLng flutter dart

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 ] ) ;

How to retrieve a Map from a Map in dart efficiently?

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 variables and assign list of data to it using flutter

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>();