Skip to content

Instantly share code, notes, and snippets.

@shingo-mori
Last active April 12, 2024 04:15
Show Gist options
  • Save shingo-mori/ee01c9fe4da0e171c52e2678577243fa to your computer and use it in GitHub Desktop.
Save shingo-mori/ee01c9fe4da0e171c52e2678577243fa to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart' as widgets;
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_integration_sample/scan_bloc.dart';
class ScanView extends StatefulWidget {
@override
State<StatefulWidget> createState() => _ScanViewState();
}
class _ScanViewState extends State<ScanView> with WidgetsBindingObserver {
final ScanBloc _bloc = ScanBloc();
bool _isPermissionGranted = false;
@override
void initState() {
super.initState();
_ambiguate(WidgetsBinding.instance)?.addObserver(this);
// カメラのアクセス権限を確認
_checkPermission();
_bloc.singleScanResult.listen((scannedData) {
// 以下を任意のビジネスロジックに変更して下さい
// _bloc.enableBarcodeCapture()を呼び出す事でスキャンが再開されます
showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Scan Result'),
content: SingleChildScrollView(
child: Text(scannedData),
),
actions: <Widget>[
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
_bloc.enableBarcodeCapture();
},
),
],
);
},
);
});
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_checkPermission();
} else if (state == AppLifecycleState.paused) {
_bloc.switchCameraOff();
}
}
@override
void dispose() {
_bloc.dispose();
_ambiguate(WidgetsBinding.instance)?.removeObserver(this);
super.dispose();
}
@override
Widget build(BuildContext context) {
Widget child;
if (!_isPermissionGranted) {
child = Text('No permission to access the camera!',
style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: Colors.black));
} else {
child = _bloc.captureView;
}
return WillPopScope(
child: SizedBox.fromSize(
child: child,
size: widgets.Size(MediaQuery.of(context).size.width, MediaQuery.of(context).size.height * 1),
),
onWillPop: () {
dispose();
return Future.value(true);
});
}
void _checkPermission() async {
Permission.camera.request().isGranted.then((value) => setState(() {
_isPermissionGranted = value;
_bloc.switchCameraOn();
_bloc.enableBarcodeCapture();
}));
}
T? _ambiguate<T>(T? value) => value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment