Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'package:flutter/material.dart';
- import 'package:mobile_scanner/mobile_scanner.dart';
- void main() {
- runApp(const MyApp());
- }
- class MyApp extends StatelessWidget {
- const MyApp({super.key});
- // This widget is the root of your application.
- @override
- Widget build(BuildContext context) {
- return const MaterialApp(
- title: 'SN scanner Demo',
- home: MyHomePage(),
- );
- }
- }
- class MyHomePage extends StatefulWidget {
- const MyHomePage({super.key});
- @override
- State<MyHomePage> createState() => _MyHomePageState();
- }
- class _MyHomePageState extends State<MyHomePage> {
- ValueNotifier<String> snFound = ValueNotifier('');
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- body: Stack(
- children: [
- SnScanner(
- onSnFound: (sn) {
- print('********** SN found: $sn');
- snFound.value = sn;
- },
- ),
- ValueListenableBuilder(
- valueListenable: snFound,
- builder: (_, sn, __) {
- return Align(
- alignment: Alignment.bottomCenter,
- child: Text(
- sn,
- textScaleFactor: 2,
- style: const TextStyle(backgroundColor: Colors.white54),
- ),
- );
- },
- ),
- ],
- ),
- );
- }
- }
- class SnScanner extends StatelessWidget {
- final Function(String sn)? onSnFound;
- const SnScanner({Key? key, this.onSnFound})
- : super(key: key);
- @override
- Widget build(BuildContext context) {
- MobileScannerController cameraController = MobileScannerController();
- return Scaffold(
- appBar: AppBar(
- title: const Text('Mobile Scanner'),
- actions: [
- IconButton(
- color: Colors.white,
- icon: ValueListenableBuilder(
- valueListenable: cameraController.torchState,
- builder: (context, state, child) {
- switch (state as TorchState) {
- case TorchState.off:
- return const Icon(Icons.flash_off, color: Colors.grey);
- case TorchState.on:
- return const Icon(Icons.flash_on, color: Colors.yellow);
- }
- },
- ),
- iconSize: 32.0,
- onPressed: () => cameraController.toggleTorch(),
- ),
- IconButton(
- color: Colors.white,
- icon: ValueListenableBuilder(
- valueListenable: cameraController.cameraFacingState,
- builder: (context, state, child) {
- switch (state as CameraFacing) {
- case CameraFacing.front:
- return const Icon(Icons.camera_front);
- case CameraFacing.back:
- return const Icon(Icons.camera_rear);
- }
- },
- ),
- iconSize: 32.0,
- onPressed: () => cameraController.switchCamera(),
- ),
- ],
- ),
- body: MobileScanner(
- allowDuplicates: false,
- controller: cameraController,
- onDetect: (barcode, args) {
- if (barcode.rawValue == null) {
- } else {
- final String code = barcode.rawValue!;
- if (onSnFound != null && _validateSn(code)) {
- onSnFound!(code);
- }
- }
- }));
- }
- bool _validateSn(String sn) {
- return sn.isNotEmpty && sn.startsWith('S') && sn.length == 13;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement