所以我的脚手架上有一把脚手架 keys :

final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

在我的脚手架上,我有一个定制抽屉和一个定制应用程序栏:

Scaffold(
    key: _scaffoldKey,
    backgroundColor: Color(0xFF3FC1C9),
    drawer: HomeDrawer(),
    body: StartAppBar(_scaffoldKey.currentState?.openDrawer),
  ),

我将打开抽屉功能传递给自定义应用程序栏.我的自定义AppBar接受如下功能:

 class StartAppBar extends StatelessWidget {
      void Function()? openDrawer;
      StartAppBar(this.openDrawer);
    and references it here:
    
        leading: IconButton(
          onPressed: () {
            openDrawer!();
            // _key.currentState!.openEndDrawer();
          },
          icon: Icon(
            Icons.view_headline_rounded,
          ),
        ),

问题是抽屉从一开始就无法打开.当我通过点击我的底部栏(下面的代码)切换屏幕主体时,抽屉打开了.我猜当我第一次加载应用程序时,我的密钥有一个空值,结果抽屉没有打开.如果是这样的话,我需要为键设置一个默认值.整个代码如下.


这就是全部代码,也许它比简化的代码更相关:

我创建密钥的类如下所示:

class HomeScreen extends StatefulWidget {
  final marken;
  const HomeScreen({Key? key, this.marken}) : super(key: key);
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  late List<Widget> _widgetOptions;

  @override
  initState() {
    _widgetOptions = <Widget>[
      Favorites(),
      BodyHomeScreen(
        marken: widget.marken,
      ),
      Kontakt(),
    ];
  }

  DateTime? lastPressed;
  final HideNavbar hiding = HideNavbar();
  int _selectedIndex = 1;

  void _onItemTap(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
      child: Scaffold(
        key: _scaffoldKey,
        backgroundColor: Color(0xFF3FC1C9),
        drawer: HomeDrawer(),
        body: StartAppBar(_selectedIndex, hiding, lastPressed, _widgetOptions,
            _scaffoldKey.currentState?.openDrawer),
        bottomNavigationBar: BottomBar(
          _onItemTap,
          _selectedIndex,
          hiding,
        ),
      ),
    );
  }
}

如上图所示,我将 keys 传给StartAppBar,如下所示:

import 'package:flutter/material.dart';

class StartAppBar extends StatelessWidget {
  final int selectedIndex;
  final hiding;
  List<Widget> widgetOptions;
  var lastPressed;
  void Function()? openDrawer;
  StartAppBar(this.selectedIndex, this.hiding, this.lastPressed,
      this.widgetOptions, this.openDrawer);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        final now = DateTime.now();
        final maxDuration = Duration(seconds: 2);
        final isWarning =
            lastPressed == null || now.difference(lastPressed!) > maxDuration;

        if (isWarning) {
          lastPressed = DateTime.now();

          final snackBar = SnackBar(
            content: Container(
              //color: Colors.white,
              decoration: BoxDecoration(
                  color: Color(0xFF03DAC6),
                  borderRadius: BorderRadius.circular(20)),
              margin: EdgeInsets.fromLTRB(0, 0, 0, 20),
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  'Doppelklick zum verlassen',
                  textAlign: TextAlign.center,
                ),
              ),
            ),
            backgroundColor: Colors.transparent,
            elevation: 1000,
            behavior: SnackBarBehavior.floating,
            duration: maxDuration,
          );

          ScaffoldMessenger.of(context)
            ..removeCurrentSnackBar()
            ..showSnackBar(snackBar);

          return false;
        } else {
          return true;
        }
      },
      child: CustomScrollView(
        controller: hiding.controller,
        slivers: [
          SliverAppBar(
            backgroundColor: Color(0xFF3FC1C9),
            automaticallyImplyLeading: false,
            elevation: 0,
            title: Text(
              "AutoLab",
              style:
                  TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
            ),
            leading: IconButton(
              onPressed: () {
                openDrawer?.call();
                // _key.currentState!.openEndDrawer();
              },
              icon: Icon(
                Icons.view_headline_rounded,
              ),
            ),
            centerTitle: true,
            expandedHeight: 120,
            floating: false,
            flexibleSpace: FlexibleSpaceBar(
              title: selectedIndex == 1
                  ? Text("Marke auswählen")
                  : selectedIndex == 2
                      ? Text("Schreibe uns!")
                      : Text("Deine Modelle"),
              centerTitle: true,
            ),
          ),
          SliverToBoxAdapter(child: widgetOptions.elementAt(selectedIndex)),
        ],
      ),
    );
  }
}

有什么办法可以纠正这种行为吗?

推荐答案

你没有必要创建一个GlobalKey,你只需要写以下内容:

onPressed: () {
    Scaffold.of(context).openDrawer();
},

因为在你的小部件树中,你已经只有一个脚手架了,所以你不需要用一个键使它唯一,这样你的图标按钮就知道要打开哪个脚手架和抽屉.

现在剩下的就是移除void Function()? openDrawer;

Flutter相关问答推荐

Android元数据为1.9.0,预期版本为1.7.1,如何解决flutter应用程序构建失败问题?

类型int不是可迭代动态tmdbapi类型的子类型<>

SingleChildScrollView正在将Container的高度限制为子对象,尽管使用了Expanded Inside Row()

Flutter 中的面向对象模式

Flutter为什么不;没有ListView.iterable()构造函数?

如何在Dart中允许正则表达式中有一个空格,但允许其他字符为1或更多?

如何使 dart 函数变得通用?

如何在点击查看措辞下方添加句子?

如何对齐 AppBar Actions 中的文本?

在 Dart 中按土耳其语字母顺序对字符串进行排序

在Flutter中为容器实现线性渐变背景动画

为什么我们需要使用ChangeNotifierProvider而不是仅仅使用ChangeNotifier?

在 Flutter 中显示有关提供者通知的对话框

如何修复 ICU Lexing 错误:Flutter 中的意外字符

通过点击缩略图加载全屏图像

如何在 Flutter 中创建 Facebook 创建帖子屏幕?

更改文本字段Flutter 中最大字母的 colored颜色

Flutter 中的无效日期格式 2022 年 11 月 14 日

Android Studio 模拟器屏幕闪烁

带图像封面的 ElevatedButton