Flutter Architecture — BLoC

Dave Chao
2 min readDec 31, 2019

這次看到Google團隊針對Flutter推薦了BLoC架構,所以特別去研究一下。

本篇主要介紹 Flutter 的 BLoC 架構

BLoC

BLoC的全名是Business Logic Component,採取Reactive Programming模式更新資料狀態,在Flutter中,我們稱它為Stream。透過Stream機制,監聽State,取得最新的資料狀態,更新UI。

BLoC的Data Flow如下:

因為BLoC是一種Design Pattern,因此可自行用Stream實作它,或者使用別人寫好的BLoC lib,本篇是使用flutter_bloc這套lib實作。下方是flutter_bloc lib提供的Data Flow:

主要的Component如下:

  1. Provider
  2. BlocBuilder
  3. BlocListener

Provider是Dependency Injection widget,主要提供兩種DI,分別是RepositoryProvider和BlocProvider,RepositoryProvider負責處理資料注入的事情,BlocProvider則負責處理Business Logic注入的事情。

BlocBuilder主要建立BLoC,以及取得最新的State,更新UI。

BlocListener主要觀察BLoC裡的State,它有個特性,就是每次State更改時,只被呼叫一次的限制,通常應用在Navigation、顯示SnackBar和顯示Dialog等。

接下來我會說明並實作BLoC架構:

加入 bloc 相關 lib

Bloc

首先定義Event和State,Event代表你想要做的事,而State代表回傳的結果。再來就是實作Bloc,也就是我們的Business Logic,在Bloc中有兩個重要的方法,分別是initialState和mapEventToState,initialState負責的工作是一開始顯示的State,mapEventToState負責的工作是接收UI dispatch的event,然後依據不同的event做不同的business logic,最後將state回傳給view。

View

因為flutter_bloc lib有提供DI機制,所以我使用了Provider,透過RepositoryProvider將ApiProvider注入Bloc中,這樣就可以從Bloc裡呼叫API,另外再透過BlocProvider將Bloc注入到View中,這樣就可以從view裡觸發Event,最後透過BlocBuilder取得最新的State,更新UI。

以上是我實作Flutter BLoC架構的歷程,BLoC徹底將UI和Business Logic劃分開來,再透過DI機制,解決了Flutter物件之間耦合高的問題。如果想要深入探討BLoC,參考連結:https://bloclibrary.dev

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Dave Chao
Dave Chao

No responses yet

Write a response