Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Dart notes · Topic 18 of 19 · 5 min read

Dart packages, testing and debugging

Dart packages and testing notes: project layout, pubspec.yaml, pub.dev packages, imports, unit tests with test and expect, debugging, format and analyze.

Anatomy of a Dart project

dart create school_app makes a ready-to-run project:

school_app/
  bin/school_app.dart      the program's entry point (main)
  lib/school_app.dart      reusable code: classes and functions
  test/school_app_test.dart  unit tests
  pubspec.yaml             project name, Dart version and packages
  analysis_options.yaml    lint rules
  README.md

Run it with dart run inside the folder. Code in bin/ runs; code in lib/ is imported by bin/ and by tests. Flutter projects have the same idea with lib/main.dart as the entry point.

pubspec.yaml

name: school_app
description: A small school management program.
version: 1.0.0

environment:
  sdk: ^3.9.0

dependencies:
  http: ^1.2.0
  intl: ^0.19.0

dev_dependencies:
  test: ^1.25.6
  lints: ^6.0.0
  • dependencies are packages the program needs to run.
  • dev_dependencies are only for development, such as tests and lints.
  • ^1.2.0 means "1.2.0 or any later 1.x version": compatible updates only.

Packages from pub.dev

pub.dev is Dart's package site: thousands of free libraries for HTTP, dates, storage, state management and more. Check a package's likes, pub points and popularity, and whether it supports your platforms, before using it.

dart pub add http          adds the latest version to pubspec.yaml and downloads it
dart pub get               downloads everything listed in pubspec.yaml
dart pub upgrade           moves to the newest allowed versions
dart pub outdated          shows which packages have newer versions

pubspec.lock records the exact versions used, so everyone on the team gets the same ones. Commit it for apps.

Imports: as, show and hide

import 'dart:convert' show jsonEncode;   // only this name
import 'dart:math' as math;              // prefix: math.sqrt, math.pi

void main() {
  print(math.sqrt(16));
  print(jsonEncode({'pi': math.pi.toStringAsFixed(2)}));
}
4.0
{"pi":"3.14"}
  • as adds a prefix, which avoids name clashes: import 'package:http/http.dart' as http; then http.get(...).
  • show imports only the listed names; hide imports everything except them.
  • package:name/file.dart imports from a package (including your own project's lib/); 'src/student.dart' imports one of your files by relative path.

Organise imports in three groups: dart: libraries, then package: imports, then your own relative files, each sorted alphabetically.

Unit tests: test, expect and group

A unit test runs a small piece of code and checks the result automatically. Add the test package as a dev dependency and put tests in test/.

// lib/marks.dart
String grade(int marks) {
  if (marks < 0 || marks > 100) throw ArgumentError('marks out of range');
  if (marks >= 75) return 'A';
  if (marks >= 33) return 'Pass';
  return 'Fail';
}
// test/marks_test.dart
import 'package:school_app/marks.dart';
import 'package:test/test.dart';

void main() {
  group('grade', () {
    test('75 and above is A', () {
      expect(grade(75), 'A');
      expect(grade(100), 'A');
    });
    test('33 is the pass mark', () {
      expect(grade(33), 'Pass');
      expect(grade(32), 'Fail');
    });
    test('rejects impossible marks', () {
      expect(() => grade(101), throwsArgumentError);
    });
  });
}

Run dart test. Each test passes or fails with a message showing the expected and actual values. group collects related tests. Matchers such as equals, isTrue, contains, greaterThan and throwsA describe what you expect.

Good tests check edge cases: the boundary values (32, 33, 75), empty lists, null and bad input.

Debugging

  1. Read the error and its stack trace: the top lines that mention your files show where it broke.
  2. print values to see what the program really does: print('total=$total, i=$i');.
  3. assert assumptions: assert(list.isNotEmpty); fails loudly in debug runs.
  4. Use the debugger in VS Code: click left of a line number to set a breakpoint, press F5, then step through the code line by line and watch variables change.
int average(List<int> marks) {
  assert(marks.isNotEmpty, 'average of an empty list');
  var total = 0;
  for (var m in marks) {
    total += m;
  }
  print('debug: total=$total count=${marks.length}');
  return total ~/ marks.length;
}

void main() {
  print(average([70, 81, 90]));
}
debug: total=241 count=3
80

Remove debug prints before sharing code.

Clean code: dart format and dart analyze

dart format .        re-indents and wraps every file in the standard style
dart analyze         reports errors, warnings and lint hints without running the code
dart fix --apply     applies the fixes the analyzer knows how to make

Effective Dart naming:

  • UpperCamelCase for classes, enums, typedefs and extensions: StudentRecord.
  • lowerCamelCase for variables, functions, parameters and constants: totalMarks, gstRate.
  • lowercase_with_underscores for file and package names: student_record.dart.
  • Start private names with _.

Lints (from package:lints or flutter_lints) catch style problems and likely bugs, such as unused variables and missing await.

Common mistakes

  • Editing pubspec.yaml and forgetting dart pub get.
  • Importing a lib/ file with a long relative path from test/; use package:your_app/....
  • Adding a package for something a few lines of your own code could do.
  • Tests that only check the happy path and miss the boundaries.
  • Leaving debug print calls in finished code.

Key points

  • dart create makes bin/, lib/, test/ and pubspec.yaml.
  • pubspec.yaml lists dependencies; dart pub add and dart pub get fetch them from pub.dev.
  • import ... as, show and hide control names from a library.
  • Unit tests use test, expect and group, run with dart test.
  • Debug with error messages, print, assert and breakpoints.
  • dart format and dart analyze keep code clean.

Practice questions

1. What is the difference between dependencies and dev_dependencies?

dependencies are needed when the program runs. dev_dependencies, such as test and lints, are needed only while developing and are not shipped.

2. What does ^2.1.0 mean for a package version?

Version 2.1.0 or any later version below 3.0.0, that is, compatible updates only.

3. Write expect lines that check add(2, 3) is 5 and add(-1, 1) is 0.
test('add', () {
  expect(add(2, 3), 5);
  expect(add(-1, 1), 0);
});
4. Why use import 'dart:math' as math;?

The prefix keeps names such as max and min from clashing with your own names, and makes it clear where math.sqrt comes from.

5. Name the correct style for: a class for exam results, a variable for total fees, and the file that holds the class.

ExamResult, totalFees and exam_result.dart.