Reputation: 2771
In my test code below I have a flag that determines whether to use a ChangeNotifierProvider or a ChangeNotifierProxyProvider. When I press the RaisedButton
both approaches properly display my GroupEditorPage.
const isUsingChangeNotifierProxyProvider = true;
class GroupsPage extends StatelessWidget {
showGroupEditor(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(builder: (_) {
return isUsingChangeNotifierProxyProvider
? ChangeNotifierProxyProvider<CloudServicesProvider,
GroupEditorProvider>(
create: (_) => GroupEditorProvider(),
update: (_, cloudServicesProvider, groupEditorProvider) =>
groupEditorProvider.update(cloudServicesProvider),
child: GroupEditorPage(),
)
: ChangeNotifierProvider<GroupEditorProvider>(
create: (_) => GroupEditorProvider(),
child: GroupEditorPage(),
);
}),
);
}
@override
Widget build(BuildContext context) {
return SliversPage(
text: 'Testing',
sliverList: SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return RaisedButton(
child: Text('+Create Group'),
onPressed: () => showGroupEditor(context),
);
},
childCount: 1,
),
),
);
}
}
But Provider.of
only returns my GroupEditorProvider instance when ChangeNotifierProvider is used. When Change ChangeNotifierProxyProvider is used, groupEditorProvider
below is null
.
class GroupEditorPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final groupEditorProvider = Provider.of<GroupEditorProvider>(context);
I've been using Provider for some time but am new to ChangeNotifierProxyProvider so likely not understanding something fundamental.
Upvotes: 1
Views: 182
Reputation: 2771
Turns out I wasn't returning the provider instance from my GroupEditorProvider.update
function:
update(CloudServicesProvider cloudServicesProvider) {
if (_cloudServicesProvider == null) {
this._cloudServicesProvider = cloudServicesProvider;
}
return this; // <--- was missing
}
Should Flutter have thrown an exception for this? I'll post to github if so.
Upvotes: 2