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'];
CodePudding user response:
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'];
}
CodePudding user response:
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');
}