barcode_scanner_analyze_image.dart
1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
class BarcodeScannerAnalyzeImage extends StatefulWidget {
const BarcodeScannerAnalyzeImage({super.key});
@override
State<BarcodeScannerAnalyzeImage> createState() =>
_BarcodeScannerAnalyzeImageState();
}
class _BarcodeScannerAnalyzeImageState
extends State<BarcodeScannerAnalyzeImage> {
final MobileScannerController _controller = MobileScannerController();
BarcodeCapture? _barcodeCapture;
Future<void> _analyzeImageFromFile() async {
try {
final XFile? file =
await ImagePicker().pickImage(source: ImageSource.gallery);
if (!mounted || file == null) {
return;
}
final BarcodeCapture? barcodeCapture =
await _controller.analyzeImage(file.path);
if (mounted) {
setState(() {
_barcodeCapture = barcodeCapture;
});
}
} catch (_) {}
}
@override
Widget build(BuildContext context) {
Widget label = const Text('Pick a file to detect barcode');
if (_barcodeCapture != null) {
label = Text(
_barcodeCapture?.barcodes.firstOrNull?.displayValue ??
'No barcode detected',
);
}
return Scaffold(
appBar: AppBar(title: const Text('Analyze image from file')),
body: Column(
children: [
Expanded(
child: Center(
child: ElevatedButton(
onPressed: kIsWeb ? null : _analyzeImageFromFile,
child: kIsWeb
? const Text('Analyze image is not supported on web')
: const Text('Choose file'),
),
),
),
Expanded(child: Center(child: label)),
],
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}