Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to have a lot of nested widgets with Flutter?

I have a strong background with Android development and I'm now trying to develop my first app with Flutter.

It is a common knowledge in the Android community that it's bad have too many nested views. It's bad for performance. (That's one of the reason why ConstraintLayout exists)

However, in a lot of Flutter tutorials I see that people nest a lot of widgets.

Could somebody confirm that it's not a problem to nest widgets with Flutter? Will my app suffer of bad performance if I do it?

Thanks in advance

like image 543
Valentin Avatar asked Jan 15 '19 06:01

Valentin


2 Answers

TL;DR: Deeply nesting single-purpose widgets in Flutter is recommended.


There are fundamental differences in how Android and Flutter render view elements (aka widgets or views).

In Android, there are relatively few, complex views that inherit each other. Each and every view provides a huge API surface, including stuff like padding, margin, colors etc.

Flutter, on the other hand, favors composition over inheritance. Most widgets exist for a single purpose only and are very lightweight. That means you need to nest widgets more deeply to achieve the same effects, but because their layout and rendering logic is easier, the rendering is typically faster.

For example, there's a Padding widget that makes some space around its child. The Padding widget's rules are very simple, making the rendering very fast. Additionally, the rules of every other widget also get simpler because they don't need to worry about padding anymore.

Basically, nesting widgets deeply is recommended in Flutter. It's quite the opposite to Android's model: If there's not much nesting, you probably did something wrong, because you have a huge widget that can often be split into simpler, faster, smaller widgets.

Here's an interesting Google Tech Talk about Flutter's rendering pipeline, which I recommend to anyone interested in this topic.

like image 170
Marcel Avatar answered Sep 18 '22 12:09

Marcel


Nesting widgets is not a problem and is actually recommended. In fact, the default counter application contains no less than 150 widgets.

Widgets are lightweight objects optimized specifically to create and destroy tons of them every frame. This is further prooved by Flutter FAQ:

Rather than having each widget provide a large number of parameters, Flutter embraces composition. Widgets are built out of smaller widgets that you can reuse and combine in novel ways to make custom widgets. For example, rather than subclassing a generic button widget, RaisedButton combines a Material widget with a GestureDetector widget. The Material widget provides the visual design and the GestureDetector widget provides the interaction design.

This quote says that you should purposefully nest widgets.

like image 26
Rémi Rousselet Avatar answered Sep 21 '22 12:09

Rémi Rousselet