如何在小部件构建中使用之前使用异步方法修改变量?

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

我有一个名为userName的变量,它依赖于数据库查询,所以异步是必须的。 我的旧代码可以这样总结

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

它警告小姐 return,我不知道如何修改我的代码。

谢谢!!

您可以使用 FutureBuilder 小部件实现此目的。请参考下面的代码。

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