Building an App in Flutter, I wanted to use the Navigation Drawer and added a few FlatButtons.
Every FlatButton
has an onPressed()
method where I do Navigator.push()
moving to the desired page, which is working just fine.
I was wondering if this over time is filling up the memory because I am always pushing but never popping pages from the stack.
Always combining a Navigator.pop()
with a Navigator.push()
successively seems a little odd and far away from good practice.
Maybe someone can enlighten me about the proper way to do it.
This will indeed lead to potential memory issue. To solve this problem, you can pop unneeded routes. You could also add a custom NavigatorObserver
to add a history limit.
example:
class HistoryLimit extends NavigatorObserver {
final int limit;
final history = <Route>[];
HistoryLimit([this.limit = 42]);
@override
void didReplace({Route<dynamic> newRoute, Route<dynamic> oldRoute}) {
final index = history.indexOf(oldRoute);
history[index] = newRoute;
}
@override
void didPush(Route route, Route previousRoute) {
history.add(route);
if (history.length >= limit) {
this.navigator.removeRoute(history.first);
}
}
@override
void didPop(Route route, Route previousRoute) {
history.remove(route);
}
@override
void didRemove(Route route, Route previousRoute) {
history.remove(route);
}
}
Which you use by adding it here:
MaterialApp(
navigatorObservers: [
HistoryLimit(10)
],
...
)
Use Navigator.pop()
when you want the back button to navigate to the previous route. In this case, yes, the stack keeps filling up.
There are other methods though like
that replace the current route by a new one. This way you can't use the Android back button to navigate back through each previous route.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With