简体   繁体   English

单个文件中的小部件与 Flutter 中的多个文件

[英]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.我想知道根据 Flutter 中的小部件组织,最佳实践是什么。假设我正在编写一些更大的小部件,例如应用程序中的边栏。 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. Flutter 单元测试通常写在一个单独的目录中。 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.如果一个小部件可以重复使用,或者如果它复杂到足以使文件不可读,我在一个单独的文件中将其声明为 public class。

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".另外:您的代码库增长得越多,您可能会发现使用目录(而不是文件)将在同一“上下文”中使用的小部件组合在一起更有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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