Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

  • This article focuses on the use of methods in DART.

1. Dart method and arrow function

Dart has a method, which is also an object. When the execution statement of a method has only one sentence, it can be expressed by the arrow function =>

Method return values and parameter types can be omitted

We can also do it this way and keep it simple, or we can do it with trinary

sum1 (a,b) => a+b; Sum1 (a,b) => a==b? a-b:a+b;Copy the code

2. Optional parameters in dart

Optional parameters: Pass parameters with the name of the parameter. When we add optional parameters to the method, use {} and add the name

Parameters B and c indicate yesdynamicthe

We tell the compiler to handle the empty case. If we don’t give it a default value, because it’s optional we don’t have to, we can choose not to, but we’ll get an error



We can alsoSpecify the typeBut do itJudge not empty

We don’t have to?Non-null judgments can be made directlyAssign the default value

We can alsoNo parameter name is taken, you can specify the default assignment when calledCannot specify argumentsYou can only pressThe orderThe assignment.

3. Anonymous methods in DART

  • No method nameThe following methods 1 and 2 have the same effect, 3 does not call equivalent.

4. Dart methods are passed as parameters

A method is also an object that can assign a value to a variable, and we can call that variable directly when a method has a return method

We define an array and print out the elements, just like we do in iOSThe for loopandenumerateObjectsUsingBlock

Similarly we pass functions as argumentsBlock closure.list.forEach(print)We put inprintMethod as aparameterPass it in.

And the underlying implementationThe for loop inTo execute the method we pass in, we customize a similar one

We can also pass anonymous functions as arguments

5. Closures in the DART method

A function defined inside a function is a closure, and a closure is also an object

What closures do: Access external functionsA local variable.

That comes from the use of the method in DART.