Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Animate a widget on removal from the widget tree, or during the end of it's lifecycle?

I have a GridView which shows custom widgets for the items in the grid. These items have an animation that scale their size from 0 to 100% when they appear in the grid, using an AnimationController.forward() command.

My hope is, that when the list of items in the grid changes and one of these items is no longer in the list, I'd like to reverse the animation before the widget is removed from the tree, to animate it's removal from the grid.

I tried doing a AnimationController.reverse() in the dispose method of the widget, but that doesn't appear to work.

Is there any way to animate a widget during the end of it's lifecycle?

like image 437
a344254 Avatar asked Nov 08 '19 14:11

a344254


1 Answers

You can try this pub https://pub.flutter-io.cn/packages/auto_animated. You can combine your custom animation with this pub and being able to reach the desired behaviour.

// With predefined options
LiveGrid.options(
  options: options,

  // Like GridView.builder, but also includes animation property
  itemBuilder: buildAnimatedItem,

  // Other properties correspond to the `ListView.builder` / `ListView.separated` widget
  itemCount: itemsCount,
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 3,
    crossAxisSpacing: 16,
    mainAxisSpacing: 16,
  ),
);

buildAnimatedItem can be your custom animation, you can define like this:

Widget buildAnimatedItem(
  BuildContext context,
  int index,
  Animation<double> animation,
) =>
  // For example wrap with fade transition
  FadeTransition(
    opacity: Tween<double>(
      begin: 0,
      end: 1,
    ).animate(animation),
    // And slide transition
    child: SlideTransition(
      position: Tween<Offset>(
        begin: Offset(0, -0.1),
        end: Offset.zero,
      ).animate(animation),
      // Paste you Widget
      child: YouWidgetHere(),
    ),
  );

Take a look at the pub Readme is pretty clear

like image 50
FedeH Avatar answered Jun 27 '23 22:06

FedeH