flutter - flutter - 在动画上创建弹性效果
问题描述
Stack
我在height 小部件中有一个容器100.0
。它使用Positioned
小部件定位在中心,如下所示
Container(
width:100.0,
height:100.0,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Positioned(
top: 40.0,
child: Container(
width: 20.0,
height: 20.0,
color: Colors.red,
),
)
],
)
)
我想以这样一种方式为红色容器设置动画,当单击它时它会转到父容器的底部,并且当单击它时会弹回顶部然后返回中心。
我尝试使用Curves.elasticOut
,但这对我来说还不够。我如何实现这种效果
解决方案
试试这段代码,如果我正确理解你的动画,请告诉我
编辑:
import 'package:flutter/material.dart';
import 'package:flutter/physics.dart';
import 'dart:math';
const BOX_COLOR = Colors.cyan;
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Spring Box",
theme: ThemeData(
primaryColor: Colors.red,
),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Padding(
child: PhysicsBox(),
padding: EdgeInsets.only(
left: 20.0,
right: 20.0,
top: 20.0,
bottom: 20.0,
),
),
));
}
}
class PhysicsBox extends StatefulWidget {
@override
BoxState createState() => BoxState();
}
class BoxState extends State<PhysicsBox> with TickerProviderStateMixin {
AnimationController controller;
AnimationController controller2;
Animation<double> animation;
SpringSimulation simulation;
double _position;
@override
void initState() {
super.initState();
simulation = SpringSimulation(
SpringDescription(
mass: 1.0,
stiffness: 100.0,
damping: 5.0,
),
400.0,
208.0,
-4000.0,
);
controller2 = AnimationController(vsync: this,duration: Duration(milliseconds: 70));
animation = Tween(begin: 200.0, end: 400.0).animate(controller2)
..addListener((){
if(controller2.status == AnimationStatus.completed){controller.reset();}
setState(() {
_position = animation.value;
});
});
controller = AnimationController(vsync: this,duration: Duration(milliseconds: 700))..forward()
..addListener(() {
if(controller.status == AnimationStatus.completed){controller2.reset();}
setState(() {
_position = simulation.x(controller.value);
});
print('${simulation.x(controller.value)}');
});
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.yellow,
width:500.0,
height:500.0,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Positioned(
top: _position,
child: GestureDetector(
onTap: (){
if (controller.status == AnimationStatus.completed) {
controller2.forward();//controller.reset();
}else{
controller.forward();}
},
child: Container(
width: 100.0,
height: 100.0,
color: Colors.red,
),
),
)
],
)
);
}
}
推荐阅读
- symfony - 是否可以自定义子资源api平台?
- c++ - 如何在 C++ 文本文件的行尾添加数据?
- python-3.x - 从所有子目录中读取内容
- bash - 将文本文件中的所有数字缩写转换为数值
- c# - 在 XML 文档注释中引用通用类型
- node.js - ResolveJS 后端系统的生产部署/运行时架构是什么?
- java - 我在springboot的帖子正文中发送请求它不起作用
- react-native - React Native iOS 构建成功,但未显示图像和徽标
- reactjs - 如何使用 TypeScript 和 Next.js 将整个道具传递给子组件?
- eclipse - Eclipse IDE:找不到或加载主类