DEV Community

Pedro Massango
Pedro Massango

Posted on • Edited on

9 1

Flutter Tip (#3): Preventing Widgets overflow

Widgets overflow is something that every new Flutter developer faces in their first time with the framweork, and is something that professional devs faces sometimes.

Whats is Widget overflow?
Is when your widgets run out of room in the screen. I bet that you already saw some yellow lines like:

The code is as follow:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
  return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Demo"),
      ),
      body: Row(
        children: List.generate(12, (i) {
          return Padding(
            padding: const EdgeInsets.all(8.0),
            child: Chip(
              label: Text("Item $i"),
            ),
          );
        }),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

You can see that we used the Row widget to list a set of Chips but since the Row widget is not scrollable he keep adding items in the same line. We have many widgets to fix this, but today we will use the Wrap widget. Lets replace Row with the Wrap widget. So the code is now:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Demo"),
      ),
      body: Wrap( // We changed from Row to Wrap
        direction = Axis.horizontal, // we need to specify the direction
        children: List.generate(12, (i) {
          return Padding(
            padding: const EdgeInsets.all(8.0),
            child: Chip(
              label: Text("Item $i"),
            ),
          );
        }),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Now the error just disappear. It is because the Wrap widget add its children in one line until there is no space left then it move to the next line and keep adding the childrens left until everything is added on the screen.

Wrap widget have so many parameters that you can aply to customize its behaviour and is so powerful. I recommend you to read its docs here.

Happy code and see you in the next post.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (1)

Collapse
 
dchristo978 profile image
Christophorus Anindityo

New things learned everyday! Thanks Sensei Pedro!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more