如何在 Flutter 中使用 GestureDetector 隐藏 appBar?

How to hide appBar using GestureDetector in Flutter?

每当我点击屏幕时,我一直在尝试使用 GestureDetector 小部件在 Flutter 中隐藏 AppBar。

但它不起作用。以下是我的代码:

import 'package:flutter/material.dart';

// This is the page widget
class PageWidget extends StatefulWidget {
  final String title;
  PageWidget({Key key, this.title}) : super(key: key);

  @override
  _PageWidgetState createState() => _PageWidgetState();
}

class _PageWidgetState extends State<PageWidget> {
  Widget build(BuildContext context) {
    // making the AppBar
    bool _showAppBar = true;
    final appBar = AppBar(
      title: Text("Page one"),
      centerTitle: true,
      backgroundColor: Colors.teal,
    );
    final body = Container(
      child: GestureDetector(
        onTap: () {
          setState(() => {_showAppBar = !_showAppBar});
          print("This GestureDetector");
        },
        behavior: HitTestBehavior.translucent,
        // content of the page.
        child: SingleChildScrollView(
        ),
      ),
    );
    
    return Scaffold(
      appBar: _showAppBar ? appBar : null,
      body: body,
    );
  }
}

这是怎么回事?

您必须将 bool _showAppBar = true; 移动到小部件的构建之外。当状态更新时,它会重建小部件。因此,您总是在变量上以 true 结束。像这样:

class _PageWidgetState extends State<PageWidget> {
  bool _showAppBar = true;

  Widget build(BuildContext context) {
    final appBar = AppBar(
      title: Text("Page one"),
      centerTitle: true,
      backgroundColor: Colors.teal,
    );