我正在寻找一种在InitState方法上加载异步数据的方法,在构建方法运行之前我需要一些数据.我正在使用GoogleAuth代码,我需要执行构建方法,直到Stream运行.
我的initState方法是:
@override void initState () { super.initState(); _googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account) { setState(() { _currentUser = account; }); }); _googleSignIn.signInSilently(); }
我将不胜感激任何反馈.
解决方法
您可以使用StreamBuilder执行此操作.只要流中的数据发生更改,这将运行构建器方法.
以下是我的一个示例项目的代码片段:
StreamBuilder<List<Content>> _getContentsList(BuildContext context) { final BlocProvider blocProvider = BlocProvider.of(context); int page = 1; return StreamBuilder<List<Content>>( stream: blocProvider.contentBloc.contents,initialData: [],builder: (context,snapshot) { if (snapshot.data.isNotEmpty) { return ListView.builder(itemBuilder: (context,index) { if (index < snapshot.data.length) { return ContentBox(content: snapshot.data.elementAt(index)); } else if (index / 5 == page) { page++; blocProvider.contentBloc.index.add(index); } }); } else { return Center( child: CircularProgressIndicator(),); } }); }
在上面的代码中,StreamBuilder监听内容的任何变化,最初是一个空数组并显示CircularProgressIndicator.一旦我进行API调用,就会将fetched数据添加到contents数组中,该数组将运行builder方法.
当用户向下滚动时,将获取更多内容并将其添加到内容数组中,这将再次运行构建器方法.
在您的情况下,只需要初始加载.但是,这为您提供了一个选项,可以在屏幕上显示其他内容,直到获取数据.
希望这是有帮助的.
编辑:
在你的情况下,我猜它将看起来如下所示:
StreamBuilder<List<Content>>( stream: account,// stream data to listen for change builder: (context,snapshot) { if(account != null) { return _googleSignIn.signInSilently(); } else { // show loader or animation } });