How do use a Switch Case Statement in Dart

DartSwitch StatementConditional Statements

Dart Problem Overview


I am trying to understand how the switch is working in the dart. I have very simple code:

methodname(num radians) {
  switch (radians) {
    case 0:
      // do something
      break;
    case PI:
      // do something else
      break;
  }
}

This unfortunately does not work. If left like this the error is: case expressions must have the same type (I think the type is num, but not the editor). If I change 0 to 0.0 it says: The switch type expression double cannot override == operator - I have no idea what this means!

So what is the way to do this switch case? I can turn it onto if/else probably but I wanted to know how to make the switch work and why is it not working in the first place.

I am running the latest stable version of DartEditor.

Dart Solutions


Solution 1 - 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

some more information:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeter StJView Question on Stackoverflow
Solution 1 - DartGünter ZöchbauerView Answer on Stackoverflow