connection_button.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. // 如果是connecting状态,添加旋转动画
  92. if (widget.state == ConnectionState.connecting) {
  93. // 启动旋转动画
  94. if (!_rotationController.isAnimating) {
  95. _rotationController.repeat();
  96. }
  97. return AnimatedBuilder(
  98. animation: _rotationController,
  99. builder: (context, child) {
  100. return Transform.rotate(
  101. angle: _rotationController.value * 2 * math.pi,
  102. child: IXImage(
  103. source: imgPath,
  104. sourceType: ImageSourceType.asset,
  105. width: 30.w,
  106. height: 30.w,
  107. ),
  108. );
  109. },
  110. );
  111. } else {
  112. // 其他状态停止旋转动画
  113. if (_rotationController.isAnimating) {
  114. _rotationController.stop();
  115. }
  116. return IXImage(
  117. source: imgPath,
  118. sourceType: ImageSourceType.asset,
  119. width: 30.w,
  120. height: 30.w,
  121. );
  122. }
  123. }
  124. @override
  125. Widget build(BuildContext context) {
  126. return GestureDetector(onTap: _onTap, child: _buildMainButton());
  127. }
  128. Widget _buildMainButton() {
  129. // 根据状态和主题获取颜色
  130. List<Color> gradientColor;
  131. String imgPath;
  132. String statusImgPath;
  133. String text;
  134. Color textColor;
  135. switch (widget.state) {
  136. case ConnectionState.disconnected:
  137. gradientColor = [
  138. Get.reactiveTheme.highlightColor,
  139. Get.reactiveTheme.hintColor,
  140. ];
  141. imgPath = Assets.switchStatusDisconnected;
  142. statusImgPath = Assets.disconnected;
  143. text = Strings.disconnected.tr;
  144. textColor = Get.reactiveTheme.hintColor;
  145. // 只在状态改变时执行一次
  146. if (_previousState != ConnectionState.disconnected && _isAtTop) {
  147. WidgetsBinding.instance.addPostFrameCallback((_) {
  148. if (mounted) {
  149. setState(() {
  150. _isAtTop = false;
  151. });
  152. }
  153. });
  154. }
  155. _stopConnectingTimer(); // 停止计时器
  156. break;
  157. case ConnectionState.connecting:
  158. gradientColor = [
  159. Get.reactiveTheme.highlightColor,
  160. Get.reactiveTheme.hintColor,
  161. ];
  162. imgPath = Assets.switchStatusConnecting;
  163. statusImgPath = Assets.connecting;
  164. text = _getConnectingText(); // 使用轮播文本
  165. textColor = Get.reactiveTheme.hintColor;
  166. // 只在状态改变时执行一次切换位置
  167. if (_previousState != ConnectionState.connecting) {
  168. WidgetsBinding.instance.addPostFrameCallback((_) {
  169. if (mounted) {
  170. setState(() {
  171. _isAtTop = !_isAtTop;
  172. });
  173. }
  174. });
  175. }
  176. // 启动连接文本轮播计时器
  177. if (_connectingTimer == null || !_connectingTimer!.isActive) {
  178. _startConnectingTimer();
  179. }
  180. break;
  181. case ConnectionState.connected:
  182. gradientColor = [
  183. Get.reactiveTheme.shadowColor,
  184. Get.reactiveTheme.primaryColor,
  185. ];
  186. imgPath = Assets.switchStatusConnected;
  187. statusImgPath = Assets.connected;
  188. text = Strings.connected.tr;
  189. textColor = Get.reactiveTheme.textTheme.bodyLarge!.color!;
  190. // 只在状态改变时执行一次
  191. if (_previousState != ConnectionState.connected && !_isAtTop) {
  192. WidgetsBinding.instance.addPostFrameCallback((_) {
  193. if (mounted) {
  194. setState(() {
  195. _isAtTop = true;
  196. });
  197. }
  198. });
  199. }
  200. _stopConnectingTimer(); // 停止计时器
  201. break;
  202. case ConnectionState.error:
  203. gradientColor = [
  204. Get.reactiveTheme.highlightColor,
  205. Get.reactiveTheme.hintColor,
  206. ];
  207. imgPath = Assets.switchStatusDisconnected;
  208. statusImgPath = Assets.error;
  209. text = Strings.error.tr;
  210. textColor = Get.reactiveTheme.hintColor;
  211. _stopConnectingTimer(); // 停止计时器
  212. break;
  213. }
  214. // 保存前一个渐变色用于动画
  215. final previousColor = _previousGradientColor ?? gradientColor;
  216. // 只在颜色真正改变时更新
  217. if (_previousGradientColor == null ||
  218. _previousGradientColor!.length != gradientColor.length ||
  219. !_colorsEqual(_previousGradientColor!, gradientColor)) {
  220. // 延迟更新,避免在 build 中调用 setState
  221. WidgetsBinding.instance.addPostFrameCallback((_) {
  222. if (mounted) {
  223. _previousGradientColor = gradientColor;
  224. }
  225. });
  226. }
  227. // 更新前一个状态
  228. if (_previousState != widget.state) {
  229. WidgetsBinding.instance.addPostFrameCallback((_) {
  230. if (mounted) {
  231. _previousState = widget.state;
  232. }
  233. });
  234. }
  235. return Column(
  236. children: [
  237. TweenAnimationBuilder<List<Color>>(
  238. duration: const Duration(milliseconds: 300),
  239. curve: Curves.easeInOut,
  240. tween: ColorListTween(begin: previousColor, end: gradientColor),
  241. builder: (context, colors, child) {
  242. return Container(
  243. width: 72.w,
  244. height: 132.w,
  245. padding: EdgeInsets.all(6.w),
  246. decoration: BoxDecoration(
  247. borderRadius: BorderRadius.circular(20.r),
  248. gradient: LinearGradient(
  249. begin: Alignment.topCenter,
  250. end: Alignment.bottomCenter,
  251. colors: colors,
  252. ),
  253. ),
  254. child: child,
  255. );
  256. },
  257. child: AnimatedAlign(
  258. duration: const Duration(milliseconds: 300),
  259. curve: Curves.fastOutSlowIn,
  260. alignment: _isAtTop ? Alignment.topCenter : Alignment.bottomCenter,
  261. child: Container(
  262. width: 60.w,
  263. height: 60.w,
  264. alignment: Alignment.center,
  265. decoration: BoxDecoration(
  266. color: Colors.white,
  267. borderRadius: BorderRadius.circular(14.r),
  268. ),
  269. child: AnimatedSwitcher(
  270. duration: const Duration(milliseconds: 300),
  271. transitionBuilder: (Widget child, Animation<double> animation) {
  272. return FadeTransition(
  273. opacity: animation,
  274. child: ScaleTransition(
  275. scale: Tween<double>(
  276. begin: 0.85,
  277. end: 1.0,
  278. ).animate(animation),
  279. child: child,
  280. ),
  281. );
  282. },
  283. child: _buildImageWithAnimation(imgPath),
  284. ),
  285. ),
  286. ),
  287. ),
  288. 20.verticalSpaceFromWidth,
  289. AnimatedSwitcher(
  290. duration: const Duration(milliseconds: 400),
  291. switchInCurve: Curves.easeIn,
  292. switchOutCurve: Curves.easeOut,
  293. transitionBuilder: (Widget child, Animation<double> animation) {
  294. return FadeTransition(opacity: animation, child: child);
  295. },
  296. child: Row(
  297. key: ValueKey(text), // 使用文本作为 key,确保文字改变时触发动画
  298. mainAxisAlignment: MainAxisAlignment.center,
  299. crossAxisAlignment: CrossAxisAlignment.center,
  300. children: [
  301. IXImage(
  302. source: statusImgPath,
  303. sourceType: ImageSourceType.asset,
  304. width: 14.w,
  305. height: 14.w,
  306. ),
  307. 4.horizontalSpace,
  308. Text(
  309. text,
  310. style: TextStyle(
  311. fontSize: 14.sp,
  312. fontWeight: FontWeight.w500,
  313. height: 1.4,
  314. color: textColor,
  315. ),
  316. ),
  317. ],
  318. ),
  319. ),
  320. ],
  321. );
  322. }
  323. }
  324. // 自定义颜色列表插值器,用于渐变色动画
  325. class ColorListTween extends Tween<List<Color>> {
  326. ColorListTween({super.begin, super.end});
  327. @override
  328. List<Color> lerp(double t) {
  329. if (begin == null || end == null) {
  330. return end ?? begin ?? [];
  331. }
  332. final length = math.max(begin!.length, end!.length);
  333. return List.generate(length, (index) {
  334. final beginColor = index < begin!.length ? begin![index] : begin!.last;
  335. final endColor = index < end!.length ? end![index] : end!.last;
  336. return Color.lerp(beginColor, endColor, t) ?? endColor;
  337. });
  338. }
  339. }