4

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?

wojtek1902
  • 503
  • 2
  • 10
  • 25

1 Answers1

7

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".

Giorgio
  • 2,137
  • 3
  • 20
  • 40
  • I thought that it might be more useful from testing point of view since I can test all the widgets separately. As they are private, I cannot do this, I can only test them as a part of the main, public widget. – wojtek1902 Oct 11 '20 at 09:57
  • 1
    Ok. Then maybe I should express more explicitly what I meant: the main requirement for a class to be testable is to be public. It doesn't matter whether it is in its own file or in the file of a class that uses it, as long as the class you want to test is public. – Giorgio Oct 11 '20 at 17:07