
今年開始用Flutter開發新專案,Flutter是一套跨平台UI框架,但在開發過程中發現UI和Business Logic都混在一起寫,專案程式複雜,最終會導致未來維護上的問題,因此必須要有良好的架構設計才行。
本篇主要介紹 Flutter 的 Scoped-Model 架構
Scoped-Model
主要提供三種Component
- Model
- ScopedModel
- ScopedModelDescendant
Scoped-Model 實現原理採取了觀察者模式更新資料狀態,首先將data model放置parent widget,當想要更新資料時,透過data model的notifyListeners吿知parent widget,此時parent widget會通知所有descendant widget更新資料。
接下來我會說明並實作Scoped-Model架構:
加入 scoped_model lib
Model
model裡主要是business logic,如果要更新UI資料狀態,則透過notifyListeners機制,通知parent widget。
ScopedModel
如果想要傳遞model給descendant widget的話,就把定義好的model放置在parent widget的ScopedModel widget裡,之後等到notifyListeners被呼叫,parent widget會通知所有descendant widget更新UI資料狀態。
ScopedModelDescendant
descendant widget透過ScopedModelDescendant取得model,之後等待parent widget通知,就可以透過model取得最新的資料狀態更新UI。
以上是我實作Flutter Scoped-Model架構的歷程,這個架構讓UI和Business Logic分離,適用於小型專案,下一篇會介紹Flutter的 Fish-Redux 架構。
你可以在我的GitHub中,找到 Scoped-Model 的 Source Code。