简体   繁体   English

如何在 Flutter 中将小部件设置为按钮

[英]How to set a widget as a button in Flutter

I set two widgets in a Stack(), the one in the back is a sidebar and the one in the front is my main page.我在 Stack() 中设置了两个小部件,后面的一个是侧边栏,前面的一个是我的主页。
When I click on the menu button from the main page, the main page gets shifted to the right and then the user can see the sidebar.当我从主页单击菜单按钮时,主页会向右移动,然后用户可以看到侧边栏。

在此处输入图像描述

Now the problem is when the sidebar gets displyed i'm obliged to click exactly on the menu button to go back to the main page.现在的问题是,当显示侧边栏时,我必须准确地单击菜单按钮 go 回到主页。
What i want to do is just to click anywhere in the main page to hide the sidebar.我想要做的只是单击主页中的任意位置以隐藏侧边栏。
I mean that i want to set the whole main page as a button when the sidebar is displayed.我的意思是我想在显示侧边栏时将整个主页设置为按钮。

You can use InkWell您可以使用InkWell

     InkWell(
        onTap: (){
         /// do something
        },
        child: Text('data')  /// your widget,
      ),

You can also use GestureDetector您还可以使用GestureDetector

Generally if you want to make anything tappable you can just wrap the widget with GestureDetector一般来说,如果你想制作任何可点击的东西,你可以用 GestureDetector 包装小部件

I fixed it by wrapping the main page with InkWell() and I added this to the onTap property"我通过用 InkWell() 包裹主页来修复它,并将它添加到 onTap 属性中”

      InkWell(
        onTap: isSidebarCollapsed ? () {
          setState(() {
            isSidebarCollapsed = false;
          });
        } : null,
        child: Container(...)
      )

Note that isSidebarCollapsed is the variable that determines if the menu is displayed or not.请注意,isSidebarCollapsed 是确定是否显示菜单的变量。

Explaination of the code:代码说明:
If the sidebar is collapsed (is displayed) then the onTap property returns a function where I set the variable isSidebarCollapsed to false (to say that the sidebar is gonna be hidden).如果侧边栏被折叠(显示),则 onTap 属性返回一个 function 我将变量 isSidebarCollapsed 设置为 false(表示侧边栏将被隐藏)。
Else it returns null否则返回null

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

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