1

在下面的测试代码中,我有一个标志,用于确定是使用 ChangeNotifierProvider 还是 ChangeNotifierProxyProvider。当我按下这RaisedButton两种方法时,正确显示我的 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,
        ),
      ),
    );
  }
}

Provider.of仅在使用 ChangeNotifierProvider 时返回我的 GroupEditorProvider 实例。当使用 Change ChangeNotifierProxyProvider 时,groupEditorProvider下面是null.

class GroupEditorPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final groupEditorProvider = Provider.of<GroupEditorProvider>(context);

我使用 Provider 已经有一段时间了,但对 ChangeNotifierProxyProvider 还是陌生的,所以很可能不了解一些基本的东西。

4

1 回答 1

2

原来我没有从我的GroupEditorProvider.update函数中返回提供者实例:

  update(CloudServicesProvider cloudServicesProvider) {
    if (_cloudServicesProvider == null) {
      this._cloudServicesProvider = cloudServicesProvider;
    }
    return this; // <--- was missing
  }

Flutter 是否应该为此抛出异常?如果是这样,我会发布到 github。

于 2020-07-14T16:16:24.173 回答