I have a Widget that I reuse in my app, say the default "you have pressed the button this many times" Widget.
I have added an asynchronous saveData
function to this Widget, which takes the int
in the State
and stores it (say in the Shared Preferences). The rationale is that I can store only once, instead of after every single change.
Now I use this Widget in an AlertDialog
called by showDialog
, and I use it again in a BottomSheet
called by showModalBottomSheet
. Additionally, I'd want to use it in a page of a PageView
.
Is there a way to get the data to save when the Dialog or BottomSheet is Widget is disposed, or otherwise from the enclosing Widget (sheet/dialog)? I would rather not create two variations of my reused Widget just because it is wrapped in a different Widget, and pulling the State out of my reused Widget into the two parent Widgets also seems unnecessary.
I've been trying to use dispose
and deactivate
, but since I'm trying to use (a snapshot of) a Widget State
variable, I couldn't do it: Doing asynchronous work and then calling super caused an error saying I failed to call super, and the other way around tells me I can't use the State after the Widget has been unmounted.
In the end, trying to intercept a dispose action was not a stable solution (esp. when using the State
too).
I ended up giving my reused Widget an optional Key
, and use a GlobalKey
if I want to upload from outside the Widget (i.e. a submit button in the enclosing PageView page). In case of the BottomSheet, I've now simply set it to auto-save the value each time it changes if no key is present. It works for now, but is not ideal (and if anyone is aware of a better solution, I'm still interested :p).