Dart: importing local libraries with git

Published November 21, 2012

We have a couple of ways to manage application’s dependencies with pub, we can

  • import a hosted package
  • clone a git repository

Just to be clear, hosted packages are not hosted on a general server, they are hosted on a pub server; since setting up our own local pub server or taking advantage of pub-cache could be really tricky, a safe and fast way to import local packages is doing it via the git system.

Let’s see how to create an application, my_app, that imports a local library, my_lib.

Assume that my_lib and my_app folders are in user’s home directory, e.g.

Linux:	/home/bob/my_lib
OS X:	/Users/bob/my_lib
Win7	C:\Users\bob\my_lib

my_lib

  1. Create my_lib folder
  2. Create lib folder within my_lib
  3. Create my_lib.dart within lib folder and pubspec.yaml at top of my_lib folder

Here’s the directory tree of *my_lib:

./my_lib/
./my_lib/lib/my_lib.dart
./my_lib/pubspec.yaml

Content of my_lib.dart:

library my_lib;

String hello(String name){
  return 'Hello $name !';
}

Content of pubspec.yaml:

name: my_lib

Now we have to “convert” my_lib into a git repository; change to my_lib and type:

git init
git add lib/my_lib.dart
git add pubspec.yaml
git commit -m "Random message"

We’re done with my_lib, let’s switch to my_app


my_app

  1. Create my_app folder
  2. Create bin folder within my_app
  3. Create my_app.dart within bin
  4. Create pubspec.yaml at the top of my_app folder

Content of my_app.dart:

import 'package:my_lib/my_lib.dart';

main(){
  print(hello('darling'));
}

And now set content of pubspec.yaml to:

name: My Application
dependencies:
  my_lib:
    git: file:///home/bob/my_lib

Remember to change git: argument accordingly to current operating system

We’re almost done. Last step is running pub install in my_app folder. Output should return:

$ pub install
Resolving dependencies...
Dependencies installed!

Some symlinks, packages, have been created in my_app folder

Now we’re ready to run our awesome application:

$ dart bin/my_app.dart
Hello darling !

Easy!

comments powered by Disqus