Home > OS >  I want to have 4 containers under each other. But the red container is above the others when I write
I want to have 4 containers under each other. But the red container is above the others when I write

Time:10-22

     Container(
       color: BColors.tealBackground,
       height: MediaQuery.of(context).size.height,
     ), 
     Container(
       color: BColors.greenBackground,
       height: MediaQuery.of(context).size.height / 2,
     ),  
     Container(
       color: BColors.yellowBackground,
       height: MediaQuery.of(context).size.height / 2/2,
     ),

I think something is wrong with the last Container, because the color is over the other. How should i can the "1/2" so that they are in order?

     Container(
       color: BColors.redBackground,
       height: MediaQuery.of(context).size.height ***, // I do not know what to do with this Container, when i delete this one it looks like the image.
     )

enter image description here

CodePudding user response:

wrap container with Column

 Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Container(
          color: Colors.teal,
          height: MediaQuery.of(context).size.height / 4,
        ),
        Container(
          color: Colors.green,
          height: MediaQuery.of(context).size.height / 4,
        ),
        Container(
          color: Colors.yellow,
          height: MediaQuery.of(context).size.height / 4,
        ),
        Container(
          color: Colors.red,
          height: MediaQuery.of(context).size.height / 4,
        )
      ],
    );
  }

enter image description here

CodePudding user response:

Better approach will be using LayoutBuilder. I think calling MediaQuery multiple times is not the suitable and also its child is totally depending on size of Parent's, that why I prefer LayoutBuilder.

Scaffold(
      body: LayoutBuilder(
        builder: (context, constraints) {
          return Column(
            children: [
              Container(
                height: constraints.maxHeight / 4,
                color: Colors.teal,
              ),
              Container(
                height: constraints.maxHeight / 4,
                color: Colors.green,
              ),
              Container(
                height: constraints.maxHeight / 4,
                color: Colors.yellow,
              ),
              Container(
                height: constraints.maxHeight / 4,
                color: Colors.red,
              ),
            ],
          );
        },
      ),
    );

  • Related