invoke method

bool invoke (
  1. BuildContext context,
  2. Intent intent,
  3. {FocusNode focusNode,
  4. bool nullOk: false}
)

Invokes the action associated with the given Intent using the Actions widget that most tightly encloses the given BuildContext.

The context, intent and nullOk arguments must not be null.

If the given intent isn't found in the first Actions.actions map, then it will move up to the next Actions widget in the hierarchy until it reaches the root.

Will throw if no ambient Actions widget is found, or if the given intent doesn't map to an action in any of the Actions.actions maps that are found.

Returns true if an action was successfully invoked.

Setting nullOk to true means that if no ambient Actions widget is found, then this method will return false instead of throwing.

Implementation

static bool invoke(
  BuildContext context,
  Intent intent, {
  FocusNode focusNode,
  bool nullOk = false,
}) {
  assert(context != null);
  assert(intent != null);
  Element actionsElement;
  Action action;

  bool visitAncestorElement(Element element) {
    if (element.widget is! Actions) {
      // Continue visiting.
      return true;
    }
    // Below when we invoke the action, we need to use the dispatcher from the
    // Actions widget where we found the action, in case they need to match.
    actionsElement = element;
    final Actions actions = element.widget as Actions;
    action = actions.actions[intent.key]?.call();
    // Keep looking if we failed to find and create an action.
    return action == null;
  }

  context.visitAncestorElements(visitAncestorElement);
  assert(() {
    if (nullOk) {
      return true;
    }
    if (actionsElement == null) {
      throw FlutterError('Unable to find a $Actions widget in the context.\n'
          '$Actions.invoke() was called with a context that does not contain an '
          '$Actions widget.\n'
          'No $Actions ancestor could be found starting from the context that '
          'was passed to $Actions.invoke(). This can happen if the context comes '
          'from a widget above those widgets.\n'
          'The context used was:\n'
          '  $context');
    }
    if (action == null) {
      throw FlutterError('Unable to find an action for an intent in the $Actions widget in the context.\n'
          "$Actions.invoke() was called on an $Actions widget that doesn't "
          'contain a mapping for the given intent.\n'
          'The context used was:\n'
          '  $context\n'
          'The intent requested was:\n'
          '  $intent');
    }
    return true;
  }());
  if (action == null) {
    // Will only get here if nullOk is true.
    return false;
  }

  // Invoke the action we found using the dispatcher from the Actions Element
  // we found, using the given focus node.
  return _findDispatcher(actionsElement).invokeAction(action, intent, focusNode: focusNode);
}