值更改时提供程序不更新自定义小部件
Provider not updating custom widget when value changes
我的提供程序在一个自定义小部件中使用,该小部件在父小部件中用作 ListTile
。
提供程序位于从 Firebase database
获取数据的 stream
中,当流被触发时,它将新数据存储在提供程序中作为 Map
.
提供程序称为 LastMessage
,Map
称为 messageMap
,使用函数 updateMap
:
添加新数据
var messageInstance = Provider.of<global.LastMessage>(context, listen: false);
StreamSubscription<Event> updates;
// roomId is a string that is used as a key
updates = ref.child(RoomId).onChildAdded.listen((event) async{ // the stream works correctly and the new data gets stored
String _x = await getLastMessage();// a function that gets the data from the database
messageInstance.updateMap(RoomId, _x);
});
class LastMessage extends ChangeNotifier{
Map<String, String> messageMap = {};
void updateMap(String RoomID, String lastMessage){
messageMap[RoomID] = lastMessage;
notifyListeners();
}
现在的问题是,即使 messageMap
更新后,当 listen
设置为 false
时小部件也不会重建,尽管它在 listen
时有效是 true
但它使整个应用程序非常慢
只有当侦听器为真时才会重建小部件。
如果侦听器为 false,则当您调用 notifyListeners();
时将不会重建小部件
解决方案是使用 StreamBuilder 而不是提供程序来更新小部件
我的提供程序在一个自定义小部件中使用,该小部件在父小部件中用作 ListTile
。
提供程序位于从 Firebase database
获取数据的 stream
中,当流被触发时,它将新数据存储在提供程序中作为 Map
.
提供程序称为 LastMessage
,Map
称为 messageMap
,使用函数 updateMap
:
var messageInstance = Provider.of<global.LastMessage>(context, listen: false);
StreamSubscription<Event> updates;
// roomId is a string that is used as a key
updates = ref.child(RoomId).onChildAdded.listen((event) async{ // the stream works correctly and the new data gets stored
String _x = await getLastMessage();// a function that gets the data from the database
messageInstance.updateMap(RoomId, _x);
});
class LastMessage extends ChangeNotifier{
Map<String, String> messageMap = {};
void updateMap(String RoomID, String lastMessage){
messageMap[RoomID] = lastMessage;
notifyListeners();
}
现在的问题是,即使 messageMap
更新后,当 listen
设置为 false
时小部件也不会重建,尽管它在 listen
时有效是 true
但它使整个应用程序非常慢
只有当侦听器为真时才会重建小部件。 如果侦听器为 false,则当您调用 notifyListeners();
时将不会重建小部件解决方案是使用 StreamBuilder 而不是提供程序来更新小部件