I tried to implement list of draggable widget using GestureDetector
and AnimationBuilder
. But when the particular widget is removed from tree its AnimationController
is assigned to next widget in list like those controllers never removed from tree after disposing that widget.
You can see in this video that after removing element from list I reset animationController
of that element, but next element’s animation resets and that element’s animation status is forward to next.
Here is block of that widget which is directly called in ListView.builder
.
class _CartItemCardState extends State<CartItemCard> with SingleTickerProviderStateMixin {
final CartController cartController = Get.find();
late AnimationController animationController;
double positionX = 0, prevPositionX = 0;
@override
void initState() {
animationController = AnimationController(vsync: this, duration: Durations.medium2, lowerBound: 0, upperBound: 25.w);
super.initState();
}
void _resetAnimation() {
animationController.reset();
}
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(horizontal: 5.w),
decoration: BoxDecoration(color: Colors.redAccent, borderRadius: BorderRadius.circular(15)),
child: Stack(
alignment: Alignment.centerRight,
children: [
InkWell(
onTap: () {
_resetAnimation();
cartController.addedItemList.remove(widget.foodModel);
},
child: Padding(
padding: EdgeInsets.all(5.w),
child: Text(
"Remove",
style: TextHelper.size14.copyWith(color: AppColors.whiteColor, fontFamily: poppinsBoldFont),
),
),
),
GestureDetector(
onHorizontalDragUpdate: (details) {
if (prevPositionX < details.globalPosition.dx) {
animationController.value -= 25.w * 0.05;
} else {
animationController.value += 25.w * 0.05;
}
if (animationController.value < 0) {
animationController.value = 0;
} else if (animationController.value > 25.w) {
animationController.value = 25.w;
}
setState(() {
prevPositionX = details.globalPosition.dx;
});
},
onHorizontalDragEnd: (details) {
if (animationController.value < 12.5.w) {
animationController.reverse(from: animationController.value);
} else {
animationController.forward(from: animationController.value);
}
},
child: AnimatedBuilder(
builder: (context, child) {
return Transform.translate(
offset: Offset(-animationController.value, 0),
child: child!,
);
},
animation: Tween<double>(begin: 0, end: 25.w).animate(animationController),
child: ...,
),
),
],
),
);
}
}
I tried disposing all controllers but it throws error for next elements animation.
I implemented this in separate widget so that I don’t have to manage list of animationControllers
.