Using underscores for unused builder arguments in Dart
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(), ));
Code with Andrea is free for everyone. Help me keep it that way by checking out this sponsor:
Faster mobile builds; faster deliveries with Codemagic CI/CD: Do not waste valuable developer resources, replace manual intervention and build, test and deliver mobile apps 20% faster with CI/CD for mobile.
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.