0

I have this useState:

class RegisterFormPageWidget extends HookConsumerWidget {
  const RegisterFormPageWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final vm = ref.watch<RegisterPageVm>(registerPageVm);
    vm.page = useState(0);

But every time I navigate away with Navigator.of(context).pop(), vm.page.value becomes 0 again.

I've put a print statement in the constructor to ensure it is not recreated:

class RegisterPageVm {
  RegisterPageVm({required this.entity}) {
    print('new instance');
  }

I can confirm it is only every constructed once. I have looked for all instances of vm.page.value = 0 and there is never code running that does that.

Any ideas what else I can check to figure out why vm.page.value is getting reset to 0 upon popping the stack?

BeniaminoBaggins
  • 11,202
  • 41
  • 152
  • 287

1 Answers1

1

I think this is the cause:

vm.page = useState(0); resets to 0 after a Navigator.pop then navigating back to the page because useState is in the page that gets destroyed by the pop. So even though the vm does not get destroyed, the page that got destroyed is setting the vm.page.

In which case useState is not suitable because it is state that lives only as long as the widget that it is in.

I have confirmed this flow, where the widget reconstructs after Navigator.pop, and navigating back to it. It would be good to know if there is some way to make hooks live longer than the widgets they are in. I doubt there is. For now, I have migrated to a Riverpod StateNotifier.

BeniaminoBaggins
  • 11,202
  • 41
  • 152
  • 287