Learn how to implement calculator functions in Dart by creating a simple console app. This guide covers defining arithmetic functions, handling user input, selecting operations, and displaying results with error handling.
In this section, we will delve into the implementation of a simple calculator console application using Dart. This project will help you understand how to define arithmetic functions, handle user input, select operations based on user input, and display results. Additionally, we will cover error handling to ensure robust application behavior.
Arithmetic operations form the core of any calculator application. In Dart, we can define functions for each arithmetic operation: addition, subtraction, multiplication, and division. These functions will take two double
parameters and return a double
result.
double add(double a, double b) => a + b;
double subtract(double a, double b) => a - b;
double multiply(double a, double b) => a * b;
double divide(double a, double b) {
if (b == 0) {
throw ArgumentError('Cannot divide by zero');
}
return a / b;
}
Explanation:
add
): Returns the sum of two numbers.subtract
): Returns the difference between two numbers.multiply
): Returns the product of two numbers.divide
): Checks if the divisor is zero to prevent division by zero errors, then returns the quotient.To perform calculations, we need to capture user input for the numbers and the desired operation. Dart’s stdin.readLineSync()
function allows us to read input from the console.
import 'dart:io';
void main() {
print('Enter first number:');
double num1 = double.parse(stdin.readLineSync()!);
print('Enter second number:');
double num2 = double.parse(stdin.readLineSync()!);
print('Choose operation (+, -, *, /):');
String? operation = stdin.readLineSync();
// Perform calculation based on the operation
}
Explanation:
stdin.readLineSync()
: Reads a line of input from the console.double.parse()
: Converts the input string to a double
.!
operator is used to assert that the input is non-null.Once we have the user inputs, we need to determine which arithmetic function to call. This can be achieved using conditional statements or a switch-case
structure.
switch
switch (operation) {
case '+':
result = add(num1, num2);
break;
case '-':
result = subtract(num1, num2);
break;
case '*':
result = multiply(num1, num2);
break;
case '/':
try {
result = divide(num1, num2);
} catch (e) {
print(e);
return;
}
break;
default:
print('Invalid operation selected.');
return;
}
Explanation:
switch-case
: Evaluates the operation
and executes the corresponding arithmetic function.try-catch
block to handle division by zero errors.After performing the calculation, the result is displayed to the user.
print('Result: $result');
Explanation:
Let’s combine all the elements to form a cohesive function that performs the entire calculation process.
import 'dart:io';
double add(double a, double b) => a + b;
double subtract(double a, double b) => a - b;
double multiply(double a, double b) => a * b;
double divide(double a, double b) {
if (b == 0) {
throw ArgumentError('Cannot divide by zero');
}
return a / b;
}
void main() {
try {
print('Enter first number:');
double num1 = double.parse(stdin.readLineSync()!);
print('Enter second number:');
double num2 = double.parse(stdin.readLineSync()!);
print('Choose operation (+, -, *, /):');
String? operation = stdin.readLineSync();
double result;
switch (operation) {
case '+':
result = add(num1, num2);
break;
case '-':
result = subtract(num1, num2);
break;
case '*':
result = multiply(num1, num2);
break;
case '/':
result = divide(num1, num2);
break;
default:
print('Invalid operation selected.');
return;
}
print('Result: $result');
} catch (e) {
print('Error: ${e.toString()}');
}
}
Explanation:
try-catch
block to handle any unexpected errors gracefully.To better understand the flow of our calculator application, let’s visualize the process using a Mermaid.js diagram.
flowchart TB A[Implementing Calculator Functions] --> B[Define Arithmetic Functions] A --> C[Handle User Input] A --> D[Select Operation] A --> E[Perform Calculation] A --> F[Display Result] A --> G[Error Handling] E --> H[Call Appropriate Function] G --> I[Catch and Display Errors]
Diagram Explanation:
In this section, we implemented a simple calculator console application in Dart. We defined arithmetic functions, handled user input, selected operations, and displayed results with error handling. This project serves as a foundational exercise in understanding Dart’s capabilities and preparing for more complex Flutter applications.