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
--------------------- | Tap Counter Screen | --------------------- [ Tap me! ] Taps: 0
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 ), ); } }
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.
--------------------- | Tap Counter Screen | --------------------- [ Tap me! ] Taps: 3
GestureDetector widget in Flutter?onTap. Other callbacks like onClick, onPressed, and onTouch do not exist on GestureDetector.onTap and a child widget, making it valid Flutter code.GestureDetector(
onTap: () => print('Tapped!'),
child: Text('Click me'),
)GestureDetector(
onTap: print('Tapped'),
child: Text('Tap me'),
)print('Tapped') runs immediately and assigns its result (void) to onTap, which is incorrect.() => print('Tapped') or (){ print('Tapped'); } to run on tap.onTap for taps and onLongPress for long presses. GestureDetector(onTap: () => print('Tap'), onLongPress: () => print('Long press'), child: Container()) uses both correctly.Pass the test and this pattern moves unknown