将 onTap 监听器添加到 appBar (Flutter)

Emi*_*ess 2 dart flutter

我们需要为 appBar 添加 onTap 监听器。不是actionsleading按钮。我们需要它用于所有 appBar。我尝试使用InkWell,但它有视觉效果,我们不需要它。我尝试使用GestureDetector,但只有当用户点击 this 中的文本时才有效GestureDetector

Rao*_*che 7

有几种方法可以做到这一点 。我认为创建自定义应用程序栏是一个好方法

例子 :

return Scaffold(
  appBar: CustomAppBar(
    appBar: AppBar(title: Text("hello"),),
    onTap: () {
      print("test");
    },
  ),
  body: Container(),
);
Run Code Online (Sandbox Code Playgroud)

要创建自定义应用栏,您需要实现 PreferredsizeWidget

class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
  final VoidCallback onTap;
  final AppBar appBar;

  const CustomAppBar({Key key, this.onTap,this.appBar}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return  GestureDetector(onTap: onTap,child: appBar);
  }

  // TODO: implement preferredSize
  @override
  Size get preferredSize => new Size.fromHeight(kToolbarHeight);
}
Run Code Online (Sandbox Code Playgroud)


Vik*_*Jr. 6

    return Scaffold(

      appBar: AppBar(
        flexibleSpace: GestureDetector(
         onTap: (){...do something...}),
      ),
Run Code Online (Sandbox Code Playgroud)