Search code examples
flutterpositiondistancecircleci

locate button in a given distance from other


we need to locate 8 buttons in a shape of half circle with equal distance from another button like shown in picture below:

(https://i.sstatic.net/F0R75.png)

  • we tried to use positioned widgets but it didnt work.

enter image description here


Solution

  • This is what my solution looks like:

    SemicircleLayout

    I hope this works for you.

    Here is the code for this layout:

    class SemicircleLayout extends StatelessWidget {
      final List<Widget> children;
      final double radius;
      final double startAngle;
      final double endAngle;
      final Widget? centerWidget;
    
      const SemicircleLayout({
        super.key,
        required this.children,
        required this.radius,
        required this.centerWidget,
        this.startAngle = -pi,
        this.endAngle = 0,
      });
    
      @override
      Widget build(BuildContext context) {
        return Stack(
          children: [
            if (centerWidget != null)
              Positioned(
                left: radius,
                top: radius,
                child: centerWidget!,
              ),
            ...children
                .asMap()
                .map((index, child) {
              final angleFraction = (index / (children.length - 1));
              final angle = startAngle + (endAngle - startAngle) * angleFraction;
              final offsetX = radius * cos(angle);
              final offsetY = radius * sin(angle);
    
              return MapEntry(
                index,
                Positioned(
                  left: radius + offsetX,
                  top: radius + offsetY,
                  child: Transform.rotate(
                    angle: angle,
                    child: child,
                  ),
                ),
              );
            })
                .values
                .toList(),
          ],
        );
      }
    }
    

    To use this widget you give it array of children, center widget and radius.

    Example of usage:

    SemicircleLayout(
       radius: 150.0,
       centerWidget: RoundButton(),
       children: [
          RoundButton(),
          RoundButton(),
          RoundButton(),
          RoundButton(),
          RoundButton(),
          RoundButton(),
          RoundButton(),
          RoundButton(),
       ],
    )
    

    // RoundButton() is a custom Widget I used for buttons