国家不更新

问题描述 投票:0回答:1

当我从数据库中获取一些数据时,我正在尝试更新小部件。我想要更改的小部件被定义为类变量:

Widget openFriendRequestNotificationWidget = new Container();

我正在使用一个空容器,因为我真的不需要在开头渲染任何东西而将它留在null是没有选择的。 我有两个函数,一个用于创建我的页面,另一个用于更新我的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,
          );
        });
      }
    });
  }

变量在createReceivedFriendRequestsNotification中更新,但不会重新渲染。 有人可以帮忙吗?

dart flutter
1个回答
1
投票

如果你在createFriendsPage中调用initState(),那么这意味着initState()中的代码只被调用一次,这就是构建UI。如果可能,我建议你在覆盖方法createFriendsPage中调用你的build()

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

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

         //other methods here ...
     }
© www.soinside.com 2019 - 2024. All rights reserved.