Search code examples
animationflutterwidget

How to shake a widget in Flutter on invalid input?


On my signup form, I have a checkbox which needs to shake a bit whenever the user tries to login before accepting the terms and conditions. How can I achieve something like this Flutter?


Solution

  • import 'package:flutter/material.dart';
    
    @immutable
    class ShakeWidget extends StatelessWidget {
      final Duration duration;
      final double deltaX;
      final Widget child;
      final Curve curve;
    
      const ShakeWidget({
        Key key,
        this.duration = const Duration(milliseconds: 500),
        this.deltaX = 20,
        this.curve = Curves.bounceOut,
        this.child,
      }) : super(key: key);
    
      /// convert 0-1 to 0-1-0
      double shake(double animation) =>
          2 * (0.5 - (0.5 - curve.transform(animation)).abs());
    
      @override
      Widget build(BuildContext context) {
        return TweenAnimationBuilder<double>(
          key: key,
          tween: Tween(begin: 0.0, end: 1.0),
          duration: duration,
          builder: (context, animation, child) => Transform.translate(
            offset: Offset(deltaX * shake(animation), 0),
            child: child,
          ),
          child: child,
        );
      }
    }
    

    If you need to re-enable shaking, just change ShakeWidget key to some random one.