Stateless vs Stateful Widgets in Flutter

when to use which?

December 05, 2024 · 3 mins read

Photo by Kelly Sikkema on Unsplash

In Flutter, stateless and stateful widgets are two fundamental types of widgets that define how a UI component behaves and interacts with the application state. It is important to differentiate between them as it is a concept used every time a developer tries to create a new widget

Stateless Widgets

A StatelessWidget is immutable, meaning it cannot change its state after being created. It is designed for widgets whose configuration and appearance remain constant throughout their lifecycle.

Characteristic properties of Stateless Widgets

  • Immutable: Once created, the widget cannot change.
  • Lightweight: Suitable for UI elements that do not need to update or interact dynamically.
  • Rebuild Mechanism: When the widget tree is rebuilt (e.g., due to a parent widget's state change), a new instance of the StatelessWidget is created.

Stateless widgets are typically used in Static text or images, icons and layout containers such as Row, Column or Containers. Example code given below:

                 
                  class MyStatelessWidget extends StatelessWidget {
final String title;
                  
MyStatelessWidget({required this.title});
                  
@override
Widget build(BuildContext context) {
    // Displays the title passed during creation
    return Text(title); 
    }
}
                  

In this example, MyStatelessWidget simply displays the title. You can't update the title after the widget is created.

Stateful Widgets

A StatefulWidget is dynamic and can change during its lifecycle based on user interaction, data updates, or other events. It consists of two classes:

  • StatefulWidget Class: Represents the widget itself.
  • State Class: Maintains the state of the widget and contains logic to update the UI.

Characteristic properties of Stateful Widgets

  • Dynamic State: Can update or modify the UI in response to events.
  • State Management: The State class stores properties that change and provides methods like setState to trigger updates.
  • Lifecycle Methods: Includes methods such as initState, setState, and dispose to manage the widget's lifecycle.

Stateful Widgets are typically used in Form inputs, Buttons with toggling states, Animations or timers or generally Widgets that respond to asynchronous data(Such as API calls).

                     
                      class MyStatefulWidget extends StatefulWidget {
  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State {
  int counter = 0;

  void incrementCounter() {
    setState(() {
      counter++; // Updates the counter and refreshes the UI
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text('Counter: $counter'),
        ElevatedButton(
          onPressed: incrementCounter,
          child: Text('Increment'),
        ),
      ],
    );
  }
}
                      
    

In this example, pressing the button updates the counter state, which triggers a UI rebuild to reflect the new value. This is also the default code when building a new project in flutter.

Choosing Between Stateless and Stateful Widgets

  • Use StatelessWidget when the widget does not need to change after being created.
  • Use StatefulWidget when the widget needs to respond to user input, animations or data updates dynamically.

Understanding the difference between Stateless and Stateless Widget is crucial as it affects the design of the whole application!