Skip to content

Feature Request: Add .toggle() extension for bool in Dart #60064

@dbspoudel

Description

@dbspoudel

In Swift, the Bool type has a built-in .toggle() method that flips the value between true and false. It simplifies boolean state management and avoids repetitive expressions like:

isEnabled = !isEnabled;

I propose adding a .toggle() method for bool in Dart, which would allow:

bool isEnabled = false;
isEnabled.toggle();  // Now isEnabled is true
print(isEmabled) // true

Use Case
This feature would improve readability and reduce redundancy, especially in stateful applications where toggling booleans is common.

Proposed Implementation
A simple method can be added to bool class in the Dart SDK:

/// Toggles the value of this boolean and stores it back in the same variable.
///
/// Example:
/// ```dart
/// bool value = true;
/// value.toggle();
/// print(value); // false
/// ```
void toggle() {
    this = !this;
  }

Adding .toggle() to bool would improve developer experience, reduce verbosity, and align Dart with other modern programming languages.

References
Swift's toggle() method: here

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions