What is StatelessWidget in Flutter?
A StatelessWidget is a widget that describes part of the user interface which does not depend on any mutable state. Once built, it never changes – it is immutable. StatelessWidgets are ideal for static content that does not need to update dynamically, such as text, icons, or images that remain the same.
Why Use StatelessWidget?
You should use StatelessWidget when your UI does not need to change after it is rendered. It is simpler, more performant (no state management overhead), and easier to test. Examples include: app logos, static text, decorative icons, and any UI that only depends on external parameters passed via the constructor.
Basic Structure of StatelessWidget
A StatelessWidget only needs to override the build method. It can accept parameters (like title) through its constructor, but those values are final – they cannot change after the widget is created.
Example: Greeting Widget
In this example, the GreetingWidget receives a name parameter. The displayed text will always be based on that initial value – it cannot be updated later without recreating the widget.
StatelessWidget vs StatefulWidget
- StatelessWidget: Immutable, no internal state, rebuilds only when the parent widget rebuilds. Ideal for static content.
- StatefulWidget: Mutable, can change over time, triggers rebuilds via
setState(). Ideal for interactive elements.
If your UI can be fully described by the constructor arguments, always prefer StatelessWidget.
When Not to Use StatelessWidget
Avoid StatelessWidget if your widget needs to:
- Respond to user input (like button taps) that changes its appearance.
- Handle animations or timers.
- Fetch data asynchronously and display the result.
- Depend on InheritedWidget updates.
In those cases, use StatefulWidget or other state management solutions.
Key Points
- StatelessWidgets are immutable and have no internal state.
- They are built once (or when the parent rebuilds).
- All member variables should be final.
- They are simpler and more performant than StatefulWidgets.
- Use them for static UI components.
Common Interview Questions
- What is the difference between StatelessWidget and StatefulWidget?
- Can StatelessWidget have mutable fields? Why not?
- When would you choose StatelessWidget over StatefulWidget?
- How does a StatelessWidget rebuild?
- Can you use
setState()in a StatelessWidget? - What are the performance implications of using StatelessWidget?