如何同时开始多次播放同一动画

时间:2019-05-14 13:29:32

标签: flutter flutter-animation

我目前正在Flutter中制作命中/损坏动画。我希望每次点击屏幕都会抛出一个显示整数的动画。我找不到使它工作的方法。现在,每次我点击屏幕时,动画都会从停止上一个动画开始。我在项目内部使用了BLoC模式,因此该动画是由streambuilder抛出的。

这是我当前的代码:

import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  final StreamController<int> streamController = StreamController<int>();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: GestureDetector(
        onTap: () {
          streamController.sink.add(Random().nextInt(5));
        },
        child: Scaffold(
          body: Center(
            child: StreamBuilder<int>(
              stream: streamController.stream,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return DamageAnimated(snapshot.data);
                }
                return Container();
              },
            ),
          ),
        ),
      ),
    );
  }
}

class DamageAnimated extends StatefulWidget {
  const DamageAnimated(this.damage);
  final int damage;

  @override
  _DamageAnimatedState createState() => _DamageAnimatedState();
}

class _DamageAnimatedState extends State<DamageAnimated> with SingleTickerProviderStateMixin {
  AnimationController animationController;

  @override
  void initState() {
    super.initState();
    animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    );
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    animationController.forward(from: 0.0);
    return AnimatedBuilder(
      animation: animationController,
      builder: (BuildContext context, Widget child) {
        return Transform.translate(
          offset: Offset(0, -100 * animationController.value),
          child: Opacity(
            opacity: 1 - animationController.value,
            child: Text(
              '${widget.damage}',
            ),
          ),j
        );
      },
    );
  }
}

这会显示一个同时向上平移并逐渐消失的整数,但我不知道如何让同一动画同时运行多次。

2 个答案:

答案 0 :(得分:0)

也许您可以尝试将StatusListeners添加到动画中,或者每次点击屏幕时都可以重置并启动动画,例如:

onTap: () {
      streamController.sink.add(Random().nextInt(5));
      animationController.reset();
      animationController.forward(from: 0.0);
    },

目前我无法独自尝试,但是我认为这是一种方法。

很抱歉,如果您的时间不起作用,那么会花费很多时间。

答案 1 :(得分:0)

您只会返回1 DamageAnimated。看下面的例子-您将需要实现类似的东西。顺便说一句,扩展列表的...语法是dart中的新增功能,因此您需要在pubspec.yaml中更新sdk版本

environment:
  sdk: ">=2.2.2 <3.0.0"

我已经在iOS(而非Android)上对此进行了测试,但没有理由不起作用。

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return 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> {
  List<Widget> _anims = [];
  int _count = 0;
  int _animationsRunning = 0;

  void animationEnded() {
    _animationsRunning--;
    if (_animationsRunning == 0) {
      setState(() {
        _anims = [];
      });
      print('all animations completed - removing widget from stack (now has ${_anims.length} elements)');
    }
  }

  void _startAnimation() {
    setState(() {
      _anims.add(DamageAnimated(_count, animationEnded));
      _count++;
      _animationsRunning++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Stack(
          children: <Widget>[
            ..._anims,
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _startAnimation,
        tooltip: 'Start animation',
        child: Icon(Icons.add),
      ),
    );
  }
}

class DamageAnimated extends StatefulWidget {
  const DamageAnimated(this.damage, this.endedCallback);
  final int damage;
  final VoidCallback endedCallback;

  @override
  _DamageAnimatedState createState() => _DamageAnimatedState();
}

class _DamageAnimatedState extends State<DamageAnimated> with SingleTickerProviderStateMixin {
  AnimationController animationController;

  @override
  void initState() {
    super.initState();
    animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..addStatusListener((AnimationStatus status) {
      if (status == AnimationStatus.completed)
        if (mounted) {
          widget.endedCallback();
        }
    });
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    animationController.forward(from: 0.0);
    return AnimatedBuilder(
      animation: animationController,
      builder: (BuildContext context, Widget child) {
        return Transform.translate(
          offset: Offset(0, -100 * animationController.value),
          child: Opacity(
            opacity: 1 - animationController.value,
            child: Text(
              '${widget.damage}',
            ),
          ),
        );
      },
    );
  }
}