Home > Software engineering >  How to center a widget inside a stack and moving it programmatically?
How to center a widget inside a stack and moving it programmatically?

Time:10-06

I have a widget in a stack that should be centered in the stack initially. The user should be able to move the widget programmatically in the stack.

I have tried a number of things. I can center the widget by setting the alignment of Stack to center using alignment: Alignment.center of the stack. And if the no TRBL properties of the Positioned widget is not set, then the widget is centered. But Then how do you move the widget from center to 2 pixels above center or 5 pixel right?

  Stack(
    alignment: Alignment.center,
    children: [
        Positioned(
          child:Container(
             height: 50,
             width: 50,
             child: Text('Move this programmatically')
           )
         )
       ]
    )

CodePudding user response:

You can play with this widget. I am using LayoutBuilder.

class StackAMovement extends StatefulWidget {
  const StackAMovement({super.key});

  @override
  State<StackAMovement> createState() => _StackAMovementState();
}

class _StackAMovementState extends State<StackAMovement> {
  double shiftX = 0;
  double shiftY = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          shiftY  = 2;
          shiftX  = 5;
          setState(() {});
        },
      ),
      body: LayoutBuilder(
        builder: (p0, constraints) {
          final centerW = constraints.maxWidth / 2;
          final centerH = constraints.maxHeight / 2;
          return Stack(
            children: [
              Positioned(
                  left: centerW   shiftX,
                  top: centerH   shiftY,
                  child: Container(
                      color: Colors.purple,
                      height: 50,
                      width: 50,
                      child: Text('Move this programmatically')))
            ],
          );
        },
      ),
    );
  }
}

CodePudding user response:

    Stack(
        alignment: Alignment.center,
        children: [
            Positioned.fill(
              child:Center(
               child:Container(
                 height: 50,
                 width: 50,
                 child: Text('Move this programmatically')
               ))
             )
           ]
        )
  • Related