Skip to content

Commit

Permalink
attempt null safety
Browse files Browse the repository at this point in the history
  • Loading branch information
Facundo Medica committed Jul 17, 2021
1 parent 5b47a05 commit 5b2023d
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 57 deletions.
34 changes: 17 additions & 17 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
import 'dart:async';
import 'package:fast_qr_reader_view/fast_qr_reader_view.dart';

List<CameraDescription> cameras;
late List<CameraDescription> cameras;

void main() async {
await runZonedGuarded(
Expand All @@ -21,7 +21,7 @@ void main() async {
);
}

void logError(String code, String message) =>
void logError(String code, String? message) =>
print('Error: $code\nError Message: $message');

class MyApp extends StatefulWidget {
Expand All @@ -30,9 +30,9 @@ class MyApp extends StatefulWidget {
}

class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
QRReaderController controller;
QRReaderController? controller;
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
AnimationController animationController;
late AnimationController animationController;

@override
void initState() {
Expand Down Expand Up @@ -71,7 +71,7 @@ class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
});
}

Animation<double> verticalPosition;
late Animation<double> verticalPosition;

@override
Widget build(BuildContext context) {
Expand Down Expand Up @@ -128,7 +128,7 @@ class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {

/// Display the preview from the camera (or a message if the preview is not available).
Widget _cameraPreviewWidget() {
if (controller == null || !controller.value.isInitialized) {
if (controller == null || !controller!.value.isInitialized!) {
return const Text(
'No camera selected',
style: const TextStyle(
Expand All @@ -139,8 +139,8 @@ class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
);
} else {
return new AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: new QRReaderPreview(controller),
aspectRatio: controller!.value.aspectRatio,
child: new QRReaderPreview(controller!),
);
}
}
Expand All @@ -149,39 +149,39 @@ class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
showInSnackBar(value.toString());
// ... do something
// wait 5 seconds then start scanning again.
new Future.delayed(const Duration(seconds: 5), controller.startScanning);
new Future.delayed(const Duration(seconds: 5), controller!.startScanning);
}

void onNewCameraSelected(CameraDescription cameraDescription) async {
if (controller != null) {
await controller.dispose();
await controller!.dispose();
}
controller = new QRReaderController(cameraDescription, ResolutionPreset.low,
[CodeFormat.qr, CodeFormat.pdf417], onCodeRead);

// If the controller is updated then update the UI.
controller.addListener(() {
controller!.addListener(() {
if (mounted) setState(() {});
if (controller.value.hasError) {
showInSnackBar('Camera error ${controller.value.errorDescription}');
if (controller!.value.hasError) {
showInSnackBar('Camera error ${controller!.value.errorDescription}');
}
});

try {
await controller.initialize();
await controller!.initialize();
} on QRReaderException catch (e) {
logError(e.code, e.description);
showInSnackBar('Error: ${e.code}\n${e.description}');
}

if (mounted) {
setState(() {});
controller.startScanning();
controller!.startScanning();
}
}

void showInSnackBar(String message) {
_scaffoldKey.currentState
.showSnackBar(new SnackBar(content: new Text(message)));
ScaffoldMessenger.maybeOf(_scaffoldKey.currentContext!)
?.showSnackBar(SnackBar(content: new Text(message)));
}
}
2 changes: 1 addition & 1 deletion example/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: fast_qr_reader_view_example
description: Demonstrates how to use the fast_qr_reader_view plugin.

environment:
sdk: '>=2.10.0 <3.0.0'
sdk: '>=2.12.0 <3.0.0'


dependencies:
Expand Down
76 changes: 38 additions & 38 deletions lib/fast_qr_reader_view.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,10 @@ String serializeResolutionPreset(ResolutionPreset resolutionPreset) {
case ResolutionPreset.low:
return 'low';
}
throw new ArgumentError('Unknown ResolutionPreset value');
}

List<String> serializeCodeFormatsList(List<CodeFormat> formats) {
List<String> list = [];
List<String?> serializeCodeFormatsList(List<CodeFormat> formats) {
List<String?> list = [];

for (var i = 0; i < formats.length; i++) {
if (_availableFormats[formats[i]] != null) {
Expand All @@ -53,7 +52,7 @@ List<String> serializeCodeFormatsList(List<CodeFormat> formats) {
return list;
}

CameraLensDirection _parseCameraLensDirection(String string) {
CameraLensDirection _parseCameraLensDirection(String? string) {
switch (string) {
case 'front':
return CameraLensDirection.front;
Expand All @@ -71,7 +70,7 @@ CameraLensDirection _parseCameraLensDirection(String string) {
Future<List<CameraDescription>> availableCameras() async {
try {
await _channel.invokeMethod('init');
final List<dynamic> cameras = await _channel.invokeMethod('availableCameras');
final List<dynamic> cameras = await (_channel.invokeMethod('availableCameras'));
return cameras.map((dynamic camera) {
return new CameraDescription(
name: camera['name'],
Expand All @@ -90,11 +89,11 @@ Future<List<CameraDescription>> availableCameras() async {
Future<PermissionStatus> checkCameraPermission() async {
try {
print("checkCameraPermission()");
var permission = await _channel.invokeMethod('checkPermission') as String;
var permission = await _channel.invokeMethod('checkPermission') as String?;
print("Permission: $permission");
return _getPermissionStatus(permission);
} on PlatformException catch (e) {
print("Error while permissions");
print("Error while permissions: $e");
return Future.value(PermissionStatus.unknown);
}
}
Expand All @@ -116,6 +115,7 @@ Future<PermissionStatus> requestCameraPermission() async {
return PermissionStatus.unknown;
}
} on PlatformException catch (e) {
print("Error while permissions: $e");
return Future.value(PermissionStatus.unknown);
}
}
Expand All @@ -124,7 +124,7 @@ Future<PermissionStatus> requestCameraPermission() async {
///
/// Given a [String] status from the method channel, it returns a
/// [PermissionStatus]
PermissionStatus _getPermissionStatus(String status) {
PermissionStatus _getPermissionStatus(String? status) {
switch (status) {
case "denied":
return PermissionStatus.denied;
Expand Down Expand Up @@ -172,8 +172,8 @@ enum PermissionStatus {
}

class CameraDescription {
final String name;
final CameraLensDirection lensDirection;
final String? name;
final CameraLensDirection? lensDirection;

CameraDescription({this.name, this.lensDirection});

Expand All @@ -196,7 +196,7 @@ class CameraDescription {
/// This is thrown when the plugin reports an error.
class QRReaderException implements Exception {
String code;
String description;
String? description;

QRReaderException(this.code, this.description);

Expand All @@ -212,24 +212,24 @@ class QRReaderPreview extends StatelessWidget {

@override
Widget build(BuildContext context) {
return controller.value.isInitialized ? new Texture(textureId: controller._textureId) : new Container();
return controller.value.isInitialized! ? new Texture(textureId: controller._textureId!) : new Container();
}
}

/// The state of a [QRReaderController].
class QRReaderValue {
/// True after [QRReaderController.initialize] has completed successfully.
final bool isInitialized;
final bool? isInitialized;

/// True when the camera is scanning.
final bool isScanning;
final bool? isScanning;

final String errorDescription;
final String? errorDescription;

/// The size of the preview in pixels.
///
/// Is `null` until [isInitialized] is `true`.
final Size previewSize;
final Size? previewSize;

const QRReaderValue({
this.isInitialized,
Expand All @@ -247,15 +247,15 @@ class QRReaderValue {
/// Convenience getter for `previewSize.height / previewSize.width`.
///
/// Can only be called when [initialize] is done.
double get aspectRatio => previewSize.height / previewSize.width;
double get aspectRatio => previewSize!.height / previewSize!.width;

bool get hasError => errorDescription != null;

QRReaderValue copyWith({
bool isInitialized,
bool isScanning,
String errorDescription,
Size previewSize,
bool? isInitialized,
bool? isScanning,
String? errorDescription,
Size? previewSize,
}) {
return new QRReaderValue(
isInitialized: isInitialized ?? this.isInitialized,
Expand Down Expand Up @@ -288,10 +288,10 @@ class QRReaderController extends ValueNotifier<QRReaderValue> {
final Function onCodeRead;
final List<CodeFormat> codeFormats;

int _textureId;
int? _textureId;
bool _isDisposed = false;
StreamSubscription<dynamic> _eventSubscription;
Completer<Null> _creatingCompleter;
StreamSubscription<dynamic>? _eventSubscription;
Completer<Null>? _creatingCompleter;

QRReaderController(this.description, this.resolutionPreset, this.codeFormats, this.onCodeRead)
: super(const QRReaderValue.uninitialized());
Expand All @@ -306,14 +306,14 @@ class QRReaderController extends ValueNotifier<QRReaderValue> {
try {
_channel.setMethodCallHandler(_handleMethod);
_creatingCompleter = new Completer<Null>();
final Map<dynamic, dynamic> reply = await _channel.invokeMethod(
final Map<dynamic, dynamic> reply = await (_channel.invokeMethod(
'initialize',
<String, dynamic>{
'cameraName': description.name,
'resolutionPreset': serializeResolutionPreset(resolutionPreset),
'codeFormats': serializeCodeFormatsList(codeFormats),
},
);
));
_textureId = reply['textureId'];
value = value.copyWith(
isInitialized: true,
Expand All @@ -327,20 +327,20 @@ class QRReaderController extends ValueNotifier<QRReaderValue> {
}
_eventSubscription =
new EventChannel('fast_qr_reader_view/cameraEvents$_textureId').receiveBroadcastStream().listen(_listener);
_creatingCompleter.complete(null);
return _creatingCompleter.future;
_creatingCompleter!.complete(null);
return _creatingCompleter!.future;
}

/// Listen to events from the native plugins.
///
/// A "cameraClosing" event is sent when the camera is closed automatically by the system (for example when the app go to background). The plugin will try to reopen the camera automatically but any ongoing recording will end.
void _listener(dynamic event) {
final Map<dynamic, dynamic> map = event;
final Map<dynamic, dynamic>? map = event;
if (_isDisposed) {
return;
}

switch (map['eventType']) {
switch (map!['eventType']) {
case 'error':
value = value.copyWith(errorDescription: event['errorDescription']);
break;
Expand All @@ -367,13 +367,13 @@ class QRReaderController extends ValueNotifier<QRReaderValue> {
///
/// Throws a [QRReaderException] if the capture fails.
Future<Null> startScanning() async {
if (!value.isInitialized || _isDisposed) {
if (!value.isInitialized! || _isDisposed) {
throw new QRReaderException(
'Uninitialized QRReaderController',
'startScanning was called on uninitialized QRReaderController',
);
}
if (value.isScanning) {
if (value.isScanning!) {
throw new QRReaderException(
'A scan has already started.',
'startScanning was called when a recording is already started.',
Expand All @@ -392,13 +392,13 @@ class QRReaderController extends ValueNotifier<QRReaderValue> {

/// Stop scanning.
Future<Null> stopScanning() async {
if (!value.isInitialized || _isDisposed) {
if (!value.isInitialized! || _isDisposed) {
throw new QRReaderException(
'Uninitialized QRReaderController',
'stopScanning was called on uninitialized QRReaderController',
);
}
if (!value.isScanning) {
if (!value.isScanning!) {
throw new QRReaderException(
'No scanning is happening',
'stopScanning was called when the scanner was not scanning.',
Expand Down Expand Up @@ -426,7 +426,7 @@ class QRReaderController extends ValueNotifier<QRReaderValue> {
if (_creatingCompleter == null) {
return new Future<Null>.value(null);
} else {
return _creatingCompleter.future.then((_) async {
return _creatingCompleter!.future.then((_) async {
await _channel.invokeMethod(
'dispose',
<String, dynamic>{'textureId': _textureId},
Expand All @@ -439,7 +439,7 @@ class QRReaderController extends ValueNotifier<QRReaderValue> {
Future<dynamic> _handleMethod(MethodCall call) async {
switch (call.method) {
case "updateCode":
if (value.isScanning) {
if (value.isScanning!) {
onCodeRead(call.arguments);
value = value.copyWith(isScanning: false);
}
Expand All @@ -448,8 +448,8 @@ class QRReaderController extends ValueNotifier<QRReaderValue> {
}

class FastQrReaderView {
static Future<String> get platformVersion async {
final String version = await _channel.invokeMethod('getPlatformVersion');
static Future<String?> get platformVersion async {
final String? version = await _channel.invokeMethod('getPlatformVersion');
return version;
}
}
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ dependencies:
sdk: flutter

environment:
sdk: '>=2.1.0 <3.0.0'
sdk: '>=2.12.0 <3.0.0'
flutter: '>=1.12.0'

# For information on the generic Dart part of this file, see the
Expand Down

0 comments on commit 5b2023d

Please sign in to comment.