gpt4 book ai didi

flutter - 如何循环运行动画

转载 作者:行者123 更新时间:2023-12-04 01:17:02 25 4
gpt4 key购买 nike

我正在使用下面的代码摇一个小部件,但效果是一次,

我如何让它以定时间隔循环运行。我相信可以通过更改 key 来完成,但这是最终的,无法更改。

import 'package:flutter/material.dart';

@immutable
class ShakeWidget extends StatelessWidget {
final Duration duration;
final double deltaX;
final Widget child;
final Curve curve;

const ShakeWidget({
Key key,
this.duration = const Duration(milliseconds: 500),
this.deltaX = 20,
this.curve = Curves.bounceOut,
this.child,
}) : super(key: key);

/// convert 0-1 to 0-1-0
double shake(double animation) =>
2 * (0.5 - (0.5 - curve.transform(animation)).abs());

@override
Widget build(BuildContext context) {
return TweenAnimationBuilder<double>(
key: key,
tween: Tween(begin: 0.0, end: 1.0),
duration: duration,
builder: (context, animation, child) => Transform.translate(
offset: Offset(deltaX * shake(animation), 0),
child: child,
),
child: child,
);
}
}

最佳答案

你需要使用 AnimationController并在 Controller 完成时调用repeat

enter image description here

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: SafeArea(
child: ShakeWidget(
child: Text('Hello world'),
),
),
),
);
}
}

class ShakeWidget extends StatefulWidget {
const ShakeWidget({
Key key,
this.duration = const Duration(milliseconds: 500),
this.deltaX = 20,
this.curve = Curves.bounceOut,
@required this.child,
}) : super(key: key);

final Duration duration;
final double deltaX;
final Widget child;
final Curve curve;

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

class _ShakeWidgetState extends State<ShakeWidget>
with SingleTickerProviderStateMixin {
AnimationController controller;

@override
void initState() {
super.initState();
controller = AnimationController(
duration: widget.duration,
vsync: this,
)
..forward()
..addListener(() {
if (controller.isCompleted) {
controller.repeat();
}
});
}

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

/// convert 0-1 to 0-1-0
double shake(double value) =>
2 * (0.5 - (0.5 - widget.curve.transform(value)).abs());

@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: controller,
builder: (context, child) => Transform.translate(
offset: Offset(widget.deltaX * shake(controller.value), 0),
child: child,
),
child: widget.child,
);
}
}

关于flutter - 如何循环运行动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63168206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com