]

Dart Functions

Published May 09, 2020

Dart method overview

Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code.

A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the functio

Method definition

General method definition
Syntax

type methodName(type Parameter name n)
{
    return n+n;
}

 

Example

int sum(int a, int b) {
    return a + b;
  }

 

Ignore type definitions (recommended to use static types on public APIs)

sum(a, b) {
    return a + b;
  }

 

There is only one expression method, you can choose to use abbreviated syntax (sometimes called fat arrow syntax) to define
 

int sum(int a, int b) => a + b;

 

Note:

  • Only one expression can be used between the arrow ( =>) and the semicolon ( ;), and no statement can be used.
  • for the voidmember type is not the one desired usage scenario. Readers expect =>to return a useful value, so the situation does not return value, or use { ... }to make the code more clear

 

Method parameters
Methods can have two types of parameters: required and optional. The required parameters are in front of the parameter list, followed by optional parameters

Optional parameters

Optional parameters can be named parameters or position-based parameters, but these two parameters can not be used as optional parameters.

In the definition of the method when using {param1, param2, …}the named parameters specified in the form

/// Sets the [bold] and [hidden] flags to the values
/// you specify.
enableFlags({bool bold, bool hidden}) {
  // ...
}

 

Call a method, you can use this form paramName: valueto specify named parameters. E.g:

enableFlags(bold: true, hidden: false);

 

Optional positional parameters (optional positional parameters)

The parameters of some methods put []in the position parameter becomes optional:

String say(String from, String msg, [String device]) {
  var result = '$from says $msg';
  if (device != null) {
    result = '$result with a $device';
  }
  return result;
}

 

assert(say('Bob', 'Howdy') == 'Bob says Howdy');

assert(say('Bob', 'Howdy', 'smoke signal') ==
    'Bob says Howdy with a smoke signal');

 

Default parameter values ??(default parameter values)
Method definition, you can use =the default values to define optional parameter. The default value can only be a compile-time constant. If no default value is provided, the default value is null

/// Sets the [bold] and [hidden] flags to the values you
/// specify, defaulting to false.
void enableFlags({bool bold = false, bool hidden = false}) {
  // ...
}

 

// bold will be true; hidden will be false.
enableFlags(bold: true);

 

Version of the problem: the old version of the code may need to use a colon ( :) instead =to set the default parameter values. The reason is that before Dart SDK 1.21, named parameters are only supported :. :Set named default parameter values can not be used in a future version, so we recommend that you use =to set the default value, and specify Dart SDK version 1.21 or higher version.

The following example shows how to set the default value of the position parameter

String say(String from, String msg,
    [String device = 'carrier pigeon', String mood]) {
  var result = '$from says $msg';
  if (device != null) {
    result = '$result with a $device';
  }
  if (mood != null) {
    result = '$result (in a $mood mood)';
  }
  return result;
}

 

assert(say('Bob', 'Howdy') ==
    'Bob says Howdy with a carrier pigeon');

 

We can also use list or map as the default. The following example defines a method doStuff () and specifies default values ??for the list and gifts parameters, respectively

void doStuff(
    {List<int> list = const [1, 2, 3],
    Map<String, String> gifts = const {
      'first': 'paper',
      'second': 'cotton',
      'third': 'leather'
    }}) {
  print('list:  $list');
  print('gifts: $gifts');
}

 

The main () function

Each application needs to have a top- main() entry method to perform. main() The method returns a value void, and has an optional List<String>parameter.

Here is a web application main() methods

void main() {
  querySelector("#sample_text_id")
    ..text = "Click me!"
    ..onClick.listen(reverseText);
}

 

Note: The preceding code ..syntax cascade call (cascade). Using the cascading call syntax, you can perform multiple operations on an object. Just understand it now, it will be introduced in detail in the next article

 

The following is a command-line application main()methods and method parameters used as input parameters

// Run the app like this: dart args.dart 1 test
void main(List<String> arguments) {
  print(arguments);

  assert(arguments.length == 2);
  assert(int.parse(arguments[0]) == 1);
  assert(arguments[1] == 'test');
}

 

we can use a method as a parameter to call another method

printElement(element) {
  print(element);
}

var list = [1, 2, 3];

 

// Pass printElement as a parameter.
list.forEach(printElement);
The method can also be assigned to a variable.
var loudify = (msg) => '!!! ${msg.toUpperCase()} !!!'; 
assert(loudify('hello') == '!!! HELLO !!!');

 

Anonymous functions (anonymous methods)
Most of the methods are presented with names such as main()or printElement(). You can create a method with no name, called anonymous methods , sometimes called lambdaor closure ??. You can assign an anonymous method to a variable, and then you can use this method, such as adding to or removing from a collection.

Anonymous functions and named functions look similar-some parameters can be defined between parentheses, the parameters are separated by commas, or they can be optional parameters. The code in braces behind is the function body

( [ [Type] param1 [, …] ] ) {
codeBlock;
};

 

The following code defines an anonymous function with parameter i (the parameter has no specified type). Each element in the list will call this function to print out, at the same time to calculate the index position of each element in the list

var list = ['apples', 'oranges', 'grapes', 'bananas', 'plums'];
list.forEach((i) {
  print(list.indexOf(i).toString() + ': ' + i);
});

 

list.forEach((i) => print(list.indexOf(i).toString() + ': ' + i));
Six, Lexical scope (static scope)
Dart is a statically scoped language, and the scope of variables is determined when the code is written. Basically, variables defined in braces can only be accessed in braces, similar to Java scope

var topLevel = true;

main() {
  var insideMain = true;

  myFunction() {
    var insideFunction = true;

    nestedFunction() {
      var insideNestedFunction = true;

      assert(topLevel);
      assert(insideMain);
      assert(insideFunction);
      assert(insideNestedFunction);
    }
  }
}

 

Lexical closures (grammar closures)

A closure is a method object, no matter where the object is called, the object can access variables in its scope.

Methods can enclose variables defined into their scope. In the following example, makeAdder() the variable is captured addBy. No matter where you perform makeAdder() the function returned, you can use addBy parameters

/// Returns a function that adds [addBy] to the
/// function's argument.
Function makeAdder(num addBy) {
  return (num i) => addBy + i;
}

main() {
  // Create a function that adds 2.
  var add2 = makeAdder(2);

  // Create a function that adds 4.
  var add4 = makeAdder(4);

  assert(add2(3) == 5);
  assert(add4(3) == 7);
}

 

Testing functions for equality
Here is an example to test the equality of top-level methods, static functions and instance functions

void foo() {} 

class A {
  static void bar() {} 
  void baz() {} 
}

void main() {
  var x;

  
  x = foo;
  assert(foo == x);

  
  x = A.bar;
  assert(A.bar == x);

  
  var v = A(); // Instance #1 of A
  var w = A(); // Instance #2 of A
  var y = w;
  x = w.baz;


  assert(y.baz == x);

 
  assert(v.baz != w.baz);
}

 

Return values
All functions return a value. If you do not specify a return value, it defaults to the statement return null;as the last statement function execution

Variable and method scope
Dart no public, protected, and privateconcepts.

But if the variable or function starts with an underscore ( _), then the function or variable belongs to the private method of this package


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

274 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions