Learn/Mini Projects/Project: Calculator App

Project: Calculator App

Build a calculator app that practices layout, state, and user interaction

12 min~7 min read+80 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Calculator Logic
  2. 2. Button Grid Layout
  3. 3. Expression Safety Rules
  4. 4. This Lesson In Simple Words
  5. 5. Your level focus
  6. 6. One practical habit
  7. 7. Deep Understanding Guide
  8. 8. Why this lesson matters
  9. 9. Study flow for better retention
  10. 10. Quick Glossary
  11. 11. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Calculator App Project

This project focuses on layout skills and user interaction. You will build a fully working calculator with a display area at the top that shows the current input and result, and a grid of buttons below for digits, operators, and actions. This gives you practice with GridView or Wrap for the button layout, Expanded for proportional sizing, setState for updating the display, and string manipulation for handling mathematical expressions. The result is a polished, functional app that looks and works like the calculator on your phone.

Features to build:

  • Display area showing current expression and result
  • Number buttons 0 through 9 and a decimal point
  • Operator buttons for addition, subtraction, multiplication, and division
  • Clear button (C) and backspace button
  • Equals button that calculates the result
  • Responsive button grid that adapts to screen size

Calculator Logic

The calculator stores the current expression as a string. Each time the user taps a button, the corresponding character is appended to the expression string. When the user taps the equals button, the expression is evaluated and the result is displayed. A simple approach is to use Dart string parsing to evaluate basic math, or you can use the math_expressions package for full support.

dart
1class _CalculatorScreenState extends State<CalculatorScreen> {
2 String _expression = '';
3 String _result = '0';
4
5 void _onButtonPressed(String value) {
6 setState(() {
7 if (value == 'C') {
8 _expression = '';
9 _result = '0';
10 } else if (value == '⌫') {
11 if (_expression.isNotEmpty) {
12 _expression = _expression.substring(0, _expression.length - 1);
13 }
14 } else if (value == '=') {
15 try {
16 // Using math_expressions package for evaluation
17 Parser p = Parser();
18 Expression exp = p.parse(_expression);
19 ContextModel cm = ContextModel();
20 double eval = exp.evaluate(EvaluationType.REAL, cm);
21
22 _result = eval == eval.roundToDouble()
23 ? eval.toInt().toString()
24 : eval.toStringAsFixed(2);
25 } catch (e) {
26 _result = 'Error';
27 }
28 } else {
29 _expression += value;
30 }
31 });
32 }
33
34 @override
35 Widget build(BuildContext context) {
36 return Scaffold(
37 backgroundColor: Colors.black,
38 body: SafeArea(
39 child: Column(
40 children: [
41 // Display area
42 Expanded(
43 flex: 2,
44 child: Container(
45 padding: const EdgeInsets.all(24),
46 alignment: Alignment.bottomRight,
47 child: Column(
48 mainAxisAlignment: MainAxisAlignment.end,
49 crossAxisAlignment: CrossAxisAlignment.end,
50 children: [
51 Text(
52 _expression,
53 style: const TextStyle(
54 fontSize: 24, color: Colors.white70,
55 ),
56 ),
57 const SizedBox(height: 8),
58 Text(
59 _result,
60 style: const TextStyle(
61 fontSize: 48,
62 fontWeight: FontWeight.bold,
63 color: Colors.white,
64 ),
65 ),
66 ],
67 ),
68 ),
69 ),
70 // Button grid
71 Expanded(
72 flex: 4,
73 child: _buildButtonGrid(),
74 ),
75 ],
76 ),
77 ),
78 );
79 }
80}

Button Grid Layout

The button grid uses a GridView or a Column of Rows. Each button is a styled container that calls _onButtonPressed when tapped. Operator buttons use a different color to visually separate them from number buttons. The zero button can span two columns using Expanded with a higher flex value.

