簡體   English   中英

狀態未更新

[英]State not updating

當我從數據庫中獲取一些數據時,我正在嘗試更新小部件。 我要更改的小部件定義為類變量:

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更新,但不會重新呈現。
有人可以幫忙嗎?

如果要在initState()中調用createFriendsPage ,則意味着initState()內的代碼僅被調用一次,即用於構建UI。 如果可能的話,建議您在覆蓋方法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