I've been scratching my head around state management in flutter for quite a while, but there is an issue that I'm struggling to resolve. Let's say your app has a feature called "user profile", which is similar to Facebook or Instagram's. The user can open the user page multiple times, and if they update something in the profile (for example like a post) all profile page of that user must be updated. Now in React Native I would have an users state which is a map of {user_id -> user_profile}. All the user profile pages that need data of an user would refer to the user profile with the specific user id. Because there is only one user profile for an user id, if I update something all the pages will get updated.
I have a similar setup in Flutter. I have an UserProfilesChangeNotifier
which contains a Map<user_id, user_profile>. Everytime the user page is open I use ChangeNotifierProvider.value
to supply the Map to it. In initState
, I would check if the particular user_id exists in the Map, if not the UserProfilesChangeNotifier
will have to fetch the data from the server. In build
method I would read the user data with userProfile.map[user_id]
, and similarly I also update the data through the UserProfilesChangeNotifier
(with notifyListeners() attached). There is some issues with this setup that I can think of:
- According to Flutter docs, you should avoid using
ChangeNotifier
with lots of listeners as it is O(N²) for dispatching notifications. In my case, many user pages will have to listen to it. Is it solvable withChangeNotifierProvider
? - If the user opens profile page for user with id 1, 2, 3, 4, then proceeds to update data in user with id 4 (write it to Map and
notifyListeners
), all the user pages for user 1, 2, 3 will have to rebuild as well, though not needed.
I feel that my setup is very flawed and there might be something to improve. What would you do in this case?