Author | Vlad
Source | Flad (Public Number: fulade_me)
function
Dart is also an object-oriented speech. So even a function is an object. The type is Function, which means that the function can be used as a variable and can also be used as a parameter of the function.
Here is an example of defining a function:
isEmpty(List aList) { return aList.length == 0; }
In order to standardize, we need to declare the return value type at the head of the function. Of course, it can be run if it is not declared.
bool isEmpty(List aList) { return aList.length == 0; }
If the function body contains only one expression, you can use the shorthand syntax:
bool isEmpty(List aList) => aList.length == 0;
=>Expresses the {return expression;} Abbreviation, sometimes referred to as fat arrow grammar.
parameter
Functions can have two forms of parameters: required parameters and optional parameters. Required parameters are defined before the parameter list, and optional parameters must be defined after the required parameters.
optional named parameters
When you call a function, you can specify named parameters using the form parametername:parametervalue. E.g:
enableFlags(bold: true, hidden: false);
Named parameters are optional unless they are specifically marked as required.
When defining a function, use {param1, param2, …} to specify named parameters:
/// set [bold] and [hidden] flags... void enableFlags({bool bold, bool hidden}) {...}
Although named parameters are a type of optional parameters, you can still use the @required annotation to mark a named parameter as a required parameter, in which case the caller must provide a value for the parameter. E.g:
const Scrollbar({Key key, @required Widget child})
A compile error will result if the caller tries to construct a Scrollbar object via the Scrollbar's constructor without providing the child parameter.
optional parameter
Use [] to wrap a series of parameters as optional parameters:
strings(String s1, String s2, [String s3]) { var result = '$s1 and $s2'; if (s3 != null) { result = '$result and $s3'; } print(result); }
Here is an example of calling the above function without optional arguments:
strings("s1", "s2"); s1 and s2
Here is an example of calling the above function with optional arguments:
strings("s1", "s2", "s3"); s1 and s2 and s3
Default parameter value
We can use = to define default values for named and optional parameters of a function. The default value must be a compile-time constant. If no default value is specified, the default value is null.
The following is an example of setting an optional parameter default value:
/// set [bold] and [hidden] flags... void enableFlags({bool bold = false, bool hidden = false}) {...} // The value of bold will be true; hidden will be false. enableFlags(bold: true);
Next example Default value:
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
main() function
Every Dart program must have a main() top-level function as the entry point of the program, and the return value of the main() function is void.
Here is an example of the main() function of a Flutter app:
void main() { runApp(MyApp()); }
function as parameter
A function can be passed as an argument to another function. E.g:
void printElement(int element) { print(element); } // Pass the printElement function as an argument. var list = [1, 2, 3]; list.forEach(printElement);
You can also assign a function to a variable, for example:
var loudify = (msg) => '!!! ${msg.toUpperCase()} !!!'; var result = loudify('hello'); print(result);
anonymous function
Most methods are named, like main() or printElement(). You can create a method without a name and call it an anonymous function. In fact, anonymous functions are very common and have different names. They are called Lambda expressions in C++ and Block closures in Objective-C. You can assign an anonymous method to a variable and use it.
An anonymous method looks similar to a named function h, with parameters that can be defined between parentheses and separated by commas.
The content in the following curly brackets is the function body:
([[type] parameter[, ...]]) { function body; };
The following code defines an anonymous method with only one parameter item and no parameter type. This function is called for each element in the List, printing a string of the element's position and value:
var list = ['apples', 'bananas', 'oranges']; list.forEach((item) { print('${list.indexOf(item)}: $item'); });
If there is only one line of statement in the function body, you can use the fat arrow abbreviation. The running result of the following code is consistent with the running result of the above code.
list.forEach( (item) => print('${list.indexOf(item)}: $item'));
variable scope
The scope of variables is determined when the code is written, and variables defined within curly braces can only be accessed within curly braces, similar to Java.
Here is an example of variables in multiple scopes in a nested function:
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); } } }
Note that the nestedFunction() function has access to all variables including top-level variables.
return value
All functions have return values. The last line of a function that does not show a return statement defaults to executing return null;.
foo() {} assert(foo() == null);
All the code in this article has been uploaded to Github