Created
December 17, 2021 20:52
-
-
Save giuliano-macedo/68d687dca88fc3b1df07e549eac6c54e to your computer and use it in GitHub Desktop.
QrCode/Barcode scanner using qr_code_scanner in flutter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:io'; | |
import 'package:flutter/foundation.dart'; | |
import 'package:flutter/material.dart'; | |
import 'package:qr_code_scanner/qr_code_scanner.dart'; | |
class ScannerWidget extends StatefulWidget { | |
final BarcodeFormat format; | |
final void Function(String?) onScan; | |
ScannerWidget({ | |
Key? key, | |
required this.format, | |
required this.onScan, | |
}) : super(key: key); | |
@override | |
_ScannerWidgetState createState() => _ScannerWidgetState(); | |
static Future<String?> show({ | |
required BuildContext context, | |
required BarcodeFormat format, | |
}) async => | |
await Navigator.of(context).push( | |
MaterialPageRoute( | |
builder: (ctx) => ScannerWidget( | |
format: format, | |
onScan: (scan) => Navigator.of(ctx).pop(scan), | |
), | |
), | |
); | |
} | |
class _ScannerWidgetState extends State<ScannerWidget> { | |
final GlobalKey qrKey = GlobalKey(debugLabel: 'QR'); | |
QRViewController? controller; | |
// In order to get hot reload to work we need to pause the camera if the platform | |
// is android, or resume the camera if the platform is iOS. | |
@override | |
void reassemble() { | |
super.reassemble(); | |
if (Platform.isAndroid) { | |
controller!.pauseCamera(); | |
} else if (Platform.isIOS) { | |
controller!.resumeCamera(); | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Column( | |
children: <Widget>[ | |
Expanded( | |
flex: 5, | |
child: QRView( | |
key: qrKey, | |
onQRViewCreated: _onQRViewCreated, | |
), | |
), | |
Expanded( | |
flex: 1, | |
child: Center( | |
child: ElevatedButton( | |
child: Text("Cancelar"), | |
style: ElevatedButton.styleFrom( | |
primary: Colors.red, | |
onPrimary: Colors.white, | |
), | |
onPressed: () => widget.onScan(null), | |
), | |
), | |
) | |
], | |
), | |
); | |
} | |
void _onQRViewCreated(QRViewController controller) { | |
this.controller = controller; | |
controller.scannedDataStream | |
.firstWhere((scanData) => scanData.format == widget.format) | |
.then((scanData) => widget.onScan(scanData.code)); | |
; | |
} | |
@override | |
void dispose() { | |
controller?.dispose(); | |
super.dispose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment