Functions in dart

Dart for beginners part - 4

Tony Wilson jesuraj
2 min readNov 18, 2021

This blog will help you to recall or will let you known about functions in dart

Why function

  • Functions allow the same piece of code to run multiple times.
  • Functions break long programs up into smaller components, so easy to understand

Creating function with parameter

void add() {
print (1 + 2);
}

And for calling it

void main() {
add();
}
void add() {
print (1 + 2); // 3
}

Functions with arguments

void main() {
add(1,2);
}
void add(int a, int b) {
print (a + b); // 3
}

or

Calling with arguments name

void main() {
print(add(a: 1,b: 2));
}
int add({int a = 0, int b = 0}) {
return a + b;
}

a=0 and b=0 is assigning value for null safety. so if not passed any parameters also code will run. To make arguments compulsory need to use required like

void main() {
print(add(a: 1,b: 2));
}
int add({required int a, required int b}) {
return a + b;
}

Function with return

void main() {
print(add(1,2));
}
int add(int a, int b) {
return a + b;
}

need to mention the data type in front of function name

Anonymous function

Its like variable as function

final sayHi = (name) => 'Hi, $name';
print(sayHi("Aron")); // Hi, Aron

Upcoming codes are higher order functions

Map method

final list = [1,2,3,3,3];
final value = list.map((x) {
return x * 10;
});
print(value.toList()); // [10, 20, 30, 30, 30]

forEach method

its like a easy for loop

final list = [1,2,3,3,3];
list.forEach((value) => print(value));

or

final list = [1,2,3,3,3];
list.forEach((value) {
print(value);
});

Where method

here, if value % 2 == 0 if the condition is true will return the value

final list = [1,2,3,3,4];
final evenList = list.where((value) => value % 2 == 0);
print(evenList); // (2,4)

Reduce method

used to combine all items inside a list and produce a single result (Example: sum of array)

final list = [1,2,3,3,3];
final sum = list.reduce((value, element) => value + element);
print(sum); // 12

here value will have add on sum and element iterate the list like 1,2,3,3,3…

If any mistake or you need to shout me, comments session in always opened

நன்றி வணக்கம்

--

--