常用第三方组件

Flutter 生态拥有丰富的第三方组件,可以大大提高开发效率。本教程将介绍最常用的第三方组件及其使用方法。

重要提示:所有第三方组件都可以在 pub.dev 上找到,使用前请查看最新版本和文档。

1. Provider 热门 推荐

Provider 是官方推荐的状态管理解决方案,简单易用,性能优秀。

包名 provider
类型 状态管理
热度 ⭐⭐⭐⭐⭐
链接 pub.dev

安装依赖

dependencies:
  provider: ^6.1.2

基本使用

// 1. 创建数据模型
class Counter extends ChangeNotifier {
  int _count = 0;
  int get count => _count;

  void increment() {
    _count++;
    notifyListeners();
  }
}

// 2. 在应用根部提供 Provider
void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => Counter(),
      child: const MyApp(),
    ),
  );
}

// 3. 在 Widget 中使用
class CounterWidget extends StatelessWidget {
  const CounterWidget({super.key});

  @override
  Widget build(BuildContext context) {
    final counter = context.watch();

    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text('计数: ${counter.count}'),
        ElevatedButton(
          onPressed: () => context.read().increment(),
          child: const Text('增加'),
        ),
      ],
    );
  }
}

// 4. 使用 Consumer 监听状态变化
Consumer(
  builder: (context, counter, child) {
    return Text('计数: ${counter.count}');
  },
)
优势:官方推荐、学习曲线平缓、性能优秀、支持依赖注入。

2. GetX 热门

GetX 是一个全功能框架,提供状态管理、路由管理、依赖注入等功能。

包名 get
类型 全功能框架
热度 ⭐⭐⭐⭐⭐
链接 pub.dev

安装依赖

dependencies:
  get: ^4.6.6

基本使用

// 1. 创建控制器
class CounterController extends GetxController {
  final count = 0.obs;

  void increment() {
    count.value++;
  }
}

// 2. 使用 GetX 状态管理
class CounterWidget extends StatelessWidget {
  final controller = Get.put(CounterController());

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Obx(() => Text('计数: ${controller.count.value}')),
        ElevatedButton(
          onPressed: () => controller.increment(),
          child: const Text('增加'),
        ),
      ],
    );
  }
}

// 3. 路由导航
Get.to(const SecondPage());
Get.back();
Get.off(const HomePage());

// 4. 带参数导航
Get.toNamed('/details', arguments: {'id': 123});

// 5. 响应式变量
var name = ''.obs;
Text('姓名: ${name.value}');
优势:功能全面、代码简洁、性能优秀、学习资源丰富。

3. Dio 热门 推荐

Dio 是一个强大的 HTTP 客户端,支持拦截器、请求取消、文件下载等功能。

包名 dio
类型 网络请求
热度 ⭐⭐⭐⭐⭐
链接 pub.dev

安装依赖

dependencies:
  dio: ^5.4.3

基本使用

// 1. 创建 Dio 实例
final dio = Dio();

// 2. GET 请求
Future fetchData() async {
  try {
    final response = await dio.get('https://api.example.com/data');
    print(response.data);
  } catch (e) {
    print('Error: $e');
  }
}

// 3. POST 请求
Future postData() async {
  try {
    final response = await dio.post(
      'https://api.example.com/users',
      data: {
        'name': 'Alice',
        'email': 'alice@example.com',
      },
    );
    print(response.data);
  } catch (e) {
    print('Error: $e');
  }
}

// 4. 添加拦截器
void setupInterceptors() {
  dio.interceptors.add(InterceptorsWrapper(
    onRequest: (options, handler) {
      print('请求: ${options.uri}');
      return handler.next(options);
    },
    onResponse: (response, handler) {
      print('响应: ${response.data}');
      return handler.next(response);
    },
    onError: (error, handler) {
      print('错误: ${error.message}');
      return handler.next(error);
    },
  ));
}

// 5. 文件下载
Future downloadFile() async {
  await dio.download(
    'https://example.com/file.pdf',
    '/path/to/save/file.pdf',
    onReceiveProgress: (received, total) {
      print('${(received / total * 100).toStringAsFixed(0)}%');
    },
  );
}
优势:功能强大、API 友好、支持拦截器、支持请求取消。

4. shared_preferences 热门 推荐

shared_preferences 用于存储简单的键值对数据,如用户设置、token 等。

包名 shared_preferences
类型 本地存储
热度 ⭐⭐⭐⭐⭐
链接 pub.dev

安装依赖

dependencies:
  shared_preferences: ^2.2.3

基本使用

import 'package:shared_preferences/shared_preferences.dart';

