config_dialog.dart 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import 'package:chicken_farm/core/api/api_client.dart';
  2. import 'package:chicken_farm/core/config/app_config.dart';
  3. import 'package:chicken_farm/core/services/connectivity_service.dart';
  4. import 'package:flutter/material.dart';
  5. class ConfigDialog extends StatefulWidget {
  6. const ConfigDialog({super.key});
  7. @override
  8. State<ConfigDialog> createState() => _ConfigDialogState();
  9. }
  10. class _ConfigDialogState extends State<ConfigDialog> {
  11. final _formKey = GlobalKey<FormState>();
  12. late TextEditingController _baseUrlController;
  13. late TextEditingController _clientIdController;
  14. @override
  15. void initState() {
  16. super.initState();
  17. _baseUrlController = TextEditingController(text: AppConfig.baseUrl);
  18. _clientIdController = TextEditingController(text: AppConfig.clientId);
  19. }
  20. @override
  21. void dispose() {
  22. _baseUrlController.dispose();
  23. _clientIdController.dispose();
  24. super.dispose();
  25. }
  26. @override
  27. Widget build(BuildContext context) {
  28. return AlertDialog(
  29. title: const Text('配置服务器'),
  30. content: SizedBox(
  31. width: MediaQuery.of(context).size.width * 0.8,
  32. child: Form(
  33. key: _formKey,
  34. child: Column(
  35. mainAxisSize: MainAxisSize.min,
  36. children: [
  37. TextFormField(
  38. controller: _baseUrlController,
  39. decoration: const InputDecoration(
  40. labelText: 'Base URL',
  41. hintText: '例如: http://localhost:8080',
  42. border: OutlineInputBorder(),
  43. ),
  44. validator: (value) {
  45. if (value == null || value.isEmpty) {
  46. return '请输入Base URL';
  47. }
  48. if (!value.startsWith('http')) {
  49. return '请输入有效的URL地址';
  50. }
  51. return null;
  52. },
  53. ),
  54. const SizedBox(height: 16),
  55. TextFormField(
  56. controller: _clientIdController,
  57. decoration: const InputDecoration(
  58. labelText: 'Client ID',
  59. border: OutlineInputBorder(),
  60. ),
  61. validator: (value) {
  62. if (value == null || value.isEmpty) {
  63. return '请输入Client ID';
  64. }
  65. return null;
  66. },
  67. ),
  68. ],
  69. ),
  70. ),
  71. ),
  72. actions: [
  73. TextButton(
  74. onPressed: () {
  75. Navigator.of(context).pop();
  76. },
  77. child: const Text('取消'),
  78. ),
  79. ElevatedButton(
  80. onPressed: () async {
  81. if (_formKey.currentState!.validate()) {
  82. // 保存配置
  83. await AppConfig.save(
  84. _baseUrlController.text.trim(),
  85. _clientIdController.text.trim(),
  86. );
  87. // 重新初始化API客户端
  88. ApiClient.clearDio();
  89. if (context.mounted) {
  90. Navigator.of(context).pop(true);
  91. }
  92. }
  93. },
  94. child: const Text('保存'),
  95. ),
  96. ],
  97. );
  98. }
  99. }