Calculators are a staple of everyday life, and building one for yourself can be a fun and educational experience. In this article, we’re going to build a simple calculator app in Flutter, Google’s open-source mobile app development framework.
Before we start, make sure you have the Flutter SDK installed on your computer. You can find instructions on how to do that on the Flutter website.
- First, let’s create a new Flutter project. Open the terminal and type in the following command:
flutter create calculator
This will create a new directory called “calculator” with all the necessary files for a new Flutter project.
2. We’re going to start by building the user interface for our calculator. In the lib
directory, open the main.dart
file. This is the file where the app's main Dart code is located.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Calculator'),
),
body: Column(
children: [
Container(
alignment: Alignment.centerRight,
padding: EdgeInsets.fromLTRB(10, 20, 10, 0),
child: Text(
'0',
style: TextStyle(fontSize: 48, fontWeight: FontWeight.bold),
),
),
Expanded(
child: Container(
padding: EdgeInsets.all(10),
color: Colors.black12,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
buildButton('7'),
buildButton('8'),
buildButton('9'),
buildButton('/'),
buildButton('4'),
buildButton('5'),
buildButton('6'),
buildButton('x'),
buildButton('1'),
buildButton('2'),
buildButton('3'),
buildButton('-'),
buildButton('.'),
buildButton('0'),
buildButton('C'),
buildButton('+'),
buildButton('='),
],
),
),
),
],
),
),
);
}
Widget buildButton(String buttonText) {
return Expanded(
child: OutlineButton(
padding: EdgeInsets.all(24),
child: Text(
buttonText,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
onPressed: () {},
),
);
}
}
Here we have created the basic layout of our calculator app. We have an AppBar
at the top with the title "Calculator", a text field that displays the current value, and a grid of buttons for the digits and operators.
- The
buildButton
method is used to create the buttons for the digits and operators, it takes a string argument which is the text to be displayed on the button. ThebuildButton
method returns anExpanded
widget that contains anOutline Button
. TheOutline Button
has a child which is aText
widget that displays the text passed to thebuildButton
method and anonPressed
property which is currently empty, this is where we will add the logic to perform the calculations.
3. Now, let’s add some functionality to our calculator. First, we need to add some state to our app. We’ll create a new file called calculator_brain.dart
in the lib
directory.
class CalculatorBrain {
String _output = '0';
double _num1 = 0;
double _num2 = 0;
String _operand = '';
String get output => _output;
set output(String value) {
_output = value;
}
void setNum1(String value) {
_num1 = double.parse(value);
}
void setNum2(String value) {
_num2 = double.parse(value);
}
void setOperand(String value) {
_operand = value;
}
void calculate() {
switch (_operand) {
case '+':
_output = (_num1 + _num2).toString();
break;
case '-':
_output = (_num1 - _num2).toString();
break;
case 'x':
_output = (_num1 * _num2).toString();
break;
case '/':
_output = (_num1 / _num2).toString();
break;
default:
_output = 'Error';
}
}
void clear() {
_output = '0';
_num1 = 0;
_num2 = 0;
_operand = '';
}
}
In this file, we’ve created a CalculatorBrain
class that has several private variables to store the current output, the first and second numbers, and the current operand. We also have several methods to set the values of these variables, perform calculations and clear the calculator.
4. Next, we’ll import the CalculatorBrain
class in our main.dart
file and use it to perform calculations.
class _MyAppState extends State<MyApp> {
CalculatorBrain _brain = CalculatorBrain();
...
Widget buildButton(String buttonText) {
return Expanded(
child: OutlineButton(
padding: EdgeInsets.all(24),
child: Text(
buttonText,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
onPressed: () {
setState(() {
if (buttonText == 'C') {
_brain.clear();
} else if (double.tryParse(buttonText) != null) {
if (_brain.output == '0' || _brain.operand.isNotEmpty) {
_brain.output = buttonText;
} else {
_brain.output += buttonText;
}
} else if (buttonText == '=') {
_brain.setNum2(_brain.output);
_brain.calculate();
} else {
_brain.setNum1(_brain.output);
_brain.output = '0';
_brain.setOperand(buttonText);
}
});
},
),
);
}
...
In the `onPressed` property of the `OutlineButton`, we use the `setState` method to update the state of the app based on the button pressed. We check the value of the button pressed and perform the appropriate actions. We also update the output text to display the current value of the calculator.
And that’s it! With just a few lines of code, we’ve created a simple calculator app in Flutter. Feel free to play around with the code and add your own features.
P.S. : Please note that this is a basic calculator and doesn’t include error handling for divide by zero or other edge cases.