Skip to content

Instantly share code, notes, and snippets.

@HayesGordon
Created July 30, 2022 09:42
Show Gist options
  • Save HayesGordon/9207e2c39b46efb90dc8280f01832f9a to your computer and use it in GitHub Desktop.
Save HayesGordon/9207e2c39b46efb90dc8280f01832f9a to your computer and use it in GitHub Desktop.
Dynamically update Flutter animations by changing Tween begin and end value.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Color(0xFFDCE2E1),
body: Center(child: SomeAnimation()),
),
);
}
}
class SomeAnimation extends StatefulWidget {
const SomeAnimation({Key? key}) : super(key: key);
@override
State<SomeAnimation> createState() => _SomeAnimationState();
}
class _SomeAnimationState extends State<SomeAnimation>
with SingleTickerProviderStateMixin {
late final controlller = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
);
late final Tween<double> someTween = Tween(begin: 0.0, end: 1.0);
late final animation = controlller.drive(someTween);
@override
void initState() {
super.initState();
controlller.repeat(reverse: true);
}
@override
void dispose() {
controlller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(64.0),
child: Column(
children: [
Expanded(
child: Center(
child: ScaleTransition(
scale: animation,
child: const Text(
'Tween',
style: TextStyle(),
),
),
),
),
Row(
children: [
const SizedBox(
width: 100,
child: Text(
'begin',
style: TextStyle(fontSize: 32, ),
),
),
Expanded(
child: SomeSlider(
onChange: (value) {
someTween.begin = value;
},
),
),
],
),
Row(
children: [
const SizedBox(
width: 100,
child: Text(
'end',
style: TextStyle(fontSize: 32,),
),
),
Expanded(
child: SomeSlider(
onChange: (value) {
someTween.end = value;
},
),
),
],
),
],
),
);
}
}
typedef DoubleCallback = void Function(double value);
class SomeSlider extends StatefulWidget {
const SomeSlider({
Key? key,
required this.onChange,
}) : super(key: key);
final DoubleCallback onChange;
@override
State<SomeSlider> createState() => _SomeSliderState();
}
class _SomeSliderState extends State<SomeSlider> {
double value = 1;
void onChange(double value) {
setState(() {});
this.value = value;
widget.onChange(value);
}
@override
Widget build(BuildContext context) {
return Slider(
min: 0,
max: 30,
value: value,
onChanged: onChange,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment