點擊按鈕關閉Drawer報錯:Scaffold.of() called with a context that does not contain a Scaffold.

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

錯誤原因:Scaffold.of()所需的context是Scaffold的,並不是Scaffold上方的build(BuildContext context)中的,這兩個並不是一個。

 Widget build(BuildContext context) {
    return new Scaffold(
        appBar: AppBar(
          elevation: 0,
          leading: IconButton(
            icon: Icon(Icons.keyboard_backspace),
            onPressed: () {
              Navigator.pop(context);
            },
            color: Colors.white,
          ),
          backgroundColor: Color(0xff605167),
        ),
        // 抽屜
        drawer: new Drawer(
          elevation: double.infinity,
          child: Catalog(bookId: widget.book['_id']),
        ),
        // 創建一個內部BuildContext,以便onPressed方法
		// 可以通過Scaffold.of() 引用Scaffold。
        body: Builder(
          builder: (BuildContext context) {
            return Container(
              color: Color(0xffe2e2e2),
              child: ListView(
                children: <Widget>[
                  // 操作欄
                  Container(
                    width: double.infinity,
                    padding: EdgeInsets.only(bottom: 5.0),
                    color: Colors.white,
                    // 子組件,在子組件中可以正常調用Scaffold.of()
                    child: buildOpera(context), // 傳遞context
                  ) ],
              ),
            );
          },
        ));
  }
子組件
Widget buildOpera(BuildContext context) {
    return Row(
      children: <Widget>[
        new Expanded(
            child: new GestureDetector(
          onTap: () {
          // 在這裏可以正常調用 Scaffold.of(context).openDrawer();來關閉抽屜
            Scaffold.of(context).openDrawer();
            debugPrint('目錄');
          },
          child: Column(
            children: <Widget>[
              Container(
                  height: 30.0,
                  child: IconButton(
                    icon: Icon(Icons.format_list_bulleted),
                  )),
              Text(
                '${widget.book['chaptersCount']}章',
                style: TextStyle(fontSize: 12.0),
              )
            ],
          ),
        )),
      ],
    );
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章