- 安装依赖
在pubspec.yaml中添加
dependencies:
provider: ^4.3.1
- 创建model
创建文件app_name/lib/models/counterProvider.dart,若没有文件夹则创建,内容
import 'package:flutter/material.dart';
import 'package:app_name/models/counterProvider.dart';
class CounterProvider with ChangeNotifier {
bool _isClickTip = false;
bool get value => _isClickTip;
void setValue(val) {
_isClickTip = val;
notifyListeners();
}
}
- 注入到main.dart中的入口组件中
runApp(MultiProvider(
providers: [
// ChangeNotifierProvider.value(value: CounterProvider()),
ChangeNotifierProvider<CounterProvider>(create: (_) => CounterProvider(),)
],
child: MyApp(),
));
- 在需要的地方使用状态
import 'package:provider/provider.dart';
// 读取方式1
Text('${Provider.of<CounterProvider>(context).value}', style: TextStyle(color: Color(0xff4a4a4a), fontSize: setFont(32), fontWeight: FontWeight.w500)),
// 读取方式2(优点:可以做到局部更新)
Consumer<CountState>(
builder: (ctx, state, child) {
return Text(state.value, style: TextStyle(color: Color(0xff4a4a4a), fontSize: setFont(32), fontWeight: FontWeight.w500)),
}
)
// 修改状态
Provider.of<CounterProvider>(context, listen: false).setValue(true);