Search code examples
dartchainingternary

How can I use a switch statement when passing an argument to a function? (dart)


In Dart, one can use switch statements rather than a long if-then-else

var command = 'OPEN';
switch (command) {
  case 'CLOSED':
    executeClosed();
    break;
  case 'OPEN':
    executeOpen();
    break;
  default:
    executeUnknown();
}

but sometimes we just want to provide a value based on a condition. Like, inside of an function call, class instantiation, or setting the value of a variable, etc.

For example

// Doesn't work, but wish it did
MakeNametag(
   adjustFontSize: switch(status) {
     case 'young' : return 'large';
     case 'old' : return 'largest';
     default: return 'normal';
    } //end switch
  }
);

If you just have two options, one can use conditional operator (sometimes called ternary operator)

// Works
MakeNametag(
  adjustFontSize: ['old','young'].contains(status) ? 'larger' : 'normal');

(javascript has the same operator and issue)


Solution

  • Often times instead of a simple switch statement, you can define a map literal and immediately subscript [] into it. Use the if null operator ?? for the default case.

    MakeNametag(adjustFont: {'young': 'large', 'old': 'largest'}[status] ?? 'normal');
    

    Often times you can also make the map literal const for a small performance improvement.

    MakeNametag(adjustFont: const {'young': 'large', 'old': 'largest'}[status] ?? 'normal');