import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: CounterScreen(),
);
}
}
class CounterScreen extends StatefulWidget {
const CounterScreen({super.key});
@override
State<CounterScreen> createState() => _CounterScreenState();
}
class _CounterScreenState extends State<CounterScreen> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter += 1;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Counter App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Counter: $_counter', style: const TextStyle(fontSize: 24)),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _incrementCounter,
child: const Text('Increment'),
),
],
),
),
);
}
}
This app uses Flutter's built-in state management with a StatefulWidget. The counter value is stored in a variable _counter inside the state class. When the user taps the 'Increment' button, the _incrementCounter method runs. It calls setState() to tell Flutter the state changed. Flutter then rebuilds the UI to show the new counter value.
This approach keeps the UI code and the state (data) together in one place. It makes the app easy to understand and change. As apps grow bigger, managing state properly helps keep the code organized and prevents bugs. This is why state management is important for scaling apps.