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:

Navigator.of(context).push(MaterialPageRoute( builder: (context) => DetailPage(), ));

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.

Takeaway: using _ for unused builder arguments carries meaning, and makes the code more concise.

Want More?

Invest in yourself with my high-quality Flutter courses.

The Complete Dart Developer Guide

The Complete Dart Developer Guide

Learn Dart Programming in depth. Includes: basic to advanced topics, exercises, and projects. Fully updated to Dart 2.15.

Flutter Animations Masterclass - Full Course

Flutter Animations Masterclass - Full Course

Master Flutter animations and build a completely custom habit tracking application.

Flutter & Firebase Course: Build a Complete App for iOS & Android

Flutter & Firebase Course: Build a Complete App for iOS & Android

A full course with in-depth content, taking you from the basics all the way up to more advanced topics.

Flutter REST API Crash Course

Flutter REST API Crash Course

Build a Coronavirus Tracking App, and learn how to use REST APIs in Flutter.

Get the best Flutter tutorials, right in your inbox.

Join over 16,000 developers who receive my weekly Flutter email course & newsletter:

No spam, ever. Unsubscribe at any time.