Structuring Flutter project by packages
Hello dev, these days I was wondering about having the best structure in my project in order to scale as much as I need and I came with a conclusion. Separate the code by feature is a good approach, however it’s not enough… So I found something interesting and I want to share with you, how to separate using packages and more than that, with packages you can reutilises in different projects as well, so let’s do it.
It’s quite simple and the first thing you need to do, is create a folder in the root of the project with the name “packages”, and inside of it create the folders according the package you want to implement.
Now inside the package folder you have to create a pubspec.yaml file with the a similar structure like the image below and also a lib folder which will have all the code files. One note here is, in the name property, give the name of the package you create.
And in this example I’ll just create a very simple Stateful widget representing the Login screen just to show how to use.
Now comes the trick, because we can not import the package directly from other file, first you need to import the package in the project’s pubspec.yaml like the image below. And on note here, the name of the package is the name of the dependency you gonna use, and the path is the path of the package.
In this example I’m using a local import, but you can create this package separately in a repository and import using the repository URL.
Now you can simply import the file in the package on your code and use as you want, and in this example I just used the Stateful widget to show something on the screen.
You might be thinking why you want to use such thing, but think about the possibilities… First you can reutilises packages like the packages you use from the pub.dev, other thing you need to consider is, each package has it owns scope and you will not have conflicts between external packages versions and so on.