|
| 1 | +import 'dart:async'; |
| 2 | + |
| 3 | +import 'package:connectivity_plus/connectivity_plus.dart'; |
| 4 | +import 'package:flutter/foundation.dart'; |
| 5 | + |
| 6 | +import '../flet_service.dart'; |
| 7 | +import '../utils/numbers.dart'; |
| 8 | + |
| 9 | +class ConnectivityService extends FletService { |
| 10 | + final Connectivity _connectivity = Connectivity(); |
| 11 | + StreamSubscription<List<ConnectivityResult>>? _subscription; |
| 12 | + |
| 13 | + ConnectivityService({required super.control}); |
| 14 | + |
| 15 | + @override |
| 16 | + void init() { |
| 17 | + super.init(); |
| 18 | + debugPrint("ConnectivityService(${control.id}).init"); |
| 19 | + control.addInvokeMethodListener(_invokeMethod); |
| 20 | + _updateListeners(); |
| 21 | + } |
| 22 | + |
| 23 | + @override |
| 24 | + void update() { |
| 25 | + _updateListeners(); |
| 26 | + } |
| 27 | + |
| 28 | + Future<dynamic> _invokeMethod(String name, dynamic args) async { |
| 29 | + switch (name) { |
| 30 | + case "check_connectivity": |
| 31 | + final results = await _connectivity.checkConnectivity(); |
| 32 | + return results.map((r) => r.name).toList(); |
| 33 | + default: |
| 34 | + throw Exception("Unknown Connectivity method: $name"); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + void _updateListeners() { |
| 39 | + final listenChange = control.getBool("on_connectivity_change") == true; |
| 40 | + if (listenChange && _subscription == null) { |
| 41 | + _subscription = _connectivity.onConnectivityChanged.listen( |
| 42 | + (List<ConnectivityResult> result) { |
| 43 | + control.triggerEvent("connectivity_change", |
| 44 | + {"connectivity": result.map((r) => r.name).toList()}); |
| 45 | + }, onError: (error) { |
| 46 | + debugPrint( |
| 47 | + "ConnectivityService: error listening to connectivity: $error"); |
| 48 | + }); |
| 49 | + } else if (!listenChange && _subscription != null) { |
| 50 | + _subscription?.cancel(); |
| 51 | + _subscription = null; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + @override |
| 56 | + void dispose() { |
| 57 | + debugPrint("ConnectivityService(${control.id}).dispose()"); |
| 58 | + control.removeInvokeMethodListener(_invokeMethod); |
| 59 | + _subscription?.cancel(); |
| 60 | + _subscription = null; |
| 61 | + super.dispose(); |
| 62 | + } |
| 63 | +} |
0 commit comments