Flutter dynamic widget generation with layoutbuilder

Created At: 2024-02-28 04:21:29 Updated At: 2024-03-03 06:15:46

Generating dynamic widgets on the fly are exciting in Flutter and an advanced concept. Here we will how to use LayoutBuilder() widget along with Flex() and List.generate() to build a mechanism for generating widgets on the fly. At the end of this tutorial you will learn how to do the below things

  1. how to get width or space between two widgets
  2. generating widgets on the fly
  3. basic algorithm for showing dynamic widgets on the screen

The above picture tells you the requirement for generating widgets dynamically. 

LayoutBuilder()

The above widget would us space between to widgets. 

List.generate()

Based on a random number and space or width from LayoutBuilder() we will give us a certain number to generate wigdet. Not only that, based on the given number it will also generate widgets for us.

SizedBox()

This widget will give us the actual widget based on LayoutBuilder and List.generate(). SizedBox() could be also replaced by Container()

See the picture to get better understanding how they work

First you need to pass LayoutBuilder() widget between the widgets that you want to get space or distance or width in. 

Because of this you would be able to access BoxContraints widget which plays crucial role. It will helps us get the available space between the two widgets.

We will get that using BoxContraints constraints object. Now we can use contraints.contrainWidth() to get actual space or width between two widgets.

Then we pass the width to List.generate() widget which would calculate (constraints.constrainWidth()/sections).floor() the widgets would be generated.

Comment

Add Reviews