Handling Firebase Stream Object in Flutter - database

I'm trying to receive Data from the Firebase Realtime Database in Flutter. I can't get it working - all the solutions I found so far don't work.
The connection to the database is working and getting Data:
String userid = FirebaseAuth.instance.currentUser!.uid;
DatabaseReference _database =FirebaseDatabase.instance.ref();
void _getData(){
_itemStream = _database.child('users/$userid/items/').onValue.listen((event) {
final Object? mydata = event.snapshot.value;
print(mydata.toString());
});
}
This gives me my set of Data as an Object. The Print-Statement returns this, which is the correct Dataset for the node:
{1646396962722: {mhd: 2022-03-04 12:29:22.722218, name: Hund, startdate: 2022-03-04 12:29:22.722106, fach: 0}, 1646396401456: {mhd: 2022-03-04 12:20:01.461668, name: Hund, startdate: 2022-03-04 12:20:01.456343, fach: 0}, 1646396946311: {mhd: 2022-03-04 12:29:06.312466, name: Maus, startdate: 2022-03-04 12:29:06.311793, fach: 0}}
The problem I can't solve is: How to Loop through this Dataset and get it into a List in Dart. If I try something like
mydata?.forEach()
I get the Error:
The method 'forEach' isn't defined for the type 'Object'.
Im really stuck. Maybe anyone can give me a tip how to approach this.
Thanks!

If you look at your dataset, this is in fact a Map<dynamic, dynamic>. You need to convert this to a better Dart object or use the for in loop. see the example below:
main() {
// in your example
// final Map<dynamic, dynamic>? mydata = event.snapshot.value;
final Map<dynamic, dynamic> yourMap = {
'1646396962722': {
'mhd': '2022-03-04 12:29:22.722218',
'name': 'Hund',
'startdate': '2022-03-04 12:29:22.722106',
'fach': '0'
},
'1646396401456': {
'mhd': '2022-03-04 12:20:01.461668',
'name': 'Hund',
'startdate': '2022-03-04 12:20:01.456343',
'fach': '0'
},
'1646396946311': {
'mhd': '2022-03-04 12:29:06.312466',
'name': 'Maus',
'startdate': '2022-03-04 12:29:06.311793',
'fach': '0'
}
};
for (final entry in yourMap.entries) {
print('key: ${entry.key}, value: ${entry.value}');
}
}
//key: 1646396962722, value: {mhd: 2022-03-04 12:29:22.722218, name: Hund, startdate: 2022-03-04 12:29:22.722106, fach: 0}
//key: 1646396401456, value: {mhd: 2022-03-04 12:20:01.461668, name: Hund, startdate: 2022-03-04 12:20:01.456343, fach: 0}
//key: 1646396946311, value: {mhd: 2022-03-04 12:29:06.312466, name: Maus, startdate: 2022-03-04 12:29:06.311793, fach: 0}

only sketchup code:
final List<dynamic> list = myData as List<dynamic>;
for(final dynamic item of list) {
final Map<String, dynamic> dataAsMap = item as Map<String, dynamic>
print(item.keys);
final Map<String, dynamic> actualObject = map[item.keys.first as String] as Map<String, dynamic>;
print(actualObject["name"]);
}
}

Related

Mongoose: Update by pushing an object in an array

This is the model I am working with:
name: {
type: String
},
payment: {
id: {
type: String,
required: true
},
cards: [
{
id: {
type: String
},
is_default: {
type: Boolean,
"default": false
}
}
]
}
I want to add a card to the cards array, for example:
card =
id: "some_token"
is_default: true
I am using the update method to push the card to the array, but it won't add the card to the document. Instead, it creates a new document with only those fields:
{
id: "some_token",
is_default: true,
_id: someId
}
Any idea how I can update the actual document I am targeting instead of creating a new document?
Here's my code (using CoffeeScript):
update_where =
payment:
id: "some_id"
update_push =
$push:
'payment.cards':
id: card_token
is_default: false
Customer.update update_where, update_push, {upsert: true}, (err, results) ->
# Do something with the results
Oh… I just noticed my mistake. The problem was in the where statement.
I was doing:
payment:
id: "some_id"
But the right thing to write is the following:
'payment.id': 'some_id'
And it now works!

