Simple Calculator App using Flutter

Raja Sharma
5 min readAug 22, 2021

Task -11

Description : Till date whatever we have learnt in Flutter ,is need to be implemented in some way integrating other technologies with it

main.dart File

If you explore the directories, you will find lib/main.dart. This is the dart file where the main method goes. In simple words this is the entry file for our application.

We are going to build our app from scratch, hence delete all the code from the main.dart file and put this code instead.

The first line imports the Flutter Material package. The second line imports the home_page.dart file where our the logic and design of our application resides.

Like in Java, C++, in Dart too, the main method is the entry point of the program. Hence the fourth line creates the main method and runs an inbuilt Flutter method runApp.

Note: Flutter applications are built with widgets.

We are then creating a class called MyApp which is a statelesswidget (Don’t worry we are going to talk about stateless and stateful widget in some time). We are building a Widget with the help of build method. The build method returns a new Material App, where we give the title of our application, set the theme and the home page.

Stateless vs Stateful Widgets

In Flutter, widgets are of two types, they can either be stateless or stateful.

Stateful widgets are the ones with which we can change the state of the app. Example when we click on the numbers button of the calculator the display changes.

Stateless widgets are the static widgets. No changes take place here.

home_page.dart File

The home_page.dart file that we imported in the main.dart file is the heart of our application code.

Create this new file in the lib directory, paste the following code.

We are returning Scaffold, which implements the basic material design visual layout structure. The Scaffold class provides APIs for showing App Bar, Drawers, Bottom Navigation etc.

The body is made of a container classwhich contains a child Text. The Text class is used to display the text.

The root widget of our application is a MaterialApp. This gives us a lot of predefined functionality that are in line with Google’s Material Design. A Scaffold also provides a lot of APIs but for now it’s only relevant for us at it makes the default font look good.
The Calculation widget is not yet created, you should get an error saying “The method ‘Calculation’ isn’t defined for the type ‘CalculatorApp'”. We will fix it in a minute by implementing the widget. The purpose of it is to represent the screen that holds all of the UI elements of our calculator.

import ‘package:flutter/material.dart’;

void main() {

runApp(CalculatorApp());

}

class CalculatorApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: ‘Flutter basic calculator’,

home: Scaffold(

body: Calculation()

),

);

}

}

The widget needs to be a StatefulWidget because we want to hold information like the current result and later also the operands and the operator. Tip: if you are unsure whether you need a StateFulWidget or a StateLessWidget, just start with a stateless one. Android Studio and VS Code offer a shortcut to convert a StateLessWidget to a StateFulWidget which you can use if you change your mind.

import ‘package:flutter/material.dart’;

class Calculation extends StatefulWidget {

@override

_CalculationState createState() => _CalculationState();

}

class _CalculationState extends State<Calculation> {

int result;

@override

Widget build(BuildContext context) {

return ResultDisplay(text: ‘0’);

}

}

ResultDisplay is the only widget that will be displayed in our first iteration. It’s the top part of the calculator showing the result of the current calculation.

import ‘package:flutter/material.dart’;

class ResultDisplay extends StatelessWidget {

ResultDisplay({

@required this.text

});

final int result;

@override

Widget build(BuildContext context) {

return Container(

width: double.infinity,

height: 80,

color: Colors.black,

child: Text(

text,

style: TextStyle(

color: Colors.white,

fontSize: 34

),

)

);

}

}

If you run the app now, it should look something like this:

Creating the keypad button

import ‘package:flutter/material.dart’;

class CalculatorButton extends StatelessWidget {

CalculatorButton({

@required this.label,

@required this.onTap,

@required this.size,

this.backgroundColor = Colors.white,

this.labelColor = Colors.black

});

@override

Widget build(BuildContext context) {

return Padding(

padding: EdgeInsets.all(6),

child: Ink(

width: size,

height: size,

decoration: BoxDecoration(

boxShadow: [

BoxShadow(

color: Colors.grey,

offset: Offset(1, 1),

blurRadius: 2

),

],

borderRadius: BorderRadius.all(

Radius.circular(size / 2)

),

color: backgroundColor

),

child: InkWell(

customBorder: RoundedRectangleBorder(

borderRadius: BorderRadius.all(Radius.circular(size / 2)),

),

onTap: onTap,

child: Center(

child: Text(

label,

style: TextStyle(fontSize: 24, color: labelColor),

)

),

),

)

);

}

Padding widget that creates an inset around its child by the specified

color property of a Container widget determines its background color

A FlatButton is a certain kind of MatierialButton

insert every button we know we are going to need.

@override

Widget build(BuildContext context) {

return Column(

children: [

ResultDisplay(text: ‘0’),

Row(

children: [

_getButton(text: ‘7’, onTap: () => numberPressed(7)),

_getButton(text: ‘8’, onTap: () => numberPressed(8)),

_getButton(text: ‘9’, onTap: () => numberPressed(9)),

_getButton(text: ‘x’, onTap: () => operatorPressed(‘*’), backgroundColor: Color.fromRGBO(220, 220, 220, 1)),

],

),

Row(

children: [

_getButton(text: ‘4’, onTap: () => numberPressed(4)),

_getButton(text: ‘5’, onTap: () => numberPressed(5)),

_getButton(text: ‘6’, onTap: () => numberPressed(6)),

_getButton(text: ‘/’, onTap: () => operatorPressed(‘/’), backgroundColor: Color.fromRGBO(220, 220, 220, 1)),

],

),

Row(

children: [

_getButton(text: ‘1’, onTap: () => numberPressed(1)),

_getButton(text: ‘2’, onTap: () => numberPressed(2)),

_getButton(text: ‘3’, onTap: () => numberPressed(3)),

_getButton(text: ‘+’, onTap: () => operatorPressed(‘+’), backgroundColor: Color.fromRGBO(220, 220, 220, 1))

],

),

Row(

children: [

_getButton(text: ‘=’, onTap: calculateResult, backgroundColor: Colors.orange, textColor: Colors.white),

_getButton(text: ‘0’, onTap: () => numberPressed(0)),

_getButton(text: ‘C’, onTap: clear, backgroundColor: Color.fromRGBO(220, 220, 220, 1)),

_getButton(text: ‘-’, onTap: () => operatorPressed(‘-’),backgroundColor: Color.fromRGBO(220, 220, 220, 1)),

],

),

]

);

}

operatorPressed(String operator) {}

numberPressed(int number) {}

calculateResult() {}

clear() {}

Okay, now Make function that is executed once the result button is tapped:

calculateResult() {

if (operator == null || secondOperand == null) {

return;

}

setState(() {

switch (operator) {

case ‘+’:

result = firstOperand + secondOperand;

break;

case ‘-’:

result = firstOperand — secondOperand;

break;

case ‘*’:

result = firstOperand * secondOperand;

break;

case ‘/’:

if (secondOperand == 0) {

return;

}

result = firstOperand ~/ secondOperand;

break;

}

firstOperand = result;

operator = null;

secondOperand = null;

result = null;

});

}

THANKS FOR READING!!

--

--