Mobile Development9 min read
Flutter QR Code Scanner in 20 Minutes
Add a QR code scanner to your Flutter app in 20 minutes with mobile_scanner: camera setup, permissions, torch control, gallery scanning and result handling.
- #flutter
- #qr-code
- #scanner
- #mobile-scanner
- #camera

QR codes are on menus, tickets, payment terminals, and product packaging, so a scanner is one of the most requested features in client apps. Building one from scratch means wiring the camera, decoding frames, and handling permissions on two platforms. The mobile_scanner package already does all three, and this guide turns it into a complete scanner screen in about 20 minutes: a live camera preview, one-time result handling, torch and camera controls, scanning from the photo gallery, and the security checks that keep a scanned code from opening something dangerous. By the end you will have a reusable ScannerScreen widget you can drop into any Flutter app. The code targets current stable Flutter and Dart, decodes entirely on the device with no network call, and needs no native code of your own — only the camera permission entries in the Android manifest and the iOS Info.plist. The same screen also pairs well with QR generation, covered in the guide to building a secure QR medical profile in Flutter.
Why use mobile_scanner for QR scanning in Flutter?
Use mobile_scanner because it is the maintained QR and barcode scanning package for Flutter, it decodes on the device with no network call, and it works on Android and iOS from one API. The older qr_code_scanner package is no longer maintained, and the camera plugin alone gives you a preview with no barcode decoding, so you would have to ship a decoder yourself. mobile_scanner wraps Google ML Kit barcode scanning on Android and AVFoundation on iOS, so the same widget reads QR codes, Aztec, Data Matrix, EAN, and Code 128 without extra setup. Decoding runs on the device, which means a scanned code never leaves the phone until your own code decides what to do with it.
| Approach | What you get | When to use it |
|---|---|---|
| mobile_scanner | Camera preview plus decoding in one widget | Almost always: the fastest path to a working scanner |
| camera plugin plus a decoder | Full control over the camera pipeline | You need custom frame processing, such as feeding frames to your own ML model |
| qr_code_scanner | An older scanning widget | Do not use it for new apps: it is no longer maintained |
Step 1: add the package and the camera permission
Add three packages to pubspec.yaml: mobile_scanner for the scanner itself, image_picker for gallery scanning later in this guide, and url_launcher for safely opening scanned links.
dependencies:
flutter:
sdk: flutter
mobile_scanner: ^7.0.0
image_picker: ^1.1.0
url_launcher: ^6.3.0
Then declare the camera permission. On Android, add the permission inside AndroidManifest.xml, before the application tag:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
On iOS, add the camera usage description to Info.plist, plus the photo library description for the gallery step:
<key>NSCameraUsageDescription</key>
<string>This app uses the camera to scan QR codes.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This app lets you pick a photo containing a QR code to scan it.</string>
The manifest entry and the Info.plist key only declare the permission. The operating system still asks the user the first time the camera opens, so the scanner screen must handle a denial gracefully — the errorBuilder in Step 2 covers that.
Step 2: build the scanner screen
The scanner screen is one StatefulWidget with a MobileScannerController and a MobileScanner widget. The controller owns the camera session, and onDetect receives a BarcodeCapture every time a code is found. Two settings matter from the start: detectionSpeed set to noDuplicates, which suppresses repeat callbacks for the same code, and formats restricted to BarcodeFormat.qrCode, so a barcode on a product behind the code does not trigger a result.
import 'package:flutter/material.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
class ScannerScreen extends StatefulWidget {
const ScannerScreen({super.key});
@override
State<ScannerScreen> createState() => _ScannerScreenState();
}
class _ScannerScreenState extends State<ScannerScreen> {
final MobileScannerController _controller = MobileScannerController(
detectionSpeed: DetectionSpeed.noDuplicates,
formats: const [BarcodeFormat.qrCode],
);
bool _handled = false;
void _onDetect(BarcodeCapture capture) {
if (_handled) return;
if (capture.barcodes.isEmpty) return;
final String? code = capture.barcodes.first.rawValue;
if (code == null || code.isEmpty) return;
_handled = true;
_controller.stop();
if (!mounted) return;
Navigator.of(context).pop(code);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Scan QR code')),
body: MobileScanner(
controller: _controller,
onDetect: _onDetect,
errorBuilder: (context, error) {
return const Center(
child: Text(
'Camera access is off. Enable the camera for this app in system settings to scan QR codes.',
),
);
},
),
);
}
}
Show the scanner with a normal route and await the popped value:
final String? result = await Navigator.of(context).push<String>(
MaterialPageRoute(builder: (_) => const ScannerScreen()),
);
if (result != null) {
// Validate the value before using it: see the security section below.
}
When the camera permission is denied, MobileScanner calls errorBuilder instead of showing a preview. The example above shows a plain message; in a production app, add a button that explains where to enable the camera in system settings.
Step 3: handle the result exactly once
onDetect fires for every camera frame that contains a readable code, so a naive handler navigates or pops the route many times in a row. The fix has three parts, and all three are in the code above: set detectionSpeed to noDuplicates, guard the callback with a _handled flag, and stop the controller after the first result. Returning the value with Navigator.pop keeps the scanner dumb and reusable — the calling screen decides whether the value is a URL to open, an ID to look up, or text to display. Keep the validation in the caller, never inside the scanner, so the same screen works for every feature that needs a scan.
Step 4: add torch and camera controls
Two buttons cover the controls users expect: a torch for dark rooms and a camera switch for front-facing scans. Both are one-line calls on the controller, and the controller exposes listenables so the icons always reflect the real state:
IconButton(
onPressed: () => _controller.toggleTorch(),
icon: ValueListenableBuilder<TorchState>(
valueListenable: _controller.torchState,
builder: (context, state, child) {
return Icon(state == TorchState.on ? Icons.flash_on : Icons.flash_off);
},
),
),
IconButton(
onPressed: () => _controller.switchCamera(),
icon: const Icon(Icons.cameraswitch),
),
Wrap the torch button in a ValueListenableBuilder on _controller.torchState so the icon flips between flash on and flash off. On devices without a torch, the state reports unavailable, so check for that value before showing the button. Place both buttons in a row over the preview with a Stack, or in the AppBar if you prefer the preview untouched.
Step 5: scan a QR code from the gallery
Users often receive a QR code as a screenshot or a saved photo, so a good scanner also reads from the gallery. The controller's analyzeImage method decodes a single image file with the same engine as the live camera, so no second package is needed:
Future<void> _scanFromGallery() async {
final XFile? image =
await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return;
final BarcodeCapture? capture = await _controller.analyzeImage(image.path);
if (capture == null || capture.barcodes.isEmpty) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No QR code found in this image')),
);
return;
}
final String? code = capture.barcodes.first.rawValue;
if (code == null || code.isEmpty) return;
if (!mounted) return;
Navigator.of(context).pop(code);
}
Call _scanFromGallery from a gallery button on the scanner screen. When analyzeImage finds no code, show a short message instead of popping the route, so the user can try another photo.
How do I limit scanning to a small area on screen?
Restrict detection with the scanWindow parameter, which takes a rectangle in the widget's coordinate space. Draw a matching frame on top of the preview so users know where to aim:
final Size size = MediaQuery.of(context).size;
MobileScanner(
controller: _controller,
scanWindow: Rect.fromCenter(
center: Offset(size.width / 2, size.height / 2),
width: 260,
height: 260,
),
onDetect: _onDetect,
)
A scan window also speeds up detection slightly, because the decoder ignores everything outside the rectangle. Keep the window large enough for a phone held at arm's length — around 260 by 260 logical pixels works on most screens.
Common problems and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Black preview on first open | Camera permission denied | Add the manifest and Info.plist entries, and show a message through errorBuilder |
| The same code fires many times | onDetect runs once per frame | Use DetectionSpeed.noDuplicates, a handled flag, and stop the controller |
| Nothing scans in a dark room | Not enough light on the code | Offer the torch button from Step 4 |
| A product barcode triggers a result | The default formats include all barcode types | Restrict formats to BarcodeFormat.qrCode |
| Crash after leaving the screen | The controller was never disposed | Call _controller.dispose in the State dispose method |
| Build error on iOS | Missing camera usage description | Add NSCameraUsageDescription to Info.plist |
What should you never do with a scanned QR code?
Never trust a scanned value. A QR code is just text printed as squares, and anyone can print one that points to a phishing page, a payment link, or a Wi-Fi network that harvests credentials. Treat every scanned value as untrusted input: show it to the user, validate it, and only then act on it. For links, parse with Uri.tryParse and allow only http and https schemes before launching:
Future<void> _openScannedValue(String value) async {
final uri = Uri.tryParse(value);
if (uri == null || (uri.scheme != 'https' && uri.scheme != 'http')) {
// Not a web link: show the text instead of opening it.
return;
}
await launchUrl(uri, mode: LaunchMode.externalApplication);
}
Never auto-join a Wi-Fi network, auto-dial a number, or auto-send a payment from a scanned code. If the value is not a web link, display it as text and let the user decide. The guide to the Flutter camera plugin covers the lower-level camera setup if you later need full control over the preview, and the secure QR medical profile guide shows the other direction: generating QR codes that carry signed, verifiable data instead of plain text. A QR scanner is a small feature with an outsized effect on how complete an app feels, and mobile_scanner keeps it to one widget and one controller. Add the screen, test it with a printed code in a dim room, and ship it. Get in touch and let's talk about your project.
Frequently asked questions
- How do I add a QR code scanner to Flutter?
- Add the mobile_scanner package, declare the camera permission in AndroidManifest.xml and NSCameraUsageDescription in Info.plist, then show a MobileScanner widget driven by a MobileScannerController and handle the result in onDetect.
- Why does my Flutter QR scanner fire multiple times for one code?
- onDetect runs for every camera frame that contains the code. Use DetectionSpeed.noDuplicates, guard the callback with a handled flag, and stop the controller after the first result.
- Can I scan a QR code from a photo in the gallery?
- Yes. Pick the image with image_picker and pass its path to controller.analyzeImage, which returns a BarcodeCapture with the decoded barcodes or an empty list when no code is found.
- Is it safe to open any QR code a user scans?
- No. A QR code can hold any text, including a phishing link. Parse the value with Uri.tryParse, allow only http and https, and show the value to the user before opening it.


