StatelessWidget vs StatefulWidget in Flutter: Differences & Best Practices
Master Flutter widget trees and choose the right widget class to keep your mobile rendering pipeline fast and efficient.
Concepts & Theory
In Flutter, everything is a Widget. UIs are declared as reactive, immutable element trees.
A `StatelessWidget` is immutable: its fields are final and its build method depends strictly on incoming configuration.
A `StatefulWidget` associates with a mutable `State` instance whose internal fields trigger re-renders via `setState()`.
Code Example
Run in Playgroundimport 'package:flutter/material.dart';
// 1. StatelessWidget : UI statique
class BadgeCertification extends StatelessWidget {
final String titre;
const BadgeCertification({super.key, required this.titre});
@override
Widget build(BuildContext context) {
return Chip(
label: Text(titre),
backgroundColor: Colors.cyan.shade900,
);
}
}
// 2. StatefulWidget : UI interactive avec état
class BoutonFavori extends StatefulWidget {
const BoutonFavori({super.key});
@override
State<BoutonFavori> createState() => _BoutonFavoriState();
}
class _BoutonFavoriState extends State<BoutonFavori> {
bool _estFavori = false;
void _basculer() {
setState(() {
_estFavori = !_estFavori;
});
}
@override
Widget build(BuildContext context) {
return IconButton(
icon: Icon(_estFavori ? Icons.star : Icons.star_border),
color: Colors.amber,
onPressed: _basculer,
);
}
}Common Pitfalls & Mistakes
✗ Mutating internal state without calling setState()
_isFavorite = true;setState(() {
_isFavorite = true;
});Flutter requires `setState()` to mark the element dirty and trigger an engine repaint pass.
Frequently Asked Questions
When should I default to StatelessWidget?▾
Default to `StatelessWidget` for its clean performance profile. Only adopt `StatefulWidget` for strictly localized, transient UI states.
Master Dart / Flutter with interactive exercises
Complete hands-on code challenges in your browser with real-time feedback and progressive hints.
