Last active
May 16, 2022 16:26
-
-
Save craiglabenz/3403bbf8de997a1875d0a54b9efe1107 to your computer and use it in GitHub Desktop.
Demonstrates how ImplicitlyAnimatedWidgets (might) work
This file contains 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
import 'package:flutter/material.dart'; | |
const Color darkBlue = Color.fromARGB(255, 18, 32, 47); | |
final colors = [Colors.red, Colors.blue]; | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatefulWidget { | |
@override | |
State<MyApp> createState() => _MyAppState(); | |
} | |
class _MyAppState extends State<MyApp> { | |
int index = 0; | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: ThemeData.dark().copyWith( | |
scaffoldBackgroundColor: darkBlue, | |
), | |
debugShowCheckedModeBanner: false, | |
home: Center( | |
child: GestureDetector( | |
onTap: () => setState(() => index = index == 0 ? 1 : 0), | |
child: ImplicitWidget(color: colors[index]), | |
), | |
), | |
); | |
} | |
} | |
class ImplicitWidget extends StatefulWidget { | |
const ImplicitWidget({super.key, required this.color, this.curve}); | |
final Color color; | |
final Curve? curve; | |
@override | |
State<ImplicitWidget> createState() => _ImplicitWidgetState(); | |
} | |
class _ImplicitWidgetState extends State<ImplicitWidget> | |
with SingleTickerProviderStateMixin { | |
late Color color; | |
Color? startOfAnimationColor; | |
late AnimationController controller; | |
@override | |
void initState() { | |
color = widget.color; | |
controller = | |
AnimationController(vsync: this, duration: const Duration(seconds: 1)); | |
super.initState(); | |
} | |
@override | |
void didUpdateWidget(covariant ImplicitWidget oldWidget) { | |
if (oldWidget.color != widget.color) { | |
_animateColor(widget.color); | |
} | |
super.didUpdateWidget(oldWidget); | |
} | |
void _animateColor(Color newColor) { | |
startOfAnimationColor = color; | |
Animation tween = Tween<double>(begin: 0, end: 1).animate( | |
CurvedAnimation( | |
parent: controller, | |
curve: widget.curve ?? Curves.linear, | |
), | |
); | |
tween.addListener(() { | |
print(widget.color); | |
setState(() { | |
color = Color.lerp( | |
startOfAnimationColor, | |
newColor, | |
tween.value, | |
)!; | |
}); | |
}); | |
controller..reset()..forward(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Container(height: 100, width: 100, color: color); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment