I want to have two pieces of data that can be addressed in the map section.
Take the information from some TextFields and put it in List<double> so that the List can be called somewhere else like down for x,y:
spots: myValues.asMap().entries. map(([x,y]) {
return FlSpot(x.value, y.value);
}).toList(),
But it gives this error for X
Error: The parameter 'x' can't have a value of 'null' because of its type 'MapEntry<int, double>', but the implicit default value is 'null'
which can receive two data from the user in two separate controls in the TextField :
late List<double> myValues = [
double.parse(fieldXController.text),double.parse(fieldYController.tex)];
I have just started working in this field and I appreciate your help.
Try to store in Map with key as x, and value as y.
Your myValues should be as following,
late Map<double, double> myValues =
<int, double>{double.parse(fieldXController.text), double.parse(fieldYController.text)};
and in usage
spots: myValues.entries.map((entry) {
return FlSpot(entry.key, entry.value);
}).toList(),
if you want to add more entries
myValues[double.parse(fieldXController.text)] = double.parse(fieldYController.text);
Related
I have stored in shared_preferences key value pairs like below....
item_001 = 'some data'
item_103 = 'some data'
item_007 = 'some data'
item_059 = 'some data'
I am trying get all the stored values begins with item_***
I know how to read and write with single key (example below)... but I am trying to get a list of items from shared_preferences where the key name begins with item_.
string
read: final myString = prefs.getString('my_string_key') ?? '';
write: prefs.setString('my_string_key', 'hello');
stringList
read: final myStringList = prefs.getStringList('my_string_list_key') ?? [];
write: prefs.setStringList('my_string_list_key', ['horse', 'cow', 'sheep']);
due to some reason, I don't want to store all the items in one list.... I want to store each item with separate key.
I searched in google and in stackoverflow, unfortunately no where found proper answer....
also I looked into this one, but not understood how to implement partial key search...
esetintis got to this first but I doodled this code so I guess I'll share it. But yes, you have to first get all of the keys in the shared preferences and then get the value for matching keys.
SharedPreferences prefs = await SharedPreferences.getInstance();
Set<String> keys = prefs.getKeys().where((key)=>key.startsWith('item_'));
for (String key in keys) {
String value = prefs.getString(key); // Throws an error if you store something other than a String
// Do your thing
}
I don't think there is a way to make such query. However, you can tackle the issue with some extra steps.
1 step :
Get all keys from SharedPreferences with prefs.getKeys() method. This will return a Set of keys. Now you can assign a List<String> keys = prefs.getKeys().where((k)=>k.startsWith('item_')) which will have the keys you want to get from the Storage.
2nd :
Iterate the filtered array and get the values you want by calling SharedPreferences, and save them to some variable.
Assuming that you have all the keys in a list, for example:
List<String> keys = ['item_001', 'item_103', 'item_007', 'item_059', 'other_key', 'blablabla'];
Now, you could iterate through all of them and checking the ones that starts with "item_", like this:
var itemKeys = [];
for(var i=0;i<keys.length;i++){
if (keys[i].startsWith('item_')) {
itemKeys.add(keys[i]);
}
}
print(itemKeys); // [item_001, item_103, item_007, item_059]
In the above example, itemKeys contains all the needed keys for you. What you could also do is to add the proper logic to fetch values from the shared preferences inside the if statement in the loop:
var result = [];
for(var i=0;i<keys.length;i++){
if (keys[i].startsWith('item_')) {
result.add(prefs.getString(keys[i]) ?? '');
}
}
result should contain what are you looking for.
I am using firestore to retrieve data
List<Data> userSearchItems = [];
...........
for (var i = 0; i<userDocument['order'].length; i++)...[
Text(userDocument["order"][i].toString()),
userSearchItems.add(userDocument["order"][i].toString()),//This do not work a read line appears with error
],
errors seen for userDocument["order"][i].toString()
The argument type 'String' can't be assigned to the parameter type 'Data'
and a red line also appears at add
Using for loop i can get the Text but i want to store it in an array or list (what is most suitable) to be used later to get data from firestore that match a list/array item that has been fetched before
Found the solution
You can implement a new method for it
var arr=List();
void addList() {
FirebaseFirestore.instance.collection("points").doc('1').get().then((value){
arr.addAll(value['order']);
});
}
and the list can be used in any other function
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());
I am making a search request on the List with the Provider pattern.
List<Device> _devices = [
Device(one: 'Apple', two: 'iphone'),
Device(one: 'Samsung', two: 'Galaxy')
];
And Query is like this
List<Device> queryQuery(String value) {
return _devices
.where((device) => device.one.toLowerCase().contains(value.toLowerCase()))
.toList();
the result I expect to get is iphone when I passed the value Apple.
But the result on the screen that I got is [instance of ‘Device’]
when I code like this
child: Text('${deviceData.getDevice('Apple')}'
I do know I should be using some kind of key using two... but I have no idea :-(
You serialized the wrong object.
What you did end-up being similar to:
Text(Device(one: 'Apple', two: 'iphone').toString());
But you don't want to do Device.toString(). What you want instead is to pass Device.two to your Text.
As such your end result is:
Text('${chordData.chordExpand('Apple').two}')
By the look of [Instance of 'Device'], it seems the function is returning a list so it is a good idea to check if the list is empty or not. if it is not empty, one of the elements is still needed to be selected. I guess it should be Text('${chordData.chordExpand('Apple')[0].two}') in case the list is not empty.
To summarize, use something like this to handle the case when list is empty
// Inside your build method before returning the widget
var l = chordData.chordExpand('Apple'); // Returns a list of devices
String textToWrite; // Here we will store the text that needs to be written
if(l.isEmpty) textToWrite = 'No results'; // If the filter resulted in an empty list
else textToWrite = l[0].two; // l[0] is an instance of a device which has a property called two. You can select any instance from the list provided it exists
return <Your Widget>(
.....
Text(textToWrite),
.....
);
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']))));
}