Flutter #29 Optimize Cubit using buildWhen & listenWhen
Автор: Ahmed saber
Загружено: 2025-08-27
Просмотров: 49
🔹 Introduction
Quick intro: “When working with Bloc, you might notice buildWhen and listenWhen. Many devs ignore them, but they’re actually key for improving performance and controlling rebuilds and reactions.”
🔹 What is buildWhen?
Used inside BlocBuilder.
Decides when the UI should rebuild.
Signature: (previous, current) → bool.
If returns true → UI rebuilds.
If returns false → UI doesn’t rebuild.
👉 Example usage:
Login screen → you don’t want the whole screen rebuilding every time a loading state changes.
With buildWhen, you can rebuild only the widget that depends on the specific state.
⚡ Benefit: Prevents unnecessary widget rebuilds → better performance.
🔹 What is listenWhen?
Used inside BlocListener.
Decides when side effects should trigger (like navigation, showing SnackBars).
Signature: (previous, current) → bool.
If returns true → listener runs.
If returns false → listener ignored.
👉 Example usage:
You don’t want a SnackBar to show every time the state changes, only when there’s an error state.
With listenWhen, you can trigger the SnackBar only for error states.
⚡ Benefit: Prevents unnecessary SnackBars, dialogs, or repeated navigations.
🔹 Why are they Important for Performance?
Without buildWhen, every single state change triggers a rebuild, even if the UI doesn’t need it.
Without listenWhen, every single state change could trigger SnackBars or navigations → messy UX.
By filtering, you:
Optimize rebuilds.
Avoid useless side effects.
Keep the app responsive and smooth.
🔹 Best Practices
Use buildWhen to rebuild only the widgets that depend on the state.
Use listenWhen for one-time actions like navigation or showing messages.
Don’t overuse them → keep logic simple.
🔹 Closing
Recap: “buildWhen = control UI rebuilds, listenWhen = control side effects. Both give you cleaner code and better performance.”
End with: “Don’t ignore them—use them smartly!”
Доступные форматы для скачивания:
Скачать видео mp4
-
Информация по загрузке: