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

class TestWidget extends State {

  @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 {

  @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"),
                ),
            ),
        },
      ),
    );
  }

 

你可能感兴趣的:(flutter)