Flutter:名为 'read' 的成员在扩展名 'ReadContext' 和 'BuildContextX' 中定义,两者都不是更具体

Flutter : A member named 'read' is defined in extensions 'ReadContext' and 'BuildContextX' and neither is more spesific

我的应用程序中有一个按钮 return :

onPressed: () {
                    return context
                        .read(FavoriteIds.provider.notifier)
                        .toggle(doa.id.toString());
                  },

在这种情况下,我使用了 riverpod 提供商。但是当我想导入一个 flutter_bloc 包时,read 关键字会出现此消息的错误 A member named 'read' is defined in extensions 'ReadContext' and 'BuildContextX' and neither is more specific. Try using an extension override to specify the extension you want to to be chosen.

请帮我解决这个问题。谢谢:)

这意味着您正在导入 2 个扩展,它们都提供相同的方法 read。考虑这个例子:

extension Ext1 on String {
  void foo() => print("from extension 1");
}

extension Ext2 on String {
  void foo() => print("from extension 2");
}

void main() {
  String s = "hello";
  s.foo();
}

这段代码应该打印什么?没有明显的答案,为了避免意外的编程错误,Dart 禁止这样做。

您可以在 read 方法上尝试“转到定义”(ctrl/cmd 在大多数 IDE 中单击)以导航到定义它的文件之一,然后删除相应的导入语句。

但是,删除该文件中的所有导入语句并使用自动完成将它们添加回来可能会更快

这里的问题是 read()ReadContextBuildContextX 扩展中都有定义。所以编译器没有得到要使用的扩展名。

要解决错误,请使用:ReadContext(context).read 如果您想访问 bloc 或 BuildContextX(context).read() 根据您的需要。