英文:
When to create separate widget of a component in a very long flutter .dart file
问题
我有这段代码作为Column
的一部分,它有很多子组件,使其长度达到了400
行。将这样的小部件拆分到单独的文件中是否是一个好做法?推荐的行数超过多少会使Flutter代码变得不太可读?
GestureDetector(
onTap: () async {
await Clipboard.setData(
ClipboardData(
text: context
.read<GeneratePasswordModel>()
.password),
);
CustomToast.showToast('Password copied to clipboard');
},
child: Padding(
padding: EdgeInsets.only(right: 15.0),
child: Icon(
FeatherIcons.copy,
size: 28.0,
),
),
)
英文:
I have this code as a part of a Column
having many children making it as long as 400
lines. Is it a good practice to split widgets like these into separate files? What is the recommended number of lines beyond which it makes flutter code less readable?
GestureDetector(
onTap: () async {
await Clipboard.setData(
ClipboardData(
text: context
.read<GeneratePasswordModel>()
.password),
);
CustomToast.showToast('Password copied to clipboard');
},
child: Padding(
padding: EdgeInsets.only(right: 15.0),
child: Icon(
FeatherIcons.copy,
size: 28.0,
),
),
)
答案1
得分: 1
这个答案很简单。作为最佳实践,我们需要将问题分解成较小的组件。实际上,在大多数情况下,代码行数并不重要。但我会尝试通过一个例子来解释,
假设我们有一个组件,它有两个部分。它有一个余额部分,下面有一个发送按钮。现在我们可以这样做:
- 将组件分成两个部分。第一部分是“余额部分”,第二部分是“发送按钮”。
- 我们将分别创建这两个部分,然后在需要它们的地方调用它们。
- 这样,我们使代码更加可读和清晰,并且分离了业务逻辑。
特别是在你的情况下,如果你的“Column”有不同的逻辑组件,那么你可以相应地拆分它们,以使代码更可读。但如果它只有一个逻辑组件,那么你可以按原样使用。在Flutter本身没有这样的限制。
英文:
Answer to this is simple. As best practice, we need to divide the problem in smaller componenets. It really does not matter on lines of code actually in most cases. But, I will try to explain it with an example,
Lets say we have a component that have two parts. It has a some balance section and below it has a send button. Now what we can do is:
- Divide the component in two parts. First
balance section
, and secondsend button
. - We will make both parts separately and then call them where they are needed.
- In this way, we made the code more readable and clean and also seperated the business logic.
Particularly in your case, if your Column
has different logical components, then you can split them accordingly to make code more readable. But if it has single logical component, then you can go with as it is. There is no such limitation in flutter itself.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论