// 1. 保存数据
Future saveData() async {
  final prefs = await SharedPreferences.getInstance();

  // 保存字符串
  await prefs.setString('username', 'Alice');

  // 保存整数
  await prefs.setInt('age', 25);

  // 保存布尔值
  await prefs.setBool('isLoggedIn', true);

  // 保存浮点数
  await prefs.setDouble('height', 1.75);

  // 保存字符串列表
  await prefs.setStringList('favorites', ['item1', 'item2', 'item3']);
}

// 2. 读取数据
Future readData() async {
  final prefs = await SharedPreferences.getInstance();

  // 读取字符串
  String? username = prefs.getString('username');
  print('用户名: $username');

  // 读取整数
  int? age = prefs.getInt('age');
  print('年龄: $age');

  // 读取布尔值
  bool? isLoggedIn = prefs.getBool('isLoggedIn');
  print('已登录: $isLoggedIn');

  // 读取浮点数
  double? height = prefs.getDouble('height');
  print('身高: $height');

  // 读取字符串列表
  List? favorites = prefs.getStringList('favorites');
  print('收藏: $favorites');
}

// 3. 删除数据
Future deleteData() async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.remove('username');
}

// 4. 清空所有数据
Future clearAll() async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.clear();
}

// 5. 检查键是否存在
Future checkKey() async {
  final prefs = await SharedPreferences.getInstance();
  bool exists = prefs.containsKey('username');
  print('键存在: $exists');
}
优势:API 简单、跨平台支持、性能优秀、使用广泛。

5. sqflite 热门

sqflite 是 SQLite 数据库的 Flutter 插件,适合存储结构化数据。

包名 sqflite
类型 数据库
热度 ⭐⭐⭐⭐
链接 pub.dev

安装依赖

dependencies:
  sqflite: ^2.3.3
  path: ^1.8.3

基本使用

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DatabaseHelper {
  static final DatabaseHelper instance = DatabaseHelper._init();
  static Database? _database;

  DatabaseHelper._init();

  Future get database async {
    if (_database != null) return _database!;
    _database = await _initDB('notes.db');
    return _database!;
  }

  Future _initDB(String filePath) async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, filePath);

    return await openDatabase(
      path,
      version: 1,
      onCreate: _createDB,
    );
  }

  Future _createDB(Database db, int version) async {
    await db.execute('''
    CREATE TABLE notes (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      title TEXT NOT NULL,
      content TEXT,
      createdAt TEXT
    )
    ''');
  }

  // 插入数据
  Future insertNote(Note note) async {
    final db = await instance.database;
    return await db.insert('notes', note.toMap());
  }

  // 查询所有数据
  Future> getAllNotes() async {
    final db = await instance.database;
    final result = await db.query('notes');
    return result.map((json) => Note.fromMap(json)).toList();
  }

  // 更新数据
  Future updateNote(Note note) async {
    final db = await instance.database;
    return await db.update(
      'notes',
      note.toMap(),
      where: 'id = ?',
      whereArgs: [note.id],
    );
  }

  // 删除数据
  Future deleteNote(int id) async {
    final db = await instance.database;
    return await db.delete(
      'notes',
      where: 'id = ?',
      whereArgs: [id],
    );
  }
}
优势:关系型数据库、支持复杂查询、事务支持、离线可用。

6. cached_network_image 热门

cached_network_image 用于显示和缓存网络图片,支持占位符和错误处理。

包名 cached_network_image
类型 图片加载
热度 ⭐⭐⭐⭐⭐
链接 pub.dev

安装依赖

dependencies:
  cached_network_image: ^3.3.1

基本使用

import 'package:cached_network_image/cached_network_image.dart';

// 1. 基本 usage
CachedNetworkImage(
  imageUrl: 'https://via.placeholder.com/300',
  placeholder: (context, url) => const CircularProgressIndicator(),
  errorWidget: (context, url, error) => const Icon(Icons.error),
)

// 2. 自定义占位符
CachedNetworkImage(
  imageUrl: 'https://example.com/image.jpg',
  placeholder: (context, url) => Container(
    width: 200,
    height: 200,
    color: Colors.grey[200],
    child: const Center(
      child: CircularProgressIndicator(),
    ),
  ),
  errorWidget: (context, url, error) => Container(
    width: 200,
    height: 200,
    color: Colors.red[100],
    child: const Center(
      child: Icon(Icons.error),
    ),
  ),
)

// 3. 带进度的加载
CachedNetworkImage(
  imageUrl: 'https://example.com/image.jpg',
  progressIndicatorBuilder: (context, url, progress) {
    return Center(
      child: CircularProgressIndicator(
        value: progress.progress,
      ),
    );
  },
  errorWidget: (context, url, error) => const Icon(Icons.error),
)

