Aree Ali
Aree Ali

Reputation: 65

What is the different between these two void methods in Dart?

Code:

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

And

Code:

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

Upvotes: 0

Views: 925

Answers (3)

lrn
lrn

Reputation: 71633

There is very little difference.

A function of the form SomeType name(args) => expression; is almost entirely equivalent to SomeType name(args) { return expression; }.

Dart's void type is slightly different from other similar language's use of void. The type is not an empty type, instead it's equivalent to Object? in that it can contain any value, it just statically prevents you from using the value. This design was chosen originally in Dart 1 because it allowed a method returning a useful value to override a method which returned void.

Dart generally disallows a return value; statement in a void returning function, because it's probably a mistake, unless the type of value is itself void (or dynamic or Null).

So

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

is equivalent to

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

but since main has a return type of void (and because it's the main method), no-one is ever going to look at the returned value.

So, in short, you can use => voidExpression; as shorthand for { voidExpression;} because no-one is going to notice the returned value.

Upvotes: 1

Sabaoon Bedar
Sabaoon Bedar

Reputation: 3689

I will go with the detailed explanation it might help you with depth.

Functions in Dart behave much like function in JavaScript. They can be defined as a method similar to our void function, as well as, they behave like first-class objects meaning they can be stored in a variable, passed as an argument or returned like a normal return value of a function.


enter image description here


As you can see from the above example, there are many ways to create a function. A function that does not define a return type (like using var syntax) has a return type of dynamic. If parameters in function definition have no types, they implicitly have the dynamic type.

Fat Arrow Expression Fat Arrow Expression or Lambda Function Expression is a syntax to write a function on a single line using => syntax AKA fat arrow. This resembles the ES6 Fat Arrow function syntax of JavaScript. This is a cleaner way to write functions with a single statement.

enter image description here

Upvotes: 2

Adam A.
Adam A.

Reputation: 153

There isn't a difference in terms of logic.

We use:

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

when the function just uses a single line. However, we use the angle brackets "{}" to indicate a complication of different lines.

For example:

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

Notice the use of more than one line.

Usually in your case, you wouldn't use the second method and id suggest you stick to the first one.

Hope it helped! :)

Upvotes: 0

Related Questions