How do use a Switch Case Statement in Dart

The comparsion of double values using '==' is not very reliable and should be avoided (not only in Dart but in most languages).

You could do something like

methodname(num radians) {
  // you can adjust this values according to your accuracy requirements
  const myPI = 3142; 
  int r = (radians * 1000).round();

  switch (r) {
    case 0:
      // do something
      break;
    case myPI: 
      // do something else
      break;
  }
}

This question contains some additional information that might interest you

  • comparing float/double values using == operator
  • How should I do floating point comparison?

some more information:

  • https://www.dartlang.org/docs/spec/latest/dart-language-specification.html#h.50ae78s6gbw2
  • http://floating-point-gui.de/errors/comparison/

Switch statements in Dart compare integer, string, or compile-time constants using ==. The compared objects must all be instances of the same class (and not of any of its subtypes), and the class must not override ==. Enumerated types work well in switch statements.

Each non-empty case clause ends with a break statement, as a rule. Other valid ways to end a non-empty case clause are a continue, throw, or return statement.

Use a default clause to execute code when no case clause matches:

var command = 'OPEN';
switch (command) {
  case 'CLOSED':
    executeClosed();
    break;
  case 'PENDING':
    executePending();
    break;
  case 'APPROVED':
    executeApproved();
    break;
  case 'DENIED':
    executeDenied();
    break;
  case 'OPEN':
    executeOpen();
    break;
  default:
    executeUnknown();
}

The following example omits the break statement in a case clause, thus generating an error:

var command = 'OPEN';
switch (command) {
  case 'OPEN':
    executeOpen();
    // ERROR: Missing break

  case 'CLOSED':
    executeClosed();
    break;
}

However, Dart does support empty case clauses, allowing a form of fall-through:

var command = 'CLOSED';
switch (command) {
  case 'CLOSED': // Empty case falls through.
  case 'NOW_CLOSED':
    // Runs for both CLOSED and NOW_CLOSED.
    executeNowClosed();
    break;
}

If you really want fall-through, you can use a continue statement and a label:

var command = 'CLOSED';
switch (command) {
  case 'CLOSED':
    executeClosed();
    continue nowClosed;
  // Continues executing at the nowClosed label.

  nowClosed:
  case 'NOW_CLOSED':
    // Runs for both CLOSED and NOW_CLOSED.
    executeNowClosed();
    break;
}

A case clause can have local variables, which are visible only inside the scope of that clause.