【问题标题】:Provider.of<> returning null with ChangeNotifierProxyProvider?Provider.of<> 使用 ChangeNotifierProxyProvider 返回 null?
【发布时间】:2020-11-03 14:26:48
【问题描述】:

在下面的测试代码中,我有一个标志,用于确定是使用 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 很陌生,所以可能不了解一些基本的东西。

【问题讨论】:

    标签: flutter flutter-change-notifier


    【解决方案1】:

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

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

    Flutter 是否应该为此抛出异常?有的话我会发到github上的。

    【讨论】:

      猜你喜欢
      • 2020-12-10
      • 2021-02-21
      • 1970-01-01
      • 2016-05-11
      • 2015-11-08
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多