简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM