DEV Community

loading...

Flutter Tip (#3): Preventing Widgets overflow

Pedro Massango
Software Engineer at Monstarlab
Updated on ・2 min read

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.

Discussion (1)

Collapse
dchristo978 profile image
Christophorus Anindityo

New things learned everyday! Thanks Sensei Pedro!