i am completely cannot explain the issue in writing so i am trying to make it step by step
i have Stfl widget page
i am putting the following in it's initState methood
@override
void initState(){
Future.delayed(const Duration(seconds: 10), () {
setState(() {});
print('ok i rebuilt the state successfully');
});
super.initState();
}
Now if i change anything in UI
before Duration(seconds: 10)
which i registered it in previous method, it will successfully update the ui as expected .
Now, out of curiosity, I wanted to know if the previous method remains pending and executed after 10 sec if I exit the page or not , and i did the following
1- i log in to the page to register the function within initstate
2- i I exited the page before the 10 seconds ran out
3- ok now i am in difference page waiting for print('ok i rebuilt the state successfully');
to print
4- well .. it is printed successfully as expected
Now i repeat the same steps with some changes like following
1- i log in to the page to register the function within initstate
2- i I exited the page before the 10 seconds ran out
3- i i log in to the page again before 10 sec is done
ok now it should print two times .. once for the first registered function and once for second one AND yes it print two time as expected but what i notice if i make changes in ui before 10 sec is done so the UI will never update it self by the first registered function (Although I saw the process was successful in console) . but it update it self by the second registered function .
now my question is why it does not update by first registered function . and how could i make it update ui by old pending setState
method .
in the fact it happening either with setState
or provider .
i need this behavior for many reasons
CodePudding user response:
When you navigate to the page, each time an new instance of the Widget is created. So the setState
is run against the corresponding widget.
Imagine you have 2 of these on the same screen, you don't expect one to update the other one's state. Same thing happens here.
Also, I don't know if you're doing the future.delayed
to test this. If you're doing this in your app, I suggest you check the mounted
property before setting state, so you prevent setting state on a disposed Widget which can cause issues and exceptions.
something like
Future.delayed(const Duration(seconds: 10), () {
if (!mounted) return;
setState(() {});
print('ok i rebuilt the state successfully');
});