首页 > 解决方案 > 错误:没有为类“BuildContext”定义方法“ancestorStateOfType”

问题描述

如下使用类 Bloc 提供程序时,出现错误:

'没有为类型'BuildContext'定义方法'ancestorInheritedElementForWidgetOfExactType'。'

所以我替换了这条线context.ancestorInheritedElementForWidgetOfExactType(type)?.widget;

用这条线context.getElementForInheritedWidgetOfExactType<_BlocProviderInherited<T>>().widget;

但后来我收到以下错误:

Error output from Xcode build:
↳
** BUILD FAILED **

Xcode's output:
↳
../../../development/flutter/.pub-cache/hosted/pub.dartlang.org/dynamic_theme-1.0.1/lib/dynamic_theme.dart:25:20: Error: The method 'ancestorStateOfType' isn't defined for the class 'BuildContext'.
 - 'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('../../../development/flutter/packages/flutter/lib/src/widgets/framework.dart').
Try correcting the name to the name of an existing method, or defining a method named 'ancestorStateOfType'.
    return context.ancestorStateOfType(const TypeMatcher<DynamicThemeState>());
                   ^^^^^^^^^^^^^^^^^^^

Command PhaseScriptExecution failed with a nonzero exit code
note: Using new build system
note: Building targets in parallel
note: Planning build
note: Constructing build description

Could not build the precompiled application for the device.

Error launching application on iPhone 

这是我正在使用的 Bloc Provider:

class BlocProvider<T extends BlocBase> extends StatefulWidget {
   BlocProvider({
   Key key,
   @required this.child,
   @required this.bloc,}) : super(key: key);
   final Widget child;
   final T bloc;
   @override
   _BlocProviderState<T> createState() => _BlocProviderState<T>();

   static T of<T extends BlocBase>(BuildContext context) {
   final type = _typeOf<_BlocProviderInherited<T>>();
   _BlocProviderInherited<T> provider =
   context.ancestorInheritedElementForWidgetOfExactType(type)?.widget;
   return provider?.bloc;
  }
}

我在主频道 Flutter(频道主,1.26.0-2.0.pre.275)

标签: flutterbloc

解决方案


升级开发频道后几乎是同样的问题

.pub-cache/hosted/pub.dartlang.org/dynamic_theme-1.0.1/lib/dynamic_theme.dart:25:20: Error: The method 'ancestorStateOfType' isn't defined for the class 'BuildContext'.
'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('/home/liudmila/snap/flutter/common/flutter/packages/flutter/lib/src/widgets/framework.dart').
Try correcting the name to the name of an existing method, or defining a method named 'ancestorStateOfType'.

使用块 4.0.0

只需在文件 .pub-cache/../dynamic_theme.dart:25:20 中更改它

context.ancestorStateOfType()

在那

context.findAncestorStateOfType<DynamicThemeState>();

那是临时解决方案,但应用程序可以工作


推荐阅读