flutterdart

Why does a SizedBox in another SizedBox ignore its width and hight?


When I nest two SizedBoxes, the width and height of the inner box are ignored. Why is this, how can I work around it?

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
        child: SizedBox(
      width: 300,
      height: 500,
      child: SizedBox(
          width: 200, height: 200, child: Container(color: Colors.green)),
    ));
  }
}

enter image description here

In this example, I have a 300x500 sized box and an inner 200x200 SizedBox. In the picture you can see that the green box is the size of the outer SizedBox but should actually be a 200x200 square.


Solution

  • The problem is, SizedBox can set widget size only within the constrains set by the parent. Many widgets, like Padding, want their child to occupy 100% of the space available to them. This makes sense, because if the child is smaller they wouldn't know where to put it.

    If you want the child to be smaller than the parent you could use Center or Align, e.g. replace