Create Counter App
Create Counter App In Flutter
In this section, you will learn how to create a simple counter app in flutter. This app will help you to understand the basic concepts of flutter. So let’s start.
Step 1: Create Flutter Project
To create a flutter project, open the command prompt and run the following command:
flutter create counter_app
Step 2: Define the Main Entry Point
Open main.dart file and define the main entry point of the app.
import 'package:flutter/material.dart';
void main() {
runApp(const CounterApp());
}
Step 3: Create the CounterApp Widget
Now, you need to create the CounterApp widget.
class CounterApp extends StatelessWidget {
const CounterApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Counter App',
home: CounterScreen(),
);
}
}
Step 4: Create the CounterScreen Widget
Now, create the CounterScreen widget.
class CounterScreen extends StatefulWidget {
@override
_CounterScreenState createState() => _CounterScreenState();
}
class _CounterScreenState extends State<CounterScreen> {
// Define the counter variable
int _counter = 0;
// Define the increment and decrement counter methods
void _incrementCounter() {
setState(() {
_counter++;
});
}
void _decrementCounter() {
setState(() {
_counter--;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter App')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'$_counter',
style: const TextStyle(fontSize: 72),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children:[
FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Add',
child: const Icon(Icons.add),
),
FloatingActionButton(
onPressed: _decrementCounter,
tooltip: 'Subtract',
child: const Icon(Icons.remove),
),
],
),
],
),
),
);
}
}
Step 5: Run the App
Now, you can run the app using the following command:
flutter run