CodeBlanks Logo Icon CodeBlanks

createState and State

Learn how createState produces the State object.

createState

The createState method of a StatefulWidget produces a State object when the widget is placed on screen. This State holds the widget's changing data for its entire lifetime. Flutter calls createState once each time the widget is inserted into the tree; the same State lives until the widget is removed.

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

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

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

  @override
  Widget build(BuildContext context) {
    return Text('$deger');
  }
}

State and setState

The State class holds the widget's variable data and build method. To change data you call setState; it marks the State as dirty and makes Flutter call build again. If you update a variable without setState, the screen does not refresh.

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

  void artir() {
    setState(() {
      deger = deger + 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text('$deger');
  }
}

Practice Print createState info

In main, print two lines with print: createState uretir and state yasar.

Starter code

main.dart
void main() {
  // iki satır yazdır:
  // createState uretir
  // state yasar

}

Sample solution

main.dart
void main() {
  print('createState uretir');
  print('state yasar');
}

Expected output

createState uretir
state yasar

Questions and answers

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

1 When is createState called?

  • Once when the widget is first inserted into the tree Correct answer
  • Every time the widget rebuilds
  • Every time setState is called
  • When the app closes

Explanation: createState is called once when the widget is first inserted into the tree and produces the State object; it does not repeat on every build.

2 createState method

Question
@override
State&lt;Sayac&gt; ____() =&gt; _SayacState();
Answer
@override
State&lt;Sayac&gt; createState() =&gt; _SayacState();

Explanation: The createState method produces the State object for a StatefulWidget.

3 createState and State

Term Meaning
createState Method that produces the State object
State nesnesi Holds variable data
setState Marks State as dirty
_SayacState Implementer of the State class

All lessons in Beginner