Get User details with user id Flutter Firestore
245
Solution 1
Yeah, you can't use snap there because you have not initialized the object.
Rather, move the usage into initState. Something like this:
class _MyHomePageState extends State<MyHomePage> {
DocumentSnapshot snap = await FirebaseFirestore.instance
.collection('Users')
.doc()
.get() as DocumentSnapshot<Object?>;
String myId;
@override
void initState() {
super.initState();
myId = snap['name'];
// should be myId = snap.get('name');
}
Solution 2
You can call it using async
and await
String myId = '';
@override
void initState() {
super.initState();
initialize();
}
void initialize() async{
DocumentSnapshot snap = await FirebaseFirestore.instance.collection('Users').doc().get() as DocumentSnapshot<Object?>;
myId = snap['name'];
}
Author by
winfred adrah
Updated on January 01, 2023Comments
-
winfred adrah over 1 year
I saw this example trying to get the User details from Firestore Firebase in Flutter. Unfortunately it gives me the error
The instance member 'snap' can't be accessed in an initializer.
DocumentSnapshot snap = FirebaseFirestore.instance.collection('Users').doc().get() as DocumentSnapshot<Object?>; String myId = snap['name'];
-
Peter Koltai almost 3 yearsPlease include more from your code, where do you make these declarations?
-
fabc almost 3 yearsHey there, may I ask if either of the two answers worked for you? If it didn't, please let us know so we can try and assist you further.
-