Dheeraj Hitech - Learn, Apply and Share

collapse
...
Home / Flutter Tutorial / How to create a calculator using Flutter

How to create a calculator using Flutter

2025-05-02  Dheeraj Pal  94 views

Step 1: Set Up a Flutter Project

flutter create calculator_app
cd calculator_app

Open lib/main.dart.

Step 2: Basic UI Layout

Replace main.dart with the following code:

import 'package:flutter/material.dart';

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

class CalculatorApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Calculator',
      home: CalculatorHome(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class CalculatorHome extends StatefulWidget {
  @override
  _CalculatorHomeState createState() => _CalculatorHomeState();
}

class _CalculatorHomeState extends State<CalculatorHome> {
  String _input = '';
  String _result = '';

  void _buttonPressed(String value) {
    setState(() {
      if (value == 'C') {
        _input = '';
        _result = '';
      } else if (value == '=') {
        try {
          _result = _calculateResult(_input);
        } catch (e) {
          _result = 'Error';
        }
      } else {
        _input += value;
      }
    });
  }

  String _calculateResult(String input) {
    // A very basic parser using Dart's built-in functionality
    final expression = input.replaceAll('×', '*').replaceAll('÷', '/');
    final parsedResult = double.parse(
        _evaluateExpression(expression).toStringAsFixed(2));
    return parsedResult.toString();
  }

  double _evaluateExpression(String expression) {
    // You can replace this with a proper math parser for more complex expressions
    // This is just for demonstration using basic arithmetic
    return double.parse(expression); // Placeholder - replace with logic or package
  }

  Widget _buildButton(String label) {
    return Expanded(
      child: ElevatedButton(
        onPressed: () => _buttonPressed(label),
        child: Text(label, style: TextStyle(fontSize: 24)),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Calculator')),
      body: Column(
        children: <Widget>[
          Expanded(
            child: Container(
              alignment: Alignment.bottomRight,
              padding: EdgeInsets.all(24),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Text(_input, style: TextStyle(fontSize: 32)),
                  SizedBox(height: 8),
                  Text(_result, style: TextStyle(fontSize: 24, color: Colors.grey)),
                ],
              ),
            ),
          ),
          Column(
            children: [
              Row(children: [_buildButton('7'), _buildButton('8'), _buildButton('9'), _buildButton('÷')]),
              Row(children: [_buildButton('4'), _buildButton('5'), _buildButton('6'), _buildButton('×')]),
              Row(children: [_buildButton('1'), _buildButton('2'), _buildButton('3'), _buildButton('-')]),
              Row(children: [_buildButton('C'), _buildButton('0'), _buildButton('='), _buildButton('+')]),
            ],
          ),
        ],
      ),
    );
  }
}

 Step 3: Add Expression Evaluation

For proper expression evaluation (e.g., 1+2×3), use a package like math_expressions.

Add to pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  math_expressions: ^2.2.0

Then update _calculateResult():

import 'package:math_expressions/math_expressions.dart';

// Inside _calculateResult:
String _calculateResult(String input) {
  final expression = input.replaceAll('×', '*').replaceAll('÷', '/');
  Parser p = Parser();
  Expression exp = p.parse(expression);
  ContextModel cm = ContextModel();
  double eval = exp.evaluate(EvaluationType.REAL, cm);
  return eval.toStringAsFixed(2);
}

Step 4: Run the App

flutter run

 

Also Read : Top 50 Flutter Interview Questions


Share: