A detailed explanation of the animation in flutter The most complete animation in the whole network


foreword

insert image description here

Learning animations and transitions in Flutter is one of the key parts of building fluid user interfaces. Here I have compiled a main learning path that can help you gradually master the animation and transition techniques in Flutter, hoping to help you


1. Basic concepts

Before getting started, it's important to understand some basic animation and transition concepts. Learn what animations, transitions are, and their role in user experience.

Animation: Animation is the process of smoothly transitioning an element from one state to another over a period of time. In the user interface, animation can make the changes of elements appear more vivid and smooth, and improve the user experience. For example, a button whose color transitions from one color to another, or an icon that smoothly moves from one position to another, are examples of animation.

Transition: A transition is a smooth process from one visual state to another. Transitions are often used when switching between user interfaces or changing the state of elements to make those changes look more natural and fluid. Transitions can be visual effects, such as gradients, rotations, scaling, etc., or switching effects between elements, such as transition effects between pages.

Animation types: In Flutter, there are various types of animations, including:

  • Implicit animation: When the value of the property changes, the transition effect is automatically generated without explicitly writing animation code.
  • Show animation: Manually control the progress of the animation, use Animationand AnimationControllerto manage the state of the animation.
  • Transition animations: Make smooth transition effects between page transitions or visual elements, such as Hero transitions.
  • Gesture animation: Trigger animation effects in response to user gesture events (such as dragging, zooming, etc.).
  • Custom Animations: CustomPainterCreate highly customized animations with custom graphics, paths, and animation effects.

Animation Curves and Interpolation: Animation Curves and Interpolation determine the speed and rate of change of animations. The curve describes how the animated value changes over time, and the interpolation defines how the value changes along the way from the start value to the end value. In Flutter, you can Curvesuse the built-in curves through the class, and you can also use Tweenthe class to define interpolation.

Animation performance and optimization: Performance is an important consideration when creating animations. Improper animation design can lead to poor application performance. As such, techniques for optimizing animation redraw ranges, frame rates, and re-rendering are all part of the learning curve.

Knowing these fundamental concepts will give you a solid foundation to further dive into animations and transitions in Flutter. After mastering these concepts, you'll be able to better understand different types of animations and transitions, and be able to more easily apply them to create pleasing user interfaces.

2. Implicit animation

Implicit animation (Implicit Animations) is a simple form of animation in Flutter, which automatically produces smooth transition effects through property changes without explicitly writing a large amount of animation code. This makes it very easy to create basic animation effects.

In implicit animation, you only need to change the property values ​​of widgets, such as color, position, transparency, etc., and Flutter will automatically create smooth transition effects between these property values ​​to achieve the effect of animation. Here are some common use cases and properties of implicit animations:

  1. AnimatedContainer: When you change AnimatedContainerthe properties of (such as color, width, height, alignmentetc.), it will produce a smooth transition between these properties.
AnimatedContainer(
  duration: Duration(seconds: 1),
  color: _isBlue ? Colors.blue : Colors.red,
  width: _isExpanded ? 200.0 : 100.0,
  height: _isExpanded ? 200.0 : 100.0,
  child: YourChildWidget(),
);
  1. AnimatedOpacity: By changing the property AnimatedOpacityof opacitythe , you can create a smooth transition of transparency.
AnimatedOpacity(
  duration: Duration(seconds: 1),
  opacity: _isVisible ? 1.0 : 0.0,
  child: YourChildWidget(),
);
  1. AnimatedPositioned: Use AnimatedPositionedto create a smooth transition of the widget's position.
Stack(
  children: [
    AnimatedPositioned(
      duration: Duration(seconds: 1),
      left: _isLeftAligned ? 0 : 100,
      top: _isTopAligned ? 0 : 100,
      child: YourChildWidget(),
    ),
  ],
);
  1. Other Implicit Animations: There are many other implicit animation widgets such as AnimatedPadding, AnimatedAlign, , AnimatedDefaultTextStyleetc., which all follow a similar principle of automatically producing transition effects by changing properties.

Implicit animation is a great starting point for learning about animations, it will give you a quick overview of how to create simple smooth transitions in Flutter. However, for more complex animation needs, you may want to use display animations (using Animationand AnimationController) or custom animations for finer control over the animation process.

3. Display animation

Display animation (Explicit Animations) is a form of animation manually controlled in Flutter, using Animationand AnimationControllerto achieve. Explicit animations provide more flexibility than implicit animations, allowing you to more precisely control the animation's progress, effects, and interactions.

Following are the main concepts and steps to display animation:

1. Animation 和 AnimationController:

  • AnimationControllerIs a class that controls the animation, which manages the state of the animation, such as start, stop, forward or reverse playback, etc.
  • AnimationRepresents the current state of the animation, which is a mutable value within the specified range. Animated values ​​change over time and can be used to control properties of UI elements to create animation effects.

2. Tween: Tween is a class used to define animation interpolation, which maps the input range of the animation to the output range. For example, you can use Tweento map animation values ​​from 0 to 1, or from a start value to an end value.

3. Monitor animation values: You can Animationupdate UI elements by monitoring the value changes of to achieve animation effects. For example, you can use to associate AnimatedBuildera widget with Animationa , causing the widget to rebuild when an animated value changes.

AnimationController controller = AnimationController(
  vsync: this,
  duration: Duration(seconds: 2),
);

Animation<double> animation = Tween(begin: 0.0, end: 1.0).animate(controller);

controller.forward(); // 启动动画

// 使用 AnimatedBuilder 监听动画值变化
AnimatedBuilder(
  animation: animation,
  builder: (context, child) {
    
    
    return Opacity(
      opacity: animation.value,
      child: YourChildWidget(),
    );
  },
);

4. Curves and animation curves: By using Curvesthe class, you can define the rate of change of the animation, which affects the feel of the animation effect. For example, you could use Curves.easeInOutto create an animation curve that accelerates and then decelerates.

5. Animation state monitoring: AnimationController Provides many callback methods, for example addStatusListener, you can monitor animation state changes (such as animation start, end, reverse, etc.).

controller.addStatusListener((status) {
    
    
  if (status == AnimationStatus.completed) {
    
    
    // 动画完成
  } else if (status == AnimationStatus.dismissed) {
    
    
    // 动画反向播放完成
  }
});

Reveal animations are suitable for situations that require finer control and customization of animation effects, such as triggering animations on user interaction, creating complex animation sequences, and more. However, for some basic smooth transition effects, implicit animation may be more convenient.

4. Transition

Transitions are smooth transitions from one state to another in a user interface. In Flutter, transitions generally involve animating between UI elements to achieve a transition in the user interface. Transitions can produce smooth effects when switching between pages, or when changing properties within a single widget.

Here are some common transition scenarios and examples of how to implement them:

1. Page transitions: Page transitions are the way to create a smooth effect between different screens. Flutter provides PageRouteBuilderto help you customize page transitions.

class CustomPageRoute<T> extends PageRoute<T> {
    
    
  // 实现页面过渡效果
}

Navigator.of(context).push(CustomPageRoute(builder: (context) => NextScreen()));

2. Hero transitions: Hero transitions are used to smoothly transfer shared elements between two pages. For example, clicking an icon in a page can use the Hero transition to transition the icon from the current page to the target page.

class FirstPage extends StatelessWidget {
    
    
  
  Widget build(BuildContext context) {
    
    
    return GestureDetector(
      onTap: () {
    
    
        Navigator.of(context).push(MaterialPageRoute(
          builder: (context) => SecondPage(),
        ));
      },
      child: Hero(
        tag: 'iconTag',
        child: Icon(Icons.star),
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
    
    
  
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      body: Center(
        child: Hero(
          tag: 'iconTag',
          child: Icon(Icons.star),
        ),
      ),
    );
  }
}

3. Attribute transition inside a widget: You can also change attributes inside a single widget to achieve transition effects, such as changing color, position, size, etc.

class PropertyTransitionWidget extends StatefulWidget {
    
    
  
  _PropertyTransitionWidgetState createState() => _PropertyTransitionWidgetState();
}

class _PropertyTransitionWidgetState extends State<PropertyTransitionWidget> {
    
    
  double _width = 100.0;

