State and counter
- Flutter course
- Beginner
- Lesson 92/99
- 4 min
Define the counter variable with StatefulWidget.
State and counter variable
To hold the counter value, you use a StatefulWidget. In the State class you define a variable like int _count = 0;. This variable is private to State, and when changed with setState, the screen is rebuilt.
class CounterScreen extends StatefulWidget {
const CounterScreen({super.key});
@override
State<CounterScreen> createState() => _CounterScreenState();
}
class _CounterScreenState extends State<CounterScreen> {
int _count = 0;
}Updating with setState
To change the counter variable, setState is called. setState runs the code inside and rebuilds the widget. This way widgets such as Text('$_count') show the current value.
setState(() {
_count = _count + 1;
});Practice Increment counter and print
Write a StatefulWidget named SayacEkrani; define an int counter variable in its State (starting at 0). Write a function artir that increments the counter by 1 inside setState and prints the counter value. In main, create a State instance and call artir.
Starter code
import 'package:flutter/material.dart';
// SayacEkrani adinda StatefulWidget yaz
// State icine bir int sayaç degiskeni tanimla (baslangic 0)
// artir fonksiyonu: setState ile sayaci 1 artirsin ve sayaci yazdirsin
void main() {
// bir State olustur ve artir'i cagir
}Sample solution
import 'package:flutter/material.dart';
class SayacEkrani extends StatefulWidget {
const SayacEkrani({super.key});
@override
State<SayacEkrani> createState() => _SayacEkraniState();
}
class _SayacEkraniState extends State<SayacEkrani> {
int _sayac = 0;
void artir() {
setState(() {
_sayac = _sayac + 1;
});
print(_sayac);
}
}
void main() {
final state = _SayacEkraniState();
state.artir();
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What type is the variable holding the counter value?
- bool
- int Correct answer
- double
- String
Explanation: Since the counter value is an integer, it is kept as int; String, bool or double are not for this purpose.
2 Add the counter variable type
class _SayacEkraniState extends State<SayacEkrani> {
____ _sayac = 0;
}
class _SayacEkraniState extends State<SayacEkrani> {
int _sayac = 0;
}
Explanation: Since the counter value is an integer, the variable is defined as int; String, bool or double are not for this purpose.
3 State and counter parts
| Term | Meaning |
|---|---|
StatefulWidget |
Widget type holding state |
int |
Counter's type |
setState |
Rebuilds the screen |
_sayac |
Counter variable in State |