Dart Wildcard Variable _ — How and When to Use It

Understand the special underscore variable in Dart, with clear examples and use cases.

Introduction

In Dart, the underscore (_) is often called the wildcard variable or throwaway variable, because it is used to indicate that a value is intentionally ignored. Think of it as saying: "I need a placeholder here, but I don’t care about its value."

1. Basic Purpose

The wildcard variable tells both the reader (and sometimes the compiler) that this variable is not meant to be used. It's commonly used in:

  • Function parameters that are unused
  • Destructuring patterns when only part of the values are needed
  • Loops where the loop variable is not required
// Example: unused parameter
void printHello(int _, String name) {
  // Ignore the int parameter
  print('Hello $name');
}

void main() {
  printHello(100, 'Dart'); // Output: Hello Dart
}

2. Using _ in Loops

If you don’t need the loop variable, you can replace it with _:

// Example: for loop without using the variable
void main() {
  for (var _ = 0; _ < 3; _++) {
    print('Hello');
  }
}

Or in a for-in loop:

void main() {
  for (var _ in [1, 2, 3]) {
    print('Loop without using the element');
  }
}

3. Ignoring Values in Destructuring

When using pattern matching or records, _ is used to skip certain values.

(String, int) getUser() {
  return ('Alice', 25);
}

void main() {
  var (_, age) = getUser(); // Ignore the name
  print(age); // 25
}

4. _name vs _

An underscore at the start of a variable name (e.g., _counter) makes it private to its library, which is different from the wildcard variable.

int _counter = 0; // Private variable, NOT a wildcard

5. Linting & Best Practices

Dart's linter may warn you about unused variables or parameters. Replacing them with _ signals that this is intentional, making the code cleaner and more readable.

Summary Table

Form Meaning
_ Wildcard, ignore the value
_name Private variable in a library
_ in loops Loop without using the variable
_ in destructuring Ignore certain values

0 Comments:

Post a Comment