【问题标题】:Using async methods in initState() flutter在 initState() 中使用异步方法颤动
【发布时间】:2019-08-13 09:57:13
【问题描述】:

我正在使用 firebase,需要在我的 initState() 方法中获取用户的 id,因为我正在构建一个需要用户 id 的小部件,来自 firebase。 firebase 使用的currentUser 方法是Future

目前,我将此作为我的初始化状态和getUser 函数:

Future<FirebaseUser> getUser() async {
    FirebaseUser user = await FirebaseAuth.instance.currentUser();
    return user;
  }

void initState() {
    getUser().then((result) {
      stream = Firestore.instance.collection('Lessons').where("teacher", isEqualTo: result.uid).limit(4).snapshots();

      _AppBarOptions = <Widget>[
        AppBar(
          title: new Text('Dashboard', style: TextStyle(color: Colors.white)),
          backgroundColor: Colors.white,
        ),
        AppBar(
            title: new Text('Lessons', style: TextStyle(color: Colors.white))),
        AppBar(title: new Text('Tasks', style: TextStyle(color: Colors.white))),
        AppBar(
            title: new Text('Settings', style: TextStyle(color: Colors.white)))
      ];

      _widgetOptions = <Widget>[
        Text(
          'Dashboard will go here',
          style: optionStyle,
        ),
        StreamBuilder(
            stream: stream,
            builder: (context, snapshot) {
              if(snapshot.hasData) {
                return ListView.builder(
                  itemExtent: 80.0,
                  itemCount: snapshot.data.documents.length,
                  itemBuilder: (context, index) =>
                      _buildListItem(context, snapshot.data.documents[index]),
                );
              } else {
                return Text('You have no Lessons');
              }

            }),
        Text(
          'Tasks will go here',
          style: optionStyle,
        ),
        Container(
          child: new RaisedButton(
            child: new Text('Sign Out'),
            onPressed: signOut,
          ),
        )
      ];
    });
  }

我面临的问题是build方法在这个完成之前执行,它使用widgetOptions来显示文本,导致错误。

我想知道是否有任何方法可以改进这一点,以便能够获取用户的 id 并在stream 中使用它,以便它可以获取文档?

非常感谢。

【问题讨论】:

    标签: firebase flutter dart


    【解决方案1】:

    对于这种情况,Flutter 有 FutureBuilder 小部件。

    它将 UI 部分的构建“推迟”到提供的 Future 完成的那一刻。

    阅读该类的 API 文档,查看一些示例,您将解决您的问题。

    因此,您将卸载 initState 方法的一部分,在该部分中,您将选项列表构造到 FutureBuilderbuilder 参数。

    【讨论】:

      【解决方案2】:

      要缓解此问题,您可以使用布尔值和setState() 来更改其值。获得用户 ID 后,如果布尔值为 true,则可以构建需要用户 ID 的小部件,否则将小部件设为进度指示器或简单地“加载”文本。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-15
        • 2019-01-16
        • 1970-01-01
        • 1970-01-01
        • 2020-01-10
        • 2021-09-01
        • 2019-01-24
        • 2020-03-20
        相关资源
        最近更新 更多