Flutter实现左右抖动动画效果
2022-05-02 本文已影响0人
ufogxl
先看效果:
抖动实现思路:
使用AnimationBuilder配合Transform.translate组件,实现显式动画。
代码:
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
const shakeCount = 4;
const shakeDuration = Duration(milliseconds: 500);
class ShakeAnimationPage extends StatefulWidget {
const ShakeAnimationPage({Key? key}) : super(key: key);
@override
_ShakeAnimationPageState createState() => _ShakeAnimationPageState();
}
class _ShakeAnimationPageState extends State<ShakeAnimationPage>
with TickerProviderStateMixin {
late final AnimationController _shakeController =
AnimationController(vsync: this, duration: shakeDuration);
shake() {
_shakeController.forward();
}
@override
void initState() {
_shakeController.addListener(() {
if (_shakeController.status == AnimationStatus.completed) {
_shakeController.reset();
}
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("抖动效果"),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedBuilder(
animation: _shakeController,
builder: (context, child) {
final sineValue =
sin(shakeCount * 2 * pi * _shakeController.value);
return Transform.translate(
offset: Offset(sineValue * 10, 0),
child: child,
);
},
child: const Text(
"我是抖动文字",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.orange),
),
),
CupertinoButton(child: const Text("抖动"), onPressed: shake),
],
),
);
}
}
参考链接:
CODE WITH ANDREA:How to implement a shake text effect in Flutter