CodeBlanks Logo Icon CodeBlanks

What is StatefulWidget?

Learn that StatefulWidget is used for UI that changes over time.

What is StatefulWidget?

A StatefulWidget is used for interfaces that can change over time. Unlike StatelessWidget, it stores variable data inside a State object. Views that update with user interaction — counters, checkboxes, forms — are written with StatefulWidget. The widget itself stays immutable, but the State object is mutable.

class Sayac extends StatefulWidget {
  const Sayac({super.key});

  @override
  State<Sayac> createState() => _SayacState();
}

class _SayacState extends State<Sayac> {
  int deger = 0;
  // ...
}

Widget and State

A StatefulWidget consists of two parts: an immutable Widget and a mutable State. The Widget stays the same across rebuilds; the State holds variables updated via setState. Even if the widget is replaced, Flutter preserves the State to prevent data loss.

// Widget: immutable
class Sayac extends StatefulWidget {
  const Sayac({super.key});
  @override
  State<Sayac> createState() => _SayacState();
}

// State: mutable
class _SayacState extends State<Sayac> {
  int deger = 0;  // can change
}

Practice Print stateful info

In main, print two lines with print: stateful degisir and state mutable.

Starter code

main.dart
void main() {
  // iki satır yazdır:
  // stateful degisir
  // state mutable

}

Sample solution

main.dart
void main() {
  print('stateful degisir');
  print('state mutable');
}

Expected output

stateful degisir
state mutable

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is StatefulWidget used?

  • Only when displaying text
  • When no data will ever come from a server
  • When the view never changes
  • When there is data that changes with user interaction Correct answer

Explanation: StatefulWidget is used for data that changes with user interaction (counter, checkbox, form); StatelessWidget is for static views.

2 State class definition

Question
class _SayacState extends ____&lt;Sayac&gt; {
  int deger = 0;
}
Answer
class _SayacState extends State&lt;Sayac&gt; {
  int deger = 0;
}

Explanation: The State class holds the widget's variable data and build method.

3 StatefulWidget concepts

Term Meaning
StatefulWidget For UIs that change over time
mutable State object can change
State Object holding variable data
immutable Widget Stays the same across rebuilds

All lessons in Beginner