0

The Problem

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.

The Question

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.

What I tried

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.

fravolt
  • 2,565
  • 1
  • 4
  • 19
  • May be wrap into InheritedWidget to store value? – Dmitry Rodionov Sep 05 '22 at 16:45
  • Thanks for the suggestion @DmitryRodionov, in the end I opted to use a GlobalKey to invoke the `saveData` function from the parent, and keep all the actual data within the reused Widget itself. – fravolt Sep 06 '22 at 14:36

2 Answers2

0

If I understand correctly, you just want to return data from the dialogs and the ModalBottomsheet, right?

var result = await showDialog(...);

var resultModal = await showModalBottom(...);

And inside your Dialog or ModalBottomSheet you return it in the Navigator.pop

Navigator.pop(context, myResult);
Ozan Taskiran
  • 2,922
  • 1
  • 13
  • 23
  • Thank you for the answer. It's not quite what I'm looking for, since in reality (this was not clear from my question) I'm using the reused widget in a PageView page too, which is never popped/dismissed, but does disappear from the screen (I mixed up dismiss and dispose in my question, I'll improve it a bit). – fravolt Sep 05 '22 at 14:55
0

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).

fravolt
  • 2,565
  • 1
  • 4
  • 19