Themelis
Themelis

Reputation: 4255

Dart anonymous function confusion

I would like an explanation of anonymous functions in Dart and how are passed as arguments to other functions.

The example demonstrated below comes from the Write your first app of flutter.dev.

Widget _buildSuggestions() {
  return ListView.builder(
      padding: const EdgeInsets.all(16.0),
      itemBuilder:  (context, i) {
        if (i.isOdd) return Divider(); 

        final index = i ~/ 2; 
        if (index >= _suggestions.length) {
          _suggestions.addAll(generateWordPairs().take(10)); 
        }
        return _buildRow(_suggestions[index]);
      });
}

The anonymous function here is the itemBuilder. Its type is {(BuildContext, int) → Widget itemBuilder}.

If its type was {() → Widget itemBuilder} I could understand that during runtime the body of the function will be executed. But now with the arguments I don't get how the BuildContext and int will be provided to the function.

Upvotes: 1

Views: 3712

Answers (1)

Richard Heap
Richard Heap

Reputation: 51770

In the constructor of the ListView you are passing a function, which the list view is going to hold onto, maybe as some instance variable called builderFunc. At some point in the future, the list view is going to be told to build and it will need to build its children. It's going to do this by calling builderFunc like this:

Widget jthChild = builderFunc(ctx, j);

where ctx and j are local variables in the scope of the caller (the method in ListView). builderFunc (your anonymous function) will construct and return the jth widget, using the build context passed to it by the list view. The list view will call your function multiple times with different values of j.

Upvotes: 1

Related Questions