In this tutorial, we’ll explore the concept of managing state with Stateful Widgets in Flutter. The state is a crucial concept that enables you to create dynamic and interactive apps.
By the end of this tutorial, you will learn:
Prerequisites:
You should have a basic understanding of Dart and Flutter. It would also be beneficial if you have some experience with Stateless Widgets.
Stateful Widgets are dynamic. The UI changes over time due to user interaction or real-time data updates. In Flutter, Stateful Widgets have mutable state.
Creating a Stateful Widget:
A Stateful Widget in Flutter is created in two steps:
- Create a class that extends StatefulWidget
- Create a separate class that extends the State class
Managing State:
The state of a widget can change over time. The state could be user input or data fetched from a database.
Here is an example of a simple counter app implemented with a Stateful Widget.
// importing Flutter package
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
// Creating a Stateful Widget
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
// Creating the State
class _MyAppState extends State<MyApp> {
int _counter = 0; // Declare a variable for the counter
void _incrementCounter() {
setState(() {
_counter++; // Increment the counter when the button is pressed
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Counter App'),
),
body: Center(
child: Text(
'Button pressed $_counter times',
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
child: Icon(Icons.add),
),
),
);
}
}
In this code:
- We declare a variable _counter
to hold the state of the counter.
- We define a function _incrementCounter
to increment the counter. We use the setState
function to tell Flutter that the state has changed and the UI needs to be updated.
- In the build
function, we display the counter value in a Text widget.
The expected output will be a Flutter app with an appBar titled 'Counter App', and a floating action button. When the button is pressed, the counter increments and the updated value is displayed on the screen.
In this tutorial, we learned about Stateful Widgets in Flutter and how to manage their state. We also looked at a practical code example.
Your next steps could be to learn about more complex state management techniques, like using the Provider package or the Bloc library.
Here are some resources to deepen your understanding:
- Flutter's official documentation on Stateful Widgets
- A video tutorial on StatefulWidget
setState
to indicate that the state has changed and the UI needs to be rebuilt.