0
0
Fluttermobile~20 mins

GestureDetector in Flutter - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Tap Counter Screen
A simple screen that counts how many times the user taps on a colored box.
Target UI
---------------------
| Tap Counter Screen |
---------------------

[ Tap me! ]

Taps: 0
Display a colored box with the text 'Tap me!'
Detect taps on the box using GestureDetector
Each tap increases the tap count by 1
Show the current tap count below the box
Starter Code
Flutter
import 'package:flutter/material.dart';

class TapCounterScreen extends StatefulWidget {
  @override
  State<TapCounterScreen> createState() => _TapCounterScreenState();
}

class _TapCounterScreenState extends State<TapCounterScreen> {
  int _tapCount = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Tap Counter Screen')),
      body: Center(
        // TODO: Add GestureDetector with colored box and tap count display
      ),
    );
  }
}
Task 1
Task 2
Task 3
Task 4
Solution
Flutter
import 'package:flutter/material.dart';

class TapCounterScreen extends StatefulWidget {
  @override
  State<TapCounterScreen> createState() => _TapCounterScreenState();
}

class _TapCounterScreenState extends State<TapCounterScreen> {
  int _tapCount = 0;

  void _incrementCounter() {
    setState(() {
      _tapCount++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Tap Counter Screen')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            GestureDetector(
              onTap: _incrementCounter,
              child: Container(
                width: 150,
                height: 150,
                color: Colors.blueAccent,
                alignment: Alignment.center,
                child: Text(
                  'Tap me!',
                  style: TextStyle(color: Colors.white, fontSize: 24),
                ),
              ),
            ),
            SizedBox(height: 20),
            Text('Taps: $_tapCount', style: TextStyle(fontSize: 20)),
          ],
        ),
      ),
    );
  }
}

We use a GestureDetector to detect taps on the blue box. When the user taps, the _incrementCounter method runs, increasing the tap count and updating the UI with setState. The box shows 'Tap me!' text, and below it, the current number of taps is displayed. This teaches how to handle simple touch gestures and update the screen accordingly.

Final Result
Completed Screen
---------------------
| Tap Counter Screen |
---------------------

[ Tap me! ]

Taps: 3
User taps the blue box labeled 'Tap me!'
Each tap increases the number shown below by 1
The box visually stays the same but responds to taps
Stretch Goal
Add a double-tap gesture that resets the tap count to zero.
💡 Hint
Use GestureDetector's onDoubleTap property to reset _tapCount and call setState.