dwyl / learn-dart

🎯Learn the Dart programming language to build cross-platform (Mobile, Web & Desktop) Apps with Flutter!
GNU General Public License v2.0
32 stars 8 forks source link

How to define functions? #6

Open SimonLab opened 4 years ago

SimonLab commented 4 years ago

Add a functions section in the README to describe how to create functions.

String hello() {
  return 'hello';
}

We can see that the value's type returned by the function is the specify at the beginning of the function declaration. From some manual test I'm not sure however that the type is required as Dart might determine it automatically (need more searching on this). However I think this is always a good idea to specify it as it describes what the function returns.

void hello() {
  print('hello');
}

However I've tested with return null; and the code compiled without error. I'm not sure if void is a specific type (where null is consider a value of void, or a synonym?)

void hello() {
  print('hello');
  return null;
}

Other questions to search:

SimonLab commented 4 years ago

image

SimonLab commented 3 years ago

Arrow function: String hello() => 'hello'. I understand arrow function as a shortcut for functions with one returning line.

Arrow function is a syntactic sugar for one statement functions:

hello() => 'hello'

is the same as:

hello() {
  return 'hello';
}

Note that the arrow function returns the value created by the statement. We can also explicitly add the type of the returned value of the function:

String hello() => 'hello';

Arrow functions can be used to create anonymous functions:

var a = () => 'hello';
print(a());
SimonLab commented 3 years ago

the main function. Entry point for Dart/flutter program

The main function is a top-level function (a function created outside a class) which is required in all Dart programs. It is the start point of your program. It usually has the type void.

void main() {
  print('hello');
}

The main function can take a list of string as a parameter.

ref: https://dart.dev/guides/language/language-tour#the-main-function