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

问题描述 投票:7回答:4

我正在寻找一种在InitState方法上加载异步数据的方法,在构建方法运行之前我需要一些数据。我正在使用GoogleAuth代码,我需要执行构建方法,直到Stream运行。

我的initState方法是:

 @override
  void initState () {
    super.initState();
    _googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account)     {
      setState(() {
        _currentUser = account;
      });
    });
    _googleSignIn.signInSilently();
  }

我将不胜感激任何反馈。

dart flutter
4个回答
7
投票

您可以使用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
            }
        });

9
投票

您可以创建一个async方法并在initState中调用它

   @override
    void initState () {
      super.initState();
     _asyncMethod();
    }

    _asyncMethod() async {
     _googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account)     {
        setState(() {
          _currentUser = account;
        });
      });
      _googleSignIn.signInSilently();
    }

8
投票

截至目前使用.then表示法似乎工作:

  // ...
  @override
  initState() {
    super.initState();
    asyncFunction.then((result) {
    print("result: $result");
    setState(() {});
    });
  }
  //...

1
投票

您可以设置一个像loaded这样的布尔值,并在listen函数中将其设置为true,并使build函数在load设置为true时返回数据,否则只需抛出一个CircularProgressIndicator

© www.soinside.com 2019 - 2024. All rights reserved.