Flutter之状态管理Provider

Flutter之状态管理Provider

强烈推荐使用,上手超级简单

  • 添加依赖
  provider: ^3.1.0
  • 变量类
import 'package:flutter/material.dart';

class Counter with ChangeNotifier {
  int _count;

  Counter(this._count);

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

  int get() {
    return _count;
  }
}
  • 添加全局监听
 runApp(MultiProvider(
   providers: [
     ChangeNotifierProvider.value(value: Counter(1)),
  // 可以有多个
   ],
   child: MyAppDemo(),
 ));
  • 绘制页面
class HomePage2 extends StatefulWidget {
  @override
  State createState() => _HomePage2State();
}

class _HomePage2State extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("首页"),
      ),
      body: Container(
        child: Column(
          children: [
            Text("点击次数:${Provider.of(context).get()}"),
            FlatButton(
                onPressed: () {
                  Navigator.of(context)
                      .push(MaterialPageRoute(builder: (context) {
                    return HomePage2Copy();
                  }));
                },
                child: Text("下一页"))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Provider.of(context).add();
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

class HomePage2Copy extends StatefulWidget {
  @override
  State createState() => _HomePage2CopyState();
}

class _HomePage2CopyState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("第二页"),
      ),
      body: Container(
        child: Column(
          children: [
            Text("点击次数:${Provider.of(context).get()}"),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Provider.of(context).add();
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

你可能感兴趣的:(Flutter,flutter,provider)