首页 > 解决方案 > setState 允许更改立即出现在界面上以进行颤动

问题描述

我正在努力更新我在 firebase 中的用户名,我希望更改立即出现在界面上。我如何为此设置状态?这是迄今为止我为“更新”按钮编写的代码。谢谢!

RaisedButton(
              onPressed: () async { //change username

                  FirebaseUser user = await Provider.of(context).auth.getCurrentUser();
                  UserUpdateInfo updateInfo = UserUpdateInfo();
                  updateInfo.displayName = _newUsernameController.text;
                  user.updateProfile(updateInfo);
                  print('USERNAME IS: ${user.displayName}');

                  setState(() {
                    //user.displayName = _newUsernameController;
                  });
                    Navigator.pop(context);

                    },
                  color: Colors.indigo,
                  shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(50)),
                  child: Padding(
                    padding: EdgeInsets.only(top: 10, bottom: 10, left: 20, right: 20),
                  child: Text("Save", style: TextStyle(color: Colors.white,
                  fontWeight: FontWeight.bold, fontSize: 15),
                    ),
                  ),
                )

标签: firebasefluttersettingssetstate

解决方案


您可以分配user.displayName给其中的变量setState并显示该变量。

String username = 'Old Name';

...

child: Column(
    children: <Widget>[
        Text(username), // HERE!
        RaisedButton(
              onPressed: () async { //change username

                  FirebaseUser user = await Provider.of(context).auth.getCurrentUser();
                  UserUpdateInfo updateInfo = UserUpdateInfo();
                  updateInfo.displayName = _newUsernameController.text;
                  user.updateProfile(updateInfo);
                  print('USERNAME IS: ${user.displayName}');

                  setState(() {
                    username = user.displayName;
                  });
                    // Navigator.pop(context); why???

                    },
                  color: Colors.indigo,
                  shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(50)),
                  child: Padding(
                    padding: EdgeInsets.only(top: 10, bottom: 10, left: 20, right: 20),
                  child: Text("Save", style: TextStyle(color: Colors.white,
                  fontWeight: FontWeight.bold, fontSize: 15),
                    ),
                  ),
                ),
    ],
),

推荐阅读