Skip to main content
The * operator functions as the multiplicative binary operator in Dart. It is used to perform arithmetic multiplication on numeric types, repetition on string types, and sequence delegation when combined with the yield keyword.

Arithmetic Multiplication

When applied to operands of type int or double, the * operator calculates the product. The return type is determined by the operands:
  • int * int: Returns int.
  • double * double, int * double, or double * int: Returns double.
int resultInt = 5 * 4;          // 20
double resultDouble = 2.5 * 2;  // 5.0

String Repetition

The String class overrides the * operator. When the left operand is a String and the right operand is an int, the operator returns a new string containing the original string concatenated with itself the specified number of times.
String pattern = "xy" * 3; // "xyxyxy"
String empty = "Dart" * 0; // ""

Operator Overloading

Custom classes can define the behavior of the * operator by implementing the operator * method. The method signature defines the expected type of the right-hand operand and the return type of the operation.
class Vector2 {
  final int x, y;
  Vector2(this.x, this.y);

  // Overloading * to scale the vector
  Vector2 operator *(int scale) {
    return Vector2(x * scale, y * scale);
  }
}

void main() {
  final v = Vector2(1, 2);
  final scaled = v * 3; // Vector2(3, 6)
}

Generator Delegation (yield*)

In the context of generator functions (sync* or async*), the * symbol modifies the yield statement. The yield* statement delegates the generation of values to another iterable or stream. It pauses the current function and emits all values from the target sequence before resuming.
Iterable<int> subCounter() sync* {
  yield 10;
  yield 20;
}

Iterable<int> mainCounter() sync* {
  yield 1;
  yield* subCounter(); // Delegates emission to subCounter
  yield 2;
}

// Output of mainCounter: 1, 10, 20, 2
Master Dart with Deep Grasping Methodology!Learn More