flutterasynchronousasync-await

How do I use an async method before building a page in Flutter?


I'm fairly new to Flutter and am trying to check a Firebase document for user information before building the page. The method to check the document is async but if I try to await the result in my class HomePage extends StatefulWidget I get the lint error:

'_HomePageState.build' ('Future Function(BuildContext)') isn't a valid override of 'State.build' ('Widget Function(BuildContext)').

Here is the _HomePageState class:

class _HomePageState extends State<HomePage> {
 
   @override   
   Future<Widget> build(BuildContext context) async {
 
     final appUser = await checkForTimeline();
       
     return ColorfulSafeArea( <There is code here to build the UI> )
 
 }

Here is the checkForTimeline method:

Future<AppUser?> checkForTimeline() async {
    // Load the user from the Firestore database
    appUser = await UserService().getUserfromFirestore();
    debugPrint('Make sure we have an AppUser: {$appUser}');
    // Check for a current timeline...
    if (appUser == null || appUser?.currentTimeline == "") {
      // no current timeline, set hasTimeline.
      debugPrint("Current timeline is empty.");
      hasTimeline == false;
      return appUser;
    } else if 
      // There is a timeline
      (appUser != null && appUser?.currentTimeline != "") {
      debugPrint("Current timeline is {$appUser!.currentTimeline}");
      hasTimeline == true;
      return appUser;
      } else {
        return appUser;
      }

How can I get the AppUser in an asynchronous method before building the UI (so I can use it to determine how to build the UI)? Any help on this would be appreciated.


Solution

  • Your widget must complete its synchronous initialization and build steps within 1/60th of a second. There's no place to wait for an async operation. You'll probably need to store a future for the action in a state variable, and use a FutureBuilder in build to show some placeholder while the action is in progress.