Skip to main content
The is operator is a type test operator that performs a runtime check to determine if an object conforms to a specific type. It evaluates to a boolean value, returning true if the object is an instance of the specified type or any of its subtypes.

Syntax

expression is Type

Evaluation Semantics

The expression obj is T evaluates to true if the runtime type of obj is a subtype of T. In Dart’s nominal type system, this encompasses the following scenarios:
  1. Direct Instance: obj is an instance of the exact class T.
  2. Subtype Polymorphism: obj is an instance of a class that extends, implements, or mixes in T.
  3. Reified Generics: The runtime type arguments of obj satisfy the constraints of T (e.g., List<int> is a subtype of List<num>).

Nullability Rules

In null-safe Dart, the evaluation logic accounts for the nullability of the target type T:
  • Non-nullable Target: If obj evaluates to null and T is non-nullable (e.g., int), the expression evaluates to false.
  • Nullable Target: If obj evaluates to null and T is nullable (e.g., int? or Null), the expression evaluates to true.

Type Promotion

The is operator is integrated into Dart’s flow analysis. When the operator evaluates to true within a control flow structure, the compiler promotes the static type of the variable to the checked type within the guarded scope. Type promotion occurs only when the compiler can guarantee type stability between the check and the usage. Eligible targets include:
  1. Local variables and parameters.
  2. Private final instance fields (since Dart 3.2), provided no conflicting getter exists in the class hierarchy.
Public instance fields and non-final fields generally do not undergo promotion because the compiler cannot guarantee that the value remains unchanged by external actors or subclass overrides.
class Box {
  final Object _value; // Private final field

  Box(this._value);

  void printIfString() {
    // Flow analysis promotes _value from Object to String
    if (_value is String) {
      print(_value.length); 
    }
  }
}

The is! Operator

The is! operator serves as the logical negation of the is operator. The expression obj is! T is syntactic sugar for !(obj is T).
if (obj is! String) {
  // Executed if the runtime type of obj is NOT String or a subtype of String
}
Master Dart with Deep Grasping Methodology!Learn More