import 'package:flutter/material.dart'; void main() => runApp(const CalculatorApp()); class CalculatorApp extends StatelessWidget { const CalculatorApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Calculator', home: const CalculatorScreen(), ); } } class CalculatorScreen extends StatefulWidget { const CalculatorScreen({super.key}); @override State createState() => CalculatorScreenState(); } class CalculatorScreenState extends State { String input = "0"; String operand = ""; String operator = ""; String history = ""; void buttonPressed(String text) { setState(() { if (text == "C") { input = "0"; operand = ""; operator = ""; history = ""; } else if (text == "=") { evaluateExpression(); } else { history = history + text; if (text == "+" || text == "-" || text == "*" || text == "/") { operator = text; operand = input; input = "0"; } else { input = input == "0" ? text : input + text; } } }); } void evaluateExpression() { double num1 = double.tryParse(operand) ?? 0; double num2 = double.tryParse(input) ?? 0; double result; switch (operator) { case "+": result = num1 + num2; break; case "-": result = num1 - num2; break; case "*": result = num1 * num2; break; case "/": result = num1 / num2; break; default: result = 0; break; } if (result == result.toInt()) { history = "$history = ${result.toInt()}\n"; } else { history = "$history = $result\n"; } input = "0"; operand = ""; operator = ""; } Widget buildButton(String text, {Color? color}) { return Expanded( child: Container( padding: const EdgeInsets.all(8), child: TextButton( style: TextButton.styleFrom( backgroundColor: color ?? Colors.grey[900], foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(vertical: 20), ), onPressed: () => buttonPressed(text), child: Center( child: Text(text, style: const TextStyle(fontSize: 40), ), ), ), ), ); } Widget buildButtonRow(List> buttons) { return Row( children: buttons.map((btn) => buildButton(btn['label'], color: btn['color'],)).toList(), ); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.black, body: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(history, style: const TextStyle(fontSize: 40, color: Colors.white)), Text(input, style: const TextStyle(fontSize: 56, color: Colors.white)), buildButtonRow([ {'label': '7'}, {'label': '8'}, {'label': '9'}, {'label': '/', 'color': Colors.orange}, ]), buildButtonRow([ {'label': '4'}, {'label': '5'}, {'label': '6'}, {'label': '*', 'color': Colors.orange}, ]), buildButtonRow([ {'label': '1'}, {'label': '2'}, {'label': '3'}, {'label': '-', 'color': Colors.orange}, ]), buildButtonRow([ {'label': '0'}, {'label': 'C', 'color': Colors.red}, {'label': '=', 'color': Colors.green}, {'label': '+', 'color': Colors.orange}, ]), const SizedBox(height: 30), ], ), ); } }