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

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章