Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Navigation push() and pop(), filling up the stack?

Tags:

flutter

dart

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.

like image 652
FuzzyTemper Avatar asked Aug 31 '18 08:08

FuzzyTemper


2 Answers

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) 
  ],
  ...
)
like image 80
Rémi Rousselet Avatar answered Sep 20 '22 22:09

Rémi Rousselet


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

  • https://docs.flutter.io/flutter/widgets/Navigator/replace.html
  • https://docs.flutter.io/flutter/widgets/Navigator/pushReplacement.html
  • https://docs.flutter.io/flutter/widgets/Navigator/popAndPushNamed.html

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.

like image 38
Günter Zöchbauer Avatar answered Sep 21 '22 22:09

Günter Zöchbauer