Search code examples
flutterresponsive-designflutter-layoutflutter-positioned

Flutter: responsive Positioned in Stack


I want to place icon out of parent bounds and make it responsive (relative to parent's height).

enter image description here

There is no problem to place an icon outside from parent bounds with Stack and Positioned widgets.

But there is a problem to make it responsive.

So, if container height decreases, then the icon size should also decrease.

Container(
  decoration: BoxDecoration(
    border: Border.all(
      color: Color(0xff2577ff),
      width: 5.0,
    ),
    borderRadius: BorderRadius.all(
      Radius.circular(15.0),
    ),
  ),
  width: 200.0,
  height: 80.0,
  child: Stack(
    clipBehavior: Clip.none,
    children: [
      Center(
        child: Text('Text'),
      ),
      Positioned( // <-- doesn't work
        top: -20.0, // <-- how to make it also relative to parent's height parameter?
        right: -20.0, // <-- how to make it also relative to parent's height parameter?
        child: FractionallySizedBox( // <-- doesn't work
          heightFactor: 0.5,
          child: Image.network('https://i.sstatic.net/dOkkG.png'),
        )
      )
    ],
  ),
)

I've tried to make some sample but with no success. I really don't know how to implement such logic with Flutter and I can't find any reliable example.


Solution

  • Use LayoutBuilder. You can get the parent's constraints using that. So, for example:

    Container(
            decoration: BoxDecoration(
              border: Border.all(
                color: Color(0xff2577ff),
                width: 5.0,
              ),
              borderRadius: BorderRadius.all(
                Radius.circular(15.0),
              ),
            ),
            width: 200.0,
            height: 160.0,
            child: LayoutBuilder(builder: (context, constraint) {
              return Stack(
                clipBehavior: Clip.none,
                children: [
                  Positioned(
                    // <-- doesn't work
                    top: -(constraint.maxHeight /
                        4), // relative to parent's height
                    right: -(constraint.maxHeight /
                        4), // relative to parent's height
                    child: Container(
                        height: constraint.maxHeight / 2, // relative to parent's height
                        width: constraint.maxHeight / 2, // relative to parent's height
                        child:
                            Image.network('https://i.sstatic.net/dOkkG.png')),
                  ),
                  Container(
                    child: Center(
                      child: Text('Text'),
                    ),
                  )
                ],
              );
            }));