Functions In Dart Programming

Functions In Dart Programming

Dart function is a set of statements that work on specific tasks. Functions can be called anywhere in a program to perform some operations and return a result. Functions make a program more readable, maintainable and easy to reuse. lets look at an example to understand the syntax of functions.

//main function
void main(){
print('multiply two numbers using the function');

//function definition
int multiply(int x, int y){
//function body
 int result;
 result = x*y;
 return result;
}
//calling a function
var z= multiply(12, 5);
print("the answer is: ${z}");
}

The function above has all it takes to define a function. It has a return_type which can be any data type, in our case we have the integer as the return_type. It also has a function name multiply followed by a parameter_list x and y.

Inside the function body we multiply x and y, at the end we have a return value named result. in the main function we are calling our function and storing the result inside a variable z.

Function parameters

These are names listed in the function definition.

required positional parameters

Required positional parameters are listed in order and the arguments supplied when calling the function simply match the same ordering. Example.

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

In our case, a and b are used inside the function. When calling the function, arguments are referenced by position in which they are defined. In this case, our first argument is a and the second b.

optional positional parameters

Optional parameters are wrapped inside [] to mark them as optional. if it is not passed a value, it set to NULL. Example.

void main(){
option_param(x,[y]){
print(x);
print(y);
}
option_param(5);
}

In the code above, our optional parameter is y hence it will give a NULL output.

output

5
null

named parameters

Named parameters are defined by listing them between curly braces. They are optional unless marked as required.

example.

int namedMultiply({required int a, required int b}){
return a*b;
}
namedMultiply(a: 4, b: 2);

Thanks for reading my article, This is just a simple illustration of functions work in dart , its really important Flutter. Thanks