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!
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 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'm starting to learn about mongoose/MongoDB aggregation functions, and am having some basic difficulties. For example, I'm trying to do the following:
var myModels= require('./models/myModel');
var myCount = myModels.countDocuments({userID: "A"});
console.log(myCount );
I just want to count the number of documents with userID of "A" but when this prints to the console, it's printing as a whole object, instead of just a numerical count. I've read the answer here but I'm still not able to solve this problem (also, is there a way, unlike in that question, to return the count directly rather than having to predefine a variable and set it in a callback function?)
I'm trying to follow the guide here and don't see where I'm going wrong.
It's because the return value of countDocuments is a promise and not a number.
You either need to wait for that Promise or use callback syntax like so:
var myModels= require('./models/myModel');
// this required the code to be inside an async function
var myCount = await myModels.countDocuments({userID: "A"});
console.log(myCount);
Or:
var myModels= require('./models/myModel');
myModels.countDocuments({userID: "A"})
.then((myCount) =>{console.log(myCount);});
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 am writing a protractor test case to compare the name(s) of the displayed data is same as the searched name.
Even though my test case works fine, I am not able to understand what is happening. Because when i expect the name to compare, it compares as expected, but when i print the elementFinder's(rowData)(i have attached the output screen shot here) value in console.log, it show a huge list of some values which i am not able to understand?
PS: I am a newbie to protractor`
This is the testCase:
it('should show proper data for given last name', function () {
var searchValue='manning';
searchBox.sendKeys(searchValue);
search.click();
element.all(by.binding('row.loanNumber')).count().then(function(value) {
var loanCount = value;
for (var i = 0; i < loanCount; i++) {
var rowData = element.all(by.binding('row.borrowerName')).get(i).getText();
expect(rowData).toMatch(searchValue.toUpperCase());
console.log(rowData,'*****',searchValue.toUpperCase());
}
});
});`
And give me valuable suggestions about my style of code
rowData is a promise (not a value), so when you console.log it, you get the promise object
Protractor patches Jasmine to automatically resolve promises within the expect(), so that's how it knows to resolve the value and compare to the expected result.
If you want to console.log the value, you need to resolve the promise with .then() to get the value.
rowData.then(function(rowDataText) {
console.log(rowDataText);
)}
This is pretty much everyone's first question when they start using protractor. You will want to learn how promises work if you want a good understanding of how to manipulate them.