How to filter all the fields in react?

How to filter all the fields in react?
I have written a code which only filters specified fields.
let filteredContacts=this.props.contacts.filter(
(contact)=>{
return contact.name.indexOf(this.state.search)!==-1;
}
);
the above code only returns filtered names...but i want to filter name,age,city work.
this is the data file:
export default function(){
return [{
key: 1,
name: 'Steve',
city: 'Paris',
}, {
key: 2,
name: 'Tim',
city: 'London',
}, {
key: 3,
name: 'Stella',
city: 'Bankok',
}, {
key: 4,
name: 'John',
city: 'Paris',
}];
}
i want to create a search bar which which filters all the fields suppose if i search john then the list of john should be displayed and if i search paris then all the entries which have paris should be displayed..So the code which i have written only searches for name as i have specified name..i want to search the inputed data to search all the fields.
The filter criteria can be the indexOf on Object.values() like below but it will only give a complete match
var data = [{
key: 1,
name: 'Steve',
city: 'Paris',
}, {
key: 2,
name: 'Tim',
city: 'London',
}, {
key: 3,
name: 'Stella',
city: 'Bankok',
}, {
key: 4,
name: 'John',
city: 'Paris',
}];
var value = 'Paris'
var newData = data.filter((obj) => {
return Object.values(obj).indexOf(value) > -1
})
console.log(newData)
Well, I fastly tried, do a loop on your keys. Maybe there's a more elegant way.
let filteredContacts=this.props.contacts.filter(
(contact)=>{
var found = false;
Object.keys(contact).map(function(key, index) {
if (contact[key].indexOf(this.state.search) >= 0)
found = true;
}
return found;
}
);

Get list of selected value from array object in angular js

I am new in angular js. I have one array object as
var data = [{ id:1, name: 'Adam', email: 'adam#email.com', age: 12},
{ id:2, name: 'Amalie', email: 'amalie#email.com', age: 12}];
Now, I want data as
var data_id = [{1},{2}];
So what should I have to get only id list from array object?
In Javascript, Objects are having key and value both.
var obj = {
myKey: value,
}
You can try JavaScript array.map() method. It will return the array with the elements you want to access.
var data = [{ id:1, name: 'Adam', email: 'adam#email.com', age: 12},
{ id:2, name: 'Amalie', email: 'amalie#email.com', age: 12}];
var result = data.map(function(item) {
return item.id;
});
console.log(result);
EDIT: Question has been updated.
The format you want the data in ([{1},{2}]) cannot be achieved. A javascript object has to have a key and a value. so, {1} is invalid.
But on the other hand if it's just the ids you want ([1,2]), see the mapping below and instead of returning {id: item.id}, just return item.id.
var data = [{ id:1, name: 'Adam', email: 'adam#email.com', age: 12},
{ id:2, name: 'Amalie', email: 'amalie#email.com', age: 12}];
// [{id: 1, {id: 2}}]
var data_id = data.map(function(item){
return { id: item.id};
});
// [1, 2]
var data_id = data.map(function(item){
return item.id;
});
If you're using ES6, you could simplify the code
var data_id = data.map(item => ({ id: item.id}));
You can use javascript map function to extract just the id.
See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Basic loop and if statement issue in AngularJS

So I have an angular function that aims to grab some basic details from an array of objects, by looking up using an id, passed into the function.
Anyway, the function works - the first time. That is, it successfully returns the customer name of the first object where the contract id's match. However, if there is more than one contract/object that matches, it only returns the first name.
I understand this must be a basic problem with regards to looping, but can't seem to get it to work!
Thanks so much in advance.
Here is the function:
$scope.getCompanyDetailsByContractId = function(contractId) {
for (var i = $scope.customers.length - 1; i >= 0; i--) {
if ($scope.customers[i].contracts[i].id == contractId ) {
return $scope.customers[i].name;
};
};;
}
And here is the data structures:
$scope.customers = [{
id: 1,
name: "John Inc",
currentContractLength: 12,
currentContractValue: 18000,
startDate: "09/01/2014",
endDate: "09/01/2015",
nextRenewalDate: "09/01/2015",
mrr: 1500,
contracts: [{
id: 234,
status: "won",
contractNumber: 1,
value: 18000,
startDate: "09/01/2014",
endDate: "09/01/2015",
nextRenewalDate: "09/01/2014"
},
{
id: 235,
status: "pending",
contractNumber: 2,
value: 18000,
startDate: "09/01/2015",
endDate: "09/01/2016",
nextRenewalDate: "09/01/2016"
}]
}, {
id: 2,
name: "Peters Company Ltd",
currentContractLength: 3,
currentContractValue: 15000,
startDate: "09/01/2014",
endDate: "09/01/2015",
nextRenewalDate: "09/01/2015",
mrr: 1500,
contracts: [{
id: 543654,
status: "won",
contractNumber: 1,
value: 4200,
startDate: "09/01/2014",
endDate: "09/01/2015",
nextRenewalDate: "09/01/2014"
},
{
id: 54354,
status: "pending",
contractNumber: 2,
value: 18000,
startDate: "09/01/2015",
endDate: "09/01/2016",
nextRenewalDate: "09/01/2016"
}]
}];
It seems you should do 2 loops to look in all possibles contracts.
With the following call you are looking only for the contract with index i
$scope.customers[i].contracts[i].id == contractId
Maybe you should do something like
for (var i = $scope.customers.length - 1; i >= 0; i--) {
for (var j = 0; j < $scope.customers[i].contracts.length; j++) {
if ($scope.customers[i].contracts[j].id == contractId ) {
return $scope.customers[i].name;
};
}
};

calculating a count (number of distinct key's in an object) in angular

I have the following Angular code, see below.
What I'd like to achieve is - for each user - find out the "count" for each activity type.
What I'd like to achieve is:
John Thompson = 2 Deal
Bill Gates = 3 Deal
Billy Wellington = 2 Deal, 1 Meeting
The activity id's are the same in the activities object, and the $scope.activities.
Bit stuck here, any idea on how to either a) Write a function to get the COUNT or b) Do something clever in the HTML element with a ng-repeat and group or something.
$scope.competitionDetails = {
end_date: "2014-03-01",
users: [{
id: 2,
name: "John Thompson",
activities: [{ //This is all their activities
id: 6431,
time: (57).minutes().ago(),
points: 20
}, {
id: 6431,
time: new Date(),
points: 20
}]
}, {
id: 3,
name: "Bill Gates",
activities: [{ //This is all their activities
id: 6431,
time: new Date(),
points: 20
}, {
id: 6431,
time: new Date(),
points: 20
}, {
id: 6431,
time: new Date(),
points: 20
}]
}, {
id: 1,
name: "Billy Wellington",
activities: [{ //This is all their activities
id: 6431,
time: new Date(),
points: 20
}, {
id: 6431,
time: new Date(),
points: 20
}, {
id: 6432,
time: new Date(),
points: 100
}]
}]
};
$scope.activities = [{
id: 6431,
name: "Deal",
points: 20
}, {
id: 6432,
name: "Meeting",
points: 100
}];
I have created a fiddle for you with a working example: http://jsfiddle.net/ADukg/4757/
Just using some regular js, with a tiny bit of angular:
// create a lookup
var lookup = {};
angular.forEach($scope.activities, function(activity){
lookup[activity.id] = activity;
});
// calculate the results
angular.forEach($scope.competitionDetails.users, function(user){
user.results = {};
angular.forEach(user.activities, function(activity){
var name = lookup[activity.id].name;
if(!user.results[name]){
user.results[name] = 1;
}else{
user.results[name] += 1;
}
});
});

Resources