[英]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.