  void _toggleSize() {
    
    
    setState(() {
    
    
      _width = _width == 100.0 ? 200.0 : 100.0;
    });
  }

  
  Widget build(BuildContext context) {
    
    
    return GestureDetector(
      onTap: _toggleSize,
      child: AnimatedContainer(
        duration: Duration(seconds: 1),
        width: _width,
        height: 100.0,
        color: Colors.blue,
      ),
    );
  }
}

Transitions play a key role in improving UI fluidity and user experience. Whether it's page transitions, shared element passing, or property changes inside widgets, by properly applying transition effects, you can bring a more alive and natural feel to your app.

5. Gesture animation

Gesture-based Animations is a technology that triggers and controls animation effects by responding to user gesture events. In Flutter, you can use GestureDetectorand other gesture recognizers to capture user gestures, and then start, stop, or change animations based on these actions.

Here are the main steps and examples of gesture animation:

1. Use GestureDetector: GestureDetector It is a widget used to capture various gesture events, such as click, drag, zoom, etc. You can wrap widgets that need to respond to gestures in GestureDetectora .

GestureDetector(
  onTap: () {
    
    
    // 响应点击事件
  },
  onPanUpdate: (details) {
    
    
    // 响应拖拽事件
  },
  onScaleUpdate: (details) {
    
    
    // 响应缩放事件
  },
  child: YourAnimatedWidget(),
)

2. Update animation state based on gestures: Based on captured gesture events, you can update the state of the animation, such as changing the value of the animation, playing, pausing, or reversing the animation.

GestureDetector(
  onPanUpdate: (details) {
    
    
    setState(() {
    
    
      // 更新动画值
      animationValue += details.delta.dx / 100;
    });
  },
  child: YourAnimatedWidget(),
)

3. Gesture recognizers and gesture details: In addition GestureDetector, Flutter also provides many other gesture recognizers, such as Draggable, Dismissible, , ScaleGestureDetectoretc., which can capture specific types of gesture events and provide detailed information about gestures.

Draggable(
  onDraggableCanceled: (Velocity velocity, Offset offset) {
    
    
    // 响应拖拽取消事件
  },
  child: YourAnimatedWidget(),
)

4. Combining animation effects: Combine captured gesture events with animation effects to create gesture-triggered animation effects. You can update the animated value based on the gesture and then apply that value to the widget.

double _animationValue = 0.0;

GestureDetector(
  onPanUpdate: (details) {
    
    
    setState(() {
    
    
      _animationValue += details.delta.dx / 100;
    });
  },
  child: AnimatedBuilder(
    animation: _controller,
    builder: (context, child) {
    
    
      return Transform.translate(
        offset: Offset(_animationValue * 100, 0),
        child: YourAnimatedWidget(),
      );
    },
  ),
)

Gesture animation allows users to interact with applications in an intuitive way, and can trigger various animation effects through gesture operations, thereby improving user experience. Whether it's dragging, zooming, swiping, or other gestures, by properly applying gesture animations, you can add more interactivity and fun to your app.

Six, complex animation

Complex animations (Complex Animations) usually refer to animation scenes that involve multiple animation elements, sequence animations, interlaced animations, etc., and require more fine-grained control during design and implementation. These animations often involve multiple animation values, different animation controllers, and coordinating the synchronization or sequence of multiple animations.

The following are the main concepts and steps of a complex animation:

1. Staggered animations: Staggered animations are multiple animations running at the same time, but their start times may be shifted to create a patchwork effect. You can Intervalimplement staggered animations by using the class to define start and end times for each animation.

Animation<double> animation1 = _controller.drive(Tween(begin: 0.0, end: 1.0));
Animation<double> animation2 = _controller.drive(Tween(begin: 0.0, end: 1.0));
Animation<double> animation3 = _controller.drive(Tween(begin: 0.0, end: 1.0));

Interval interval1 = Interval(0.0, 0.33);
Interval interval2 = Interval(0.33, 0.66);
Interval interval3 = Interval(0.66, 1.0);

Animation<double> anim1 = CurvedAnimation(parent: _controller, curve: interval1);
Animation<double> anim2 = CurvedAnimation(parent: _controller, curve: interval2);
Animation<double> anim3 = CurvedAnimation(parent: _controller, curve: interval3);

// 使用 anim1、anim2、anim3 分别作用于不同的动画部件

2. Chain animation: Chain animation is a way to trigger the next animation after the animation is completed. You can use the state listener of the animation controller to detect the state change of the animation, and then trigger the next animation according to the state.

_animation1.addStatusListener((status) {
    
    
  if (status == AnimationStatus.completed) {
    
    
    _controller2.forward(); // 触发第二个动画
  }
});

_animation2.addStatusListener((status) {
    
    
  if (status == AnimationStatus.completed) {
    
    
    _controller3.forward(); // 触发第三个动画
  }
});

3. Animation sequence: An animation sequence is a group of animations played in a certain order, usually used to create continuous animation effects. You can use multiple AnimationControllerand CurvedAnimationand trigger the next animation after each animation completes.

_animationController1.forward();
_animationController1.addStatusListener((status) {
    
    
  if (status == AnimationStatus.completed) {
    
    
    _animationController2.forward();
  }
});

_animationController2.addStatusListener((status) {
    
    
  if (status == AnimationStatus.completed) {
    
    
    _animationController3.forward();
  }
});

4. Multiple animation values: In complex animations, multiple animation values ​​may be involved, you need to create multiple Animationand apply them to different widgets.

Animation<double> animation1 = _controller.drive(Tween(begin: 0.0, end: 1.0));
Animation<double> animation2 = _controller.drive(Tween(begin: 0.0, end: 1.0));

AnimatedBuilder(
  animation: _controller,
  builder: (context, child) {
    
    
    return Transform.translate(
      offset: Offset(animation1.value * 100, animation2.value * 100),
      child: YourAnimatedWidget(),
    );
  },
)

5. Combined animation: Combined animation is to combine multiple animation effects together, such as rotation and scaling. You can use Transformto combine multiple transformations (such as translation, rotation, scaling) to create combined animations.

Transform(
  transform: Matrix4.rotationZ(animation1.value) * Matrix4.diagonal3Values(animation2.value, animation2.value, 1.0),
  child: YourAnimatedWidget(),
)

Complex animations require more advanced animation control and coordination skills to ensure that multiple animations are synchronized and perform as expected. By understanding these concepts, you will be able to implement more complex and richer animation scenarios in your application.

Seven, custom animation

Custom Animations (Custom Animations) refers to the realization of specific animation effects through custom codes to meet specific design requirements. In Flutter, you can use CustomPainterto draw custom graphics, or use to AnimatedBuilderencapsulate animation logic to create highly customized animation effects.

Here are the main steps and examples for custom animations:

1. CustomPainter: Use CustomPainterto draw custom graphics and animations. You need to implement CustomPainterthe class and override paintthe method, where you define your drawing logic.

class MyCustomPainter extends CustomPainter {
    
    
  
