You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.8KB

  1. import 'dart:io' show Platform;
  2. import 'package:barcode_scan/barcode_scan.dart';
  3. import 'package:farm_tpf/presentation/custom_widgets/widget_toast.dart';
  4. import 'package:farm_tpf/presentation/screens/home/home.dart';
  5. import 'package:flutter/material.dart';
  6. import 'package:flutter/services.dart';
  7. import 'package:fluttertoast/fluttertoast.dart';
  8. class ScanBarcodeScreen extends StatefulWidget {
  9. @override
  10. _ScanBarcodeScreenState createState() => _ScanBarcodeScreenState();
  11. }
  12. class _ScanBarcodeScreenState extends State<ScanBarcodeScreen> {
  13. ScanResult scanResult;
  14. var _aspectTolerance = 0.00;
  15. var _selectedCamera = -1;
  16. var _useAutoFocus = true;
  17. var _autoEnableFlash = false;
  18. final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  19. FlutterToast flutterToast;
  20. @override
  21. // ignore: type_annotate_public_apis
  22. initState() {
  23. super.initState();
  24. flutterToast = FlutterToast(context);
  25. scan();
  26. }
  27. @override
  28. Widget build(BuildContext context) {
  29. return Scaffold(
  30. key: _scaffoldKey,
  31. appBar: AppBar(
  32. title: Text("Quét mã QR"),
  33. ),
  34. body: Center(
  35. child: scanResult == null ? Container() : Text(scanResult?.rawContent),
  36. ),
  37. );
  38. }
  39. Future scan() async {
  40. try {
  41. var options = ScanOptions(
  42. strings: {
  43. "cancel": "Huỷ",
  44. "flash_on": "Bật flash",
  45. "flash_off": "Tắt flash",
  46. },
  47. useCamera: _selectedCamera,
  48. autoEnableFlash: _autoEnableFlash,
  49. android: AndroidOptions(
  50. aspectTolerance: _aspectTolerance,
  51. useAutoFocus: _useAutoFocus,
  52. ),
  53. );
  54. var result = await BarcodeScanner.scan(options: options);
  55. setState(() {
  56. scanResult = result;
  57. if (1 != 1) {
  58. Navigator.of(context).pop();
  59. Navigator.of(context)
  60. .push(MaterialPageRoute(builder: (_) => HomePage()));
  61. } else {
  62. flutterToast.showToast(
  63. child:
  64. WidgetToast(message: "Mã QR không đúng", color: Colors.red));
  65. Navigator.of(context).pop();
  66. }
  67. });
  68. } on PlatformException catch (e) {
  69. var result = ScanResult(
  70. type: ResultType.Error,
  71. format: BarcodeFormat.unknown,
  72. );
  73. if (e.code == BarcodeScanner.cameraAccessDenied) {
  74. setState(() {
  75. result.rawContent = 'Vui lòng cấp quyền truy cập camera';
  76. });
  77. } else {
  78. result.rawContent = 'Vui lòng cấp quyền truy cập camera.';
  79. }
  80. setState(() {
  81. scanResult = result;
  82. });
  83. flutterToast.showToast(
  84. child: WidgetToast(
  85. message: "Vui lòng cấp quyền truy cập camera.",
  86. color: Colors.red));
  87. Navigator.of(context).pop();
  88. }
  89. }
  90. }