dart
1Widget _buildButtonGrid() {
2 final buttons = [
3 ['C', '⌫', '%', '/'],
4 ['7', '8', '9', '*'],
5 ['4', '5', '6', '-'],
6 ['1', '2', '3', '+'],
7 ['0', '.', '='],
8 ];
9
10 return Column(
11 children: buttons.map((row) {
12 return Expanded(
13 child: Row(
14 children: row.map((label) {
15 return Expanded(
16 flex: (label == '0') ? 2 : 1,
17 child: Padding(
18 padding: const EdgeInsets.all(4),
19 child: _CalcButton(
20 label: label,
21 color: _getButtonColor(label),
22 onTap: () => _onButtonPressed(label),
23 ),
24 ),
25 );
26 }).toList(),
27 ),
28 );
29 }).toList(),
30 );
31}
32
33Color _getButtonColor(String label) {
34 if (label == 'C' || label == '⌫') return Colors.red.shade700;
35 if ('+-*/=%'.contains(label)) return Colors.orange.shade700;
36 return Colors.grey.shade800;
37}
38
39// Reusable calculator button widget
40class _CalcButton extends StatelessWidget {
41 final String label;
42 final Color color;
43 final VoidCallback onTap;
44
45 const _CalcButton({
46 required this.label,
47 required this.color,
48 required this.onTap,
49 });
50
51 @override
52 Widget build(BuildContext context) {
53 return Material(
54 color: color,
55 borderRadius: BorderRadius.circular(12),
56 child: InkWell(
57 borderRadius: BorderRadius.circular(12),
58 onTap: onTap,
59 child: Center(
60 child: Text(
61 label,
62 style: const TextStyle(
63 fontSize: 28,
64 fontWeight: FontWeight.bold,
65 color: Colors.white,
66 ),
67 ),
68 ),
69 ),
70 );
71 }
72}

math_expressions Package

💡 math_expressions Package

Add math_expressions to your pubspec.yaml for safe expression evaluation instead of writing your own parser. It handles operator precedence, parentheses, and decimal numbers correctly.

Expression Safety Rules

Most calculator bugs happen from invalid expression strings. Define guard rules inside _onButtonPressed:

  • Prevent two operators in a row unless the second one starts a negative value.
  • Block multiple decimal points inside the same number segment.
  • Reject expressions that end with an operator before evaluation.
  • On equals, run parsing in try-catch and keep previous valid result when parsing fails.
  • Normalize symbols if needed (for example x to * and ÷ to /) before parsing.

These rules make your calculator feel stable and intentional, especially during fast tapping.

Calculator Edge Cases Matrix

  • Division by zero and expressions like 0/0 should never crash the app.
  • Trailing operator input such as 7+ should produce a safe error state.
  • Repeated equals taps after a result should follow one predictable rule.
  • Leading zeros and decimal input (0.5, 00.2) should be normalized intentionally.
  • Very long expressions should still render safely in the display area.

Calculator UX Polish Checklist

  • Operator, action, and numeric buttons are visually distinct and consistent.
  • Tap feedback is immediate, and accidental double taps are handled gracefully.
  • Expression text scales or scrolls so long input remains readable.
  • Portrait and landscape layouts both keep balanced spacing and legibility.
  • Error state recovery is clear: user knows how to continue without restarting.

This Lesson In Simple Words

Build a calculator app that practices layout, state, and user interaction. Widgets are reusable UI blocks. You combine them like LEGO pieces to build screens.

Your level focus

Connect each concept to real app features you can build.

One practical habit

Sketch the widget tree first, then code from top to bottom.

Deep Understanding Guide

Why this lesson matters

Most Flutter productivity comes from understanding layout rules and composing widgets cleanly.

Study flow for better retention

  1. Map the lesson to one screen, one user action, and one expected output.
  2. When a UI bug appears, inspect constraints and parent-child relations before changing random values.
  3. If you can choose between two approaches and explain why, you are improving.

Common Mistakes To Avoid

  • Nesting too many widgets without extracting reusable pieces.
  • Ignoring constraints and guessing with random SizedBox heights.
  • Using one giant build method for unrelated UI sections.
  • Putting heavy calculations directly in build methods.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build one card layout with Row/Column and rebuild it using Stack for comparison.
  • Split a large widget into 3 smaller widgets with clear responsibilities.
  • Use const constructors where possible and observe rebuild behavior.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What layout approach works best for a calculator button grid?".

Quick Glossary

  • state: Data that can change and update what the user sees.
  • build: The method that describes UI for the current state.
  • bloc: An event-to-state pattern that separates logic from UI.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Good widget composition is architecture at UI level, because it decides testability and reuse.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "Project: Calculator App" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Nesting too many widgets without extracting reusable pieces.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What layout approach works best for a calculator button grid?

A Column of Rows where each cell is Expanded creates an evenly spaced grid that fills the available screen space perfectly.

How do you make the zero button span two columns?

Setting flex: 2 on the Expanded widget makes the zero button take twice the width of a normal button.

What should happen when the user taps the equals button and the expression is invalid?

Wrapping the evaluation in a try-catch and displaying Error gives the user feedback without crashing the app.

What widget gives a ripple effect when a button is tapped?

InkWell provides the Material Design ripple splash effect on tap. Wrap it in a Material widget for the effect to render properly.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue