commit f0805d1c72143712e62ec0859b2713fc46aa1633 Author: ayub Date: Sun Aug 10 13:37:17 2025 +0700 init diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..2393c04 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,24 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[BUG] " +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**Flutter information** +Always provide the output of `flutter doctor -v` as it is needed in order to know on which Flutter versions the bug exists in. + +**Device (please complete the following information):** + - Device: [e.g. iPhone6] + - OS: [e.g. iOS8.1] + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..864a505 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,17 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: "[FEATURE] " +labels: enhancement +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..7825473 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,20 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + reviewers: + - "juliansteenbakker" + - package-ecosystem: gradle + directory: "/android" + schedule: + interval: "weekly" + reviewers: + - "juliansteenbakker" + - package-ecosystem: gradle + directory: "/example/android" + schedule: + interval: "weekly" + reviewers: + - "juliansteenbakker" \ No newline at end of file diff --git a/.github/workflows/dart.yml b/.github/workflows/dart.yml new file mode 100644 index 0000000..78bf815 --- /dev/null +++ b/.github/workflows/dart.yml @@ -0,0 +1,24 @@ +name: dart + +on: [push, pull_request] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-java@v3 + with: + distribution: 'temurin' + java-version: '11' + - uses: subosito/flutter-action@v2.10.0 + - name: Version + run: flutter doctor -v + - name: Install dependencies + run: flutter pub get + - name: Format + run: dart format --set-exit-if-changed . + - name: Linter + run: flutter analyze diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..aef8b20 --- /dev/null +++ b/.gitignore @@ -0,0 +1,116 @@ +# Miscellaneous +*.class +*.lock +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +.last_build_id + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# Visual Studio Code related +.classpath +.project +.settings/ +.vscode/ + +# Flutter repo-specific +/bin/cache/ +/bin/mingit/ +/dev/benchmarks/mega_gallery/ +/dev/bots/.recipe_deps +/dev/bots/android_tools/ +/dev/docs/doc/ +/dev/docs/flutter.docs.zip +/dev/docs/lib/ +/dev/docs/pubspec.yaml +/dev/integration_tests/**/xcuserdata +/dev/integration_tests/**/Pods +/packages/flutter/coverage/ +version + +# packages file containing multi-root paths +.packages.generated + +# Flutter/Dart/Pub related +**/doc/api/ +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +build/ +flutter_*.png +linked_*.ds +unlinked.ds +unlinked_spec.ds + +# Android related +**/android/**/gradle-wrapper.jar +**/android/.gradle +**/android/captures/ +**/android/gradlew +**/android/gradlew.bat +**/android/local.properties +**/android/**/GeneratedPluginRegistrant.java +**/android/key.properties +*.jks + +# iOS/XCode related +**/ios/**/*.mode1v3 +**/ios/**/*.mode2v3 +**/ios/**/*.moved-aside +**/ios/**/*.pbxuser +**/ios/**/*.perspectivev3 +**/ios/**/*sync/ +**/ios/**/.sconsign.dblite +**/ios/**/.tags* +**/ios/**/.vagrant/ +**/ios/**/DerivedData/ +**/ios/**/Icon? +**/ios/**/Pods/ +**/ios/.symlinks/ +**/ios/**/.symlinks/ +**/ios/**/profile +**/ios/**/xcuserdata +**/ios/.generated/ +**/ios/Flutter/App.framework +**/ios/Flutter/Flutter.framework +**/ios/Flutter/Flutter.podspec +**/ios/Flutter/Generated.xcconfig +**/ios/Flutter/app.flx +**/ios/Flutter/app.zip +**/ios/Flutter/flutter_assets/ +**/ios/Flutter/flutter_export_environment.sh +**/ios/ServiceDefinitions.json +**/ios/Runner/GeneratedPluginRegistrant.* + +# macOS +**/macos/Flutter/GeneratedPluginRegistrant.swift +**/macos/Flutter/Flutter-Debug.xcconfig +**/macos/Flutter/Flutter-Release.xcconfig +**/macos/Flutter/Flutter-Profile.xcconfig + +# Coverage +coverage/ + +# Symbols +app.*.symbols + +# Exceptions to above rules. +!**/ios/**/default.mode1v3 +!**/ios/**/default.mode2v3 +!**/ios/**/default.pbxuser +!**/ios/**/default.perspectivev3 +!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages +!/dev/ci/**/Gemfile.lock \ No newline at end of file diff --git a/.resources/android-app-screen-one.jpg b/.resources/android-app-screen-one.jpg new file mode 100755 index 0000000..f0c3992 Binary files /dev/null and b/.resources/android-app-screen-one.jpg differ diff --git a/.resources/android-app-screen-two.jpg b/.resources/android-app-screen-two.jpg new file mode 100755 index 0000000..aa2cde0 Binary files /dev/null and b/.resources/android-app-screen-two.jpg differ diff --git a/.resources/called-multiple-times-debug01.png b/.resources/called-multiple-times-debug01.png new file mode 100644 index 0000000..759f19a Binary files /dev/null and b/.resources/called-multiple-times-debug01.png differ diff --git a/.resources/called-multiple-times-debug02.png b/.resources/called-multiple-times-debug02.png new file mode 100644 index 0000000..997cb93 Binary files /dev/null and b/.resources/called-multiple-times-debug02.png differ diff --git a/.resources/ios-app-screen-one.png b/.resources/ios-app-screen-one.png new file mode 100644 index 0000000..b53fbe3 Binary files /dev/null and b/.resources/ios-app-screen-one.png differ diff --git a/.resources/ios-app-screen-two.png b/.resources/ios-app-screen-two.png new file mode 100644 index 0000000..b6d0a93 Binary files /dev/null and b/.resources/ios-app-screen-two.png differ diff --git a/.resources/sample_qr_code.png b/.resources/sample_qr_code.png new file mode 100644 index 0000000..45892b8 Binary files /dev/null and b/.resources/sample_qr_code.png differ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..6f91f3c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,165 @@ +## 1.0.0 +Breaking changes: +Minimum Flutter version is now Flutter 3.0.0 (Dart 2.17.0). + +#### Features +* Inverted is now mixed with normal scanning. +* onPermissionSet now works on web aswell. +* [Android] zxing core is updated to 3.5.0. +* [Android] Several code improvements. +* [Android] Several dependencies updated. + +## 0.7.0 +#### Features +* Add inverted feature for Android. See https://github.com/juliuscanute/qr_code_scanner/issues/403 + +#### Bugfixes +* Fixed permission error on devices running Android 7 or lower. +* Fixed error being thrown when user declines permission on iOS. +* Updated dependencies + +## 0.6.1 +* Fix bug which caused build to fail for iOS. (#452) + +## 0.6.0 +#### Features +* Add support for raw bytes on iOS. (#421) +* Add custom cutout width and height next to cutout size. (#432) + +#### Bugfixes +* Fix for calling permission multiple times. (#381) +* Fix for QRView Overlay cutoutbottomoffset. (#383) +* Multiple minor improvements + +## 0.5.2 +#### Bugfixes +* Increased delay to fix QRView opening zoomed in on some devices by adding small delay to updateDimensions(). (#250) +* Updated ZXING from 3.3.0 to 3.4.1 (#369) +* Fixed permission not being called correctly on Android (#351) + +## 0.5.1 +Removed web from library export. + +## 0.5.0 +* Added initial web-support. This function is still under development and not fully tested. +* Fixed permissions on iOS. +* Updated dependencies. + +## 0.4.0 +Stable null-safety support. (#278) + +## 0.3.5 +#### Bug fixes +* Fixed QRView opening zoomed in on some devices by adding small delay to updateDimensions(). (#250) +* Changed upc-A to EAN13 on iOS. (#262) +* Fixed null-pointer on BarcodeFormat array on iOS. (#262) +* Added LifecycleEventHandler to dispose(). (#265) + +## 0.3.4 +#### Bug fixes +* Fixed No barcode view found on Android when calling controller.dispose() (#257) +* Fixed Hot reload not working on Android. + +## 0.3.3 +#### Bug fixes +* Fixed updateDimensions not being called causing zoom on iOS. (#250) +* Fixed Android permission callback not working. (#251) (#252) +* Fixed null-pointers after declining permission on Android. + +## 0.3.2 +#### Bug fixes +* Fixed null-pointer when no overlay provided on iOS. (#245) +* Fixed camera not stopping (green dot on iOS 14) when navigating to other page. (#240) + +## 0.3.1 +#### Bug fixes +* Fixed permission callback on iOS & Android. +* Fixed camera facing not working on Android. +* Fixed scanArea not being honored on Android. +* Updated ShapeBorder to QrScannerOverlayShape. + +## 0.3.0 +#### Breaking change +Its not necessary anymore to wrap the QRView in a SizeChangedLayoutNotifier because this is handled inside the plugin. +#### New Features +* Added possibility to set allowed barcodes. (#135) +* Added possibility to check what features are supported by device. (hasFlash, hasBackCamera, hasFrontCamera) (#135) +* Added possibility to check if flash is on. (#135) +* Added possibility to check which camera is active. (#135) +* All functions are now async so you can await them. (#135) + +See the updated example on how to implement these features. +#### Bug fixes +* Fixed permission handling in Android. +* Native functions now returns results so exceptions can be thrown when an error occurs. + +## 0.2.1 +* Fixed critical bug where scanner wouldn't open when no scan overlay was configured. + +## 0.2.0 +#### Breaking change +* The plugin now returns Barcode object instead of QR String. This object includes the type of code, the code itself and on Android devices the raw bytes. (#63) +#### New Features +* Added possibility to provide scanArea on iOS. (#165) +#### Bug fixes +* Fixed preview going black after hot reload. (#76) +* Fixed nullpointer when plugin binding order isn't correct. (#181) +* Fixed permission being asked on startup (#185) + +## 0.1.0 +* Changed Android minSDKversion from 24 to 21 (#170) +* Fix preview size after iPad rotation (#125) +* Implemented Android Embedding V2 (#132) +* Added cutout bottom offset (#115) +* Fix Android ActivityLifecycleCallbacks (#166) +* Fix some other small bugs + +## 0.0.14 +* Fix disposing camera on iOS 14 (#113) + +## 0.0.13 +* Fix misalignment when QRView doesn't start from the top left (#45) +* Fix crash on iOS when scanning returns nil (#69, #72) +* Fix ArithmeticException on Android (#43) + +## 0.0.12 +* Add optional parameter to use a camera overlay. +* Simplify controller, expose scanDataStream. +* Fix for Android flash toggle. +* Add ability to pause/resume the camera. +* Thanks! to Luis Thein for all the above contributions. + +## 0.0.11 +* android build break fix + +## 0.0.10 +* update README.md + +## 0.0.9 +* update README.md + +## 0.0.8 +* migrated Android project to androidx (by Felipe César) +* migrated iOS to Swift 5 (by Felipe César) + +## 0.0.7 +* flash light support added + +## 0.0.6 +* camera flip added + +## 0.0.5 +* preview stretching after change screen orientation fix + +## 0.0.4 +* fix black screen orientation/unlock/focus + +## 0.0.3 +* iOS library reference fix +* Android pause/resume fix + +## 0.0.2 +* Added documentation to cover how to use the plugin. + +## 0.0.1 +* QR Code scanner embedded inside flutter. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7279e1f --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +Copyright 2018 Julius Canute + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..8279f82 --- /dev/null +++ b/README.md @@ -0,0 +1,209 @@ +# Project in Maintenance Mode Only + +Since the underlying frameworks of this package, [zxing for android](https://github.com/zxing/zxing) and [MTBBarcodescanner for iOS](https://github.com/mikebuss/MTBBarcodeScanner) are both not longer maintaned, this plugin is no longer up to date and in maintenance mode only. Only bug fixes and minor enhancements will be considered. + +I am developing a new plugin [mobile_scanner](https://pub.dev/packages/mobile_scanner) that uses the latest version of MLKit for detecting barcodes and QR codes. On Android it also uses the latest version of CameraX, and on iOS the native AVFoundation for best camera performance. + +# QR Code Scanner + +[![pub package](https://img.shields.io/pub/v/qr_code_scanner?include_prereleases)](https://pub.dartlang.org/packages/qr_code_scanner) +[![Join the chat](https://img.shields.io/discord/829004904600961054)](https://discord.gg/aZujk84f6V) +[![GH Actions](https://github.com/juliuscanute/qr_code_scanner/workflows/dart/badge.svg)](https://github.com/juliuscanute/qr_code_scanner/actions) + +A QR code scanner that works on both iOS and Android by natively embedding the platform view within Flutter. The integration with Flutter is seamless, much better than jumping into a native Activity or a ViewController to perform the scan. + +## Screenshots + + + + + + + + + + + + + + + + + + + +
+Android +
+

+ +

+
+

+ +

+
+iOS +
+

+ +

+
+

+ +

