Design Converter
Education
Last updated on Aug 5, 2024
Last updated on Jul 3, 2024
Welcome to the Flutter tutorial!
Today, we're going to dive into the exciting world of Flutter development by creating a simple yet functional calculator app.
In this guide, we will walk you through the creation of a Flutter simple calculator. This project aims to familiarize you with the fundamental concepts of Flutter while building a simple calculator. This calculator app will allow users to perform basic arithmetic operations such as addition, subtraction, multiplication, and division.
Key features of the basic calculator app include:
A clean and user-friendly interface.
Responsive design that works on various
To begin developing a basic calculator app using Flutter, you first need to install the Flutter SDK. Here’s a step-by-step guide to help you through the process:
Download the Flutter SDK:
Extract the Downloaded File:
C:\src\flutter
.Update the System Path:
Add the Flutter bin directory to your system PATH. This allows you to run Flutter commands from any terminal window.
On Windows:
Search for "Environment Variables" in the Start Menu.
Select "Edit the system environment variables".
Click on "Environment Variables".
Under "System variables", find the PATH variable and click "Edit".
Add the full path to the flutter/bin directory.
On macOS and Linux:
◦ Open your .bashrc, .bash_profile, or .zshrc file and add the following line:
1export PATH="$PATH:`pwd`/flutter/bin"
Run Flutter Doctor:
1flutter doctor
To make your Flutter development experience smoother, it's recommended to use an Integrated Development Environment (IDE). The two most popular IDEs for Flutter development are Android Studio and Visual Studio Code.
Install Android Studio:
Set Up Flutter Plugin:
Open Android Studio.
Go to File > Settings (or Android Studio > Preferences on macOS).
Select Plugins and search for Flutter and Dart plugins. Install both plugins and restart Android Studio.
Configure Android Studio:
Open Android Studio and go to Configure > SDK Manager.
Ensure the latest Android SDK and Virtual Device are installed.
Configure the AVD (Android Virtual Device) for testing your Flutter apps.
Install Visual Studio Code:
Set Up Flutter Extension:
Open Visual Studio Code.
Go to the Extensions view by clicking on the Extensions icon in the Activity Bar or pressing Ctrl+Shift+X.
Search for Flutter and install the Flutter extension by Dart Code. This will also install the Dart extension.
Configure Visual Studio Code:
Open the Command Palette by pressing Ctrl+Shift+P and run the Flutter: New Project command to create a new Flutter project.
Use the integrated terminal in Visual Studio Code to run and debug your Flutter apps.
By following these steps, you will have a fully functional development environment set up for building your basic calculator app using Flutter.
To start creating your basic calculator app, you need to initialize a new Flutter project. This is done using the Flutter command-line tools.
Open a Terminal or Command Prompt:
Run the Flutter Create Command:
Use the following command to create a new Flutter project:
1flutter create calculator_app
Replace calculator_app with your desired project name. This command will generate a new Flutter project with the necessary files and folders.
Once the project is created, you will see a directory structure similar to this:
lib: This directory contains the main code for your Flutter app. The main.dart file is where the app execution starts.
android: This directory contains the Android-specific configuration and code.
ios: This directory contains the iOS-specific configuration and code.
test: This directory contains the unit tests for your Flutter app.
pubspec.yaml: This file manages the project's dependencies and other configurations.
Here is a brief overview of the key files and directories:
lib/main.dart: The entry point for your Flutter application.
pubspec.yaml: The file where you define the dependencies for your project.
android: Contains Android-specific files, including the AndroidManifest.xml.
ios: Contains iOS-specific files, including the Info.plist.
After initializing the new Flutter project, you can run the default app to ensure everything is set up correctly.
1cd calculator_app
Open a new terminal window and run the following command to verify your installation:
1flutter doctor
This command checks your environment and displays a report of the status of your Flutter installation.
The default Flutter app contains a simple counter application. Here’s an overview of the main.dart file:
1import 'package:flutter/material.dart'; 2 3void main() { 4 runApp(const MyApp()); 5} 6 7class MyApp extends StatelessWidget { 8 const MyApp({Key? key}) : super(key: key); 9 10 11 Widget build(BuildContext context) { 12 return MaterialApp( 13 title: 'Flutter Demo', 14 theme: ThemeData( 15 primarySwatch: Colors.blue, 16 ), 17 home: const MyHomePage(title: 'Flutter Demo Home Page'), 18 ); 19 } 20} 21 22class MyHomePage extends StatefulWidget { 23 const MyHomePage({Key? key, required this.title}) : super(key: key); 24 25 final String title; 26 27 28 State<MyHomePage> createState() => _MyHomePageState(); 29} 30 31class _MyHomePageState extends State<MyHomePage> { 32 int _counter = 0; 33 34 void _incrementCounter() { 35 setState(() { 36 _counter++; 37 }); 38 } 39 40 41 Widget build(BuildContext context) { 42 return Scaffold( 43 appBar: AppBar( 44 title: Text(widget.title), 45 ), 46 body: Center( 47 child: Column( 48 mainAxisAlignment: MainAxisAlignment.center, 49 children: <Widget>[ 50 const Text( 51 'You have pushed the button this many times:', 52 ), 53 Text( 54 '$_counter', 55 style: Theme.of(context).textTheme.headlineMedium, 56 ), 57 ], 58 ), 59 ), 60 floatingActionButton: FloatingActionButton( 61 onPressed: _incrementCounter, 62 tooltip: 'Increment', 63 child: const Icon(Icons.add), 64 ), 65 ); 66 } 67}
void main(): The entry point of the application.
MyApp: A stateless widget that sets up the app’s theme and home screen.
MyHomePage: A stateful widget that manages the app’s state and displays a counter.
By understanding this basic structure, you can start modifying it to develop your basic calculator app using Flutter. This will involve creating additional widgets and implementing the logic for the calculator operations.
Developing an intuitive and visually appealing user interface (UI) is critical for your basic calculator software. Here’s a step-by-step guide on planning the UI layout and adding the necessary widgets for buttons and displays.
For a basic calculator app, the UI should include:
Display Area: To show the input numbers and results.
Buttons: For digits (0-9), operations (addition, subtraction, multiplication, division), and functionalities like clear (C) and equals (=).
The layout can be structured using a combination of Column and Row widgets to arrange the buttons in a grid format.
Display Area:
Buttons:
Use RaisedButton or ElevatedButton widgets for the calculator buttons.
Arrange the buttons using Row and Column widgets within a GridView or Table widget for a structured layout.
Here’s a basic layout plan:
A Column widget as the main container.
A Container at the top for the display area.
Multiple Row widgets within a GridView for the buttons.
Now, let's write the code for the main layout of the simple calculator app using Flutter widgets.
1import 'package:flutter/material.dart'; 2 3void main() { 4 runApp(const CalculatorApp()); 5} 6 7class CalculatorApp extends StatelessWidget { 8 const CalculatorApp({Key? key}) : super(key: key); 9 10 11 Widget build(BuildContext context) { 12 return MaterialApp( 13 debugShowCheckedModeBanner: false, 14 home: Scaffold( 15 appBar: AppBar(title: const Text('Simple Calculator')), 16 body: const Calculator(), 17 ), 18 ); 19 } 20} 21 22class Calculator extends StatefulWidget { 23 const Calculator({Key? key}) : super(key: key); 24 25 26 _CalculatorState createState() => _CalculatorState(); 27} 28 29class _CalculatorState extends State<Calculator> { 30 String _output = "0"; 31 32 Widget buildButton(String buttonText) { 33 return Expanded( 34 child: OutlinedButton( 35 onPressed: () { 36 // Handle button press 37 }, 38 child: Text( 39 buttonText, 40 style: const TextStyle(fontSize: 20.0), 41 ), 42 ), 43 ); 44 } 45 46 47 Widget build(BuildContext context) { 48 return Column( 49 children: <Widget>[ 50 Container( 51 alignment: Alignment.centerRight, 52 padding: const EdgeInsets.symmetric( 53 vertical: 24.0, 54 horizontal: 12.0, 55 ), 56 child: Text( 57 _output, 58 style: const TextStyle( 59 fontSize: 48.0, 60 fontWeight: FontWeight.bold, 61 ), 62 ), 63 ), 64 const Expanded(child: Divider()), 65 Column( 66 children: [ 67 Row( 68 children: [ 69 buildButton("7"), 70 buildButton("8"), 71 buildButton("9"), 72 buildButton("/"), 73 ], 74 ), 75 Row( 76 children: [ 77 buildButton("4"), 78 buildButton("5"), 79 buildButton("6"), 80 buildButton("*"), 81 ], 82 ), 83 Row( 84 children: [ 85 buildButton("1"), 86 buildButton("2"), 87 buildButton("3"), 88 buildButton("-"), 89 ], 90 ), 91 Row( 92 children: [ 93 buildButton("."), 94 buildButton("0"), 95 buildButton("00"), 96 buildButton("+"), 97 ], 98 ), 99 Row( 100 children: [ 101 buildButton("C"), 102 buildButton("="), 103 ], 104 ), 105 ], 106 ) 107 ], 108 ); 109 } 110}
Column Widget: The main layout container that holds the display and buttons.
Container Widget: Used for the display area to show the input and results.
Row Widget: Used to arrange buttons in horizontal lines.
OutlinedButton Widget: Used for the calculator buttons to perform actions when pressed.
This basic structure provides a foundation to build upon by adding the necessary functionality to handle user interactions and perform calculations. By organizing your layout using Column and Row widgets, and styling your buttons with OutlinedButton widgets, you can create a visually appealing and functional simple calculator app using Flutter.
To make your calculator app functional, you must handle user input effectively. This involves capturing button presses and updating the display accordingly.
You need to modify the buildButton method to capture button presses and update the internal state of the calculator. Here’s how to handle button presses:
Update the _CalculatorState class to handle different types of button presses such as numbers, operators, and special buttons like "C" (clear) and "=" (equals).
1import 'package:flutter/material.dart'; 2 3void main() { 4 runApp(const CalculatorApp()); 5} 6 7// Define the CalculatorApp class 8class CalculatorApp extends StatelessWidget { 9 const CalculatorApp({Key? key}) : super(key: key); 10 11 12 Widget build(BuildContext context) { 13 return MaterialApp( 14 title: 'Flutter Demo', 15 theme: ThemeData( 16 primarySwatch: Colors.blue, 17 visualDensity: VisualDensity.adaptivePlatformDensity, 18 ), 19 home: const Calculator(), 20 ); 21 } 22} 23 24// Define the Calculator StatefulWidget 25class Calculator extends StatefulWidget { 26 const Calculator({Key? key}) : super(key: key); 27 28 29 _CalculatorState createState() => _CalculatorState(); 30} 31 32// The existing _CalculatorState class 33class _CalculatorState extends State<Calculator> { 34 String _output = "0"; 35 String _result = "0"; 36 String _operation = ""; 37 double num1 = 0.0; 38 double num2 = 0.0; 39 40 void buttonPressed(String buttonText) { 41 if (buttonText == "C") { 42 _output = "0"; 43 _result = "0"; 44 num1 = 0.0; 45 num2 = 0.0; 46 _operation = ""; 47 } else if (buttonText == "+" || buttonText == "-" || buttonText == "/" || buttonText == "*") { 48 num1 = double.tryParse(_output) ?? 0.0; 49 _operation = buttonText; 50 _output = "0"; 51 } else if (buttonText == "=") { 52 num2 = double.tryParse(_output) ?? 0.0; 53 switch (_operation) { 54 case "+": 55 _result = (num1 + num2).toString(); 56 break; 57 case "-": 58 _result = (num1 - num2).toString(); 59 break; 60 case "*": 61 _result = (num1 * num2).toString(); 62 break; 63 case "/": 64 _result = num2 != 0 ? (num1 / num2).toString() : "Error"; 65 break; 66 default: 67 break; 68 } 69 _output = _result; 70 _operation = ""; 71 num1 = 0.0; 72 num2 = 0.0; 73 } else { 74 // Check if _output is "0" and the button pressed is a number 75 if (_output == "0" && buttonText != ".") { 76 _output = buttonText; 77 } else { 78 _output += buttonText; 79 } 80 } 81 setState(() { 82 _output = _output; 83 }); 84} 85 86 87 Widget build(BuildContext context) { 88 return Scaffold( 89 appBar: AppBar( 90 title: Text("Calculator"), 91 ), 92 body: Column( 93 children: <Widget>[ 94 Container( 95 alignment: Alignment.centerRight, 96 padding: const EdgeInsets.symmetric(vertical: 24.0, horizontal: 12.0), 97 child: Text( 98 _output, 99 style: const TextStyle(fontSize: 48.0, fontWeight: FontWeight.bold), 100 ), 101 ), 102 const Expanded(child: Divider()), 103 ..._buildCalculatorButtons(), 104 ], 105 ), 106 ); 107 } 108 109 List<Widget> _buildCalculatorButtons() { 110 // This function builds buttons in a more scalable way 111 List<List<String>> buttons = [ 112 ["7", "8", "9", "/"], 113 ["4", "5", "6", "*"], 114 ["1", "2", "3", "-"], 115 [".", "0", "00", "+"], 116 ["C", "="] 117 ]; 118 return buttons.map((List<String> row) { 119 return Row( 120 children: row.map((String buttonText) { 121 return buildButton(buttonText); 122 }).toList(), 123 ); 124 }).toList(); 125 } 126 127 Widget buildButton(String buttonText) { 128 return Expanded( 129 child: OutlinedButton( 130 onPressed: () => buttonPressed(buttonText), 131 child: Text( 132 buttonText, 133 style: const TextStyle(fontSize: 20.0), 134 ), 135 ), 136 ); 137 } 138}
We have successfully created a Flutter simple calculator in this step-by-step guide. We started by setting up the Flutter development environment, including installing the Flutter SDK and configuring an IDE. We then initialized a new Flutter project, explored its default structure, and built the calculator UI using various Flutter widgets.
Finally, we implemented the core logic for handling user input and performing arithmetic operations. With this foundation, you can now explore more advanced features and enhancements to expand the functionality of your calculator app, delving deeper into the exciting world of Flutter development.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.