Kyrylo Petrenko
Kyrylo Petrenko

Reputation: 147

GestureDetector detects clicks only on widget inside

I need my app to change background color to any random color when I tap anywhere on the screen. I was trying to use GestureDetector but it only works when I tap on the text and I can't get why that's happening.

class _MyAppState extends State<MyApp> {
Color _color;

void changeColor() {
setState(() => _color = Colors.primaries[Random().nextInt(Colors.primaries.length)]);
}



@override
Widget build(BuildContext context) {
return Scaffold(
  body: GestureDetector(
  onTap: () => changeColor(),
  child: Container(
    color: _color,
    child: Center(
      child: Text('Hey there'),
    ),
  ),
),
);
}
}

Upvotes: 1

Views: 1257

Answers (2)

Deepak Lohmod
Deepak Lohmod

Reputation: 2282

simply add the behaviour to it as opaque this will allow it to detect gesture outside the child.

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () => changeColor(),
      child: Container(
        color: _color,
        child: Center(
          child: Text('Hey there'),
        ),
      ),
    ),
  );
}

Upvotes: 3

Fatima ayaa
Fatima ayaa

Reputation: 650

add behavior: HitTestBehavior.translucent to your GestureDetector

 body: GestureDetector(
                behavior: HitTestBehavior.translucent, // add this
              onTap: () => changeColor(),
              child: Container(
                color: _color,
                child: Center(
                  child: Text('Hey there'),
                ),
              ),
            ),

Upvotes: 0

Related Questions