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.
Build a calculator app that practices layout, state, and user interaction
You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.
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
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:
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.
1class _CalculatorScreenState extends State<CalculatorScreen> {2String _expression = '';3String _result = '0';45void _onButtonPressed(String value) {6setState(() {7if (value == 'C') {8_expression = '';9_result = '0';10} else if (value == '⌫') {11if (_expression.isNotEmpty) {12_expression = _expression.substring(0, _expression.length - 1);13}14} else if (value == '=') {15try {16// Using math_expressions package for evaluation17Parser p = Parser();18Expression exp = p.parse(_expression);19ContextModel cm = ContextModel();20double eval = exp.evaluate(EvaluationType.REAL, cm);2122_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}3334@override35Widget build(BuildContext context) {36return Scaffold(37backgroundColor: Colors.black,38body: SafeArea(39child: Column(40children: [41// Display area42Expanded(43flex: 2,44child: Container(45padding: const EdgeInsets.all(24),46alignment: Alignment.bottomRight,47child: Column(48mainAxisAlignment: MainAxisAlignment.end,49crossAxisAlignment: CrossAxisAlignment.end,50children: [51Text(52_expression,53style: const TextStyle(54fontSize: 24, color: Colors.white70,55),56),57const SizedBox(height: 8),58Text(59_result,60style: const TextStyle(61fontSize: 48,62fontWeight: FontWeight.bold,63color: Colors.white,64),65),66],67),68),69),70// Button grid71Expanded(72flex: 4,73child: _buildButtonGrid(),74),75],76),77),78);79}80}
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.
1Widget _buildButtonGrid() {2final buttons = [3['C', '⌫', '%', '/'],4['7', '8', '9', '*'],5['4', '5', '6', '-'],6['1', '2', '3', '+'],7['0', '.', '='],8];910return Column(11children: buttons.map((row) {12return Expanded(13child: Row(14children: row.map((label) {15return Expanded(16flex: (label == '0') ? 2 : 1,17child: Padding(18padding: const EdgeInsets.all(4),19child: _CalcButton(20label: label,21color: _getButtonColor(label),22onTap: () => _onButtonPressed(label),23),24),25);26}).toList(),27),28);29}).toList(),30);31}3233Color _getButtonColor(String label) {34if (label == 'C' || label == '⌫') return Colors.red.shade700;35if ('+-*/=%'.contains(label)) return Colors.orange.shade700;36return Colors.grey.shade800;37}3839// Reusable calculator button widget40class _CalcButton extends StatelessWidget {41final String label;42final Color color;43final VoidCallback onTap;4445const _CalcButton({46required this.label,47required this.color,48required this.onTap,49});5051@override52Widget build(BuildContext context) {53return Material(54color: color,55borderRadius: BorderRadius.circular(12),56child: InkWell(57borderRadius: BorderRadius.circular(12),58onTap: onTap,59child: Center(60child: Text(61label,62style: const TextStyle(63fontSize: 28,64fontWeight: FontWeight.bold,65color: Colors.white,66),67),68),69),70);71}72}
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.
Most calculator bugs happen from invalid expression strings. Define guard rules inside _onButtonPressed:
These rules make your calculator feel stable and intentional, especially during fast tapping.
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.
Connect each concept to real app features you can build.
Sketch the widget tree first, then code from top to bottom.
Most Flutter productivity comes from understanding layout rules and composing widgets cleanly.
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.
A Column of Rows where each cell is Expanded creates an evenly spaced grid that fills the available screen space perfectly.
Setting flex: 2 on the Expanded widget makes the zero button take twice the width of a normal button.
Wrapping the evaluation in a try-catch and displaying Error gives the user feedback without crashing the app.
InkWell provides the Material Design ripple splash effect on tap. Wrap it in a Material widget for the effect to render properly.
Something seems incorrect, unclear, or missing? Let us know.
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