Home > Blockchain >  Flutter / Dart syntax Inside an anonymous function
Flutter / Dart syntax Inside an anonymous function

Time:05-29

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?

CodePudding user response:

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),
),


CodePudding user response:

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

CodePudding user response:

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
},
  • Related