widget encapsulation vs. inheritance?

1,147 views
Skip to first unread message

Rick Spencer

unread,
Dec 9, 2018, 11:41:11 AM12/9/18
to flutt...@googlegroups.com
Hello all,

I am interested in the thoughts of other programmers regarding the
best way to extend the capabilities of Widgets in the Flutter library.

I have found that for every custom widget I have made, I have ended up
creating a StatefulWidget or StatelessWidget and encapsulating the
widget that I want to extend in the build method. For example:
https://github.com/rapido-mobile/rapido-flutter/blob/master/lib/src/document_actions_button.dart

I extend StatelessWidget and return a PopupMenuButton in the build
function, rather than extending PopupMenuButton directly.

Are there cases where inheriting directly from the widget is
preferred? Are there heuristics that others use to decide when to
choose either method? Am I missing something?

Thanks.

Cheers, Rick

Adam Barth

unread,
Dec 9, 2018, 11:54:13 AM12/9/18
to richard.ling...@gmail.com, Flutter Dev
On Sun, Dec 9, 2018 at 8:41 AM Rick Spencer <richard.ling...@gmail.com> wrote:
I am interested in the thoughts of other programmers regarding the
best way to extend the capabilities of Widgets in the Flutter library.

I have found that for every custom widget I have made, I have ended up
creating a StatefulWidget or StatelessWidget and encapsulating the
widget that I want to extend in the build method. For example:
https://github.com/rapido-mobile/rapido-flutter/blob/master/lib/src/document_actions_button.dart

I extend StatelessWidget and return a PopupMenuButton in the build
function, rather than extending PopupMenuButton directly.

Yes!

Are there cases where inheriting directly from the widget is
preferred? Are there heuristics that others use to decide when to
choose either method? Am I missing something?

Generally, we've found that composition (the pattern you've described above) works better than inheritance.  There are a few cases where we use inheritance in the framework, but they're pretty rare.  Composition is just more flexible.

Adam

Rick Spencer

unread,
Dec 9, 2018, 1:01:19 PM12/9/18
to aba...@google.com, flutt...@googlegroups.com
Adam,

Thank you for your response.

In summary:
1. "Composition" is the preferred term of "encapsulation."
2. The heuristic is "composition unless there is a strong reason to inherit."

FWIW, I don't find composition only to be more flexible, as you say,
but I find the resulting code so much easier to read and modify. Much
more developer friendly. The whole experience of programming with
Flutter reminds me of a lot of the really enjoyable things about
programming with QML, obscure though QML may be.

Cheers, Rick
Reply all
Reply to author
Forward
0 new messages