  void paint(Canvas canvas, Size size) {
    
    
    // 在这里实现自定义绘制逻辑
  }

  
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    
    
    return true; // 控制是否需要重新绘制
  }
}

class MyCustomAnimationWidget extends StatelessWidget {
    
    
  
  Widget build(BuildContext context) {
    
    
    return CustomPaint(
      painter: MyCustomPainter(),
      child: YourChildWidget(),
    );
  }
}

2. Use AnimatedBuilder to encapsulate animation logic: AnimatedBuilder it is a widget for encapsulating animation logic, which accepts an animation as a parameter, and rebuilds the widget when the animation value changes.

AnimationController _controller = AnimationController(
  vsync: this,
  duration: Duration(seconds: 2),
);

Animation<double> _animation = CurvedAnimation(
  parent: _controller,
  curve: Curves.easeInOut,
);


Widget build(BuildContext context) {
    
    
  return AnimatedBuilder(
    animation: _animation,
    builder: (context, child) {
    
    
      return Transform.scale(
        scale: _animation.value,
        child: YourChildWidget(),
      );
    },
  );
}

3. Custom path animation: use it CustomPainter, you can draw any shape of path, and change the properties of the path in the animation to achieve the path animation effect.

class PathAnimationPainter extends CustomPainter {
    
    
  PathAnimationPainter(this.animation);

