I have a simple controller like this
class MatchListController with ChangeNotifier {
List<MatchData> liveMatches = [];
MatchListController() {
getMatchList();
}
getMatchList() async {
debugPrint('match list api called');
var response = await ApiService().matchList();
if (response != null) {
final databody = json.decode(response);
notifyListeners();
}
}
}
When my page loads it runs the function getMatchList()
which is fine but If I change the page between function and when it return data notifyListeners
hit and app crash. I am using loading but I have tab menu so I can change the page from there What I want is if page is close then notifyListeners dispose.
CodePudding user response:
One way to solve this issue is to use the mounted
property of the State
object, as such:
class MatchListController with ChangeNotifier {
List<MatchData> liveMatches = [];
bool _isMounted = true;
MatchListController() {
getMatchList();
}
@override
void dispose() {
_isMounted = false;
super.dispose();
}
getMatchList() async {
debugPrint('match list api called');
var response = await ApiService().matchList();
if (response != null && _isMounted) {
final databody = json.decode(response);
notifyListeners();
}
}
}
Now if the user navigates to another screen before the API call returns, notifyListeners()
will not be called and the app won't crash.
CodePudding user response:
The answer that khalil mentioned is correct, there is also another solution:
Since you are using loading, I assume you want to prevent the page from changing, so you can wrap the tab menu buttons with an AbsorbPointer
widget, and use setState
to change its absorbing state according to your loading state. Your loading state can simply be a boolean inside your stateful widget.