// 4. 内存缓存配置
CachedNetworkImage(
  imageUrl: 'https://example.com/image.jpg',
  memCacheWidth: 300,
  memCacheHeight: 300,
  maxWidthDiskCache: 600,
  maxHeightDiskCache: 600,
)
优势:自动缓存、支持占位符、错误处理、性能优秀。

7. image_picker 热门

image_picker 用于从相机或图库选择图片和视频。

包名 image_picker
类型 媒体选择
热度 ⭐⭐⭐⭐⭐
链接 pub.dev

安装依赖

dependencies:
  image_picker: ^1.0.7

基本使用

import 'package:image_picker/image_picker.dart';

final ImagePicker _picker = ImagePicker();

// 1. 从相机拍照
Future pickImageFromCamera() async {
  final XFile? photo = await _picker.pickImage(
    source: ImageSource.camera,
    imageQuality: 80,
  );
  if (photo != null) {
    print('图片路径: ${photo.path}');
  }
}

// 2. 从图库选择
Future pickImageFromGallery() async {
  final XFile? image = await _picker.pickImage(
    source: ImageSource.gallery,
    maxWidth: 1920,
    maxHeight: 1080,
  );
  if (image != null) {
    print('图片路径: ${image.path}');
  }
}

// 3. 选择多张图片
Future pickMultipleImages() async {
  final List images = await _picker.pickMultiImage(
    imageQuality: 80,
  );
  for (var image in images) {
    print('图片路径: ${image.path}');
  }
}

// 4. 从相机录制视频
Future pickVideoFromCamera() async {
  final XFile? video = await _picker.pickVideo(
    source: ImageSource.camera,
    maxDuration: const Duration(minutes: 5),
  );
  if (video != null) {
    print('视频路径: ${video.path}');
  }
}

// 5. 从图库选择视频
Future pickVideoFromGallery() async {
  final XFile? video = await _picker.pickVideo(
    source: ImageSource.gallery,
  );
  if (video != null) {
    print('视频路径: ${video.path}');
  }
}
优势:跨平台支持、API 简单、支持多种媒体、官方维护。

8. url_launcher 热门 推荐

url_launcher 用于在移动应用中启动 URL、拨打电话、发送邮件等。

包名 url_launcher
类型 系统功能
热度 ⭐⭐⭐⭐⭐
链接 pub.dev

安装依赖

dependencies:
  url_launcher: ^6.2.6

基本使用

import 'package:url_launcher/url_launcher.dart';

// 1. 打开网页
Future launchWebsite() async {
  final Uri url = Uri.parse('https://flutter.dev');
  if (!await launchUrl(url)) {
    throw Exception('无法启动 $url');
  }
}

// 2. 拨打电话
Future makePhoneCall() async {
  final Uri launchUri = Uri(
    scheme: 'tel',
    path: '1234567890',
  );
  if (!await launchUrl(launchUri)) {
    throw Exception('无法拨打电话');
  }
}

// 3. 发送短信
Future sendSMS() async {
  final Uri launchUri = Uri(
    scheme: 'sms',
    path: '1234567890',
  );
  if (!await launchUrl(launchUri)) {
    throw Exception('无法发送短信');
  }
}

// 4. 发送邮件
Future sendEmail() async {
  final Uri launchUri = Uri(
    scheme: 'mailto',
    path: 'example@example.com',
    queryParameters: {
      'subject': '邮件主题',
      'body': '邮件内容',
    },
  );
  if (!await launchUrl(launchUri)) {
    throw Exception('无法发送邮件');
  }
}

// 5. 打开应用商店评价页面
Future openStoreReview() async {
  // iOS
  final iosUrl = Uri.parse(
    'https://apps.apple.com/app/id1234567890?action=write-review'
  );
  // Android
  final androidUrl = Uri.parse(
    'market://details?id=com.example.app'
  );

  final url = Theme.of(context).platform == TargetPlatform.iOS
      ? iosUrl
      : androidUrl;

  if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
    throw Exception('无法打开应用商店');
  }
}
优势:跨平台支持、功能全面、API 简单、官方维护。

使用建议

  • 根据项目需求选择合适的第三方组件
  • 使用前查看组件的文档和示例
  • 关注组件的维护状态和更新频率
  • 优先选择官方推荐或社区认可度高的组件
  • 注意组件的兼容性和依赖关系
  • 在生产环境中进行充分测试
  • 定期更新依赖包以获取新功能和修复
资源:访问 pub.dev 查找更多第三方组件和插件。