skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    Using a FutureBuilder as suggested by Randal Schwartz, I got this to work (and I eliminated the checkForTimeline method and went right to the UserService):

    class _HomePageState extends State<HomePage> {
    
      late Future<AppUser?> appUser;
    
      @override
      void initState() {
        super.initState();
        appUser = UserService().getUserfromFirestore();
      }
    
      // This is the basic structure of the page.
      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
            future: appUser, // Must wait for appUser to proceed with the build...
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.hasData) {
                debugPrint(snapshot.data);
              }
              return ColorfulSafeArea( <code to build the UI> )
    

    }


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search