This blog assumes that you have a beginner’s knowledge in Flutter. Otherwise, dive into to get the basics and come right back!

Now, how do we layout widgets in Flutter? Normally we use a stack, row or column. But what if our requirement is more than that? If we want to arrange some widgets horizontally, we use a Row Widget. If we want to arrange them vertically, we would wrap them in a Column and use Stack to arrange elements on top of another. But we can’t expect our UI to be so simple as that. For example, I was met with a requirement of a circular widget with five equally spaced buttons located on it (check out the image below!).

Flutter widgets

Don’t worry! We can do it with a CustomMultiChildLayout widget which takes only two arguments.

  1. delegate - of type MultiChildLayoutDelegate which is responsible for positioning the children. 
  2. children - which is the array of widgets to be positioned. The children argument is similar to the one used in rows and columns, but one difference is that every item in that array should be marked with a Layout id for identifying that child.

Now, the important part is the delegate. The MultiChildLayoutDelegate is an abstract class. So, we have to extend it for our use. Override the method performLayout and we can write the code to position items in it.

  1. The performLayout method gives us the widget’s size from which we can calculate the center of the circle. 
  2. Since we have to layout five widgets along the circle, use a for loop for it.
  3. Remember we have created every item with an id attached to it. So we are using the same id to check whether the item exists or not. 
  4. Now, size of the button is retrieved using layoutChild method. 
  5. The angle between the item and center axis is calculated using the function _calculateItemAngle.
  1. Finally,  positionChild method is called with the id of the item and the offset. The offset is calculated using the mathematical equation,

A point at angle theta on the circle whose centre is (x0,y0) and whose radius is r is (x0 + r cos theta, y0 + r sin theta).

  1. The shouldRelayout method is called to compare the current layout and the old one and return true if a relayout is needed.

So, that’s how easy it is to create custom layouts in Flutter. If you want to read more about our Flutter experience, check out our recent blog. Flutter has always been our core areas of expertise. So, stay tuned for more similar updates and information exchange! 

You can further learn about our Flutter contributions in GitHub.

Subscribe to our newsletter. Get updates on awesome happenings in the technology world!
Newsletter subscription successfull! Something went wrong! Email is already registered!