加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

dart – 有没有办法在InitState方法上加载异步数据?

发布时间:2020-12-14 14:49:11 所属栏目:百科 来源:网络整理
导读:我正在寻找一种在InitState方法上加载异步数据的方法,在构建方法运行之前我需要一些数据.我正在使用GoogleAuth代码,我需要执行构建方法,直到Stream运行. 我的initState方法是: @override void initState () { super.initState(); _googleSignIn.onCurrentUs
我正在寻找一种在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
            }
        });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读