简体   繁体   English

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

[英]How to hide appBar using GestureDetector in Flutter?

I have been trying to hide the AppBar in Flutter using GestureDetector widget whenever I tap on the screen.每当我点击屏幕时,我一直试图使用 GestureDetector 小部件隐藏 Flutter 中的 AppBar。

But it's not working.但它不起作用。 Following are my codes:以下是我的代码:

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,
    );
  }
}

What's going on here?这里发生了什么?

You must move bool _showAppBar = true;你必须移动bool _showAppBar = true; to be outside the build of the widget.在小部件的构建之外。 When state updates, it rebuilds the widget.当 state 更新时,它会重建小部件。 Hence you always end up with true on the variable.因此,您总是以变量为真。 Like this:像这样:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM