[Dart] WildCard Variables

[Dart] WildCard Variables

Did you know that wildcard variables were introduced in Dart 3.7?

Let’s explore what they are and why you might want to use them.

So... What is a WildCard Variable?

A wildcard variable _ declares a local variable or parameter that is non-binding. It serves as a placeholder.

Where Can You Declare Wildcards?

At its core, a wildcard can appear in:

  • local declarations
  • function parameters
  • catch clauses
  • loop variables
  • and even generic types

A quick recap

Before Dart 3.7, we were writing functions like below to avoid name collisions

function A(_ , __, ___)

Now since Dart 3.7, we can simply writing it as follows:

function A(_, _, _)

To use it, make sure your SDK in pubspec.yml is set to 3.7 or above

environment:
  sdk: ^3.8.1

Why use _?

Wildcards are useful when you want to ignore values that you don’t need.
They tell the compiler: “Yes, I’m aware of this value, but I don’t need it.”

They can match any type, and they don’t create assignments or memory bindings for those values.

Common Uses

  1. Destructuring records, or lists.
void main() {
  var (country, _, _) = record;
  print(country); // France is returned
}

var record = ('France', 'Orange', 'Car');
  1. Declaring local variable
var _ = 10;
  1. Loop Variables
for (final _ in [1, 2, 3]) {
  print('tick');
}
  1. Catch Clause Parameters
try {
  throw Exception('error');
} catch (_) {
  print('Something went wrong.');
}
  1. Generic Types
List<_> values = [];

What you need to know

  • Wildcards do not create variables that you can use later.

And that's it. On that note, I hope you learned something new!


References

Variables
Learn about variables in Dart.

About Me

I am Zaahra, a Google Women Techmakers Ambassador who enjoy mentoring people and writing about technical contents that might help people in their developer journey. I also enjoy building stuffs to solve real life problems.

To reach me:

LinkedIn: https://www.linkedin.com/in/faatimah-iz-zaahra-m-0670881a1/

X (previously Twitter): _fz3hra

GitHub: https://github.com/fz3hra

Cheers,

Umme Faatimah-Iz-Zaahra Mujore | Google Women TechMakers Ambassador | Software Engineer