How to add a package from GitHub in Flutter?

Example of pubspec.yaml


Dependency with the specific branch:

dependencies:
  flutter:
    sdk: flutter

  carousel_pro:
    git:
      url: git://github.com/jlouage/flutter-carousel-pro.git
      ref: main # branch name

Dependency with the specific commit:

dependencies:
  flutter:
    sdk: flutter

  carousel_pro:
    git:
      url: git://github.com/jlouage/flutter-carousel-pro.git
      ref: ea12e41 # commit hash

Example of a file importing the package:

import 'package:carousel_pro/src/carousel_pro_widgets.dart';
import 'package:flutter/material.dart';

class NewsCarousel extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 200.0,
      child: WidgetCarousel(
        autoplay: false,
        pages: [],
      ),
    );
  }
}

Note: If your IDE doesn't see the package, try to restart it.


The above answers are correct but I have added some examples.

So to use pub/package/lib without publishing on pub.dev :

1. Local - Save in some local folder

dependencies:
  library_name:
   path: /path/to/library_name

2. Hosted - Pushed on Github, Gitlab etc.

dependencies:
  library_name:
   git: https://github.com/username/library_name

Or to target exact branch

dependencies:
  library_name:
   git:
    url: https://github.com/username/library_name.git
    ref: dev    #branch name

Or to target exact commit

dependencies:
  library_name:
   git:
    url: https://github.com/username/library_name.git
    ref: e234072340    #commit reference id

Where 'library_name' has to be the same as the 'name' declared in pubspec.yaml of that pub.


I will show this use case, where you want to access a specific folder in a branch other than main/master:


  amplify_flutter:
    git:
      url: git://github.com/aws-amplify/amplify-flutter.git
      ref: null-safety-master
      path: packages/amplify_flutter/