scan_utils.dart 2.31 KB
import 'package:flutter/material.dart';

import 'dart:async';
import 'package:flutter/services.dart';

import 'package:flutter_barcode_scanner_ohos/flutter_barcode_scanner_ohos.dart';
import 'package:one_key/utils/dialog_util.dart';
import 'package:one_key/utils/misc.dart';
import 'package:permission_handler/permission_handler.dart';

class ScanUtils {
  static Future<bool> requestCamera() async {
    var status = await Permission.camera.status;
    if (!status.isGranted) {
      var result = await Permission.camera.request();
      if (result.isGranted) {
        // 权限被用户允许
        print('Permission granted');
        return true;
      } else {
        // 权限被用户拒绝
        print('Permission denied');

        return false;
      }
    } else {
      // 权限已经授权
      print('Permission already granted');
      return true;
    }
  }

  static Future<String> scanQR(BuildContext context) async {
    // 获取权限状态
    bool result = await requestCamera();
    String? barcodeScanRes;
    if (result) {
      // Platform messages may fail, so we use a try/catch PlatformException.
      try {
        barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
            '#ff6666', '取消', true, ScanMode.qr);
        print(barcodeScanRes);
      } on PlatformException {
        barcodeScanRes = 'Failed to get platform version.';
      }
    } else {
      // 提示用户打开相机权限
      // 打开系统设置页面
      // openAppSettings();
      //  String title = Platform.isIOS ? '相册' : Platform.isAndroid ?'存储':'图片和视频';
      String title = '相机';
      // //用户选择不在弹出权限提示框
      // print('never');
      // // Navigator.pop(context);
      DialogUtil.openAlertDialog(
          context, '未获得${title}权限', "请在手机的权限管理里,将${title}权限开启", '去设置', 340.0,
          onTap: () {
        openSetting();
        Navigator.pop(context, '');
      });
    }
    return barcodeScanRes ?? '';

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    // if (!mounted) return;

    // setState(() {
    //   _scanBarcode = barcodeScanRes;
    // });
  }
}