RayCC
Cover Image

Flutter study - simple calculate

Flutter Study Coding Sample

Source code reference: https://www.geeksforgeeks.org/simple-calculator-app-using-flutter/

I made some modifications here.

pubspec.yaml

1
2
3
4
dependencies:
  flutter:
    sdk: flutter
  math_expressions: ^2.6.0

lib/main.dart

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import 'package:flutter/material.dart';
import 'package:math_expressions/math_expressions.dart';

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

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        colorSchemeSeed: Color(0xffaaaa22),
        useMaterial3: true,
      ),
      home: Scaffold(
        body: Homepage(),
      ),);}
}

class Homepage extends StatefulWidget {
  const Homepage({super.key});

  @override
  State<Homepage> createState() => _HomepageState();
}

class _HomepageState extends State<Homepage> {
  String _userInput = "";
  String _answer = "";

  final List<String> buttons = [
    'C', '±', '%', 'DEL', 
    '7', '8', '9', '/', 
    '4', '5', '6', '*', 
    '1', '2', '3', '-', 
    '0', '.', '=', '+',
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Simple Calculator'),
        backgroundColor: Theme.of(context).colorScheme.primary,
        foregroundColor: Theme.of(context).colorScheme.onPrimary,
      ),
      body: Column(
        children: [
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                Container(
                  // Answer
                  padding: EdgeInsets.all(10),
                  alignment: Alignment.centerRight,
                  child: SelectableText(
                    _answer,
                    style: Theme.of(context).textTheme.headlineLarge,
                  ),
                ),
                Container(
                  // User Input
                  padding: EdgeInsets.all(10),
                  alignment: Alignment.centerRight,
                  child: SelectableText(
                    _userInput,
                    style: Theme.of(context).textTheme.bodyLarge,
                  ),),
              ],),
          ),
          Expanded(
            flex: 3,
            child: GridView.builder(
              itemCount: buttons.length,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 4,
                mainAxisSpacing: 8.0,
                crossAxisSpacing: 8.0,
                childAspectRatio: 1.2,
              ),
              itemBuilder: (BuildContext context, int index) {
                switch (index) {
                  case 0:
                    // "C" button
                    return Buttons(
                      buttonStyle: ElevatedButton.styleFrom(
                        backgroundColor: Colors.red,
                        foregroundColor: Colors.white,
                      ),
                      buttonString: buttons[index],
                      onTap: () {
                        setState(() {
                          _userInput = "";
                        });
                      },
                    );
                  case 1:
                    // "±" button
                    return Buttons(
                      buttonStyle: ElevatedButton.styleFrom(
                        backgroundColor: Colors.orange,
                        foregroundColor: Colors.white,
                      ),
                      buttonString: buttons[index],
                      onTap: () {
                        setState(() {
                          if (_userInput == "" || _userInput[0] != "-") {
                            _userInput = "-$_userInput";
                          } else {
                            _userInput = _userInput.substring(1);
                          }
                        });
                      },
                    );
                  case var x when [2, 7, 11, 15, 19].contains(x):
                    // Operator buttons
                    return Buttons(
                      buttonStyle: ElevatedButton.styleFrom(
                        backgroundColor: Colors.orange,
                        foregroundColor: Colors.white,
                      ),
                      buttonString: buttons[index],
                      onTap: () {
                        setState(() {
                          _userInput += buttons[index];
                        });
                      },
                    );
                  case 3:
                    // "DEL" button
                    return Buttons(
                      buttonStyle: ElevatedButton.styleFrom(
                        backgroundColor: Colors.red,
                        foregroundColor: Colors.white,
                      ),
                      buttonString: buttons[index],
                      onTap: () {
                        setState(() {
                          _userInput =
                              _userInput.substring(0, _userInput.length - 1);
                        });
                      },
                    );
                  case 18:
                    // "=" button
                    return Buttons(
                        buttonStyle: ElevatedButton.styleFrom(
                          backgroundColor:
                              Theme.of(context).colorScheme.primary,
                          foregroundColor:
                              Theme.of(context).colorScheme.onPrimary,
                        ),
                        buttonString: buttons[index],
                        onTap: () {
                          setState(() {
                            _equalPressed();
                          });
                        });
                  default:
                    // Number buttons
                    return Buttons(
                      buttonString: buttons[index],
                      onTap: () {
                        setState(() {
                          _userInput += buttons[index];
                        });
                    },);}},
            ),),],
      ),);}

  // Calculate expression
  void _equalPressed() {
    try {
      _answer = Parser()
          .parse(_userInput)
          .evaluate(EvaluationType.REAL, ContextModel())
          .toString();
    } catch (e) {
      _answer = "Error";
    }
  }
}

class Buttons extends StatelessWidget {
  final ButtonStyle? buttonStyle;
  final String buttonString;
  final void Function() onTap;

  const Buttons({
    super.key,
    this.buttonStyle,
    required this.buttonString,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onTap,
      style: buttonStyle,
      child: Text(
        buttonString,
        style: TextStyle(fontSize: 20),
      ),);
  }
}