Home > Back-end >  Flutter how do I give constraints to this gesturedetector?
Flutter how do I give constraints to this gesturedetector?

Time:08-08

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.

  @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));
                              });
     
                            },

CodePudding user response:

when you calculate the new offset check for dy and dx to be inside view. 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

CodePudding user response:

Are there any max/min function I can apply here

You can use clamp method:

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;
  • Related