Home > Back-end >  Neither Positioned's width or SizedBox's width works inside a stack widget - Flutter
Neither Positioned's width or SizedBox's width works inside a stack widget - Flutter

Time:11-17

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Title Text'),
      ),
      body: SafeArea(
          child: Stack(children: [
        Column(
          children: const [
            Text('short content'),
          ],
        ),
        const Positioned(
            top: 100,
            width: 320,
            child: SizedBox(
              width: 320,
              height: 50,
              child: ColoredBox(color: Colors.red),
            ))
      ])),
    );

enter image description here

I need the red box taking almost the entire screen with, but it flows the text width. How should I make this work?

CodePudding user response:

Wrap your Stack with SizedBox:

SizedBox(
        width: double.infinity,
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            SizedBox(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: const [
                  Text('short content'),
                ],
              ),
            ),
            Positioned(
                top: 100,
                right: 0,
                left: 0,
                child: Container(
                  height: 50,
                  color: Colors.red,
                ))
          ],
        ),
      ),

enter image description here

CodePudding user response:

You can wrap all children of the stack with either Align or Positioned so that the Stack can properly lay them out.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Title Text'),
      ),
      body: SafeArea(
        child: Stack(
          children: [
            /// The column is now positioned.
            Positioned(
              top: .0,
              left: .0,
              child: Column(
                children: const [
                  ColoredBox(color: Colors.amber, child: Text('short content'))
                ],
              ),
            ),
            const Positioned(
              top: 100.0,
              width: 320.0,
              height: 50.0,
              child: ColoredBox(color: Colors.red),
            )
          ],
        ),
      ),
    );
  }

Output:

enter image description here

  • Related