Flutter 组合实例:TurnBox
封面图
•
2025-11-10
•
Flutter
0
0
0
0
在 Flutter 中,`TurnBox` 是一个用于旋转控件的组件,它可以通过 `RotationTransition` 或 `Transform` 实现旋转效果。下面是一个完整的 Flutter 组合实例,展示如何使用 `TurnBox` 来实现一个可旋转的盒子。 --- ## 🧩 示例:Flutter TurnBox(可旋转的盒子) ### 功能说明: - 一个可以点击旋转的盒子。 - 使用 `GestureDetector` 捕获点击事件。 - 使用 `RotationTransition` 实现旋转动画。 --- ## ✅ 代码示例 ```dart import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'TurnBox Example', home: Scaffold( appBar: AppBar( title: Text('TurnBox Example'), ), body: Center( child: TurnBox(), ), ), ); } } class TurnBox extends StatefulWidget { @override _TurnBoxState createState() => _TurnBoxState(); } class _TurnBoxState extends State<TurnBox> with SingleTickerProviderStateMixin { late AnimationController _controller; late Animation<double> _animation; double _rotation = 0.0; @override void initState() { super.initState(); _controller = AnimationController( duration: const Duration(milliseconds: 500), vsync: this, ); _animation = Tween<double>(begin: 0, end: 1).animate(_controller) ..addListener(() { setState(() { _rotation = _animation.value * 2 * pi; // 0 ~ 2π }); }); } @override void dispose() { _controller.dispose(); super.dispose(); } void _rotateBox() { _controller.reset(); _controller.forward(); } @override Widget build(BuildContext context) { return GestureDetector( onTap: _rotateBox, child: Transform( alignment: Alignment.center, transform: Matrix4.identity() ..rotateZ(_rotation), child: Container( width: 200, height: 200, color: Colors.blueAccent, child: Center( child: Text( 'Rotate Me', style: TextStyle(color: Colors.white, fontSize: 24), ), ), ), ), ); } } ``` --- ## 📌 说明: - `AnimationController` 控制动画的播放与停止。 - `Tween<double>` 从 0 到 1,对应旋转角度从 0 到 2π(一圈)。 - `Transform.rotateZ()` 实现旋转效果。 - `GestureDetector` 监听点击事件,触发旋转动画。 --- ## 🔄 扩展建议: 你可以进一步扩展这个例子,比如: - 添加按钮来控制旋转方向(顺时针/逆时针)。 - 使用 `AnimatedBuilder` 替代 `setState` 来优化性能。 - 添加手势滑动旋转功能。 --- 如果你需要更高级的 `TurnBox` 实现(如类似陀螺仪效果),也可以使用 `RotationTransition` 或 `AnimatedContainer` 来实现。 是否需要我提供一个使用 `RotationTransition` 的版本?
上一篇:
Flutter 组合现有组件
标题录入,一次不能超过6条
留言
评论