我正在寻找一种在InitState方法上加载异步数据的方法,我需要一些数据才能运行Build方法.我使用的是GoogleAuth代码,我需要执行build method,直到Stream运行.

我的initState方法是:

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

如果有任何反馈,我将不胜感激.

推荐答案

Method 1 :你可以用StreamBuilder来做这个.每当stream中的数据发生变化时,将运行builder方法.

下面是我的一个示例项目的代码片段:

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,获取的数据就会被添加到contents数组中,该数组将运行builder方法.

当用户向下滚动时,将获取更多内容并将其添加到内容数组,该数组将再次运行builder方法.

在您的情况下,只需要初始加载.但这为您提供了在获取数据之前在屏幕上显示其他内容的选项.

希望这能对您有所帮助.

EDIT:

在您的情况下,我猜它将如下所示:

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

Method 2:另一个方法是创建一个async方法,并从您的initState()方法中调用它,如下所示:

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

  void asyncMethod() async {
    await asyncCall1();
    await asyncCall2();
    // ....
  }

Flutter相关问答推荐

在Flutter 动中绘制ECG图

Flutter creating Constant.dart InputDecoration section put pass in hintText

我不能在Fighting中裁剪图片输入错误,否则应用程序会崩溃

分页控制器在到达页面末尾之前或在初始化页面时对每个索引调用API

Flutter :在后台实现振动

GitHub Actions工作流secret中的特殊字符未被保留

SingleChildScrollView在ErrorWidget.builder中不工作

Flutter 日期时间格式

使用 Firebase Realtime 实现高效流式传输

打开键盘时屏幕组件会被压扁

如何在flutter中更改showModalBottomSheet小部件中CheckboxListTile小部件的值?

找不到任何与 com.google.firebase:firebase-sessions:[15.0.0, 16.0.0) 匹配的版本

为 flutter app/firebase 保存 chatgpt api-key 的正确方法是什么

如何从列表中更新provider变量:Flutter列表和Provider优化指南

Flutter:如何从运行时创建的列表中访问单个子部件的值

Flutter使Perspective Page View无限循环

type '({bool growable}) => List' 不是类型转换中类型 'List' 的子类型

Flutter 用户过滤器

如何将图像网络装箱到具有边界半径的容器中

在自动完成中 Select 值后保持键盘焦点