Lewis
Lewis

Reputation: 83

How can i always setState when the page is opened?

My issue is, when the page is opened my variable isn't set. So when i'm querying from firestore i get the error The method '[]' was called on null. Receiver: null Tried calling: []("userbio")

I declared 2 variables

  var userid;
  var useremail;

Then i wrote this future

Future getUserData() async {
    var firestore = Firestore.instance;
    final FirebaseUser user = await FirebaseAuth.instance.currentUser();
    final String uid = user.uid.toString();
    final String email = user.email.toString();
    DocumentReference qn = await firestore
        .collection("users")
        .document(email)
        .collection('userdetails')
        .document(uid);
    void initState() {
      setState(() {
        userid = uid;
        useremail = email;
      });
    }

   
    return qn.documentID;
  }

This is how i'm currently trying to setState but it's not working

void initState() {
          setState(() {
            userid = uid;
            useremail = email;
          });
        }
    

Please help, thanks. comment if you need more context

Upvotes: 1

Views: 867

Answers (2)

user2872856
user2872856

Reputation: 2051

Try assign your variable an empty value instead of leaving it null.

var userid = '';
var useremail = '';

Upvotes: 0

MickaelHrndz
MickaelHrndz

Reputation: 3832

Seems like you're declaring the nested function initState() but you're not calling it. I would just remove the function and call setState() directly :

...
.document(uid);
setState(() {
...

EDIT : Call getUserData() inside initState :

// In a class extending State<T>
@override
void initState() {
    super.initState();
    // synchronous call if you don't care about the result
    getUserData();
    // anonymous function if you want the result
    () async {
        var result = await getUserData();
    }();
}

PS : initState(), like build() or setState(), is a predefined name in Flutter. Try not to use those names for functions that are not overriding the original ones.

Upvotes: 1

Related Questions