Flutter / Dart-(){}与()=>之间的差异; {} [英] Flutter/Dart - Difference between () {} and () => {}
问题描述
在Flutter / Dart中,示例有时显示粗箭头,有时不显示。以下是示例:
In Flutter/Dart the examples sometimes show fat arrow and sometimes dont. Here are examples:
RaisedButton(
onPressed: () {
setState(() {
_myTxt = "Text Changed";
});
},
在其他地方可以看到:
void main() => runApp(MyApp());
推荐答案
胖箭头语法只是返回表达式的简写方式,类似于(){返回表达式;}
。
根据文档。
The fat arrow syntax is simply a short hand for returning an expression and is similar to (){ return expression; }
.
According to the docs.
注意:仅表达式而不是语句-可以出现在箭头(=>)和分号(;)之间。例如,您不能在其中放置if语句,但是可以使用条件表达式
Note: Only an expression—not a statement—can appear between the arrow (=>) and the semicolon (;). For example, you can’t put an if statement there, but you can use a conditional expression
void main(){
final cls = TestClass();
cls.displayAnInt((){
//you can create statements here and then return a value
int num1 = 55;
int num2 = 1;
int sum = num1 + num2;
return sum;
});
cls.displayAnInt(() => 55 + 1); // simply return an int expression
}
class TestClass{
displayAnInt(makeIntFunc){
int intValue = makeIntFunc();
print('The int value is $intValue');
}
}
从上面的代码中,您可以看到在以下情况下可以执行多行语句
From the code above, You can see that multiline statement can be made when the callback function is used and then a value is returned, while the fat arrow simply has an expression with no return keyword.
考虑您对不支持dart中多行语句的粗箭头的回答。这是可以理解的,因为这样做()=> {somtheing}
表示您正在返回地图,并且可能会看到类似()=>的内容。 {’name’:’John’,‘age’:25}
而不是()=> {_myTxt =文字已更改; _myTxt =从不介意; }
。
Considering your answer about fat arrows not supporting multiline statements in dart. This is quite understandable since doing () => {somtheing}
would imply you are returning a map and it would expect to see something like () => {'name':'John', 'age':25}
and not () => { _myTxt = "Text Changed";_myTxt = "Never Mind"; }
.
这篇关于Flutter / Dart-(){}与()=>之间的差异; {}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!