简体   繁体   English

状态未更新

[英]State not updating

I'm trying to update a widget when I got some data from my database. 当我从数据库中获取一些数据时,我正在尝试更新小部件。 The widget that I'm trying to change is defined as a class variable: 我要更改的小部件定义为类变量:

Widget openFriendRequestNotificationWidget = new Container();

I'm using an empty container because I really don't need to render anything at the beginning and leaving it at null is no option. 我使用的是空容器,因为我真的不需要在开始时渲染任何内容,而将其保留为null是没有选择的。
I've got two functions, one to create my page and the other one the update my openFriendRequestNotificationWidget : 我有两个功能,一个用于创建页面,另一个用于更新openFriendRequestNotificationWidget

  Widget createFriendsPage() {
    if (currentUser.friends == null) {
      return new Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          openFriendRequestNotificationWidget,
          new Material(
              child: new InkWell(
                child: new Center(
                  child: new Text("Woops, looks like you have no friends yet.\nTap here to find some!", textAlign: TextAlign.center,),
                ),
                onTap: () => createFriendsDialog(),
              )
          )
        ],
      );
    }
    return new Column(
      children: <Widget>[
        openFriendRequestNotificationWidget,
        new Text("ok")
      ],
    );
  }

  void createReceivedFriendRequestsNotification() {
    FirebaseDatabase.instance.reference().child("friend_requests").child(currentUser.uid).once().then((DataSnapshot snap) {
      Map<String, Map<String, String>> response = snap.value;
      if (response != null) {
        this.setState(() {
          print("Changing widget");
          openFriendRequestNotificationWidget = new Container(
            child: new Text("You've got ${response.length.toString()} new friend requests!"),
            color: Colors.black,
          );
        });
      }
    });
  }

The variable is updating in createReceivedFriendRequestsNotification but it is not re-rendering. 该变量正在createReceivedFriendRequestsNotification更新,但不会重新呈现。
Could someone help out? 有人可以帮忙吗?

if you are calling createFriendsPage in initState() , then it means that the code inside initState() is called only once, which is to build the UI. 如果要在initState()中调用createFriendsPage ,则意味着initState()内的代码仅被调用一次,即用于构建UI。 If it's possible, I suggest that you call your createFriendsPage inside the override method build() 如果可能的话,建议您在覆盖方法build()调用createFriendsPage

   class FriendPage extends StatefullWidget{
          //instantiate your state ..  }

   class FriendsPageState extends State<FriendPage> {
         @override 
         Widget build(Build context) {
               return cteateFriendsPage(); 
         }

         //other methods here ...
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM