Last active
August 24, 2020 00:32
-
-
Save guid-empty/bbf00382c6d5f4f0fa34876c21b62b10 to your computer and use it in GitHub Desktop.
Explicit Animations - Timer based
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'; | |
import 'dart:async'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class Ball extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Container( | |
decoration: BoxDecoration( | |
shape: BoxShape.circle, | |
color: Colors.green, | |
), | |
width: 40.0, | |
height: 40.0, | |
); | |
} | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
double currentLeft; | |
double start; | |
double end; | |
double increment; | |
void move(Timer t) async { | |
final width = 40; | |
final endPosition = end - width; | |
if (currentLeft < endPosition) { | |
setState(() { | |
currentLeft += increment; | |
}); | |
} else { | |
t.cancel(); | |
} | |
print('frame'); | |
} | |
void interpolate(double start, double end) { | |
setState(() { | |
increment = (end - start) / 60; | |
}); | |
} | |
void initState() { | |
super.initState(); | |
currentLeft = 0; | |
start = 0; | |
} | |
@override | |
Widget build(BuildContext context) { | |
final size = MediaQuery.of(context).size; | |
end = size.width; | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('Explicit Animations - Timer based'), | |
), | |
body: Center( | |
child: Container( | |
height: 300, | |
child: Stack( | |
children: <Widget>[ | |
Positioned( | |
left: currentLeft, | |
child: Ball(), | |
), | |
], | |
), | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () { | |
setState(() { | |
currentLeft = 0; | |
interpolate(start, end); | |
new Timer.periodic(const Duration(milliseconds: 16), move); | |
}); | |
}, | |
child: Icon(Icons.play_arrow), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment