From 1128a35045281d3991b8a8157c0361e5f2d4687c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Danilo=20Spano=CC=80?= Date: Thu, 3 Oct 2024 17:22:17 +0200 Subject: [PATCH] feat: added addIf in bloc.dart in order to to allows conditional event addition --- packages/bloc/lib/src/bloc.dart | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/packages/bloc/lib/src/bloc.dart b/packages/bloc/lib/src/bloc.dart index 252f2227a0c..69ba6610376 100644 --- a/packages/bloc/lib/src/bloc.dart +++ b/packages/bloc/lib/src/bloc.dart @@ -101,6 +101,27 @@ abstract class Bloc extends BlocBase } } + /// Adds an [event] to the [Bloc] if the given [condition] is true. + /// + /// This method allows conditional event addition, which can be useful + /// for scenarios where events should only be added based on certain + /// conditions. + /// + /// ```dart + /// bloc.addIf(() => MyEvent(), someCondition); + /// ``` + /// + /// * [eventBuilder] - A function that returns the event to be added. + /// * [condition] - A boolean that determines whether the event should be added. + void addIf( + T Function() eventBuilder, + bool condition, + ) { + if (condition) { + add(eventBuilder()); + } + } + /// Called whenever an [event] is [add]ed to the [Bloc]. /// A great spot to add logging/analytics at the individual [Bloc] level. ///