首页 > 解决方案 > 值更改时提供程序不更新自定义小部件

问题描述

我的提供程序用于自定义小部件内,该小部件用作ListTile父小部件内。

提供者位于从 astream中获取数据的 aFirebase database中,当触发流时,它将新数据存储在提供者中作为 a Map

调用提供程序LastMessageMap调用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小部件也不会重建,虽然它在什么时候工作,但它使整个应用程序非常慢listenfalselistentrue

标签: flutterdartflutter-provider

解决方案


只有当监听器为真时,小部件才会被重建。如果侦听器为 false,则在您调用 notifyListeners() 时不会重建小部件;


推荐阅读