Flutter:Scaffold.of() called with a context that does not contain a Scaffold.

Flutter:Scaffold.of() called with a context that does not contain a Scaffold.在这里插入图片描述

当我第一次点击按钮想要弹出底部消息时出现了如下错误

@override
  Widget build(BuildContext context) {
    
    
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text('SnackBar'),
        leading: IconButton(
          icon: Icon(Icons.chevron_left),
          onPressed: () {
    
    
            Navigator.pop(context);
          },
        ),
      ),
      body: Container(
        alignment: Alignment.center,
        child: Column(
          children: <Widget>[
            RaisedButton(
              onPressed: () {
    
    
                Scaffold.of(context).showSnackBar(
                  SnackBar(
                    content: Text('测试'),
                  ),
                );
              },
            )
          ],
        ),
      ),
    );
  }

当BuildContext在Scaffold之前时,调用Scaffold.of(context)会报错。这时可以通过Builder Widget来解决,代码如下:

  @override
  Widget build(BuildContext context) {
    
    
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text('SnackBar'),
        leading: IconButton(
          icon: Icon(Icons.chevron_left),
          onPressed: () {
    
    
            Navigator.pop(context);
          },
        ),
      ),
      body: Container(
        alignment: Alignment.center,
        child: Column(
          children: <Widget>[
            Builder(
              builder: (BuildContext context) {
    
    
                return Center(
                  child: RaisedButton(
                    onPressed: () {
    
    
                      Scaffold.of(context).showSnackBar(
                        SnackBar(
                          content: Text('测试'),
                        ),
                      );
                    },
                  ),
                );
              },
            )
          ],
        ),
      ),
    );
  }

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_46005137/article/details/107346260