[Flutter] TextEditingController 是否可以被放進 Bloc 裡

開始使用 Bloc 之後,想到了一個問題:如果都已經把狀態變數放進 Bloc 裡了,那 TextEditingController 這類的東西是否也可以移進去呢?

在還沒使用 Bloc 的時候,我們會把狀態變數跟 TextEditingController 放在 State 裡面。但在使用 Bloc 之後,我們會開始把變態變數放在 Bloc 裡。這時候就會遇到一個尷尬的問題。照理說,如果我們只需要處理狀態變數,使用了 Bloc 之後,我們就可以擺脫 StatefulWidget 跟 State。但如果我們同時又使用了 TextEditingController 這類的東西,那我們就沒辦法不使用 StatefulWidget 跟 State。

就是因為同時使用 Bloc + StatefulWidget + State 讓我不是很愉快,所以我就異想天開:那… 把 TextEditingController 也一起移進去不就好了嗎?這樣 StatefulWidget 跟 State 就不需要存在啦。於是我就去 google 看看,這個做法到底是不是一個 good practice,然後就找到了這篇。

[Question] What is the best practices to work with TextEditingControllers.

Bloc 的作者 Felix Angelov 親自解答了這個問題:

I would highly recommend against maintaining TextEditingController as part of the bloc. Blocs should ideally be platform-agnostic and have no dependency on Flutter. If you need to use TextEditingControllers I would recommend creating a StatefulWidget and maintaining them as part of the State class. Then you can interface with the control in response to state changes via BlocListener. If you don’t need TextEditingControllers then the solution provided by @Gene-Dana using onChanged with TextField works well and eliminates the need to have a StatefulWidget.

基本上,他不贊成把 TextEditingController 放進 Bloc 裡,因為這樣會導致 Bloc 對 Flutter 跟 Widgets 有相依性。其實我個人是蠻同意他的看法。從架構的角度來看,presentation (Widgets) 應該是比 business logic (Bloc) 更上層,所以應該是 presentation 對 business logic 有相依性,不應該反過來。如果 Bloc 對 Flutter 跟 Widgets 有相依性,這樣就很難對 Bloc 做測試,而且物件的重複使用性也會大打折扣。

好吧,為了 TextEditingController 只好繼續留著 StatefulWidget 跟 State,這樣做雖然還是讓我感到不舒服,但是從軟體架構的角度來看,我覺得這個作法是相當正確的。

發表留言

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料