Provider not updating custom widget when value changes

Issue

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

Solution

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

Answered By – Anan Saadi

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *