-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathmain.dart
More file actions
506 lines (477 loc) · 15.7 KB
/
Copy pathmain.dart
File metadata and controls
506 lines (477 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_vless/flutter_vless.dart';
import 'package:flutter_vless_example/routing.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
final base = ThemeData.dark();
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter VLESS',
theme: base.copyWith(
colorScheme: base.colorScheme.copyWith(
primary: Colors.orangeAccent,
secondary: Colors.orangeAccent.shade200,
),
inputDecorationTheme: const InputDecorationTheme(
border: OutlineInputBorder(),
),
),
home: const HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final ValueNotifier<VlessStatus> vlessStatus =
ValueNotifier<VlessStatus>(VlessStatus());
late final FlutterVless flutterVless = FlutterVless(
onStatusChanged: (status) {
vlessStatus.value = status;
},
);
final TextEditingController config = TextEditingController(text: '{}');
bool proxyOnly = false;
List<String> bypassSubnets = [];
List<String> blockedApps = [];
List<String> blockedDomains = [];
String? coreVersion;
String remark = 'Example Remark';
@override
void initState() {
super.initState();
// Plugin initialization
flutterVless
.initializeVless(
notificationIconResourceType: 'mipmap',
notificationIconResourceName: 'ic_launcher',
providerBundleIdentifier: 'dev.tfox.flutterXrayExample',
groupIdentifier: 'group.dev.tfox.flutterXray',
)
.then((_) async {
coreVersion = await flutterVless.getCoreVersion();
setState(() {});
});
}
@override
void dispose() {
config.dispose();
vlessStatus.dispose();
super.dispose();
}
Future<void> _requestPermission() async {
final ok = await flutterVless.requestPermission();
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(ok ? 'Permission granted' : 'Permission denied'),
));
}
Future<void> _connect() async {
if (!proxyOnly && !await flutterVless.requestPermission()) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Permission Denied'),
));
return;
}
await flutterVless.startVless(
remark: remark,
config: config.text,
proxyOnly: proxyOnly,
bypassSubnets: bypassSubnets,
blockedApps: blockedApps,
notificationDisconnectButtonName: 'DISCONNECT',
);
}
Future<void> _disconnect() async {
await flutterVless.stopVless();
}
Future<void> _showProviderDiagnostics() async {
const channel = MethodChannel('flutter_vless');
try {
final snapshot = await channel.invokeMethod<String>(
'getProviderDebugSnapshot',
) ??
'';
if (!mounted) return;
final content = snapshot.trim().isEmpty
? 'No provider diagnostics have been recorded yet. Connect the VPN first, then retry after a failure.'
: snapshot;
await showDialog<void>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('VPN diagnostics'),
content: SizedBox(
width: double.maxFinite,
height: 420,
child: Scrollbar(
thumbVisibility: true,
child: SingleChildScrollView(
padding: const EdgeInsets.only(right: 12),
child: SelectableText(
content,
style: const TextStyle(
fontFamily: 'monospace',
fontSize: 12,
),
),
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(),
child: const Text('Close'),
),
ElevatedButton.icon(
onPressed: snapshot.trim().isEmpty
? null
: () async {
await Clipboard.setData(ClipboardData(text: snapshot));
if (!dialogContext.mounted || !mounted) return;
Navigator.of(dialogContext).pop();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('VPN diagnostics copied')),
);
},
icon: const Icon(Icons.copy),
label: const Text('Copy'),
),
],
),
);
} on PlatformException catch (error) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Diagnostics unavailable: ${error.message}')),
);
}
}
Future<void> _importFromClipboard() async {
if (await Clipboard.hasStrings()) {
try {
final text =
(await Clipboard.getData('text/plain'))?.text?.trim() ?? '';
final FlutterVlessURL parsed = FlutterVless.parse(text);
remark = parsed.remark;
config.text = parsed.getFullConfiguration();
if (!mounted) return;
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(content: Text('Imported')));
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Import error: $e')));
}
}
}
bool _canStop(VlessStatus status) {
return switch (status.connectionState) {
VlessConnectionState.connected ||
VlessConnectionState.connecting ||
VlessConnectionState.disconnecting =>
true,
VlessConnectionState.disconnected ||
VlessConnectionState.unknown =>
false,
};
}
Future<void> _showBypassEditor() async {
final controller = TextEditingController(text: bypassSubnets.join('\n'));
await showDialog<void>(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.grey[900],
title: const Text('Bypass subnets'),
content: TextField(
controller: controller,
maxLines: 6,
decoration: const InputDecoration(
hintText: 'one subnet per line, e.g. 192.168.0.0/13',
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
ElevatedButton(
onPressed: () {
final list = controller.text
.split('\n')
.map((s) => s.trim())
.where((s) => s.isNotEmpty)
.toList();
setState(() {
bypassSubnets = list;
});
Navigator.of(context).pop();
},
child: const Text('Save'),
),
],
),
);
}
String _formatBytes(int? bytes) {
if (bytes == null) return '-';
const units = ['B', 'KB', 'MB', 'GB'];
double b = bytes.toDouble();
int i = 0;
while (b >= 1024 && i < units.length - 1) {
b /= 1024;
i++;
}
return '${b.toStringAsFixed(b >= 10 ? 0 : 1)} ${units[i]}';
}
String _formatDuration(int? seconds) {
if (seconds == null) return '- s';
return '$seconds s';
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Vless — Example'),
actions: [
IconButton(
icon: const Icon(Icons.settings),
onPressed: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => Routing(
config: config.text,
blockedApps: blockedApps,
blockedDomains: blockedDomains,
onApplyConfig: (String c) => config.text = c,
onApplyApps: (List<String> apps) => blockedApps = apps,
onApplyDomains: (List<String> domains) =>
blockedDomains = domains)),
),
tooltip: 'Routing / Rules',
),
],
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Expanded(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildConfigCard(),
const SizedBox(height: 12),
_buildStatusCard(),
const SizedBox(height: 12),
_buildControls(),
const SizedBox(height: 52),
],
),
),
),
],
),
),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () async {
if (_canStop(vlessStatus.value)) {
await _disconnect();
} else {
await _connect();
}
},
backgroundColor: Theme.of(context).colorScheme.primary,
icon: const Icon(
Icons.power_settings_new,
color: Colors.black87,
),
label: ValueListenableBuilder<VlessStatus>(
valueListenable: vlessStatus,
builder: (context, status, child) {
return Text(
_canStop(status) ? 'Disconnect' : 'Connect',
style: const TextStyle(color: Colors.black87),
);
},
),
),
);
}
Widget _buildConfigCard() {
return Card(
color: Colors.grey[900],
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Configuration (JSON)',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
const SizedBox(height: 8),
SizedBox(
height: 140,
child: TextField(
controller: config,
maxLines: null,
expands: true,
style: const TextStyle(fontFamily: 'monospace', fontSize: 13),
decoration: const InputDecoration(
isDense: true,
contentPadding: EdgeInsets.all(12),
),
),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: [
ElevatedButton.icon(
onPressed: _requestPermission,
icon: const Icon(Icons.shield),
label: const Text('Request Permission'),
),
ElevatedButton.icon(
onPressed: _importFromClipboard,
icon: const Icon(Icons.paste),
label: const Text('Import (clipboard)'),
),
],
),
],
),
),
);
}
Widget _buildStatusCard() {
return Card(
color: Colors.grey[900],
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
child: Padding(
padding: const EdgeInsets.all(14),
child: ValueListenableBuilder<VlessStatus>(
valueListenable: vlessStatus,
builder: (context, st, child) {
final state = st.state;
final durationSeconds = st.duration;
final upSpeed = st.uploadSpeed;
final downSpeed = st.downloadSpeed;
final upTraffic = st.upload;
final downTraffic = st.download;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(state,
style: const TextStyle(
fontSize: 18, fontWeight: FontWeight.bold)),
Chip(
backgroundColor:
Colors.orangeAccent.shade100.withValues(alpha: 0.15),
label: Text(_formatDuration(durationSeconds)),
),
],
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: _smallInfo(
'Up', _formatBytes(upTraffic), '$upSpeed B/s')),
const SizedBox(width: 12),
Expanded(
child: _smallInfo('Down', _formatBytes(downTraffic),
'$downSpeed B/s')),
],
),
const SizedBox(height: 12),
if ((vlessStatus.value.state).toUpperCase() == 'CONNECTED')
LinearProgressIndicator(value: null),
const SizedBox(height: 8),
Text('Core: ${coreVersion ?? '-'}',
style: const TextStyle(fontSize: 12)),
],
);
},
),
),
);
}
Widget _buildControls() {
return Card(
color: Colors.grey[900],
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
child: Padding(
padding: const EdgeInsets.all(14),
child: Wrap(
spacing: 8,
children: [
ElevatedButton.icon(
onPressed: _showBypassEditor,
icon: const Icon(Icons.wifi_off),
label: const Text('Bypass Subnets'),
),
ElevatedButton.icon(
onPressed: () => setState(() => proxyOnly = !proxyOnly),
icon: const Icon(Icons.swap_horiz),
label: Text(proxyOnly ? 'Proxy Only' : 'VPN Mode'),
),
ElevatedButton.icon(
onPressed: () async {
// Get server delay
int delay;
if ((vlessStatus.value.state).toUpperCase() == 'CONNECTED') {
delay = await flutterVless.getConnectedServerDelay();
} else {
delay =
await flutterVless.getServerDelay(config: config.text);
}
if (!mounted) return;
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('$delay ms')));
},
icon: const Icon(Icons.timer),
label: const Text('Delay'),
),
if (Platform.isIOS || Platform.isMacOS)
ElevatedButton.icon(
onPressed: _showProviderDiagnostics,
icon: const Icon(Icons.bug_report_outlined),
label: const Text('VPN Diagnostics'),
),
],
),
),
);
}
Widget _smallInfo(String title, String traffic, String speed) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title,
style: const TextStyle(fontSize: 12, color: Colors.white70)),
const SizedBox(height: 6),
Text(traffic,
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600)),
const SizedBox(height: 4),
Text(speed,
style: const TextStyle(fontSize: 12, color: Colors.white60)),
],
);
}
}