Scaffold.of() called with a context that does not contain a Scaffold.
错误原因:Scaffold.of()所需的context是Scaffold的,并不是Scaffold上方的build(BuildContext context)中的,这两个并不是一个。
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
elevation: 0,
leading: IconButton(
icon: Icon(Icons.keyboard_backspace),
onPressed: () {
Navigator.pop(context);
},
color: Colors.white,
),
backgroundColor: Color(0xff605167),
),
// 抽屉
drawer: new Drawer(
elevation: double.infinity,
child: Catalog(bookId: widget.book['_id']),
),
// 创建一个内部BuildContext,以便onPressed方法
// 可以通过Scaffold.of() 引用Scaffold。
body: Builder(
builder: (BuildContext context) {
return Container(
color: Color(0xffe2e2e2),
child: ListView(
children: <Widget>[
// 操作栏
Container(
width: double.infinity,
padding: EdgeInsets.only(bottom: 5.0),
color: Colors.white,
// 子组件,在子组件中可以正常调用Scaffold.of()
child: buildOpera(context), // 传递context
) ],
),
);
},
));
}
子组件
Widget buildOpera(BuildContext context) {
return Row(
children: <Widget>[
new Expanded(
child: new GestureDetector(
onTap: () {
// 在这里可以正常调用 Scaffold.of(context).openDrawer();来关闭抽屉
Scaffold.of(context).openDrawer();
debugPrint('目录');
},
child: Column(
children: <Widget>[
Container(
height: 30.0,
child: IconButton(
icon: Icon(Icons.format_list_bulleted),
)),
Text(
'${widget.book['chaptersCount']}章',
style: TextStyle(fontSize: 12.0),
)
],
),
)),
],
);
}