本文主要是介绍Flutter错误总结1:Scaffold.of() called with a context that does not contain a Scaffold.,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在这里插入代码片## 1.Scaffold.of() called with a context that does not contain a Scaffold.
错误出现的场景: 使用Navigator 从第二个页面向第一个页面返回值
class HomePage extends StatelessWidget {@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text('我是第一个页面'),),body: Center(child: Column(children: <Widget>[RaisedButton(child: Text('点我进入下一页面'),onPressed: (){_navigateToSecondPage(context);},)],),),);}_navigateToSecondPage(BuildContext context) async {final result = await Navigator.push(context, MaterialPageRoute(builder: (context)=> SecondPage(),));Scaffold.of(context).showSnackBar(SnackBar(content: Text('$result'),));}
}
修改后
class HomePage extends StatelessWidget {@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text('我是第一个页面'),),body: Center(child: Column(children: <Widget>[RaiseMyButton()],),),);}
}class RaiseMyButton extends StatelessWidget{@override Widget build(BuildContext context) {// TODO: implement buildreturn Column(children: <Widget>[RaisedButton(child: Text('点我进入下一页面'),onPressed: (){_navigateToSecondPage(context);},)], );}_navigateToSecondPage(BuildContext context) async {final result = await Navigator.push(context, MaterialPageRoute(builder: (context)=> SecondPage(),));Scaffold.of(context).showSnackBar(SnackBar(content: Text('$result'),));}
}
原因: of method
需要将RaiseButton剥离出来,因为build方法如果嵌套build后,接收不到外层的context参数
这篇关于Flutter错误总结1:Scaffold.of() called with a context that does not contain a Scaffold.的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!