簡體   English   中英

Provider.of<> 使用 ChangeNotifierProxyProvider 返回 null?

[英]Provider.of<> returning null with ChangeNotifierProxyProvider?

在下面的測試代碼中,我有一個標志來確定是使用 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 時,下面的groupEditorProvidernull

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

我使用 Provider 已經有一段時間了,但對 ChangeNotifierProxyProvider 還是陌生的,所以很可能不了解一些基本的東西。

原來我沒有從我的GroupEditorProvider.update function 返回提供程序實例:

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

Flutter 是否應該為此拋出異常? 如果是這樣,我將發布到 github。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM