How to Use pub.dev in Flutter: Add and Manage Packages
To use
pub.dev in Flutter, find the package you want on pub.dev, then add its dependency to your pubspec.yaml file. Run flutter pub get to install the package, and import it in your Dart code to use its features.Syntax
To add a package from pub.dev, you edit the pubspec.yaml file in your Flutter project. Under the dependencies: section, add the package name and version.
Example parts:
dependencies:- starts the list of packagespackage_name: ^version- specifies the package and version constraint
After saving, run flutter pub get to download the package.
yaml
dependencies:
http: ^0.14.0Example
This example shows how to add the http package to your Flutter app and use it to fetch data from the internet.
dart
dependencies: http: ^0.14.0 // main.dart import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('pub.dev Example')), body: Center( child: FutureBuilder<http.Response>( future: http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1')), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return CircularProgressIndicator(); } else if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else { return Text('Response: ${snapshot.data?.body}'); } }, ), ), ), ); } }
Output
A Flutter app showing a loading spinner, then displaying JSON data fetched from the internet.
Common Pitfalls
Common mistakes when using pub.dev packages include:
- Forgetting to run
flutter pub getafter editingpubspec.yaml. - Using incompatible package versions causing build errors.
- Not importing the package in your Dart files.
- Ignoring platform-specific setup instructions some packages require.
dart
/// Wrong: Added dependency but forgot to run flutter pub get /// Right: Run flutter pub get after editing pubspec.yaml /// Wrong: Using package without import // Text('Hello') /// Right: Import package before use import 'package:http/http.dart' as http;
Quick Reference
- Find packages on pub.dev.
- Add package and version under
dependencies:inpubspec.yaml. - Run
flutter pub getto install. - Import the package in your Dart code.
- Check package documentation for usage and setup.
Key Takeaways
Add packages by editing
pubspec.yaml under dependencies:.Always run
flutter pub get after changing dependencies.Import packages in your Dart files to use them.
Check package docs on
pub.dev for setup and usage details.Be mindful of version constraints to avoid conflicts.