Pub :
webview_flutter: ^3.0.4
qr_code_scanner: ^1.0.1
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:webview_flutter/webview_flutter.dart';
class QRViewExample extends StatefulWidget {
@override
QRViewExampleState createState() => QRViewExampleState();
}
class QRViewExampleState extends State<QRViewExample> {
final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
Barcode? result;
QRViewController? controller;
bool isScanning = true; // Track if scanning is active or stopped
@override
void reassemble() {
super.reassemble();
if (Platform.isAndroid) {
controller!.pauseCamera();
} else if (Platform.isIOS) {
controller!.resumeCamera();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Expanded(
flex: 5,
child: QRView(
key: qrKey,
onQRViewCreated: _onQRViewCreated,
),
),
Expanded(
flex: 1,
child: Center(
child: (result != null)
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Barcode Type: ${describeEnum(result!.format)} Data: ${result!.code}',
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
setState(() {
result = null; // Reset result to trigger scanning again
isScanning = true; // Set scanning to active
});
},
child: Text('Retry Scan'),
),
],
)
: Text('Scan a code'),
),
),
],
),
);
}
void _onQRViewCreated(QRViewController controller) {
this.controller = controller;
controller.scannedDataStream.listen((scanData) {
setState(() {
result = scanData;
// Check if scanning is active and scanned content is a URL
if (isScanning && result != null && Uri.tryParse(result!.code!) != null) {
_openWebView(result!.code!);
// Stop scanning after successful scan
isScanning = false;
}
});
});
}
void _openWebView(String url) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => Scaffold(
appBar: AppBar(
title: Text('Web View'),
),
body: WebView(
initialUrl: url,
javascriptMode: JavascriptMode.unrestricted,
),
),
),
);
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
}