Dart anonymous function confusion
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 j
th 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
.
Themelis
Updated on December 10, 2022Comments
-
Themelis 11 months
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 theBuildContext
andint
will be provided to the function. -
Themelis over 4 yearsThanks for the clear answer. I guess its an elementary question to those who know about functional programming. One more thing about that function that I'm passing in the constructor of the ListView... Is that what a closure is all about?
-
Richard Heap over 4 yearsPretty much, yes. In your builder function you access
_suggestions
which isn't local to the function (unlikecontext
andi
which are actual parameters). Nor is it part of theListView
that's making the callback. Yet your function has access to it, because it has 'captured' it. A closure is a function plus an environment. In your code, it's clear what the function is. The environment is the extra bit that allows that function to reach up and access the member variable of your stateful widget.