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’异常。该异常通常发生在BuildContext未包含Scaffold时调用Scaffold.of(context)。为解决问题,你需要确保在正确的位置和上下文中使用Scaffold.of()。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class TestWidget extends State<TestWidget> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Widget简介")),
      body: Center(
          child:RaisedButton(
            onPressed: () {
              Scaffold.of(context).showSnackBar( SnackBar(
                content: Text("我是SnackBar"),
              ),);
            },
            child: Text("显示SnackBar"),
          ),
      ),
    );
  }

出现异常如下:

The following assertion was thrown while handling a gesture:
Scaffold.of() called with a context that does not contain a Scaffold.

No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). This usually happens when the context provided is from the same StatefulWidget as that whose build function actually creates the Scaffold widget being sought.
There are several ways to avoid this problem. The simplest is to use a Builder to get a context that is "under" the Scaffold. For an example of this, please see the documentation for Scaffold.of():
  https://api.flutter.dev/flutter/material/Scaffold/of.html
A more efficient solution is to split your build function into several widgets. This introduces a new context from which you can obtain the Scaffold. In this solution, you would have an outer widget that creates the Scaffold populated by instances of your new inner widgets, and then in these inner widgets you would use Scaffold.of().
A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, then use the key.currentState property to obtain the ScaffoldState rather than using the Scaffold.of() function.

原因 :BuildContext在Scaffold之前,调用Scaffold.of(context)会报错

解决:

class TestWidget extends State<TestWidget> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Widget简介")),
      body: Builder(
        builder: (BuildContext context) {
          return Center(
            child: RaisedButton(
                  onPressed: () {
                    Scaffold.of(context).showSnackBar(
                      new SnackBar(
                        content: Text("我是SnackBar"),
                      ),
                    );
                  },
                  child: Text("显示SnackBar"),
                ),
            ),
        },
      ),
    );
  }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值