flutterwidgetreadabilitycode-splitting

When to create separate widget of a component in a very long flutter .dart file


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,
                          ),
                        ),
                      )

Solution

  • 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:

    1. Divide the component in two parts. First balance section, and second send button.
    2. We will make both parts separately and then call them where they are needed.
    3. 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.