Create a Calculator App for Android in Flutter




  • The Flutter Create Calculator app demonstrates how to build an app with Flutter. 
  • The app is a calculator that is capable of floating around the screen. 
  • The background color, text color, and buttons colors can be controlled by the user. 
  • The app is built with a main.dart file and buttons.dart file. 
  • The button's colors are set through the MainStatelessWidget using a StatelessWidget method.

Step 1: Add the Dependency to pubspec.yaml file as shown below:



 dependencies:
  lint: ^1.8.2
  math_expressions: ^2.3.0

Step 2: Import the library

Now in your Dart code, you can use:

 import 'package:math_expressions/math_expressions.dart';

Create a Button List


 List button = [
    "AC","DLT","%","/","9","8","7","*","6","5","4","-","3","2","1","+","0",".","=",
  ];


Expression method() create



 void expression(){
    Parser p = Parser();
    Expression exp = p.parse(userInput);
    ContextModel cm = ContextModel();
    var evalue = exp.evaluate(EvaluationType.REAL, cm);
    userInput = evalue.toString();

  }

Operations create



   isOperator(String x){
    if(x == "%" || x == "+" || x == "-" || x == "*" || x == "/" || x == "="){
      return true;
    }
    return false;
  }


Full Source Code

main.dart


import 'package:calculator/HomeScreen/home_screen.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Calculator Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomeScreen(),
    );
  }
}

button_widget.dart

import 'package:flutter/material.dart';

class ButtonWid extends StatefulWidget {
  ButtonWid(
      {required this.buttonColor,
      required this.buttonText,
      required this.buttonTextColor,
      this.onPressed});

  Color buttonColor;
  String buttonText;
  Color buttonTextColor;
  final VoidCallback? onPressed;

  @override
  State createState() => _ButtonWidState();
}

class _ButtonWidState extends State {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: widget.onPressed,
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Container(
          decoration: BoxDecoration(
            color: widget.buttonColor,
            borderRadius: BorderRadius.circular(20),
          ),
          child: Center(
            child: Text(
              widget.buttonText,
              style: TextStyle(
                  color: widget.buttonTextColor,
                  fontWeight: FontWeight.bold,
                  fontSize: 20),
            ),
          ),
        ),
      ),
    );
  }
}

home_screen.dart


import 'package:calculator/Widgets/botton_widget.dart';
import 'package:flutter/material.dart';
import 'package:math_expressions/math_expressions.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State {
  List button = [
    "AC","DLT","%","/","9","8","7","*","6","5","4","-","3","2","1","+","0",".","=",
  ];

  void expression(){
    Parser p = Parser();
    Expression exp = p.parse(userInput);
    ContextModel cm = ContextModel();
    var evalue = exp.evaluate(EvaluationType.REAL, cm);
    userInput = evalue.toString();

  }

  isOperator(String x){
    if(x == "%" || x == "+" || x == "-" || x == "*" || x == "/" || x == "="){
      return true;
    }
    return false;
  }

  var userInput = "";
  var userOutput = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body: Column(
          children: [
            Expanded(
              child: Padding(
                padding: const EdgeInsets.only(top: 85.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Container(
                      child: Text(
                        userInput,
                        style: TextStyle(color: Colors.black, fontSize: 35),
                      ),
                    ),
                    Divider(
                      indent: 25,
                      endIndent: 25,
                      thickness: 2,
                      color: Colors.grey,
                    ),
                    Container(
                      alignment: Alignment.centerRight,
                      child: Text(userOutput,style: TextStyle(
                        color: Colors.black,fontSize: 30
                      ),),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
              flex: 2,
              child: SizedBox(
                width: 350,
                child: GridView.builder(
                    gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 4,
                    ),
                  itemCount: button.length,
                  itemBuilder: (BuildContext context, int index) {
                    if(index == 0){
                      return ButtonWid(
                        onPressed: (){
                          setState(() {
                            userInput = "";
                          });
                        },
                        buttonColor: Colors.amber,
                        buttonText: button[index],
                        buttonTextColor: Colors.white,
                      );
                    } else if(index == 1){
                      return ButtonWid(
                        onPressed: (){
                          setState(() {
                            userInput = userInput.substring(0,userInput.length - 1);
                          });
                        },
                        buttonColor: Colors.amber,
                        buttonText: button[index],
                        buttonTextColor: Colors.white,
                      );
                    } else if(index == button.length - 1){
                      return ButtonWid(
                        onPressed: (){
                          setState(() {
                            expression();
                          });
                        },
                        buttonColor: Colors.amber,
                        buttonText: button[index],
                        buttonTextColor: Colors.white,
                      );
                    } else {
                      return ButtonWid(
                        onPressed: (){
                          setState(() {
                            userInput = userInput + button[index];
                          });
                        },
                        buttonColor:  isOperator(button[index])
                        ? Colors.amber
                        : Colors.blue,
                        buttonText: button[index],
                        buttonTextColor: Colors.white,
                      );
                    }
                  },

                ),
              ),
            )
          ],
        ));
  }
}


OUTPUT