当我们其中一个 model 依赖于另外一个 model 时,就需要使用 ProxyProvider
上代码
import 'package:flutter/material.dart';import 'package:provider/provider.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MultiProvider( // <--- MultiProviderproviders: [ChangeNotifierProvider<MyModel>( // <--- ChangeNotifierProvidercreate: (context) => MyModel(),),ProxyProvider<MyModel, AnotherModel>( // <--- ProxyProviderupdate: (context, myModel, anotherModel) => AnotherModel(myModel),),],child: MaterialApp(home: Scaffold(appBar: AppBar(title: Text('My App')),body: Column(children: <Widget>[Row(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[Container(padding: const EdgeInsets.all(20),color: Colors.green[200],child: Consumer<MyModel>( // <--- MyModel Consumerbuilder: (context, myModel, child) {return RaisedButton(child: Text('Do something'),onPressed: (){myModel.doSomething('Goodbye');},);},)),Container(padding: const EdgeInsets.all(35),color: Colors.blue[200],child: Consumer<MyModel>( // <--- MyModel Consumerbuilder: (context, myModel, child) {return Text(myModel.someValue);},),),],),Container(padding: const EdgeInsets.all(20),color: Colors.red[200],child: Consumer<AnotherModel>( // <--- AnotherModel Consumerbuilder: (context, anotherModel, child) {return RaisedButton(child: Text('Do something else'),onPressed: (){anotherModel.doSomethingElse();},);},)),],),),),);}}class MyModel with ChangeNotifier { // <--- MyModelString someValue = 'Hello';void doSomething(String value) {someValue = value;print(someValue);notifyListeners();}}class AnotherModel { // <--- AnotherModelMyModel _myModel;AnotherModel(this._myModel);void doSomethingElse() {_myModel.doSomething('See you later');print('doing something else');}}
看效果

