We have seen stateless widget by now.

Stateful widget is used to show changing data in the app.

Write ‘stful’ for code snippet.

We can convert stateless to stateful widget by refactoring it ( ctrl + . )

Stateless:

class Test extends StatelessWidget {
  const Test({super.key});

  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}

Converted to Stateful by refactoring:

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

  @override
  State<Test> createState() => _TestState();
}

class _TestState extends State<Test> {
  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}

See that, the actual class remains same, we now just rebuild the widget every time the data changes. We move the build function.

Now we can define our widget inside the 2nd class, _TestState( ) and also define our data.

Full code:

import 'package:flutter/material.dart';

//ignore_for_file: prefer_const_constructors

void main() => runApp(
      MaterialApp(
        home: Test(),
        theme: ThemeData.dark(),
      ),
    );

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

  @override
  State<Test> createState() => _TestState();
}

class _TestState extends State<Test> {
  int count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      body: Center(
        child: Text('You have pushed the button $count times.'),
      ),

      floatingActionButton: FloatingActionButton(
        onPressed: () {
          count++;
        },
        child: Icon(Icons.add),
    ),

    );
  }
}

Here we can define variable (e.g. count=0 here). Now we show the text inside body with the count changing. But see the part in floatingActionButton

        onPressed: () {
          count++;
        },

Although the count changes, but that’s not shown in the app, the text in body gets updated only when we do a hot reload.

To keep updating the text constantly we need a function setState( ), and inside this we need to write count++;

      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            count++;
          });
        },
        child: Icon(Icons.add),
    ),

That is, whenever the button is presses, a new state is set with count++