In this example, you'll see the use of numbers, functions, and parameters in Dart.
There are two types of numbers in Dart:
- int: Contains integer values no larger than 64 bits
- double: Contains 64 -bit, double-precision floating-point numbers
You also have the num type: both int and double are num.
Consider the following example:
void main() {
double result = calculateArea(12, 5);
print ('The result is ' + result.toString());
}
In this code, we are declaring a variable called result, of a type called double, which will take the return value of a function called calculateArea, which we'll need to define later. We are passing two numbers—12 and 5—to the function.
After the function returns its value, we will show the result, after converting it to a string.
Let's write the function:
double calculateArea(double width, double height) {
double area = width * height;
return area;
}
In this case, the width and height parameters are required. You can also add optional parameters to functions, by including them in square brackets. Let's insert an optional parameter to the calculateArea() function, so that the function can also calculate the area of a triangle:
double calculateArea(double width, double height, [bool isTriangle]) {
double area;
if (isTriangle) {
area = width * height / 2;
}
else {
area = width * height;
}
return area;
}
Now, from the main() method, we can call this function twice, with or without the optional parameter:
void main() {
double result = calculateArea(12,5,false);
print ('The result for a rectangle is ' + result.toString());
result = calculateArea(12,5,true);
print ('The result for a triangle is ' + result.toString());
}
The full function with the expected result is shown here:
At this time, function overloading is not supported in Dart.