winfred adrah
winfred adrah

Reputation: 428

Get User details with user id Flutter Firestore

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'];

Upvotes: 1

Views: 786

Answers (2)

Peter Obiechina
Peter Obiechina

Reputation: 2835

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');
  }

Upvotes: 2

Jahidul Islam
Jahidul Islam

Reputation: 12595

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'];
}

Upvotes: 2

Related Questions