2

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.stack.imgur.com/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.

mr.boris
  • 3,667
  • 8
  • 37
  • 70

1 Answers1

3

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.stack.imgur.com/dOkkG.png')),
              ),
              Container(
                child: Center(
                  child: Text('Text'),
                ),
              )
            ],
          );
        }));
Riwen
  • 4,734
  • 2
  • 19
  • 31
  • Thank you very much, it solves this problem. But would be nice if Flutter add something like `FractionallyPositioned` widget to the core. – mr.boris Feb 01 '21 at 20:09