2

Given the following block of code in Flutter, I am seeing syntax errors that I wouldn't expect

FloatingActionButton(
  onPressed: () => {
        //undefined name x, Expected to find ','
        int x = 12; 

        //Unexpected text 'return'
        if (_timer != null && _timer!.isActive)
        {
          return
        }

        _timer =
            Timer.periodic(Duration(milliseconds: 250), (timer) {
          for (var i = 0; i < 6; i++) {
            myKeys[i].currentState?.roll();
          }
        })
      },
  child: const Icon(Icons.check),
),

In JS (or c#) something like this works fine:

const f = ()=> {
  var j = "123";
  console.log(j);
  return;
}

Other than "because it wasn't implemented that way", why doesn't this work in Dart and what's the right way to do this?

2
  • Ok you need () { ..., not () => { ... Commented May 28, 2022 at 16:47
  • In Dart, () => { ... } declares a zero-argument anonymous function that returns a Set literal. Commented May 28, 2022 at 17:58

3 Answers 3

2

for your onTap-parameter: either you use a block body () {} for more than one statement or an arrow-function for a single statement () => print("hello world")

Also don't forget the semicolon after the return keyword

fixed solution:

FloatingActionButton(
  onPressed: () {
    int x = 12;

    if (_timer != null && _timer!.isActive) {
      return;
    }

    _timer =
        Timer.periodic(Duration(milliseconds: 250), (timer) {
      for (var i = 0; i < 6; i++) {
        myKeys[i].currentState?.roll();
      }
    });
  },
  child: const Icon(Icons.check),
),


Sign up to request clarification or add additional context in comments.

Comments

2

Both Dart and JavaScript support arrow syntax (=>), but they are different. In Dart, arrow syntax is only used when the function contains a single expression or return statement.

dart documentation

Comments

1

Arrow functions are used for single statement execution such as,

onPressed: () => Navigator.push(//stuff in here);

whereas block statements are used for multiple statements to execute i.e.

onPressed: (){
// Do a lot of stuff in here
},

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.