In my code below, I am struggling with LifeCyrles in Flutter where I can update my State in Provider, APPARENTLY, only in didChangeDependencies
hook or in a templat
I am new to flutter as well, But I have learned about a few architecture patterns that have helped me build some apps.
Here is how I do it:
Create a Provider
which holds the data for you in runtime. (It can be a Bloc
in your case). Stick to one architecture, don't try to put providers and blocs in the same project. Both are used for state management and only using one would be a great practice.
Second, Register
the providers using ChangeNotificationProvider
or any other widgets which does a similar job of rebuilding the child widget when a data gets changed.
Third, Get the provider in the build method of the widget that is supposed to change when the value of the variable provider changes. This way only the concerned widget is redrawn.
For your case,
If you want to hide the header and footer once you reach the last page, you can declare a variable, let's say isLastPage
set to false
by default in your provider.
Next, wrap the widget, i.e. header
and footer
with ChangeNotificationListner
Now, let that widget decide what it has to do based on the value of isLastPage
, either hide itself or show.
I hope this helps!
At the long run, I seem to have found Mounted
lifecycle hook in Flutter which is implemented with the help of Future.microtask
. Unlike .addPostFrameCallback
:
SchedulerBinding.instance
.addPostFrameCallback((_) => this._detectLastPage());
Which is triggered only once like InitState
(but only at the end of the build execution), Future.microtask
can be placed inside build
block and be invoked after every change and state update.
It doesn't solve the problem with the inaccurate state in didChangeDependencies
hook but provides another way to perform post-build executions.
Credits for the current solution to @Abion47
example
Future.microtask(() => this._detectLastPage());