Google News
logo
Flutter - Interview Questions
What is a StatefulWidget and how is it used in Flutter?
In Flutter, a `StatefulWidget` is a widget that has mutable state. The state of a `StatefulWidget` can change during the lifetime of the widget, based on user interactions, changes in external data sources, or other factors.

`StatefulWidget`s are used to represent UI elements that can change over time. Examples include text fields, sliders, progress indicators, and other UI elements that can be updated based on user input or changes in the underlying data.

A `StatefulWidget` is implemented by creating a new class that extends the `StatefulWidget` class and overriding two methods: `createState()` and `build()`. The `createState()` method returns a new `State` object that will be used to manage the widget's state, while the `build()` method defines the widget's appearance.

Here's an example of a simple `StatefulWidget` that displays a counter and increments it when a button is pressed:
import 'package:flutter/material.dart';

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

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

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Counter: $_counter'),
        ElevatedButton(
          onPressed: _incrementCounter,
          child: Text('Increment'),
        ),
      ],
    );
  }
}​
In this example, we define a new `StatefulWidget` called `CounterWidget`. The `createState()` method returns a new instance of the `_CounterWidgetState` class, which extends the `State` class and defines the mutable state for the widget.

The `_CounterWidgetState` class has a private field `_counter` that holds the current count, and a private method `_incrementCounter()` that updates the count and calls `setState()` to signal that the widget's state has changed.

In the `build()` method, we create a `Column` widget that displays the current count and an `ElevatedButton` widget that calls `_incrementCounter()` when it is pressed.

`StatefulWidget`s are useful for creating UI elements that can change over time. However, since they have mutable state, they can be more complex to reason about and optimize for performance compared to `StatelessWidget`s. It's important to use `StatefulWidget`s only when necessary and to manage their state carefully to ensure that the UI remains responsive and efficient.
Advertisement