BLoC (Business Logic Component) in flutter is a writing style allows motion of intense state in outside of the view.
An event and a state ensure a structured timely management of the states.
This separation of concerns makes the testing and scaling significantly easier as the app progresses.
The principle of the BLoC architecture pattern implies the usage of streams to organize work with data in a Flutter application.
Separation of concerns: The technical effect that it keeps the business logic separate from the UI.
Unidirectional data flow: Ensures predictable state changes
Scalability: Leverages complex state in large applications.
Testability: This makes logic easy to unit test.Reusability: They can use business logics in a widget mechanism that has been used in common reusable widgets.
Event:
class Increment extends CounterEvent {}
State:
class CounterState { final int count; CounterState(this.count); }
BLoC:
class CounterBloc extends Bloc<CounterEvent, CounterState> {
CounterBloc() : super(CounterState(0));
Stream<CounterState> mapEventToState(CounterEvent event) async* {
if (event is Increment) yield CounterState(state.count + 1);
}
}
Screen:
class CounterPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final CounterBloc _bloc = BlocProvider.of<CounterBloc>(context);
return Scaffold(
appBar: AppBar(title: Text('Counter')),
body: Center(
child: BlocBuilder<CounterBloc, CounterState>(
builder: (context, state) {
return Text('Counter: ${state.counter}');
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => _bloc.add(Increment()),
child: Icon(Icons.add),
),
);
}
}
Apps constructed using BLoC pattern have a clear division between business logic and the UI, thus improving the ability of apps to be maintained and scaled.
Adhering state transition due to the absence of feedback loop, improves the usability of the app.
First one simplifies the debugging process because the code is less complicated in comparison to other forms of programming languages.
Allows unit testing, which means the quality of code is better.
Good for complicated scenarios, while aiming at extensibility.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Flutter Expertise.