Voici un exemple de code Flutter impressionnant qui combine animations complexes, effets visuels et interactions utilisateur. Ce code crée une AppBar personnalisée avec une animation de morphing entre un état compact et un état de recherche expansible :
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'AppBar Morphing Animation',
theme: ThemeData.dark(),
home: Scaffold(body: MorphingAppBar()),
);
}
}
class MorphingAppBar extends StatefulWidget {
@override
_MorphingAppBarState createState() => _MorphingAppBarState();
}
class _MorphingAppBarState extends State<MorphingAppBar>
with TickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _expandAnimation;
final double maxAppBarHeight = 200.0;
final double minAppBarHeight = 60.0;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: Duration(milliseconds: 500),
vsync: this,
);
_expandAnimation = Tween<double>(begin: 0, end: 1).animate(
CurvedAnimation(
parent: _controller,
curve: Curves.easeOutCubic,
reverseCurve: Curves.easeInCubic,
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _handleDragUpdate(DragUpdateDetails details) {
if (details.primaryDelta! > 0) {
_controller.value -= details.primaryDelta! / maxAppBarHeight;
} else {
_controller.value -= details.primaryDelta! / maxAppBarHeight;
}
_controller.value = _controller.value.clamp(0.0, 1.0);
}
@override
Widget build(BuildContext context) {
return NestedScrollView(
headerSliverBuilder: (context, _) => [
SliverPersistentHeader(
pinned: true,
delegate: _MorphingAppBarDelegate(
expandAnimation: _expandAnimation,
controller: _controller,
onVerticalDragUpdate: _handleDragUpdate,
minExtent: minAppBarHeight,
maxExtent: maxAppBarHeight,
),
),
],
body: Center(child: Text('Contenu principal')),
);
}
}
class _MorphingAppBarDelegate extends SliverPersistentHeaderDelegate {
final Animation<double> expandAnimation;
final AnimationController controller;
final Function(DragUpdateDetails) onVerticalDragUpdate;
final double minExtent;
final double maxExtent;
_MorphingAppBarDelegate({
required this.expandAnimation,
required this.controller,
required this.onVerticalDragUpdate,
required this.minExtent,
required this.maxExtent,
});
@override
Widget build(
BuildContext context,
double shrinkOffset,
bool overlapsContent,
) {
return AnimatedBuilder(
animation: expandAnimation,
builder: (context, child) {
final appBarHeight = lerpDouble(minExtent, maxExtent, expandAnimation.value)!;
final searchOpacity = expandAnimation.value;
return Container(
height: appBarHeight,
color: Colors.deepPurple.withOpacity(0.9),
child: Stack(
fit: StackFit.expand,
children: [
// Fond ondulé personnalisé
Positioned.fill(
child: CustomPaint(
painter: WavePainter(progress: expandAnimation.value),
),
),
// Titre principal
Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: EdgeInsets.only(left: 20 + (1 - searchOpacity) * 40),
child: Text(
'Mon App',
style: TextStyle(
fontSize: 24 + (searchOpacity * 8),
fontWeight: FontWeight.bold,
color: Colors.white.withOpacity(1 - searchOpacity),
),
),
),
),
// Barre de recherche
Opacity(
opacity: searchOpacity,
child: Transform.translate(
offset: Offset(0, -20 * (1 - searchOpacity)),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
child: Container(
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.2),
borderRadius: BorderRadius.circular(30),
),
child: TextField(
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
border: InputBorder.none,
prefixIcon: Icon(Icons.search, color: Colors.white70),
hintText: 'Rechercher...',
hintStyle: TextStyle(color: Colors.white60),
),
),
),
),
),
),
// Icônes d'actions
Positioned(
right: 20,
bottom: 10,
child: Row(
children: [
IconButton(
icon: Icon(Icons.notifications, size: 24),
onPressed: () {},
),
SizedBox(width: 10),
GestureDetector(
onVerticalDragUpdate: onVerticalDragUpdate,
onVerticalDragEnd: (details) {
if (details.primaryVelocity! > 0) {
controller.forward();
} else {
controller.reverse();
}
},
child: Icon(
Icons.drag_handle,
color: Colors.white.withOpacity(0.7),
),
),
],
),
),
],
),
);
},
);
}
@override
bool shouldRebuild(_MorphingAppBarDelegate oldDelegate) {
return oldDelegate.expandAnimation != expandAnimation ||
oldDelegate.controller != controller;
}
}
class WavePainter extends CustomPainter {
final double progress;
WavePainter({required this.progress});
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.deepPurple.shade800.withOpacity(0.3)
..style = PaintingStyle.fill;
final path = Path();
final double waveHeight = 20 * progress;
path.moveTo(0, size.height);
for (int i = 0; i <= size.width; i += 20) {
final double x = i.toDouble();
final double y = size.height -
(waveHeight * (1 + sin(x * 0.1 + progress * 10)));
path.lineTo(x, y);
}
path.lineTo(size.width, size.height);
path.close();
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(WavePainter oldDelegate) {
return oldDelegate.progress != progress;
}
}
Ce code démontre plusieurs concepts avancés de Flutter :
- Animations complexes : Utilisation d'AnimationController avec des courbes personnalisées
- Gestes tactiles : Détection de swipe vertical pour contrôler l'animation
- Peinture personnalisée : CustomPainter pour créer des vagues dynamiques
- Stacks et transformations : Combinaison de Transform et Opacity pour des effets visuels
- Gestion d'état avancée : Coordination entre différents widgets via des animations
- Effets de profondeur : Superposition de widgets avec transparence et ombres
- UI réactive : Adaptation de l'interface selon l'état d'expansion
Pour utiliser ce code :
- Créez un nouveau projet Flutter
- Remplacez le contenu de main.dart par ce code
- Lancez l'application sur un émulateur ou un appareil
L'AppBar se transforme en glissant vers le haut pour révéler une barre de recherche avec un fond ondulé animé. L'effet combine des transitions fluides, des gestes personnalisés et un dessin personnalisé pour un résultat visuel impressionnant.