Search code examples
flutterdraggablegesturedetector

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.

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


Solution

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

    And to apply the constraints to bottom and right you need to know the constraints of the object you're working with.

    If you have them you can apply the computation:

    Size objectSize = // the size of the object you're applying the constraints
    
    double upperLimitX = screenWidth - objectSize.width;
    double upperLimitY = screenHeight - objectSize.height;
    

    You can check this working example at dartpad.dev and on this gist.github.com.

    flutter clamp sample