+
+ +## Get Scanned QR Code + +When a QR code is recognized, the text identified will be set in 'result' of type `Barcode`, which contains the output text as property 'code' of type `String` and scanned code type as property 'format' which is an enum `BarcodeFormat`, defined in the library. + +```dart +class _QRViewExampleState extends State { + final GlobalKey qrKey = GlobalKey(debugLabel: 'QR'); + Barcode? result; + 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: [ + Expanded( + flex: 5, + child: QRView( + key: qrKey, + onQRViewCreated: _onQRViewCreated, + ), + ), + Expanded( + flex: 1, + child: Center( + child: (result != null) + ? Text( + 'Barcode Type: ${describeEnum(result!.format)} Data: ${result!.code}') + : Text('Scan a code'), + ), + ) + ], + ), + ); + } + + void _onQRViewCreated(QRViewController controller) { + this.controller = controller; + controller.scannedDataStream.listen((scanData) { + setState(() { + result = scanData; + }); + }); + } + + @override + void dispose() { + controller?.dispose(); + super.dispose(); + } +} + +``` + +## Android Integration +In order to use this plugin, please update the Gradle, Kotlin and Kotlin Gradle Plugin: + +In ```android/build.gradle``` change ```ext.kotlin_version = '1.3.50'``` to ```ext.kotlin_version = '1.5.10'``` + +In ```android/build.gradle``` change ```classpath 'com.android.tools.build:gradle:3.5.0'``` to ```classpath 'com.android.tools.build:gradle:4.2.0'``` + +In ```android/gradle/wrapper/gradle-wrapper.properties``` change ```distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip``` to ```distributionUrl=https\://services.gradle.org/distributions/gradle-6.9-all.zip``` + +In ```android/app/build.gradle``` change +```defaultConfig{``` + ```...``` + ```minSdkVersion 16``` +```}``` to +```defaultConfig{``` + ```...``` + ```minSdkVersion 20``` +```}``` + +### *Warning* +If you are using Flutter Beta or Dev channel (1.25 or 1.26) you can get the following error: + +`java.lang.AbstractMethodError: abstract method "void io.flutter.plugin.platform.PlatformView.onFlutterViewAttached(android.view.View)"` + +This is a bug in Flutter which is being tracked here: https://github.com/flutter/flutter/issues/72185 + +There is a workaround by adding `android.enableDexingArtifactTransform=false` to your `gradle.properties` file. + +## iOS Integration +In order to use this plugin, add the following to your Info.plist file: +``` +io.flutter.embedded_views_preview + +NSCameraUsageDescription +This app needs camera access to scan QR codes +``` + +## Web Integration + +Add this to `web/index.html`: + +```html + +``` + +Please note: on web, only QR codes are supported. Other barcodes and 2D codes cannot be scanned. + +Web support is in very early stage. Features such as flash, pause or resume are not implemented. Moreover, the camera +preview does not respect the surrounding constraints. This is not at last due to Flutter's early state of platform views +on web. + +## Flip Camera (Back/Front) +The default camera is the back camera. +```dart +await controller.flipCamera(); +``` + +## Flash (Off/On) +By default, flash is OFF. +```dart +await controller.toggleFlash(); +``` + +## Resume/Pause +Pause camera stream and scanner. +```dart +await controller.pauseCamera(); +``` +Resume camera stream and scanner. +```dart +await controller.resumeCamera(); +``` + + +# SDK +Requires at least SDK 20. +Requires at least iOS 8. + +# TODOs +* iOS Native embedding is written to match what is supported in the framework as of the date of publication of this package. It needs to be improved as the framework support improves. +* In future, options will be provided for default states. +* Finally, I welcome PR's to make it better :), thanks + +# Credits +* Android: https://github.com/zxing/zxing +* iOS: https://github.com/mikebuss/MTBBarcodeScanner +* Special Thanks To: LeonDevLifeLog for his contributions towards improving this package. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..a3be6b8 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1 @@ +include: package:flutter_lints/flutter.yaml \ No newline at end of file diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..d36c796 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,67 @@ +# Built application files +*.apk +*.ap_ +*.aab + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# IntelliJ +*.iml +.idea/workspace.xml +.idea/tasks.xml +.idea/gradle.xml +.idea/assetWizardSettings.xml +.idea/dictionaries +.idea/libraries +.idea/caches + +# Keystore files +# Uncomment the following lines if you do not want to check your keystore files in. +#*.jks +#*.keystore + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild + +# Google Services (e.g. APIs or Firebase) +google-services.json + +# Freeline +freeline.py +freeline/ +freeline_project_description.json + +# fastlane +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots +fastlane/test_output +fastlane/readme.md \ No newline at end of file diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 0000000..31ff696 --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,64 @@ +group 'net.touchcapture.qr.flutterqr' +version '1.0-SNAPSHOT' + +buildscript { + ext.kotlin_version = '1.9.0' + repositories { + google() + mavenCentral() + } + + dependencies { + classpath 'com.android.tools.build:gradle:8.1.0' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +rootProject.allprojects { + repositories { + google() + mavenCentral() + } +} + +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' + +android { + namespace 'net.touchcapture.qr.flutterqr' + compileSdk 33 + + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } + defaultConfig { + // minSdkVersion is determined by Native View. + minSdkVersion 20 + targetSdkVersion 33 + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + multiDexEnabled true + } + + kotlinOptions { + jvmTarget = '11' + } + + compileOptions { + // Flag to enable support for the new language APIs + coreLibraryDesugaringEnabled true + // Sets Java compatibility to Java 11 + sourceCompatibility JavaVersion.VERSION_11 + targetCompatibility JavaVersion.VERSION_11 + } + if (project.android.hasProperty('namespace')) { + namespace 'net.touchcapture.qr.flutterqr' + } +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + implementation('com.journeyapps:zxing-android-embedded:4.3.0') { transitive = false } + implementation 'androidx.appcompat:appcompat:1.6.1' + implementation 'com.google.zxing:core:3.5.2' + coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.3' +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..08f2b5f --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx1536M +android.enableJetifier=true +android.useAndroidX=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ae04661 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 0000000..16c4243 --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'flutter_qr' diff --git a/android/src/main/AndroidManifest.xml b/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..28f2e86 --- /dev/null +++ b/android/src/main/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + diff --git a/android/src/main/kotlin/net/touchcapture/qr/flutterqr/CustomFramingRectBarcodeView.kt b/android/src/main/kotlin/net/touchcapture/qr/flutterqr/CustomFramingRectBarcodeView.kt new file mode 100644 index 0000000..3ad7431 --- /dev/null +++ b/android/src/main/kotlin/net/touchcapture/qr/flutterqr/CustomFramingRectBarcodeView.kt @@ -0,0 +1,45 @@ +package net.touchcapture.qr.flutterqr + +import android.content.Context +import android.graphics.Rect +import android.util.AttributeSet +import com.journeyapps.barcodescanner.BarcodeView +import com.journeyapps.barcodescanner.Size + +class CustomFramingRectBarcodeView : BarcodeView { + private var bottomOffset = BOTTOM_OFFSET_NOT_SET_VALUE + + constructor(context: Context?) : super(context) + constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) + constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super( + context, + attrs, + defStyleAttr + ) + + override fun calculateFramingRect(container: Rect, surface: Rect): Rect { + val containerArea = Rect(container) + val intersects = + containerArea.intersect(surface) //adjusts the containerArea (code from super.calculateFramingRect) + val scanAreaRect = super.calculateFramingRect(container, surface) + if (bottomOffset != BOTTOM_OFFSET_NOT_SET_VALUE) { //if the setFramingRect function was called, then we shift the scan area by Y + val scanAreaRectWithOffset = Rect(scanAreaRect) + scanAreaRectWithOffset.bottom -= bottomOffset + scanAreaRectWithOffset.top -= bottomOffset + val belongsToContainer = scanAreaRectWithOffset.intersect(containerArea) + if (belongsToContainer) { + return scanAreaRectWithOffset + } + } + return scanAreaRect + } + + fun setFramingRect(rectWidth: Int, rectHeight: Int, bottomOffset: Int) { + this.bottomOffset = bottomOffset + framingRectSize = Size(rectWidth, rectHeight) + } + + companion object { + private const val BOTTOM_OFFSET_NOT_SET_VALUE = -1 + } +} \ No newline at end of file diff --git a/android/src/main/kotlin/net/touchcapture/qr/flutterqr/FlutterQrPlugin.kt b/android/src/main/kotlin/net/touchcapture/qr/flutterqr/FlutterQrPlugin.kt new file mode 100644 index 0000000..97977a4 --- /dev/null +++ b/android/src/main/kotlin/net/touchcapture/qr/flutterqr/FlutterQrPlugin.kt @@ -0,0 +1,47 @@ +package net.touchcapture.qr.flutterqr + +import androidx.annotation.NonNull +import io.flutter.embedding.engine.plugins.FlutterPlugin +import io.flutter.embedding.engine.plugins.activity.ActivityAware +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding + +class FlutterQrPlugin : FlutterPlugin, ActivityAware { + + /** Plugin registration embedding v2 */ + override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { + flutterPluginBinding.platformViewRegistry + .registerViewFactory( + VIEW_TYPE_ID, + QRViewFactory(flutterPluginBinding.binaryMessenger) + ) + } + + override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { + // Leave empty + // Nullifying QrShared.activity and QrShared.binding here will cause errors if plugin is detached by another plugin + } + + override fun onAttachedToActivity(activityPluginBinding: ActivityPluginBinding) { + QrShared.activity = activityPluginBinding.activity + QrShared.binding = activityPluginBinding + } + + override fun onDetachedFromActivityForConfigChanges() { + QrShared.activity = null + QrShared.binding = null + } + + override fun onReattachedToActivityForConfigChanges(activityPluginBinding: ActivityPluginBinding) { + QrShared.activity = activityPluginBinding.activity + QrShared.binding = activityPluginBinding + } + + override fun onDetachedFromActivity() { + QrShared.activity = null + QrShared.binding = null + } + + companion object { + private const val VIEW_TYPE_ID = "net.touchcapture.qr.flutterqr/qrview" + } +} diff --git a/android/src/main/kotlin/net/touchcapture/qr/flutterqr/QRView.kt b/android/src/main/kotlin/net/touchcapture/qr/flutterqr/QRView.kt new file mode 100644 index 0000000..4589f2f --- /dev/null +++ b/android/src/main/kotlin/net/touchcapture/qr/flutterqr/QRView.kt @@ -0,0 +1,386 @@ +package net.touchcapture.qr.flutterqr + +import android.Manifest +import android.annotation.SuppressLint +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.view.View +import androidx.core.content.ContextCompat +import com.google.zxing.BarcodeFormat +import com.google.zxing.ResultPoint +import com.journeyapps.barcodescanner.BarcodeCallback +import com.journeyapps.barcodescanner.BarcodeResult +import com.journeyapps.barcodescanner.DefaultDecoderFactory +import io.flutter.plugin.common.BinaryMessenger +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.PluginRegistry +import io.flutter.plugin.platform.PlatformView + +class QRView( + private val context: Context, + messenger: BinaryMessenger, + private val id: Int, + private val params: HashMap +) : PlatformView, MethodChannel.MethodCallHandler, PluginRegistry.RequestPermissionsResultListener { + + private val cameraRequestCode = QrShared.CAMERA_REQUEST_ID + this.id + + private val channel: MethodChannel = MethodChannel( + messenger, "net.touchcapture.qr.flutterqr/qrview_$id" + ) + private val cameraFacingBack = 0 + private val cameraFacingFront = 1 + + private var isRequestingPermission = false + private var isTorchOn = false + private var isPaused = false + private var barcodeView: CustomFramingRectBarcodeView? = null + private var unRegisterLifecycleCallback: UnRegisterLifecycleCallback? = null + + init { + QrShared.binding?.addRequestPermissionsResultListener(this) + + channel.setMethodCallHandler(this) + + unRegisterLifecycleCallback = QrShared.activity?.registerLifecycleCallbacks( + onPause = { + if (!isPaused && hasCameraPermission) barcodeView?.pause() + + }, + onResume = { + if (!hasCameraPermission && !isRequestingPermission) checkAndRequestPermission() + else if (!isPaused && hasCameraPermission) barcodeView?.resume() + } + ) + } + + override fun dispose() { + unRegisterLifecycleCallback?.invoke() + + QrShared.binding?.removeRequestPermissionsResultListener(this) + + barcodeView?.pause() + barcodeView = null + } + + override fun getView(): View = initBarCodeView() + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + @Suppress("UNCHECKED_CAST") + when (call.method) { + "startScan" -> startScan(call.arguments as? List, result) + + "stopScan" -> stopScan() + + "flipCamera" -> flipCamera(result) + + "toggleFlash" -> toggleFlash(result) + + "pauseCamera" -> pauseCamera(result) + + // Stopping camera is the same as pausing camera + "stopCamera" -> pauseCamera(result) + + "resumeCamera" -> resumeCamera(result) + + "requestPermissions" -> checkAndRequestPermission() + + "getCameraInfo" -> getCameraInfo(result) + + "getFlashInfo" -> getFlashInfo(result) + + "getSystemFeatures" -> getSystemFeatures(result) + + "changeScanArea" -> changeScanArea( + dpScanAreaWidth = requireNotNull(call.argument("scanAreaWidth")), + dpScanAreaHeight = requireNotNull(call.argument("scanAreaHeight")), + cutOutBottomOffset = requireNotNull(call.argument("cutOutBottomOffset")), + result = result, + ) + + "invertScan" -> setInvertScan( + isInvert = call.argument("isInvertScan") ?: false, + ) + + else -> result.notImplemented() + } + } + + private fun initBarCodeView(): CustomFramingRectBarcodeView { + var barcodeView = barcodeView + + if (barcodeView == null) { + barcodeView = CustomFramingRectBarcodeView(QrShared.activity).also { + this.barcodeView = it + } + + barcodeView.decoderFactory = DefaultDecoderFactory(null, null, null, 2) + + if (params[PARAMS_CAMERA_FACING] as Int == 1) { + barcodeView.cameraSettings?.requestedCameraId = cameraFacingFront + } + } else if (!isPaused) { + barcodeView.resume() + } + + return barcodeView + } + + // region Camera Info + + private fun getCameraInfo(result: MethodChannel.Result) { + val barcodeView = barcodeView ?: return barCodeViewNotSet(result) + + result.success(barcodeView.cameraSettings.requestedCameraId) + } + + private fun getFlashInfo(result: MethodChannel.Result) { + if (barcodeView == null) return barCodeViewNotSet(result) + + result.success(isTorchOn) + } + + private fun hasFlash(): Boolean { + return hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH) + } + + @SuppressLint("UnsupportedChromeOsCameraSystemFeature") + private fun hasBackCamera(): Boolean { + return hasSystemFeature(PackageManager.FEATURE_CAMERA) + } + + private fun hasFrontCamera(): Boolean { + return hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT) + } + + private fun hasSystemFeature(feature: String): Boolean = + context.packageManager.hasSystemFeature(feature) + + private fun getSystemFeatures(result: MethodChannel.Result) { + try { + result.success( + mapOf( + "hasFrontCamera" to hasFrontCamera(), + "hasBackCamera" to hasBackCamera(), + "hasFlash" to hasFlash(), + "activeCamera" to barcodeView?.cameraSettings?.requestedCameraId + ) + ) + } catch (e: Exception) { + result.error("", e.message, null) + } + } + + // endregion + + // region Camera Controls + + private fun flipCamera(result: MethodChannel.Result) { + val barcodeView = barcodeView ?: return barCodeViewNotSet(result) + + barcodeView.pause() + + val settings = barcodeView.cameraSettings + if (settings.requestedCameraId == cameraFacingFront) { + settings.requestedCameraId = cameraFacingBack + } else settings.requestedCameraId = cameraFacingFront + + barcodeView.resume() + + result.success(settings.requestedCameraId) + } + + private fun toggleFlash(result: MethodChannel.Result) { + val barcodeView = barcodeView ?: return barCodeViewNotSet(result) + + if (hasFlash()) { + barcodeView.setTorch(!isTorchOn) + isTorchOn = !isTorchOn + result.success(isTorchOn) + } else { + result.error(ERROR_CODE_NOT_SET, ERROR_MESSAGE_FLASH_NOT_FOUND, null) + } + } + + private fun pauseCamera(result: MethodChannel.Result) { + val barcodeView = barcodeView ?: return barCodeViewNotSet(result) + + if (barcodeView.isPreviewActive) { + isPaused = true + barcodeView.pause() + } + + result.success(true) + } + + private fun resumeCamera(result: MethodChannel.Result) { + val barcodeView = barcodeView ?: return barCodeViewNotSet(result) + + if (!barcodeView.isPreviewActive) { + isPaused = false + barcodeView.resume() + } + + result.success(true) + } + + private fun startScan(arguments: List?, result: MethodChannel.Result) { + checkAndRequestPermission() + + val allowedBarcodeTypes = getAllowedBarcodeTypes(arguments, result) + + if (arguments == null) { + barcodeView?.decoderFactory = DefaultDecoderFactory(null, null, null, 2) + } else { + barcodeView?.decoderFactory = DefaultDecoderFactory(allowedBarcodeTypes, null, null, 2) + } + + barcodeView?.decodeContinuous( + object : BarcodeCallback { + override fun barcodeResult(result: BarcodeResult) { + if (allowedBarcodeTypes.isEmpty() || allowedBarcodeTypes.contains(result.barcodeFormat)) { + val code = mapOf( + "code" to result.text, + "type" to result.barcodeFormat.name, + "rawBytes" to result.rawBytes + ) + + channel.invokeMethod(CHANNEL_METHOD_ON_RECOGNIZE_QR, code) + } + } + + override fun possibleResultPoints(resultPoints: List) = Unit + } + ) + } + + private fun stopScan() { + barcodeView?.stopDecoding() + } + + private fun setInvertScan(isInvert: Boolean) { + val barcodeView = barcodeView ?: return + with(barcodeView) { + pause() + cameraSettings.isScanInverted = isInvert + resume() + } + } + + private fun changeScanArea( + dpScanAreaWidth: Double, + dpScanAreaHeight: Double, + cutOutBottomOffset: Double, + result: MethodChannel.Result + ) { + setScanAreaSize(dpScanAreaWidth, dpScanAreaHeight, cutOutBottomOffset) + + result.success(true) + } + + private fun setScanAreaSize( + dpScanAreaWidth: Double, + dpScanAreaHeight: Double, + dpCutOutBottomOffset: Double + ) { + barcodeView?.setFramingRect( + dpScanAreaWidth.convertDpToPixels(), + dpScanAreaHeight.convertDpToPixels(), + dpCutOutBottomOffset.convertDpToPixels(), + ) + } + + // endregion + + // region permissions + + private val hasCameraPermission: Boolean + get() = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || + ContextCompat.checkSelfPermission( + context, + Manifest.permission.CAMERA + ) == PackageManager.PERMISSION_GRANTED + + override fun onRequestPermissionsResult( + requestCode: Int, + permissions: Array, + grantResults: IntArray + ): Boolean { + if (requestCode != cameraRequestCode) return false + isRequestingPermission = false + + val permissionGranted = + grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED + + channel.invokeMethod(CHANNEL_METHOD_ON_PERMISSION_SET, permissionGranted) + + return permissionGranted + } + + + + private fun checkAndRequestPermission() { + if (hasCameraPermission) { + channel.invokeMethod(CHANNEL_METHOD_ON_PERMISSION_SET, true) + return + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !isRequestingPermission) { + QrShared.activity?.requestPermissions( + arrayOf(Manifest.permission.CAMERA), + cameraRequestCode + ) + } + } + + // endregion + + // region barcode common + + private fun getAllowedBarcodeTypes( + arguments: List?, + result: MethodChannel.Result + ): List { + return try { + arguments?.map { + BarcodeFormat.values()[it] + }.orEmpty() + } catch (e: Exception) { + result.error("", e.message, null) + + emptyList() + } + } + + private fun barCodeViewNotSet(result: MethodChannel.Result) { + result.error( + ERROR_CODE_NOT_SET, + ERROR_MESSAGE_NOT_SET, + null + ) + } + + // endregion + + // region helpers + + private fun Double.convertDpToPixels() = + (this * context.resources.displayMetrics.density).toInt() + + // endregion + + companion object { + private const val CHANNEL_METHOD_ON_PERMISSION_SET = "onPermissionSet" + private const val CHANNEL_METHOD_ON_RECOGNIZE_QR = "onRecognizeQR" + + private const val PARAMS_CAMERA_FACING = "cameraFacing" + + private const val ERROR_CODE_NOT_SET = "404" + + private const val ERROR_MESSAGE_NOT_SET = "No barcode view found" + private const val ERROR_MESSAGE_FLASH_NOT_FOUND = "This device doesn't support flash" + } +} + diff --git a/android/src/main/kotlin/net/touchcapture/qr/flutterqr/QRViewFactory.kt b/android/src/main/kotlin/net/touchcapture/qr/flutterqr/QRViewFactory.kt new file mode 100644 index 0000000..013c725 --- /dev/null +++ b/android/src/main/kotlin/net/touchcapture/qr/flutterqr/QRViewFactory.kt @@ -0,0 +1,30 @@ +package net.touchcapture.qr.flutterqr + +import android.content.Context +import io.flutter.plugin.common.BinaryMessenger +import io.flutter.plugin.common.StandardMessageCodec +import io.flutter.plugin.platform.PlatformView +import io.flutter.plugin.platform.PlatformViewFactory + + +class QRViewFactory( + private val messenger: BinaryMessenger +) : PlatformViewFactory(StandardMessageCodec.INSTANCE) { + + override fun create( + context: Context?, + viewId: Int, + args: Any? + ): PlatformView { + + @Suppress("UNCHECKED_CAST") + val params = args as HashMap + + return QRView( + context = requireNotNull(context), + id = viewId, + messenger = messenger, + params = params + ) + } +} \ No newline at end of file diff --git a/android/src/main/kotlin/net/touchcapture/qr/flutterqr/QrActivityLifecycleCallbacks.kt b/android/src/main/kotlin/net/touchcapture/qr/flutterqr/QrActivityLifecycleCallbacks.kt new file mode 100644 index 0000000..e22f711 --- /dev/null +++ b/android/src/main/kotlin/net/touchcapture/qr/flutterqr/QrActivityLifecycleCallbacks.kt @@ -0,0 +1,41 @@ +package net.touchcapture.qr.flutterqr + +import android.app.Activity +import android.app.Application +import android.os.Bundle + +class UnRegisterLifecycleCallback( + private val application: Application, + private val callback: Application.ActivityLifecycleCallbacks, +) { + operator fun invoke() = application.unregisterActivityLifecycleCallbacks(callback) +} + +fun Activity.registerLifecycleCallbacks( + onPause: (() -> Unit)? = null, + onResume: (() -> Unit)? = null, +): UnRegisterLifecycleCallback { + val callback = object : Application.ActivityLifecycleCallbacks { + override fun onActivityPaused(p0: Activity) { + if (p0 == this@registerLifecycleCallbacks) onPause?.invoke() + } + + override fun onActivityResumed(p0: Activity) { + if (p0 == this@registerLifecycleCallbacks) onResume?.invoke() + } + + override fun onActivityStarted(p0: Activity) = Unit + + override fun onActivityDestroyed(p0: Activity) = Unit + + override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) = Unit + + override fun onActivityStopped(p0: Activity) = Unit + + override fun onActivityCreated(p0: Activity, p1: Bundle?) = Unit + } + + application.registerActivityLifecycleCallbacks(callback) + + return UnRegisterLifecycleCallback(application, callback) +} diff --git a/android/src/main/kotlin/net/touchcapture/qr/flutterqr/QrShared.kt b/android/src/main/kotlin/net/touchcapture/qr/flutterqr/QrShared.kt new file mode 100644 index 0000000..6814640 --- /dev/null +++ b/android/src/main/kotlin/net/touchcapture/qr/flutterqr/QrShared.kt @@ -0,0 +1,15 @@ +package net.touchcapture.qr.flutterqr + +import android.annotation.SuppressLint +import android.app.Activity +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding + +@SuppressLint("StaticFieldLeak") +object QrShared { + const val CAMERA_REQUEST_ID = 513469796 + + var activity: Activity? = null + + var binding: ActivityPluginBinding? = null + +} \ No newline at end of file diff --git a/example/.gitignore b/example/.gitignore new file mode 100644 index 0000000..4736dd6 --- /dev/null +++ b/example/.gitignore @@ -0,0 +1,72 @@ +# Miscellaneous +*.class +*.lock +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +.last_build_id + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# Visual Studio Code related +.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +.dart_tool/ +.flutter-plugins +.packages +.pub-cache/ +.pub/ +build/ + +# Android related +**/android/**/gradle-wrapper.jar +**/android/.gradle +**/android/captures/ +**/android/gradlew +**/android/gradlew.bat +**/android/local.properties +**/android/**/GeneratedPluginRegistrant.java + +# iOS/XCode related +**/ios/**/*.mode1v3 +**/ios/**/*.mode2v3 +**/ios/**/*.moved-aside +**/ios/**/*.pbxuser +**/ios/**/*.perspectivev3 +**/ios/**/*sync/ +**/ios/**/.sconsign.dblite +**/ios/**/.tags* +**/ios/**/.vagrant/ +**/ios/**/DerivedData/ +**/ios/**/Icon? +**/ios/**/Pods/ +**/ios/**/.symlinks/ +**/ios/**/profile +**/ios/**/xcuserdata +**/ios/.generated/ +**/ios/Flutter/App.framework +**/ios/Flutter/Flutter.framework +**/ios/Flutter/Generated.xcconfig +**/ios/Flutter/app.flx +**/ios/Flutter/app.zip +**/ios/Flutter/flutter_assets/ +**/ios/ServiceDefinitions.json +**/ios/Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!**/ios/**/default.mode1v3 +!**/ios/**/default.mode2v3 +!**/ios/**/default.pbxuser +!**/ios/**/default.perspectivev3 +!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages diff --git a/example/.metadata b/example/.metadata new file mode 100644 index 0000000..f173f89 --- /dev/null +++ b/example/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 58c8489fcdb4e4ef6c010117584c9b23d15221aa + channel: beta + +project_type: app diff --git a/example/README.md b/example/README.md new file mode 100644 index 0000000..cfaa9b4 --- /dev/null +++ b/example/README.md @@ -0,0 +1,192 @@ +# qr_code_scanner + +Demonstrates how to use the qr_code_scanner plugin. + +## iOS Support: +### info.plist +```xml + + io.flutter.embedded_views_preview + + UIBackgroundModes + + fetch + remote-notification + + NSCameraUsageDescription + Can we access your camera in order to scan barcodes? + + +``` + +## Example: +```dart +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:qr_code_scanner/qr_code_scanner.dart'; + +void main() => runApp(MaterialApp(home: QRViewExample())); + +class QRViewExample extends StatefulWidget { + const QRViewExample({ + Key key, + }) : super(key: key); + + @override + State createState() => _QRViewExampleState(); +} + +class _QRViewExampleState extends State { + Barcode result; + QRViewController controller; + final GlobalKey qrKey = GlobalKey(debugLabel: 'QR'); + + // 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(); + } + controller.resumeCamera(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Column( + children: [ + Expanded(flex: 4, child: _buildQrView(context)), + Expanded( + flex: 1, + child: FittedBox( + fit: BoxFit.contain, + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + if (result != null) + Text( + 'Barcode Type: ${describeEnum(result.format)} Data: ${result.code}') + else + Text('Scan a code'), + Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Container( + margin: EdgeInsets.all(8), + child: RaisedButton( + onPressed: () async { + await controller?.toggleFlash(); + setState(() {}); + }, + child: FutureBuilder( + future: controller?.getFlashStatus(), + builder: (context, snapshot) { + return Text('Flash: ${snapshot.data}'); + }, + )), + ), + Container( + margin: EdgeInsets.all(8), + child: RaisedButton( + onPressed: () async { + await controller?.flipCamera(); + setState(() {}); + }, + child: FutureBuilder( + future: controller?.getCameraInfo(), + builder: (context, snapshot) { + if (snapshot.data != null) { + return Text( + 'Camera facing ${describeEnum(snapshot.data)}'); + } else { + return Text('loading'); + } + }, + )), + ) + ], + ), + Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Container( + margin: EdgeInsets.all(8), + child: RaisedButton( + onPressed: () async { + await controller?.pauseCamera(); + }, + child: Text('pause', style: TextStyle(fontSize: 20)), + ), + ), + Container( + margin: EdgeInsets.all(8), + child: RaisedButton( + onPressed: () async { + await controller?.resumeCamera(); + }, + child: Text('resume', style: TextStyle(fontSize: 20)), + ), + ) + ], + ), + ], + ), + ), + ) + ], + ), + ); + } + + Widget _buildQrView(BuildContext context) { + // For this example we check how width or tall the device is and change the scanArea and overlay accordingly. + var scanArea = (MediaQuery.of(context).size.width < 400 || + MediaQuery.of(context).size.height < 400) + ? 150.0 + : 300.0; + // To ensure the Scanner view is properly sizes after rotation + // we need to listen for Flutter SizeChanged notification and update controller + return QRView( + key: qrKey, + // You can choose between CameraFacing.front or CameraFacing.back. Defaults to CameraFacing.back + // cameraFacing: CameraFacing.front, + onQRViewCreated: _onQRViewCreated, + // Choose formats you want to scan. Defaults to all formats. + // formatsAllowed: [BarcodeFormat.qrcode], + overlay: QrScannerOverlayShape( + borderColor: Colors.red, + borderRadius: 10, + borderLength: 30, + borderWidth: 10, + cutOutSize: scanArea, + ), + ); + } + + void _onQRViewCreated(QRViewController controller) { + setState(() { + this.controller = controller; + }); + controller.scannedDataStream.listen((scanData) { + setState(() { + result = scanData; + }); + }); + } + + @override + void dispose() { + controller?.dispose(); + super.dispose(); + } +} +``` + + + diff --git a/example/analysis_options.yaml b/example/analysis_options.yaml new file mode 100644 index 0000000..a3be6b8 --- /dev/null +++ b/example/analysis_options.yaml @@ -0,0 +1 @@ +include: package:flutter_lints/flutter.yaml \ No newline at end of file diff --git a/example/android/app/build.gradle b/example/android/app/build.gradle new file mode 100644 index 0000000..d4b7c14 --- /dev/null +++ b/example/android/app/build.gradle @@ -0,0 +1,63 @@ +def localProperties = new Properties() +def localPropertiesFile = rootProject.file('local.properties') +if (localPropertiesFile.exists()) { + localPropertiesFile.withReader('UTF-8') { reader -> + localProperties.load(reader) + } +} + +def flutterRoot = localProperties.getProperty('flutter.sdk') +if (flutterRoot == null) { + throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") +} + +def flutterVersionCode = localProperties.getProperty('flutter.versionCode') +if (flutterVersionCode == null) { + flutterVersionCode = '1' +} + +def flutterVersionName = localProperties.getProperty('flutter.versionName') +if (flutterVersionName == null) { + flutterVersionName = '1.0' +} + +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" + +android { + compileSdk 33 + + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } + + defaultConfig { + applicationId "net.touchcapture.qr.flutterqrexample" + // minSdkVersion is determined by Native View. + minSdkVersion 20 + targetSdkVersion 33 + versionCode flutterVersionCode.toInteger() + versionName flutterVersionName + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig signingConfigs.debug + } + } + namespace 'net.touchcapture.qr.flutterqrexample' +} + +flutter { + source '../..' +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + testImplementation 'junit:junit:4.13.2' + androidTestImplementation 'com.android.support.test:runner:1.0.2' + androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' +} diff --git a/example/android/app/src/main/AndroidManifest.xml b/example/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..bc99518 --- /dev/null +++ b/example/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + diff --git a/example/android/app/src/main/res/drawable/launch_background.xml b/example/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/example/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/values/styles.xml b/example/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..3257023 --- /dev/null +++ b/example/android/app/src/main/res/values/styles.xml @@ -0,0 +1,19 @@ + + + + + + + + diff --git a/example/android/build.gradle b/example/android/build.gradle new file mode 100644 index 0000000..1dd38bc --- /dev/null +++ b/example/android/build.gradle @@ -0,0 +1,29 @@ +buildscript { + ext.kotlin_version = '1.9.0' + repositories { + google() + mavenCentral() + } + + dependencies { + classpath 'com.android.tools.build:gradle:8.1.0' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +rootProject.buildDir = '../build' +subprojects { + project.buildDir = "${rootProject.buildDir}/${project.name}" + project.evaluationDependsOn(':app') +} + +tasks.register('clean', Delete) { + delete rootProject.buildDir +} diff --git a/example/android/gradle.properties b/example/android/gradle.properties new file mode 100644 index 0000000..1310f7a --- /dev/null +++ b/example/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx1536M +android.useAndroidX=true +android.enableJetifier=true +android.defaults.buildfeatures.buildconfig=true +android.nonTransitiveRClass=false +android.nonFinalResIds=false \ No newline at end of file diff --git a/example/android/gradle/wrapper/gradle-wrapper.properties b/example/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..c943057 --- /dev/null +++ b/example/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Aug 08 21:31:11 CEST 2023 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/example/android/settings.gradle b/example/android/settings.gradle new file mode 100644 index 0000000..44e62bc --- /dev/null +++ b/example/android/settings.gradle @@ -0,0 +1,11 @@ +include ':app' + +def localPropertiesFile = new File(rootProject.projectDir, "local.properties") +def properties = new Properties() + +assert localPropertiesFile.exists() +localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } + +def flutterSdkPath = properties.getProperty("flutter.sdk") +assert flutterSdkPath != null, "flutter.sdk not set in local.properties" +apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" diff --git a/example/ios/Flutter/AppFrameworkInfo.plist b/example/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..9367d48 --- /dev/null +++ b/example/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 8.0 + + diff --git a/example/ios/Flutter/Debug.xcconfig b/example/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..e8efba1 --- /dev/null +++ b/example/ios/Flutter/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "Generated.xcconfig" diff --git a/example/ios/Flutter/Release.xcconfig b/example/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..399e934 --- /dev/null +++ b/example/ios/Flutter/Release.xcconfig @@ -0,0 +1,2 @@ +#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "Generated.xcconfig" diff --git a/example/ios/Podfile b/example/ios/Podfile new file mode 100644 index 0000000..1e8c3c9 --- /dev/null +++ b/example/ios/Podfile @@ -0,0 +1,41 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '9.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + use_modular_headers! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..93f92c8 --- /dev/null +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,589 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 4FA3805501F593094264678B /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 75B64521967C76C845268E71 /* Pods_Runner.framework */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 08F42BD28C1585A831B4FDA2 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 75B64521967C76C845268E71 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + DB8991B7B046D94B2E68CEAD /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + EF8A0739582463E296AD6CB1 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 4FA3805501F593094264678B /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + D7C58E57CAF69D9A14CC212F /* Pods */, + AF031A634C9742F16BF4F89A /* Frameworks */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 97C146F11CF9000F007C117D /* Supporting Files */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; + 97C146F11CF9000F007C117D /* Supporting Files */ = { + isa = PBXGroup; + children = ( + ); + name = "Supporting Files"; + sourceTree = ""; + }; + AF031A634C9742F16BF4F89A /* Frameworks */ = { + isa = PBXGroup; + children = ( + 75B64521967C76C845268E71 /* Pods_Runner.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + D7C58E57CAF69D9A14CC212F /* Pods */ = { + isa = PBXGroup; + children = ( + DB8991B7B046D94B2E68CEAD /* Pods-Runner.debug.xcconfig */, + EF8A0739582463E296AD6CB1 /* Pods-Runner.release.xcconfig */, + 08F42BD28C1585A831B4FDA2 /* Pods-Runner.profile.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 7BEA526A4A0DFAAC4945EC09 /* [CP] Check Pods Manifest.lock */, + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + 8DB6578C615972DBF2DFAA0D /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 1020; + ORGANIZATIONNAME = "The Chromium Authors"; + TargetAttributes = { + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + DevelopmentTeam = 5LSCTACHT8; + LastSwiftMigration = 1020; + ProvisioningStyle = Automatic; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 7BEA526A4A0DFAAC4945EC09 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 8DB6578C615972DBF2DFAA0D /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/MTBBarcodeScanner/MTBBarcodeScanner.framework", + "${BUILT_PRODUCTS_DIR}/qr_code_scanner/qr_code_scanner.framework", + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/MTBBarcodeScanner.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/qr_code_scanner.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_IDENTITY = "iPhone Developer"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 5LSCTACHT8; + ENABLE_BITCODE = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Flutter", + ); + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Flutter", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.steenbakker.qr; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 4.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 5LSCTACHT8; + ENABLE_BITCODE = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Flutter", + ); + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Flutter", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.steenbakker.qr; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 5LSCTACHT8; + ENABLE_BITCODE = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Flutter", + ); + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Flutter", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.steenbakker.qr; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 4.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..a28140c --- /dev/null +++ b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,91 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/ios/Runner.xcworkspace/contents.xcworkspacedata b/example/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..21a3cc1 --- /dev/null +++ b/example/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example/ios/Runner/AppDelegate.swift b/example/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..70693e4 --- /dev/null +++ b/example/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import UIKit +import Flutter + +@UIApplicationMain +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..3d43d11 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..28c6bf0 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..2ccbfd9 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..f091b6b Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cde121 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..d0ef06e Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..dcdc230 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..2ccbfd9 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..c8f9ed8 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..a6d6b86 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..a6d6b86 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..75b2d16 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..c4df70d Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..6a84f41 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..d0e1f58 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/example/ios/Runner/Base.lproj/LaunchScreen.storyboard b/example/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/example/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/ios/Runner/Base.lproj/Main.storyboard b/example/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/example/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/ios/Runner/Info.plist b/example/ios/Runner/Info.plist new file mode 100644 index 0000000..d8eec84 --- /dev/null +++ b/example/ios/Runner/Info.plist @@ -0,0 +1,54 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + flutter_qr_example + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + NSCameraUsageDescription + Can we access your camera in order to scan barcodes? + UIBackgroundModes + + fetch + remote-notification + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UIViewControllerBasedStatusBarAppearance + + io.flutter.embedded_views_preview + + + diff --git a/example/ios/Runner/Runner-Bridging-Header.h b/example/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..7335fdf --- /dev/null +++ b/example/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" \ No newline at end of file diff --git a/example/lib/main.dart b/example/lib/main.dart new file mode 100644 index 0000000..477b8d3 --- /dev/null +++ b/example/lib/main.dart @@ -0,0 +1,192 @@ +import 'dart:developer'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:qr_code_scanner/qr_code_scanner.dart'; + +void main() => runApp(const MaterialApp(home: MyHome())); + +class MyHome extends StatelessWidget { + const MyHome({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Flutter Demo Home Page')), + body: Center( + child: ElevatedButton( + onPressed: () { + Navigator.of(context).push(MaterialPageRoute( + builder: (context) => const QRViewExample(), + )); + }, + child: const Text('qrView'), + ), + ), + ); + } +} + +class QRViewExample extends StatefulWidget { + const QRViewExample({Key? key}) : super(key: key); + + @override + State createState() => _QRViewExampleState(); +} + +class _QRViewExampleState extends State { + Barcode? result; + QRViewController? controller; + final GlobalKey qrKey = GlobalKey(debugLabel: 'QR'); + + // 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(); + } + controller!.resumeCamera(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Column( + children: [ + Expanded(flex: 4, child: _buildQrView(context)), + Expanded( + flex: 1, + child: FittedBox( + fit: BoxFit.contain, + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + if (result != null) + Text( + 'Barcode Type: ${describeEnum(result!.format)} Data: ${result!.code}') + else + const Text('Scan a code'), + Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Container( + margin: const EdgeInsets.all(8), + child: ElevatedButton( + onPressed: () async { + await controller?.toggleFlash(); + setState(() {}); + }, + child: FutureBuilder( + future: controller?.getFlashStatus(), + builder: (context, snapshot) { + return Text('Flash: ${snapshot.data}'); + }, + )), + ), + Container( + margin: const EdgeInsets.all(8), + child: ElevatedButton( + onPressed: () async { + await controller?.flipCamera(); + setState(() {}); + }, + child: FutureBuilder( + future: controller?.getCameraInfo(), + builder: (context, snapshot) { + if (snapshot.data != null) { + return Text( + 'Camera facing ${describeEnum(snapshot.data!)}'); + } else { + return const Text('loading'); + } + }, + )), + ) + ], + ), + Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Container( + margin: const EdgeInsets.all(8), + child: ElevatedButton( + onPressed: () async { + await controller?.pauseCamera(); + }, + child: const Text('pause', + style: TextStyle(fontSize: 20)), + ), + ), + Container( + margin: const EdgeInsets.all(8), + child: ElevatedButton( + onPressed: () async { + await controller?.resumeCamera(); + }, + child: const Text('resume', + style: TextStyle(fontSize: 20)), + ), + ) + ], + ), + ], + ), + ), + ) + ], + ), + ); + } + + Widget _buildQrView(BuildContext context) { + // For this example we check how width or tall the device is and change the scanArea and overlay accordingly. + var scanArea = (MediaQuery.of(context).size.width < 400 || + MediaQuery.of(context).size.height < 400) + ? 150.0 + : 300.0; + // To ensure the Scanner view is properly sizes after rotation + // we need to listen for Flutter SizeChanged notification and update controller + return QRView( + key: qrKey, + onQRViewCreated: _onQRViewCreated, + overlay: QrScannerOverlayShape( + borderColor: Colors.red, + borderRadius: 10, + borderLength: 30, + borderWidth: 10, + cutOutSize: scanArea), + onPermissionSet: (ctrl, p) => _onPermissionSet(context, ctrl, p), + ); + } + + void _onQRViewCreated(QRViewController controller) { + setState(() { + this.controller = controller; + }); + controller.scannedDataStream.listen((scanData) { + setState(() { + result = scanData; + }); + }); + } + + void _onPermissionSet(BuildContext context, QRViewController ctrl, bool p) { + log('${DateTime.now().toIso8601String()}_onPermissionSet $p'); + if (!p) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('no Permission')), + ); + } + } + + @override + void dispose() { + controller?.dispose(); + super.dispose(); + } +} diff --git a/example/pubspec.yaml b/example/pubspec.yaml new file mode 100644 index 0000000..30a6d72 --- /dev/null +++ b/example/pubspec.yaml @@ -0,0 +1,60 @@ +name: qr_code_scanner_example +description: Demonstrates how to use the flutter_qr plugin. +publish_to: 'none' + +environment: + sdk: '>=2.12.0 <3.0.0' + +dependencies: + flutter: + sdk: flutter + +dev_dependencies: + flutter_lints: ^1.0.4 + flutter_test: + sdk: flutter + + qr_code_scanner: + path: ../ + +# For information on the generic Dart part of this file, see the +# following page: https://www.dartlang.org/tools/pub/pubspec + +# The following section is specific to Flutter. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.io/assets-and-images/#resolution-aware. + + # For details regarding adding assets from package dependencies, see + # https://flutter.io/assets-and-images/#from-packages + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.io/custom-fonts/#from-packages diff --git a/example/test/widget_test.dart b/example/test/widget_test.dart new file mode 100644 index 0000000..eb105c3 --- /dev/null +++ b/example/test/widget_test.dart @@ -0,0 +1,6 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility that Flutter provides. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. diff --git a/example/web/favicon.png b/example/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/example/web/favicon.png differ diff --git a/example/web/icons/Icon-192.png b/example/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/example/web/icons/Icon-192.png differ diff --git a/example/web/icons/Icon-512.png b/example/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/example/web/icons/Icon-512.png differ diff --git a/example/web/index.html b/example/web/index.html new file mode 100644 index 0000000..f243f37 --- /dev/null +++ b/example/web/index.html @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + example + + + + + + + + + diff --git a/example/web/manifest.json b/example/web/manifest.json new file mode 100644 index 0000000..8c01291 --- /dev/null +++ b/example/web/manifest.json @@ -0,0 +1,23 @@ +{ + "name": "example", + "short_name": "example", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + } + ] +} diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..fce96a3 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,78 @@ +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## Build generated +build/ +DerivedData/ + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata/ + +## Other +*.moved-aside +*.xccheckout +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa +*.dSYM.zip +*.dSYM + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +# Package.pins +# Package.resolved +.build/ + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# +# Pods/ +# +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace + +# Carthage +# +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build + +# fastlane +# +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://docs.fastlane.tools/best-practices/source-control/#source-control + +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ \ No newline at end of file diff --git a/ios/Assets/.gitkeep b/ios/Assets/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/ios/Classes/FlutterQrPlugin.h b/ios/Classes/FlutterQrPlugin.h new file mode 100644 index 0000000..c3d077d --- /dev/null +++ b/ios/Classes/FlutterQrPlugin.h @@ -0,0 +1,4 @@ +#import + +@interface FlutterQrPlugin : NSObject +@end diff --git a/ios/Classes/FlutterQrPlugin.m b/ios/Classes/FlutterQrPlugin.m new file mode 100644 index 0000000..d52bedc --- /dev/null +++ b/ios/Classes/FlutterQrPlugin.m @@ -0,0 +1,13 @@ +#import "FlutterQrPlugin.h" + +#if __has_include() +#import +#else +#import "qr_code_scanner-Swift.h" +#endif + +@implementation FlutterQrPlugin ++ (void)registerWithRegistrar:(NSObject*)registrar { + [SwiftFlutterQrPlugin registerWithRegistrar:registrar]; +} +@end diff --git a/ios/Classes/QRView.swift b/ios/Classes/QRView.swift new file mode 100644 index 0000000..1af7581 --- /dev/null +++ b/ios/Classes/QRView.swift @@ -0,0 +1,304 @@ +// +// QRView.swift +// flutter_qr +// +// Created by Julius Canute on 21/12/18. +// + +import Foundation +import MTBBarcodeScanner + +public class QRView:NSObject,FlutterPlatformView { + @IBOutlet var previewView: UIView! + var scanner: MTBBarcodeScanner? + var registrar: FlutterPluginRegistrar + var channel: FlutterMethodChannel + var cameraFacing: MTBCamera + + // Codabar, maxicode, rss14 & rssexpanded not supported. Replaced with qr. + // UPCa uses ean13 object. + var QRCodeTypes = [ + 0: AVMetadataObject.ObjectType.aztec, + 1: AVMetadataObject.ObjectType.qr, + 2: AVMetadataObject.ObjectType.code39, + 3: AVMetadataObject.ObjectType.code93, + 4: AVMetadataObject.ObjectType.code128, + 5: AVMetadataObject.ObjectType.dataMatrix, + 6: AVMetadataObject.ObjectType.ean8, + 7: AVMetadataObject.ObjectType.ean13, + 8: AVMetadataObject.ObjectType.interleaved2of5, + 9: AVMetadataObject.ObjectType.qr, + 10: AVMetadataObject.ObjectType.pdf417, + 11: AVMetadataObject.ObjectType.qr, + 12: AVMetadataObject.ObjectType.qr, + 13: AVMetadataObject.ObjectType.qr, + 14: AVMetadataObject.ObjectType.ean13, + 15: AVMetadataObject.ObjectType.upce + ] + + public init(withFrame frame: CGRect, withRegistrar registrar: FlutterPluginRegistrar, withId id: Int64, params: Dictionary){ + self.registrar = registrar + previewView = UIView(frame: frame) + cameraFacing = MTBCamera.init(rawValue: UInt(Int(params["cameraFacing"] as! Double))) ?? MTBCamera.back + channel = FlutterMethodChannel(name: "net.touchcapture.qr.flutterqr/qrview_\(id)", binaryMessenger: registrar.messenger()) + } + + deinit { + scanner?.stopScanning() + } + + public func view() -> UIView { + channel.setMethodCallHandler({ + [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in + switch(call.method){ + case "setDimensions": + let arguments = call.arguments as! Dictionary + self?.setDimensions(result, + width: arguments["width"] ?? 0, + height: arguments["height"] ?? 0, + scanAreaWidth: arguments["scanAreaWidth"] ?? 0, + scanAreaHeight: arguments["scanAreaHeight"] ?? 0, + scanAreaOffset: arguments["scanAreaOffset"] ?? 0) + case "startScan": + self?.startScan(call.arguments as! Array, result) + case "flipCamera": + self?.flipCamera(result) + case "toggleFlash": + self?.toggleFlash(result) + case "pauseCamera": + self?.pauseCamera(result) + case "stopCamera": + self?.stopCamera(result) + case "resumeCamera": + self?.resumeCamera(result) + case "getCameraInfo": + self?.getCameraInfo(result) + case "getFlashInfo": + self?.getFlashInfo(result) + case "getSystemFeatures": + self?.getSystemFeatures(result) + default: + result(FlutterMethodNotImplemented) + return + } + }) + return previewView + } + + func setDimensions(_ result: @escaping FlutterResult, width: Double, height: Double, scanAreaWidth: Double, scanAreaHeight: Double, scanAreaOffset: Double) { + // Then set the size of the preview area. + previewView.frame = CGRect(x: 0, y: 0, width: width, height: height) + + // Then set the size of the scan area. + let midX = self.view().bounds.midX + let midY = self.view().bounds.midY + + if let sc: MTBBarcodeScanner = scanner { + // Set the size of the preview if preview is already created. + if let previewLayer = sc.previewLayer { + previewLayer.frame = self.previewView.bounds + } + } else { + // Create new preview. + scanner = MTBBarcodeScanner(previewView: previewView) + } + + // Set scanArea if provided. + if (scanAreaWidth != 0 && scanAreaHeight != 0) { + scanner?.didStartScanningBlock = { + self.scanner?.scanRect = CGRect(x: Double(midX) - (scanAreaWidth / 2), y: Double(midY) - (scanAreaHeight / 2), width: scanAreaWidth, height: scanAreaHeight) + + // Set offset if provided. + if (scanAreaOffset != 0) { + let reversedOffset = -scanAreaOffset + self.scanner?.scanRect = (self.scanner?.scanRect.offsetBy(dx: 0, dy: CGFloat(reversedOffset)))! + + } + } + } + return result(width) + + } + + func startScan(_ arguments: Array, _ result: @escaping FlutterResult) { + // Check for allowed barcodes + var allowedBarcodeTypes: Array = [] + arguments.forEach { arg in + allowedBarcodeTypes.append( QRCodeTypes[arg]!) + } + MTBBarcodeScanner.requestCameraPermission(success: { [weak self] permissionGranted in + guard let self = self else { return } + + self.channel.invokeMethod("onPermissionSet", arguments: permissionGranted) + + if permissionGranted { + do { + try self.scanner?.startScanning(with: self.cameraFacing, resultBlock: { [weak self] codes in + if let codes = codes { + for code in codes { + var typeString: String; + switch(code.type) { + case AVMetadataObject.ObjectType.aztec: + typeString = "AZTEC" + case AVMetadataObject.ObjectType.code39: + typeString = "CODE_39" + case AVMetadataObject.ObjectType.code93: + typeString = "CODE_93" + case AVMetadataObject.ObjectType.code128: + typeString = "CODE_128" + case AVMetadataObject.ObjectType.dataMatrix: + typeString = "DATA_MATRIX" + case AVMetadataObject.ObjectType.ean8: + typeString = "EAN_8" + case AVMetadataObject.ObjectType.ean13: + typeString = "EAN_13" + case AVMetadataObject.ObjectType.itf14, + AVMetadataObject.ObjectType.interleaved2of5: + typeString = "ITF" + case AVMetadataObject.ObjectType.pdf417: + typeString = "PDF_417" + case AVMetadataObject.ObjectType.qr: + typeString = "QR_CODE" + case AVMetadataObject.ObjectType.upce: + typeString = "UPC_E" + default: + return + } + let bytes = { () -> Data? in + if #available(iOS 11.0, *) { + switch (code.descriptor) { + case let qrDescriptor as CIQRCodeDescriptor: + return qrDescriptor.errorCorrectedPayload + case let aztecDescriptor as CIAztecCodeDescriptor: + return aztecDescriptor.errorCorrectedPayload + case let pdf417Descriptor as CIPDF417CodeDescriptor: + return pdf417Descriptor.errorCorrectedPayload + case let dataMatrixDescriptor as CIDataMatrixCodeDescriptor: + return dataMatrixDescriptor.errorCorrectedPayload + default: + return nil + } + } else { + return nil + } + }() + let result = { () -> [String : Any]? in + guard let stringValue = code.stringValue else { + guard let safeBytes = bytes else { + return nil + } + return ["type": typeString, "rawBytes": safeBytes] + } + guard let safeBytes = bytes else { + return ["code": stringValue, "type": typeString] + } + return ["code": stringValue, "type": typeString, "rawBytes": safeBytes] + }() + guard result != nil else { continue } + if allowedBarcodeTypes.count == 0 || allowedBarcodeTypes.contains(code.type) { + self?.channel.invokeMethod("onRecognizeQR", arguments: result) + } + + } + } + + }) + } catch { + let scanError = FlutterError(code: "unknown-error", message: "Unable to start scanning", details: error) + result(scanError) + } + } + }) + } + + func stopCamera(_ result: @escaping FlutterResult) { + if let sc: MTBBarcodeScanner = self.scanner { + if sc.isScanning() { + sc.stopScanning() + } + } + } + + func getCameraInfo(_ result: @escaping FlutterResult) { + result(self.cameraFacing.rawValue) + } + + func flipCamera(_ result: @escaping FlutterResult) { + if let sc: MTBBarcodeScanner = self.scanner { + if sc.hasOppositeCamera() { + sc.flipCamera() + self.cameraFacing = sc.camera + } + return result(sc.camera.rawValue) + } + return result(FlutterError(code: "404", message: "No barcode scanner found", details: nil)) + } + + func getFlashInfo(_ result: @escaping FlutterResult) { + if let sc: MTBBarcodeScanner = self.scanner { + result(sc.torchMode.rawValue != 0) + } else { + let error = FlutterError(code: "cameraInformationError", message: "Could not get flash information", details: nil) + result(error) + } + } + + func toggleFlash(_ result: @escaping FlutterResult){ + if let sc: MTBBarcodeScanner = self.scanner { + if sc.hasTorch() { + sc.toggleTorch() + return result(sc.torchMode == MTBTorchMode(rawValue: 1)) + } + return result(FlutterError(code: "404", message: "This device doesn\'t support flash", details: nil)) + } + return result(FlutterError(code: "404", message: "No barcode scanner found", details: nil)) + } + + func pauseCamera(_ result: @escaping FlutterResult) { + if let sc: MTBBarcodeScanner = self.scanner { + if sc.isScanning() { + sc.freezeCapture() + } + return result(true) + } + return result(FlutterError(code: "404", message: "No barcode scanner found", details: nil)) + } + + func resumeCamera(_ result: @escaping FlutterResult) { + if let sc: MTBBarcodeScanner = self.scanner { + if !sc.isScanning() { + sc.unfreezeCapture() + } + return result(true) + } + return result(FlutterError(code: "404", message: "No barcode scanner found", details: nil)) + } + + func getSystemFeatures(_ result: @escaping FlutterResult) { + if let sc: MTBBarcodeScanner = scanner { + var hasBackCameraVar = false + var hasFrontCameraVar = false + let camera = sc.camera + + if(camera == MTBCamera(rawValue: 0)){ + hasBackCameraVar = true + if sc.hasOppositeCamera() { + hasFrontCameraVar = true + } + }else{ + hasFrontCameraVar = true + if sc.hasOppositeCamera() { + hasBackCameraVar = true + } + } + return result([ + "hasFrontCamera": hasFrontCameraVar, + "hasBackCamera": hasBackCameraVar, + "hasFlash": sc.hasTorch(), + "activeCamera": camera.rawValue + ]) + } + return result(FlutterError(code: "404", message: nil, details: nil)) + } + + } diff --git a/ios/Classes/QRViewFactory.swift b/ios/Classes/QRViewFactory.swift new file mode 100644 index 0000000..6f851f6 --- /dev/null +++ b/ios/Classes/QRViewFactory.swift @@ -0,0 +1,27 @@ +// +// QRViewFactory.swift +// flutter_qr +// +// Created by Julius Canute on 21/12/18. +// + +import Foundation + +public class QRViewFactory: NSObject, FlutterPlatformViewFactory { + + var registrar: FlutterPluginRegistrar? + + public init(withRegistrar registrar: FlutterPluginRegistrar){ + super.init() + self.registrar = registrar + } + + public func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView { + let params = args as! Dictionary + return QRView(withFrame: frame, withRegistrar: registrar!,withId: viewId, params: params) + } + + public func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol { + return FlutterStandardMessageCodec(readerWriter: FlutterStandardReaderWriter()) + } +} diff --git a/ios/Classes/SwiftFlutterQrPlugin.swift b/ios/Classes/SwiftFlutterQrPlugin.swift new file mode 100644 index 0000000..f26aff6 --- /dev/null +++ b/ios/Classes/SwiftFlutterQrPlugin.swift @@ -0,0 +1,22 @@ +import Flutter +import UIKit + +public class SwiftFlutterQrPlugin: NSObject, FlutterPlugin { + + var factory: QRViewFactory + public init(with registrar: FlutterPluginRegistrar) { + self.factory = QRViewFactory(withRegistrar: registrar) + registrar.register(factory, withId: "net.touchcapture.qr.flutterqr/qrview") + } + + public static func register(with registrar: FlutterPluginRegistrar) { + registrar.addApplicationDelegate(SwiftFlutterQrPlugin(with: registrar)) + } + + public func applicationDidEnterBackground(_ application: UIApplication) { + } + + public func applicationWillTerminate(_ application: UIApplication) { + } + +} diff --git a/ios/qr_code_scanner.podspec b/ios/qr_code_scanner.podspec new file mode 100644 index 0000000..f94e7cc --- /dev/null +++ b/ios/qr_code_scanner.podspec @@ -0,0 +1,23 @@ +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html +# + +Pod::Spec.new do |s| + s.name = 'qr_code_scanner' + s.version = '0.2.0' + s.summary = 'QR Code Scanner for flutter.' + s.description = <<-DESC +A new Flutter project. + DESC + s.homepage = 'https://github.com/juliuscanute/qr_code_scanner' + s.license = { :file => '../LICENSE' } + s.author = { 'Your Company' => 'juliuscanute[*]touchcapture.net' } + s.source = { :path => '.' } + s.source_files = 'Classes/**/*' + s.public_header_files = 'Classes/**/*.h' + s.dependency 'Flutter' + s.dependency 'MTBBarcodeScanner' + s.ios.deployment_target = '8.0' + s.swift_version = '4.0' +end + diff --git a/lib/qr_code_scanner.dart b/lib/qr_code_scanner.dart new file mode 100644 index 0000000..4220613 --- /dev/null +++ b/lib/qr_code_scanner.dart @@ -0,0 +1,7 @@ +export 'src/qr_code_scanner.dart'; +export 'src/qr_scanner_overlay_shape.dart'; +export 'src/types/barcode.dart'; +export 'src/types/barcode_format.dart'; +export 'src/types/camera.dart'; +export 'src/types/camera_exception.dart'; +export 'src/types/features.dart'; diff --git a/lib/src/lifecycle_event_handler.dart b/lib/src/lifecycle_event_handler.dart new file mode 100644 index 0000000..0580d17 --- /dev/null +++ b/lib/src/lifecycle_event_handler.dart @@ -0,0 +1,22 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; + +class LifecycleEventHandler extends WidgetsBindingObserver { + LifecycleEventHandler({ + required this.resumeCallBack, + }); + + late final AsyncCallback resumeCallBack; + + @override + Future didChangeAppLifecycleState(AppLifecycleState state) async { + switch (state) { + case AppLifecycleState.resumed: + await resumeCallBack(); + break; + case AppLifecycleState.inactive: + case AppLifecycleState.paused: + case AppLifecycleState.detached: + } + } +} diff --git a/lib/src/qr_code_scanner.dart b/lib/src/qr_code_scanner.dart new file mode 100644 index 0000000..0a1deb3 --- /dev/null +++ b/lib/src/qr_code_scanner.dart @@ -0,0 +1,373 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'lifecycle_event_handler.dart'; +import 'qr_scanner_overlay_shape.dart'; +import 'types/barcode.dart'; +import 'types/barcode_format.dart'; +import 'types/camera.dart'; +import 'types/camera_exception.dart'; +import 'types/features.dart'; +import 'web/flutter_qr_stub.dart' +// ignore: uri_does_not_exist + if (dart.library.html) 'web/flutter_qr_web.dart'; + +typedef QRViewCreatedCallback = void Function(QRViewController); +typedef PermissionSetCallback = void Function(QRViewController, bool); + +/// The [QRView] is the view where the camera +/// and the barcode scanner gets displayed. +class QRView extends StatefulWidget { + const QRView({ + required Key key, + required this.onQRViewCreated, + this.overlay, + this.overlayMargin = EdgeInsets.zero, + this.cameraFacing = CameraFacing.back, + this.onPermissionSet, + this.formatsAllowed = const [], + }) : super(key: key); + + /// [onQRViewCreated] gets called when the view is created + final QRViewCreatedCallback onQRViewCreated; + + /// Use [overlay] to provide an overlay for the view. + /// This can be used to create a certain scan area. + final QrScannerOverlayShape? overlay; + + /// Use [overlayMargin] to provide a margin to [overlay] + final EdgeInsetsGeometry overlayMargin; + + /// Set which camera to use on startup. + /// + /// [cameraFacing] can either be CameraFacing.front or CameraFacing.back. + /// Defaults to CameraFacing.back + final CameraFacing cameraFacing; + + /// Calls the provided [onPermissionSet] callback when the permission is set. + final PermissionSetCallback? onPermissionSet; + + /// Use [formatsAllowed] to specify which formats needs to be scanned. + final List formatsAllowed; + + @override + State createState() => _QRViewState(); +} + +class _QRViewState extends State { + late MethodChannel _channel; + late LifecycleEventHandler _observer; + + @override + void initState() { + super.initState(); + _observer = LifecycleEventHandler(resumeCallBack: updateDimensions); + WidgetsBinding.instance.addObserver(_observer); + } + + @override + Widget build(BuildContext context) { + return NotificationListener( + onNotification: onNotification, + child: SizeChangedLayoutNotifier( + child: (widget.overlay != null) + ? _getPlatformQrViewWithOverlay() + : _getPlatformQrView(), + ), + ); + } + + @override + void dispose() { + super.dispose(); + WidgetsBinding.instance.removeObserver(_observer); + } + + Future updateDimensions() async { + await QRViewController.updateDimensions( + widget.key as GlobalKey>, _channel, + overlay: widget.overlay); + } + + bool onNotification(notification) { + updateDimensions(); + return false; + } + + Widget _getPlatformQrViewWithOverlay() { + return Stack( + children: [ + _getPlatformQrView(), + Padding( + padding: widget.overlayMargin, + child: Container( + decoration: ShapeDecoration( + shape: widget.overlay!, + ), + ), + ) + ], + ); + } + + Widget _getPlatformQrView() { + Widget _platformQrView; + if (kIsWeb) { + _platformQrView = createWebQrView( + onPlatformViewCreated: widget.onQRViewCreated, + onPermissionSet: widget.onPermissionSet, + cameraFacing: widget.cameraFacing, + ); + } else { + switch (defaultTargetPlatform) { + case TargetPlatform.android: + _platformQrView = AndroidView( + viewType: 'net.touchcapture.qr.flutterqr/qrview', + onPlatformViewCreated: _onPlatformViewCreated, + creationParams: + _QrCameraSettings(cameraFacing: widget.cameraFacing).toMap(), + creationParamsCodec: const StandardMessageCodec(), + ); + break; + case TargetPlatform.iOS: + _platformQrView = UiKitView( + viewType: 'net.touchcapture.qr.flutterqr/qrview', + onPlatformViewCreated: _onPlatformViewCreated, + creationParams: + _QrCameraSettings(cameraFacing: widget.cameraFacing).toMap(), + creationParamsCodec: const StandardMessageCodec(), + ); + break; + default: + throw UnsupportedError( + "Trying to use the default qrview implementation for $defaultTargetPlatform but there isn't a default one"); + } + } + return _platformQrView; + } + + void _onPlatformViewCreated(int id) { + _channel = MethodChannel('net.touchcapture.qr.flutterqr/qrview_$id'); + + // Start scan after creation of the view + final controller = QRViewController._( + _channel, + widget.key as GlobalKey>?, + widget.onPermissionSet, + widget.cameraFacing) + .._startScan(widget.key as GlobalKey>, + widget.overlay, widget.formatsAllowed); + + // Initialize the controller for controlling the QRView + widget.onQRViewCreated(controller); + } +} + +class _QrCameraSettings { + _QrCameraSettings({ + this.cameraFacing = CameraFacing.unknown, + }); + + final CameraFacing cameraFacing; + + Map toMap() { + return { + 'cameraFacing': cameraFacing.index, + }; + } +} + +class QRViewController { + QRViewController._(MethodChannel channel, GlobalKey? qrKey, + PermissionSetCallback? onPermissionSet, CameraFacing cameraFacing) + : _channel = channel, + _cameraFacing = cameraFacing { + _channel.setMethodCallHandler((call) async { + switch (call.method) { + case 'onRecognizeQR': + if (call.arguments != null) { + final args = call.arguments as Map; + final code = args['code'] as String?; + final rawType = args['type'] as String; + // Raw bytes are only supported by Android. + final rawBytes = args['rawBytes'] as List?; + final format = BarcodeTypesExtension.fromString(rawType); + if (format != BarcodeFormat.unknown) { + final barcode = Barcode(code, format, rawBytes); + _scanUpdateController.sink.add(barcode); + } else { + throw Exception('Unexpected barcode type $rawType'); + } + } + break; + case 'onPermissionSet': + if (call.arguments != null && call.arguments is bool) { + _hasPermissions = call.arguments; + if (onPermissionSet != null) { + onPermissionSet(this, _hasPermissions); + } + } + break; + } + }); + } + + final MethodChannel _channel; + final CameraFacing _cameraFacing; + final StreamController _scanUpdateController = + StreamController(); + + Stream get scannedDataStream => _scanUpdateController.stream; + + bool _hasPermissions = false; + bool get hasPermissions => _hasPermissions; + + /// Starts the barcode scanner + Future _startScan(GlobalKey key, QrScannerOverlayShape? overlay, + List? barcodeFormats) async { + // We need to update the dimension before the scan is started. + try { + await QRViewController.updateDimensions(key, _channel, overlay: overlay); + return await _channel.invokeMethod( + 'startScan', barcodeFormats?.map((e) => e.asInt()).toList() ?? []); + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } + + /// Gets information about which camera is active. + Future getCameraInfo() async { + try { + var cameraFacing = await _channel.invokeMethod('getCameraInfo') as int; + if (cameraFacing == -1) return _cameraFacing; + return CameraFacing + .values[await _channel.invokeMethod('getCameraInfo') as int]; + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } + + /// Flips the camera between available modes + Future flipCamera() async { + try { + return CameraFacing + .values[await _channel.invokeMethod('flipCamera') as int]; + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } + + /// Get flashlight status + Future getFlashStatus() async { + try { + return await _channel.invokeMethod('getFlashInfo'); + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } + + /// Toggles the flashlight between available modes + Future toggleFlash() async { + try { + await _channel.invokeMethod('toggleFlash') as bool?; + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } + + /// Pauses the camera and barcode scanning + Future pauseCamera() async { + try { + await _channel.invokeMethod('pauseCamera'); + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } + + /// Stops barcode scanning and the camera + Future stopCamera() async { + try { + await _channel.invokeMethod('stopCamera'); + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } + + /// Resumes barcode scanning + Future resumeCamera() async { + try { + await _channel.invokeMethod('resumeCamera'); + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } + + /// Returns which features are available on device. + Future getSystemFeatures() async { + try { + var features = + await _channel.invokeMapMethod('getSystemFeatures'); + if (features != null) { + return SystemFeatures.fromJson(features); + } + throw CameraException('Error', 'Could not get system features'); + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } + + /// Stops the camera and disposes the barcode stream. + void dispose() { + if (defaultTargetPlatform == TargetPlatform.iOS) stopCamera(); + _scanUpdateController.close(); + } + + /// Updates the view dimensions for iOS. + static Future updateDimensions(GlobalKey key, MethodChannel channel, + {QrScannerOverlayShape? overlay}) async { + if (defaultTargetPlatform == TargetPlatform.iOS) { + // Add small delay to ensure the render box is loaded + await Future.delayed(const Duration(milliseconds: 300)); + if (key.currentContext == null) return false; + final renderBox = key.currentContext!.findRenderObject() as RenderBox; + try { + await channel.invokeMethod('setDimensions', { + 'width': renderBox.size.width, + 'height': renderBox.size.height, + 'scanAreaWidth': overlay?.cutOutWidth ?? 0, + 'scanAreaHeight': overlay?.cutOutHeight ?? 0, + 'scanAreaOffset': overlay?.cutOutBottomOffset ?? 0 + }); + return true; + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } else if (defaultTargetPlatform == TargetPlatform.android) { + if (overlay == null) { + return false; + } + await channel.invokeMethod('changeScanArea', { + 'scanAreaWidth': overlay.cutOutWidth, + 'scanAreaHeight': overlay.cutOutHeight, + 'cutOutBottomOffset': overlay.cutOutBottomOffset + }); + return true; + } + return false; + } + + //Starts/Stops invert scanning. + Future scanInvert(bool isScanInvert) async { + if (defaultTargetPlatform == TargetPlatform.android) { + try { + await _channel + .invokeMethod('invertScan', {"isInvertScan": isScanInvert}); + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } + } +} diff --git a/lib/src/qr_scanner_overlay_shape.dart b/lib/src/qr_scanner_overlay_shape.dart new file mode 100644 index 0000000..83fc5ef --- /dev/null +++ b/lib/src/qr_scanner_overlay_shape.dart @@ -0,0 +1,183 @@ +import 'dart:math'; + +import 'package:flutter/material.dart'; + +class QrScannerOverlayShape extends ShapeBorder { + QrScannerOverlayShape({ + this.borderColor = Colors.red, + this.borderWidth = 3.0, + this.overlayColor = const Color.fromRGBO(0, 0, 0, 80), + this.borderRadius = 0, + this.borderLength = 40, + double? cutOutSize, + double? cutOutWidth, + double? cutOutHeight, + this.cutOutBottomOffset = 0, + }) : cutOutWidth = cutOutWidth ?? cutOutSize ?? 250, + cutOutHeight = cutOutHeight ?? cutOutSize ?? 250 { + assert( + borderLength <= + min(this.cutOutWidth, this.cutOutHeight) / 2 + borderWidth * 2, + "Border can't be larger than ${min(this.cutOutWidth, this.cutOutHeight) / 2 + borderWidth * 2}", + ); + assert( + (cutOutWidth == null && cutOutHeight == null) || + (cutOutSize == null && cutOutWidth != null && cutOutHeight != null), + 'Use only cutOutWidth and cutOutHeight or only cutOutSize'); + } + + final Color borderColor; + final double borderWidth; + final Color overlayColor; + final double borderRadius; + final double borderLength; + final double cutOutWidth; + final double cutOutHeight; + final double cutOutBottomOffset; + + @override + EdgeInsetsGeometry get dimensions => const EdgeInsets.all(10); + + @override + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { + return Path() + ..fillType = PathFillType.evenOdd + ..addPath(getOuterPath(rect), Offset.zero); + } + + @override + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { + Path _getLeftTopPath(Rect rect) { + return Path() + ..moveTo(rect.left, rect.bottom) + ..lineTo(rect.left, rect.top) + ..lineTo(rect.right, rect.top); + } + + return _getLeftTopPath(rect) + ..lineTo( + rect.right, + rect.bottom, + ) + ..lineTo( + rect.left, + rect.bottom, + ) + ..lineTo( + rect.left, + rect.top, + ); + } + + @override + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { + final width = rect.width; + final borderWidthSize = width / 2; + final height = rect.height; + final borderOffset = borderWidth / 2; + final _borderLength = + borderLength > min(cutOutHeight, cutOutHeight) / 2 + borderWidth * 2 + ? borderWidthSize / 2 + : borderLength; + final _cutOutWidth = + cutOutWidth < width ? cutOutWidth : width - borderOffset; + final _cutOutHeight = + cutOutHeight < height ? cutOutHeight : height - borderOffset; + + final backgroundPaint = Paint() + ..color = overlayColor + ..style = PaintingStyle.fill; + + final borderPaint = Paint() + ..color = borderColor + ..style = PaintingStyle.stroke + ..strokeWidth = borderWidth; + + final boxPaint = Paint() + ..color = borderColor + ..style = PaintingStyle.fill + ..blendMode = BlendMode.dstOut; + + final cutOutRect = Rect.fromLTWH( + rect.left + width / 2 - _cutOutWidth / 2 + borderOffset, + -cutOutBottomOffset + + rect.top + + height / 2 - + _cutOutHeight / 2 + + borderOffset, + _cutOutWidth - borderOffset * 2, + _cutOutHeight - borderOffset * 2, + ); + + canvas + ..saveLayer( + rect, + backgroundPaint, + ) + ..drawRect( + rect, + backgroundPaint, + ) + // Draw top right corner + ..drawRRect( + RRect.fromLTRBAndCorners( + cutOutRect.right - _borderLength, + cutOutRect.top, + cutOutRect.right, + cutOutRect.top + _borderLength, + topRight: Radius.circular(borderRadius), + ), + borderPaint, + ) + // Draw top left corner + ..drawRRect( + RRect.fromLTRBAndCorners( + cutOutRect.left, + cutOutRect.top, + cutOutRect.left + _borderLength, + cutOutRect.top + _borderLength, + topLeft: Radius.circular(borderRadius), + ), + borderPaint, + ) + // Draw bottom right corner + ..drawRRect( + RRect.fromLTRBAndCorners( + cutOutRect.right - _borderLength, + cutOutRect.bottom - _borderLength, + cutOutRect.right, + cutOutRect.bottom, + bottomRight: Radius.circular(borderRadius), + ), + borderPaint, + ) + // Draw bottom left corner + ..drawRRect( + RRect.fromLTRBAndCorners( + cutOutRect.left, + cutOutRect.bottom - _borderLength, + cutOutRect.left + _borderLength, + cutOutRect.bottom, + bottomLeft: Radius.circular(borderRadius), + ), + borderPaint, + ) + ..drawRRect( + RRect.fromRectAndRadius( + cutOutRect, + Radius.circular(borderRadius), + ), + boxPaint, + ) + ..restore(); + } + + @override + ShapeBorder scale(double t) { + return QrScannerOverlayShape( + borderColor: borderColor, + borderWidth: borderWidth, + overlayColor: overlayColor, + ); + } +} diff --git a/lib/src/types/barcode.dart b/lib/src/types/barcode.dart new file mode 100644 index 0000000..c8c3105 --- /dev/null +++ b/lib/src/types/barcode.dart @@ -0,0 +1,16 @@ +import 'barcode_format.dart'; + +/// The [Barcode] object holds information about the barcode or qr code. +/// +/// [code] is the string-content of the barcode. +/// [format] displays which type the code is. +/// Only for Android and iOS, [rawBytes] gives a list of bytes of the result. +class Barcode { + Barcode(this.code, this.format, this.rawBytes); + + final String? code; + final BarcodeFormat format; + + /// Raw bytes are only supported by Android and iOS. + final List? rawBytes; +} diff --git a/lib/src/types/barcode_format.dart b/lib/src/types/barcode_format.dart new file mode 100644 index 0000000..49bcee2 --- /dev/null +++ b/lib/src/types/barcode_format.dart @@ -0,0 +1,148 @@ +enum BarcodeFormat { + /// Aztec 2D barcode format. + aztec, + + /// CODABAR 1D format. + /// Not supported in iOS + codabar, + + /// Code 39 1D format. + code39, + + /// Code 93 1D format. + code93, + + /// Code 128 1D format. + code128, + + /// Data Matrix 2D barcode format. + dataMatrix, + + /// EAN-8 1D format. + ean8, + + /// EAN-13 1D format. + ean13, + + /// ITF (Interleaved Two of Five) 1D format. + itf, + + /// MaxiCode 2D barcode format. + /// Not supported in iOS. + maxicode, + + /// PDF417 format. + pdf417, + + /// QR Code 2D barcode format. + qrcode, + + /// RSS 14 + /// Not supported in iOS. + rss14, + + /// RSS EXPANDED + /// Not supported in iOS. + rssExpanded, + + /// UPC-A 1D format. + /// Same as ean-13 on iOS. + upcA, + + /// UPC-E 1D format. + upcE, + + /// UPC/EAN extension format. Not a stand-alone format. + upcEanExtension, + + /// Unknown + unknown +} + +extension BarcodeTypesExtension on BarcodeFormat { + int asInt() { + return index; + } + + static BarcodeFormat fromString(String format) { + switch (format) { + case 'AZTEC': + return BarcodeFormat.aztec; + case 'CODABAR': + return BarcodeFormat.codabar; + case 'CODE_39': + return BarcodeFormat.code39; + case 'CODE_93': + return BarcodeFormat.code93; + case 'CODE_128': + return BarcodeFormat.code128; + case 'DATA_MATRIX': + return BarcodeFormat.dataMatrix; + case 'EAN_8': + return BarcodeFormat.ean8; + case 'EAN_13': + return BarcodeFormat.ean13; + case 'ITF': + return BarcodeFormat.itf; + case 'MAXICODE': + return BarcodeFormat.maxicode; + case 'PDF_417': + return BarcodeFormat.pdf417; + case 'QR_CODE': + return BarcodeFormat.qrcode; + case 'RSS14': + return BarcodeFormat.rss14; + case 'RSS_EXPANDED': + return BarcodeFormat.rssExpanded; + case 'UPC_A': + return BarcodeFormat.upcA; + case 'UPC_E': + return BarcodeFormat.upcE; + case 'UPC_EAN_EXTENSION': + return BarcodeFormat.upcEanExtension; + default: + return BarcodeFormat.unknown; + } + } + + String get formatName { + switch (this) { + case BarcodeFormat.aztec: + return 'AZTEC'; + case BarcodeFormat.codabar: + return 'CODABAR'; + case BarcodeFormat.code39: + return 'CODE_39'; + case BarcodeFormat.code93: + return 'CODE_93'; + case BarcodeFormat.code128: + return 'CODE_128'; + case BarcodeFormat.dataMatrix: + return 'DATA_MATRIX'; + case BarcodeFormat.ean8: + return 'EAN_8'; + case BarcodeFormat.ean13: + return 'EAN_13'; + case BarcodeFormat.itf: + return 'ITF'; + case BarcodeFormat.maxicode: + return 'MAXICODE'; + case BarcodeFormat.pdf417: + return 'PDF_417'; + case BarcodeFormat.qrcode: + return 'QR_CODE'; + case BarcodeFormat.rss14: + return 'RSS14'; + case BarcodeFormat.rssExpanded: + return 'RSS_EXPANDED'; + case BarcodeFormat.upcA: + return 'UPC_A'; + case BarcodeFormat.upcE: + return 'UPC_E'; + case BarcodeFormat.upcEanExtension: + return 'UPC_EAN_EXTENSION'; + default: + return 'UNKNOWN'; + } + } +} diff --git a/lib/src/types/camera.dart b/lib/src/types/camera.dart new file mode 100644 index 0000000..67fe8cb --- /dev/null +++ b/lib/src/types/camera.dart @@ -0,0 +1,10 @@ +enum CameraFacing { + /// Shows back facing camera. + back, + + /// Shows front facing camera. + front, + + /// Unknown camera + unknown +} diff --git a/lib/src/types/camera_exception.dart b/lib/src/types/camera_exception.dart new file mode 100644 index 0000000..0abb639 --- /dev/null +++ b/lib/src/types/camera_exception.dart @@ -0,0 +1,14 @@ +/// This is thrown when the plugin reports an error. +class CameraException implements Exception { + /// Creates a new camera exception with the given error code and description. + CameraException(this.code, this.description); + + /// Error code. + String code; + + /// Textual description of the error. + String? description; + + @override + String toString() => 'CameraException($code, $description)'; +} diff --git a/lib/src/types/features.dart b/lib/src/types/features.dart new file mode 100644 index 0000000..0c3618a --- /dev/null +++ b/lib/src/types/features.dart @@ -0,0 +1,13 @@ +class SystemFeatures { + SystemFeatures(this.hasFlash, this.hasBackCamera, this.hasFrontCamera); + + factory SystemFeatures.fromJson(Map features) => + SystemFeatures( + features['hasFlash'] ?? false, + features['hasBackCamera'] ?? false, + features['hasFrontCamera'] ?? false); + + final bool hasFlash; + final bool hasFrontCamera; + final bool hasBackCamera; +} diff --git a/lib/src/web/flutter_qr_stub.dart b/lib/src/web/flutter_qr_stub.dart new file mode 100644 index 0000000..a6bc04d --- /dev/null +++ b/lib/src/web/flutter_qr_stub.dart @@ -0,0 +1,6 @@ +import 'package:flutter/material.dart'; +import 'package:qr_code_scanner/src/types/camera.dart'; + +Widget createWebQrView( + {onPlatformViewCreated, onPermissionSet, CameraFacing? cameraFacing}) => + const SizedBox(); diff --git a/lib/src/web/flutter_qr_web.dart b/lib/src/web/flutter_qr_web.dart new file mode 100644 index 0000000..de368ac --- /dev/null +++ b/lib/src/web/flutter_qr_web.dart @@ -0,0 +1,334 @@ +// ignore_for_file: avoid_web_libraries_in_flutter + +import 'dart:async'; +import 'dart:core'; +import 'dart:html' as html; +import 'dart:js_util'; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; + +import '../../qr_code_scanner.dart'; +import 'jsqr.dart'; +import 'media.dart'; + +/// Even though it has been highly modified, the origial implementation has been +/// adopted from https://github.com:treeder/jsqr_flutter +/// +/// Copyright 2020 @treeder +/// Copyright 2021 The one with the braid + +class WebQrView extends StatefulWidget { + final QRViewCreatedCallback onPlatformViewCreated; + final PermissionSetCallback? onPermissionSet; + final CameraFacing? cameraFacing; + + const WebQrView( + {Key? key, + required this.onPlatformViewCreated, + this.onPermissionSet, + this.cameraFacing = CameraFacing.front}) + : super(key: key); + + @override + _WebQrViewState createState() => _WebQrViewState(); + + static html.DivElement vidDiv = + html.DivElement(); // need a global for the registerViewFactory + + static Future cameraAvailable() async { + final sources = + await html.window.navigator.mediaDevices!.enumerateDevices(); + // List vidIds = []; + var hasCam = false; + for (final e in sources) { + if (e.kind == 'videoinput') { + // vidIds.add(e['deviceId']); + hasCam = true; + } + } + return hasCam; + } +} + +class _WebQrViewState extends State { + html.MediaStream? _localStream; + // html.CanvasElement canvas; + // html.CanvasRenderingContext2D ctx; + bool _currentlyProcessing = false; + + QRViewControllerWeb? _controller; + + late Size _size = const Size(0, 0); + Timer? timer; + String? code; + String? _errorMsg; + html.VideoElement video = html.VideoElement(); + String viewID = 'QRVIEW-' + DateTime.now().millisecondsSinceEpoch.toString(); + + final StreamController _scanUpdateController = + StreamController(); + late CameraFacing facing; + + Timer? _frameIntervall; + + @override + void initState() { + super.initState(); + + facing = widget.cameraFacing ?? CameraFacing.front; + + // video = html.VideoElement(); + WebQrView.vidDiv.children = [video]; + // ignore: UNDEFINED_PREFIXED_NAME + ui.platformViewRegistry + .registerViewFactory(viewID, (int id) => WebQrView.vidDiv); + // giving JavaScipt some time to process the DOM changes + Timer(const Duration(milliseconds: 500), () { + start(); + }); + } + + Future start() async { + await _makeCall(); + _frameIntervall?.cancel(); + _frameIntervall = + Timer.periodic(const Duration(milliseconds: 200), (timer) { + _captureFrame2(); + }); + } + + void cancel() { + if (timer != null) { + timer!.cancel(); + timer = null; + } + if (_currentlyProcessing) { + _stopStream(); + } + } + + @override + void dispose() { + cancel(); + super.dispose(); + } + + // Platform messages are asynchronous, so we initialize in an async method. + Future _makeCall() async { + if (_localStream != null) { + return; + } + + try { + var constraints = UserMediaOptions( + video: VideoOptions( + facingMode: (facing == CameraFacing.front ? 'user' : 'environment'), + )); + // dart style, not working properly: + // var stream = + // await html.window.navigator.mediaDevices.getUserMedia(constraints); + // straight JS: + if (_controller == null) { + _controller = QRViewControllerWeb(this); + widget.onPlatformViewCreated(_controller!); + } + var stream = await promiseToFuture(getUserMedia(constraints)); + widget.onPermissionSet?.call(_controller!, true); + _localStream = stream; + video.srcObject = _localStream; + video.setAttribute('playsinline', + 'true'); // required to tell iOS safari we don't want fullscreen + await video.play(); + } catch (e) { + cancel(); + if (e.toString().contains("NotAllowedError")) { + widget.onPermissionSet?.call(_controller!, false); + } + setState(() { + _errorMsg = e.toString(); + }); + return; + } + if (!mounted) return; + + setState(() { + _currentlyProcessing = true; + }); + } + + Future _stopStream() async { + try { + // await _localStream.dispose(); + _localStream!.getTracks().forEach((track) { + if (track.readyState == 'live') { + track.stop(); + } + }); + // video.stop(); + video.srcObject = null; + _localStream = null; + // _localRenderer.srcObject = null; + // ignore: empty_catches + } catch (e) {} + } + + Future _captureFrame2() async { + if (_localStream == null) { + return null; + } + final canvas = + html.CanvasElement(width: video.videoWidth, height: video.videoHeight); + final ctx = canvas.context2D; + // canvas.width = video.videoWidth; + // canvas.height = video.videoHeight; + ctx.drawImage(video, 0, 0); + final imgData = ctx.getImageData(0, 0, canvas.width!, canvas.height!); + + final size = + Size(canvas.width?.toDouble() ?? 0, canvas.height?.toDouble() ?? 0); + if (size != _size) { + setState(() { + _setCanvasSize(size); + }); + } + + try { + final code = jsQR(imgData.data, canvas.width, canvas.height); + // ignore: unnecessary_null_comparison + if (code != null && code.data != null) { + _scanUpdateController + .add(Barcode(code.data, BarcodeFormat.qrcode, code.data.codeUnits)); + } + } on NoSuchMethodError { + // Do nothing, this exception occurs continously in web release when no + // code is found. + // NoSuchMethodError: method not found: 'get$data' on null + } + } + + @override + Widget build(BuildContext context) { + if (_errorMsg != null) { + return Center(child: Text(_errorMsg!)); + } + if (_localStream == null) { + return const Center(child: CircularProgressIndicator()); + } + return LayoutBuilder( + builder: (context, constraints) { + var zoom = 1.0; + + if (_size.height != 0) zoom = constraints.maxHeight / _size.height; + + if (_size.width != 0) { + final horizontalZoom = constraints.maxWidth / _size.width; + if (horizontalZoom > zoom) { + zoom = horizontalZoom; + } + } + + return SizedBox( + width: constraints.maxWidth, + height: constraints.maxHeight, + child: Center( + child: SizedBox.fromSize( + size: _size, + child: Transform.scale( + alignment: Alignment.center, + scale: zoom, + child: HtmlElementView(viewType: viewID), + ), + ), + ), + ); + }, + ); + } + + void _setCanvasSize(ui.Size size) { + setState(() { + _size = size; + }); + } +} + +class QRViewControllerWeb implements QRViewController { + final _WebQrViewState _state; + + QRViewControllerWeb(this._state); + @override + void dispose() => _state.cancel(); + + @override + Future flipCamera() async { + // TODO: improve error handling + _state.facing = _state.facing == CameraFacing.front + ? CameraFacing.back + : CameraFacing.front; + await _state.start(); + return _state.facing; + } + + @override + Future getCameraInfo() async { + return _state.facing; + } + + @override + Future getFlashStatus() async { + // TODO: flash is simply not supported by JavaScipt. To avoid issuing applications, we always return it to be off. + return false; + } + + @override + Future getSystemFeatures() { + // TODO: implement getSystemFeatures + throw UnimplementedError(); + } + + @override + // TODO: implement hasPermissions. Blocking: WebQrView.cameraAvailable() returns a Future whereas a bool is required + bool get hasPermissions => throw UnimplementedError(); + + @override + Future pauseCamera() { + // TODO: implement pauseCamera + throw UnimplementedError(); + } + + @override + Future resumeCamera() { + // TODO: implement resumeCamera + throw UnimplementedError(); + } + + @override + Stream get scannedDataStream => _state._scanUpdateController.stream; + + @override + Future stopCamera() { + // TODO: implement stopCamera + throw UnimplementedError(); + } + + @override + Future toggleFlash() async { + // TODO: flash is simply not supported by JavaScipt + return; + } + + @override + Future scanInvert(bool isScanInvert) { + // TODO: implement scanInvert + throw UnimplementedError(); + } +} + +Widget createWebQrView( + {onPlatformViewCreated, onPermissionSet, CameraFacing? cameraFacing}) => + WebQrView( + onPlatformViewCreated: onPlatformViewCreated, + onPermissionSet: onPermissionSet, + cameraFacing: cameraFacing, + ); diff --git a/lib/src/web/jsqr.dart b/lib/src/web/jsqr.dart new file mode 100644 index 0000000..386936c --- /dev/null +++ b/lib/src/web/jsqr.dart @@ -0,0 +1,12 @@ +@JS() +library jsqr; + +import 'package:js/js.dart'; + +@JS('jsQR') +external Code jsQR(var data, int? width, int? height); + +@JS() +class Code { + external String get data; +} diff --git a/lib/src/web/media.dart b/lib/src/web/media.dart new file mode 100644 index 0000000..cacd527 --- /dev/null +++ b/lib/src/web/media.dart @@ -0,0 +1,36 @@ +// This is here because dart doesn't seem to support this properly +// https://stackoverflow.com/questions/61161135/adding-support-for-navigator-mediadevices-getusermedia-to-dart + +@JS('navigator.mediaDevices') +library media_devices; + +import 'package:js/js.dart'; + +@JS('getUserMedia') +external Future getUserMedia(UserMediaOptions constraints); + +@JS() +@anonymous +class UserMediaOptions { + external VideoOptions get video; + + external factory UserMediaOptions({VideoOptions? video}); +} + +@JS() +@anonymous +class VideoOptions { + external String get facingMode; + // external DeviceIdOptions get deviceId; + + external factory VideoOptions( + {String? facingMode, DeviceIdOptions? deviceId}); +} + +@JS() +@anonymous +class DeviceIdOptions { + external String get exact; + + external factory DeviceIdOptions({String? exact}); +} diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..72f21cb --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,31 @@ +name: qr_code_scanner +description: QR code scanner that can be embedded inside flutter. It uses zxing in Android and MTBBarcode scanner in iOS. +version: 1.0.0 +homepage: https://juliuscanute.com +repository: https://github.com/juliuscanute/qr_code_scanner + +environment: + sdk: '>=2.17.0 <3.0.0' + flutter: ">=1.12.0" + +dependencies: + js: ^0.6.3 + flutter: + sdk: flutter + flutter_web_plugins: + sdk: flutter + +dev_dependencies: + flutter_lints: ^1.0.4 + +flutter: + plugin: + platforms: + android: + package: net.touchcapture.qr.flutterqr + pluginClass: FlutterQrPlugin + ios: + pluginClass: FlutterQrPlugin +# web: +# pluginClass: FlutterQrPlugin +# fileName: flutter_qr_web.dart