Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Context: https://stackoverflow.com/questions/58775671/restore-animationcontroller-state-upon-returning-to-page
- import 'package:flutter/material.dart';
- import 'package:provider/provider.dart';
- void main() => runApp(MyApp());
- class MyApp extends StatelessWidget {
- @override
- Widget build(BuildContext context) {
- return Provider<CounterStateModel>(
- builder: (context) => CounterStateModel(),
- child: MaterialApp(
- title: 'Flutter Demo',
- theme: ThemeData(
- primarySwatch: Colors.blue,
- ),
- home: MyHomePage(title: 'Flutter Demo Home Page'),
- ),
- );
- }
- }
- class MyHomePage extends StatefulWidget {
- MyHomePage({Key key, this.title}) : super(key: key);
- final String title;
- @override
- _MyHomePageState createState() => _MyHomePageState();
- }
- class _MyHomePageState extends State<MyHomePage> {
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text(widget.title),
- ),
- body: Center(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: <Widget>[
- FlatButton(
- color: Colors.blue,
- child: Text("AnimatonController"),
- onPressed: () {
- Navigator.push(
- context,
- MaterialPageRoute(builder: (context) => Counter()),
- );
- },
- ),
- ],
- ),
- ),
- );
- }
- }
- class CounterText extends AnimatedWidget {
- CounterText({Key key, this.animation})
- : super(key: key, listenable: animation);
- Animation<int> animation;
- @override
- build(BuildContext context) {
- return new Text(
- animation.value.toString(),
- style: new TextStyle(fontSize: 200.0),
- );
- }
- }
- class CounterStateModel {
- AnimationController _controller;
- int startCount = 10;
- }
- class Counter extends StatefulWidget {
- State createState() => new _CounterState();
- }
- class _CounterState extends State<Counter> with TickerProviderStateMixin {
- AnimationController _controller;
- @override
- void initState() {
- super.initState();
- }
- @override
- Widget build(BuildContext context) {
- CounterStateModel _counterStateModel =
- Provider.of<CounterStateModel>(context);
- if (_counterStateModel._controller == null) {
- _counterStateModel._controller = new AnimationController(
- vsync: this,
- duration: new Duration(seconds: _counterStateModel.startCount),
- );
- _counterStateModel._controller = _controller;
- } else {
- _controller = _counterStateModel._controller;
- }
- return new Scaffold(
- floatingActionButton: new FloatingActionButton(
- child: Icon(_controller.isAnimating ? Icons.pause : Icons.play_arrow),
- onPressed: () {
- setState(() {
- _controller.isAnimating
- ? _controller.stop()
- : _controller.forward();
- });
- }),
- body: new Container(
- child: new Center(
- child: new CounterText(
- animation: new StepTween(
- begin: _counterStateModel.startCount,
- end: 0,
- ).animate(_controller),
- ),
- ),
- ),
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement