14

I am new to flultter and dart. I see main calls the first widget as follows with added print statements.

void main() {
  print('begin ');
  runApp(MyApp());
  print('end');
}

I see another way is

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

but when I try following it does not work

void main() => { print(' begin '); runApp(MyApp()); };

My question is if I want to run multiple statements in second( => ) approach, how I can do that and what is the name of => operator ?

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402

5 Answers5

34

i dont know why no one answered but yes its possible to call many statements with an arrow function but you need a comma in between (simlair to passing arguments to function) this can be usefull when passing many function to onTap or OnClick function

your exemple:

void main() => { print(' begin '), runApp(MyApp()) ,print(' end ')};
Yefet
  • 2,010
  • 1
  • 10
  • 19
  • Note that it only works if the return type is void unless the whole body will be recognized as a literal Set – yelliver Jan 01 '22 at 05:27
  • 1
    This doesn't feel right, I suggest reading @Abion47's answer as well before automatically taking this high voted one. It may work as a side effect, but definitely not what the language intended for you to do – Oded Ben Dov Jul 07 '22 at 09:16
  • What this does is create a Set literal whose values are a bunch of statements that just happen to get executed in order as they are evaluated. It depends on a bunch of subtle behaviors that cannot be guaranteed to always work in new Dart version releases. It's a horrendous practice that technically works _for now_. Please just do it the intended way. – Abion47 Jul 08 '22 at 15:53
3

The => is not an operator, per se. It is a syntax that allows you to write one-liner functions that perform a single action and can also return a value. For example:

// Return a value
String getString() => 'a string';

// Do something
void doSomething() => doSomethingElse();

// It also works for getters
int _privateValue;
int get publicValue => _privateValue;

// They are also common in higher order functions
var numbers = [1, 2, 3, 4, 5];
var oddNumbers = numbers.where((n) => n % 2 != 0); // Output: [1, 3, 5]

Each of these examples is equivalent to a fully written-out method with curly brackets and return statements.

However, one-liner functions are, by definition, required to only have a single line of code. If you want a second line, you can't use a one-liner function and instead have to write a complete method:

// Incorrect, will cause the second statement to execute separately 
// or will throw an error, depending on where and how you do this
void oneLinerFunction() => print('1'); print('2');

// The correct way to define a method with more than one line of code in it
void fullMethod() {
  print('1');
  print('2');
}

As far as your final example, combining => and {} doesn't make the one-liner function execute multiple lines. It makes the function attempt to return a map or a set, since that's what values within curly brackets means. For example:

Map<String, int> getMap() => { 'a': 1, 'b': 2 };

This will not work if you try to use it to sneak in multiple lines of code to the function. The compiler will interpret it as a set and will not work as you expect at best and throw an error at worst.

Abion47
  • 22,211
  • 4
  • 65
  • 88
  • 1
    You say "lambda functions" - I also noticed this [here](https://stackoverflow.com/a/59346369/6509751) - however, we do not speak of *lambda functions* in this case. In the other case I linked it is *correct* as [a *lambda function* is an **anonymous function**](https://stackoverflow.com/a/16509/6509751) or **callback** in that particular case. The shorthand syntax just declares ***regular** functions or methods*, but can obviously also define a "lambda function" or anonymous function/callback (to use what I prefer). It is just an *alternate syntax* and not inherently anonymous. – creativecreatorormaybenot Dec 17 '19 at 17:51
  • @creativecreatorormaybenot I call it a lambda function because that's what it is. An **anonymous function** is any function that is declared without an identifier, usually as a local utility function or an inline function passed to a higher-order function. A **lambda function** is a special kind of anonymous function with an abbreviated syntax for a single statement. A **callback** can be any kind of function (named, anonymous, lambda) and is merely the name for a function that is called from another (usually asynchronous) function once execution of that function is complete. – Abion47 Dec 17 '19 at 17:58
  • 2
    @creativecreatorormaybenot I didn't downvote you, I don't know who did. – Abion47 Dec 17 '19 at 18:02
  • 2
    @creativecreatorormaybenot And not necessarily. As I said in my reply, lambda functions strictly speaking are inherently anonymous. That being said, lambda functions and fat arrow notation have become so synonymous that you can refer to a named function using fat arrow notation as a lambda function and people will know what you mean, so arguing that point is technically true but somewhat pedantic. – Abion47 Dec 17 '19 at 18:04
2

The => operator is referred to as the Arrow Operator

Functions defined inline with the => operator are referred to as Lambda Functions or Arrow Functions. These functions execute and return a single statement.

If you want to perform multiple statements, you can use Anonymous Functions. Specified with {} and without the => operator:

someFunc( () { print("1"); print("2"); print("3");} )

(Anonymous functions can have return values as well)

There's a big thread about it here on Stack Overflow

Oded Ben Dov
  • 9,936
  • 6
  • 38
  • 53
1

As others have said, => operator is referred to as the Arrow Operator and it is meant to be a one liner.

I came here wanting to have multiple lines of code in the onPressed of a button and this is one way to do it:

        ElevatedButton(
          onPressed: () {
            print('one');
            print('two');
          },
          child: Text("Click me"),
        ),
Katu
  • 1,296
  • 1
  • 24
  • 38
-2

If you have a method that only contains one line, you can use => to save room and make the entire method declaration and body fit on one line. You can have multiple operations, as long as they fit on that single line. It basically translates to 'just return this value' (and it acts like a return statement).

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

is completely equivalent to saying:

void main(){
  return runApp(MyApp());
}

However, if you have a method that includes multiple lines, you need to use brackets.

Kris
  • 3,091
  • 20
  • 28
  • Not exactly - it will not return the value if `void` is the return type of the function. `void foo() { return 5; }` is invalid but `void foo() => 5;` is valid. – creativecreatorormaybenot Dec 17 '19 at 17:54
  • @creativecreatorormaybenot That's not quite right. The full function equivalent of `void foo() => 5;` would be `void foo() { 5; }`, not `void foo() { return 5; }` – Abion47 Dec 17 '19 at 18:01
  • @Abion47 Yes, that is what I was saying. The OP of this answer stated "it acts like a return statement" and my comment is in response to that. – creativecreatorormaybenot Dec 17 '19 at 18:19