addScopedWillPopCallback method Null safety

void addScopedWillPopCallback(
  1. WillPopCallback callback
)

Enables this route to veto attempts by the user to dismiss it.

This callback is typically added using a WillPopScope widget. That widget finds the enclosing ModalRoute and uses this function to register this callback:
Widget build(BuildContext context) {
  return WillPopScope(
    onWillPop: () async {
      // ask the user if they are sure
      return true;
    },
    child: Container(),
  );
}

This callback runs asynchronously and it's possible that it will be called after its route has been disposed. The callback should check State.mounted before doing anything.

A typical application of this callback would be to warn the user about unsaved Form data if the user attempts to back out of the form. In that case, use the Form.onWillPop property to register the callback.

To register a callback manually, look up the enclosing ModalRoute in a State.didChangeDependencies callback:
abstract class _MyWidgetState extends State<MyWidget> {
  ModalRoute<dynamic>? _route;

  // ...

  @override
  void didChangeDependencies() {
   super.didChangeDependencies();
   _route?.removeScopedWillPopCallback(askTheUserIfTheyAreSure);
   _route = ModalRoute.of(context);
   _route?.addScopedWillPopCallback(askTheUserIfTheyAreSure);
  }
}

If you register a callback manually, be sure to remove the callback with removeScopedWillPopCallback by the time the widget has been disposed. A stateful widget can do this in its dispose method (continuing the previous example):
abstract class _MyWidgetState2 extends State<MyWidget> {
  ModalRoute<dynamic>? _route;

  // ...

  @override
  void dispose() {
    _route?.removeScopedWillPopCallback(askTheUserIfTheyAreSure);
    _route = null;
    super.dispose();
  }
}

See also:

  • WillPopScope, which manages the registration and unregistration process automatically.
  • Form, which provides an onWillPop callback that uses this mechanism.
  • willPop, which runs the callbacks added with this method.
  • removeScopedWillPopCallback, which removes a callback from the list that willPop checks.

Implementation

void addScopedWillPopCallback(WillPopCallback callback) {
  assert(_scopeKey.currentState != null, 'Tried to add a willPop callback to a route that is not currently in the tree.');
  _willPopCallbacks.add(callback);
}