1. 安装依赖

    在pubspec.yaml中添加

    1. dependencies:
    2. provider: ^4.3.1
    1. 创建model

    创建文件app_name/lib/models/counterProvider.dart,若没有文件夹则创建,内容

    1. import 'package:flutter/material.dart';
    2. import 'package:app_name/models/counterProvider.dart';
    3. class CounterProvider with ChangeNotifier {
    4. bool _isClickTip = false;
    5. bool get value => _isClickTip;
    6. void setValue(val) {
    7. _isClickTip = val;
    8. notifyListeners();
    9. }
    10. }
    1. 注入到main.dart中的入口组件中
    1. runApp(MultiProvider(
    2. providers: [
    3. // ChangeNotifierProvider.value(value: CounterProvider()),
    4. ChangeNotifierProvider<CounterProvider>(create: (_) => CounterProvider(),)
    5. ],
    6. child: MyApp(),
    7. ));
    1. 在需要的地方使用状态
    1. import 'package:provider/provider.dart';
    2. // 读取方式1
    3. Text('${Provider.of<CounterProvider>(context).value}', style: TextStyle(color: Color(0xff4a4a4a), fontSize: setFont(32), fontWeight: FontWeight.w500)),
    4. // 读取方式2(优点:可以做到局部更新)
    5. Consumer<CountState>(
    6. builder: (ctx, state, child) {
    7. return Text(state.value, style: TextStyle(color: Color(0xff4a4a4a), fontSize: setFont(32), fontWeight: FontWeight.w500)),
    8. }
    9. )
    10. // 修改状态
    11. Provider.of<CounterProvider>(context, listen: false).setValue(true);