The builder pattern is an essential building block for creating composable UIs in Flutter.
As such, Flutter exposes convenience builder types that are used as arguments in many widget classes.
Here are a couple of examples from the Flutter SDK:
/// Signature for a function that creates a widget, e.g. [StatelessWidget.build] /// or [State.build]. typedef WidgetBuilder = Widget Function(BuildContext context); /// Signature for a function that creates a widget for a given index, e.g., in a /// list. typedef IndexedWidgetBuilder = Widget Function(BuildContext context, int index);
A very common use case of builders is when pushing a new route with
Navigator.of(context).push(MaterialPageRoute( builder: (context) => DetailPage(), ));
Get Doppio Today. A fully managed API for developers that enables you to generate beautiful PDF or screenshots and store them directly in your own S3 bucket without compromising privacy.
However, if the context argument in the builder is not used, it can be replaced with
_ (which is a valid identifier name in Dart):
Navigator.of(context).push(MaterialPageRoute( builder: (_) => DetailPage(), ));
This also works with builders that take more than one argument. For example, here's a
ListView where both the context and index arguments are not used:
ListView.builder( itemBuilder: (_, __) => ListTile(title: Text('a list item')), );
Note how we use
__ (double underscore) for the second argument, to differentiate it from the first one.
_for unused builder arguments carries meaning, and makes the code more concise.