In Flutter, SlideTransition
is a widget that animates the position of its child widget by sliding it along a given axis. It is used to create a slide transition effect, where the child widget moves smoothly from its initial position to its final position.
Construction
SlideTransition({
Key? key,
required Animation<Offset> position,
Widget? child,
bool transformHitTests = true,
Offset? offset = Offset.zero,
})
Parameters
position
: The animation that controls the slide transition.child
: The child widget to be animated.transformHitTests
: Whether to apply the slide transition to hit testing. Defaults to true.offset
: The initial offset of the child widget. Defaults toOffset.zero
.
Example
import 'package:flutter/material.dart';
class SlideTransitionScreen extends StatefulWidget {
const SlideTransitionScreen({Key? key}) : super(key: key); // Removed unused parameter.
@override
_SlideTransitionScreenState createState() => _SlideTransitionScreenState();
}
class _SlideTransitionScreenState extends State<SlideTransitionScreen> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<Offset> _animation;
@override
void initState() {
super.initState();
// Initialize AnimationController with 2-second duration and repeat it with reverse.
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
)..repeat(reverse: true);
// Tween from Offset(-1, 0) to Offset(1, 0) for sliding horizontally.
_animation = Tween<Offset>(begin: Offset(-1, 0), end: Offset(1, 0)).animate(_controller);
}
@override
void dispose() {
// Dispose of the controller when no longer needed to avoid memory leaks.
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("SlideTransition Example"),
flexibleSpace: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.deepPurple, Colors.orangeAccent],
begin: Alignment.topLeft,
end: Alignment.topRight,
),
),
),
),
body: Center(
child: SlideTransition(
position: _animation,
child: Container(
width: 200,
height: 100,
color: Colors.blue,
),
),
),
);
}
}