class KindaCodeDemo extends StatefulWidget {
const KindaCodeDemo({Key? key}) : super(key: key);
@override
State<KindaCodeDemo> createState() => _KindaCodeDemoState();
}
class _KindaCodeDemoState extends State<KindaCodeDemo> {
// the tap location
Offset? _tapPosition;
// 获取点击的位置
void _getTapPosition(TapDownDetails details) async {
final tapPosition = details.globalPosition;
setState(() {
_tapPosition = tapPosition;
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTapDown: (details) => _getTapPosition(details),
child: Scaffold(
appBar: AppBar(title: const Text('KindaCode.com')),
body: Padding(
padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: double.infinity,
height: 200,
color: Colors.blue,
padding: const EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Display X coordinate of tap
Text(
'X: ${_tapPosition?.dx.toStringAsFixed(2) ?? "Tap Somewhere"}',
style: const TextStyle(fontSize: 36, color: Colors.white),
),
const SizedBox(
height: 20,
),
// Display Y coordinate of tap
Text(
'Y: ${_tapPosition?.dy.toStringAsFixed(2) ?? "Tap Somewhere"}',
style:
const TextStyle(fontSize: 36, color: Colors.yellow),
),
],
),
),
// the action of getting tap location doesn't prevent user from interacting with other widgets like buttons, forms, etc.
// the purpose of the button below is to demonstrate that
const SizedBox(
height: 30,
),
ElevatedButton(
onPressed: () =>
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Hi There'),
)),
child: const Text('A Useless Button')),
],
),
),
),
);
}
}
网友评论