Search code examples
flutterasynchronousbuildwidgetfuture

How to modify a variable using async method before it use in widget build?


I have a variable named userName,which depends on databse query,so async is a must. My older code can be concluded liks this

class IndexScreen extends StatefulWidget {
  @override
  _IndexScreenState createState() => _IndexScreenState();
}

//use database query function
Future<void> initUser() async{
  UserTable().getUserInfo(curUserEmail).then((value)=>null);
}

//show page
class _IndexScreenState extends State<IndexScreen> {
  @override
  Widget build(BuildContext context) {
    initUser().then((value){
    final theme = Theme.of(context);
    return WillPopScope(
      onWillPop: () =>router.navigateTo(context, '/welcome'),
      child: SafeArea(
        child: Scaffold(
//The static global variable is used in Body in other files
            body: Body()
        ),
      ),
    );
  });
}
}

It warns that miss return,I dont knwo how to amend my code.

Thanks!!


Solution

  • You can achive this by using the FutureBuilder widget. Please refer the code below.

    class IndexScreen extends StatefulWidget {
      @override
      _IndexScreenState createState() => _IndexScreenState();
    }
    
    //use database query function
    Future<Map> initUser() async {
      final data =
          await UserTable().getUserInfo(curUserEmail);
      return data;
    }
    
    //show page
    class _IndexScreenState extends State<IndexScreen> {
      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
          future: initUser(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.hasData) {
              final theme = Theme.of(context);
              return WillPopScope(
                onWillPop: () => router.navigateTo(context, '/welcome'),
                child: SafeArea(
                  child: Scaffold(
                    body: Body(),
                  ),
                ),
              );
            } else {
              // Returns empty container untill the data is loaded
              Container();
            }
          },
        );
      }
    }