Skip to content

Instantly share code, notes, and snippets.

@sgr-ksmt
Last active May 5, 2020
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@sgr-ksmt sgr-ksmt commented May 5, 2020

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