# Provider
# Provider 的使用
# 添加 provider 依赖
dependencies:
...
# 状态管理
provider: ^4.0.5
...
# 新建 Provider
import 'package:flutter/material.dart';
class CountProvider with ChangeNotifier {
int count = 0;
changeCount(int newNum) {
count = newNum;
notifyListeners();
}
}
# 页面包裹 Provider
import 'package:provider/provider.dart';
class CountPageState extends StatefulWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => CountProvider(),
child: ...,
);
}
}
# 获取或修改当前状态
// 取值
int count = Provider.of<CountProvider>(context).count;
// 设置值
Provider.of<CountProvider>(context, listen: false).changeCount(index);
← Dart语言 flutter 组件 →