Skip to content

<callback>

A tag that binds an event handler with custom arguments. If you don't need to pass any arguments, bind the handler directly using EL: <TextButton onPressed="${onPressed}"/>. This is sufficient in most cases.

The <callback> tag creates an event handler function and executes the action when the event is triggered. action is an EL expression that is evaluated at the time of the event. Do not enclose the expression in curly braces ${...}, otherwise it will be evaluated immediately upon creation instead of when the event is fired.

If the handler function defines arguments in its signature, declare them using the vars attribute. This attribute takes a comma-separated list of argument names. When the handler is triggered, argument values are added to Dependencies using the specified name as the key, and can be referenced in the action expression. By default these values are scoped to the invocation and do not persist after the handler returns (see dependenciesScope). If you don't need the values, use an underscore (_) in place of the name — those values won't be added to Dependencies. BuildContext is never added to Dependencies even when named, because this would cause a memory leak.

Attributes

Name Type Description Required Default
for String The name of the parent's attribute that will be assigned the event handler. Yes -
action String The EL expression to evaluate when the event handler is triggered. Yes -
vars String A comma-separated list of handler function arguments. Named arguments are stored as dependencies. Supports up to five. No null
returnVar String The dependency key in which to store action's return value. Always written to the surrounding Dependencies (independent of dependenciesScope), so other widgets can read it. No null
dependenciesScope String How dependencies are scoped while action is evaluated (does not affect returnVar). One of new, copy, or inherit. Defaults to inherit, or copy when vars is present. No auto

Examples

Basic Callback

<TextButton>
    <callback for="onPressed" action="doSomething('Hello World')"/>
    <Text>Press Me</Text>
</TextButton>

Callback with Arguments

<ListView.builder itemCount="${length(items)}">
    <builder for="itemBuilder" vars="_,index">
        <ListTile>
            <Text for="title" data="${items[index].name}"/>
            <callback for="onTap" action="selectItem(items[index])"/>
        </ListTile>
    </builder>
</ListView.builder>

Callback with Return Value

<TextButton>
    <callback for="onPressed" action="computeTotal()" returnVar="total"/>
    <Text>Calculate</Text>
</TextButton>

The return value of computeTotal() is stored in the total dependency key in the surrounding scope, where other widgets can reference it as ${total}. returnVar is always written to the surrounding Dependencies, regardless of dependenciesScope.

See Also

  • <builder> - For wrapping children in a builder function
  • Expression Language - EL syntax reference