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} ;
Related
i am building a calculator app although its working fine but i just want to make it look like this before its is been turn into mathematical expression:
how do i achieve something like this:
'5X4' = 20
instead of using the asterisk sign '5*4' = 20
like i want to be able to replace the string 'X' in background before it's been computed
i tried this code below:
final multiply = '5X4';
final computed = multiply.replaceAll('X','*');
final result = computed;
if i run the
print(result)
but if i try
print(int.parse(result));
the console print out
Uncaught Error: FormatException: 5*4
how do i fix this?
You can use expressions package. Here is an example:
String data = "12x2÷3-2+4";
data = data.replaceAll("x", "*");
data = data.replaceAll("÷", "/");
Expression expression = Expression.parse(data);
const evaluator = ExpressionEvaluator();
var r = evaluator.eval(expression, {});
print(r.toString()); // 10.0
You should try this approach.
final multiply = '5X4';
final computed = multiply.replaceAll('X','*');
final List<String> variable1 = computed.split('*');
final result = int.parse(variable1.first) * int.parse(variable1.last);
final lastResult = '$computed = $result';
print(lastResult);
Dartpad
I want to add calculation on Map dynamically using query string, as shown below. I will define variable:
Map<dynamic, dynamic> data= new Map();
data["qty"] = 12;
data["price"] = 18;
I want to write just like a string query like below
string string = "Content data["amount"] = data["qty"]*data["price"]";
I want to execute this string and it return Map values which I will add to data map code here, it is possible in flutter.
You can use this package
Math_expressions
And solve math expressions using string like the following
Parser p = Parser();
Expression exp = p.parse("(x^2 + cos(y)) / 3");
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>();