import 'dart:io'; import 'dart:convert'; import 'package:flutter/services.dart'; import 'package:flutter/material.dart'; import 'package:meshport_client_core/meshport_client_core.dart'; Future confirmDiscard(BuildContext context) async => await showDialog( context: context, builder: (c) => AlertDialog( title: const Text('放弃未保存的草稿?'), content: const Text('正在运行的配置不会改变。'), actions: [ TextButton( onPressed: () => Navigator.pop(c, false), child: const Text('继续编辑'), ), FilledButton( onPressed: () => Navigator.pop(c, true), child: const Text('放弃'), ), ], ), ) ?? false; class DraftScaffold extends StatelessWidget { final String title; final bool dirty, busy; final Widget body; final VoidCallback save; const DraftScaffold({ super.key, required this.title, required this.dirty, required this.busy, required this.body, required this.save, }); @override Widget build(BuildContext context) => PopScope( canPop: !dirty && !busy, onPopInvokedWithResult: (didPop, result) async { if (!didPop && !busy && await confirmDiscard(context) && context.mounted) { Navigator.pop(context, true); } }, child: Scaffold( appBar: AppBar( title: Text(title), actions: [ TextButton( onPressed: busy ? null : save, child: Text(busy ? '保存中…' : '保存草稿'), ), ], ), body: SingleChildScrollView( padding: const EdgeInsets.all(20), child: Center( child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 720), child: body, ), ), ), ), ); } bool validDomain(String v) => v.length <= 253 && v .split('.') .every( (label) => RegExp( r'^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$', ).hasMatch(label), ); bool validCidr(String v) { final parts = v.split('/'); final address = InternetAddress.tryParse(parts.first); final bits = parts.length == 2 ? int.tryParse(parts[1]) : null; return address != null && bits != null && bits >= 0 && bits <= (address.type == InternetAddressType.IPv4 ? 32 : 128); } bool validDns(String v) { if (InternetAddress.tryParse(v) != null) return true; final uri = Uri.tryParse('udp://$v'); return uri != null && InternetAddress.tryParse(uri.host) != null && uri.hasPort && uri.port > 0 && uri.port <= 65535; } class RuleEditor extends StatefulWidget { final Map? rule; const RuleEditor({super.key, this.rule}); @override State createState() => _RuleEditorState(); } class _RuleEditorState extends State { late String type = widget.rule?['type'] ?? 'domain_suffix', action = widget.rule?['action'] ?? 'proxy'; late final value = TextEditingController(text: widget.rule?['value'] ?? ''); String error = ''; @override void dispose() { value.dispose(); super.dispose(); } @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: const Text('编辑分流规则'), actions: [ TextButton( onPressed: () { final v = value.text.trim(); if (type == 'ip_cidr' ? !validCidr(v) : !validDomain(v)) { setState(() => error = '请输入有效域名或 CIDR,不接受星号语法'); return; } Navigator.pop(context, { 'type': type, 'value': v, 'action': action, }); }, child: const Text('保存规则'), ), ], ), body: SingleChildScrollView( padding: const EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, spacing: 16, children: [ if (error.isNotEmpty) Text(error), DropdownButtonFormField( isExpanded: true, initialValue: type, items: const [ DropdownMenuItem(value: 'domain', child: Text('精确域名')), DropdownMenuItem(value: 'domain_suffix', child: Text('域名后缀')), DropdownMenuItem(value: 'ip_cidr', child: Text('IP CIDR')), ], onChanged: (v) => setState(() => type = v!), ), TextField( controller: value, decoration: const InputDecoration(labelText: '匹配值'), ), DropdownButtonFormField( isExpanded: true, initialValue: action, items: const [ DropdownMenuItem(value: 'proxy', child: Text('所选代理')), DropdownMenuItem(value: 'direct', child: Text('直连')), DropdownMenuItem(value: 'reject', child: Text('拒绝')), ], onChanged: (v) => setState(() => action = v!), ), const Text('按列表顺序匹配;组网优先,然后普通规则,最后规则集。'), ], ), ), ); } class RulesPage extends StatefulWidget { final ProxyProfile profile; final VoidCallback changed; const RulesPage({super.key, required this.profile, required this.changed}); @override State createState() => _RulesPageState(); } class _RulesPageState extends State { late final rules = widget.profile.rules .map((v) => Map.from(v)) .toList(); late final sets = widget.profile.ruleSets .map((v) => Map.from(v)) .toList(); String ruleError = ''; late String outlet = widget.profile.defaultAction; Future editSet([int? index]) async { final result = await Navigator.push>( context, MaterialPageRoute( builder: (_) => RuleSetEditor(initial: index == null ? null : sets[index]), ), ); if (result != null && mounted) { setState(() { if (index == null) { sets.add(result); } else { sets[index] = result; } dirty = true; }); } } bool dirty = false; Future edit([int? index]) async { final next = await Navigator.push>( context, MaterialPageRoute( builder: (_) => RuleEditor(rule: index == null ? null : rules[index]), ), ); if (next != null && mounted) { setState(() { if (index == null) { rules.add(next); } else { rules[index] = next; } dirty = true; }); } } @override Widget build(BuildContext context) => DraftScaffold( title: '分流规则', dirty: dirty, busy: false, save: () { final tags = sets.map((v) => v['tag']).toList(); if (tags.toSet().length != tags.length) { setState(() => ruleError = '规则集标识不能重复'); return; } widget.profile.rules = rules; widget.profile.ruleSets = sets; widget.profile.defaultAction = outlet; widget.changed(); setState(() => dirty = false); Navigator.pop(context); }, body: Column( crossAxisAlignment: CrossAxisAlignment.stretch, spacing: 16, children: [ if (ruleError.isNotEmpty) Text(ruleError), const ListTile( leading: Icon(Icons.lock_outline), title: Text('组网优先 · 受管理'), subtitle: Text('有效目标走组网;已知失效目标拒绝。不能移动或关闭。'), ), Text( widget.profile.mode == 'rule' && widget.profile.feature != 'mesh' ? '普通规则按顺序执行' : '当前模式暂停普通规则', ), for (final entry in rules.indexed) Card( child: ListTile( title: Text('${entry.$1 + 1}. ${entry.$2['value']}'), subtitle: Text('${entry.$2['type']} → ${entry.$2['action']}'), onTap: () => edit(entry.$1), trailing: Wrap( children: [ IconButton( tooltip: '上移', onPressed: entry.$1 == 0 ? null : () => setState(() { final v = rules.removeAt(entry.$1); rules.insert(entry.$1 - 1, v); dirty = true; }), icon: const Icon(Icons.arrow_upward), ), IconButton( tooltip: '删除', onPressed: () => setState(() { rules.removeAt(entry.$1); dirty = true; }), icon: const Icon(Icons.delete_outline), ), ], ), ), ), OutlinedButton(onPressed: () => edit(), child: const Text('添加规则')), const Text('规则集 · 普通规则之后按顺序匹配'), for (final e in sets.indexed) ListTile( title: Text('${e.$2['tag']} → ${e.$2['action']}'), subtitle: Text( e.$2['url'] == null ? '内联规则' : 'HTTPS ${e.$2['format']} · 每 ${e.$2['update_hours'] ?? 24} 小时更新', ), leading: Switch( value: e.$2['enabled'] == true, onChanged: (v) => setState(() { e.$2['enabled'] = v; dirty = true; }), ), onTap: () => editSet(e.$1), trailing: Wrap( children: [ IconButton( tooltip: '上移规则集', icon: const Icon(Icons.arrow_upward), onPressed: e.$1 == 0 ? null : () => setState(() { sets.insert(e.$1 - 1, sets.removeAt(e.$1)); dirty = true; }), ), IconButton( tooltip: '删除规则集', icon: const Icon(Icons.delete_outline), onPressed: () => setState(() { sets.removeAt(e.$1); dirty = true; }), ), ], ), ), OutlinedButton(onPressed: () => editSet(), child: const Text('添加规则集')), DropdownButtonFormField( isExpanded: true, initialValue: outlet, decoration: const InputDecoration(labelText: '固定默认出口'), items: const [ DropdownMenuItem(value: 'proxy', child: Text('所选代理')), DropdownMenuItem(value: 'direct', child: Text('直连')), DropdownMenuItem(value: 'reject', child: Text('拒绝')), ], onChanged: (v) => setState(() { outlet = v!; dirty = true; }), ), const Text('保存不改变当前会话;应用时需要重连。'), ], ), ); } class DnsPage extends StatefulWidget { final ProxyProfile profile; final VoidCallback changed; const DnsPage({super.key, required this.profile, required this.changed}); @override State createState() => _DnsPageState(); } class _DnsPageState extends State { late final bootstrap = TextEditingController(text: widget.profile.dnsServer), direct = TextEditingController(text: widget.profile.directDnsServer), proxy = TextEditingController(text: widget.profile.proxyDnsServer), exclude = TextEditingController( text: widget.profile.fakeIPExclude.join('\n'), ); late bool fake = widget.profile.fakeIP; late final mesh = widget.profile.meshDns .map((v) => Map.from(v)) .toList(); bool dirty = false; String error = ''; @override void dispose() { bootstrap.dispose(); direct.dispose(); proxy.dispose(); exclude.dispose(); super.dispose(); } Future meshRule([int? index]) async { final result = await showDialog>( context: context, builder: (_) => _MeshDnsDialog(initial: index == null ? null : mesh[index]), ); if (result != null && mounted) { setState(() { if (index == null) { mesh.add(result); } else { mesh[index] = result; } dirty = true; }); } } void save() { final exclusions = exclude.text .split('\n') .map((v) => v.trim()) .where((v) => v.isNotEmpty) .toList(); if (!validDns(bootstrap.text.trim()) || (proxy.text.trim().isNotEmpty && !validResolver(proxy.text.trim())) || (direct.text.trim().isNotEmpty && !validResolver(direct.text.trim())) || exclusions.any((v) => !validDomain(v))) { setState( () => error = '启动 DNS 需为 IP;解析器支持 IP、https:// 和 tls://;排除项需为域名后缀', ); return; } final p = widget.profile; p.dnsServer = bootstrap.text.trim(); p.proxyDnsServer = proxy.text.trim(); p.directDnsServer = direct.text.trim(); p.meshDns = mesh; p.fakeIP = fake; p.fakeIPExclude = exclusions; widget.changed(); setState(() => dirty = false); Navigator.pop(context); } @override Widget build(BuildContext context) => DraftScaffold( title: 'DNS 设置', dirty: dirty, busy: false, save: save, body: Column( crossAxisAlignment: CrossAxisAlignment.stretch, spacing: 16, children: [ if (error.isNotEmpty) Text( error, style: TextStyle(color: Theme.of(context).colorScheme.error), ), const Text( '默认使用 Cloudflare 加密 DNS,经所选代理查询,失败不回退直连。代理 DNS 留空时使用默认值。直连模式使用直连 DNS。启动 DNS 用于连接节点和解析器,组网域名走组网 DNS。', ), TextField( controller: bootstrap, onChanged: (_) => setState(() => dirty = true), decoration: const InputDecoration( labelText: '启动 DNS IP', helperText: '必要启动解析走物理网络,可用 IP 地址减少此类查询', ), ), TextField( controller: direct, onChanged: (_) => setState(() => dirty = true), decoration: const InputDecoration( labelText: '直连 DNS(可选)', helperText: 'https://dns.example/dns-query 或 tls://dns.example', ), ), TextField( controller: proxy, onChanged: (_) => setState(() => dirty = true), decoration: const InputDecoration( labelText: '代理 DNS', helperText: '留空使用 https://cloudflare-dns.com/dns-query;支持 IP / DoH / DoT', ), ), SwitchListTile( title: const Text('FakeIP'), subtitle: const Text('普通 A/AAAA 查询返回虚拟地址;组网和排除域名使用真实解析。修改后需重连。'), value: fake, onChanged: widget.profile.feature == 'mesh' ? null : (v) => setState(() { fake = v; dirty = true; }), ), TextField( controller: exclude, maxLines: 3, onChanged: (_) => setState(() => dirty = true), decoration: const InputDecoration( labelText: 'FakeIP 排除域名后缀', helperText: '每行一个域名后缀;localhost / local / lan 固定排除', ), ), const SizedBox(height: 16), const Text('组网域名范围 · 失败不回退公共 DNS'), for (final entry in mesh.indexed) ListTile( title: Text(entry.$2['suffix']), subtitle: Text('${entry.$2['server']} · 组网出口 · 拒绝回退'), onTap: () => meshRule(entry.$1), trailing: IconButton( onPressed: () => setState(() { mesh.removeAt(entry.$1); dirty = true; }), icon: const Icon(Icons.delete_outline), ), ), OutlinedButton( onPressed: widget.profile.feature == 'proxy' ? null : () => meshRule(), child: const Text('添加组网 DNS 规则'), ), const Text( 'FakeIP 映射保留在会话私有缓存,公告重建不清空;释放会话时清理。显式重连可能中断现有连接。仅代理时组网 DNS 不启用。', ), ], ), ); } class NetworkConfigPage extends StatefulWidget { final String section; final Map initial; final Future Function(Map) save; const NetworkConfigPage({ super.key, required this.section, required this.initial, required this.save, }); @override State createState() => _NetworkConfigPageState(); } class _NetworkConfigPageState extends State { late final v = NetworkProfile(widget.initial).values; final controllers = {}; bool dirty = false, busy = false; String error = ''; Map get flags => v['flags'] as Map; Map get policy => v['optimization'] as Map; @override void initState() { super.initState(); v.putIfAbsent('flags', () => {}); v.putIfAbsent('optimization', () => {'mode': 'adaptive'}); } @override void dispose() { for (final c in controllers.values) { c.dispose(); } super.dispose(); } Widget text( String title, String key, { Map? map, bool list = false, bool secret = false, bool number = false, int lines = 1, }) { final data = map ?? v; final id = '${identical(data, policy) ? 'policy' : identical(data, flags) ? 'flags' : 'root'}:$key'; final controller = controllers.putIfAbsent( id, () => TextEditingController( text: list ? (data[key] as List? ?? []).join('\n') : '${data[key] ?? ''}', ), ); return Padding( padding: const EdgeInsets.only(bottom: 14), child: TextField( controller: controller, obscureText: secret, maxLines: lines, decoration: InputDecoration(labelText: title), onChanged: (value) => setState(() { data[key] = list ? value .split('\n') .map((v) => v.trim()) .where((v) => v.isNotEmpty) .toList() : number ? (key == 'foreign_relay_bps_limit' ? value.trim() : num.tryParse(value)) : value; dirty = true; }), ), ); } Widget toggle( String title, String key, { Map? map, bool enabled = true, bool defaultValue = false, }) { final data = map ?? v; return SwitchListTile( contentPadding: EdgeInsets.zero, title: Text(title), value: data[key] as bool? ?? defaultValue, onChanged: enabled ? (value) => setState(() { data[key] = value; dirty = true; }) : null, ); } Widget choice( String title, String key, List items, { Map? map, }) { final data = map ?? v; return DropdownButtonFormField( isExpanded: true, initialValue: data[key] as String? ?? items.first, decoration: InputDecoration(labelText: title), items: items .map((v) => DropdownMenuItem(value: v, child: Text(v))) .toList(), onChanged: (value) => setState(() { data[key] = value; dirty = true; }), ); } Future save() async { setState(() => busy = true); try { await widget.save(v); if (mounted) { setState(() => dirty = false); Navigator.pop(context); } } catch (_) { if (mounted) setState(() => error = '配置校验或保存失败,请检查字段;当前连接保持不变。'); } finally { if (mounted) setState(() => busy = false); } } @override Widget build(BuildContext context) { final p2p = flags['disable_p2p'] != true; return DraftScaffold( title: widget.section, dirty: dirty, busy: busy, save: save, body: Column( crossAxisAlignment: CrossAxisAlignment.stretch, spacing: 16, children: [ if (error.isNotEmpty) Text(error), const Text('保存为配置,不立即修改运行会话;应用时需要重连。'), const SizedBox(height: 16), if (widget.section == '基础配置') ...[ choice('网络入口', 'runtime_mode', [ 'application', 'system_vpn', 'unified_vpn', ]), text('网络名称', 'network_name'), text('网络密钥', 'network_secret', secret: true), text('节点名称', 'hostname'), toggle( '自动分配虚拟 IP', 'dhcp', enabled: v['runtime_mode'] == 'application', ), if (v['dhcp'] != true) text('虚拟 IPv4 / 前缀', 'ipv4'), text('引导节点(每行一个 tcp:// 或 udp://)', 'peers', list: true, lines: 3), const Text('无引导节点即独立组网,不会自动发现互联网上的设备。公共引导列表暂不内置。'), ], if (widget.section == '连接与打洞') ...[ toggle('禁用 P2P', 'disable_p2p', map: flags), toggle( '禁用 UDP 打洞', 'disable_udp_hole_punching', map: flags, enabled: p2p, ), toggle( '禁用 TCP 打洞', 'disable_tcp_hole_punching', map: flags, enabled: p2p, ), toggle( '禁用对称 NAT 打洞', 'disable_sym_hole_punching', map: flags, enabled: p2p, ), toggle('底层 IPv6', 'enable_ipv6', defaultValue: true), choice('首选底层协议', 'default_protocol', ['udp', 'tcp'], map: flags), text('监听 URI(每行一个)', 'listeners', list: true, lines: 3), for (final key in ['stun_servers', 'stun_servers_v6']) ...[ SwitchListTile( title: Text('$key · 使用默认'), value: v[key] == null, onChanged: (value) => setState(() { v[key] = value ? null : []; dirty = true; }), ), if (v[key] != null) text('$key(每行 host:port)', key, list: true, lines: 3), ], const SwitchListTile( value: false, onChanged: null, title: Text('UPnP · 当前 SDK 未提供'), ), ], if (widget.section == '高级配置') ...[ const SwitchListTile( value: true, onChanged: null, title: Text('加密 · 固定开启'), ), toggle('私有模式', 'private_mode', map: flags), toggle('仅 P2P', 'p2p_only', map: flags), toggle('按需建立 P2P', 'lazy_p2p', map: flags), toggle('主动 P2P', 'need_p2p', map: flags), text( '外部中继速率限制(字节/秒)', 'foreign_relay_bps_limit', map: flags, number: true, ), for (final title in [ 'KCP / QUIC', '本地子网发布', '出口节点 / 系统转发', '多线程控制', ]) SwitchListTile( value: false, onChanged: null, title: Text('$title · SDK 未开放'), ), ], if (widget.section == '线路策略') ...[ choice('策略', 'mode', [ 'adaptive', 'direct', 'latency', 'hop', ], map: policy), text('最低改善(ms)', 'min_improvement_ms', map: policy, number: true), text( '最低改善比例(0~1)', 'min_improvement_ratio', map: policy, number: true, ), text('持续确认(秒)', 'hold_seconds', map: policy, number: true), text('切换冷却(秒)', 'cooldown_seconds', map: policy, number: true), toggle('优先已确认 UDP', 'prefer_udp', map: policy, defaultValue: true), text( '候选中继节点 ID(每行一个)', 'relay_peer_ids', map: policy, list: true, lines: 3, ), const Text('候选中继是筛选条件,不强制始终走某个节点。延迟优先由该策略统一决定。'), ], ], ), ); } } class _MeshDnsDialog extends StatefulWidget { final Map? initial; const _MeshDnsDialog({this.initial}); @override State<_MeshDnsDialog> createState() => _MeshDnsDialogState(); } class _MeshDnsDialogState extends State<_MeshDnsDialog> { late final suffix = TextEditingController(text: widget.initial?['suffix']); late final server = TextEditingController(text: widget.initial?['server']); String? error; @override void dispose() { suffix.dispose(); server.dispose(); super.dispose(); } @override Widget build(BuildContext context) => AlertDialog( title: const Text('组网 DNS 规则'), content: Column( mainAxisSize: MainAxisSize.min, children: [ TextField( controller: suffix, decoration: const InputDecoration(labelText: '域名后缀'), ), TextField( controller: server, decoration: InputDecoration( labelText: '组网 DNS IPv4', errorText: error, ), ), const Text('请求经组网;失败拒绝。自动排除 FakeIP。'), ], ), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text('取消'), ), FilledButton( onPressed: () { final ip = InternetAddress.tryParse(server.text.trim()); if (!validDomain(suffix.text.trim()) || ip == null || ip.type != InternetAddressType.IPv4) { setState(() => error = '需要有效后缀及 IPv4'); return; } Navigator.pop(context, { 'suffix': suffix.text.trim(), 'server': server.text.trim(), }); }, child: const Text('保存'), ), ], ); } bool validResolver(String value) { if (!value.contains('://')) return validDns(value); final u = Uri.tryParse(value); return u != null && {'https', 'tls'}.contains(u.scheme) && u.host.isNotEmpty && (InternetAddress.tryParse(u.host) != null || validDomain(u.host)) && u.userInfo.isEmpty && u.fragment.isEmpty && u.query.isEmpty && (!u.hasPort || (u.port > 0 && u.port <= 65535)) && (u.scheme != 'tls' || u.path.isEmpty || u.path == '/'); } class RuleSetEditor extends StatefulWidget { final Map? initial; const RuleSetEditor({super.key, this.initial}); @override State createState() => _RuleSetEditorState(); } class _RuleSetEditorState extends State { late final tag = TextEditingController(text: widget.initial?['tag'] ?? ''), url = TextEditingController(text: widget.initial?['url'] ?? ''), rules = TextEditingController( text: widget.initial?['rules'] == null ? '' : const JsonEncoder.withIndent( ' ', ).convert({'version': 3, 'rules': widget.initial!['rules']}), ); late String format = widget.initial?['format'] ?? 'source', action = widget.initial?['action'] ?? 'direct', detour = widget.initial?['download_detour'] ?? 'direct'; late bool remote = widget.initial?['rules'] == null; late int hours = widget.initial?['update_hours'] ?? 24; bool dirty = false; String error = ''; @override void dispose() { tag.dispose(); url.dispose(); rules.dispose(); super.dispose(); } void save() { try { if (!validDomain(tag.text.trim())) { throw const FormatException('规则集标识需为字母数字或域名形式'); } final next = { 'tag': tag.text.trim(), 'enabled': widget.initial?['enabled'] ?? true, 'action': action, }; if (remote) { final u = Uri.tryParse(url.text.trim()); if (u == null || u.scheme != 'https' || u.host.isEmpty || u.userInfo.isNotEmpty || u.fragment.isNotEmpty) { throw const FormatException('需要 HTTPS 规则集地址'); } next.addAll({ 'url': u.toString(), 'format': format, 'download_detour': detour, 'update_hours': hours, }); } else { final j = jsonDecode(rules.text); final list = j is List ? j : (j as Map)['rules']; if (list is! List || list.isEmpty || list.length > 256 || list.any((v) => v is! Map) || utf8.encode(jsonEncode(list)).length > 24000) { throw const FormatException( '需要最多 256 条、24 KiB 的 sing-box source 规则;不支持文件路径', ); } next['rules'] = list; } setState(() => dirty = false); Navigator.pop(context, next); } catch (e) { setState( () => error = e is FormatException ? e.message : '规则集 JSON 格式无效', ); } } @override Widget build(BuildContext context) => DraftScaffold( title: '编辑规则集', dirty: dirty, busy: false, save: save, body: Column( crossAxisAlignment: CrossAxisAlignment.stretch, spacing: 16, children: [ if (error.isNotEmpty) Text(error), TextField( controller: tag, onChanged: (_) => setState(() => dirty = true), decoration: const InputDecoration( labelText: '唯一标识', hintText: '例如 private-sites', ), ), SwitchListTile( title: const Text('远程规则集'), value: remote, onChanged: (v) => setState(() { remote = v; dirty = true; }), ), if (remote) ...[ TextField( controller: url, onChanged: (_) => setState(() => dirty = true), decoration: const InputDecoration( labelText: 'HTTPS source / binary 地址', ), ), DropdownButtonFormField( isExpanded: true, initialValue: format, items: const [ DropdownMenuItem(value: 'source', child: Text('Source JSON')), DropdownMenuItem(value: 'binary', child: Text('Binary .srs')), ], onChanged: (v) => setState(() { format = v!; dirty = true; }), ), DropdownButtonFormField( isExpanded: true, initialValue: hours, decoration: const InputDecoration(labelText: '更新间隔'), items: [1, 6, 12, 24, 48, 168] .map((v) => DropdownMenuItem(value: v, child: Text('$v 小时'))) .toList(), onChanged: (v) => setState(() { hours = v!; dirty = true; }), ), DropdownButtonFormField( isExpanded: true, initialValue: detour, decoration: const InputDecoration(labelText: '下载出口'), items: const [ DropdownMenuItem(value: 'direct', child: Text('直连')), DropdownMenuItem(value: 'proxy', child: Text('所选代理')), ], onChanged: (v) => setState(() { detour = v!; dirty = true; }), ), ] else ...[ TextField( controller: rules, maxLines: 8, onChanged: (_) => setState(() => dirty = true), decoration: const InputDecoration( labelText: 'sing-box source JSON(rules)', ), ), OutlinedButton( onPressed: () async { try { final text = await const MethodChannel( 'meshport/system_vpn', ).invokeMethod('import_file'); if (text != null && mounted) { setState(() { rules.text = text; dirty = true; }); } } catch (_) { if (mounted) setState(() => error = '文件读取失败或平台尚不支持'); } }, child: const Text('从 JSON 文件导入'), ), ], DropdownButtonFormField( isExpanded: true, initialValue: action, decoration: const InputDecoration(labelText: '匹配后执行'), items: const [ DropdownMenuItem(value: 'direct', child: Text('直连')), DropdownMenuItem(value: 'proxy', child: Text('所选代理')), DropdownMenuItem(value: 'reject', child: Text('拒绝')), ], onChanged: (v) => setState(() { action = v!; dirty = true; }), ), const Text('远程集在规则模式连接期间自动更新并缓存;首次下载失败会阻止连接,后续失败保留已缓存版本。保存后重连生效。'), ], ), ); }