  final Animation<double> animation;

  
  void paint(Canvas canvas, Size size) {
    
    
    // 创建自定义路径
    Path path = createPathWithAnimation(animation.value, size);
    
    // 在画布上绘制路径
    canvas.drawPath(path, paint);
  }

  
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    
    
    return true;
  }
}

Custom animations allow you to take full control over animation effects, from drawing custom shapes and paths to creating your own animation logic. Whether creating specific graphic animations or implementing unique animation interactions, custom animations give you a lot of freedom.

Eight, physical animation

Physics-based Animations is an animation effect that simulates real physical phenomena, such as bouncing, inertia, etc. In Flutter, you can use the Tween, AnimationControllerand physics simulators to create these effects.

Here are the main steps and examples for physical animation:

1. Use Tweenand AnimationController: Like other animation types, you can use Tweento define the start value and end value of the animation, and to AnimationControllercontrol the progress of the animation.

AnimationController _controller = AnimationController(
  vsync: this,
  duration: Duration(seconds: 1),
);

Animation<double> _animation = Tween(begin: 0.0, end: 1.0).animate(_controller);

2. Use the physical simulator ( SpringSimulation): SpringSimulation It is a physical simulator used to realize physical animation effects such as bouncing and inertia. You can use Simulationobjects to simulate the physics of animation.

final SpringDescription _spring = SpringDescription(
  mass: 1,
  stiffness: 100,
  damping: 10,
);

final SpringSimulation _sim = SpringSimulation(_spring, 0, 1, 0);

3. Apply physics simulation to animation: Combine physics simulation with animation controllers to apply physics effects during the animation process.

_controller.animateWith(_sim);

4. Parameter adjustment of physical animation: Adjusting SpringDescriptionthe parameters (mass, stiffness, damping) will affect the animation effect. Different parameter settings will produce different elastic and inertial effects.

final SpringDescription _customSpring = SpringDescription(
  mass: 2,
  stiffness: 300,
  damping: 15,
);

5. Application of physical animation: Physical animation is usually used to simulate physical phenomena in the real world, such as bouncing buttons, scrolling with inertial effects, etc. When applying physical animation, you can adjust the simulation parameters according to actual needs to achieve the desired effect.

Physical animations can add more realistic interactions and dynamics to your app. By simulating physical phenomena, you can make your interface look more natural and attractive.

9. Flutter animation library

Flutter provides many built-in libraries for creating various types of animations. Here are some commonly used Flutter animation libraries and their functions:

  1. flutter_animation_progress_bar: A progress bar library with animation effects, which can add cool loading indicators to the application.
  2. flutter_staggered_animations: Provides a set of ordered animation effects that can trigger animations in a specific order to create complex animation sequences.
  3. flutter_sequence_animation: Used to create complex sequence animations, which can trigger a series of animations at time intervals.
  4. liquid_swipe: Provides a fluid page switching animation effect, which can create a transition effect of card stacking.
  5. flare_flutter: Allows integrating vector animations created with the Flare tool into Flutter apps for creating highly customized vector animations.
  6. lottie: After Effects animations created with the Lottie tool can be integrated into Flutter apps to showcase complex vector animations.
  7. motion_widget: Provide a set of predefined animation effects, you can easily add different transition animations, such as fade in and fade out, slide, etc.
  8. flip_panel: Create a panel that can be flipped, used to display numbers, letters, etc., with a flip animation effect.
  9. sliver_fab_animation: Implemented a linkage animation between SliverAppBar and FloatingActionButton, which is used to hide or display FloatingActionButton when scrolling.
  10. animated_text_kit: Provides a set of widgets for creating animated text effects, such as color gradients, typewriter effects, and more.
  11. flutter_animator: Provides a set of predefined animation effects, and various animation effects can be applied through simple configuration parameters.

These are some commonly used Flutter animation libraries, which can help you achieve different types of animation effects more easily, thereby improving the user experience of your application. According to your specific needs, you can choose the animation library suitable for your project, or conduct custom development as needed

10. Animation performance and optimization

Animation performance and optimization are very important in application development, because unreasonable animation design may cause application performance degradation and affect user experience. Here are some important considerations for animation performance and optimization:

1. Select the appropriate animation type: According to your application requirements, select the appropriate animation type. Implicit animation is usually lightweight and suitable for simple transition effects, while explicit animation is suitable for animation scenes that require fine control.

