Does the dx property of the Offset class return the double value of the logical pixels on the x-axis? I need to know if I can measure say a percentage of the dx against MediaQuery.of(context).size.width?


Solution 1: Enedee

Short answer: The dx property of an Offset object and the Width size of a Media Query are both doubles (pixel, yes) thus you can divide, multiply or do any math operation with them (separately or with each other). So, you can do your OffsetObject.dx/MediaQuery(context).Size.Width to get the percentage. You can run the code block below on Dart pad.

Loooong Answer: Not sure it adds more info.

  • Yes, of course you can measure the dx property of an Offset object against the width property of a MediaQuery because they are both of type double.

  • The mere fact that they are both of type doubles should allow you to carry out any math/arithmetic calculation you need. See the sample app below. the text returns the numbers (you can run it on Dartpad). I explained the variables/objects defined below as well.

  • ScreenWidthSize: the MediaQuery width, note the type is double. MediaQuery.of(context).size.width returns an object of type double.

  • offsetMagnitude: This defines the Offset object (I am not sure how you will get your Offset object so this for illustration. Then I need to get the dx.

  • horizontalOffset: This defines/extracts the dx property of the offsetMagnitude, the offset object. Note it is a double too.

  • horizontalOffsetToScreenWidthRatio: Since both ScreenWidthSize and horizontalOffset are doubles, I can carry out any mathematical operation, as long as they are applicable to the type double. I have therefore measured the percentage (we can format the result better but you get it).

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    double screenWidthSize = MediaQuery.of(context).size.width;
    Offset offsetMagnitude = Offset(12,25);
    double horizontalOffset = offsetMagnitude.dx;

    double horizontalOffsetToScreenWidthRatio = offsetMagnitude.dx/screenWidthSize;

    return Text(
      'Hello, my screen is $screenWidthSize wide and my horizontal offset is $horizontalOffset, so the horizontal offset to screen width ratio is $horizontalOffsetToScreenWidthRatio',
      style: Theme.of(context).textTheme.headline4,
    );
  }
}

/* Not sure what you are trying to achieve but it seems like some form of adaptive or responsive operation. I think if you check the docs, you will find a close widget needing only little manipulation to achieve what you want. Check the Align widget, might be what you need*/