Home > Software design >  Why Alignment not work when the widget has a screen width?
Why Alignment not work when the widget has a screen width?

Time:04-21

enter image description here

here the code when the image has screen width and alignment not align:

Align(
    alignment: const Alignment(2.0, 0),
      child: Image.network(
          'https://cdn.wallpapersafari.com/28/53/PjfrGv.jpg',
        width: MediaQuery.of(context).size.width,
      )
  )

enter image description here

here the code when the image has small width and it align:

Align(
    alignment: const Alignment(2.0, 0),
      child: Image.network(
          'https://cdn.wallpapersafari.com/28/53/PjfrGv.jpg',
        width: 200,
      )
  )

Can someone explain it to me? Thank you

CodePudding user response:

-1 means it aligns to the left side of the available space, 0 is center, 1 is the right side. Values above 1 will push it even more to the right, or to quote the documentation:

  /// The distance fraction in the horizontal direction.
  ///
  /// A value of -1.0 corresponds to the leftmost edge. A value of 1.0
  /// corresponds to the rightmost edge. Values are not limited to that range;
  /// values less than -1.0 represent positions to the left of the left edge,
  /// and values greater than 1.0 represent positions to the right of the right
  /// edge.

Now what does an x value of 2.0 exactly mean?
Imagine the distance it needs to move to go from the center to the right side of the available space, now this distance is taken twice. As a result. If you have a widget that already fills the complete space, then the distance from center to the right edge is 0, and therefore an align of 2.0 won't do anything because 2 times 0 is still 0. So in conclusion. if you use an x of 2.0 it will only have effect when the widget is smaller than the Align, and then it will be pushed out to the right so that a right aligned widget would be right in between this widget and a center aligned widget.

To demonstrate consider this code:

  runApp(MaterialApp(
    home: Stack(children: [
      Align(
          alignment: const Alignment(0, 0),
          child: Container(color: Colors.red, width: 600, height: 600)),
      Align(
          alignment: const Alignment(1, 1),
          child: Container(color: Colors.blue, width: 600, height: 600)),
      Align(
          alignment: const Alignment(2, 2),
          child: Container(color: Colors.yellow, width: 600, height: 600)),
    ]),
  ));

I'll demonstrate for flutter web since it's easy to resize windows there. but this applies to mobile as well. This will result in this:

enter image description here

Now increasing the window size will push the yellow one more out of screen because it's size will be smaller compared to the total size:

enter image description here

And as you can see, the relative distance between the 3 stays the same

  • Related