当我们其中一个 model 依赖于另外一个 model 时,就需要使用 ProxyProvider

上代码

  1. import 'package:flutter/material.dart';
  2. import 'package:provider/provider.dart';
  3. void main() => runApp(MyApp());
  4. class MyApp extends StatelessWidget {
  5. @override
  6. Widget build(BuildContext context) {
  7. return MultiProvider( // <--- MultiProvider
  8. providers: [
  9. ChangeNotifierProvider<MyModel>( // <--- ChangeNotifierProvider
  10. create: (context) => MyModel(),
  11. ),
  12. ProxyProvider<MyModel, AnotherModel>( // <--- ProxyProvider
  13. update: (context, myModel, anotherModel) => AnotherModel(myModel),
  14. ),
  15. ],
  16. child: MaterialApp(
  17. home: Scaffold(
  18. appBar: AppBar(title: Text('My App')),
  19. body: Column(
  20. children: <Widget>[
  21. Row(
  22. mainAxisAlignment: MainAxisAlignment.center,
  23. children: <Widget>[
  24. Container(
  25. padding: const EdgeInsets.all(20),
  26. color: Colors.green[200],
  27. child: Consumer<MyModel>( // <--- MyModel Consumer
  28. builder: (context, myModel, child) {
  29. return RaisedButton(
  30. child: Text('Do something'),
  31. onPressed: (){
  32. myModel.doSomething('Goodbye');
  33. },
  34. );
  35. },
  36. )
  37. ),
  38. Container(
  39. padding: const EdgeInsets.all(35),
  40. color: Colors.blue[200],
  41. child: Consumer<MyModel>( // <--- MyModel Consumer
  42. builder: (context, myModel, child) {
  43. return Text(myModel.someValue);
  44. },
  45. ),
  46. ),
  47. ],
  48. ),
  49. Container(
  50. padding: const EdgeInsets.all(20),
  51. color: Colors.red[200],
  52. child: Consumer<AnotherModel>( // <--- AnotherModel Consumer
  53. builder: (context, anotherModel, child) {
  54. return RaisedButton(
  55. child: Text('Do something else'),
  56. onPressed: (){
  57. anotherModel.doSomethingElse();
  58. },
  59. );
  60. },
  61. )
  62. ),
  63. ],
  64. ),
  65. ),
  66. ),
  67. );
  68. }
  69. }
  70. class MyModel with ChangeNotifier { // <--- MyModel
  71. String someValue = 'Hello';
  72. void doSomething(String value) {
  73. someValue = value;
  74. print(someValue);
  75. notifyListeners();
  76. }
  77. }
  78. class AnotherModel { // <--- AnotherModel
  79. MyModel _myModel;
  80. AnotherModel(this._myModel);
  81. void doSomethingElse() {
  82. _myModel.doSomething('See you later');
  83. print('doing something else');
  84. }
  85. }

看效果

proxyprovider.gif

来源链接