How many Stateless Widget Classes should a Flutter Developer put in one file?

728

You can add as much classes as you need in a single file. It depends on the developer's mindset.

But, let say if one of your class can be reused by other classes or packages then you should add it to another file for better separation.

I can favour you one approach is that your each file should have maximum one Stateful widget and as many Stateless widgets as you want for that corresponding widget will be a better scenario.

Still in some cases if you feel that more than enough stateless widgets has been added in a single file you should separate it in another file based on your choice.

Share:
728
MuTe33
Author by

MuTe33

Updated on December 15, 2022

Comments

  • MuTe33
    MuTe33 over 1 year

    I'm currently working on a flutter application. I have a file with a big widget tree. In order to easier understand, read and maintain I wanted to "crop" the widget tree.

    First what I did was to create multiple functions, which represented a bigger part of the tree such as _createFancyImage() or _createFancyContainer. After some research, I found out that such a design has some downsides (see: https://github.com/flutter/flutter/issues/19269). So then I decided to create StatelessWidgets instead. Because of the huge size of the widget tree, I broke it down to 3 logical StatelessWidgets. Now I can use FancyImage() or FancyContainer() which represent each a standalone widget.

    As a beginner, I'm not sure whether I should keep those StatelessWidgetclasses within the same file. Alternatively, I could create independent files. One thing to clarify: I'm not using those fancy widgets somewhere else. Those are unique to this one big widget tree otherwise I could have outsourced them into a new folder such as "common_widgets" or "components".

    Unfortunately, I couldn't find something within the Dart and Flutter Repo style guides nor on the internet.

    I appreciate every suggestion.