I have a provider with states:
enum RemoteJSONState { parsing, parsed, failedToParse }
In one my widgets, I listen to all the changes with
class RemoteJSONStateProvider with ChangeNotifier {
set remoteJSONState(RemoteJSONState givenState) {
if (givenState == _remoteJSONState) {
return;
}
_remoteJSONState = givenState;
notifyListeners();
}
}
In another widget of mine, I only want to listen to "parsed" state. This is because initially my widget is running information based on local storage. When remote data is fetched it will update itself with the fetched info. If fetching fails, I simply dont want to build my widget and I want to use the local information available. Hence, I dont want a widget rebuild.
Here is what i tried so far.
@override
Widget build(BuildContext context) {
RemoteJSONStateProvider =
Provider.of<RemoteJSONStateProvider>(context);
}
The problem is my widget gets rebuild if RemoteJSONStateProvider states is changed to "failedToParse". How may I only listen for a condition? which is
RemoteJSONStateProvider._remoteJSONState == RemoteJSONState.parsed
The other answers didnt satisfy me as I need to keep the old function for my other widget. After an hour of research, I made a Selector widget to do my needs.
Selector<RemoteJSONStateProvider, RemoteJSONState>(
builder: (context, remoteJSONStateProvider, child) {
print("rebuild");
return Text('build');
},
selector: (buildContext, remoteJSONStateProvider) =>
remoteJSONStateProvider.remoteJSONState,
shouldRebuild: (prev, next) =>
prev != RemoteJSONState.parsed && next == RemoteJSONState.parsed,
);