flutter - 如何为通过滑动偏移旋转的小部件添加惯性?(增加动力)
问题描述
例如,我有一个在用户滑动时使用变量旋转的小部件dragoffset += details.offset.dx
;
滑动结束时如何为旋转添加惯性?例如,当您松开手指时,对象继续以下降的速度旋转——就像 ListView 通常的行为一样。
以下是一些样板代码作为示例:
Widget rotatedWidget() {
double fingerOffset = 0.0;
return GestureDetector(
onHorizontalDragUpdate: (details) {
setState((){
fingerOffset += details.delta.dx;
});
},
onHorizontalDragEnd: (details) {
/// some code to add inertia
},
child: Transform.rotate(
angle: offset,
child: Container(width: 100, height: 100, color: Colors.blue),
));
}
解决方案
感谢@pskink提供此解决方案。
(编辑:添加物理包导入和SingleTickerProviderStateMixin
类的继承,因为 AnimationController 需要垂直同步到当前类)
import 'package:flutter/physics.dart';
class RotateState extends State<Rotate> with SingleTickerProviderStateMixin {
AnimationController ctrl;
@override
void initState() {
super.initState();
ctrl = AnimationController.unbounded(vsync: this);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onPanUpdate: (d) => ctrl.value += d.delta.dx / 100,
onPanEnd: (d) {
ctrl.animateWith(
FrictionSimulation(
0.05, // <- the bigger this value, the less friction is applied
ctrl.value,
d.velocity.pixelsPerSecond.dx / 100 // <- Velocity of inertia
));
},
child: Scaffold(
appBar: AppBar(
title: Text('RotatedBox'),
),
body: AnimatedBuilder(
animation: ctrl,
builder: (ctx, w) {
return Center(
child: Transform.rotate(
angle: ctrl.value,
child: Container(width: 100, height: 100, color: Colors.blue),
),
);
},
),
),
);
}
}
推荐阅读
- android - 将版本从 MAJOR.MINOR 更改为 MAJOR.MINOR.PATCH
- java - Java 字符串池 什么是存储 1000 个字符串的最佳方式。GC 是否在字符串池上运行
- grpc - gRPC 服务器如何注意到客户端取消了服务器端的流式调用?
- php - 下载临时文件并显示结果
- javascript - 计算地图可见部分的边界
- swift - 如何在不破坏“菜单”按钮默认行为的情况下在 tvOS 游戏中设置主菜单
- c++ - Fuse 文件系统查找 /.Trash、/autorun.inf 和 /.xdg-volume-info 文件
- java - 使用 Java 中的接口作为与更多团队一起处理代码的一种手段
- solr - 数组字段特定索引处的 Solr 过滤器值
- printing - 在 IP 打印机中使用骆驼打印机打印