匿名函数内部的 Flutter / Dart 语法
Flutter / Dart syntax Inside an anonymous function
鉴于 Flutter 中的以下代码块,我看到了意想不到的语法错误
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),
),
在 JS(或 c#)中,类似这样的东西工作正常:
const f = ()=> {
var j = "123";
console.log(j);
return;
}
除了“因为它不是那样实现的”之外,为什么这在 Dart 中不起作用?正确的方法是什么?
箭头函数用于单条语句执行,例如,
onPressed: () => Navigator.push(//stuff in here);
而块语句用于执行多个语句,即
onPressed: (){
// Do a lot of stuff in here
},
你的onTap-parameter:
要么对多个语句使用块体 () {}
,要么对单个语句使用 arrow-function () => print("hello world")
另外不要忘记return
关键字后的分号
固定解:
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),
),
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.
鉴于 Flutter 中的以下代码块,我看到了意想不到的语法错误
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),
),
在 JS(或 c#)中,类似这样的东西工作正常:
const f = ()=> {
var j = "123";
console.log(j);
return;
}
除了“因为它不是那样实现的”之外,为什么这在 Dart 中不起作用?正确的方法是什么?
箭头函数用于单条语句执行,例如,
onPressed: () => Navigator.push(//stuff in here);
而块语句用于执行多个语句,即
onPressed: (){
// Do a lot of stuff in here
},
你的onTap-parameter:
要么对多个语句使用块体 () {}
,要么对单个语句使用 arrow-function () => print("hello world")
另外不要忘记return
关键字后的分号
固定解:
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),
),
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.