Calling a Function When Loading a Stateful Widget in Flutter

My capstone group is building a mobile app using the Flutter SDK, and it requires for a user to be logged in to reach any page other than a login page, a sign up page, and a forgotten password page. We are using Google’s FirebaseAuthentication package to handle securely logging in and out, but we also have our own Cloud Firestore database that stores additional user and account information beyond the basic login information that Firebase stores. So after a new user creates an account, we needed a way to gather the additional information we need and store that in the database.

After a user logs in or sign ups, our app routes them to the app’s homepage, so we figured that when the home widget is loaded, we could just call a function that would determine if the user’s FirbaseAuth user ID corresponded with a document in our Firestore database, but figuring out how to effectively call this function when loading the stateful class that builds the widget that is the foundation of our homepage proved trickier than I anticipated.

I first tried to just call a function in the widget’s build method but quickly ran into an issue: database calls need to be made asynchronously to prevent blocking, and the build method is not asynchronous. So I did some googling and cam across initState().

initState() is a function that is called a single time when a widget is inserted into the app’s widget tree and the widget’s state is initialized. Because other screens are just loaded in the body of our homepage widget, meaning the homepage should only be inserted into the tree a single time when a user is already in the database, this is a great solution that will not make a bunch of unnecessary database calls. I used the following code within the widget generated by the StatefulWidget’s createState() method to check if the user already existed in the database and if not, route them to a set up page.

class NavBarPage extends StatefulWidget

const NavBarPage({    Key? key,  }) : super(key: key);
  @override  State<NavBarPage> createState() => _NavBarPageState();

}

class _NavBarPageState extends State<NavBarPage> {

  @override 

// Check if firebase_auth uid corresponds to document in db.  void initState() {    asyncUidCheck().then((value) {    });    super.initState(); 

}

}

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *