Blog Details

image

20 Apr 2024

What is Flutter

Flutter is an open-source UI software development kit created by Google. It is used to develop applications for Android, iOS, Linux, Mac, Windows, Google Fuchsia, and the web from a single codebase. Flutter uses a programming language called Dart, which is also developed by Google.

One of the key features of Flutter is its ability to create beautiful and highly customized user interfaces. It uses a reactive framework, which means that when the state of the application changes, the UI automatically updates to reflect those changes. This makes it easier to build complex and interactive UIs.

Flutter also provides a rich set of pre-built widgets that help developers create stunning interfaces quickly. These widgets can be customized and combined to create unique designs, giving developers a high degree of flexibility and creativity.

In summary, Flutter is a powerful and flexible framework for building cross-platform applications with beautiful user interfaces, fast development cycles, and a rich set of features.

Why Flutter

  1. Single Codebase: Flutter allows you to write code once and deploy it on multiple platforms, including Android, iOS, web, and desktop. This reduces development time and effort compared to maintaining separate codebases for each platform.
  2. Fast Development: Flutter's hot reload feature allows you to see the effects of code changes in real-time, speeding up the development process. This rapid iteration cycle is particularly useful for prototyping and debugging.
  3. Beautiful UIs: Flutter provides a rich set of customizable widgets that make it easy to create visually appealing and interactive user interfaces. These widgets adhere to the design guidelines of each platform, ensuring a native look and feel.
  4. High Performance: Flutter's architecture is designed to deliver high performance, thanks to its use of the Dart language and a rendering engine that provides 60 frames per second (fps) performance. This results in smooth animations and responsive user interfaces.
  5. Community and Ecosystem: Flutter has a large and active community of developers, which means there are plenty of resources, libraries, and plugins available to help you build your app. The community also provides support and guidance, making it easier to learn and use Flutter.

Overall, Flutter is a powerful and versatile framework that offers a compelling solution for cross-platform app development, enabling developers to build high-quality apps with a great user experience.

System Requirements

  1. Operating System: Flutter supports development on Windows (7 or later), macOS (Sierra 10.12.6 or later), and Linux (64-bit).
  2. Disk Space: You'll need around 2-3 GB of disk space to install Flutter and its dependencies.
  3. Tools: Flutter requires Git for Windows and macOS. Linux users will need to install Git manually if it's not already installed.
  4. IDE: While you can use any text editor for Flutter development, it's recommended to use either Android Studio with the Flutter plugin, or Visual Studio Code with the Flutter and Dart plugins installed.
  5. Emulator or Physical Device: To run and test your Flutter apps, you'll need either an Android emulator (Android Studio includes one) or a physical Android/iOS device connected to your computer.

For more detailed system requirements, you can visit the official documentation at Flutter Official Docs.

Building a Calculator with Flutter

In this tutorial, we will learn the basics of Flutter by building a simple calculator app. Flutter is a powerful framework for building native cross-platform apps from a single codebase. By following along with this tutorial, you will get hands-on experience with Flutter's key concepts and features.

By the end of this tutorial, you will have a functional calculator app that you can run on Android, iOS, and the web. Let's get started!

Step 1: Creating a Flutter App

Open the Terminal / Command-prompt. Change Directory to your choice and run flutter create calculatorApp. Open the calculatorApp in VS Code or Android Studio.

Step 2: Coding Calculator App

In the lib folder, there is a main.dart file already present. And now in the same folder create a new file named buttons.dart. Starting with main.dart file. Create MyApp class and make it StatelessWidget. Add an array of buttons to be displayed. Set the background-color, text-color, functionality onTapped to the buttons. Write a function to calculate the Answers.

import 'package:flutter/material.dart';
import 'buttons.dart';
import 'package:math_expressions/math_expressions.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
	return MaterialApp(
	debugShowCheckedModeBanner: false,
	home: HomePage(),
	); // MaterialApp
}
}

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
var userInput = '';
var answer = '';

// Array of button
final List<String> buttons = [
	'C',
	'+/-',
	'%',
	'DEL',
	'7',
	'8',
	'9',
	'/',
	'4',
	'5',
	'6',
	'x',
	'1',
	'2',
	'3',
	'-',
	'0',
	'.',
	'=',
	'+',
];

@override
Widget build(BuildContext context) {
	return Scaffold(
	appBar: new AppBar(
		title: new Text("Calculator"),
	), //AppBar
	backgroundColor: Colors.white38,
	body: Column(
		children: <Widget>[
		Expanded(
			child: Container(
			child: Column(
				mainAxisAlignment: MainAxisAlignment.spaceEvenly,
				children: <Widget>[
					Container(
					padding: EdgeInsets.all(20),
					alignment: Alignment.centerRight,
					child: Text(
						userInput,
						style: TextStyle(fontSize: 18, color: Colors.white),
					),
					),
					Container(
					padding: EdgeInsets.all(15),
					alignment: Alignment.centerRight,
					child: Text(
						answer,
						style: TextStyle(
							fontSize: 30,
							color: Colors.white,
							fontWeight: FontWeight.bold),
					),
					)
				]),
			),
		),
		Expanded(
			flex: 3,
			child: Container(
			child: GridView.builder(
				itemCount: buttons.length,
				gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
					crossAxisCount: 4),
				itemBuilder: (BuildContext context, int index) {
					// Clear Button
					if (index == 0) {
					return MyButton(
						buttontapped: () {
						setState(() {
							userInput = '';
							answer = '0';
						});
						},
						buttonText: buttons[index],
						color: Colors.blue[50],
						textColor: Colors.black,
					);
					}

					// +/- button
					else if (index == 1) {
					return MyButton(
						buttonText: buttons[index],
						color: Colors.blue[50],
						textColor: Colors.black,
					);
					}
					// % Button
					else if (index == 2) {
					return MyButton(
						buttontapped: () {
						setState(() {
							userInput += buttons[index];
						});
						},
						buttonText: buttons[index],
						color: Colors.blue[50],
						textColor: Colors.black,
					);
					}
					// Delete Button
					else if (index == 3) {
					return MyButton(
						buttontapped: () {
						setState(() {
							userInput =
								userInput.substring(0, userInput.length - 1);
						});
						},
						buttonText: buttons[index],
						color: Colors.blue[50],
						textColor: Colors.black,
					);
					}
					// Equal_to Button
					else if (index == 18) {
					return MyButton(
						buttontapped: () {
						setState(() {
							equalPressed();
						});
						},
						buttonText: buttons[index],
						color: Colors.orange[700],
						textColor: Colors.white,
					);
					}

					// other buttons
					else {
					return MyButton(
						buttontapped: () {
						setState(() {
							userInput += buttons[index];
						});
						},
						buttonText: buttons[index],
						color: isOperator(buttons[index])
							? Colors.blueAccent
							: Colors.white,
						textColor: isOperator(buttons[index])
							? Colors.white
							: Colors.black,
					);
					}
				}), // GridView.builder
			),
		),
		],
	),
	);
}

bool isOperator(String x) {
	if (x == '/' || x == 'x' || x == '-' || x == '+' || x == '=') {
	return true;
	}
	return false;
}

// function to calculate the input operation
void equalPressed() {
	String finaluserinput = userInput;
	finaluserinput = userInput.replaceAll('x', '*');

	Parser p = Parser();
	Expression exp = p.parse(finaluserinput);
	ContextModel cm = ContextModel();
	double eval = exp.evaluate(EvaluationType.REAL, cm);
	answer = eval.toString();
}
}

Step 3: Building the buttons.dart

In buttons.dart, which is already imported in main.dart file, we are declaring variables that will be used throughout the program using a constructor. The color, text color, button text, and the functionality of the button on tapped will be implemented in main.dart file.

import 'package:flutter/material.dart';

// creating Stateless Widget for buttons
class MyButton extends StatelessWidget {

// declaring variables
final color;
final textColor;
final String buttonText;
final buttontapped;

//Constructor
MyButton({this.color, this.textColor, this.buttonText, this.buttontapped});

@override
Widget build(BuildContext context) {
	return GestureDetector(
	onTap: buttontapped,
	child: Padding(
		padding: const EdgeInsets.all(0.2),
		child: ClipRRect(
		// borderRadius: BorderRadius.circular(25),
		child: Container(
			color: color,
			child: Center(
			child: Text(
				buttonText,
				style: TextStyle(
				color: textColor,
				fontSize: 25,
				fontWeight: FontWeight.bold,
				),
			),
			),
		),
		),
	),
	);
}
}
Step 4: Adding dependencies in pubspec.yaml file

To make the process easier we are using math_expressions: ^2.0.0  package which is imported in main.dart file to handle all the calculations and run time error exceptions.

##Conclusion

Congratulations! You've completed the tutorial on building a simple calculator app with Flutter. Throughout this tutorial, you've learned the basics of Flutter, including setting up a development environment, creating a new project, designing a user interface, and writing logic for a basic app.

Flutter offers a powerful and flexible framework for building cross-platform apps with beautiful user interfaces. With its hot reload feature, rich set of widgets, and high performance, Flutter is a great choice for mobile app development.

We hope this tutorial has inspired you to explore more of what Flutter has to offer. Continue your Flutter journey by exploring advanced topics such as state management, navigation, and working with APIs. The Flutter documentation and community are great resources for learning and growing as a Flutter developer.

Thank you for joining us on this Flutter adventure. Happy coding!

Join my newsletter!

Enter your email to receive our latest newsletter.

Don't worry, we don't spam

Related Articles

image
20 Apr 2024

Flutter for beginners

Learn about the Flutter

image
30 Mar 2024

Create your first AI app in an hour

Exploring the Differences and Advantages

image
29 Mar 2024

Simplifying Flutter Navigation - Understanding GoRouter

Streamlining Declarative Routing for Flutter Apps