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

Time:08-30

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.

CodePudding user response:

According to flutter documentation: If given a child, this widget forces it to have a specific width and/or height. These values will be ignored if this widget's parent does not permit them. For example, this happens if the parent is the screen (forces the child to be the same size as the parent), or another SizedBox (forces its child to have a specific width and/or height). This can be remedied by wrapping the child SizedBox in a widget that does permit it to be any size up to the size of the parent, such as Center or Align.

So wrapping the child with center would solve the problem:

Center(
        child: SizedBox(
          width: 300,
          height: 500,
          child: Center(
            child: SizedBox(
                width: 200, height: 200, child: Container(color: Colors.green)),
          ),
        )),

CodePudding user response:

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

  • Related