Bird
Raised Fist0
Fluttermobile~20 mins

GestureDetector in Flutter - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
GestureDetector Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate
2:00remaining
Tap Gesture Detection Output
What will be the output when the user taps the blue container in this Flutter app?
Flutter
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(
        body: Center(
          child: GestureDetector(
            onTap: () {
              print('Container tapped');
            },
            child: Container(
              width: 100,
              height: 100,
              color: Colors.blue,
            ),
          ),
        ),
      ),
    );
  }
}
ANothing visible changes on screen, but 'Container tapped' is printed in the console.
BThe app crashes with a runtime error.
CThe blue container changes color to red when tapped.
DA popup dialog appears saying 'Container tapped'.
Attempts:
2 left
💡 Hint
Check what the onTap callback does in the GestureDetector.
❓ lifecycle
intermediate
2:00remaining
GestureDetector onLongPress Behavior
What happens when the user presses and holds the green container for 2 seconds in this Flutter app?
Flutter
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String message = 'Hold the box';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: GestureDetector(
            onLongPress: () {
              setState(() {
                message = 'Long pressed!';
              });
            },
            child: Container(
              width: 150,
              height: 150,
              color: Colors.green,
              alignment: Alignment.center,
              child: Text(message, style: const TextStyle(color: Colors.white)),
            ),
          ),
        ),
      ),
    );
  }
}
ANothing happens because onLongPress is not a valid GestureDetector callback.
BThe text inside the green box changes to 'Long pressed!' after holding for 2 seconds.
CThe app throws a setState error because message is not mutable.
DThe green box disappears from the screen.
Attempts:
2 left
💡 Hint
onLongPress triggers when the user presses and holds the widget.
❓ navigation
advanced
2:00remaining
GestureDetector and Navigation Behavior
What happens when the user taps the red container in this Flutter app?
Flutter
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(
        body: Center(
          child: GestureDetector(
            onTap: () {
              Navigator.of(context).push(MaterialPageRoute(
                builder: (context) => const SecondScreen(),
              ));
            },
            child: Container(
              width: 120,
              height: 120,
              color: Colors.red,
              alignment: Alignment.center,
              child: const Text('Tap me', style: TextStyle(color: Colors.white)),
            ),
          ),
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  const SecondScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Second Screen')),
      body: const Center(child: Text('Welcome to the second screen!')),
    );
  }
}
AThe app navigates to a new screen showing 'Welcome to the second screen!'.
BNothing happens because Navigator.of(context) cannot be used inside GestureDetector.
CThe app crashes with a runtime error about context.
DThe red container changes color to blue.
Attempts:
2 left
💡 Hint
Navigator.of(context).push opens a new screen on tap.
📝 Syntax
advanced
2:00remaining
GestureDetector Syntax Error Identification
Which option contains a syntax error that will prevent the Flutter app from compiling?
Flutter
GestureDetector(
  onTap: () {
    print('Tapped');
  },
  child: Container(
    width: 100,
    height: 100,
    color: Colors.yellow,
  ),
)
AGestureDetector(onTap: () { print('Tapped'); }, child: Container(width: 100, height: 100, color: Colors.yellow))
B))wolley.sroloC :roloc ,001 :thgieh ,001 :htdiw(reniatnoC :dlihc ,} ;)'deppaT'(tnirp { )( :paTno(rotceteDerutseG
CGestureDetector(onTap: () => print('Tapped'), child: Container(width: 100, height: 100, color: Colors.yellow))
DGestureDetector(onTap: () { print('Tapped') child: Container(width: 100, height: 100, color: Colors.yellow))
Attempts:
2 left
💡 Hint
Look for missing punctuation or brackets.
🔧 Debug
expert
2:00remaining
Why does GestureDetector not detect taps?
Given this Flutter code, why does tapping the container not trigger the onTap callback?
Flutter
GestureDetector(
  onTap: () {
    print('Tapped');
  },
  child: Container(
    width: 100,
    height: 100,
    color: Colors.transparent,
  ),
)
ABecause GestureDetector only works with visible widgets that have text.
BBecause onTap requires the container to have a GestureRecognizer explicitly attached.
CBecause the container's color is transparent, it does not receive pointer events, so GestureDetector doesn't detect taps.
DBecause the onTap callback must be async to work properly.
Attempts:
2 left
💡 Hint
Try changing the container's color to a non-transparent color.

Practice

(1/5)
1. What is the primary purpose of the GestureDetector widget in Flutter?
easy
A. To detect user touch gestures like taps and swipes on its child widget
B. To display images and icons on the screen
C. To manage app navigation between screens
D. To style text with different fonts and colors

Solution

  1. Step 1: Understand GestureDetector's role

    The GestureDetector widget listens for user touch gestures such as taps, double taps, long presses, and drags on its child widget.
  2. Step 2: Compare with other options

    Displaying images and icons, managing app navigation, and styling text are handled by other widgets like Image/Icon, Navigator/Router, and TextStyle, not GestureDetector.
  3. Final Answer:

    To detect user touch gestures like taps and swipes on its child widget -> Option A
  4. Quick Check:

    GestureDetector = Detects touch gestures [OK]
Hint: GestureDetector listens for user touches on child widgets [OK]
Common Mistakes:
  • Confusing GestureDetector with navigation widgets
  • Thinking it styles UI elements
  • Assuming it displays images
2. Which of the following is the correct way to detect a tap using GestureDetector in Flutter?
easy
A. GestureDetector(onPressed: () { print('Tapped'); }, child: Text('Tap me'))
B. GestureDetector(onClick: () { print('Tapped'); }, child: Text('Tap me'))
C. GestureDetector(onTouch: () { print('Tapped'); }, child: Text('Tap me'))
D. GestureDetector(onTap: () { print('Tapped'); }, child: Text('Tap me'))

Solution

  1. Step 1: Identify the correct GestureDetector callback

    The correct callback for detecting a tap is onTap. Other callbacks like onClick, onPressed, and onTouch do not exist on GestureDetector.
  2. Step 2: Verify syntax correctness

    GestureDetector(onTap: () { print('Tapped'); }, child: Text('Tap me')) uses the correct syntax with onTap and a child widget, making it valid Flutter code.
  3. Final Answer:

    GestureDetector(onTap: () { print('Tapped'); }, child: Text('Tap me')) -> Option D
  4. Quick Check:

    Tap detection uses onTap callback [OK]
Hint: Use onTap callback to detect taps in GestureDetector [OK]
Common Mistakes:
  • Using onClick or onPressed instead of onTap
  • Forgetting to provide a child widget
  • Misspelling callback names
3. What will happen when the user taps the text in this Flutter code?
GestureDetector(
  onTap: () => print('Tapped!'),
  child: Text('Click me'),
)
medium
A. The text 'Tapped!' will be printed to the console
B. Nothing happens because onTap is not a valid callback
C. The app will crash due to missing onPressed callback
D. The text will change to 'Tapped!' on screen

Solution

  1. Step 1: Understand onTap behavior

    The onTap callback runs the provided function when the user taps the child widget. Here, it prints 'Tapped!' to the console.
  2. Step 2: Check other options

    The text does not change on screen automatically without state management like setState. onTap is valid, so something does happen on tap. The app won't crash because onPressed is not required for GestureDetector.
  3. Final Answer:

    The text 'Tapped!' will be printed to the console -> Option A
  4. Quick Check:

    onTap prints 'Tapped!' on tap [OK]
Hint: onTap runs code on tap, prints to console if print() used [OK]
Common Mistakes:
  • Thinking onTap changes UI automatically
  • Confusing onTap with onPressed
  • Expecting visual changes without setState
4. Identify the error in this Flutter code snippet using GestureDetector:
GestureDetector(
  onTap: print('Tapped'),
  child: Text('Tap me'),
)
medium
A. Missing child widget inside GestureDetector
B. onTap should be a function, not the result of print()
C. GestureDetector does not support onTap callback
D. Text widget cannot be a child of GestureDetector

Solution

  1. Step 1: Analyze onTap assignment

    The onTap callback expects a function to call when tapped. Here, print('Tapped') runs immediately and assigns its result (void) to onTap, which is incorrect.
  2. Step 2: Correct usage

    onTap should be assigned a function like () => print('Tapped') or (){ print('Tapped'); } to run on tap.
  3. Final Answer:

    onTap should be a function, not the result of print() -> Option B
  4. Quick Check:

    onTap needs a function, not immediate call [OK]
Hint: Pass a function to onTap, not a direct call [OK]
Common Mistakes:
  • Calling print() instead of passing a function
  • Omitting child widget
  • Using unsupported callbacks
5. You want to detect both tap and long press gestures on a button in Flutter. Which GestureDetector code correctly handles both events?
hard
A. GestureDetector(onPressed: () => print('Tap'), onLongPress: () => print('Long press'), child: Container())
B. GestureDetector(onTap: () => print('Tap'), onDoubleTap: () => print('Long press'), child: Container())
C. GestureDetector(onTap: () => print('Tap'), onLongPress: () => print('Long press'), child: Container())
D. GestureDetector(onTap: () => print('Tap'), onHold: () => print('Long press'), child: Container())

Solution

  1. Step 1: Identify correct callbacks for tap and long press

    GestureDetector uses onTap for taps and onLongPress for long presses. GestureDetector(onTap: () => print('Tap'), onLongPress: () => print('Long press'), child: Container()) uses both correctly.
  2. Step 2: Check other options for errors

    GestureDetector(onTap: () => print('Tap'), onDoubleTap: () => print('Long press'), child: Container()) uses onDoubleTap instead of onLongPress, which is incorrect. GestureDetector(onPressed: () => print('Tap'), onLongPress: () => print('Long press'), child: Container()) uses onPressed which GestureDetector does not have. GestureDetector(onTap: () => print('Tap'), onHold: () => print('Long press'), child: Container()) uses onHold which is not a valid callback.
  3. Final Answer:

    GestureDetector(onTap: () => print('Tap'), onLongPress: () => print('Long press'), child: Container()) -> Option C
  4. Quick Check:

    Use onTap and onLongPress for tap and long press [OK]
Hint: Use onTap and onLongPress callbacks together [OK]
Common Mistakes:
  • Using onPressed instead of onTap
  • Confusing onDoubleTap with onLongPress
  • Using non-existent callbacks like onHold
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard