问题描述
嗨,我如何访问小部件中的上下文,下面是代码。在顶部布局的小部件中,我在IconButton上具有onclick的期望值。那么如何使上下文可用于该onClick?
Widget toplayout = new Container(
width: 70,height: 70,color: Colors.white,child: new Row(
crossAxisAlignment: CrossAxisAlignment.center,children: <Widget>[
new IconButton(
icon: Icon(Icons.arrow_back),iconSize: 30,onpressed: () {
// Here i want context
if (Navigator.canPop(context)) {
Navigator.pop(context);
} else {
SystemNavigator.pop();
}
},),new Container(
margin: const EdgeInsets.fromLTRB(20,0),child: new Text("Day 1",style: new TextStyle(
fontSize: 30,color: Colors.black,)))
],);
解决方法
您必须使用Builder类包装IconButton:
Builder(builder: (context) => IconButton(
icon: Icon(Icons.arrow_back),iconSize: 30,onPressed: () {
// Here i want context
if (Navigator.canPop(context)) {
Navigator.pop(context);
} else {
SystemNavigator.pop();
}
},),)