Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Widgets in single file vs multiple files in Flutter

I am wondering what is the best practice according to organization of widgets in Flutter. Let's image I am writing some bigger widget like side bar in the application. This widget consists of several smaller widgets (like title, some greeting, user data, list of menu buttons, etc.) that I know won't be reused in other widgets. And now my question is - should all of them be kept in the same file (widgets or methods that build these widgets) as their context is the same or maybe should I separate them into large amount of small files in order to write tests for them more easily?

like image 380
wojtek1902 Avatar asked Sep 17 '25 15:09

wojtek1902


1 Answers

Having a separate file shouldn't bring any testing-related advantages, as far as I know. Flutter unit tests are usually written in a separate directory anyway. Using a separate file for a widget is useful for readability and for re-use (as you mention) rather than for testing.

I personally try to have one public widget per file, and to break down complex widgets into smaller private classes (not methods) that reside in the same file. If a widget can be reused or if it's complex enough to make a file not readable, I declare it as a public class in a separate file.

Also: the more your codebase grows, the more you might find it useful to use directories (rather than files) to group together widgets that are used in the same "context".

like image 121
Giorgio Avatar answered Sep 19 '25 06:09

Giorgio