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'];
}
Share:
245
winfred adrah
Author by

winfred adrah

Updated on January 01, 2023

Comments

  • winfred adrah
    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
      Peter Koltai almost 3 years
      Please include more from your code, where do you make these declarations?
    • fabc
      fabc almost 3 years
      Hey 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.