Skip to content

Instantly share code, notes, and snippets.

@sgr-ksmt
Last active May 5, 2020 23:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgr-ksmt/83f68b01cec7e97b5beb644f8f2773cb to your computer and use it in GitHub Desktop.
Save sgr-ksmt/83f68b01cec7e97b5beb644f8f2773cb to your computer and use it in GitHub Desktop.
BouncedWidget
Widget buld(BuildContext context) {
return BouncedWidget.create(
child: const SomeListTile(),
bounce: 0.1,
duration: const Duration(milliseconds: 350),
);
}
import 'package:disposable_provider/disposable_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:vsync_provider/vsync_provider.dart';
@immutable
class BouncedWidget extends StatelessWidget {
const BouncedWidget._({
@required this.child,
this.onTap,
}) : assert(child != null);
static Widget create({
@required Widget child,
VoidCallback onTap,
double bounce = 0.05,
Duration duration = const Duration(milliseconds: 200),
}) {
assert(child != null);
assert(bounce != null);
assert(duration != null);
return MultiProvider(
providers: [
const VsyncProvider(),
DisposableProvider(
create: (context) => _Controller(
bounce: bounce,
duration: duration,
vsync: VsyncProvider.of(context),
),
),
],
child: BouncedWidget._(
child: child,
onTap: onTap,
),
);
}
final Widget child;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final controller = context.watch<_Controller>();
return GestureDetector(
onTapDown: (_) => controller.forward(),
onTapUp: (_) => controller.reverse(),
onTapCancel: controller.reverse,
onTap: onTap,
child: AnimatedBuilder(
animation: controller.animation,
builder: (_, child) {
return Transform.scale(
scale: controller.animation.value,
child: child,
);
},
child: child,
),
);
}
}
class _Controller implements Disposable {
_Controller({
@required TickerProvider vsync,
this.bounce,
Duration duration,
}) : _animationController = AnimationController(
vsync: vsync,
duration: duration,
);
final AnimationController _animationController;
final double bounce;
Animation<double> get animation => _animationController.drive(
Tween(
begin: 1,
end: 1 - bounce,
),
);
void forward() => _animationController.forward();
void reverse() => _animationController.reverse();
@override
void dispose() {
_animationController.dispose();
}
}
@sgr-ksmt
Copy link
Author

sgr-ksmt commented May 5, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment