fluttergesturedetector

How to get width of GestureDetector in flutter?


I'm doing a web-app and it looks like this: Image of the web app for better understanding, where you can choose how hot your water should be (just a silly example to illustrate my problem).

the code to that looks like the following:

Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: GestureDetector(
            onTapDown: (val) {
              print(val.localPosition.dx);
            },
            child: Container(
              decoration: const BoxDecoration(gradient: LinearGradient(colors: [Colors.blue, Colors.red])),
              height: 100,
              margin: const EdgeInsets.all(20),
            )),
      ),
    );

I'm trying to detect how fare from the left edge the user has pressed the gesture Detector. I add a print statement and it tells me the number of pixels.

But what i need is something like a percentage, for example when the user presses the Container in the middle it should return 50% or 0.5 or something like that. Just the numbers of pixels doesnt help me to further set the temperature. Since the width of the container is changing by the window size, I can not simply divide the dx value of the positoin by the width of the container.

Any ideas how to solve that?


Solution

  • Just put everything in a new widget and use the build context of the build method:

    class Thermometer extends StatelessWidget {
      const Thermometer({super.key});
    
      @override
      Widget build(BuildContext context) {
        return GestureDetector(
            onTapDown: (x) {
              print(context.size?.width);
              print("--> ${100 * x.localPosition.dx / (context.size?.width ?? 1)}%");
            },
            child: Container(
              decoration: const BoxDecoration(gradient: LinearGradient(colors: [Colors.blue, Colors.red])),
              height: 100,
            ));
      }
    }
    

    That prints something like

    779.111083984375
    
    --> 20.764405690078366%
    

    when you tap on it.