dwyl/learn-dart

How to define functions?

SimonLab opened this issue ยท 3 comments

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

  • simple function example:
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 function type. The void keywords for a functions means that the function doesn't return any value.
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;
}
  • the main function. Entry point for Dart/flutter program
  • Arrow function: String hello() => 'hello'. I understand arrow function as a shortcut for functions with one returning line.

Other questions to search:

  • Research how to use parameters

    • give name to parameters
    • give default value to parameters
    • are parameters optional
  • Add a section on metada which allow us to add more information about a function, for example deprecated, required, override...

  • Does Dart allow anonymous functions? https://dart.dev/guides/language/language-tour#anonymous-functions

image

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());

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