dartflutter

Is there a way to load async data on InitState method?


I'm a looking for a way to load async data on InitState method, I need some data before build method runs. I'm using a GoogleAuth code, and I need to execute build method 'till a Stream runs.

My initState method is:

 @override
  void initState () {
    super.initState();
    _googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account)     {
      setState(() {
        _currentUser = account;
      });
    });
    _googleSignIn.signInSilently();
  }

I will appreciate any feedback.


Solution

  • You can create an async method and call it inside your initState

    @override
    void initState () {
      super.initState();
      WidgetsBinding.instance.addPostFrameCallback((_){
        _asyncMethod();
      });
            
    }
    
    _asyncMethod() async {
      _googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account)     {
        setState(() {
          _currentUser = account;
        });
      });
      _googleSignIn.signInSilently();
    }