Implementing a fortune wheel

There are cases when you want to have an iconic way of selecting a random value from a given list. In this tutorial we ware going to implement a fortune wheel.

Use case

In game or gamification context where speed is not the major interest but it’s about entertainment, a fortune wheel might be a good choice to let the user watch the app make a random choice based on a given list. A prominent example is whether or much you have won.

Goal

This is how the final implementation result should look like:

Flutter Fortune Wheel animated

Requirements

Before we start with the actual implementation, let’s define the requirements that we apply to our fortune wheel:

  • For every slice of the fortune wheel the value and the visual representation should be configurable. E.g: The value is 100 and the visual representation is a widget showing “YOU WIN 100 €”
  • The background color of every slice should be configurable as well
  • There should be an arrow indicator that shows which slice is currently selected whose turn speed should be configurable
  • There should be a way of getting the current value and widget, also during the animation
  • It should be possible to trigger the beginning of the spin from the outside

Implementation

Let’s begin with defining the different classes.

import 'package:flutter/widgets.dart';

class FortuneWheelChild<T> {
  FortuneWheelChild({
    required this.foreground,
    this.background,
    required this.value
  });

  final Widget foreground;
  final Color? background;
  final T value;
}

Our first class is the FortuneWheelChild. The visual representation of this is one slice of the wheel. So the wheel widget is supposed to expect a list of FortuneWheelChild in its constructor to know how the wheel should look like. The FortuneWheelChild uses a generic type. That’s because we want to be able to statically check if the type of value corresponds with the generic type we provide for the FortuneWheel widget.

foreground is basically the visual representation of the value (like the above mentioned “YOU WIN 100 €” widget). background defines the background color.

import 'package:flutter/widgets.dart';
import 'package:fortune_wheel/widgets/fortune_wheel.dart';

class FortuneWheelController<T> extends ChangeNotifier {
  FortuneWheelChild<T>? value;

  bool isAnimating = false;
  bool shouldStartAnimation = false;
  
  void rotateTheWheel() {
    shouldStartAnimation = true;
    notifyListeners();
  }

  void animationStarted() {
    shouldStartAnimation = false;
    isAnimating = true;
  }

  void setValue(FortuneWheelChild<T> fortuneWheelChild) {
    value = fortuneWheelChild;
    notifyListeners();
  }

  void animationFinished() {
    isAnimating = false;
    shouldStartAnimation = false;
    notifyListeners();
  }
}

For the implementation of the controller we are going to use a technique that is described in this article.

The controller is the link between the widget holding the animation and the presentation of the wheel and the parent widget that is interested in starting the rotation and receiving updates about the currently selected value. That’s why the controller needs to carry three variables:

  • value
  • isAnimating
  • shouldStartAnimation

The value should represent the currently selected child and is to be updated by the animation on change. isAnimating exists to prevent the animation to start over when an animation is still running. The last one is the variable that is set to true when the trigger to rotate the wheel was received and to false once the animation has begun.

These variables are controlled by the four public methods of this class:

  • rotateTheWheel()
  • animationStarted()
  • setValue()
  • animationFinished()

In a common process, these methods are executed in the very same order they appear in the class declaration:

1.) The parent widget triggers a rotation of the wheel (e. g. because the user has tapped a button)
2.) Once the animation has started, it triggers the respective method
3.) On every updated being emitted by the animation controller, the new value is being sent to the controller
4.) When the animation is completed, it communicates this circumstance to the controller

Great! We have a widget representing a slice of the wheel and a controller being responsible for the communication. Now we need the core of the this app: the wheel widget itself, which ties everything together and holds the animation controller.

Let’s start with the signature of this widget:

class FortuneWheel<T> extends StatefulWidget {
  FortuneWheel({
    required this.controller,
    this.turnsPerSecond = 8,
    this.rotationTimeLowerBound = 2000,
    this.rotationTimeUpperBound = 4000,
    required this.children
  }): assert(children.length > 1, 'List with at least two elements must be given');

  final FortuneWheelController<T> controller;
  final List<FortuneWheelChild<T>> children;
  final int turnsPerSecond;
  final int rotationTimeLowerBound;
  final int rotationTimeUpperBound;

  @override
  _FortuneWheelState createState() => _FortuneWheelState();
}

The only required parameter is the controller and the children being a list of FortuneWheelChild. All other parameters define the rather cosmetical aspects like the speed of the arrow (in turns per second) and the lower and upper bound of the amount of time it keeps on rotating during one phase.

It needs to be a StatefulWidget because inside the widget we keep track of the animation, which is a local state being managed by the widget.

Animation

We start with the animation part.

  void _initiateAnimation() {
    _animationController = new AnimationController(
      vsync: this,
      lowerBound: 0,
      upperBound: double.infinity
    );

    _animationController.addListener(() {
      widget.controller.setValue(
        widget.children[
          ((widget.children.length) * (_animationController.value % 1)).floor()
        ]
      );

      if (_animationController.isCompleted) {
        widget.controller.animationFinished();
      }
    });
  }

We create an AnimationController with a lowerBound of zero and an upperBound of infinity. That’s because we let the animation value represent the number of turns the wheel has made. Every triggered rotation process results in an unknown number of spins because it depends on the spinning duration which is a random value between the given rotationTimeLowerBound and rotationTimeUpperBound.

We listen to the AnimationController and on every new value we inform our controller. To do this, we calculate the index in the given list of FortuneWheelChild so that it behaves as follows: if we have a list of four children, the first child should be chosen if the rotation is between 0 and 1/4. The second if it’s between 1/4 and 2/4 (equals 1/2), the third between 2/4 and 3/4 and the last between 3/4 and 4/4 (equals 1). Because the rotation value from the animation controller can be higher than 1, we first need to use the modulo operator. After that, we round the double value to the next integer by using math.floor().

Once the animation is finished, we inform the controller about that.

After having defined the part of initiating and listening to the animation, we still need the other way: listen to the controller and start the animation if necessary.

  void _initiateControllerSubscription() {
    widget.controller.addListener(() {
      if (!widget.controller.shouldStartAnimation || widget.controller.isAnimating)
        return;
    
      _startAnimation();
    }

Pretty straight forward and self-explanatory. If the start of the animation is requested and an animation is not currently running, start a new one.

  void _startAnimation() {
    widget.controller.animationStarted();
        
    int milliseconds = Random().nextInt(widget.rotationTimeLowerBound) + (widget.rotationTimeUpperBound - widget.rotationTimeLowerBound);
    double rotateDistance = milliseconds / 1000 * widget.turnsPerSecond;
        
    _animationController.value = _animationController.value % 1;
        
    _animationController.duration = Duration(milliseconds: milliseconds.toInt());
        
    _animationController.animateTo(
      _animationController.value + rotateDistance,
      curve: Curves.easeInOut
    );
  }

Starting a new animation is nothing else but determining the animation duration by generating a random value between the given boundaries. After that, reset the animation value to the current value modulo 1. That ensures that we keep the rotation where it was but cut off the spins that are higher than 1. Example: if in the previous round, the wheel rotated 7.86 amounts, it will then be 0.86.

Then we make the AnimationController animate from the current value to the newly calculated rotation distance.

That’s it. What’s left to do is to call both methods in initState() method.

Design

Before we deep dive into designing the different elements of our wheel, let’s think about it for a second – what parts do we have?

  • The most important part are the slices of the whole circle. Their look is determined by the FortuneWheelChild class
  • Then there is an indicator in the center that is supposed to point at the current result and spin according to the animation

Okay then, let’s start off with drawing a single slice!

import 'package:flutter/material.dart';
import 'dart:math';

class WheelSlicePainter extends CustomPainter {
  WheelSlicePainter({
    required this.divider,
    required this.number,
    required this.color
  });

  final int divider;
  final int number;
  final Color? color;
  
  Paint? currentPaint;
  double angleWidth = 0;

  @override
  void paint(Canvas canvas, Size size) {
    _initializeFill();
    _drawSlice(canvas, size);
  }

  void _initializeFill() {
    currentPaint = Paint()..color = color != null
      ? color!
      : Color.lerp(Colors.red, Colors.orange, number / (divider -1))!;
    
    angleWidth = pi * 2 / divider;
  }

  void _drawSlice(Canvas canvas, Size size) {
    canvas.drawArc(
      Rect.fromCenter(
        center: Offset(size.width / 2, size.height / 2),
        height: size.height,
        width: size.width,
      ),
      0,
      angleWidth,
      true,
      currentPaint!,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

We use a CustomPaint class to draw our slice. If you think about it, a slice is nothing but an arc. That’s why we use the drawArc() method of the canvas class.

Important: we need to know the total amount of children (called divider here) so that we can adjust the angle of the arc. Basically we take a whole circle (pi * 2) and divide it by the amount of children to get the arc.

If no color is given, we interpolate the color (linearinterpolate method) from red to orange.

Flutter fortune wheel slice
The first iteration of a slice

If we draw it on the screen with divider being 5 and number being 0, we get the above result. It seems like drawing an arc always starts at (0,0) if you regard the circle in the context of a cartesian coordinate system. This translates to pi / 2 or 90 °.

Now, we want the first child that is added to be the first element of the rotation and to be a the top center position of the wheel. So we need to rotate the whole wheel. But first, let’s wrap the slice in a class.

class WheelSlice extends StatelessWidget {
  WheelSlice({
    required this.index,
    required this.size,
    required this.fortuneWheelChildren
  });

  final int index;
  final double size;
  final List<FortuneWheelChild> fortuneWheelChildren;

  @override
  Widget build(BuildContext context) {
    int childCount = fortuneWheelChildren.length;
    double pieceAngle = (index / childCount * pi * 2);

    return Stack(
      children: [
        _getSliceBackground(pieceAngle, childCount),
      ],
    );
  }

  Transform _getSliceBackground(double pieceAngle, int childCount) {
    return Transform.rotate(
      angle: pieceAngle,
      alignment: Alignment.center,
      child: Stack(
        children: [
          Container(
            width: size,
            height: size,
            child: CustomPaint(
              painter: WheelSlicePainter(
                divider: childCount,
                number: index,
                color: fortuneWheelChildren[index].background
              ),
              size: Size(size, size),
            ),
          ),
        ],
      ),
    );
  }
}

Our class WheelSlice expects an index, a size and a list of all FortuneWheelChild objects. We use these information to calculate an angle by which the slice should be rotated and pass it to the painter we have created before.

  @override
  Widget build(BuildContext context) {
    return Container(
      child: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          size = min(constraints.maxHeight, constraints.maxWidth);

          return SizedBox(
            width: size,
            height: size,
            child: _getWheelContent(),
          );
        }
      ),
    );
  }

  Stack _getWheelContent() {
    return Stack(
      children: [
        _getSlices(),
      ],
    );
  }

  Widget _getSlices() {
    return Stack(
      children: [
        for (int index = 0; index < widget.children.length; index++)
          WheelSlice(
          	index: index, size: size, fortuneWheelChildren: widget.children
    	  ),
      ],
    );
  }

We enhanced our FortuneWheel class with a build function. Previously we have only created the animation, but now we actually display something based on the animation value.

We prepare a Stack because there will be Widgets on top of the slices.

Flutter fortune wheel slices
The rotation is not correct, yet

Looks like a fortune wheel. However, the rotation does not seem right. If the color interpolates from red to orange, then we would expect the red slice to be oon top. Let’s fix this by rotating the whole wheel back by a quarter of a circle.

  Widget _getSlices() {
    double fourthCircleAngle = pi / 2;
    double pieceAngle = pi * 2 / widget.children.length;

    return Stack(
      children: [
        for (int index = 0; index < widget.children.length; index++)
          Transform.rotate(
            angle: (-fourthCircleAngle) - (pieceAngle / 2),
            child: WheelSlice(
              index: index, size: size, fortuneWheelChildren: widget.children
            ),
          ),
      ],
    );
  }
Flutter fortune wheel slices
Our wheel with the corrected rotation

Okay, this is better. Now in addition to the background color. we want to display the foreground widget centered on top of every slice.

  @override
  Widget build(BuildContext context) {
    int childCount = fortuneWheelChildren.length;
    double pieceAngle = (index / childCount * pi * 2);
    double pieceWidth = childCount == 2 ? size : sin(pi / childCount) * size / 2;
    double pieceHeight = size / 2;

    return Stack(
      children: [
        _getSliceBackground(pieceAngle, childCount),
        _getSliceForeground(pieceAngle, pieceWidth, pieceHeight)
      ],
    );
  }  

  Widget _getSliceForeground(double pieceAngle, double pieceWidth, double pieceHeight) {
    double centerOffset = (pi / fortuneWheelChildren.length);
    double leftRotationOffset = (-pi / 2);

    return Transform.rotate(
      angle: leftRotationOffset + pieceAngle + centerOffset,
      alignment: Alignment.center,
      child: Stack(
        children: [
          Positioned(
            top: size / 2,
            left: size / 2 - pieceWidth / 2,
            child: Container(
              padding: EdgeInsets.all(size / fortuneWheelChildren.length / 4),
              height: pieceHeight,
              width: pieceWidth,
              child: FittedBox(
                  fit: BoxFit.scaleDown,
                  alignment: Alignment.center,
                  child: Transform.rotate(
                      angle: -pieceAngle - leftRotationOffset * 2,
                      child: fortuneWheelChildren[index].foreground
                  )
              ),
            )
          ),
        ],
      ),
    );
  }

We can’t just use the pieceAngle to position the foreground on top of the slice. We also want it to be centered within the slice. For that, we need a rectangle that spans across our slice and put the widget in the center. The imaginary rectangle (colored green, half-transparent) looks like this:

Flutter fortune wheel slice markers
The green rectangle resembles the imaginary area in which the widget is centered

We have a known angle (360 ° divided by the amount of slices) and two sides with a known length (the radius of a circle). This enables us to calculate the missing side length with the sinus rule: sin(pi / childCount) * size / 2. If the number of children equals 2, we can not use this rule because we have no triangle. Instead, we make it size / 2 wide then.

SizedBox(
    width: 350,
    height: 350,
    child: FortuneWheel<int>(
      controller: fortuneWheelController,
      children: [
        FortuneWheelChild(foreground: Text('Test1'), value: 1),
        FortuneWheelChild(foreground: Text('Test2'), value: 2),
        FortuneWheelChild(foreground: Text('Test3'), value: 3),
      ],
    )
)
Flutter fortune wheel slices with foreground
Wheel with foreground widgets

Now we need the part of the wheel that indicates the currently selected slice. For that, we place a triangle attached to a circle at the center of our wheel on top of everything.

class WheelResultIndicator extends StatelessWidget {
  WheelResultIndicator({
    required this.wheelSize,
    required this.animationController,
    required this.childCount
  });

  final double wheelSize;
  final AnimationController animationController;
  final int childCount;

  @override
  Widget build(BuildContext context) {

    double indicatorSize = wheelSize / 10;
    Color indicatorColor = Colors.black;

    return Stack(
      children: [
        _getCenterIndicatorCircle(indicatorColor, indicatorSize),
        _getCenterIndicatorTriangle(wheelSize, indicatorSize, indicatorColor),
      ],
    );
  }

  Positioned _getCenterIndicatorTriangle(double wheelSize, double indicatorSize, Color indicatorColor) {
    return Positioned(
      top: wheelSize / 2 - indicatorSize,
      left: wheelSize / 2 - (indicatorSize / 2),
      child: AnimatedBuilder(
        builder: (BuildContext context, Widget? child) {
          return Transform.rotate(
            origin: Offset(0, indicatorSize / 2),
            angle: (animationController.value * pi * 2) - (pi / (childCount)),
            child: CustomPaint(
              painter: TrianglePainter(
                fillColor: indicatorColor,
              ),
              size: Size(indicatorSize, indicatorSize)
            ),
          );
        },
        animation: animationController,
      ),
    );
  }

  Center _getCenterIndicatorCircle(Color indicatorColor, double indicatorSize) {
    return Center(
      child: Container(
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: indicatorColor,
        ),
        width: indicatorSize,
        height: indicatorSize,
      )
    );
  }
}

As there is no built-in widget that resembles a triangle, we use the CustomPaint widget to draw some. The indicator has the size of a tenth of the whole widget size. To keep it simple, we draw the circle as a usual container in the widget tree with a circle shape.

Flutter fortune wheel slices with indicator
Wheel with arrow indicator

Okay, we still have some problem: the arrow indicator is pointing towards the beginning of the first slice. While this is technically correct, I think it’s more aesthetic if it starts at the top center. That’s why we have to reset the animation value initially to half of one child:

 void _initiateAnimation() {
    _animationController = new AnimationController(
      vsync: this,
      lowerBound: 0,
      upperBound: double.infinity
    );

    _animationController.value =  (0.5 / (widget.children.length));
  ...

Usage

Now that we have designed the widget to be fully configurable and usable from the outside, let’s look at a sample usage:

import 'package:flutter/material.dart';

import 'widgets/fortune_wheel.dart';

class DemoScreen extends StatefulWidget {
  @override
  _DemoScreenState createState() => _DemoScreenState();
}

class _DemoScreenState extends State<DemoScreen> {
  FortuneWheelController<int> fortuneWheelController = FortuneWheelController();
  FortuneWheelChild? currentWheelChild;
  int currentBalance = 0;

  @override
  void initState() {
    fortuneWheelController.addListener(() {
      if (fortuneWheelController.value == null)
        return;

      setState(() {
        currentWheelChild = fortuneWheelController.value;
      });

      if (fortuneWheelController.isAnimating)
        return;

      if (fortuneWheelController.shouldStartAnimation)
        return;

      setState(() {
        currentBalance += fortuneWheelController.value!.value;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Container(
          color: Colors.white,
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  padding: EdgeInsets.all(24),
                  decoration: BoxDecoration(
                      color: currentBalance.isNegative ? Colors.red : Colors.green,
                      borderRadius: BorderRadius.circular(16)
                  ),
                  child: Text(
                    'Current balance: $currentBalance €',
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                        fontSize: 18
                    ),
                  ),
                ),
                SizedBox(height: 24,),
                Divider(color: Colors.black87,),
                SizedBox(height: 16,),
                Container(
                  height: 80,
                  width: 80,
                  child: currentWheelChild != null ? currentWheelChild!.foreground : Container(),
                ),
                SizedBox(height: 16,),
                SizedBox(
                    width: 350,
                    height: 350,
                    child: FortuneWheel<int>(
                      controller: fortuneWheelController,
                      children: [
                        FortuneWheelChild(
                            foreground: Text('Test 1'),
                            value: 1
                        ),
                        FortuneWheelChild(
                            foreground: Text('Test 2'),
                            value: 2
                        ),
                        FortuneWheelChild(
                            foreground: Text('Test 3'),
                            value: 3
                        ),
                      ],
                    )
                ),
                SizedBox(height: 24),
                ElevatedButton(
                    onPressed: () => fortuneWheelController.rotateTheWheel(),
                    child: Padding(
                      padding: EdgeInsets.all(16),
                      child: Text('ROTATE', style: TextStyle(fontWeight: FontWeight.bold),),
                    )
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

We just listen to the FortuneWheelController in the initState() method of our widget. Whenever the value changes and is not null, we store it in a member variable. If isAnimating is false and shouldStartAnimation is false as well (meaning that the value has been revealed and animation ended), then we add the current value to the sum we have previously initiated.

We also display the currently selected value above the wheel, as the controller exposes that.

Flutter fortunr wheel result
This is what a usage could look like

Final thoughts

By having used the method that was described in the custom controller tutorial, we were able to quickly create a fortune wheel that exposes its state to the outside and animates making its choice.

If you like what you’ve read, feel free to support me:

🥗Buy me a salad

Leave a Comment