Area calculator

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;
}
Since Dart 2.1, the int literals are automatically converted to doubles; for example, you can write: double value = 2;. This is instead of having to write: double value = 2.0;.

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. 

Overloading is a feature of some OOP languages, such as Java and C#, which allows a class to have more than one method with the same name, provided that their argument lists are different in number or type. For example, you could have a method called calculateArea (double side) to calculate the area of a square, and another method called calculateArea (double width, double height) to calculate the area of a rectangle. This is currently not supported in Dart.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.223.190