Anan Saadi
Anan Saadi

Reputation: 338

Provider not updating custom widget when value changes

My provider is used inside a custom widget that is used as ListTile inside the parent widget .

The provider is inside a stream that fetches data from a Firebase database, when the stream is triggered it stores the new data inside the provider as a Map.

The provider is called LastMessage and the Map is called messageMap, new data gets added using the function 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();
  }

Now the problem is that even after messageMap is updated the widget doesn't get rebuilt when listen is set to false, although it works when listen is true but it makes the whole app very slow

Upvotes: 0

Views: 1059

Answers (2)

Anan Saadi
Anan Saadi

Reputation: 338

The solution was using StreamBuilder instead of provider to update the widget

Upvotes: 0

StasVo
StasVo

Reputation: 914

Widget will be rebuilt only if the listener is true. If the listener is false then the widget will not be rebuilt when you call notifyListeners();

Upvotes: 1

Related Questions