Dart function is a set of codes that together perform a specific task. It is used to break the large code into smaller modules and reuse it when needed. Functions make the program more readable and easy to debug. It improves the modular approach and enhances the code reusability.
Suppose, we write a simple calculator program where we need to perform operations number of times when the user enters the values. We can create different functions for each calculator operator. By using the functions, we don’t need to write code for adding, subtracting, multiplying, and divide again and again. We can use the functions multiple times by calling.
Dart function definition
A function is a mapping of zero or more input parameters to zero or more output parameters.
The advantages of using functions are:
- Reducing duplication of code
- Improving clarity of the code
- Reuse of code
- Decomposing complex problems into simpler pieces
- Information hiding
- Dart functions are first-class citizens. Functions can be assigned to variables, passed as arguments to functions or returned from functions. This makes the language more flexible.
The body of the function consists of statements that are executed when the function is called. We use the return keyword to return values from functions. The body is delimited with a pair of curly brackets {}. To call a function, we specify its name followed by round brackets (). A function may or may not take parameters.
The following example creates a simple function in Dart.
main.dart
void main() {
int x = 4;
int y = 5;
int z = add(x, y);
print("Output: $z");
}
int add(int a, int b) {
return a + b;
}
In the example, we define a function which adds two values.
void main() {
The main function is the entry point of the program.
int z = add(x, y);
We call the add function; it takes two parameters. The computed value is passed to the z variable.
int add(int a, int b) {
return a + b;
}
The definition of the add function starts with its return value type. The parameters of the function are separated with comma; each parameter name is preceded with its data type. The statements that are executed when the function is called are placed between curly brackets. The result of the addition operation is returned to the caller with the return keyword.
The print is a built-in Dart function, which prints the given value to the console.
$ dart main.dart
Output: 9
Types of function in Dart
Let’s discuss the types of function. Remember that function can be categorized in any manner. But here we categorized them based on arguments and return type.
first of all, remember that one function can only return one type. And both return_type and return_value must be the same. Like if your function is String type then it must return a string value. It cannot return an int or double type.
There are four main types of user define functions (based on arguments and return type).
- Function with no arguments and no return type
- Function with arguments and no return type
- Function with no arguments and return type
- Function with arguments and with return type
Function with no arguments and no return type
Here if you don’t specify any return type, by default it’s considered as void. But it’s good practice if you specify the void if there is no return type.
Syntax
void SayMyName(){
print("Jay Tillu");
}
main(){
SayMyName();
}
Output
Jay Tillu
Function with no arguments and return type
In this category, the function has no arguments but rather it has a return type.
Syntax
int ShowMyAge(){
int age = 20;
return age;
}
main(){
int myAge = ShowMyAge();
print(myAge);
}
Output
20
Function with arguments and no return type
Here our function has arguments but it does not have any return type.
When there are arguments in a function, we have to specify each argument’s value when we call the function. Otherwise, it will give you a runtime error. So be careful about that.
AboutMySelf(int age, int totalGf) {
print(age);
print(totalGf);
}
main() {
AboutMySelf(20, 0);
}
Output
200
Function with arguments and with return type
Congrats!! now our function has arguments and return type both.
Example
int Sum(int numberOne, int numberTwo) {
int addition = numberOne + numberTwo;
return addition;
}
main() {
int mySum = Sum(20, 30);
print(mySum);
}
Output
Sum is 50
So, guys, that’s it for types of functions. Please explore around it, practice it and try to understand it conceptually. These all are language fundamentals, if you have a strong understanding of it, you will feel right at home while learning flutter. These concepts are also important for the logic building
Dart main function arguments
The main function can accept arguments from the command line.
main.dart
void main(List args) {
print(args);
print(args.length);
if (args.length > 1) {
var a = args[1];
print(a);
}
}
The command line arguments are stored in the args list of strings.
$ dart main.dart 1 2 3 4 5
[1, 2, 3, 4, 5]
5
Dart arrow function
The arrow function allows us to create a simplified function consisting of a single expression. We can omit the curly brackets and the return keyword.
main.dart
int add(int x, int y) => x + y;
int sub(int x, int y) => x - y;
void main() {
print(add(3, 5));
print(sub(5, 4));
}
In the example, we have two functions defined with the arrow syntax.
$ dart main.dart
8
1
Dart anonymous function
We can create anonymous functions. Anonymous functions do not have a name.
main.dart
void main() {
var words = ['sky', 'cloud', 'forest', 'welcome'];
words.forEach((String word) {
print('$word has ${word.length} characters');
});
}
We create an anonymous function which counts characters for each of the words in the list.
$ dart main.dart
sky has 3 characters
cloud has 5 characters
forest has 6 characters
welcome has 7 characters
Dart recursive function
Recursion, in mathematics and computer science, is a way of defining methods in which the method being defined is applied within its own definition. To put it differently, a recursive method calls itself to do its task. Recursion is a widely used approach to solve many programming tasks.
A typical example is the calculation of a factorial.
main.dart
int fact(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * fact(n - 1);
}
void main() {
print(fact(7));
print(fact(10));
print(fact(15));
}