Reputation: 8202
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 Container
s, 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
.
What is happening, and what should I do?
Upvotes: 0
Views: 552
Reputation: 1037
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,
),
);
}
}
Upvotes: -1
Reputation: 2089
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,
),
);
}
}
Upvotes: 2
Reputation: 754
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,
),
),
Upvotes: 2