updates to qr scanner view

This commit is contained in:
Adam Velebil 2022-03-31 16:31:03 +02:00
parent db62e124ef
commit 6f6a4ef322
No known key found for this signature in database
GPG Key ID: AC6D6B9D715FC084

View File

@ -4,18 +4,23 @@ import 'package:mobile_scanner/mobile_scanner.dart';
import '../../app/navigation_service.dart'; import '../../app/navigation_service.dart';
import '../../oath/models.dart'; import '../../oath/models.dart';
/// Status of view state
enum _ScanStatus { looking, error, success }
class OverlayClipper extends CustomClipper<Path> { class OverlayClipper extends CustomClipper<Path> {
/// helper method to calculate position of the rect
Rect _getOverlayRect(Size size, double width) => Rect.fromCenter(
center: Offset(size.width / 2, size.height / 2),
width: width,
height: width);
@override @override
Path getClip(Size size) { Path getClip(Size size) {
const r = 40.0; const r = 40.0;
var w = size.width - 40; var w = size.width - 40;
return Path() return Path()
..addRect(Rect.fromLTWH(0, 0, size.width, size.height)) ..addRect(Rect.fromLTWH(0, 0, size.width, size.height))
..addRRect(RRect.fromRectXY( ..addRRect(RRect.fromRectXY(_getOverlayRect(size, w), r, r))
Rect.fromPoints(
const Offset(32, 32), Offset(size.width - 32, 32 + w)),
r,
r))
..fillType = PathFillType.evenOdd; ..fillType = PathFillType.evenOdd;
} }
@ -26,49 +31,64 @@ class OverlayClipper extends CustomClipper<Path> {
class MobileScannerWrapper extends StatelessWidget { class MobileScannerWrapper extends StatelessWidget {
final MobileScannerController controller; final MobileScannerController controller;
final Function(Barcode barcode, MobileScannerArguments? args)? onDetect; final Function(Barcode barcode, MobileScannerArguments? args)? onDetect;
final Color frameColor; final _ScanStatus status;
const MobileScannerWrapper({ const MobileScannerWrapper({
Key? key, Key? key,
required this.controller, required this.controller,
required this.frameColor,
required this.onDetect, required this.onDetect,
required this.status,
}) : super(key: key); }) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
const radius = 40.0; var backgroundColor = status == _ScanStatus.looking
var dimension = MediaQuery.of(context).size.width - 64; ? Colors.white
: status == _ScanStatus.error
? Colors.red.shade900
: Colors.green.shade900;
var size = MediaQuery.of(context).size;
var positionRect = Rect.fromCenter(
center: Offset(size.width / 2, size.height / 2 - 51),
width: size.width - 38,
height: size.width - 38);
return Stack(children: [ return Stack(children: [
MobileScanner( MobileScanner(
controller: controller, controller: controller,
allowDuplicates: true,
onDetect: (barcode, args) { onDetect: (barcode, args) {
onDetect?.call(barcode, args); onDetect?.call(barcode, args);
}), }),
ClipPath( ClipPath(
clipper: OverlayClipper(), clipper: OverlayClipper(),
child: Opacity( child: Opacity(
opacity: 0.5, opacity: 0.3,
child: ColoredBox( child: ColoredBox(
color: Colors.white, color: backgroundColor,
child: Column( child: Column(
mainAxisSize: MainAxisSize.max, mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: const [Spacer()], children: const [Spacer()],
)))), )))),
Positioned.fromRect( if (status == _ScanStatus.success)
rect: Rect.fromPoints( Positioned.fromRect(
const Offset(32, 32), Offset(dimension + 32, 60 + dimension)), rect: positionRect,
child: DecoratedBox( child: Icon(
child: SizedBox( Icons.check_circle,
width: dimension, size: 200,
height: dimension, color: Colors.green.shade400,
), )),
decoration: BoxDecoration( if (status == _ScanStatus.error)
border: Border.all(color: frameColor, width: 5), Positioned.fromRect(
borderRadius: rect: positionRect,
const BorderRadius.all(Radius.circular(radius))))) child: Icon(
Icons.error,
size: 200,
color: Colors.red.shade400,
)),
]); ]);
} }
} }
@ -82,32 +102,61 @@ class QrScannerView extends StatefulWidget {
class _QrScannerViewState extends State<QrScannerView> { class _QrScannerViewState extends State<QrScannerView> {
String? _scannedString; String? _scannedString;
// will be used later
// ignore: unused_field
CredentialData? _credentialData; CredentialData? _credentialData;
String? _scanningError; _ScanStatus _status = _ScanStatus.looking;
Color _frameColor = Colors.grey;
final MobileScannerController _controller = final MobileScannerController _controller =
MobileScannerController(facing: CameraFacing.back, torchEnabled: false); MobileScannerController(facing: CameraFacing.back, torchEnabled: false);
void handleResult(String? code) { void setError() {
_credentialData = null;
_scannedString = null;
_status = _ScanStatus.error;
Future.delayed(const Duration(milliseconds: 2000), () {
resetError();
});
}
void resetError() {
setState(() {
_credentialData = null;
_scannedString = null;
_status = _ScanStatus.looking;
});
}
void handleResult(String? code, MobileScannerArguments? args) {
if (_status != _ScanStatus.looking) {
// on success and error ignore reported codes
return;
}
setState(() { setState(() {
if (code != null) { if (code != null) {
try { try {
var parsedCredential = CredentialData.fromUri(Uri.parse(code)); var parsedCredential = CredentialData.fromUri(Uri.parse(code));
_frameColor = Colors.green;
_credentialData = parsedCredential; _credentialData = parsedCredential;
_scanningError = null;
_scannedString = code; _scannedString = code;
_status = _ScanStatus.success;
Future.delayed(const Duration(milliseconds: 800), () {
BuildContext dialogContext =
NavigationService.navigatorKey.currentContext!;
if (Navigator.of(dialogContext).canPop()) {
// prevent several callbacks
Navigator.of(dialogContext).pop(_scannedString);
}
});
} on ArgumentError catch (_) { } on ArgumentError catch (_) {
_frameColor = Colors.red; setError();
_credentialData = null; } catch (e) {
_scanningError = 'Invalid code'; setError();
_scannedString = null;
} }
} else { } else {
_frameColor = Colors.red; setError();
_credentialData = null;
_scanningError = 'Invalid code';
_scannedString = null;
} }
}); });
} }
@ -119,7 +168,6 @@ class _QrScannerViewState extends State<QrScannerView> {
child: Scaffold( child: Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Scan QR code'), title: const Text('Scan QR code'),
//actions: actions,
leading: BackButton( leading: BackButton(
onPressed: () { onPressed: () {
Navigator.of(context).pop(); Navigator.of(context).pop();
@ -129,150 +177,53 @@ class _QrScannerViewState extends State<QrScannerView> {
body: Stack(children: [ body: Stack(children: [
MobileScannerWrapper( MobileScannerWrapper(
controller: _controller, controller: _controller,
frameColor: _frameColor, status: _status,
onDetect: (barcode, _) => handleResult(barcode.rawValue), onDetect: (barcode, args) =>
handleResult(barcode.rawValue, args),
), ),
Padding( Padding(
padding: padding:
const EdgeInsets.symmetric(vertical: 32, horizontal: 32), const EdgeInsets.symmetric(vertical: 32, horizontal: 32),
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max, mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
const SizedBox( Column(children: [
height: 32, const SizedBox(
), height: 32,
if (_credentialData == null && _scanningError == null) ),
Card( if (_status == _ScanStatus.looking)
elevation: 10, Text('Looking for a code...',
child: Padding( style: Theme.of(context)
padding: const EdgeInsets.all(16), .textTheme
child: Column( .headline6
mainAxisSize: MainAxisSize.max, ?.copyWith(color: Colors.black)),
// mainAxisAlignment: MainAxisAlignment.start, if (_status == _ScanStatus.success)
crossAxisAlignment: CrossAxisAlignment.center, Text('Found a valid code',
children: [ style: Theme.of(context)
Text('Scan QR code', .textTheme
style: Theme.of(context) .headline6
.textTheme ?.copyWith(color: Colors.white)),
.headline5), if (_status == _ScanStatus.error)
const SizedBox(height: 16), Text('This code is not valid, try again.',
Text('or', style: Theme.of(context)
style: Theme.of(context) .textTheme
.textTheme .headline6
.bodyLarge), ?.copyWith(color: Colors.white)),
const SizedBox(height: 16), ]),
Row( Row(
mainAxisAlignment: mainAxisAlignment: MainAxisAlignment.spaceEvenly,
MainAxisAlignment.spaceEvenly, children: [
children: [ MaterialButton(
OutlinedButton( color: Colors.white38,
onPressed: () { onPressed: () {
Navigator.of(dialogContext).pop(''); Navigator.of(dialogContext).pop('');
}, },
child: const Text('Add manually'), child: const Text('Add manually'),
), )
], ],
) )
],
))),
if (_credentialData != null)
Card(
elevation: 10,
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Successfully scanned',
style: Theme.of(context)
.textTheme
.headline5),
const SizedBox(
height: 16,
),
Text('Name',
style: Theme.of(context)
.textTheme
.bodySmall),
Text(_credentialData?.name ?? '',
style: Theme.of(context)
.textTheme
.headline6),
if (_credentialData?.issuer != null)
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
const SizedBox(
height: 16,
),
Text('Issuer',
style: Theme.of(context)
.textTheme
.bodySmall),
Text(_credentialData?.issuer ?? '',
style: Theme.of(context)
.textTheme
.headline6),
const SizedBox(
height: 32,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ElevatedButton(
onPressed: () {
if (Navigator.of(dialogContext)
.canPop()) {
// prevent several callbacks
Navigator.of(dialogContext)
.pop(_scannedString);
}
},
child: const Text('Add this'),
)
],
)
],
))),
if (_scanningError != null)
Card(
elevation: 10,
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text('Scan failed, try again',
style: Theme.of(context)
.textTheme
.headline5),
const SizedBox(height: 16),
Text('or',
style: Theme.of(context)
.textTheme
.bodyLarge),
const SizedBox(height: 16),
Row(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: [
OutlinedButton(
onPressed: () {
Navigator.of(dialogContext).pop('');
},
child: const Text('Add manually'),
),
],
)
],
))),
], ],
)), )),
]))); ])));