Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Barcode type detection #256

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@
pubspec.lock

build/
*/.idea/caches/
*/.idea/caches/
example/ios/Flutter/flutter_export_environment.sh
Binary file removed android/.idea/caches/build_file_checksums.ser
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.amolg.flutterbarcodescanner;

import java.util.HashMap;
import com.google.android.gms.vision.barcode.Barcode;

public class BarcodeTypes {
HashMap<Integer, String> typesMap = new HashMap<Integer, String>();

BarcodeTypes(){
typesMap.put(Barcode.AZTEC,"AZTEC");
typesMap.put(Barcode.CODE_128,"CODE_128");
typesMap.put(Barcode.CODE_39,"CODE_39");
typesMap.put(Barcode.CODE_93,"CODE_93");
typesMap.put(Barcode.CODABAR,"CODABAR");
typesMap.put(Barcode.DATA_MATRIX,"DATA_MATRIX");
typesMap.put(Barcode.EAN_13,"EAN_13");
typesMap.put(Barcode.EAN_8,"EAN_8");
typesMap.put(Barcode.ITF,"ITF");
typesMap.put(Barcode.QR_CODE,"QR_CODE");
typesMap.put(Barcode.UPC_A,"UPC_A");
typesMap.put(Barcode.UPC_E,"UPC_E");
typesMap.put(Barcode.PDF417,"PDF417");
}

public String getFormat(int format) {
if(typesMap.containsKey(format)) {
return typesMap.get(format);
}else{
return new String("UNKNOWN");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import com.google.android.gms.vision.barcode.Barcode;

import java.util.Map;
import java.util.HashMap;

import io.flutter.embedding.android.FlutterActivity;

Expand Down Expand Up @@ -150,20 +151,28 @@ public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == CommonStatusCodes.SUCCESS) {
if (data != null) {
try {
BarcodeTypes formats = new BarcodeTypes();
Barcode barcode = data.getParcelableExtra(BarcodeCaptureActivity.BarcodeObject);
String barcodeResult = barcode.rawValue;
pendingResult.success(barcodeResult);
// String barcodeResult = barcode.rawValue;
Log.i(TAG, "code format " + barcode.format);
HashMap<String, String> result = new HashMap<String, String>();
result.put("data",barcode.rawValue);
result.put("format", formats.getFormat(barcode.format));
pendingResult.success(result);
} catch (Exception e) {
pendingResult.success("-1");
// pendingResult.success("-1");
pendingResult.error("error",e.toString(),e);
}
} else {
pendingResult.success("-1");
// pendingResult.success("-1");
pendingResult.error("error","No data available",null);
}
pendingResult = null;
arguments = null;
return true;
} else {
pendingResult.success("-1");
// pendingResult.success("-1");
pendingResult.error("error","resultCode "+resultCode,null);
}
}
return false;
Expand Down
4 changes: 2 additions & 2 deletions example/ios/Podfile.lock
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
PODS:
- Flutter (1.0.0)
- flutter_barcode_scanner (1.1.0):
- flutter_barcode_scanner (2.0.0):
- Flutter

DEPENDENCIES:
Expand All @@ -15,7 +15,7 @@ EXTERNAL SOURCES:

SPEC CHECKSUMS:
Flutter: 434fef37c0980e73bb6479ef766c45957d4b510c
flutter_barcode_scanner: cd6b739f16ff1696ba9e304904f2411ba97d303c
flutter_barcode_scanner: 7a1144744c28dc0c57a8de7218ffe5ec59a9e4bf

PODFILE CHECKSUM: aafe91acc616949ddb318b77800a7f51bffa2a4c

Expand Down
20 changes: 10 additions & 10 deletions example/ios/Runner.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@
TargetAttributes = {
97C146ED1CF9000F007C117D = {
CreatedOnToolsVersion = 7.3.1;
DevelopmentTeam = F75RB9Z89T;
DevelopmentTeam = TR98873U46;
LastSwiftMigration = 1020;
ProvisioningStyle = Automatic;
};
Expand Down Expand Up @@ -352,7 +352,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
IPHONEOS_DEPLOYMENT_TARGET = 10.2;
MTL_ENABLE_DEBUG_INFO = NO;
ONLY_ACTIVE_ARCH = NO;
SDKROOT = iphoneos;
Expand All @@ -370,15 +370,15 @@
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = F75RB9Z89T;
DEVELOPMENT_TEAM = TR98873U46;
EMBED_ASSET_PACKS_IN_PRODUCT_BUNDLE = YES;
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
INFOPLIST_FILE = Runner/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
IPHONEOS_DEPLOYMENT_TARGET = 10.2;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
Expand Down Expand Up @@ -441,7 +441,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
IPHONEOS_DEPLOYMENT_TARGET = 10.2;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
Expand Down Expand Up @@ -493,7 +493,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
IPHONEOS_DEPLOYMENT_TARGET = 10.2;
MTL_ENABLE_DEBUG_INFO = NO;
ONLY_ACTIVE_ARCH = NO;
SDKROOT = iphoneos;
Expand All @@ -513,15 +513,15 @@
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = F75RB9Z89T;
DEVELOPMENT_TEAM = TR98873U46;
EMBED_ASSET_PACKS_IN_PRODUCT_BUNDLE = YES;
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
INFOPLIST_FILE = Runner/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
IPHONEOS_DEPLOYMENT_TARGET = 10.2;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
Expand All @@ -546,15 +546,15 @@
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = F75RB9Z89T;
DEVELOPMENT_TEAM = TR98873U46;
EMBED_ASSET_PACKS_IN_PRODUCT_BUNDLE = YES;
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
INFOPLIST_FILE = Runner/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
IPHONEOS_DEPLOYMENT_TARGET = 10.2;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
Expand Down
47 changes: 17 additions & 30 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,18 @@ class _MyAppState extends State<MyApp> {
}

Future<void> startBarcodeScanStream() async {
FlutterBarcodeScanner.getBarcodeStreamReceiver(
'#ff6666', 'Cancel', true, ScanMode.BARCODE)!
FlutterBarcodeScanner.getBarcodeStreamReceiver('#ff6666', 'Cancel', true, ScanMode.BARCODE)!
.listen((barcode) => print(barcode));
}

Future<void> scanQR() async {
String barcodeScanRes;
Map barcodeScanRes;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
'#ff6666', 'Cancel', true, ScanMode.QR);
print(barcodeScanRes);
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode('#ff6666', 'Cancel', true, ScanMode.QR);
print('**** Result:' + barcodeScanRes.toString());
} on PlatformException {
barcodeScanRes = 'Failed to get platform version.';
barcodeScanRes = {'error': 'Failed to scan code'};
}

// If the widget was removed from the tree while the asynchronous platform
Expand All @@ -42,20 +40,19 @@ class _MyAppState extends State<MyApp> {
if (!mounted) return;

setState(() {
_scanBarcode = barcodeScanRes;
_scanBarcode = barcodeScanRes.toString();
});
}

// Platform messages are asynchronous, so we initialize in an async method.
Future<void> scanBarcodeNormal() async {
String barcodeScanRes;
Map barcodeScanRes;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
'#ff6666', 'Cancel', true, ScanMode.BARCODE);
print(barcodeScanRes);
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode('#ff6666', 'Cancel', true, ScanMode.BARCODE);
print('**** Result:' + barcodeScanRes.toString());
} on PlatformException {
barcodeScanRes = 'Failed to get platform version.';
barcodeScanRes = {'error': 'Failed to scan code'};
}

// If the widget was removed from the tree while the asynchronous platform
Expand All @@ -64,7 +61,7 @@ class _MyAppState extends State<MyApp> {
if (!mounted) return;

setState(() {
_scanBarcode = barcodeScanRes;
_scanBarcode = barcodeScanRes.toString();
});
}

Expand All @@ -76,22 +73,12 @@ class _MyAppState extends State<MyApp> {
body: Builder(builder: (BuildContext context) {
return Container(
alignment: Alignment.center,
child: Flex(
direction: Axis.vertical,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () => scanBarcodeNormal(),
child: Text('Start barcode scan')),
ElevatedButton(
onPressed: () => scanQR(),
child: Text('Start QR scan')),
ElevatedButton(
onPressed: () => startBarcodeScanStream(),
child: Text('Start barcode scan stream')),
Text('Scan result : $_scanBarcode\n',
style: TextStyle(fontSize: 20))
]));
child: Flex(direction: Axis.vertical, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
ElevatedButton(onPressed: () => scanBarcodeNormal(), child: Text('Start barcode scan')),
ElevatedButton(onPressed: () => scanQR(), child: Text('Start QR scan')),
ElevatedButton(onPressed: () => startBarcodeScanStream(), child: Text('Start barcode scan stream')),
Text('Scan result : $_scanBarcode\n', style: TextStyle(fontSize: 20))
]));
})));
}
}
31 changes: 26 additions & 5 deletions ios/Classes/SwiftFlutterBarcodeScannerPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public class SwiftFlutterBarcodeScannerPlugin: NSObject, FlutterPlugin, ScanBarc
}
}

public func userDidScanWith(barcode: String){
public func userDidScanWith(barcode: NSDictionary){
pendingResult(barcode)
}

Expand All @@ -142,7 +142,7 @@ public class SwiftFlutterBarcodeScannerPlugin: NSObject, FlutterPlugin, ScanBarc
}

protocol ScanBarcodeDelegate {
func userDidScanWith(barcode: String)
func userDidScanWith(barcode: NSDictionary)
}

class BarcodeScannerViewController: UIViewController {
Expand All @@ -159,6 +159,21 @@ class BarcodeScannerViewController: UIViewController {
AVMetadataObject.ObjectType.dataMatrix,
AVMetadataObject.ObjectType.interleaved2of5,
AVMetadataObject.ObjectType.qr]
private let formatsMap = [
AVMetadataObject.ObjectType.upce: "UPC_E",
AVMetadataObject.ObjectType.code39: "CODE_39",
AVMetadataObject.ObjectType.code39Mod43: "CODE39MOD43",
AVMetadataObject.ObjectType.code93: "CODE_93",
AVMetadataObject.ObjectType.code128: "CODE_128",
AVMetadataObject.ObjectType.ean8: "EAN_8",
AVMetadataObject.ObjectType.ean13: "EAN_13",
AVMetadataObject.ObjectType.aztec: "AZTEC",
AVMetadataObject.ObjectType.pdf417: "PDF417",
AVMetadataObject.ObjectType.itf14: "ITF14",
AVMetadataObject.ObjectType.dataMatrix: "DATA_MATRIX",
AVMetadataObject.ObjectType.interleaved2of5: "ITF",
AVMetadataObject.ObjectType.qr: "QR_CODE"
]
public var delegate: ScanBarcodeDelegate? = nil
private var captureSession = AVCaptureSession()
private var videoPreviewLayer: AVCaptureVideoPreviewLayer?
Expand Down Expand Up @@ -464,7 +479,8 @@ class BarcodeScannerViewController: UIViewController {
}else{
if self.delegate != nil {
self.dismiss(animated: true, completion: {
self.delegate?.userDidScanWith(barcode: "-1")
let result = ["error": "Canceled by user"];
self.delegate?.userDidScanWith(barcode: result as NSDictionary)
})
}
}
Expand Down Expand Up @@ -559,7 +575,7 @@ class BarcodeScannerViewController: UIViewController {
: UIApplication.shared.statusBarOrientation.isPortrait
}

private func launchApp(decodedURL: String) {
private func launchApp(decodedURL: NSDictionary) {
if presentedViewController != nil {
return
}
Expand Down Expand Up @@ -589,7 +605,12 @@ extension BarcodeScannerViewController: AVCaptureMetadataOutputObjectsDelegate {
if(SwiftFlutterBarcodeScannerPlugin.isContinuousScan){
SwiftFlutterBarcodeScannerPlugin.onBarcodeScanReceiver(barcode: metadataObj.stringValue!)
}else{
launchApp(decodedURL: metadataObj.stringValue!)
print("**** code format \(metadataObj.type) \(formatsMap[metadataObj.type] ?? "Unknown")")
let result = [
"data": metadataObj.stringValue!,
"format": formatsMap[metadataObj.type],
];
launchApp(decodedURL: result as NSDictionary)
}
}
}
Expand Down
17 changes: 7 additions & 10 deletions lib/flutter_barcode_scanner.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,9 @@ enum ScanMode { QR, BARCODE, DEFAULT }
/// This class is an interface between the native Android and iOS classes and a
/// Flutter project.
class FlutterBarcodeScanner {
static const MethodChannel _channel =
MethodChannel('flutter_barcode_scanner');
static const MethodChannel _channel = MethodChannel('flutter_barcode_scanner');

static const EventChannel _eventChannel =
EventChannel('flutter_barcode_scanner_receiver');
static const EventChannel _eventChannel = EventChannel('flutter_barcode_scanner_receiver');

static Stream? _onBarcodeReceiver;

Expand All @@ -23,8 +21,8 @@ class FlutterBarcodeScanner {
/// Shows a scan line with [lineColor] over a scan window. A flash icon is
/// displayed if [isShowFlashIcon] is true. The text of the cancel button can
/// be customized with the [cancelButtonText] string.
static Future<String> scanBarcode(String lineColor, String cancelButtonText,
bool isShowFlashIcon, ScanMode scanMode) async {
static Future<Map> scanBarcode(
String lineColor, String cancelButtonText, bool isShowFlashIcon, ScanMode scanMode) async {
if (cancelButtonText.isEmpty) {
cancelButtonText = 'Cancel';
}
Expand All @@ -39,8 +37,7 @@ class FlutterBarcodeScanner {
};

/// Get barcode scan result
final barcodeResult =
await _channel.invokeMethod('scanBarcode', params) ?? '';
final barcodeResult = await _channel.invokeMethod('scanBarcode', params) ?? '';
return barcodeResult;
}

Expand All @@ -51,8 +48,8 @@ class FlutterBarcodeScanner {
/// displayed if [isShowFlashIcon] is true. The text of the cancel button can
/// be customized with the [cancelButtonText] string. Returns a stream of
/// detected barcode strings.
static Stream? getBarcodeStreamReceiver(String lineColor,
String cancelButtonText, bool isShowFlashIcon, ScanMode scanMode) {
static Stream? getBarcodeStreamReceiver(
String lineColor, String cancelButtonText, bool isShowFlashIcon, ScanMode scanMode) {
if (cancelButtonText.isEmpty) {
cancelButtonText = 'Cancel';
}
Expand Down