Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter run once method with context available?

Tags:

flutter

Is there any strategy for having you code run only once(like initState()) and have the context also available (to use .of(context)). For example I am getting Bloc.of(context) and I want to subscribe to it (do some stuff like showing an alert dialog, etc). Subscribing in build(), means subscribing multiple times

I can use didChangeDependencies() and set the subscription ??= bloc.listen, but I was wondering if there is another good strategy.

like image 789
cosinus Avatar asked Oct 28 '25 08:10

cosinus


1 Answers

there is another way to do that , by add a "bool" variable and set it as "false" in the "initState" , and lets named (isExec)

2 - in the build method check if "isExec" == false , then run your code that you want to excute it once (alert , subscribe .. etc)

3 - change "isExec" to true (isExec = true);

now if your app state change the build method well avoid that code in the if statment

like image 113
abdalmonem Avatar answered Oct 30 '25 23:10

abdalmonem