Search code examples
androidflutterflutter-layoutflutter-animationflutter-packages

How to move(with animation) a cell's colored container from one position to another inside generated List from grid view count in flutter?


Here, I have a list. a = [92,93,94,95,81,66,51,36..];

I just want to move my colored cell's container according to the list index with animation.

To understand my question better, in the given image, I want to animate that cell container which is located at index 92, according to a list(a).

Image Example


Solution

  • While we know the box size, we can use getPosition() method to position the circle.

     Offset getPosition(int index) {
        assert(boxWidth != null, "init boxWidth inside layoutBuilder");
        final dx = index <= crossAxisCount
            ? index * boxWidth!
            : (index % crossAxisCount) * boxWidth!;
        final dy = index <= crossAxisCount
            ? 0.0
            : (index / crossAxisCount).floor() * boxWidth!;
        return Offset(dx, dy);
      }
    

    Use like

    AnimatedPositioned(
      duration: const Duration(milliseconds: 400),
      left: getPosition(currentPosition).dx,
      top: getPosition(currentPosition).dy,
      child: Container(
        alignment: Alignment.center,
        width: constraints.maxWidth / crossAxisCount,
        height: constraints.maxWidth / crossAxisCount,
        decoration: const BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.cyanAccent,
        ),
      ),
    ),
    

    Full Snippet On dartpad