Flutter SDK更新后,经常会出现一些错误。尤其是Flutter 2.0,有些API也跟着变动了,真是牵一发而动全身啊,非常坑。
以下是我更新2.0后老项目的报错解决方法。
错误列表
- 报错信息:Error: No named parameter with the name 'resizeToAvoidBottomPadding'
- BuildContext方法改动
- 报错信息:The method ‘ancestorWidgetOfExactType‘ isn‘t defined for the type ‘BuildContext‘
- 报错信息:Error: The method 'ancestorStateOfType' isn't defined for the class 'BuildContext'.
- 报错信息:Error: The method 'inheritFromWidgetOfExactType' isn't defined for the class 'BuildContext'.
- 报错信息:Error: Method not found: 'TypeMatcher'.
- 报错信息:Error: No named parameter with the name 'nullOk'.
- 报错信息:Error: Method not found: 'CupertinoPageRoute.buildPageTransitions'.
- 报错信息:Error: The getter 'title' isn't defined for the class 'TextTheme'
- 报错信息:Error: The getter 'body1' isn't defined for the class 'TextTheme'.
报错信息:Error: No named parameter with the name ‘resizeToAvoidBottomPadding’
原因:resizeToAvoidBottomPadding在新版本的Scaffold中被resizeToAvoidBottomInset属性取代了,替换即可。
Scaffold(
// resizeToAvoidBottomPadding: false,
resizeToAvoidBottomInset: false,
..........
)
BuildContext方法改动
报错信息:The method ‘ancestorWidgetOfExactType‘ isn‘t defined for the type ‘BuildContext‘
原因:BuildContext的ancestorWidgetOfExactType被findAncestorStateOfType替代,并且没有了参数,在泛型中传入需要获取的Widget即可。
ancestorWidgetOfExactType ----> findAncestorWidgetOfExactType
// SliverAppBar sliverAppBar = context.ancestorWidgetOfExactType(SliverAppBar);
SliverAppBar sliverAppBar = context.findAncestorStateOfType<SliverAppBar>();
报错信息:Error: The method ‘ancestorStateOfType’ isn’t defined for the class ‘BuildContext’.
2.0之前的写法
ComplexLayoutState state = context.ancestorStateOfType(const TypeMatcher<ComplexLayoutState>()) as ComplexLayoutState;
2.0之后的用法
ComplexLayoutState state = context.ancestorStateOfType<ComplexLayoutState>();
报错信息:Error: The method ‘inheritFromWidgetOfExactType’ isn’t defined for the class ‘BuildContext’.
原因:dependOnInheritedWidgetOfExactType()被dependOnInheritedWidgetOfExactType替代,并且参数是个可选命名参数,需要加上aspect。
// context.dependOnInheritedWidgetOfExactType(_xxxProvider)
context.dependOnInheritedWidgetOfExactType(aspect: _xxxProvider)
报错信息:Error: Method not found: ‘TypeMatcher’.
2.0中,TypeMatcher
这个类已经被移除,ancestorStateOfType
方法中也没有TypeMatcher
这个参数了。
报错信息:Error: No named parameter with the name ‘nullOk’.
原因:在Flutter2.0中,很多类的of(..)
静态方法中的nullok参数被移除了,比如Scaffold.of()
、Localizations.localeOf()
、Navigation.of()
,都不需要nullok参数了。
// final ScaffoldState scaffold = Scaffold.of(context, nullOk: true);
final ScaffoldState scaffold = Scaffold.of(context);
// Localizations.localeOf(context, nullOk: true);
Localizations.localeOf(context);
报错信息:Error: Method not found: ‘CupertinoPageRoute.buildPageTransitions’.
报错信息:Error: The getter ‘title’ isn’t defined for the class ‘TextTheme’
widget.textTheme?.title
报错信息:Error: The getter ‘body1’ isn’t defined for the class ‘TextTheme’.
widget.textTheme?.body1