2. Reduce animation frame rate: Excessively high animation frame rate may occupy too much CPU and GPU resources, causing performance problems. Depending on the performance requirements of the application, the animation frame rate can be set to 30 or 60 frames.

3. Avoid unnecessary animations: Avoid running multiple unnecessary animations on the screen at the same time, as this may cause performance degradation. Animations should only be used when they have real value to the user experience.

4. Use hardware acceleration: Flutter enables GPU hardware acceleration by default, which can significantly improve animation performance. Make sure your app is properly configured to take advantage of hardware acceleration.

5. Avoid frequent rebuilding of widgets: Rebuilding widgets too frequently may cause unnecessary layout calculations and drawing operations, affecting performance. Use AnimatedBuilderetc. to limit rebuilds.

6. Optimize layout and drawing: Streamline layout and drawing operations to avoid frequent layout changes during animation. Minimize complex layout and drawing operations to reduce performance overhead.

7. Use cache: If the content in the animation does not change frequently, you can consider using a cache mechanism to reduce unnecessary redrawing.

8. Avoid animation chains: Avoid starting one animation immediately before the next one ends, which can cause performance issues. Animation state monitoring can be used to ensure animations are in the correct order.

9. Limit the animation range: Limit the redrawing range of the animation, and only update the part affected by the animation. For example, use ClipRector ClipRRectto limit the animation area.

10. Use ValueListenableBuilder: For the animation inside the widget, you can use ValueListenableBuilderto monitor the change of the property value to avoid unnecessary reconstruction.

11. Perform performance testing: Use performance testing tools (such as Flutter DevTools) to monitor performance indicators such as animation frame rate and memory usage, and look for potential performance problems.

Through reasonable animation design and performance optimization, you can ensure that the performance of the application is fully maintained while providing an excellent user experience.

11. Third-party animation library

In Flutter, there are many third-party animation libraries to choose from, which can help you easily achieve various complex animation effects. The following are some commonly used third-party animation libraries:

  1. Rive (formerly Flare): Rive allows you to use the Flare tool to create complex vector animations and then integrate them into your Flutter app. It supports interactive, highly customizable vector animations.
  2. Lottie: The Lottie library can export animations created with Adobe After Effects as JSON files, and then play these animations in Flutter apps. Lottie supports various types of animation effects, such as shape change, color change, animation combination, etc.
  3. Motion: Motion is a powerful animation library that provides a variety of exquisite transition animation effects, such as gradients, slides, rotations, etc. It makes it easy to animate widgets and pages.
  4. Staggered Animations: This library provides a set of ordered animation effects, suitable for creating complex animation sequences. You can trigger animations on widgets in a specific order to achieve staggered animation effects.
  5. Smooth Page Indicator: This library can help you create various smooth page indicators, such as dots, lines, sliders, etc., to indicate switching between pages.
  6. Flip Panel: The Flip Panel library can create panels that can be flipped, used to display numbers, letters, etc., with flip animation effects.
  7. Curved Navigation Bar: This library helps you create a bottom navigation bar with a curved effect, supports custom colors, icons, and more.
  8. Animated Text Kit: This library provides a variety of animated text effects, such as color gradients, typewriter effects, etc. Suitable for adding vivid animation effects on text.
  9. Smooth Animation: This library focuses on creating smooth animation effects, providing a variety of animation styles, such as translation, rotation, scaling, etc.
  10. Liquid Swipe: The Liquid Swipe library can help you create fluid page switching animation effects, suitable for creating transition effects for card stacking.

These third-party animation libraries can greatly simplify the implementation process of complex animations, thus adding more dynamics and creativity to your applications. When choosing third-party libraries, make sure they match your project needs and design style for a better user experience


Summarize

Learning these contents step by step, from basic to advanced, can make you more confident in handling various animations and transition effects when developing Flutter applications. Practice and practice are the key to mastering these techniques, so keep experimenting with different animation scenarios and applying what you learn to your projects.

The whole article is 14,000 words, I hope it can help you, see this, give me a thumbs up

Guess you like

Origin blog.csdn.net/u010755471/article/details/132314100