处理手势时引发了以下断言:Scaffold.of()在不包含Scaffold的上下文中调用

时间:2020-07-15 15:46:15

标签: flutter dart

import 'package:flutter/material.dart';

import 'dashboard.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SafeArea(
        child: Scaffold(
          appBar: AppBar(
            leading: IconButton(
              icon: Icon(Icons.accessible),
              onPressed: () => Scaffold.of(context).openEndDrawer(),
            ),
            title: Text('Sorted.'),
            backgroundColor: Color(0xff0A3D62),
          ),
          drawer: Drawer(
            child: ListView(
              padding: EdgeInsets.zero,
              children: <Widget>[
                new UserAccountsDrawerHeader(
                  accountName: new Text('XYZ'),
                  accountEmail: new Text('XYZ@gmail.com'),
                  currentAccountPicture: new CircleAvatar(),
                )
              ],
            ),
          ),
          body: Center(child: Home()),
        ),
      ),
    );
  }
}

错误:

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.

当我尝试从图标打开抽屉时,将引发错误。请帮我解决这个问题。预先感谢!

1 个答案:

答案 0 :(得分:0)

@ rkdupr0n正确地说您的context变量没有Scaffold祖先。 context当前是指外部build函数正在传递的内容,该函数没有Scaffold作为祖先,仅包含它。因此,您需要获得一个BuildContext,它具有Scaffold个作为祖先已经在您的树中拥有的支架。为此,您可以使用Builder小部件来包装需要此上下文的区域:

AppBar(
  leading: Builder(
    builder: (context) {//NEW CONTEXT OBTAINED HERE
      return IconButton(
        icon: Icon(Icons.accessible),
        onPressed: () => Scaffold.of(context).openEndDrawer(),
      );
    }
  ),
  ...
),