49

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

0

2 Answers 2

105

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Not working..., it always takes the height and width of screen
Linter 2 hints to avoid the use of const.
instead of SizedBox with height and width with the same value, we can use SizedBox.square and use only a specific value.
0

You can use the following:

FractionalTranslation(
    translation: Offset(0, 0),
        child: Container(
        width: 100,
        height: 100,
        child: SizedBox(
            height:  1,
            width: 1,
            child: const ColoredBox(color: Colors.amber),
        )
    ),
),

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.