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 {
   @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('我是第一个页面'),),
      body: Center(
        child: Column(
          children: [
            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 {
   @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('我是第一个页面'),),
      body: Center(
        child: Column(
          children: [
            RaiseMyButton()
          ],
        ),
      ),
    );
  }
}

class RaiseMyButton extends StatelessWidget{
    @override 
    Widget build(BuildContext context) {
    // TODO: implement build
    return Column(
      children: [
        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)