Last active
November 6, 2024 09:15
-
-
Save austinevick/dd02703fd218a926290946d6d473155d to your computer and use it in GitHub Desktop.
Flutter pageView animation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Home extends StatefulWidget { | |
const Home({super.key}); | |
@override | |
State<Home> createState() => _HomeState(); | |
} | |
class _HomeState extends State<Home> { | |
final pageController = PageController(viewportFraction: 0.8, initialPage: 1); | |
int currentIndex = 1; | |
int totalItem = 5; | |
late final Timer timer; | |
@override | |
void initState() { | |
timer = Timer.periodic(const Duration(milliseconds: 2000), (t) { | |
if (currentIndex == totalItem - 1) { | |
pageController.animateToPage(0, | |
duration: const Duration(seconds: 1), curve: Curves.ease); | |
} else { | |
pageController.nextPage( | |
duration: const Duration(seconds: 1), curve: Curves.ease); | |
} | |
}); | |
super.initState(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: SafeArea( | |
child: Column( | |
children: [ | |
Expanded( | |
child: PageView.builder( | |
controller: pageController, | |
itemCount: 5, | |
onPageChanged: (value) => setState(() => currentIndex = value), | |
itemBuilder: (context, i) => AnimatedContainer( | |
padding: const EdgeInsets.all(16), | |
// This is where the magic happens | |
margin: EdgeInsets.symmetric( | |
horizontal: 8, vertical: currentIndex == i ? 100 : 150), | |
decoration: BoxDecoration( | |
border: Border.all(), | |
borderRadius: BorderRadius.circular(12), | |
color: currentIndex == i | |
? Colors.black | |
: const Color(0xfff5f8ff)), | |
width: 200, | |
duration: const Duration(milliseconds: 800), | |
child: Center( | |
child: Text( | |
'item $i', | |
style: TextStyle( | |
fontWeight: FontWeight.w800, | |
color: currentIndex == i ? Colors.white : Colors.black, | |
fontSize: 22, | |
), | |
), | |
), | |
), | |
), | |
), | |
], | |
), | |
)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment