How to Make a Calculator App with Flutter

In this tutorial, we will guide you on how to create a calculator app using Flutter. Flutter is an open-source UI framework developed by Google for crafting beautiful, natively compiled applications for mobile, web, and desktop platforms from a single codebase.

The calculator app we will build will be able to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. We will also implement a clear button to reset the calculator display.

Before we get started, ensure that you have Flutter installed on your machine. You can follow the official Flutter installation guide for instructions on how to set up Flutter: Flutter Installation Guide

Step 1: Create a new Flutter project

To start, open your terminal or command prompt and navigate to the directory where you want to create your new Flutter project. Use the following command to create a new Flutter project:

flutter create calculator_app

This command will create a new directory named calculator_app with the basic project structure and files.

Step 2: Set up the project dependencies

After creating the Flutter project, open it in your preferred code editor. Then, open the pubspec.yaml file located in the root of your project.

Add the following line under the dependencies section:

math_expressions: ^2.0.3

This package will help us evaluate the mathematical expressions entered by the user.

Save the pubspec.yaml file, and run the following command in the terminal to fetch the newly added dependency:

flutter pub get

Step 3: Design the user interface

We will now design the user interface (UI) of our calculator app. Navigate to the lib directory of your project and open the main.dart file.

Remove the default code in the main.dart file, and replace it with the following code:

import 'package:flutter/material.dart';
import 'package:math_expressions/math_expressions.dart';

void main() {
  runApp(CalculatorApp());
}

class CalculatorApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Calculator',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: CalculatorHomePage(),
    );
  }
}

class CalculatorHomePage extends StatefulWidget {
  @override
  _CalculatorHomePageState createState() => _CalculatorHomePageState();
}

class _CalculatorHomePageState extends State<CalculatorHomePage> {
  String userInput = '';
  String result = '';

  void evaluateResult() {
    Parser p = Parser();
    Expression exp = p.parse(userInput);
    ContextModel cm = ContextModel();
    double eval = exp.evaluate(EvaluationType.REAL, cm);
    setState(() {
      result = eval.toString();
    });
  }

  void clear() {
    setState(() {
      userInput = '';
      result = '';
    });
  }

  Widget buildButton(String buttonText, Color buttonColor,
      {bool isClearButton = false}) {
    return Expanded(
      child: Container(
        margin: EdgeInsets.all(8.0),
        child: FlatButton(
          child: Text(
            buttonText,
            style: TextStyle(fontSize: 20.0, color: Colors.white),
          ),
          onPressed: () {
            setState(() {
              if (isClearButton) {
                clear();
              } else {
                userInput += buttonText;
                evaluateResult();
              }
            });
          },
        ),
        color: buttonColor,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Calculator'),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: Container(
              padding: EdgeInsets.all(16.0),
              alignment: Alignment.bottomRight,
              child: Text(
                userInput,
                style: TextStyle(fontSize: 32.0),
              ),
            ),
          ),
          Expanded(
            child: Container(
              padding: EdgeInsets.all(16.0),
              alignment: Alignment.bottomRight,
              child: Text(
                result,
                style: TextStyle(
                  fontSize: 32.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          Row(
            children: <Widget>[
              buildButton('7', Colors.grey.shade700),
              buildButton('8', Colors.grey.shade700),
              buildButton('9', Colors.grey.shade700),
              buildButton('/', Colors.orange.shade700),
            ],
          ),
          Row(
            children: <Widget>[
              buildButton('4', Colors.grey.shade700),
              buildButton('5', Colors.grey.shade700),
              buildButton('6', Colors.grey.shade700),
              buildButton('*', Colors.orange.shade700),
            ],
          ),
          Row(
            children: <Widget>[
              buildButton('1', Colors.grey.shade700),
              buildButton('2', Colors.grey.shade700),
              buildButton('3', Colors.grey.shade700),
              buildButton('-', Colors.orange.shade700),
            ],
          ),
          Row(
            children: <Widget>[
              buildButton('0', Colors.grey.shade700),
              buildButton('.', Colors.grey.shade700),
              buildButton('=', Colors.red.shade600),
              buildButton('+', Colors.orange.shade700),
            ],
          ),
          Row(
            children: <Widget>[
              buildButton('C', Colors.red.shade600, isClearButton: true),
            ],
          ),
        ],
      ),
    );
  }
}

In this code, we have defined the CalculatorApp class, which is the entry point of our Flutter app. Inside this class, we have defined a stateful widget named CalculatorHomePage.

The CalculatorHomePage widget contains the UI layout for our calculator app. It has two Text widgets to display the user input and the result. The user input is stored in the userInput variable, and the result is stored in the result variable.

We have also defined various helper methods to handle button presses and evaluate the mathematical expression using the math_expressions package.

The buildButton method is responsible for creating the calculator buttons. Each button is represented by a FlatButton wrapped inside a Container with a specified color.

Step 4: Run the app

Congratulations! You have completed the coding part. Now, it’s time to run our calculator app.

In the terminal, navigate to the root directory of your Flutter project and run the following command:

flutter run

This command will compile the code and launch the app on an available simulator or connected device. You will see your calculator app running on the screen.

Conclusion

In this tutorial, we learned how to create a calculator app using Flutter. We used Flutter’s UI framework to design the user interface and implemented the basic arithmetic operations.

Flutter enables developers to build high-quality apps for multiple platforms using a single codebase. By enhancing our calculator app, you can add more advanced features like parentheses handling, memory functions, and scientific calculations.

You can find the complete source code of the calculator app on GitHub: Calculator App Source Code

I hope you found this tutorial helpful in getting started with Flutter and building your own calculator app. Happy coding!

Related Post