Search code examples
flutterflutter-layout

Neither Positioned's width or SizedBox's width works inside a stack widget - Flutter


  @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?


Solution

  • 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