connection_widget.dart 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import 'package:flutter/cupertino.dart';
  2. import 'package:flutter/material.dart';
  3. import 'connection_status.dart';
  4. class ConnectionWidget extends StatefulWidget {
  5. final ConnectionStatus status;
  6. final Function() onTap; // 只通知外部发生了点击事件
  7. const ConnectionWidget({
  8. Key? key,
  9. required this.status,
  10. required this.onTap,
  11. }) : super(key: key);
  12. @override
  13. _ConnectionWidgetState createState() => _ConnectionWidgetState();
  14. }
  15. class _ConnectionWidgetState extends State<ConnectionWidget> {
  16. late String currentImage;
  17. @override
  18. void initState() {
  19. super.initState();
  20. _updateImage();
  21. }
  22. @override
  23. void didUpdateWidget(ConnectionWidget oldWidget) {
  24. super.didUpdateWidget(oldWidget);
  25. if (oldWidget.status != widget.status) {
  26. _updateImage();
  27. }
  28. }
  29. void _updateImage() {
  30. switch (widget.status) {
  31. case ConnectionStatus.disconnected:
  32. currentImage = 'assets/images/main/disconnected.gif';
  33. break;
  34. case ConnectionStatus.connecting:
  35. currentImage = 'assets/images/main/connecting.gif';
  36. break;
  37. case ConnectionStatus.stopped:
  38. currentImage = 'assets/images/main/stopped.gif';
  39. break;
  40. case ConnectionStatus.connected:
  41. currentImage = 'assets/images/main/stopped.gif';
  42. break;
  43. }
  44. }
  45. @override
  46. Widget build(BuildContext context) {
  47. return Stack(
  48. alignment: Alignment.center,
  49. children: <Widget>[
  50. Image.asset(
  51. currentImage,
  52. fit: BoxFit.cover,
  53. width: 200,
  54. height: 200,
  55. ),
  56. ClipOval(
  57. child: Material(
  58. color: Colors.transparent,
  59. child: GestureDetector(
  60. onTap: widget.onTap, // 使用外部传入的点击函数
  61. child: Container(
  62. width: 100,
  63. height: 100,
  64. decoration: const BoxDecoration(
  65. shape: BoxShape.circle,
  66. color: Colors.transparent,
  67. ),
  68. ),
  69. ),
  70. ),
  71. ),
  72. ],
  73. );
  74. }
  75. }