Flutter Firebase how to add map within array - firebase

I got list.
final services= [
HizmetModel(title: 'ServiceA', price: 30),
HizmetModel(title: 'ServiceB', price: 30),
HizmetModel(title: 'ServiceD', price: 30),
];
I would like to write and read this list to Firebase like below.

Assuming that HizmetModel has a method toMap() that converts HizmetModel(title: 'ServiceA', price: 30) => {'ServiceA': 30}.
List<Map> firebaseData = services.map((e) => e.toMap());
You can upload this List to firebase as usual.
https://firebase.flutter.dev/docs/overview/

Related

Firebase RTDB Search for a keyword in a list of keywords

I am using Firebase RTDB to access my data using the Flutter app.
The data has the following attributes:
{
'Category': 'Food',
'Product Description': 'Energy Drink',
'Product Picture': 'image_link',
'Product Title': 'Coca Cola',
'Price': 40000,
'inStock': 1,
'keywords':[
'coco cola',
'energy drink',
'drink',
'other keywords'
]
}
I would like to use the keywords field to search for a specific product. How can I do that?
I know about 'orderby' and 'equalto' keywords in Firebase RTDB but how to use it with a list?
Or how do I change the structure of the data so that I can efficiently search for specific keywords?
Store the keywords as maps. So it would be like keywords: {'coca cola':true, ...}
Then you can do
.orderBy('keywords/coca cola').equalTo(true)

Flutter delete array from document [duplicate]

I'm making a Flutter application.
But, I cannot delete a field in the Firestore document.
In another language I know to use FieldValue.delete() to delete a file in Firestorm document.
In Dart, How do I delete?
Update Oct,2018: This is Now Possible:
In order to delete a particular field from a Cloud Firestore document - make sure you are using Plugin version 0.8.0 or Above. Now a E.g If you have a document having a field 'Desc' with contain some Text. In Order to Delete it.
Firestore.instance.collection('path').document('name').update({'Desc': FieldValue.delete()}).whenComplete((){
print('Field Deleted');
});
This will Delete 'Desc' Field from the Document 'name'
I think this is currently impossible in standard, non hacky way.
There is an open issue https://github.com/flutter/flutter/issues/13905 in Flutter which have to be resolved first.
Get the DocumentReference, invoke update with a map which has a key you want to delete and value FieldValue.delete().
var collection = FirebaseFirestore.instance.collection('collection');
collection
.doc('document_id')
.update({
'field_to_delete': FieldValue.delete(),
}
);
Here is an official solution for deleting Field Path when programming in Flutter/Dart
Here is how a sample Firestore collection looks like:
{
'path': {
'name': {
'title': 'my title'
'description': 'my description',
}
}
}
In order to delete description field, you can do this:
Firestore.instance.collection('path').document('name').set(
{'description': FieldValue.delete()},
SetOptions(
merge: true,
),
)
And the collection will look like this:
{
'path': {
'name': {
'title': 'my title'
}
}
}
if you have nested fields then use the '.' (Dot) notation to specify the field.
E.g if your data is nested Map then this is handy.
Firestore.instance.collection('path').document('name').update({'address.town': FieldValue.delete()}).whenComplete((){
print('Field Deleted');
});

Dispatch multiple actions from in redux-observable

I am trying to dispatch multiple actions to redux. Here is my code
action$.pipe(
ofType(trigger),
mergeMap(({ payload }) =>
from(endpoint(payload)).pipe(
map(response =>
// this works fine
// setData(response.data)
// this doesn't
concat(
of(setData(response.data)),
of({ type: 'hello' })
)
// I also tried
[
of(setData(response.data)),
of({ type: 'hello' })
]
)
)
),
catchError(err => Promise.resolve(creators.setError(err)))
)
Single dispatch works, but if I try multiple items as above I am getting Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
map just maps one item to another so when you return [action1, action2] you're still returning an array and redux-observable tries to treat it as an action itself. What you want instead is "unwrapping" the array (or Observable created with concat) returned.
So instead of using map you can use mergeMap (or concatMap) and when you return an array it'll iterate it and make separate emissions for each item:
mergeMap(response => [
setData(response.data),
{ type: 'hello' },
]),
If this looks too odd you can wrap the array with from to make it more obvious:
mergeMap(response => from([
setData(response.data),
{ type: 'hello' },
])),
You can even use a single of:
mergeMap(response => of(
setData(response.data),
{ type: 'hello' },
)),

Not able to retrieve data from firestore

I have a collection 'posts' which has documents as uid of the particular users, under each document I have array 'posts' which contains a string 'likes' and a map 'post' which again contain a string 'userpost'.
I need to show data of the 'userpost' as a list in my homepage. Can someone suggest me a query for this.
I tried this:
return Firestore.instance.collection('posts').where('posts', arrayContains: 'post').snapshot();
And in my home page under listview.builder I'm retrieving data like this:-
Text( snapshot.data.documents[i].data['userpost'], )
But after running It isn't showing anything in the homepage and an execption is thrown: A build function returned null.
Firestore QuerySnapshot which you have to loop over to get the actual document map
Should try this
snapshot.data.documents.map((DocumentSnapshot doc){
if(doc.data.hasdata)){
return Text( doc.data.data['userpost'], );
}
return Text('Loading');
}).toList()

Linked list for firestore documents

I have a use case to make a linked list of documents like
{ name, next_ptr} and next_ptr is a reference to another document
I have following code and I am getting next_ptr but not getting fields belonging to next_ptr
I am getting following output
KkkGTTKjuwcGmzJzQ3Wa => FIRE => undefined
iW9lm7sYkgvuZPdVvrZE => GAS => undefined
NtTyJNjqIT79PZ6zkqtY => WATER => undefined
Expected Output
KkkGTTKjuwcGmzJzQ3Wa => FIRE => GAS
iW9lm7sYkgvuZPdVvrZE => GAS => WATER
NtTyJNjqIT79PZ6zkqtY => WATER => undefined
Code
db = defaultApp.firestore() ;
abc_collection = db.collection("abc") ;
abc_collection.get()
.then( data => {
data.forEach(item => {
console.log(item.id , "=>", item.get('name')) ;
next_ref = item.get('next_ptr') ;
next_ref.get("name").then(item => {
console.log(item) ;
}).catch("") ;
} ) ;
}).catch("") ;
It looks like you're assuming that the query results contain all the referenced documents:
item.get('next_ptr')['name']
What item.get('next_ptr') returns is a DocumentReference object, not the entire contents of the document. You will have to query that document with its get() method in order to load its contents, or find the document using its ID in the results that you queried (if you guarantee that the reference always points to a document in the same collection.
You might just be better off storing the string ID of the document if you don't want to deal with the DocumentReference.

Resources