I found some question to this issue but none of them were for flutter. Basically I'm saving double value data in firestore number format but when the number is rounded for example 130.00 it save it as an integer. Now how can I make it double when retrieving the data. I've got simple model class which populate the data from map but I'm struggling to make it double there
factory Tool.fromMap(Map<String, dynamic> toolData) {
if (toolData == null) {
return null;
}
final double length = toolData['length']; //<-- how to make it double here
final String name = toolData['name'];
...
return Tool(
length: length,
name: name
...);
}
The known approaches doesn't seems to work here like
toolData['length'].toDouble()
UPDATE
Actually it works.. It just doesn't show as an option in android studio
I think parse method of double class could be solution for this.
double.parse(toolData['length'].toString());
Related
I have a compress function like below, which has a return value List<int>
List<int> compressData() {
var stringBytes = utf8.encode(plainText);
return BZip2Encoder().encode(stringBytes);
}
then I want to encrypt the data with salsa20 from the package encrypt, but must be string data as input data, I've tried with toString() but it makes the data 2X bigger, how to solve the problem?
I'm having trouble extracting the values of the data received from the push notification:
Message data: {default: {"event":"text","id":"23Vlj0BwSA7xKtsf4IbFCHAIsNr"}}, where I tried a lot of .map methods etc. but I always get null values. Is there an easy approach to get the data from the message.data, so I can extract the value of the event key and the id value from the id key?
Can you try with the below code?
import 'dart:convert';
const rawJson =
'{"default": {"event":"text","id":"23Vlj0BwSA7xKtsf4IbFCHAIsNr"}}';
void parse() {
final value = json.decode(rawJson);
print(value['default']['event']);
print(value['default']['id']);
}
Output:
Thanks to #sanjay for the help, his solution wasn't working for me but it was close enough, only these 2 small changes worked:
NOTICE: Apart from #sanjay's answer I had to change json.decode to jsonDecode and I had to put a variable var instead of the constant value. I can understand the var and const, but I'm not sure about the jsonDecode method why I had to change it but it worked like this.
var value = jsonDecode(message.data['default']);
var event = value['event'];
var id = value['id'];
print(id);
Output:
23Vlj0BwSA7xKtsf4IbFCHAIsNr
Thanks for the help!
I have this Flutter bit of code here, which is a large String. It would be different every time, but the format would stay the same since it's a template:
"William\nWilliam description here...\n$^170^ usd" + Uuid().v4()
I want to extract the 170 part, and then convert it to interger, so I can remove it from list of ints. I have tried a lot of code, but it isn't working for a few reasons, one is I can't extract the actual number from the String between the ^ and ^, and then I can't convert it to interger. Here's the try function (incomplete).
deleteSumItem(item) {
final regEx = RegExp(r'\^\d+(?:\^\d+)?'); //not sure if this is right regex for the String template
final priceValueMatch = regEx.firstMatch(item); //this doesn't return the particular number extracted
_totalPrice.remove(priceValueMatch); //i get error here that it isn't a int
_counter = _counter - priceValueMatch; //then remove it from interger as int
}
The function would take that String ("William\nWilliam description here...\n$^170^ usd" + Uuid().v4()) template (the number would be different between the ^ ^, but the template is same), then convert it to interger and remove from list as int.
Try the following:
void main() {
RegExp regExp = RegExp(r'\^(\d+)\^');
String input = r"William\nWilliam description here...\n$^170^ usd";
String match = regExp.firstMatch(input).group(1);
print(match); // 170
int number = int.parse(match);
print(number); // 170
}
I have changed the RegExp so it does correctly capture the number in its own capture group. It looked like you got a little confused in the process of creating the RegExp but it could also be I am missing some details about the problem.
I am trying to convert a Firebase Timestamp to a DateTime to display in a text widget. This is all wrapped in a Streambuilder. The problem is that when I'm querying the data i don't know if there has been set a timestamp yet.
I have tried to try and catch multiple conversions but I always get an exception when I try to display the data.
startingString = DateFormat('kk:mm').format(snapshot.data['startingTime'].toDate());
this works fine if there is a timestamp in firebase but it fails if there is none.
Many thanks to everyone who can help me!!
It might just be a casting problem. Try this:
final timeStamp = snapshot.data['startingTime'] as TimeStamp;
var startingString = '--';
if (timeStamp == null) {
// null case
} else {
startingString = DateFormat('kk:mm').format(timeStamp.toDate());
}
try to add a field of type string and assign it a value of DateTime.now();
and then try to parse it using
var myTime = await DateTime.parse(snapshot.data['time']);
then format it.
I developed a app using flutter 1.0. The app works well on most android and ios phones. But I found there one android phone and one iphone can not open that app, just show the error message "type '_Smi' is not a subtype of type 'double'". Is there someone can tell me what's going on my app.
Error picture when open the flutter app:
It's hard to tell without the relevant piece of code, but in my case, this happened when trying to assign a double value from a Map. The solution was simply to call .toDouble on the value:
// myMap is a Map<String, dynamic>
double myDouble = myMap['mykey'].toDouble();
It used to work without the .toDouble(), but the _Smi error started happening one day.
_Smi stands for Small machine integers, according to Dart Cookbook
So basically you're getting an int and parsing it incorrectly.
I had the same problem and settled on this.
Try to replace this:
double myDouble = myMap['mykey'].toDouble();
To this:
double myDouble = double.parse(myMap['mykey'].toString());
this helped me to read json from another api.
double temp = weatherData['main']['temp'].toDouble();
when you are using firestore (from google firebase) and you are having fields in a document that are stored as number (only number available, so number is used for int, double, float, ...) - make sure that you use .toDouble() before assigning the field value of a document to a double field in your model class in dart.
Example:
final collectionReference =
FirebaseFirestore.instance.collection("Products");
final products = await collectionReference.get();
List productsDocuments = products.docs
.map((doc) => doc.data())
.toList();
items = Items.fromList(productsDocuments);
List<Item> items;
factory Items.fromList(docsFirebase) => Items(
items: List<Item>.from(docsFirebase.map((docFirebase) => Item(
itemName: docFirebase['item_name'],
variantId: docFirebase['variant_id'],
imageUrl: docFirebase['image_url'],
barcode: docFirebase['barcode'],
defaultPrice: docFirebase['default_price'].toDouble(),
lowStock: docFirebase['low_stock'],
optimalStock: docFirebase['optimal_stock']))));
}