How to create colour box with fixed width and height in flutter?

Issue

I am trying to create a color box with fixed width and height in a flutter.
How to achieve this?

Solution

Wrap any widget in a SizedBox to force it to match a fixed size.

As for background colors or border, use DecoratedBox.

You can then combine both, which leads to

const SizedBox(
  width: 42.0,
  height: 42.0,
  child: const DecoratedBox(
    decoration: const BoxDecoration(
      color: Colors.red
    ),
  ),
),

You may as well use Container which is a composition of many widgets including those two from above. Which leads to :

new Container(
  height: 42.0,
  width: 42.0,
  color: Colors.red,
)

I tend to prefer the first option. Because Container prevents the use of ‘const’ constructor. But both works and do the same.

Answered By – Rémi Rousselet

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *