diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fdd130..b22619c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## 3.0.0-nullsafety.1 +* Fix typo in PayloadStatus enum (`IN_PROGRRESS -> IN_PROGRESS`). + +## 3.0.0-nullsafety.0 +* Migrated to Null Safety. + ## 2.0.2 * Fix missingPluginException. diff --git a/example/lib/main.dart b/example/lib/main.dart index 06a14c8..616e2ca 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -39,7 +39,7 @@ class _MyBodyState extends State { File tempFile; //reference to the file currently being transferred Map map = - Map(); //store filename mapped to corresponding payloadId + Map(); //store filename mapped to corresponding payloadId @override Widget build(BuildContext context) { @@ -57,12 +57,12 @@ class _MyBodyState extends State { child: Text("checkLocationPermission"), onPressed: () async { if (await Nearby().checkLocationPermission()) { - Scaffold.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text("Location permissions granted :)"))); } else { - Scaffold.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: - Text("Location permissions not granted :("))); + Text("Location permissions not granted :("))); } }, ), @@ -70,12 +70,12 @@ class _MyBodyState extends State { child: Text("askLocationPermission"), onPressed: () async { if (await Nearby().askLocationPermission()) { - Scaffold.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text("Location Permission granted :)"))); } else { - Scaffold.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: - Text("Location permissions not granted :("))); + Text("Location permissions not granted :("))); } }, ), @@ -83,11 +83,11 @@ class _MyBodyState extends State { child: Text("checkExternalStoragePermission"), onPressed: () async { if (await Nearby().checkExternalStoragePermission()) { - Scaffold.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: - Text("External Storage permissions granted :)"))); + Text("External Storage permissions granted :)"))); } else { - Scaffold.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text( "External Storage permissions not granted :("))); } @@ -109,10 +109,10 @@ class _MyBodyState extends State { child: Text("checkLocationEnabled"), onPressed: () async { if (await Nearby().checkLocationEnabled()) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text("Location is ON :)"))); } else { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text("Location is OFF :("))); } }, @@ -121,12 +121,12 @@ class _MyBodyState extends State { child: Text("enableLocationServices"), onPressed: () async { if (await Nearby().enableLocationServices()) { - Scaffold.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text("Location Service Enabled :)"))); } else { - Scaffold.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: - Text("Enabling Location Service Failed :("))); + Text("Enabling Location Service Failed :("))); } }, ), @@ -148,7 +148,8 @@ class _MyBodyState extends State { showSnackbar(status); }, onDisconnected: (id) { - showSnackbar("Disconnected: ${endpointMap[id].endpointName}, id $id"); + showSnackbar( + "Disconnected: ${endpointMap[id].endpointName}, id $id"); setState(() { endpointMap.remove(id); }); @@ -205,7 +206,8 @@ class _MyBodyState extends State { setState(() { endpointMap.remove(id); }); - showSnackbar("Disconnected from: ${endpointMap[id].endpointName}, id $id"); + showSnackbar( + "Disconnected from: ${endpointMap[id].endpointName}, id $id"); }, ); }, @@ -217,7 +219,8 @@ class _MyBodyState extends State { ); }, onEndpointLost: (id) { - showSnackbar("Lost discovered Endpoint: ${endpointMap[id].endpointName}, id $id"); + showSnackbar( + "Lost discovered Endpoint: ${endpointMap[id].endpointName}, id $id"); }, ); showSnackbar("DISCOVERING: " + a.toString()); @@ -255,20 +258,23 @@ class _MyBodyState extends State { String a = Random().nextInt(100).toString(); showSnackbar("Sending $a to ${value.endpointName}, id: $key"); - Nearby().sendBytesPayload(key, Uint8List.fromList(a.codeUnits)); + Nearby() + .sendBytesPayload(key, Uint8List.fromList(a.codeUnits)); }); }, ), RaisedButton( child: Text("Send File Payload"), onPressed: () async { - File file = - await ImagePicker.pickImage(source: ImageSource.gallery); + PickedFile file = + await ImagePicker().getImage(source: ImageSource.gallery); if (file == null) return; - for(MapEntry m in endpointMap.entries){ - int payloadId = await Nearby().sendFilePayload(m.key, file.path); + for (MapEntry m + in endpointMap.entries) { + int payloadId = + await Nearby().sendFilePayload(m.key, file.path); showSnackbar("Sending file to ${m.key}"); Nearby().sendBytesPayload( m.key, @@ -341,7 +347,7 @@ class _MyBodyState extends State { }, onPayloadTransferUpdate: (endid, payloadTransferUpdate) { if (payloadTransferUpdate.status == - PayloadStatus.IN_PROGRRESS) { + PayloadStatus.IN_PROGRESS) { print(payloadTransferUpdate.bytesTransferred); } else if (payloadTransferUpdate.status == PayloadStatus.FAILURE) { diff --git a/example/pubspec.lock b/example/pubspec.lock index d059d13..9b58520 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -122,7 +122,7 @@ packages: path: ".." relative: true source: path - version: "2.0.2" + version: "3.0.0-nullsafety.1" path: dependency: transitive description: @@ -130,20 +130,6 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.8.0-nullsafety.3" - pedantic: - dependency: transitive - description: - name: pedantic - url: "https://pub.dartlang.org" - source: hosted - version: "1.9.2" - plugin_platform_interface: - dependency: transitive - description: - name: plugin_platform_interface - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.3" sky_engine: dependency: transitive description: flutter @@ -206,5 +192,5 @@ packages: source: hosted version: "2.1.0-nullsafety.5" sdks: - dart: ">=2.12.0-0.0 <3.0.0" + dart: ">=2.12.0-29.10.beta <3.0.0" flutter: ">=1.20.0 <2.0.0" diff --git a/lib/src/classes.dart b/lib/src/classes.dart index 103cb93..8bf0d4f 100644 --- a/lib/src/classes.dart +++ b/lib/src/classes.dart @@ -14,11 +14,11 @@ class Payload { int id; PayloadType type; - Uint8List bytes; - String filePath; + Uint8List? bytes; + String? filePath; Payload({ - this.id, + required this.id, this.bytes, this.type = PayloadType.NONE, this.filePath, @@ -32,9 +32,9 @@ class PayloadTransferUpdate { PayloadStatus status; PayloadTransferUpdate({ - this.id, - this.bytesTransferred, - this.totalBytes, + required this.id, + required this.bytesTransferred, + required this.totalBytes, this.status = PayloadStatus.NONE, }); } diff --git a/lib/src/defs.dart b/lib/src/defs.dart index c548f22..4ec857c 100644 --- a/lib/src/defs.dart +++ b/lib/src/defs.dart @@ -9,7 +9,7 @@ import 'package:nearby_connections/src/classes.dart'; /// **P2P_POINT_TO_POINT** - single connection, very high bandwidth enum Strategy { P2P_CLUSTER, P2P_STAR, P2P_POINT_TO_POINT } enum Status { CONNECTED, REJECTED, ERROR } -enum PayloadStatus { NONE, SUCCESS, FAILURE, IN_PROGRRESS, CANCELED } +enum PayloadStatus { NONE, SUCCESS, FAILURE, IN_PROGRESS, CANCELED } enum PayloadType { NONE, BYTES, FILE, STREAM } // @@ -29,7 +29,7 @@ typedef void OnDisconnected(String endpointId); // typedef void OnEndpointFound( String endpointId, String endpointName, String serviceId); -typedef void OnEndpointLost(String endpointId); +typedef void OnEndpointLost(String? endpointId); // // diff --git a/lib/src/nearby.dart b/lib/src/nearby.dart index 55b084c..0b1e3f1 100644 --- a/lib/src/nearby.dart +++ b/lib/src/nearby.dart @@ -1,7 +1,6 @@ import 'dart:async'; import 'dart:typed_data'; -import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:nearby_connections/src/classes.dart'; import 'package:nearby_connections/src/defs.dart'; @@ -14,24 +13,24 @@ import 'package:nearby_connections/src/defs.dart'; /// All methods are asynchronous. class Nearby { //Singleton pattern for maintaining only 1 instance of this class - static Nearby _instance; + static Nearby? _instance; factory Nearby() { if (_instance == null) { _instance = Nearby._(); } - return _instance; + return _instance!; } Nearby._() { - _channel.setMethodCallHandler((handler) { - Map args = handler.arguments; + _channel.setMethodCallHandler((MethodCall handler) { + Map args = handler.arguments!; switch (handler.method) { case "ad.onConnectionInitiated": - String endpointId = args['endpointId']; - String endpointName = args['endpointName']; - String authenticationToken = args['authenticationToken']; - bool isIncomingConnection = args['isIncomingConnection']; + String endpointId = args['endpointId'] ?? '-1'; + String endpointName = args['endpointName'] ?? '-1'; + String authenticationToken = args['authenticationToken'] ?? '-1'; + bool isIncomingConnection = args['isIncomingConnection'] ?? false; _advertConnectionInitiated?.call( endpointId, @@ -40,24 +39,25 @@ class Nearby { return null; case "ad.onConnectionResult": - String endpointId = args['endpointId']; - Status statusCode = Status.values[args['statusCode']]; + String endpointId = args['endpointId'] ?? '-1'; + Status statusCode = + Status.values[args['statusCode'] ?? Status.ERROR.index]; _advertConnectionResult?.call(endpointId, statusCode); return null; case "ad.onDisconnected": - String endpointId = args['endpointId']; + String endpointId = args['endpointId'] ?? '-1'; _advertDisconnected?.call(endpointId); return null; case "dis.onConnectionInitiated": - String endpointId = args['endpointId']; - String endpointName = args['endpointName']; - String authenticationToken = args['authenticationToken']; - bool isIncomingConnection = args['isIncomingConnection']; + String endpointId = args['endpointId'] ?? '-1'; + String endpointName = args['endpointName'] ?? '-1'; + String authenticationToken = args['authenticationToken'] ?? '-1'; + bool isIncomingConnection = args['isIncomingConnection'] ?? false; _discoverConnectionInitiated?.call( endpointId, @@ -66,38 +66,39 @@ class Nearby { return null; case "dis.onConnectionResult": - String endpointId = args['endpointId']; - Status statusCode = Status.values[args['statusCode']]; + String endpointId = args['endpointId'] ?? '-1'; + Status statusCode = + Status.values[args['statusCode'] ?? Status.ERROR.index]; _discoverConnectionResult?.call(endpointId, statusCode); return null; case "dis.onDisconnected": - String endpointId = args['endpointId']; + String endpointId = args['endpointId'] ?? '-1'; _discoverDisconnected?.call(endpointId); return null; case "dis.onEndpointFound": - String endpointId = args['endpointId']; - String endpointName = args['endpointName']; - String serviceId = args['serviceId']; + String endpointId = args['endpointId'] ?? '-1'; + String endpointName = args['endpointName'] ?? '-1'; + String serviceId = args['serviceId'] ?? '-1'; _onEndpointFound?.call(endpointId, endpointName, serviceId); return null; case "dis.onEndpointLost": - String endpointId = args['endpointId']; + String endpointId = args['endpointId'] ?? '-1'; _onEndpointLost?.call(endpointId); return null; case "onPayloadReceived": - String endpointId = args['endpointId']; - int type = args['type']; - Uint8List bytes = args['bytes']; - int payloadId = args['payloadId']; - String filePath = args['filePath']; + String endpointId = args['endpointId'] ?? '-1'; + int type = args['type'] ?? PayloadType.NONE; + Uint8List bytes = args['bytes'] ?? Uint8List(0); + int payloadId = args['payloadId'] ?? -1; + String filePath = args['filePath'] ?? ''; Payload payload = Payload( type: PayloadType.values[type], @@ -110,11 +111,11 @@ class Nearby { break; case "onPayloadTransferUpdate": - String endpointId = args['endpointId']; - int payloadId = args['payloadId']; - int status = args['status']; - int bytesTransferred = args['bytesTransferred']; - int totalBytes = args['totalBytes']; + String endpointId = args['endpointId'] ?? '-1'; + int payloadId = args['payloadId'] ?? -1; + int status = args['status'] ?? Status.ERROR.index; + int bytesTransferred = args['bytesTransferred'] ?? 0; + int totalBytes = args['totalBytes'] ?? 0; PayloadTransferUpdate payloadTransferUpdate = PayloadTransferUpdate( id: payloadId, @@ -127,22 +128,22 @@ class Nearby { break; } return null; - }); + } as Future Function(MethodCall)?); } //for advertisers - OnConnectionInitiated _advertConnectionInitiated, + OnConnectionInitiated? _advertConnectionInitiated, _discoverConnectionInitiated; - OnConnectionResult _advertConnectionResult, _discoverConnectionResult; - OnDisconnected _advertDisconnected, _discoverDisconnected; + OnConnectionResult? _advertConnectionResult, _discoverConnectionResult; + OnDisconnected? _advertDisconnected, _discoverDisconnected; //for discoverers - OnEndpointFound _onEndpointFound; - OnEndpointLost _onEndpointLost; + OnEndpointFound? _onEndpointFound; + OnEndpointLost? _onEndpointLost; //for receiving payload - OnPayloadReceived _onPayloadReceived; - OnPayloadTransferUpdate _onPayloadTransferUpdate; + OnPayloadReceived? _onPayloadReceived; + OnPayloadTransferUpdate? _onPayloadTransferUpdate; static const MethodChannel _channel = const MethodChannel('nearby_connections'); @@ -151,21 +152,23 @@ class Nearby { /// /// returns true/false based on location permissions. /// Discovery cannot be started with insufficient permission - Future checkLocationPermission() async => await _channel.invokeMethod( + Future checkLocationPermission() async => + await _channel.invokeMethod( 'checkLocationPermission', - ); + ) ?? + false; /// convenience method /// /// Asks location permission Future askLocationPermission() async => - await _channel.invokeMethod('askLocationPermission'); + await _channel.invokeMethod('askLocationPermission') ?? false; /// convenience method /// /// returns true/false based on external storage permissions. Future checkExternalStoragePermission() async => - await _channel.invokeMethod('checkExternalStoragePermission'); + await _channel.invokeMethod('checkExternalStoragePermission') ?? false; /// convenience method /// @@ -174,13 +177,13 @@ class Nearby { /// If Location isn't enabled, devices may disconnect often. /// Some devices may immediately disconnect Future checkLocationEnabled() async => - await _channel.invokeMethod('checkLocationEnabled'); + await _channel.invokeMethod('checkLocationEnabled') ?? false; /// convenience method /// /// directs user to Location Settings, so they can turn on their Location/GPS Future enableLocationServices() async => - await _channel.invokeMethod('enableLocationServices'); + await _channel.invokeMethod('enableLocationServices') ?? false; /// convenience method /// @@ -201,22 +204,21 @@ class Nearby { Future startAdvertising( String userNickName, Strategy strategy, { - @required OnConnectionInitiated onConnectionInitiated, - @required OnConnectionResult onConnectionResult, - @required OnDisconnected onDisconnected, + required OnConnectionInitiated onConnectionInitiated, + required OnConnectionResult onConnectionResult, + required OnDisconnected onDisconnected, String serviceId = "com.pkmnapps.nearby_connections", }) async { - assert(userNickName != null && strategy != null && serviceId != null); - this._advertConnectionInitiated = onConnectionInitiated; this._advertConnectionResult = onConnectionResult; this._advertDisconnected = onDisconnected; return await _channel.invokeMethod('startAdvertising', { - 'userNickName': userNickName, - 'strategy': strategy.index, - 'serviceId': serviceId, - }); + 'userNickName': userNickName, + 'strategy': strategy.index, + 'serviceId': serviceId, + }) ?? + false; } /// Stop Advertising @@ -236,19 +238,19 @@ class Nearby { Future startDiscovery( String userNickName, Strategy strategy, { - @required OnEndpointFound onEndpointFound, - @required OnEndpointLost onEndpointLost, + required OnEndpointFound onEndpointFound, + required OnEndpointLost onEndpointLost, String serviceId = "com.pkmnapps.nearby_connections", }) async { - assert(userNickName != null && strategy != null && serviceId != null); this._onEndpointFound = onEndpointFound; this._onEndpointLost = onEndpointLost; return await _channel.invokeMethod('startDiscovery', { - 'userNickName': userNickName, - 'strategy': strategy.index, - 'serviceId': serviceId, - }); + 'userNickName': userNickName, + 'strategy': strategy.index, + 'serviceId': serviceId, + }) ?? + false; } /// Stop Discovery @@ -278,7 +280,6 @@ class Nearby { /// this will call the onDisconnected method on callbacks of /// connected endPoint Future disconnectFromEndpoint(String endpointId) async { - assert(endpointId != null); await _channel.invokeMethod( 'disconnectFromEndpoint', {'endpointId': endpointId}); } @@ -293,24 +294,22 @@ class Nearby { Future requestConnection( String userNickName, String endpointId, { - @required OnConnectionInitiated onConnectionInitiated, - @required OnConnectionResult onConnectionResult, - @required OnDisconnected onDisconnected, + required OnConnectionInitiated onConnectionInitiated, + required OnConnectionResult onConnectionResult, + required OnDisconnected onDisconnected, }) async { this._discoverConnectionInitiated = onConnectionInitiated; this._discoverConnectionResult = onConnectionResult; this._discoverDisconnected = onDisconnected; - assert(endpointId != null); - assert(userNickName != null); - return await _channel.invokeMethod( - 'requestConnection', - { - 'userNickName': userNickName, - 'endpointId': endpointId, - }, - ); + 'requestConnection', + { + 'userNickName': userNickName, + 'endpointId': endpointId, + }, + ) ?? + false; } /// Needs be called by both discoverer and advertiser @@ -323,20 +322,19 @@ class Nearby { /// only if both of them accept the connection Future acceptConnection( String endpointId, { - @required OnPayloadReceived onPayLoadRecieved, - OnPayloadTransferUpdate onPayloadTransferUpdate, + required OnPayloadReceived onPayLoadRecieved, + OnPayloadTransferUpdate? onPayloadTransferUpdate, }) async { this._onPayloadReceived = onPayLoadRecieved; this._onPayloadTransferUpdate = onPayloadTransferUpdate; - assert(endpointId != null); - return await _channel.invokeMethod( - 'acceptConnection', - { - 'endpointId': endpointId, - }, - ); + 'acceptConnection', + { + 'endpointId': endpointId, + }, + ) ?? + false; } /// Reject Connection @@ -349,14 +347,13 @@ class Nearby { /// [OnConnectionResult] is called on both /// even if one of them rejects the connection Future rejectConnection(String endpointId) async { - assert(endpointId != null); - return await _channel.invokeMethod( - 'rejectConnection', - { - 'endpointId': endpointId, - }, - ); + 'rejectConnection', + { + 'endpointId': endpointId, + }, + ) ?? + false; } /// Send bytes [Uint8List] payload to endpoint @@ -374,8 +371,6 @@ class Nearby { /// ``` /// Future sendBytesPayload(String endpointId, Uint8List bytes) async { - assert(endpointId != null); - return await _channel.invokeMethod( 'sendPayload', { @@ -392,9 +387,7 @@ class Nearby { /// You must also send a bytes payload to send the filename and extension /// so that receiver can rename the file accordingly /// Send the payloadID and filename to receiver as bytes payload - Future sendFilePayload(String endpointId, String filePath) async { - assert(endpointId != null); - + Future sendFilePayload(String endpointId, String filePath) async { return await _channel.invokeMethod( 'sendFilePayload', { @@ -406,8 +399,6 @@ class Nearby { /// Use it to cancel/stop a payload transfer Future cancelPayload(int payloadId) async { - assert(payloadId != null); - return await _channel.invokeMethod( 'cancelPayload', { diff --git a/pubspec.lock b/pubspec.lock index 2d3263b..37461ce 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -143,5 +143,5 @@ packages: source: hosted version: "2.1.0-nullsafety.5" sdks: - dart: ">=2.12.0-0.0 <3.0.0" + dart: ">=2.12.0-29.10.beta <3.0.0" flutter: ">=1.20.0 <2.0.0" diff --git a/pubspec.yaml b/pubspec.yaml index 131b66f..b0021c1 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,10 +1,10 @@ name: nearby_connections description: Plugin for the android NearbyConnections API. Bytes and Files Supported. -version: 2.0.2 +version: 3.0.0-nullsafety.1 homepage: https://github.com/mannprerak2/nearby_connections environment: - sdk: ">=2.1.0 <3.0.0" + sdk: '>=2.12.0-29.10.beta <3.0.0' flutter: ">=1.20.0 <2.0.0" dependencies: