The author | | vlad source vlad (public number: fulade_me)

function

Dart is also object-oriented speech. So even a function is an object. The type is Function, which means functions can be used as variables or as arguments to functions.

Here is an example of defining a function:

isEmpty(List aList) {
  return aList.length == 0;
}
Copy the code

We need to declare the return value type in the header of the function for the sake of specification, but we can run it without declaring it.

bool isEmpty(List aList) {
  return aList.length == 0;
}
Copy the code

If the function body contains only one expression, you can use shorthand syntax:

bool isEmpty(List aList) => aList.length == 0;
Copy the code

=> expresses {return expression; }, sometimes => is also called fat arrow syntax.

parameter

Functions can take two forms of arguments: mandatory and optional. Mandatory parameters are defined before the parameter list. Optional parameters must be defined after required parameters.

Optional named parameter

When you call a function, you can specify named arguments in the form of parameter names: parameter values. Such as:

enableFlags(bold: true, hidden: false);
Copy the code

Named parameters are optional unless they are specifically marked as required.

When defining functions, use {param1, param2… } to specify named arguments:

/// Set the [bold] and [Hidden] flags...
void enableFlags({bool bold, boolhidden}) {... }Copy the code

Although named parameters are one type of optional parameter, you can still use the @required annotation to indicate that a named parameter is required, in which case the caller must provide a value for the parameter. Such as:

const Scrollbar({Key key, @required Widget child})
Copy the code

If the caller wants to construct a Scrollbar object through the constructor of the Scrollbar without providing the child argument, it causes a compilation error.

Optional parameters

Use [] to wrap a list of arguments as optional arguments:

strings(String s1, String s2, [String s3]) {
  var result = '$s1 and $s2';
  if(s3 ! =null) {
    result = '$result and $s3';
  }
  print(result);
}
Copy the code

Here is an example of calling the above function without optional arguments:

strings("s1"."s2");
s1 and s2
Copy the code

Here is an example of calling the above function with optional arguments:

strings("s1"."s2"."s3");
s1 and s2 and s3
Copy the code
Default Parameter Value

We can use = to define default values for the named and optional parameters of the function. The default value must be compile-time constant, or null if no default value is specified.

The following is an example of setting optional parameter defaults:

/// Set the [bold] and [Hidden] flags...
void enableFlags({bool bold = false.bool hidden = false{...}) }// Bold will be true; And hidden is going to be false.
enableFlags(bold: true);
Copy the code

Default for the next example:

strings(String s1, String s2, [String s3 = 'this is s3'.String s4]) {
  var result = '$s1 and $s2';
  if(s3 ! =null) {
    result = '$result and $s3';
  }
  if(s4 ! =null) {
    result = '$result and $s4';
  }
  print(result);
}

strings("s1"."s2");
s1 and s2 and this is s3
Copy the code
The main () function

Each Dart program must have a main() top-level function as an entry point to the program, which returns void.

Here is an example of the main() function applied to Flutter:

void main() {
  runApp(MyApp());
}
Copy the code
Function as argument

You can pass a function as an argument to another function. Such as:

void printElement(int element) {
  print(element);
}
// Pass printElement as an argument.
var list = [1.2.3];
list.forEach(printElement);
Copy the code

You can also assign a function to a variable, as in:

var loudify = (msg) => '!!!!!!${msg.toUpperCase()}!!!!!!!!! ';
var result = loudify('hello');
print(result);
Copy the code

Anonymous functions

Most methods have names, such as main() or printElement(). You can create a method that doesn’t have a name and call it an anonymous function, and anonymous functions are very common and have different names, Lambda expressions in C++, Block closures in Objective-C. You can assign an anonymous method to a variable and then use it.

Anonymous methods look similar to the named function H in that arguments can be defined between parentheses, separated by commas.

The following contents in braces are the body of the function:

([[type] parameter [,...]]) {function body; };Copy the code

The following code defines an anonymous method that takes only one parameter item and has no parameter type. This function is called for each element in the List, printing a string of element positions and values:

var list = ['apples'.'bananas'.'oranges'];
list.forEach((item) {
  print('${list.indexOf(item)}: $item');
});
Copy the code

If there is only one line in the function body, you can use the fat arrow abbreviation. The result of the following code is the same as the result of the above code.

list.forEach(
    (item) => print('${list.indexOf(item)}: $item'));
Copy the code

Variable scope

The scope of a variable is defined at code writing time, and variables defined in braces can only be accessed within braces, similar to Java.

Here is an example of a nested function with variables in multiple scopes:

bool topLevel = true;

void main() {
  var insideMain = true;

  void myFunction() {
    var insideFunction = true;

    void nestedFunction() {
      var insideNestedFunction = true;

      assert(topLevel);
      assert(insideMain);
      assert(insideFunction);
      assert(insideNestedFunction); }}}Copy the code

Note that the nestedFunction() function can access all variables, including the top-level variable.

Return value All functions have return values. The last line of a function that does not display a return statement defaults to return NULL; .

foo() {}

assert(foo() == null);
Copy the code

All the code for this article has been uploaded to Github