Can I use 'is' operator in a switch case in Dart?

No.

The Dart switch case is a very low-level construct. It allows only constant-value expressions that don't override operator == (except for a few basic platform types), so effectively it can be implemented using identical checks.

There is no ability to do complicated checks, or checks on the type of the object, only identity checks.

The recommended pretty way to do what you want is to have ClassA, ClassB and ClassC all implement an interface with a doStuff member, and then do:

 currentState.doStuff()

If that is not possible, you are back to the if sequence.


You can't use the same syntax as in Kotlin but you can use Freezed.

https://pub.dev/packages/freezed

It allows you to use a similar syntax.

Considering this model:

@freezed
abstract class Model with _$Model {
  factory Model.first(String a) = First;
  factory Model.second(int b, bool c) = Second;
}

You can use when in the following way:

var model = Model.first('42');

print(
  model.when(
    first: (String a) => 'first $a',
    second: (int b, bool c) => 'second $b $c'
  ),
); // first 42

switch (runtimeType) {
   case ClassA: //do stuff 
      return;
   case ClassB: //do stuff
      return;
}