问题说明
在阅读《flutter实战》这本书的第二章Widget简介的时候,自己试了下Context参数的实例,发现无法运行,实例如下:
class ContextRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Context测试"),
),
body: Container(
child: Builder(builder: (context) {
// 在 widget 树中向上查找最近的父级`Scaffold` widget
Scaffold scaffold = context.findAncestorWidgetOfExactType<Scaffold>();
// 直接返回 AppBar的title, 此处实际上是Text("Context测试")
return (scaffold.appBar as AppBar).title;
}),
),
);
}
}
在findAncestorWidgetOfExactType函数和下面调用AppBar的时候会报错。
查看文档发现findAncestorWidgetOfExactType接口已经变化。类型需要定义为T?。
如果提示The return type ‘Widget?’ isn’t a ‘Widget’, as required by the closure’s context.,则需要在Widget对象后面加上感叹号。
后面修改如下:
Scaffold? scaffold = context.findAncestorWidgetOfExactType<Scaffold>();
return (scaffold!.appBar as AppBar).title!;
注意下面的两个感叹号哦!!!
参考:
1.一文搞懂 BuildContext
2.The return type ‘Widget?’ isn’t a ‘Widget’, as required by the closure’s context