国家不更新

时间:2017-12-26 20:22:54

标签: dart flutter

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

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中更新,但不会重新渲染 有人可以帮忙吗?

1 个答案:

答案 0 :(得分: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 ...
     }
相关问题