How to resolve The operator '[]' isn't defined for the type 'Object'?
Solution 1:
An important detail for DocumentSnapshot
is that it is defined with a generic:
DocumentSnapshot<T extends Object?>
https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/DocumentSnapshot-class.html
Where T
is then used by the data()
method signature:
data() → T?
If we don't specify anything in the generic part, Dart will in this case automatically assume T
is Object?
. This is a problem in your case since Object?
does not have any [String]
operator.
You therefore need to explicit tell Dart what type you expect T
to be by doing something like this:
UserModel.fromSnapShot(DocumentSnapshot<Map<String,dynamic>> documentSnapshot){
Here we tell Dart that T
in DocumentSnapshot
should be Map<String,dynamic>
so when we call data()
, Dart can assume that you get a Map<String,dynamic>?
typed object back (notice it will always add ?
at the end because that is how data()
is defined).