如何计算Flutter中的触摸坐标?

如何计算Flutter中的触摸坐标?,第1张

如何计算Flutter中的触摸坐标?

您可以将GestureDetector添加为堆栈的父级,然后注册

onTapDownDetails
侦听器。这应该在每个tapdown事件上调用您的侦听器,并在您的侦听器的TapDownDetails参数中使用Tap的全局偏移量。

这是演示相同代码的示例代码。

import 'package:flutter/material.dart';void main() {  runApp(new MyApp());}class MyApp extends StatelessWidget {  @override  Widget build(BuildContext context) {    return new MaterialApp(      title: 'Flutter Demo',      home: new MyHomePage(),    );  }}class MyHomePage extends StatefulWidget {  @override  MyHomePageState createState() => new MyHomePageState();}class MyHomePageState extends State<MyHomePage> {  @override  Widget build(BuildContext context) {    return new Scaffold(        appBar: new AppBar(          title: new Text('Popup Demo'),        ),        body: new MyWidget());  }}class MyWidget extends StatefulWidget {  @override  State<StatefulWidget> createState() {    return new MyWidgetState();  }}class MyWidgetState extends State<MyWidget> {  double posx = 100.0;  double posy = 100.0;  void onTapDown(BuildContext context, TapDownDetails details) {    print('${details.globalPosition}');    final RenderBox box = context.findRenderObject();    final Offset localOffset = box.globalToLocal(details.globalPosition);    setState(() {      posx = localOffset.dx;      posy = localOffset.dy;    });  }  @override  Widget build(BuildContext context) {    return new GestureDetector(      onTapDown: (TapDownDetails details) => onTapDown(context, details),      child: new Stack(fit: StackFit.expand, children: <Widget>[        // Hack to expand stack to fill all the space. There must be a better        // way to do it.        new Container(color: Colors.white),        new Positioned(          child: new Text('hello'),          left: posx,          top: posy,        )      ]),    );  }}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5051885.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存