Reputation: 2174
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyNewPage()),
)
This loads a new page.
How can I make it such that it calls a destructor on the current page so it can clear its things properly?
I tried adding a dispose method but it isn't executed when I change pages.
Upvotes: 2
Views: 1932
Reputation: 334
You can just use the Navigator.pushReplacement
as follows:
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (BuildContext context) => MyHomePage()));
this will push what you tell it and dispose the previous one once the new one finishes loading.
Upvotes: 0
Reputation: 3136
To clear whole current context you can use:
Navigator.of(context)
.pushAndRemoveUntil(MaterialPageRoute(builder: (context) =>
MyNewPage()), (Route<dynamic> route) => false)
Make sure to use a RoutePredicate, that always returns false (Route<dynamic> route) => false
. In this situation it removes all of the routes except for the new MyNewPage()
route pushed in stack.
In case you need to execute some cleanup function
dispose()
method:
it is called when this object is removed from the tree permanently. Keep in mind, that it is an error to call setState
here and make sure to end your method with a call to super.dispose()
when overriding it.@override
void dispose() {
// Your function.
super.dispose();
}
initState()
method of route you are pushing in a stack: It is called when this object is inserted into the tree. If you override this, make sure your method starts with a call to super.initState()
. @override
void initState() {
super.initState();
// Your function.
}
BuildContext
for your cleanup function you can use didChangeDependencies()
: It is called when a dependency of this State object changes and also immediately after initState
, it is safe to use BuildContext
here. Subclasses rarely override this method because the framework always calls build after a dependency changes. Some subclasses do override this method because they need to do some expensive work (e.g., network fetches) when their dependencies change, and that work would be too expensive to do for every build. @override
void didChangeDependencies() {
// Your function.
super.didChangeDependencies();
}
Getx package also has variety of ways to insert a Middleware function:
GetPage redirect( ) {
final authService = Get.find<AuthService>();
return authService.authed.value ? null : RouteSettings(name: '/login')
}
GetPage onPageCalled(GetPage page) {
final authService = Get.find<AuthService>();
return page.copyWith(title: 'Welcome ${authService.UserName}');
}
List<Bindings> onBindingsStart(List<Bindings> bindings) {
final authService = Get.find<AuthService>();
if (authService.isAdmin) {
bindings.add(AdminBinding());
}
return bindings;
}
GetPageBuilder onPageBuildStart(GetPageBuilder page) {
print('bindings are ready');
return page;
}
Upvotes: 2