Basic Functions
- Definition:
- Advantages of function:
Avoid repetition of codes.
Increases program readability.
Divide a complex problem into simpler ones.
Reduces chances of error.
Modifying a program becomes easier by using function.
- Syntax:
function_name : A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Dart.
parameters_list : Parameters (arguments) through which we pass values to a function. They are optional.
return type : Type of Return value.
A function with void as return type don't return any value.
- Function call:
- Types of functions:
- Examples
- Example 1 : Average Calculator
- Example 2 : Random numbers generator (Without Parameters)
- Example 3 : Print a message (Void Function)
- Example 4 : helloWorld (void function without Parameters)
Function is a logically grouped set of statements that perform a specific task. In Dart program, a function is created to achieve something. Every Dart program has at least one function i.e. main() where the execution of the program starts. It is a mandatory function in Dart.
statement(s)
return value;
}
A function call can be made by using a call statement. A function call statement consists of function name and required argument enclosed in round brackets.
function_name ( parameters_list );
1. Library functions :
Library functions are the built in function that are already defined in the Dart library. For Example : print().
2. User-defined functions:
Those functions that are defined by user to use them when required are called user-defined function.
double average(List numbers) {
double total = 0;
for (int i = 0; i < numbers.length; i++) total += numbers[i];
return total / numbers.length;
}
void main() {
var list1 = [12, 15, 18, 19, 7];
double average_list1 = average(list1);
print(average_list1);
var list2 = [3.14, 5.34, 12.0, 19.4];
print(average(list2));
}
9.969999999999999
import 'dart:math';
List randomGenerator() {
var randoms = [];
for (int i = 0; i < 5; i++) {
int x = Random().nextInt(100);
randoms.add(x);
}
return randoms;
}
void main() {
print(randomGenerator());
var l1 = randomGenerator();
print(l1);
}
[23, 57, 55, 42, 22]
void show(object, quantity) {
print("You have $quantity $object in storage");
}
void main() {
show("Pictures", 23);
show("Documents", 11);
show("Videos", 5);
}
You have 11 Documents in storage
You have 5 Videos in storage
void helloWorld() {
print("Hello Flutter Pro students <3");
}
void main() {
helloWorld();
}
Note:
For functions that contain just one expression, you can use a shorthand syntax:
void helloWorld() => print("Hello World");