How to convert Firebase Map to Dart Map? - firebase

This fails silently in Dart:
Map<String,String> dartMap = doc.data['keyForFieldthatContainsMap'];
doc is a firebase document (type DocumentSnapshot) that has a field "keyForFieldthatContainsMap" which contains a Map.
doc.data is of type:
Map<String,dynamic>
At runtime doc.data['keyForFieldthatContainsMap'] has the type:
_InternalLinkedHashMap<dynamic, dynamic>
from which I don't know how to access the keys and values.
I'm using the package:
import 'package:cloud_firestore/cloud_firestore.dart';
I'm looking for a way to read map fields just like I can read string, number, boolean,... fields from firebase.

Try to change your dartMap to Map<dynamic,dynamic>. Your error might occour cause you cant now which types your Map in Firestore has.

Related

Update Field with FieldPath, update doesn't accept FieldPath as parameter - Firebase Flutter

I was trying to delete a FieldValue inside Firebase, but the key had a "/" in it.
So my app gave me this exception:
FirebaseException ([cloud_firestore/unknown] Use FieldPath.of() for field names containing '~*/[]'.)
After researching "FieldPath" for a while, I came up with following:
final CollectionReference userTodos = FirebaseFirestore.instance.collection('userTodos');
Future deleteToDo(String key, String listID) async {
return await userTodos
.doc(userID)
.collection('Lists')
.doc(listID)
.update(FieldPath([key]), FieldValue.delete());
}
But for some reason, it gives me this error:
The argument type 'FieldPath' can't be assigned to the parameter type 'Map<String, Object?>'
I don't understand why because here it says it accepts a String or FieldPath:
https://firebase.google.com/docs/reference/js/v8/firebase.firestore.DocumentReference#update
Could someone help me please?
Thanks :)
You are referring to the documentation of the JavaScript Firestore client API, while you are using the Dart programming language. That's the source of confusion.
The Dart Firestore client's DocumentReference.update method doesn't accept FieldPaths.

How to use FieldPath.of() in Firebase Firestore with Flutter

I'm trying to update a nested document field in Firebase Firestore, but when I use the FieldPath instance, It raises a compiler exception
Map _map = {
'name': 'vin',
'quantity': 2,
'costPrice': 12000,
};
var fieldPath = new FieldPath(['categories', 'branch']);
final CollectionReference _storeRef =
FirebaseFirestore.instance.collection('stores');
_storeRef.doc('6').update({fieldPath: _map});
How do I update a nested document Field using the Firebase FieldPath instance
The DocumentReference.update method requires a Map<String, dynamic> as it's first parameter and the reason for the compiler error is because you're trying to pass a FieldPath object instead of a String.
You can reduce the values of the FieldPath into a String and use that as the path for the update method.
Update this:
_storeRef.doc('6').update({fieldPath: _map});
to this:
_storeRef
.doc('6')
.update({'${fieldPath.components.reduce((a, b) => '$a.$b')}': _map});
This basically means the same as:
_storeRef
.doc('6')
.update({'categories.branch': _map});

How do I read and write a text file from firebase storage in Flutter?

I need to make a storage for my saved images in firebase storage.
Is there a way I can read and write to online text file on firebase storage in flutter?
Is there any alternative to make my images storage?
It's so simple. Let's explain the solution with the example.
import the library as following :
import package:firebase_storage/firebase_storage.dart' as firebase_storage;
Secondly, get the firebase reference by :
firebase_storage.Reference ref = firebase_storage.FirebaseStorage.instance
.ref()
.child('playground')
.child('/put-string-example.txt');
Third, to get the data from the current file you are in :
Uint8List downloadedData = await ref.getData();
Fourth, now you will get a value in Uint8List format,
you have to decode this value by Utf8Codec class that is an instance of the
default implementation of the [Utf8Codec] and you will get the result in String object:
print(utf8.decode(downloadedData));
Now for writing it's a bit easier :
Firstly, we have the String object :
String putStringText = 'Hello World';
Secondly, we write to the current file with firebase ref object :
ref.putString(putStringText,
metadata: firebase_storage.SettableMetadata(
contentLanguage: 'en'));
the first argument is our string the second one is the metadata that allows you some extra options like the contentLanguage param.
I hope you find it useful.

Querying Firestore documents by Array or Map fields values in Firebase console

Here, I want to query by the value "ministoreid1" in Firebase console. But I am not able to figure out. Here, I am trying to do the query in console not using codes.
I have filed the feature request at Alex' suggestion. And the reply I received from Firebase Support:
Currently, there is no query similar to array-contains available in the Firestore Console. I can file a feature request ticket on your behalf. However, I can't guarantee anything at the moment, so please watch out for any updates on our blog or release notes for now. For the map field, you can try to filter on the console using the format: 'mapFieldName.keyName' in the field text box
So we can query for map values by 'mapFieldName.keyName'. I didn't know this before.
Here, I am trying to do the query in console not using codes.
Unfortunately, there is currently no way you can filter your documents in the Firebase console according to a value that exist in an array. As you can see, there are only the following operators:
== is equal to
> is after
>= is after and includes
< is before
<= is before and includes
But an whereArrayContains option it is not present yet. I recommend you file a feature request for that. It might be also useful for other developers.
The query that you perform in the console does't return any results because you are checking if the mini_stores_assigned is equal to ministoreid1, which obviously is not since the mini_stores_assigned property is an array and not a String so you can compare them.
For future use, Firebase has added the feature request by Ssuburat. You can now can filter your documents in the Firebase console according to a value that exist in an array.
###FILTER BLOGS BY USER.
for example if you have two collections (one to many)
/users
/blogs
blog and user has these schemes:
blog: { name,date,user:{myusername:true}}
//notice that user is a map or object and document blog has id itself wich you can use in user document and viceversa.
user:{name,lastname,blogs:{idblog1:true,idblog2:true}} //blogs is a map or object
if you want to filter by map object you can do this:
import firebase from "firebase/compat/app";
import { getFirestore } from "firebase/firestore";
const appFirebase = firebase.initializeApp(firebaseConfig);
export const dbFirebase = getFirestore(appFirebase);
const myuser= "myusername"
const q = query(collection(dbFirebase, "blogs"), where(`user.${myuser}`, "==", true));
const blogsSnapshot = await getDocs(q);
blogsSnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
console.log({blogsSnapshot});

How to add Geopoint, timestamp and reference to a document in Firestore trough Flutter

It is fairly straightforward hot to set basic types inside Firestore.
But I cannot find how to construct Geopoint, Timestamp and another document reference with flutter Firestore plugin.
What do you assing inside data that you set to the coollection Map<String,dynamic> for each object?
Any help or examples?
I created manually an object on the server and got it inside my flutter app.
For TimeStamp you can pass DateTime object directly from dart.
For Geopoint there is GeoPoint object inside Firestore plugin.
new GeoPoint(longitude: 3.4, latitude: 4.5) })
For another document reference, you would pass DocumentReference that you retrieved as a value to the data object.
To create or update geopoint in firebase you can use the object GeoPoint(Latitude, Longitude) directly, this example from official documentation
CollectionReference users = FirebaseFirestore.instance.collection('users');
Future<void> updateUser() {
return users
.doc('ABC123')
.update({'info.address.location': GeoPoint(53.483959, -2.244644)})
.then((value) => print("User Updated"))
.catchError((error) => print("Failed to update user: $error"));
}
In the latest version of flutter a GeoPoint is created without named parameters.
GeoPoint(0, 0);
first argument => latitude
second argument => longitude

Resources