Flutter: How to Reduce the number of imports?

While creating a Flutter app you must have seen a bundle of imports at starting of every page, like Google Fonts, Material Icons, SVG Image, etc. While some imports are unique to a file, some or most of the package imports are required across fairly every file. We will see how to reduce the number of imports in Flutter.

Image Showing Multiple Imports vs One Import. In the commons.dart file all the imports are mentioned.
Image Showing Multiple Imports vs One Import
This may not seem like a issue to you, but a file with fewer imports is easier to read compared to file with many imports.

Solution:

We will create a file by any name (eg: commons.dart). It is advisable to create the file in the root directory i.e in lib/commons.dart. We will then export all the repetitive files from this file and import this file wherever needed.

lib/commons.dart

Now we can easily import this file commons.dart from any file. All the files specified in commons.dart will be in turn imported. Now our files will be easier to read. Also, we don’t have to reimport the packages again and again in each file, which reduces the number of imports in every file.

lib/main.dart

You can check the complete source code here. Please note that this is a solution to the problem of the same repetitive imports across some pages, this doesn’t mean that you include all the files in a file and import it everywhere. That would be a bad practice as the imports are going unused. During execution, the compiler converts your whole code into a single file and replaces the imports with the real content inside the files. I am not sure if Flutter is smart enough to not keep the unused code aside. So fixing this from the developer’s end.

If you still have any queries you can let me know in the comments down below. If you are new to flutter check my post on how to install flutter on windows?

Leave a Reply

Your email address will not be published.

Previous Post
How to use HexColor in Flutter

How to convert HexColor to Flutter Color?

Next Post

Flutter: How to create Code Snippets?

Related Posts