Flutter’s Container: This ain’t your Daddy’s div

Move Over <div>, Here Comes Container( )

It’s amazing! It’s astounding! It does everything! It slices! It dices!

Look, if this thing could wash dishes then my girlfriend would throw me out and marry the Container. So, how many should I put you down for? A hundred? Or do ya wanna buy two hundred?

Okay, but seriously, this thing really does do a ton, and I see code everywhere that uses a lot of unnecessary Widgets around Containers when people could write a lot less code by using the full capability of their Containers. This results in dozens, hundreds, maybe thousands of unnecessary lines cluttering up your code, for no good reason.

Bad Dev, no Coffee.

Don’t believe me? Take a look around at some code, just about anywhere, and see how often you can find constructors piled on top of constructors like this:

Every Single Widget Requires Another Constructor Call

If you got rid of my comments, this is what many people look at as normal:

  • Pad the Container to get some space around it.
  • Center the Text.
  • Put some Padding around the text so it’s not touching the edges of the Container.
  • Add the text.

What we need to keep in mind is that every, single, last, separate one of those Widgets is an individual, unique, unnecessary, redundant constructor call… and they’re even more wasteful than all of the extra words I just jammed into this stupid sentence.

So how does the Container do it better?

5 Widgets on the Left, 2 on the Right… And they do the exact same thing!

If you think this doesn’t look like a lot of savings then keep in mind this is just one Container. How many Containers do you use in an app? Yeah, it’s like that.

So here are the Container’s parameters you want to pay extra attention to:

  • padding:
  • margin:
  • alignment:
  • transform:
  • foregroundDecoration:
  • decoration:

Next, take this one step further because you can put a DecoratedBox in the decoration parameter and the DecoratedBox will give you access to all sorts of things, such as:

  • You can shape it.
  • Border and Border Radius
  • Gradient
  • Ways to blend the background.
  • Box Shadow
  • Image

So the “simple” Container will allow you to pad, color, align, transform, decorate and add margin; and using the decoration parameter to its fullest will allow you to have borders, gradients, images, box shadows and shapes.

So like I said, “This ain’t your daddy’s <div>”, so stop wasting it by using it like one!

Scott Stoll is a Freelance Flutter Developer, Author and Public Speaker. He is available for Freelance work and is able to travel in order to give talks, workshops or do company training. He is the organizer of GDG Cleveland, creator of #HumpDayQandA and an editor at Flutter Community on Medium.

Twitter: @scottstoll2017 — Email: scott.stoll@learnflutter.io — Websites: https://learnflutter.io/ and https://scottstoll.me/