2. How To Structure A Dart Project

Rahul Vashishth
learn dart
Published in
3 min readApr 9, 2019

This is the second blog in the series of dart tutorials. Here we will discuss how a dart project should be structured.

Dart team also provides a dart structure generator named StageHand.

You can either create your own project structure or alternatively use StageHand.

A simple library package

Above is the directory layout of a library package.

A simplest Dart project(dart package) is a directory containing pubspec.yaml file. Pubspec.yaml is same as pom.xml in java or package.json in JS projects.

Unlike java projects, dart project are called dart package.

In pubspec.yaml file we manage the dependencies and package specific information such as package name, version, author etc.

Below is a sample pubspec.yaml file. here ‘hello_dart’ is the package name. and this package has the dependency on english_word library of version 3.1.5

a simple pubspec.yaml file

Dart Package vs Dart Library?

Dart libraries are like java packages. One library should contain a specific functionality and should not have an executable function or main function. like java.io package contains the classes related to file operations, dart:io library contains simple file handling functionality.

Below is an example of java spring-boot style dart_package, this contains a library component as well executable main function.

sample dart executable dart package with lib dir

bin directory should contain only one file, named main.dart. This will be the execution starting point of.

lib directory should contain the library file. generally, all the implementation file should go under src directory under lib. and only one dart file should be exported from the lib directory.

Once we run the ‘pub get’ command, .packages and pubspec.lock file will be generated as below.

package after running pub get command
  • .packages will have concrete information of immediate and transitive dependency.
  • .packages file will map the dependencies used in the application to the downloaded dependency in the system cache.

Read dart’s official package documentation to understand more about dart package layout.

Following is a summary of dart package convention -

my_dart_package/            - root package directory
.packages - dependencies mapping with system cache
pubspec.yaml - meta-info and dependencies
pubspec.lock - final used dependencies info
bin/ - executal main file
main.dart
doc/ - documentations
example/ - application samples
lib/ - this app's library package
string_merger.dart - file to be imported by others
src/ - internal files used by this lib
util.dart - this file should not be exposed
test/ - unit test cases
string_merger_test.dart
web/ - web specifc files
index.html -
style.css - this can be in nested folders

Follow this page for more dart tips and concepts.

--

--

Rahul Vashishth
learn dart

Tech Enthusiast, Cloud, Kubernetes, Java, DevOps. Environmentalist.