Reputation: 179
I have a class for Player that has nextDate, loginDate and saveDate. Below code works fine and able to retrieve the fields.
DocumentSnapshot documentSnapshot =
await db.collection(Paths.playersPath).doc(uid).get();
Player player = Player.fromFirestore(documentSnapshot);
print('print ${player.nextDate}');
print('print ${player.loginDate}');
print('print ${player.saveDate}');
My question now is if it is possible to use a variable for the nextDate, loginDate and saveDate so that I can just pass which date should I retrieve. I tried the following but it is not working.
String dateName = 'nextDate';
DocumentSnapshot documentSnapshot =
await db.collection(Paths.playersPath).doc(uid).get();
Player player = Player.fromFirestore(documentSnapshot);
print('print ${player.$dateName}');
Please help. Thanks!
Upvotes: 0
Views: 282
Reputation: 3596
As far as the code snippet is concerned, I can see you have already defined a method fromFirebase
to serialize it, in that case you must extract the data payload from the DocumentSnapshot
provided by the Firebase DB by using the data
method provided by the DocumentSnapshot
class. The problem in your case is you're trying to serialize the DocumentSnapshot
itself which is not a class of type Map<String, dynamic>
which is need for json serialization. If you take a look at the docs, the data
method provides a Map<String, dynamic>
Another alternative could be
If you are using FlutterFire
plugins that are officially developed by the Firebase and Flutter teams, you can use the withConverter
method which can serialize the response for you to the Player
class in your case. Here you can find more info about the same.
Upvotes: 1
Reputation: 2096
unluckily, in Flutter mirrors
are not available.
You can look it up in the official documentation about this matter.
Nonetheless, the most straightforward workaround is using a Map
, so that the keys in that map are your options, and the values the actual property you want to use.
There's a good example in this previous answer.
Upvotes: 1