简体   繁体   English

Flutter/Dart - () {} 和 () => {} 之间的区别

[英]Flutter/Dart - Difference between () {} and () => {}

In Flutter/Dart the examples sometimes show fat arrow and sometimes dont.在 Flutter/Dart 中,示例有时显示粗箭头,有时不显示。 Here are examples:以下是示例:

RaisedButton(
  onPressed: () {
    setState(() {
      _myTxt = "Text Changed";
    });
  },

Elsewhere you see:在其他地方你会看到:

void main() => runApp(MyApp());

The fat arrow syntax is simply a short hand for returning an expression and is similar to (){ return expression; }粗箭头语法只是返回表达式的简写,类似于(){ return expression; } (){ return expression; } . (){ return expression; }
According to the docs .根据文档

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例如,您不能在其中放置 if 语句,但可以使用条件表达式

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.从上面的代码可以看出,当使用回调函数并返回一个值时,可以进行多行语句,而胖箭头只是一个没有返回关键字的表达式。

Considering your answer about fat arrows not supporting multiline statements in dart.考虑到您关于胖箭头不支持 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"; }这是可以理解的,因为执行() => {somtheing}意味着您正在返回一个地图,并且它会期望看到类似() => {'name':'John', 'age':25}而不是() => { _myTxt = "Text Changed";_myTxt = "Never Mind"; } () => { _myTxt = "Text Changed";_myTxt = "Never Mind"; } . () => { _myTxt = "Text Changed";_myTxt = "Never Mind"; }

I found that the mean the exact same thing.我发现这意味着完全相同的事情。 The only difference is that you can use (you don't have to) the fat arrow if there is only one statement.唯一的区别是,如果只有一个语句,您可以使用(您不必)粗箭头。 Following is the above RaisedButton declaration with the fat arrow.以下是上面带有粗箭头的RaisedButton声明。 Notice I had to remove two curly braces and one semi-colon:请注意,我必须删除两个花括号和一个分号:

RaisedButton(
  onPressed: () {
    setState(() =>
      _myTxt = "Text Changed"
    );
  },

If you are used to other languages that allow you to put multiple statements after a fat arrow you'll you'll find that you can't in dart and if you try you'll get an error as in the following:如果你习惯了其他允许你在粗箭头后面放置多个语句的语言,你会发现你不能在 dart 中,如果你尝试你会得到一个错误,如下所示:

this wont work这行不通

RaisedButton(
  onPressed: () {
    setState(() => {
      _myTxt = "Text Changed";
      _myTxt = "Never Mind";
    });
  },

They are both for expressing anonymous functions.它们都用于表达匿名函数。 The fat arrow is for returning a single line, braces are for returning a code block.粗箭头用于返回单行,大括号用于返回代码块。

A fat arrow trying to return a code block will not compile.试图返回代码块的粗箭头将无法编译。

=> is used to return a value of an anonymous function. =>用于返回匿名函数的值。

() {} lets you execute multiple statements. () {}允许您执行多个语句。

while尽管

() => {myVar} or () => myVar; () => {myVar}() => myVar; allows one single statement.允许一个单一的语句。

() => myVar; is short and simple when returning one statement.返回一个语句时简短而简单。


The same logic goes for creating non anonymous functions too.同样的逻辑也适用于创建非匿名函数。

Single statement func func() => y = x + x;单语句 func func() => y = x + x;

Multiple statement func多语句函数

func () {
   x = x + x; 
   print(x + ' value of x');
};

=> Short hand expression is used to define a single expression in a function. => 简写表达式用于在函数中定义单个表达式。 Enough with the definition and properties.足够的定义和属性。

  • By using fat arrow => the curly brackets needs to be removed.通过使用胖箭头 => 需要删除大括号。 Otherwise, the code editor will show you an error.否则,代码编辑器会显示错误。
  • If a function has a return type then by using a Fat arrow it is required to remove the return keyword.如果函数具有返回类型,则需要使用胖箭头删除 return 关键字。

Below Both are the same function and will return the same value.下面两者都是相同的函数,将返回相同的值。 Just a different syntax只是语法不同

This is with => type这是 => 类型

var size = (int s) => s*2;

This is return type这是return类型

var size = (int s) { 
  return s*2; 
} 

To understand the concept with a real code example.用一个真实的代码示例来理解这个概念。 We will consider the same examples that are done in Dart functions tutorial.我们将考虑在 Dart 函数教程中完成的相同示例。 The code executes the Perimeter and Area of a rectangle.代码执行矩形的周长和面积。 This is how usually it is done with the help of functions.这通常是在函数的帮助下完成的。

 void main() {
  findPerimeter(9, 6);
  var rectArea = findArea(10, 6);
  print('The area is $rectArea');
}

void findPerimeter(int length, int breadth) {
  var perimeter = 2 * (length * breadth);
  print('The perimeter is $perimeter');
}

int findArea(int length, int breadth) {
  return length * breadth;
}

The given functions can be optimized with the help of fat arrow in Dart.可以借助 Dart 中的粗箭头优化给定的函数。

 void main() {
  findPerimeter(9, 6);
  var rectArea = findArea(10, 6);
  print('The area is $rectArea');
}

void findPerimeter(int length, int breadth) =>
  print('The perimeter is ${2 * (length * breadth)}');


int findArea(int length, int breadth) =>
   length * breadth;

After hitting the run button we are still getting the same result.按下运行按钮后,我们仍然得到相同的结果。

The perimeter is 108
The area is 60

Is from : https://flutterrdart.com/dart-fat-arrow-or-short-hand-syntax-tutorial/来自: https ://flutterrdart.com/dart-fat-arrow-or-short-hand-syntax-tutorial/

There seems to be one difference at least in case of Dart version 2.10:至少在 Dart 2.10 版的情况下似乎有一个区别:

If the expression to be executed is a Future, then the execution order is not the same.如果要执行的表达式是Future,那么执行顺序就不一样了。

=> =>

new Future(() => print('future #1 of 2'))
  .then((_) => new Future(() => print('future #1a (a new future)')))
  .then((_) => print('future #1b'));

new Future(() => print('future #2 of 2'))
  .then((_) => new Future(() => print('future #2a (aa new futue)' )))
  .then((_) => print('future #2b'));

The result is:结果是:

future #1 of 2
future #2 of 2
future #1a (a new future)
future #1b
future #2a (aa new futue)
future #2b`

{} : {}:

new Future(() => print('future #1 of 2'))
  .then((_) => new Future(() => print('future #1a (a new future)')))
  .then((_) => print('future #1b'));

new Future(() => print('future #2 of 2'))
  .then((_) { new Future(() => print('future #2a (aa new futue)' )); })
  .then((_) => print('future #2b'));

The result is结果是

future #1 of 2
future #2 of 2
future #2b
future #1a (a new future)
future #1b
future #2a (a new futue)

Fat Aarrow => Single line of code => Expression form, does not use return statement , the expression is automatically returned Fat Aarrow => 单行代码 => 表达式形式,不使用return语句,表达式自动返回

void main() => runApp(MyApp()); // you cannot specify return here. This
is the turned value from the function. This is shorthand form

No fat arrow, uses {}, can have multiple statements, have to use return statement if we want to return a value, if not return can be skipped没有粗箭头,使用{},可以有多个语句,如果要返回值必须使用return语句,如果没有return可以跳过

setState(() {
      _myTxt = "Text Changed";
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM