Using BLOC in Flutter

Me after knowing that BLOC is easy, 19 hours of straight coding.

Why use Software Architecture/Patterns?

  • A basis for communication. What communication? Isn’t a software project only communicates using API/something like that? Yes, that’s it. But, discussing your software architecture before you create the project so the stakeholders understand your plans, and make them easier to understand the whole project and maybe helps you with funding if needed.
  • The earliest decision. As discussed before, before you create the project, you need to plan on the software architecture. This steps have a huge impact on your process on finishing the project, because choosing the most suitable architecture for your project makes your work easier.
  • Transferability of the model. Your architecture explains how your app will function, therefore having a tidy project may help you to reuse your code, maybe in your future project.

Structure of BLOC

Structure of BLOC Pattern

When to use BLOC

BLOC in Action!

class PantauLaporanBloc extends Bloc<PantauLaporanEvent, PantauLaporanState> {  PantauLaporanBloc() : super(PantauLaporanInitial([], false));  @override  Stream<PantauLaporanState> mapEventToState(PantauLaporanEvent   event,) async* {    List<PantauLaporan>? laporan;
try {
if (event is PantauLaporanSearchEvent) {
laporan = await PantauLaporan.getSearchResult(qSearch: event.query);
if (laporan!.isEmpty) {
yield PantauLaporanLoaded(laporan: laporan, hasReachedLimit: true);}
else {
yield PantauLaporanSearchState(
laporan: laporan,
hasReachedLimit: true,
);}
} else if (state is PantauLaporanInitial || state is PantauLaporanErrorLoaded || event is PantauLaporanRefreshEvent) {
laporan = await PantauLaporan.fetchLaporan(limit: 10);
yield (laporan!.length < 10) ? PantauLaporanLoaded(laporan: laporan, hasReachedLimit: true) : PantauLaporanLoaded(laporan: laporan, hasReachedLimit: false);
} else {
if (event is PantauLaporanEvent && state is PantauLaporanLoaded) {
PantauLaporanLoaded pantauLoaded = state as PantauLaporanLoaded;
if (state.laporan!.isEmpty) {
laporan = await PantauLaporan.fetchLaporan(limit: 10);
} else {
laporan = await PantauLaporan.fetchLaporan(
start: state.laporan!.last.reference, limit: 10);
}
yield (laporan!.isEmpty) ? pantauLoaded.copyWith(hasReachedLimit: true): PantauLaporanLoaded(laporan: pantauLoaded.laporan! + laporan, hasReachedLimit: false);}}} catch (e) {
yield PantauLaporanErrorLoaded([], false);
}
}
}

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ahmad Irfan Luthfi

Ahmad Irfan Luthfi

A Computer Science Student at Universitas Indonesia