StatefulWidget in Flutter

A StatefulWidget is a widget that maintains state across rebuilds. It’s used when the UI depends on changing data, such as:

  • Button presses
  • User input
  • Animations

Source Code​

				
					import 'package:flutter/material.dart';

class CounterWidget extends StatefulWidget {
  @override
  _CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int _count = 0;

  void _incrementCounter() {
    setState(() {
      _count++; // updates UI
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Stateful Widget Example')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('You pressed the button this many times:'),
            Text('$_count', style: TextStyle(fontSize: 24)),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _incrementCounter,
              child: Text('Increment'),
            ),
          ],
        ),
      ),
    );
  }
}

				
			

Ai Code Analizer

🧠  Key Concepts

ConceptDescription
StatefulWidgetThe immutable widget structure.
State<T>The mutable state class.
setState()Notifies Flutter to rebuild the widget with new data.
initState()Called once when the widget is inserted (for setup).
dispose()Called when the widget is removed (for cleanup).

📌  When to Use StatefulWidget

Use StatefulWidget when:

  • You want to update the UI dynamically.

  • You need to track user input, toggles, or animations.

  • You’re managing resources like controllers, focus nodes, timers, etc.