Home > Back-end >  Switch statement inside getter
Switch statement inside getter

Time:10-23

How do I define a switch statement inside a getter in Dart?

// Doesn't work... ❌
get String buttonText => {
  switch (step) {
    case 1: return "Register >";
    case 2: return "Confirmation >";
  }
  throw "Invalid step";
}

It fails with what looks like a syntax error:

Expected to find '}'.dart(expected_token)

I find this weird, because it works just fine in function form:

// Works fine... ✅
String buttonText() {
  switch (step) {
    case 1: return "Register >";
    case 2: return "Confirmation >";
  }
  throw "Invalid step";
}

CodePudding user response:

Remove the fat arrow => and it should work fine.

String get buttonText {
  ....

In dart, you can only have one or the other: Either you have curly brackets, or a fat arrow. In case of curly brackets you must have a return statement. In case of a fat arrow, any expression that comes after it would be the returned value.

// either
String get one => "1";

// or
String get one {
  return "1";
}

EDIT: (based on cameron1024's comment)

The only exception to that rule is if you are returning a map literal, as such: someFunction() => {} which is a function that returns an empty set.

CodePudding user response:

I believe you are confusing this with JS/TS (probably?) . As mentioned in the documentation,

"Only an expression—not a statement—can appear between the arrow (=>) and the semicolon (;)"

Moreover,

The => expr syntax is a shorthand for { return expr; }.

Unlike JS, => { expr } is invalid and for multi line statements { expr } should be used instead.

Note: This rule not only applies to getters, but to functions and setters as well.

  • Related