cpd_2022_zi/lib/widgets/scanner.dart

86 lines
2.7 KiB
Dart

import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:flutter/material.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:provider/provider.dart';
import 'package:smoke_cess_app/models/settings.dart';
import 'package:smoke_cess_app/services/json_service.dart';
import 'package:smoke_cess_app/services/settings_service.dart';
import 'package:smoke_cess_app/widgets/buttons/text_icon_button.dart';
import '../providers/settings_provider.dart';
import '../services/notification_service.dart';
class MyScanner extends StatelessWidget {
const MyScanner({super.key});
@override
Widget build(BuildContext context) {
SettingsProvider settingsProvider = context.watch<SettingsProvider>();
void handleSucces(String? rawValue) {
String qrText = rawValue!;
Map<String, dynamic> json = stringToJSON(qrText);
Settings settings = Settings.fromJson(json);
saveSettings(settings);
settingsProvider.initSettings();
NotificationService().setAllNotifications();
settingsProvider.scanning = false;
AwesomeDialog(
context: context,
dialogType: DialogType.success,
title: 'Geschafft',
desc: 'Der Code wurde erfolgreich gescannt!',
).show();
}
void handleError() {
settingsProvider.scanning = false;
AwesomeDialog(
context: context,
dialogType: DialogType.error,
title: 'Fehler',
desc: 'Der QR-Code war fehlerhaft!',
).show();
}
void onDetect(capture) {
try {
final List<Barcode> barcodes = capture.barcodes;
for (final barcode in barcodes) {
if (barcode.rawValue != null) {
return handleSucces(barcode.rawValue);
}
}
} catch (e) {
handleError();
}
}
return settingsProvider.scanning
? Expanded(
child: Stack(
alignment: Alignment.center,
children: [
MobileScanner(
fit: BoxFit.contain,
controller: MobileScannerController(
detectionTimeoutMs: 2000,
),
onDetect: onDetect,
),
ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
height: MediaQuery.of(context).size.height / 3,
width: MediaQuery.of(context).size.width * 0.8,
color: Colors.white.withOpacity(0.4))),
],
))
: TextIconButton(
text: "Scan",
onPressed: () => settingsProvider.scanning = true,
iconData: Icons.qr_code_scanner_outlined);
}
}