简介
Provider 最常用场景是 Flutter 状态管理,也广泛用于 React、鸿蒙、.NET 等框架,核心是跨组件共享数据、解耦状态与视图
1 2 3 4 5 6 7 8 9 10 11 12
| ┌───────────────────-─┐ │ Provider 架构 │ ├────────────────-────┤ │ ChangeNotifier → 状态数据 + 通知机制│ │ ↓ │ │ Provider → 状态提供 │ │ ↓ │ │ Consumer → 状态消费/监听 │
│ ↓ │ │ InheritedWidget → 跨组件树共享状态 │ └──────────────────-──┘
|
添加依赖
pubspec.yaml 中添加相关依赖
1 2 3 4
| dependencies: flutter: sdk: flutter provider: ^6.1.1 # 最新版本
|
provider 三种 使用方式
专门用于提供 ChangeNotifier 子类实例的 Provider
1 2 3 4 5 6 7 8 9 10 11 12 13
| import 'package:flutter/cupertino.dart'; import 'package:provider/provider.dart';
import 'CounterNotifier.dart';
void main() { runApp( ChangeNotifierProvider( create: (context) => CounterNotifier(), child: MyApp(), ), ); }
|
CounterNotifier 演示 Provider 范例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| import 'package:flutter/material.dart'; import 'package:provider/provider.dart';
class CounterNotifier extends ChangeNotifier { int _count = 0; int get count => _count;
void increment() { _count++; notifyListeners(); }
void decrement() { _count--; notifyListeners(); } }
void main() { runApp( ChangeNotifierProvider( create: (_) => CounterNotifier(), child: const MyApp(), ), ); }
class MyApp extends StatelessWidget { const MyApp({super.key});
@override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Provider 示例')), body: Center( child: Consumer<CounterNotifier>( builder: (context, counter, _) { return Text('${counter.count}', style: const TextStyle(fontSize: 48)); }, ), ), floatingActionButton: Column( mainAxisAlignment: MainAxisAlignment.end, children: [ FloatingActionButton( onPressed: () => context.read<CounterNotifier>().increment(), child: const Icon(Icons.add), ), const SizedBox(height: 10), FloatingActionButton( onPressed: () => context.read<CounterNotifier>().decrement(), child: const Icon(Icons.remove), ), ], ), ), ); } }
|
Consumer(推荐)
1 2 3 4 5
| Consumer<CounterNotifier>( builder: (context, counter, child) { return Text('${counter.count}'); }, )
|
文档中优先使用 Consumer,是因为它能局部刷新(仅重建 Consumer 内部的 Widget)
- 优点
- 作用域明确 - 只在 builder 内监听状态变化
- 性能优化 - 可配合 child 参数减少重建
- 代码清晰 - 一眼看出这是状态消费点
- 缺点
- 增加嵌套层级 - 多层 Consumer 会导致 Widget 树过深
- 只能在 build 方法中使用 - 不能在非 Widget 上下文使用
Provider.of
1 2
| final counter = Provider.of<CounterNotifier>(context); Text('${counter.count}')
|
Provider.of 是 Provider 库中获取共享状态的核心方法之一,用于在 Widget 中访问已注入 Widget 树的 Provider 实例,本质是通过 BuildContext 查找上层的 InheritedWidget(Provider 底层依赖)
- 优点
- 灵活 - 可在任何有 context 的地方使用
- 可控 - 可明确指定是否监听状态
- 无额外嵌套 - 不增加 Widget 层级
- 缺点
- 容易出错 - 忘记设置 listen: false 会导致不必要的重建
- build 外部必须用 listen: false
- 可读性稍差 - 需要看参数才知道是否监听
watch / read(扩展方法)
1 2
| context.watch<CounterNotifier>().count context.read<CounterNotifier>().increment()
|
context.watch().count:用于「读取状态 + 监听变化」,等价于 Provider.of<CounterNotifier>(context, listen: true),状态改变时会自动重建当前 Widget,适合用于展示状态的场景。
context.read():用于「读取状态 + 仅修改状态(不监听)」,等价于 Provider.of(context, listen: false),不会监听状态变化,适合用于按钮点击等仅触发修改的场景。
- 优点
- 语法最简洁 - 代码量少,可读性高
- 语义清晰 - watch 和 read 意图明确,不易出错
- 缺点
- 需要导入扩展 - 需确保 provider 包版本 >= 6.0
- watch 限制 - 不能在 build 方法外部调用