import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Mini Calculator',
theme: ThemeData(primarySwatch: Colors.indigo),
home: const CalculatorPage(),
);
}
}
class CalculatorPage extends StatefulWidget {
const CalculatorPage({super.key});
@override
State<CalculatorPage> createState() => _CalculatorPageState();
}
class _CalculatorPageState extends State<CalculatorPage> {
final TextEditingController _num1Controller = TextEditingController();
final TextEditingController _num2Controller = TextEditingController();
final TextEditingController _resultController = TextEditingController();
/// Function with arguments (operation chosen by operator)
void calculate(double a, double b, String operator) {
double result = 0;
switch (operator) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
if (b != 0) {
result = a / b;
} else {
_resultController.text = "Cannot divide by 0";
return;
}
break;
}
setState(() {
_resultController.text = result.toString();
});
}
/// Helper to safely parse numbers
void _onOperationPressed(String operator) {
final double? num1 = double.tryParse(_num1Controller.text);
final double? num2 = double.tryParse(_num2Controller.text);
if (num1 != null && num2 != null) {
calculate(num1, num2, operator);
} else {
setState(() {
_resultController.text = "Invalid input";
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Mini Calculator")),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _num1Controller,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: "Enter first number",
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
TextField(
controller: _num2Controller,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: "Enter second number",
border: OutlineInputBorder(),
),
),
const SizedBox(height: 16),
/// Row of operation buttons
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
onPressed: () => _onOperationPressed('+'),
child: const Text("+"),
),
ElevatedButton(
onPressed: () => _onOperationPressed('-'),
child: const Text("-"),
),
ElevatedButton(
onPressed: () => _onOperationPressed('*'),
child: const Text("×"),
),
ElevatedButton(
onPressed: () => _onOperationPressed('/'),
child: const Text("÷"),
),
],
),
const SizedBox(height: 20),
TextField(
controller: _resultController,
readOnly: true,
decoration: const InputDecoration(
labelText: "Result",
border: OutlineInputBorder(),
),
),
],
),
),
);
}
}
mini calculator app with four buttons (Add, Subtract, Multiply, Divide). Each button will call the same style of function with arguments.
August 30, 2025 in Flutter Programming