Dart Packages & Pub

Managing dependencies and sharing code with Pub package manager

📦 What is Pub?

Pub is Dart's package manager that helps you add external libraries, manage dependencies, and share your own packages with the Dart community easily.


# pubspec.yaml
dependencies:
  http: ^0.13.5
  json_annotation: ^4.8.0
                                    

Command:

dart pub get

Packages downloaded and ready to use!

Pub Package System

📋

pubspec.yaml

Project configuration file

name: my_app
dependencies:
  flutter: sdk
⬇️

Installing Packages

Add external libraries

dart pub add http
dart pub get
🔍

Package Discovery

Find packages on pub.dev

dart pub search json
dart pub deps
📤

Publishing

Share your own packages

dart pub publish
dart pub publish --dry-run

🔹 Creating a pubspec.yaml

The pubspec.yaml file defines your project and its dependencies:

name: my_awesome_app
description: A sample Dart application
version: 1.0.0
homepage: https://github.com/myusername/my_awesome_app

environment:
  sdk: '>=2.17.0 <4.0.0'

dependencies:
  # HTTP requests
  http: ^0.13.5
  
  # JSON serialization
  json_annotation: ^4.8.0
  
  # Date formatting
  intl: ^0.18.0
  
  # Logging
  logging: ^1.1.1

dev_dependencies:
  # Testing
  test: ^1.21.0
  
  # Code generation
  json_serializable: ^6.6.0
  build_runner: ^2.3.3
  
  # Linting
  lints: ^2.0.0

# Assets and resources
flutter:
  assets:
    - images/
    - data/config.json

After running 'dart pub get':

✓ http 0.13.5 downloaded

✓ json_annotation 4.8.0 downloaded

✓ intl 0.18.0 downloaded

✓ All dependencies resolved!

🔹 Using Packages in Code

Import and use external packages in your Dart code:

// Import packages
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'dart:convert';

void main() async {
  // Use HTTP package for API calls
  await fetchUserData();
  
  // Use intl package for date formatting
  formatDates();
  
  // Use built-in JSON support
  handleJsonData();
}

Future<void> fetchUserData() async {
  try {
    final response = await http.get(
      Uri.parse('https://jsonplaceholder.typicode.com/users/1'),
      headers: {'Content-Type': 'application/json'},
    );
    
    if (response.statusCode == 200) {
      final userData = json.decode(response.body);
      print('User: ${userData['name']}');
      print('Email: ${userData['email']}');
    } else {
      print('Failed to load user data');
    }
  } catch (e) {
    print('Error: $e');
  }
}

void formatDates() {
  final now = DateTime.now();
  
  // Different date formats using intl package
  final dateFormat = DateFormat('yyyy-MM-dd');
  final timeFormat = DateFormat('HH:mm:ss');
  final fullFormat = DateFormat('EEEE, MMMM d, yyyy');
  
  print('Date: ${dateFormat.format(now)}');
  print('Time: ${timeFormat.format(now)}');
  print('Full: ${fullFormat.format(now)}');
}

void handleJsonData() {
  final user = {
    'id': 1,
    'name': 'John Doe',
    'email': '[email protected]',
    'active': true
  };
  
  // Convert to JSON string
  final jsonString = json.encode(user);
  print('JSON: $jsonString');
  
  // Parse JSON string
  final parsedUser = json.decode(jsonString);
  print('Parsed name: ${parsedUser['name']}');
}

Output:

User: Leanne Graham

Email: [email protected]

Date: 2024-01-15

Time: 14:30:25

Full: Monday, January 15, 2024

JSON: {"id":1,"name":"John Doe","email":"[email protected]","active":true}

🔹 Common Pub Commands

Essential commands for managing Dart packages:

Package Management:

  • dart pub get - Download dependencies
  • dart pub add package_name - Add a new dependency
  • dart pub remove package_name - Remove a dependency
  • dart pub upgrade - Update all packages

Information Commands:

  • dart pub deps - Show dependency tree
  • dart pub search keyword - Search for packages
  • dart pub outdated - Check for updates

Development Commands:

  • dart pub run build_runner build - Generate code
  • dart pub publish --dry-run - Test publishing
  • dart pub global activate package_name - Install globally
# Example workflow
dart create my_project
cd my_project

# Add dependencies
dart pub add http intl
dart pub add --dev test build_runner

# Get all dependencies
dart pub get

# Check what's installed
dart pub deps

# Update packages
dart pub upgrade

# Run the app
dart run

Terminal Output:

$ dart pub add http

✓ Added dependency http ^0.13.5

$ dart pub get

✓ Got dependencies!

🧠 Test Your Knowledge

What file defines dependencies in a Dart project?