i am learning flutter and i just created an app that will update a counter variable when the user clicks on any part of the screen except the AppBar. However, the GestureDetector does not detect any clicks on the4 screen except for those on the text itself
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("i am a title"),
backgroundColor: Colors.teal,
leading: const Icon(
Icons.home,
color: Colors.white,
),
),
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: const [
Expanded(
child: Clicks(),
),
],
),
),
),
);
}
}
class Clicks extends StatefulWidget {
const Clicks({super.key});
@override
State<Clicks> createState() => _ClicksState();
}
class _ClicksState extends State<Clicks> {
int count = 0;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => setState(
() {
count++;
},
),
child: Center(
child: Text("total number of clicking on scren is $count "),
),
);
}
}
2
Answers
The
GestureDetector
will detect any gestures for it’s child – in this case theText
widget.If you want to detect everything, wrap the entrie Scaffold with a GestureDector.
In this case, you’ll have to refactor your code:
Try with below changes :