2

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!!

1
  • why shouldn't you use FutureBuilder? It will be helpful to load the screen like you want after completed the future. Commented Jun 23, 2021 at 12:15

1 Answer 1

1

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();
        }
      },
    );
  }
}

Sign up to request clarification or add additional context in comments.

3 Comments

Should it be "else{ return Container();}"? I run this code but it shows black screen which I think is Container(),but the initUser() function has finished,it didn't change.I doubt it's for my gteUserInfo() method retrun nothing,it just assign values to static variables
I have updated the code snippets. Can you please check with the current code snippet and revert back?
I watch snapshot.connectionState to fix my special bug,thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.