connection_button.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. import 'package:flutter/material.dart' hide ConnectionState;
  2. import 'package:flutter_screenutil/flutter_screenutil.dart';
  3. import 'dart:math' as math;
  4. import 'dart:async';
  5. import 'package:get/get.dart';
  6. import 'package:nomo/app/widgets/ix_image.dart';
  7. import '../../../constants/assets.dart';
  8. import '../../../../config/theme/theme_extensions/theme_extension.dart';
  9. import '../../../../config/translations/strings_enum.dart';
  10. import '../../../constants/enums.dart';
  11. class ConnectionButton extends StatefulWidget {
  12. final ConnectionState state;
  13. final VoidCallback? onTap;
  14. const ConnectionButton({super.key, required this.state, this.onTap});
  15. @override
  16. State<ConnectionButton> createState() => _ConnectionButtonState();
  17. }
  18. class _ConnectionButtonState extends State<ConnectionButton>
  19. with TickerProviderStateMixin {
  20. bool _isAtTop = false; // 控制按钮位置,false=底部,true=顶部
  21. List<Color>? _previousGradientColor; // 保存前一个渐变色用于动画过渡
  22. late AnimationController _rotationController; // 旋转动画控制器
  23. Timer? _connectingTimer; // 连接中状态的计时器
  24. int _connectingTextIndex = 0; // 当前显示的连接文本索引(0-4)
  25. ConnectionState? _previousState; // 保存前一个连接状态
  26. @override
  27. void initState() {
  28. super.initState();
  29. // 初始化旋转动画控制器
  30. _rotationController = AnimationController(
  31. duration: const Duration(seconds: 2),
  32. vsync: this,
  33. );
  34. }
  35. @override
  36. void dispose() {
  37. _rotationController.dispose();
  38. _connectingTimer?.cancel();
  39. super.dispose();
  40. }
  41. void _onTap() {
  42. if (widget.onTap != null) {
  43. widget.onTap!();
  44. }
  45. }
  46. // 启动连接中状态的文本轮播计时器
  47. void _startConnectingTimer() {
  48. _connectingTimer?.cancel();
  49. _connectingTextIndex = 0;
  50. _connectingTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
  51. if (mounted) {
  52. setState(() {
  53. // 每秒切换到下一个文本,循环显示0-4
  54. _connectingTextIndex = (_connectingTextIndex + 1) % 5;
  55. });
  56. }
  57. });
  58. }
  59. // 停止连接中状态的文本轮播计时器
  60. void _stopConnectingTimer() {
  61. _connectingTimer?.cancel();
  62. _connectingTimer = null;
  63. _connectingTextIndex = 0;
  64. }
  65. // 根据索引获取对应的连接文本
  66. String _getConnectingText() {
  67. switch (_connectingTextIndex) {
  68. case 0:
  69. return Strings.securingData.tr;
  70. case 1:
  71. return Strings.encryptingTraffic.tr;
  72. case 2:
  73. return Strings.protectingPrivacy.tr;
  74. case 3:
  75. return Strings.safeConnection.tr;
  76. case 4:
  77. return Strings.yourDataIsSafe.tr;
  78. default:
  79. return Strings.connecting.tr;
  80. }
  81. }
  82. // 比较两个颜色列表是否相等
  83. bool _colorsEqual(List<Color> a, List<Color> b) {
  84. if (a.length != b.length) return false;
  85. for (int i = 0; i < a.length; i++) {
  86. if (a[i].value != b[i].value) return false;
  87. }
  88. return true;
  89. }
  90. Widget _buildImageWithAnimation(String imgPath) {
  91. // 如果是 connectingVirtual/connecting 或 disconnecting 状态,添加旋转动画
  92. if (widget.state == ConnectionState.connectingVirtual ||
  93. widget.state == ConnectionState.connecting ||
  94. widget.state == ConnectionState.disconnecting) {
  95. // 启动旋转动画
  96. if (!_rotationController.isAnimating) {
  97. _rotationController.repeat();
  98. }
  99. return AnimatedBuilder(
  100. animation: _rotationController,
  101. builder: (context, child) {
  102. return Transform.rotate(
  103. angle: _rotationController.value * 2 * math.pi,
  104. child: IXImage(
  105. source: imgPath,
  106. sourceType: ImageSourceType.asset,
  107. width: 30.w,
  108. height: 30.w,
  109. ),
  110. );
  111. },
  112. );
  113. } else {
  114. // 其他状态停止旋转动画
  115. if (_rotationController.isAnimating) {
  116. _rotationController.stop();
  117. }
  118. return IXImage(
  119. source: imgPath,
  120. sourceType: ImageSourceType.asset,
  121. width: 30.w,
  122. height: 30.w,
  123. );
  124. }
  125. }
  126. @override
  127. Widget build(BuildContext context) {
  128. return GestureDetector(onTap: _onTap, child: _buildMainButton());
  129. }
  130. Widget _buildMainButton() {
  131. // 根据状态和主题获取颜色
  132. List<Color> gradientColor;
  133. String imgPath;
  134. String statusImgPath;
  135. String text;
  136. Color textColor;
  137. switch (widget.state) {
  138. case ConnectionState.disconnected:
  139. gradientColor = [
  140. Get.reactiveTheme.highlightColor,
  141. Get.reactiveTheme.hintColor,
  142. ];
  143. imgPath = Assets.switchStatusDisconnected;
  144. statusImgPath = Assets.disconnected;
  145. text = Strings.disconnected.tr;
  146. textColor = Get.reactiveTheme.hintColor;
  147. // 只在状态改变时执行一次
  148. if (_previousState != ConnectionState.disconnected && _isAtTop) {
  149. WidgetsBinding.instance.addPostFrameCallback((_) {
  150. if (mounted) {
  151. setState(() {
  152. _isAtTop = false;
  153. });
  154. }
  155. });
  156. }
  157. _stopConnectingTimer(); // 停止计时器
  158. break;
  159. case ConnectionState.connectingVirtual:
  160. case ConnectionState.connecting:
  161. gradientColor = [
  162. Get.reactiveTheme.highlightColor,
  163. Get.reactiveTheme.hintColor,
  164. ];
  165. imgPath = Assets.switchStatusConnecting;
  166. statusImgPath = Assets.connecting;
  167. text = _getConnectingText(); // 使用轮播文本
  168. textColor = Get.reactiveTheme.hintColor;
  169. // 只在状态改变时执行一次切换位置
  170. if (_previousState != ConnectionState.connectingVirtual &&
  171. _previousState != ConnectionState.connecting) {
  172. WidgetsBinding.instance.addPostFrameCallback((_) {
  173. if (mounted) {
  174. setState(() {
  175. _isAtTop = !_isAtTop;
  176. });
  177. }
  178. });
  179. }
  180. // 启动连接文本轮播计时器
  181. if (_connectingTimer == null || !_connectingTimer!.isActive) {
  182. _startConnectingTimer();
  183. }
  184. break;
  185. case ConnectionState.disconnecting:
  186. gradientColor = [
  187. Get.reactiveTheme.highlightColor,
  188. Get.reactiveTheme.hintColor,
  189. ];
  190. imgPath = Assets.switchStatusConnecting;
  191. statusImgPath = Assets.connecting;
  192. text = Strings.disconnecting.tr;
  193. textColor = Get.reactiveTheme.hintColor;
  194. _stopConnectingTimer(); // 停止计时器
  195. break;
  196. case ConnectionState.connected:
  197. gradientColor = [
  198. Get.reactiveTheme.shadowColor,
  199. Get.reactiveTheme.primaryColor,
  200. ];
  201. imgPath = Assets.switchStatusConnected;
  202. statusImgPath = Assets.connected;
  203. text = Strings.connected.tr;
  204. textColor = Get.reactiveTheme.textTheme.bodyLarge!.color!;
  205. // 只在状态改变时执行一次
  206. if (_previousState != ConnectionState.connected && !_isAtTop) {
  207. WidgetsBinding.instance.addPostFrameCallback((_) {
  208. if (mounted) {
  209. setState(() {
  210. _isAtTop = true;
  211. });
  212. }
  213. });
  214. }
  215. _stopConnectingTimer(); // 停止计时器
  216. break;
  217. case ConnectionState.error:
  218. gradientColor = [
  219. Get.reactiveTheme.highlightColor,
  220. Get.reactiveTheme.hintColor,
  221. ];
  222. imgPath = Assets.switchStatusDisconnected;
  223. statusImgPath = Assets.error;
  224. text = Strings.error.tr;
  225. textColor = Get.reactiveTheme.hintColor;
  226. _stopConnectingTimer(); // 停止计时器
  227. break;
  228. }
  229. // 保存前一个渐变色用于动画
  230. final previousColor = _previousGradientColor ?? gradientColor;
  231. // 只在颜色真正改变时更新
  232. if (_previousGradientColor == null ||
  233. _previousGradientColor!.length != gradientColor.length ||
  234. !_colorsEqual(_previousGradientColor!, gradientColor)) {
  235. // 延迟更新,避免在 build 中调用 setState
  236. WidgetsBinding.instance.addPostFrameCallback((_) {
  237. if (mounted) {
  238. _previousGradientColor = gradientColor;
  239. }
  240. });
  241. }
  242. // 更新前一个状态
  243. if (_previousState != widget.state) {
  244. WidgetsBinding.instance.addPostFrameCallback((_) {
  245. if (mounted) {
  246. _previousState = widget.state;
  247. }
  248. });
  249. }
  250. return Column(
  251. children: [
  252. TweenAnimationBuilder<List<Color>>(
  253. duration: const Duration(milliseconds: 300),
  254. curve: Curves.easeInOut,
  255. tween: ColorListTween(begin: previousColor, end: gradientColor),
  256. builder: (context, colors, child) {
  257. return Container(
  258. width: 72.w,
  259. height: 132.w,
  260. padding: EdgeInsets.all(6.w),
  261. decoration: BoxDecoration(
  262. borderRadius: BorderRadius.circular(20.r),
  263. gradient: LinearGradient(
  264. begin: Alignment.topCenter,
  265. end: Alignment.bottomCenter,
  266. colors: colors,
  267. ),
  268. ),
  269. child: child,
  270. );
  271. },
  272. child: AnimatedAlign(
  273. duration: const Duration(milliseconds: 300),
  274. curve: Curves.fastOutSlowIn,
  275. alignment: _isAtTop ? Alignment.topCenter : Alignment.bottomCenter,
  276. child: Container(
  277. width: 60.w,
  278. height: 60.w,
  279. alignment: Alignment.center,
  280. decoration: BoxDecoration(
  281. color: Colors.white,
  282. borderRadius: BorderRadius.circular(14.r),
  283. ),
  284. child: AnimatedSwitcher(
  285. duration: const Duration(milliseconds: 300),
  286. transitionBuilder: (Widget child, Animation<double> animation) {
  287. return FadeTransition(
  288. opacity: animation,
  289. child: ScaleTransition(
  290. scale: Tween<double>(
  291. begin: 0.85,
  292. end: 1.0,
  293. ).animate(animation),
  294. child: child,
  295. ),
  296. );
  297. },
  298. child: _buildImageWithAnimation(imgPath),
  299. ),
  300. ),
  301. ),
  302. ),
  303. 20.verticalSpaceFromWidth,
  304. AnimatedSwitcher(
  305. duration: const Duration(milliseconds: 400),
  306. switchInCurve: Curves.easeIn,
  307. switchOutCurve: Curves.easeOut,
  308. transitionBuilder: (Widget child, Animation<double> animation) {
  309. return FadeTransition(opacity: animation, child: child);
  310. },
  311. child: Row(
  312. key: ValueKey(text), // 使用文本作为 key,确保文字改变时触发动画
  313. mainAxisAlignment: MainAxisAlignment.center,
  314. crossAxisAlignment: CrossAxisAlignment.center,
  315. children: [
  316. IXImage(
  317. source: statusImgPath,
  318. sourceType: ImageSourceType.asset,
  319. width: 14.w,
  320. height: 14.w,
  321. ),
  322. 4.horizontalSpace,
  323. Text(
  324. text,
  325. style: TextStyle(
  326. fontSize: 14.sp,
  327. fontWeight: FontWeight.w500,
  328. height: 1.4,
  329. color: textColor,
  330. ),
  331. ),
  332. ],
  333. ),
  334. ),
  335. ],
  336. );
  337. }
  338. }
  339. // 自定义颜色列表插值器,用于渐变色动画
  340. class ColorListTween extends Tween<List<Color>> {
  341. ColorListTween({super.begin, super.end});
  342. @override
  343. List<Color> lerp(double t) {
  344. if (begin == null || end == null) {
  345. return end ?? begin ?? [];
  346. }
  347. final length = math.max(begin!.length, end!.length);
  348. return List.generate(length, (index) {
  349. final beginColor = index < begin!.length ? begin![index] : begin!.last;
  350. final endColor = index < end!.length ? end![index] : end!.last;
  351. return Color.lerp(beginColor, endColor, t) ?? endColor;
  352. });
  353. }
  354. }