Table of contents
No headings in the article.
The function is a one type of set of statement which take input , do only specific computation , and then process of output.
Mostly , we create function when some certain statements are occurring in the program , so every time write the same statement and make code lengthier and slow , instead we can create one function then we have to call only function where we want to use this certain statement which increase the code reusability of the program.
Basically, there are four types of functions in Dart.
These are as follows:
No arguments and no return type
With arguments and no return type
No arguments and return type
With arguments and with return type
- No arguments and no return type
- in this function, we do not give any argument and any no return type.
// Define a function named exampleFunction
void exampleFunction() {
print('This is an example function with no arguments and no return type.');
}
void main() {
// Call the exampleFunction
exampleFunction(); // Output: This is an example function with no arguments and no return type.
}
- With arguments and return type
in this function, we are giving an argument and no return type
So in this example myPrice is the function that is int means it is returning int type and the empty pair of parentheses suggests that there is no argument which is passed to the function.
// Define a function named addNumbers that takes two integer arguments and returns their sum
int addNumbers(int a, int b) {
return a + b;
}
void main() {
// Call the addNumbers function with arguments 5 and 3, and store the returned value
int sum = addNumbers(5, 3);
// Print the returned value
print('The sum is: $sum'); // Output: The sum is: 8
}
- No arguments and return type
Basically in this function, we do not give any argument but we need a return type.
So last time myPrice is the function that is void means it is not returning anything and but now , the pair of parentheses is not empty this time which suggests that it accept an argument.
// Define a function named exampleFunction
String exampleFunction() {
return 'This is an example function.';
}
void main() {
// Call the exampleFunction and store the returned value
String result = exampleFunction();
// Print the result
print(result); // Output: This is an example function.
}
- With arguments and with return type
- Basically in this function, we are giving an argument and expect return type.
// Define a function named calculateArea that takes two double arguments (length and width) and returns their product
double calculateArea(double length, double width) {
return length * width;
}
void main() {
// Call the calculateArea function with arguments 5.0 and 3.0, and store the returned value
double area = calculateArea(5.0, 3.0);
// Print the returned value
print('The area is: $area'); // Output: The area is: 15.0
}