Creating an advanced calculator app in Flutter involves additional features beyond basic arithmetic, such as scientific functions (e.g., trigonometry, logarithms) and better state management. Below is a step-by-step guide with source code.

Step 1: Set Up a New Flutter Project

  1. Create a new Flutter project:
   flutter create advanced_calculator
  1. Navigate to the project directory:
   cd advanced_calculator

Step 2: Update pubspec.yaml

Add the math_expressions package to handle complex mathematical calculations:

dependencies:
  flutter:
    sdk: flutter
math_expressions: ^3.1.0

Run flutter pub get to install the package.

Step 3: Create the User Interface and Logic

In the lib directory, open main.dart and replace its content with the following code:

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

void main() => runApp(AdvancedCalculatorApp());

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

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

class _CalculatorHomePageState extends State<CalculatorHomePage> {
  String expression = "";
  String result = "0";

  void buttonPressed(String buttonText) {
    setState(() {
      if (buttonText == "CLEAR") {
        expression = "";
        result = "0";
      } else if (buttonText == "=") {
        try {
          Parser p = Parser();
          Expression exp = p.parse(expression.replaceAll('X', '*'));
          ContextModel cm = ContextModel();
          result = '${exp.evaluate(EvaluationType.REAL, cm)}';
        } catch (e) {
          result = "Error";
        }
      } else {
        expression += buttonText;
      }
    });
  }

  Widget buildButton(String buttonText, {Color? color, Color? textColor}) {
    return Expanded(
      child: OutlineButton(
        padding: EdgeInsets.all(24.0),
        color: color,
        textColor: textColor ?? Colors.black,
        child: Text(
          buttonText,
          style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
        ),
        onPressed: () => buttonPressed(buttonText),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Advanced Calculator'),
      ),
      body: Column(
        children: <Widget>[
          Container(
            alignment: Alignment.centerRight,
            padding: EdgeInsets.symmetric(
              vertical: 24.0,
              horizontal: 12.0,
            ),
            child: Text(
              expression,
              style: TextStyle(
                fontSize: 32.0,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          Container(
            alignment: Alignment.centerRight,
            padding: EdgeInsets.symmetric(
              vertical: 24.0,
              horizontal: 12.0,
            ),
            child: Text(
              result,
              style: TextStyle(
                fontSize: 48.0,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          Expanded(
            child: Divider(),
          ),
          Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  buildButton("7"),
                  buildButton("8"),
                  buildButton("9"),
                  buildButton("/", color: Colors.blue, textColor: Colors.white),
                ],
              ),
              Row(
                children: <Widget>[
                  buildButton("4"),
                  buildButton("5"),
                  buildButton("6"),
                  buildButton("X", color: Colors.blue, textColor: Colors.white),
                ],
              ),
              Row(
                children: <Widget>[
                  buildButton("1"),
                  buildButton("2"),
                  buildButton("3"),
                  buildButton("-", color: Colors.blue, textColor: Colors.white),
                ],
              ),
              Row(
                children: <Widget>[
                  buildButton("."),
                  buildButton("0"),
                  buildButton("00"),
                  buildButton("+", color: Colors.blue, textColor: Colors.white),
                ],
              ),
              Row(
                children: <Widget>[
                  buildButton("sin"),
                  buildButton("cos"),
                  buildButton("tan"),
                  buildButton("sqrt", color: Colors.blue, textColor: Colors.white),
                ],
              ),
              Row(
                children: <Widget>[
                  buildButton("CLEAR", color: Colors.red, textColor: Colors.white),
                  buildButton("=", color: Colors.green, textColor: Colors.white),
                ],
              )
            ],
          ),
        ],
      ),
    );
  }
}

Step 4: Run the App

Now that the code is in place, run your app using the following command:

flutter run

Explanation:

  • UI Structure: The UI includes buttons for numbers, basic arithmetic operations, and additional scientific functions like sincostan, and sqrt.
  • Math Expressions: The math_expressions package is used to evaluate the expressions entered by the user. It allows for more complex operations and ensures accurate calculations.
  • State Management: The app uses a StatefulWidget to manage the state of the expression and result.

This advanced calculator app covers both basic and scientific functions, making it more versatile for various calculations.

Categories: Flutter

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *