Dart Flutter : How to run animation from a scoped-model?
如何在作为 ScopedModel 后代的小部件中运行动画,来自 scoped-model。我在这里有一个红色按钮,单击它时会显示一个正方形。方块在 3 秒后消失,这发生得很快。我想做的是让正方形在几秒钟内消失。我尝试了 AnimationController,但它需要一个"vsync:"参数,我看到该参数通常在 initState() 中作为"vsync:this"完成,并且在其他地方使用时会出错。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | import 'package:flutter/material.dart'; import 'dart:async'; import 'package:scoped_model/scoped_model.dart'; void main() { runApp(new MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'scoped model Opacity', home: new ScopedModel<MyScopedModel>( model: new MyScopedModel(), child: new MyPage(), ), ); } } class MyScopedModel extends Model { double myOpacity = 0.0; Timer myTimer; AnimationController myAnimationController; void myShowSquare() { myOpacity = 1.0; myTimer = new Timer(new Duration(seconds: 3), _removeSquare); notifyListeners(); } void _removeSquare() { myOpacity = 0.0; myTimer.cancel(); notifyListeners(); } } class MyPage extends StatelessWidget { @override Widget build(BuildContext context) { return new Container( color: Colors.grey, child: new ScopedModelDescendant<MyScopedModel>( builder: (context, child, model) => new Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ new GestureDetector( onTap: model.myShowSquare, child: new Stack( alignment: Alignment.center, children: <Widget>[ new Container( constraints: new BoxConstraints.expand( width: 50.0, height: 50.0), color: Colors.deepOrange, ), new Text( '+', style: new TextStyle(color: Colors.black), ), ], ), ), new Opacity( opacity: model.myOpacity, child: new Container( constraints: new BoxConstraints.expand(width: 50.0, height: 50.0), color: Colors.amber, ), ) ], ), )); } } |
我认为您正在寻找的是一个 FadeTransition,我相信它可以为您处理使您的小部件淡出的艰苦工作。如果您还想更改大小,也可以使用 AnimatedCrossFade 小部件。
但是,如果您想自己制作动画,我建议您查看动画文档和本动画教程,因为它们将解释其工作原理的详细信息。