[Flutter] Function in Dart

2021-04-01 hit count image

Let's see how to use Dart for developing an app with Flutter. In this blog post, I will introduce how to use Function in Dart.

Blog series

This blog post is a series. You can see the other posts on the link below.

Outline

In this blog post, I will introduce how to use Function in Dart.

You can see the source code, that is introduced on this blog post, on the link below

Function

We can define the Function and use it in Dart like below.

String add(int a, int b) {
  int sum = a + b;
  return 'Sum: $sum';
}

void main() {
  print(add(1, 2));
  print(add(3, 4));
  print(add(5, 6));
  print(add(7, 8));
}

Optional parameter

When you define the Function, you can set the Optional parameter and set the default value on it like below.

String add(int a, int b, [int c = 0]) {
  int sum = a + b + c;
  return 'Sum: $sum';
}

void main() {
  print(add(1, 1));
  print(add(1, 1, 1));
}

Named parameter

When the Function has many parameters, we can’t remember the older of the parameters. In this case, we can use Named parameter. If you use Named parameter, you can set the parameter more clearly when you call the Function.

String add(int a, int b, {int c = 0, int d = 0}) {
  int sum = a + b + c + d;
  return 'Sum: $sum';
}

void main() {
  print(add(1, 1));
  print(add(1, 1, c: 1));
  print(add(1, 1, d: 1));
  print(add(1, 1, c: 1, d: 1));
}

typedef

You can pass the Function via the parameter in Dart. However, if you don’t set the type of the parameter, you don’t know what value is passed, and how to use it.

In this case, you can use typedef. You can define typedef and you can set it on the Function parameter.

typedef Operator(int n, int m);

String add(int a, int b) {
  int sum = a + b;
  return 'Sum: $sum';
}

String substract(int c, int d) {
  int sub = c - d;
  return 'Sub: $sub';
}

String calculate(int x, int y, Operator op) {
  return op(x, y);
}

void main() {
  print(add(2, 1));
  print(substract(2, 1));

  Operator op = add;
  print(op(2, 1));

  op = substract;
  print(op(2, 1));

  print(calculate(2, 1, add));
  print(calculate(2, 1, substract));
}

Complete

We’ve seen how to use Function in Dart to develop an app with Flutter. We can know there is no difference between Dart and other languages to define the Function and use it. Also, we’ve seen how to use typedef to define the type of the FUnction and set it for the parameter in the Function.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts