How to create calculator using flutter

Creating a calculator app in Flutter involves designing the UI and implementing the logic for basic arithmetic operations. Here’s a step-by-step guide to get you started:

1. Set Up Your Flutter Project

  1. Install Flutter: Ensure you have Flutter installed on your system. If not, follow the official installation guide.
  2. Create a New Project:
flutter create calculator_app
cd calculator_app

3.Open the Project: Use your preferred IDE (like VSCode or Android Studio) to open the project.

    2. Define Dependencies

    You don’t need any additional dependencies for a basic calculator, so you can proceed with the default setup.

    3. Create the UI

    In your lib folder, you will mainly work with main.dart. Open main.dart and start designing your UI.

    Also Raed:- How to create a News Website Using Admin Panel In PHP

    Here’s a simple example of how to create a basic calculator UI:

    import 'package:flutter/material.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 _expression = '';
    
      void _append(String value) {
        setState(() {
          _expression += value;
        });
      }
    
      void _clear() {
        setState(() {
          _expression = '';
        });
      }
    
      void _calculate() {
        try {
          final result = _evaluateExpression(_expression);
          setState(() {
            _expression = result.toString();
          });
        } catch (e) {
          setState(() {
            _expression = 'Error';
          });
        }
      }
    
      double _evaluateExpression(String expression) {
        // Simple evaluation logic (use a package like `expressions` for more complex expressions)
        return double.parse(expression); // Replace with actual evaluation logic
      }
    
      @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(20),
                  child: Text(
                    _expression,
                    style: TextStyle(fontSize: 48, fontWeight: FontWeight.bold),
                  ),
                ),
              ),
              GridView.count(
                shrinkWrap: true,
                crossAxisCount: 4,
                children: <Widget>[
                  ...['7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '=', '+', 'C'].map((text) {
                    return _CalculatorButton(
                      text: text,
                      onPressed: () {
                        if (text == 'C') {
                          _clear();
                        } else if (text == '=') {
                          _calculate();
                        } else {
                          _append(text);
                        }
                      },
                    );
                  }).toList(),
                ],
              ),
            ],
          ),
        );
      }
    }
    
    class _CalculatorButton extends StatelessWidget {
      final String text;
      final VoidCallback onPressed;
    
      _CalculatorButton({required this.text, required this.onPressed});
    
      @override
      Widget build(BuildContext context) {
        return ElevatedButton(
          onPressed: onPressed,
          child: Text(text, style: TextStyle(fontSize: 24)),
          style: ElevatedButton.styleFrom(
            padding: EdgeInsets.all(20),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(0),
            ),
          ),
        );
      }
    }
    

    4. Implement the Calculator Logic

    The _evaluateExpression method in this basic example is just a placeholder. For a fully functional calculator, you should parse and evaluate mathematical expressions.

    You can use a package like expressions or implement a basic parser yourself.

    Using the expressions package:

    1. Add the package to your pubspec.yaml:
    dependencies:
      flutter:
        sdk: flutter
      expressions: ^0.1.7
    

    2. Import and use it in your code:

    import 'package:expressions/expressions.dart';
    
    double _evaluateExpression(String expression) {
      final exp = Expression.parse(expression);
      final evaluator = const ExpressionEvaluator();
      return evaluator.eval(exp, {});
    }
    

    5. Test Your Calculator

    Run your app using:

    flutter run
    

    Test the functionality of your calculator to ensure all arithmetic operations are working correctly.

    6. Polish and Expand

    • Design Improvements: You can style buttons and layout to make it look more polished.
    • Advanced Features: Add functionalities like parentheses, scientific functions, or history.

    This guide covers the basics of creating a calculator app with Flutter. Depending on your needs, you can further customize and enhance it!

    Also Read: How to create hospital management system project using PHP and MySQL

    Leave a Comment