Home > Software engineering >  Is there a recommended way to use models and common files in multiple flutter projects?
Is there a recommended way to use models and common files in multiple flutter projects?

Time:05-20

I have two flutter projects, one is admin application and other user application. Both applications use many same models and classes, and common widgets.

Currently I am copying the model classes and widgets, to both projects, and when I need to change anything, I need to remember to change it in the other project too.

Is there any other method to do this? Should I create a custom package and import it in both projects? What would be the recommended way to do this?

CodePudding user response:

The conventional approach would be put your common code in a separate Dart package (that is, a separate directory with its own pubspec.yaml file and its source files in a lib subdirectory). Unless you want your package to be public, there is no need to publish your package to pub.dev.

Your other projects can then add that package as a dependency in their pubspec.yaml files. For packages not hosted on pub.dev, you probably will want to specify a local filesystem path to the package or to specify an URL to your own Git server. See the Package Dependencies documentation for more details.

Other approaches (that I don't recommend, but I mention for completeness):

  • Have your projects just import common .dart files by relative paths. However, navigating up multiple parent directories is very ugly.
  • In your projects' source directories, add symlinks that refer to the common code. Then you could import common files by relative path without needing to navigate up parent directories.
  • If you use separate source control repositories instead of a mono-repo, you could make each project consume common code as a Git submodule. Unlike the two approaches above, this would allow your different projects to use independent versions (the flipside is that that flexibility would be more work to maintain).
  • Related