简体   繁体   English

Flutter 如何对这个手势检测器进行约束?

[英]Flutter how do I give constraints to this gesturedetector?

What I'm trying to achieve is to drag the widget anywhere on the screen.我想要实现的是将小部件拖动到屏幕上的任何位置。 The solution below allows me to drag but goes beyond the limit of the screen.下面的解决方案允许我拖动但超出了屏幕的限制。

Are there any max/min function I can apply here or the corresponding calculation to keep the widget inside the height and width of the screen.是否有任何最大/最小 function 我可以在这里应用或相应的计算以将小部件保持在屏幕的高度和宽度内。

  @override
  Widget build(BuildContext context) {
    return Sizer(builder: (context, orientation, deviceType) {
      return MaterialApp(
          debugShowCheckedModeBanner: false,
          home: Container(
              decoration: const BoxDecoration(
                color: Colors.transparent,
                image: DecorationImage(
                  image: AssetImage('assets/images/due.jpeg'),
                  fit: BoxFit.cover,
                ),
              ),
              child: Scaffold(
                  extendBody: true,
                  backgroundColor: Colors.transparent,
                  body: Stack(
                    children: <Widget>[
                      Positioned(
                          left: offset.dx,
                          top: offset.dy,
                          child: GestureDetector(
                            onPanUpdate: (details) {
                              setState(() {
                                offset = (Offset(offset.dx + details.delta.dx,
                                    offset.dy + details.delta.dy));
                              });
     
                            },

when you calculate the new offset check for dy and dx to be inside view.当您计算新的偏移量时,检查 dy 和 dx 是否在视图内。 for example check offset.dx + details.delta.dx is bigger than 0 and smaller than MediaQuery.of(context).size.width then add this to new offset例如检查 offset.dx + details.delta.dx 大于 0 且小于 MediaQuery.of(context).size.width 然后将其添加到新偏移量

Are there any max/min function I can apply here有没有最大/最小 function 我可以在这里申请

You can use clamp method:您可以使用clamp法:

double limitX = (offset.dx + details.delta.dx).clamp(lowerLimit, upperLimit);
double limitY = (offset.dy + details.delta.dy).clamp(lowerLimit, upperLimit);

offset = Offset(limitX, limitY);

to keep the widget inside the height and width of the screen.将小部件保持在屏幕的高度宽度内。

Use:利用:

double screenWidth = MediaQuery.of(context).size.width;
double screenHeight = MediaQuery.of(context).size.height;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM