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.