Dart Flutter:如何从范围模型中运行动画?

时间:2018-04-23 09:02:50

标签: flutter scoped-model

如何在范围模型的小部件(ScopedModeldescendant)中运行动画。我有一个红色按钮,点击时显示一个正方形。 3秒后,方块会消失,这很快就会发生。我想做的是让广场在几秒钟内消失。我尝试过AnimationController,但它需要一个'vsync:'参数,我看到它通常在initState()中作为'vsync:this'完成,并在其他地方使用时出错。

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,
                    ),
                  )
                ],
              ),
        ));
  }
}

1 个答案:

答案 0 :(得分:2)

我认为你所寻找的是一个FadeTransition,我相信这可以帮助你完成淡出你的小部件的艰苦工作。如果您想要更改大小,也可以使用AnimatedCrossFade窗口小部件。

但是,如果您希望自己制作动画,我建议您查看Animation documentationAnimation Tutorial,因为他们会详细说明其工作原理。