Icon
Get In Touch
#flutter

Managing State

Managing state is key to building dynamic applications. Flutter provides several methods for managing state, from local state management using setState() to global state management solutions like Provider.

Using setState()

setState() is the simplest way to manage state within a widget.

1
import 'package:flutter/material.dart';
2
3
void main() {
4
runApp(const MainApp());
5
}
6
7
class MainApp extends StatelessWidget {
8
const MainApp({super.key});
9
10
@override
11
Widget build(BuildContext context) {
12
return MaterialApp(
13
debugShowCheckedModeBanner: false,
14
initialRoute: '/',
15
routes: {
16
'/': (context) => const Home(),
17
},
18
);
19
}
20
}
21
22
class Home extends StatefulWidget {
23
const Home({super.key});
24
25
@override
26
State<Home> createState() => _HomeState();
27
}
28
29
class _HomeState extends State<Home> {
30
int _counter = 0;
31
32
// Method to increment counter and update UI
33
void _incrementCounter() {
34
setState(() {
35
_counter++;
36
});
37
}
38
39
@override
40
Widget build(BuildContext context) {
41
return MaterialApp(
42
home: Scaffold(
43
appBar: AppBar(title: const Text('Manage State')),
44
body: Center(
45
child: Text(
46
'Counter: $_counter',
47
style: const TextStyle(fontSize: 30),
48
),
49
),
50
floatingActionButton: FloatingActionButton(
51
onPressed: _incrementCounter, // Increment counter on button press
52
child: const Icon(Icons.add),
53
),
54
));
55
}
56
}

Key Takeaways

- setState() updates the state of a widget and triggers a rebuild.
- For complex applications, use global state management solutions like Provider or Riverpod.

©2024 Codeblockz

Privacy Policy