0

我的应用程序实现了 Firebase 身份验证,每个用户都必须输入他们的显示名称才能注册到应用程序中。

在我的应用程序中,我希望用户能够更新这个显示名称

逻辑非常简单,用户单击“更改显示名称”按钮,出现一个ModalBottomSheet,用户可以在其中输入新的显示名称并保存。但是这样,当显示名称更改时,屏幕不会更新,直到我热重新加载或重新启动应用程序。

在此处输入图像描述

class Body extends StatelessWidget {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  @override
  Widget build(BuildContext context) {
    String displayName = _auth.currentUser.displayName;
    final _formKey = GlobalKey<FormState>();
    String newDisplayName;

    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Current display name is:',
              style: TextStyle(fontSize: 20),
            ),
            Text(
              '$displayName',
              style: TextStyle(fontSize: 25),
            ),
            RaisedButton(
              child: Text('Change Display Name'),
              onPressed: () {
                showModalBottomSheet(
                  isScrollControlled: true,
                  context: context,
                  builder: (context) {
                    return Padding(
                      padding: MediaQuery.of(context).viewInsets
                      child: Form(
                        key: _formKey,
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            TextFormField(
                              decoration: InputDecoration(
                                labelText: 'New Display Name',
                              ),
                              keyboardType: TextInputType.text,
                              onSaved: (value) {
                                newDisplayName = value;
                              },
                            ),
                            RaisedButton(
                              child: Text('Change'),
                              onPressed: () {
                                _formKey.currentState.save();
                              
                                _auth.currentUser
                                    .updateProfile(displayName: newDisplayName);

                                Navigator.pop(context);
                              },
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

我试图在不同的地方调用 .reload 但在页面刷新之前显示名称不会改变。

_auth.currentUser.reload();

编辑:感谢https://stackoverflow.com/users/11921453/twelve的解决方案

使用以下 StreamBuilder 包装 manin 小部件,您将能够立即检索 snapshot.data.displayName。

child: StreamBuilder<User>(
      stream: FirebaseAuth.instance.userChanges(),
4

1 回答 1

3

Firebase 有一个流来监听用户的变化。在您的 _auth 旁边定义此流。

使用 au streambuilder 包装您的小部件树并将值设置为定义的流。

现在,每次用户数据更改时都会重建小部件树。

于 2020-10-05T18:01:41.423 回答