Dart: How to compile/run a project with a pubspec.yaml file (dependencies)

If you ever want to compile and run a Dart project that uses a pubspec.yaml file to include some dependencies, here’s a quick example of the solution.

Your Dart source code

First, create your code and pubspec.yaml file as usual. Here’s the source code for a file named http_get.dart that uses the http package:

import 'package:http/http.dart' as http;
//import 'package:http/http.dart';

void main() async {
    print('1');
    var url = Uri.parse('https://jsonplaceholder.typicode.com/todos/1');
    print('2');
    var response = await http.get(url);
    print('3');
    print('response status: ${response.statusCode}');
    print('4');
    print('response body:   ${response.body}');
    print('5');
}

Note that I also do some async/await stuff in the code as well, though that’s secondary to what I’m trying to show in this example.

Your pubspec.yaml file

Next, create the pubspec.yaml file that’s necessary for using the http package:

name: http_test
dependencies:
  http: ^0.13.4

environment:
  sdk: '>=2.10.0 <3.0.0'

Note to self: The pubspec.yaml “caret” syntax in the http example means, “any version of http that is backwards compatible with version 0.13.4,” which I believe means any 0.13.x release. See this Dart caret syntax section for more details.

Download the dependencies

With that setup, the next thing you need to do is to run the dart pub get command to actually download your project dependencies (i.e., the http package):

$ dart pub get
(some output here)

Run your Dart code

Once that completes you can run this little Dart/pubspec.yaml project. You run it with the dart run command, as shown here, including the program output:

$ dart run http_get.dart

1
2
3
Response status: 200
4
Response body: {
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
5

If you’re interested in the async/await part of the code, that output may look interesting to you.

Bonus: Create an executable image

For extra credit, note that if you want to create an executable image (exe) from this Dart/pubspec.yaml project, do that like this:

$ dart compile exe http_get.dart

That command creates an exe file named http_get.exe on my macOS system.

The end

In summary, if you wanted to see how to run a Dart project that uses a pubspec.yaml file, I hope this example is helpful.

Reporting live from Longmont, Colorado,
Alvin Alexander