Drawer是自定义小部件MenuDrawer().它位于BottomNavigationBar号楼的同一层.这样做使得当打开新屏幕时,它们不显示BottomNavigationBar,并且屏幕的整个表面是干净的.这是有效的,但只有当我try 从BottomNavigationBar内的下一个小部件调用抽屉时.这可以使用Scaffold.of(context).openDrawer()来完成

但是,如果我试图从嵌套在内部的小部件中调用Drawer,那么它就不起作用了. 我试着用我找到的所有小贴士,用builderScaffold.of(context).openEndDrawer().context is lost和抽屉好像打不开了.如果你有什么 idea ,或者我错过了什么,我将不胜感激.

@override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _systemBackButtonPressed,
      child: Scaffold(
        drawer: const MenuDrawer(),
        bottomNavigationBar: BottomNavigationBar(...),
          ],
          currentIndex: _selectedIndex,
          onTap: _onItemTapped,
        ),
        body: SafeArea(
          top: false,
          child: IndexedStack(
            index: _selectedIndex,
            children: const <Widget>[
              MenuNavigator(),
              CabinetNavigator(),
              SearchNavigator(),
              ContactsNavigator(),
              CartNavigator()
            ],
          ),
        ),
      ),
    );
  }

推荐答案

您可以创建一个全局键变量并将其传递到此处.

例如

final GlobalKey<ScaffoldState> globalScaffoldKey = GlobalKey();

class YourMainScreen extends StatefulWidget {
  const YourMainScreen({Key? key}) : super(key: key);

  @override
  State<YourMainScreen> createState() => _YourMainScreenState();
}

class _YourMainScreenState extends State<YourMainScreen> {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _systemBackButtonPressed,
      child: Scaffold(
        key: globalScaffoldKey, // Global Key
        drawer: const MenuDrawer(),
        bottomNavigationBar: BottomNavigationBar(...),
          ],
          currentIndex: _selectedIndex,
          onTap: _onItemTapped,
        ),
        body: SafeArea(
          top: false,
          child: IndexedStack(
            index: _selectedIndex,
            children: const <Widget>[
              MenuNavigator(),
              CabinetNavigator(),
              SearchNavigator(),
              ContactsNavigator(),
              CartNavigator()
            ],
          ),
        ),
      ),
    );
  }
}

然后,您可以通过调用从任何位置打开抽屉

globalScaffoldKey.currentState!.openDrawer()

Flutter相关问答推荐

无法在Flatter中设计正确的布局

Flutter 对齐:不适用于多行文字

我想在Flutter中画一个箭头,但我似乎无法填满空间

Flex ListView用于可滚动和响应的页面

Flutter 块消费者仅对特定的状态属性更改做出react

如何管理枚举类型的阻塞事件?

有没有可能不在BlocBuilder中重新构建内容?

Flutter如何将2个以上的值传递到ListView上的另一个屏幕?

我无法找到修复此错误的位置,指出无法使用静态访问来访问实例成员

点击按钮后重新启动定时器

什么最接近 Dart 的 List.asMap().forEach() 返回列表?

当我使用 Confetti Widget 时,Flutter Android 和 IOS 应用程序崩溃

如何使用 riverpod_annotation 创建非自动处置提供程序?

在 flutter 的另一个类中使用变量值

为什么 orientation == Orientation.portrait 总是正确的,尽管我的设备已经处于横向

我一直在try 创建按钮以导航到第二页,但不知何故 RaisedButton 功能无法正常工作

Android Studio 模拟器屏幕闪烁

如何在 ElevatedButton 上设置背景 colored颜色 动画?

如何验证位于 PageView 内不同页面的 TextFormFields

如何在 IntroductionScreen 小部件 Flutter 中制作全屏渐变色