Advertisement
Guest User

Shaking Button

a guest
Mar 19th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 2.24 KB | None | 0 0
  1. import 'package:flutter/material.dart';
  2. import 'package:flutter/animation.dart';
  3.  
  4. void main() => runApp(MaterialApp(
  5.       title: 'Example',
  6.       home: MyApp(),
  7.     ));
  8.  
  9. class MyApp extends StatefulWidget {
  10.   @override
  11.   MyAppState createState() => MyAppState();
  12. }
  13.  
  14. class MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
  15.   Animation animation;
  16.   AnimationController animationController;
  17.  
  18.   @override
  19.   void initState() {
  20.     animationController =
  21.         AnimationController(duration: Duration(milliseconds: 100), vsync: this);
  22.     animation = Tween(begin: 0.0, end: 10.0).animate(animationController);
  23.     super.initState();
  24.   }
  25.  
  26.   void onPressed() {
  27.     animation.addStatusListener((status) {
  28.       if (status == AnimationStatus.completed) {
  29.         animationController.reverse();
  30.       } else if (status == AnimationStatus.dismissed) {
  31.         animationController.forward();
  32.       }
  33.     });
  34.     animationController.forward();
  35.     print('Pushed the Button');
  36.   }
  37.  
  38.   @override
  39.   Widget build(BuildContext context) {
  40.     return Scaffold(
  41.         body: Column(
  42.             mainAxisAlignment: MainAxisAlignment.center,
  43.             crossAxisAlignment: CrossAxisAlignment.stretch,
  44.             children: <Widget>[
  45.           ButtonAnimation(
  46.             onPressed: onPressed,
  47.             animation: animation,
  48.           ),
  49.           Container(
  50.             width: 100.0,
  51.             height: 100.0,
  52.           ),
  53.           RaisedButton(
  54.             child: Text('Stop Animation'),
  55.             onPressed: () {
  56.               animationController.stop();
  57.             },
  58.           )
  59.         ]));
  60.   }
  61.  
  62.   @override
  63.   void dispose() {
  64.     animationController.dispose();
  65.     super.dispose();
  66.   }
  67. }
  68.  
  69. class ButtonAnimation extends AnimatedWidget {
  70.   ButtonAnimation({Key key, Animation animation, this.onPressed})
  71.       : super(key: key, listenable: animation);
  72.  
  73.   Function onPressed;
  74.  
  75.   @override
  76.   Widget build(BuildContext context) {
  77.     Animation animation = listenable;
  78.     return Center(
  79.       child: Container(
  80.         margin: EdgeInsets.only(left: animation.value ?? 0),
  81.         child: RaisedButton(
  82.           child: Text("Push Me"),
  83.           onPressed: onPressed,
  84.         ),
  85.       ),
  86.     );
  87.   }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement