flutter navigator pop dialog - error - Unhandled Exception: NoSuchMethodError: The method 'findAncestorStateOfType' was called on null

984

After reading the trace prints we can be sure the problem was with FlutterInappPurchase.purchaseUpdated.listen(...) and FlutterInappPurchase.purchaseError.listen(...) that weren't disposed after the dialog was closed. They used the context to pop and open a new dialog (in the case of the purchaseError) which at that moment could be null. Canceling the streams after disposing the widget fixes the issue. Glad to know that fixes the problem

@override
void dispose(){
  super.dispose();
  _purchaseUpdatedSubscription.cancel();
  _purchaseErrorSubscription.cancel();
}
Share:
984
Axil
Author by

Axil

Updated on November 22, 2022

Comments

  • Axil
    Axil over 1 year

    I have got this piece of pop up Dialog() code in flutter https://gist.github.com/axilaris/2b186c7a4073671128e8cacc09dfc384, if you check out the code somewhere right at the bottom

    class PurchaseDialog extends StatefulWidget with NavigationStates {
    ...
    class _PurchaseDialogState extends State<PurchaseDialog> {
    ...
      @override
      Widget build(BuildContext context) {
        return Dialog(
    ...
     showSecondaryButton(BuildContext context) {
    ...
    Navigator.of(context).pop(); <--- here is the problem
    

    whenever it calls

    Navigator.of(context).pop();
    

    it will cause the following error

    [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'findAncestorStateOfType' was called on null.
    

    this looks like a duplicate of this NoSuchMethodError: The method 'ancestorStateOfType' was called on null with await and async method, but i'ved tried the solutions it does not work. (context can only set once, and checking mounted variable have no effect).

    How to resolve this ? So far it dismiss the dialog (with pop() so its correct behaviour), but I dont want this error coming out.

    UPDATE info: The PurchaseDialog() above is called in this way:

        showDialog(
          context: context,
          builder: (BuildContext context) => PurchaseDialog(),
        ).then((value) {
          setState(() {
          });
        });
    

    here are trace prints: https://gist.github.com/axilaris/6d8db8824b0b89e33fee7ddfdd238e34