0

I am working on a flutter project, and I would like to display a Container inside another one with specific sizes. However, when I specify the size of the Containers, it doesn't take it into consideration.

Here is a code sample:

import 'package:flutter/material.dart';

void main() {
  runApp(MyWidget());
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 200.0,
      height: 200.0,
      color: Colors.blue,
      child: Container(
        width: 20.0,
        height: 20.0,
        color: Colors.red,
      ),
    );
  }
}

Here is what I get, I cannot see the blue Container.

enter image description here

What is happening, and what should I do?

Valentin Vignal
  • 6,151
  • 2
  • 33
  • 73

3 Answers3

2

You need to specify where the second box would be

   Container(
        width: 200.0,
        height: 200.0,
        color: Colors.orange,
        alignment: Alignment.center, // where to position the child
        child: Container(
          width: 50.0,
          height: 50.0,
          color: Colors.blue,
        ),
      ),
CharlyKeleb
  • 587
  • 4
  • 17
2

as I mentioned in comment you need to specify where the second box would be

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 200.0,
      height: 200.0,
      color: Colors.blue,
      alignment: Alignment.center,
      child: Container(
        width: 20.0,
        height: 20.0,
        color: Colors.red,
      ),
    );
  }
}
Nagual
  • 1,576
  • 10
  • 17
  • 27
-1

Actually, what happens here is that you're directly passing the Container as the root widget. So, the container has to occupy the entire screen as it doesn't know what else to show in the background. So, you will see that it occupies the entires screen. With respect to the red-colored container, it seems that it also follows the same property as its parent. So, it fills the entire screen. Unless, we specify the alignment property.

I added the alignment property to the parent as well. Yet, it still occupies the entire screen.

import 'package:flutter/material.dart';

void main() {
  runApp(MyWidget());
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      width: 40.0,
      height: 40.0,
      color: Colors.blue,
      child: Container(
        alignment: Alignment.center,
        width: 20.0,
        height: 20.0,
        color: Colors.red,
      ),
    );
  }
}
Preet Shah
  • 792
  • 5
  • 12