ソースコード source code

下記アプリの主要なソースコードを公開しています。アプリ開発の参考になれば幸いです。

画像等が別途必要ですので下記情報のみでアプリが完成するものではありません。 アプリは少しずつ機能拡張していますのでストア公開されているアプリと内容が異なる場合があります。 コードはコピーして自由にお使いいただけます。ただし著作権は放棄しておりませんので全部の再掲載はご遠慮ください。部分的に再掲載したり、改変して再掲載するのは構いません。 自身のアプリ作成の参考として個人使用・商用問わず自由にお使いいただけます。 コード記述のお手本を示すものではありません。ミニアプリですので変数名などさほど気遣いしていない部分も有りますし間違いも有るかと思いますので参考程度にお考え下さい。 他の賢者の皆様が公開されているコードを参考にした箇所も含まれます。Androidアプリ開発の熟練者が書いたコードではありません。 エンジニア向け技術情報共有サービスではありませんので説明は省いています。ご了承ください。 GitHubなどへの公開は予定しておりません。

下記コードの最終ビルド日: 2025-11-11

name: barcodereader
description: "barcodereader"
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 2.7.2+44

environment:
  sdk: ^3.9.2

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  mobile_scanner: ^7.0.1
  shared_preferences: ^2.0.15
  flutter_toastr: ^1.0.3
  url_launcher: ^6.1.5
  share_plus: ^12.0.0
  google_mobile_ads: ^6.0.0
  provider: ^6.0.3
  clipboard: ^2.0.2
  intl: ^0.20.2
  audioplayers: ^6.0.0

dev_dependencies:
  flutter_test:
    sdk: flutter

  flutter_launcher_icons: ^0.14.4    #flutter pub run flutter_launcher_icons
  flutter_native_splash: ^2.3.5     #flutter pub run flutter_native_splash:create

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^6.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

flutter_icons:
  android: "launcher_icon"
  ios: true
  image_path: "assets/icon/icon.png"
  adaptive_icon_background: "assets/icon/icon_back.png"
  adaptive_icon_foreground: "assets/icon/icon_fore.png"

flutter_native_splash:
  color: '#9da9f5'
  image: 'assets/image/splash.png'
  color_dark: '#9da9f5'
  image_dark: 'assets/image/splash.png'
  fullscreen: true
  android_12:
    icon_background_color: '#9da9f5'
    image: 'assets/image/splash.png'
    icon_background_color_dark: '#9da9f5'
    image_dark: 'assets/image/splash.png'

# The following section is specific to Flutter packages.
flutter:
  generate: true # Add this line

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  assets:
    - assets/image/
    - assets/sound/

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/to/resolution-aware-images

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/to/asset-from-package

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/to/font-from-package
import 'package:flutter/cupertino.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'package:barcodereader/ad_manager.dart';

class AdBannerWidget extends StatefulWidget {
  final AdManager adManager;
  const AdBannerWidget({super.key, required this.adManager});
  @override
  State<AdBannerWidget> createState() => _AdBannerWidgetState();
}

class _AdBannerWidgetState extends State<AdBannerWidget> {
  int _lastBannerWidthDp = 0;
  bool _isAdLoaded = false;
  bool _isLoading = false;
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: LayoutBuilder(
        builder: (context, constraints) {
          final int width = constraints.maxWidth.isFinite ? constraints.maxWidth.truncate() : MediaQuery.of(context).size.width.truncate();
          final bannerAd = widget.adManager.bannerAd;
          if (width > 0) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (mounted) {
                final bannerAd = widget.adManager.bannerAd;
                final bool widthChanged = _lastBannerWidthDp != width;
                final bool sizeMismatch = bannerAd == null || bannerAd.size.width != width;
                if ((widthChanged || !_isAdLoaded || sizeMismatch) && !_isLoading) {
                  _lastBannerWidthDp = width;
                  setState(() { _isAdLoaded = false; _isLoading = true; });
                  widget.adManager.loadAdaptiveBannerAd(width, () {
                    if (mounted) {
                      setState(() { _isAdLoaded = true; _isLoading = false; });
                    }
                  });
                }
              }
            });
          }
          if (_isAdLoaded && bannerAd != null) {
            return const SizedBox.shrink();
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(height: 10),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SizedBox(
                      width: bannerAd.size.width.toDouble(),
                      height: bannerAd.size.height.toDouble(),
                      child: AdWidget(ad: bannerAd),
                    ),
                  ],
                )
              ]
            );
          } else {
            return const SizedBox.shrink();
          }
        },
      ),
    );
  }
}
/*
 *	mainへの記述
 *	void main() async {
 *		WidgetsFlutterBinding.ensureInitialized();
 *		if (!kIsWeb) {
 *			//AdMob初期化
 *			MobileAds.instance.initialize();
 *			//NPAポリシーの集中設定(将来拡張もここで) 現時点は使用していないので記述しなくても良い
 *			await AdManager.initForNPA();
 *		}
 *		runApp(const MyApp());
 *	}
 */

import 'dart:async';
import 'dart:io' show Platform;
import 'dart:ui';

import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:google_mobile_ads/google_mobile_ads.dart';

class AdManager {
  //Test IDs
  //static const String _androidAdUnitId = "ca-app-pub-3940256099942544/6300978111";
  //static const String _iosAdUnitId     = "ca-app-pub-3940256099942544/2934735716";

  //Production IDs
  static const String _androidAdUnitId = "ca-app-pub-0/0";
  static const String _iosAdUnitId     = "ca-app-pub-0/0";

  static String get _adUnitId => Platform.isIOS ? _iosAdUnitId : _androidAdUnitId;

  BannerAd? _bannerAd;
  int _lastWidthPx = 0;
  VoidCallback? _onLoadedCb;
  Timer? _retryTimer;
  int _retryAttempt = 0;

  BannerAd? get bannerAd => _bannerAd;

  //(任意)アプリ起動時などに呼ぶ。将来のCMP/NPA関連設定を集中管理。
  static Future<void> initForNPA() async {
    if (kIsWeb) {
      return;
    }
    //ここでグローバルなRequestConfigurationを設定しておく(必要に応じて拡張)
    await MobileAds.instance.updateRequestConfiguration(
      RequestConfiguration(
        //例:最大コンテンツレーティング等を付けたい場合はここに追加
        //maxAdContentRating: MaxAdContentRating.g,	//例
        //tagForChildDirectedTreatment: TagForChildDirectedTreatment.unspecified,
        //tagForUnderAgeOfConsent: TagForUnderAgeOfConsent.unspecified,
      ),
    );
  }

  Future<void> loadAdaptiveBannerAd(
    int widthPx,
    VoidCallback onAdLoaded,
  ) async {
    if (kIsWeb) {
      return;
    }
    _onLoadedCb = onAdLoaded;
    _lastWidthPx = widthPx;
    _retryAttempt = 0;
    _retryTimer?.cancel();
    _startLoad(widthPx);
  }

  Future<void> _startLoad(int widthPx) async {
    if (kIsWeb) {
      return;
    }
    _bannerAd?.dispose();

    AnchoredAdaptiveBannerAdSize? adaptiveSize;
    try {
      adaptiveSize =
          await AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(
            widthPx,
          );
    } catch (_) {
      adaptiveSize = null;
    }
    final AdSize size = adaptiveSize ?? AdSize.fullBanner;

    //常にNPAで配信(CMP対応)
    const adRequest = AdRequest(
      nonPersonalizedAds: true,	//NPA Non-Personalized Ads(非パーソナライズ広告)指定
    );

    _bannerAd = BannerAd(
      adUnitId: _adUnitId,
      request: adRequest,
      size: size,
      listener: BannerAdListener(
        onAdLoaded: (ad) {
          _retryTimer?.cancel();
          _retryAttempt = 0;
          final cb = _onLoadedCb;
          if (cb != null) {
            cb();
          }
        },
        onAdFailedToLoad: (ad, err) {
          ad.dispose();
          _scheduleRetry();
        },
      ),
    )..load();
  }

  void _scheduleRetry() {
    if (kIsWeb) {
      return;
    }
    _retryTimer?.cancel();
    // Exponential backoff: 3s, 6s, 12s, max 30s
    _retryAttempt = (_retryAttempt + 1).clamp(1, 5);
    final seconds = _retryAttempt >= 4 ? 30 : (3 << (_retryAttempt - 1));
    _retryTimer = Timer(Duration(seconds: seconds), () {
      _startLoad(_lastWidthPx > 0 ? _lastWidthPx : 320);
    });
  }

  void dispose() {
    _bannerAd?.dispose();
    _retryTimer?.cancel();
  }
}

/*
広告配信について
本アプリでは、Google AdMob を利用して広告を表示しています。
当アプリの広告はすべて「非パーソナライズ広告(NPA)」として配信しており、ユーザーの行動履歴や個人情報をもとにしたパーソナライズは一切行っていません。
Google AdMob によって、広告の表示のために以下の情報が利用される場合があります:
- 端末情報(例:OSの種類、画面サイズなど)
- おおまかな位置情報(国・地域レベル)
これらの情報は、パーソナライズを目的としたトラッキングやプロファイリングには使用されません。
詳しくは、Google のプライバシーポリシーをご覧ください:
https://policies.google.com/privacy


Advertising
This app uses Google AdMob to display advertisements.
All ads in this app are served as non-personalized ads (NPA).
This means that we do not use personal data or user behavior information to personalize the ads you see.
Google AdMob may use certain information in order to display ads properly, such as:
- Device information (e.g., OS type, screen size)
- Approximate location information (country/region level)
This information is not used for tracking or profiling for advertising purposes.
For more details, please refer to Google Privacy Policy:
https://policies.google.com/privacy
*/
/*
  CMP(Consent Management Platform)「同意管理プラットフォーム」
  UMP とは、Google AdMobでGDPRの同意を取得するために使用されるライブラリ User Messaging Platform (UMP) SDK

  ad_manager.dart で NPA Non-Personalized Ads(非パーソナライズ広告)指定 している。

  必要な変数
  late final UmpConsentController _adUmp;
  AdUmpState _adUmpState = AdUmpState.initial;

  @override
  void initState() {
    super.initState();
    _adUmp = UmpConsentController();
    _refreshConsentInfo();
  }

  必要な関数
  Future<void> _refreshConsentInfo() async {
    _adUmpState = await _adUmp.updateConsentInfo(current: _adUmpState);
    if (mounted) {
      setState(() {});
    }
  }
  Future<void> _onTapPrivacyOptions() async {
    final err = await _adUmp.showPrivacyOptions();
    await _refreshConsentInfo();
    if (err != null && mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('プライバシー設定画面を表示できませんでした: ${err.message}')),
      );
    }
  }
 */

import 'dart:async';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:flutter/widgets.dart';
import 'package:barcodereader/l10n/app_localizations.dart';

/// UMP状態格納用
class AdUmpState {
  final PrivacyOptionsRequirementStatus privacyStatus;
  final ConsentStatus consentStatus;
  final bool privacyOptionsRequired;
  final bool isChecking;
  const AdUmpState({
    required this.privacyStatus,
    required this.consentStatus,
    required this.privacyOptionsRequired,
    required this.isChecking,
  });

  AdUmpState copyWith({
    PrivacyOptionsRequirementStatus? privacyStatus,
    ConsentStatus? consentStatus,
    bool? privacyOptionsRequired,
    bool? isChecking,
  }) {
    return AdUmpState(
      privacyStatus: privacyStatus ?? this.privacyStatus,
      consentStatus: consentStatus ?? this.consentStatus,
      privacyOptionsRequired:
          privacyOptionsRequired ?? this.privacyOptionsRequired,
      isChecking: isChecking ?? this.isChecking,
    );
  }

  static const initial = AdUmpState(
    privacyStatus: PrivacyOptionsRequirementStatus.unknown,
    consentStatus: ConsentStatus.unknown,
    privacyOptionsRequired: false,
    isChecking: false,
  );
}

//UMPコントローラ
class UmpConsentController {
  //デバッグ用:EEA地域を強制するか(本番ではfalseにすること)
  final bool forceEeaForDebug = false;
  //埋め込みのテストデバイスID
  static const List<String> _testDeviceIds = [
    '608970392F100B87D62A1174996C952C', //arrows We2 (M07)
  ];

  ConsentRequestParameters _buildParams() {
    if (forceEeaForDebug && _testDeviceIds.isNotEmpty) {
      return ConsentRequestParameters(
        consentDebugSettings: ConsentDebugSettings(
          debugGeography: DebugGeography.debugGeographyEea,
          testIdentifiers: _testDeviceIds,
        ),
      );
    }
    return ConsentRequestParameters();
  }

  //同意情報を更新して状態を返す
  Future<AdUmpState> updateConsentInfo(
      {AdUmpState current = AdUmpState.initial}) async {
    if (kIsWeb) return current;
    var state = current.copyWith(isChecking: true);

    try {
      final params = _buildParams();
      final completer = Completer<AdUmpState>();

      ConsentInformation.instance.requestConsentInfoUpdate(
        params,
        () async {
          final s = await ConsentInformation.instance
              .getPrivacyOptionsRequirementStatus();
          final c = await ConsentInformation.instance.getConsentStatus();
          completer.complete(
            state.copyWith(
              privacyStatus: s,
              consentStatus: c,
              privacyOptionsRequired:
                  s == PrivacyOptionsRequirementStatus.required,
              isChecking: false,
            ),
          );
        },
        (FormError e) {
          completer.complete(
            state.copyWith(
              privacyStatus: PrivacyOptionsRequirementStatus.unknown,
              consentStatus: ConsentStatus.unknown,
              privacyOptionsRequired: false,
              isChecking: false,
            ),
          );
        },
      );

      state = await completer.future;
      return state;
    } catch (_) {
      return state.copyWith(isChecking: false);
    }
  }

  //プライバシーオプションフォームを表示
  Future<FormError?> showPrivacyOptions() async {
    if (kIsWeb) return null;
    final completer = Completer<FormError?>();
    ConsentForm.showPrivacyOptionsForm((FormError? e) {
      completer.complete(e);
    });
    return completer.future;
  }
}

extension ConsentStatusL10n on ConsentStatus {
  String localized(BuildContext context) {
    final l = AppLocalizations.of(context)!;
    switch (this) {
      case ConsentStatus.obtained:
        return l.cmpConsentStatusObtained;
      case ConsentStatus.required:
        return l.cmpConsentStatusRequired;
      case ConsentStatus.notRequired:
        return l.cmpConsentStatusNotRequired;
      case ConsentStatus.unknown:
        return l.cmpConsentStatusUnknown;
    }
  }
}
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:share_plus/share_plus.dart';

import 'package:barcodereader/l10n/app_localizations.dart';
import 'package:barcodereader/scan_provider.dart';
import 'package:barcodereader/ad_manager.dart';
import 'package:barcodereader/ad_banner_widget.dart';

class HistoryPage extends StatefulWidget {
  const HistoryPage({super.key});
  @override
  State<HistoryPage> createState() => _HistoryPageState();
}

class _HistoryPageState extends State<HistoryPage> {
  final ScrollController _scrollController = ScrollController();
  late AdManager _adManager;

  @override
  void initState() {
    super.initState();
    _adManager = AdManager();
    // buildが完了した直後に実行
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 遅延させてからスクロールを実行
      Timer(const Duration(milliseconds: 50), _scrollToBottom);
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _adManager.dispose();
    super.dispose();
  }

  void _scrollToBottom() {
    // scrollControllerがListViewに紐付いていて、スクロール可能な場合
    if (_scrollController.hasClients) {
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final l = AppLocalizations.of(context)!;
    return Consumer<ScanProvider>(
      builder: (context, scanProvider, child) {
        // スキャン結果が空の場合の表示
        if (scanProvider.scanResults.isEmpty) {
          return Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.transparent,
              title: Text(l.history),
              centerTitle: true,
            ),
            body: Center(
              child: Text(l.noData),
            ),
            bottomNavigationBar: AdBannerWidget(adManager: _adManager),
          );
        }
        // スキャン結果をリスト表示
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.transparent,
            title: Text(l.history),
            centerTitle: true,
          ),
          body: SafeArea(
            child: ListView.builder(
              controller: _scrollController, // コントローラーを紐付け
              padding: const EdgeInsets.all(8.0),
              itemCount: scanProvider.scanResults.length,
              itemBuilder: (context, index) {
                // 古いものが上、新しいものが下になるようにそのままのindexを使用
                final result = scanProvider.scanResults[index];
                final parts = result.split(',');
                // データのパース
                final timestamp =
                    parts.isNotEmpty
                        ? parts[0]
                        : l.noDate;
                final format = parts.length > 1
                    ? parts[1].split('.').last
                    : l.unknownFormat;
                final content = parts.length > 2
                    ? parts.sublist(2).join(',')
                    : l.noContent;

                // デフォルトのテキストスタイルを取得
                final textTheme = Theme.of(context).textTheme;
                final titleStyle = textTheme.titleMedium;

                return Card(
                  margin: const EdgeInsets.symmetric(vertical: 4.0),
                  child: ListTile(
                    title: Text('$timestamp - $format'),
                    subtitle: Text(content, style: titleStyle),
                    onTap: () {
                      showDialog(
                        context: context,
                        builder: (context) => AlertDialog(
                          title: Text(content),
                          actions: <Widget>[
                            TextButton(
                              child: Text(l.sendAction),
                              onPressed: () {
                                Navigator.of(context).pop();
                                SharePlus.instance.share(ShareParams(text: content));
                              },
                            ),
                            TextButton(
                              child: Text(l.deleteAction),
                              onPressed: () {
                                Navigator.of(context).pop();
                                scanProvider.deleteScanResult(index);
                              },
                            ),
                            TextButton(
                              child: Text(l.cancel),
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                );
              },
            ),
          ),
          bottomNavigationBar: AdBannerWidget(adManager: _adManager),
        );
      },
    );
  }

}
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart';

import 'package:barcodereader/l10n/app_localizations.dart';
import 'package:barcodereader/ad_manager.dart';
import 'package:barcodereader/ad_banner_widget.dart';
import 'package:barcodereader/info_page.dart';
import 'package:barcodereader/history_page.dart';
import 'package:barcodereader/scan_provider.dart';
import 'package:barcodereader/scanner_page.dart';
import 'package:barcodereader/settings_page.dart';
import 'package:barcodereader/model.dart';
import 'package:barcodereader/loading_screen.dart';
import 'package:barcodereader/main.dart';
import 'package:barcodereader/parse_locale_tag.dart';
import 'package:barcodereader/theme_color.dart';
import 'package:barcodereader/theme_mode_number.dart';

class MainHomePage extends StatefulWidget {
  const MainHomePage({super.key});

  @override
  State<MainHomePage> createState() => _MainHomePageState();
}

class _MainHomePageState extends State<MainHomePage> {
  late AdManager _adManager;
  late ThemeColor _themeColor;
  bool _isReady = false;
  bool _isFirst = true;
  //
  final _textController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  late ScanProvider _scanProvider;
  VoidCallback? _settingsListener;
  bool _hasAutoStartedScan = false;
  //
  static const double _buttonHeight1 = 76.0;
  static const double _buttonHeight2 = 40.0;

  @override
  void initState() {
    super.initState();
    _initState();
  }

  void _initState() async {
    _adManager = AdManager();
    _scanProvider = context.read<ScanProvider>();
    _scanProvider.loadScanResults().then((_) {
      _updateTextField();
    });
    _scanProvider.addListener(_updateTextField);
    _settingsListener = _handleSettingsChanged;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _maybeStartScanOnLaunch();
    });
    if (mounted) {
      setState(() {
        _isReady = true;
      });
    }
  }

  @override
  void dispose() {
    _scanProvider.removeListener(_updateTextField);
    _textController.dispose();
    _scrollController.dispose();
    _adManager.dispose();
    super.dispose();
  }

  Future<void> _scanBarcode() async {
    await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => ScannerPage(
          onScan: (result) async {
            await _scanProvider.addScanResult(result);
          },
        ),
      ),
    );
  }

  void _handleSettingsChanged() {
    _maybeStartScanOnLaunch();
  }

  void _maybeStartScanOnLaunch() {
    if (_hasAutoStartedScan) {
      return;
    }
    if (!Model.startScanOnLaunch) {
      return;
    }
    _hasAutoStartedScan = true;
    if (_settingsListener != null) {
      _settingsListener = null;
    }
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        unawaited(_scanBarcode());
      }
    });
  }

  void _updateTextField() {
    _textController.text = _scanProvider.getFormattedResults();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  void _copyToClipboard(String text) {
    if (text.isEmpty) return;
    Clipboard.setData(ClipboardData(text: text));
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(AppLocalizations.of(context)!.copiedToClipboard),
        duration: const Duration(seconds: 1),
      ),
    );
  }

  void _shareText(String text) {
    if (text.isEmpty) {
      return;
    }
    SharePlus.instance.share(ShareParams(text: text));
  }

  void _launchUrlOrShare(String text) async {
    if (text.isEmpty) return;
    Uri uri;
    final parsedUri = Uri.tryParse(text);
    if (parsedUri != null &&
        (parsedUri.scheme == 'http' || parsedUri.scheme == 'https')) {
      uri = parsedUri;
    } else {
      uri = Uri.parse(
        'https://www.google.com/search?q=${Uri.encodeComponent(text)}',
      );
    }
    try {
      if (!await launchUrl(uri)) {
        if (!mounted) return;
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              AppLocalizations.of(context)!.couldNotLaunchBrowserFor(
                uri.toString(),
              ),
            ),
          ),
        );
      }
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(
        SnackBar(
          content: Text(
            AppLocalizations.of(context)!.errorLaunchingBrowser(
              e.toString(),
            ),
          ),
        ),
      );
    }
  }

  Future<bool> _showConfirmDialog(String title) async {
    return await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: Text(AppLocalizations.of(context)!.cancel),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: Text(AppLocalizations.of(context)!.ok),
          ),
        ],
      ),
    ) ??
    false;
  }

  Future<void> _showMessageDialog({String? title, required List<String> messages}) async {
    await showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        title: title != null ? Text(title) : null,
        content: messages.length == 1
          ? Text(messages.first)
          : Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              for (var i = 0; i < messages.length; i++)
                Padding(
                  padding: EdgeInsets.only(bottom: i == messages.length - 1 ? 0 : 8.0),
                  child: Text(messages[i]),
                ),
            ],
          ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text(AppLocalizations.of(context)!.ok),
          ),
        ],
      ),
    );
  }

  Future<void> _handleDeleteDuplicates() async {
    if (!await _showConfirmDialog(
      AppLocalizations.of(context)!.deleteDuplicatesConfirmation,
    )) {
      return;
    }
    final results = await _scanProvider.removeDuplicateScanResults();
    if (!mounted) {
      return;
    }
    if (results.isEmpty) {
      await _showMessageDialog(
        title: AppLocalizations.of(context)!.deleteDuplicates,
        messages: [AppLocalizations.of(context)!.noDuplicateDataFound],
      );
      return;
    }
    await _showMessageDialog(
      title: AppLocalizations.of(context)!.duplicateRemovalResultTitle,
      messages: results
        .map(
          (entry) => AppLocalizations.of(context)!.duplicateRemovalEntry(
            entry.removedCount,
            entry.data,
          ),
        )
        .toList(),
    );
  }

  Future<void> _onOpenSetting() async {
    final bool? updated = await Navigator.push<bool>(context,MaterialPageRoute(builder: (_) => const SettingPage()));
    if (!mounted) {
      return;
    }
    if (updated == true) {
      final mainState = context.findAncestorStateOfType<MainAppState>();
      if (mainState != null) {
        mainState
          ..themeMode = ThemeModeNumber.numberToThemeMode(Model.themeNumber)
          ..locale = parseLocaleTag(Model.languageCode)
          ..seedColor = HSVColor.fromAHSV(1,Model.colorHue.toDouble(),Model.colorSaturation,Model.colorBrightness).toColor()
          ..setState(() {});
      }
      _isFirst = true;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (_isReady == false) {
      return const LoadingScreen();
    }
    if (_isFirst) {
      _isFirst = false;
      _themeColor = ThemeColor(context: context);
    }
    final l = AppLocalizations.of(context)!;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: _themeColor.mainButtonColor2,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.info_outline),
            onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(builder: (context) => const InfoPage()),
            ),
          ),
          IconButton(
            icon: const Icon(Icons.list),
            onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(builder: (context) => const HistoryPage()),
            ),
          ),
          IconButton(
            icon: const Icon(Icons.settings),
            color: _themeColor.mainForeColor,
            tooltip: l.setting,
            onPressed: _onOpenSetting,
          ),
        ],
      ),
      body: SafeArea(
        child: Column(
          children: [
            const SizedBox(height: 1),
            _buildFullWidthButton(
              AppLocalizations.of(context)!.scan,
              _scanBarcode,
              backColor: _themeColor.mainButtonColor1,
              foreColor: _themeColor.mainForeColor,
              height: _buttonHeight1,
            ),
            const SizedBox(height: 1),
            _buildFullWidthButton(
              AppLocalizations.of(context)!.copy,
              () async {
                if (await _showConfirmDialog(
                  AppLocalizations.of(context)!.copyAll,
                )) {
                  _copyToClipboard(_scanProvider.toCsv());
                }
              },
              backColor: _themeColor.mainButtonColor2,
              foreColor: _themeColor.mainForeColor,
              height: _buttonHeight2,
            ),
            const SizedBox(height: 1),
            _buildFullWidthButton(
              AppLocalizations.of(context)!.send,
              () async {
                if (await _showConfirmDialog(
                  AppLocalizations.of(context)!.sendAll,
                )) {
                  _shareText(_scanProvider.toCsv());
                }
              },
              backColor: _themeColor.mainButtonColor2,
              foreColor: _themeColor.mainForeColor,
              height: _buttonHeight2,
            ),
            const SizedBox(height: 1),
            _buildFullWidthButton(
              AppLocalizations.of(context)!.deleteDuplicates,
              () {
                unawaited(_handleDeleteDuplicates());
              },
              backColor: _themeColor.mainButtonColor2,
              foreColor: _themeColor.mainForeColor,
              height: _buttonHeight2,
            ),
            const SizedBox(height: 1),
            _buildFullWidthButton(
              AppLocalizations.of(context)!.deleteAll,
              () async {
                if (await _showConfirmDialog(
                  AppLocalizations.of(context)!.deleteAll,
                )) {
                  _scanProvider.deleteAllScanResults();
                }
              },
              backColor: _themeColor.mainButtonColor2,
              foreColor: _themeColor.mainForeColor,
              height: _buttonHeight2,
            ),
            const SizedBox(height: 1),
            _buildFullWidthButton(
              AppLocalizations.of(context)!.copyLast,
              () => _copyToClipboard(_scanProvider.getLastScanContent()),
              backColor: _themeColor.mainButtonColor3,
              foreColor: _themeColor.mainForeColor,
              height: _buttonHeight2,
            ),
            const SizedBox(height: 1),
            _buildFullWidthButton(
              AppLocalizations.of(context)!.sendLast,
              () => _shareText(_scanProvider.getLastScanContent()),
              backColor: _themeColor.mainButtonColor3,
              foreColor: _themeColor.mainForeColor,
              height: _buttonHeight2,
            ),
            const SizedBox(height: 1),
            _buildFullWidthButton(
              AppLocalizations.of(context)!.browserLast,
              () => _launchUrlOrShare(_scanProvider.getLastScanContent()),
              backColor: _themeColor.mainButtonColor3,
              foreColor: _themeColor.mainForeColor,
              height: _buttonHeight2,
            ),
            const SizedBox(height: 1),
            _buildFullWidthButton(
              AppLocalizations.of(context)!.deleteLast,
              () async {
                if (await _showConfirmDialog(
                  AppLocalizations.of(context)!.deleteLastConfirmation,
                )) {
                  _scanProvider.deleteLastScanResult();
                }
              },
              backColor: _themeColor.mainButtonColor3,
              foreColor: _themeColor.mainForeColor,
              height: _buttonHeight2,
            ),
            const SizedBox(height: 1),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.only(left: 8, right: 8, top: 10, bottom: 0),
                child: Scrollbar(
                  controller: _scrollController,
                  thumbVisibility: true,
                  child: TextField(
                    controller: _textController,
                    scrollController: _scrollController,
                    readOnly: true,
                    maxLines: null,
                    expands: true,
                    textAlignVertical: TextAlignVertical.top,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      isDense: true,
                      contentPadding: EdgeInsets.zero,
                      filled: true,
                      fillColor: _themeColor.mainResultBackColor,
                    ),
                    style: const TextStyle(fontSize: 12.0),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
      bottomNavigationBar: AdBannerWidget(adManager: _adManager),
    );
  }

  Widget _buildFullWidthButton(
    String text,
    VoidCallback onPressed, {
      required Color backColor,
      required Color foreColor,
      required double height,
    }) {
    return Container(
      height: height,
      decoration: BoxDecoration(
        color: backColor,
      ),
      child: SizedBox.expand(
        child: TextButton(
          onPressed: onPressed,
          child: Text(text, style: TextStyle(color: foreColor))
        ),
      ),
    );
  }

}
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'package:barcodereader/l10n/app_localizations.dart';
import 'package:barcodereader/scan_provider.dart';
import 'package:barcodereader/ad_manager.dart';
import 'package:barcodereader/ad_banner_widget.dart';
import 'package:barcodereader/model.dart';
import 'package:barcodereader/theme_color.dart';

class InfoPage extends StatefulWidget {
  const InfoPage({super.key});
  @override
  State<InfoPage> createState() => _InfoPageState();
}

class _InfoPageState extends State<InfoPage> {
  late AdManager _adManager;
  late ThemeColor _themeColor;
  bool _isFirst = true;

  @override
  void initState() {
    super.initState();
    _adManager = AdManager();
  }

  @override
  void dispose() {
    _adManager.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isFirst) {
      _isFirst = false;
      _themeColor = ThemeColor(themeNumber: Model.themeNumber, context: context);
    }
    final l = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: _themeColor.backColor,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        title: Text(l.information),
        centerTitle: true,
      ),
      body: SafeArea(
        child: Consumer<ScanProvider>(
          builder: (context, scanProvider, child) {
            final results = scanProvider.scanResults;
            if (results.isEmpty) {
              return Center(
                child: Text(l.noData),
              );
            }
            final breakdown = _calculateBreakdown(results);
            return ListView(
              padding: const EdgeInsets.all(16.0),
              children: [
                _buildTotal(results.length),
                const Divider(height: 40),
                for (final entry in breakdown)
                  _buildEntry(entry.key, entry.value)
              ],
            );
          },
        ),
      ),
      bottomNavigationBar: AdBannerWidget(adManager: _adManager),
    );
  }

  List<MapEntry<String, int>> _calculateBreakdown(List<String> scanResults) {
    final counts = <String, int>{};
    for (final result in scanResults) {
      final parts = result.split(',');
      String format;
      if (parts.length >= 2) {
        final formatPart = parts[1];
        final normalizedFormat = formatPart.split('.').last;
        format = normalizedFormat.isEmpty ? 'unknown' : normalizedFormat;
      } else {
        format = 'unknown';
      }
      counts.update(format, (value) => value + 1, ifAbsent: () => 1);
    }
    final sortedEntries = counts.entries.toList()
      ..sort((a, b) {
        final countCompare = b.value.compareTo(a.value);
        if (countCompare != 0) {
          return countCompare;
        }
        return a.key.compareTo(b.key);
      });
    return sortedEntries;
  }

  Widget _buildTotal(int count) {
    return SizedBox(
      width: double.infinity,
      child: Card(
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
          child: Text('Total: $count', style: Theme.of(context).textTheme.titleLarge),
        )
      )
    );
  }

  Widget _buildEntry(String format, int count) {
    return SizedBox(
      width: double.infinity,
      child: Card(
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
          child: Text('$format: $count', style: Theme.of(context).textTheme.titleLarge),
        )
      )
    );
  }

}
import 'package:flutter/material.dart';

class LoadingScreen extends StatelessWidget {
  const LoadingScreen({super.key});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromRGBO(157,169,245,1),
      body: const Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(Colors.purpleAccent),
              backgroundColor: Colors.white,
            ),
            SizedBox(height: 16),
            Text(
              'Loading...',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'package:barcodereader/l10n/app_localizations.dart';
import 'package:barcodereader/model.dart';
import 'package:barcodereader/home_page.dart';
import 'package:barcodereader/theme_mode_number.dart';
import 'package:barcodereader/loading_screen.dart';
import 'package:barcodereader/parse_locale_tag.dart';
import 'package:barcodereader/scan_provider.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
  SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
    statusBarColor: Colors.transparent,
    systemNavigationBarColor: Colors.transparent,
  ));
  MobileAds.instance.initialize();
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => ScanProvider()),
      ],
      child: const MainApp(),
    ),
  );
}

class MainApp extends StatefulWidget {
  const MainApp({super.key});
  @override
  State<MainApp> createState() => MainAppState();
}

class MainAppState extends State<MainApp> {
  ThemeMode themeMode = ThemeMode.light;
  Locale? locale;
  bool _isReady = false;
  Color seedColor = Colors.purple;

  @override
  void initState() {
    super.initState();
    _initState();
  }

  void _initState() async {
    await Model.ensureReady();
    themeMode = ThemeModeNumber.numberToThemeMode(Model.themeNumber);
    locale = parseLocaleTag(Model.languageCode);
    setState(() {
      _isReady = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          body: Center(
            child: LoadingScreen(),
          ),
        ),
      );
    }
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
      locale: locale,
      themeMode: themeMode,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: seedColor),
        useMaterial3: true,
      ),
      darkTheme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: seedColor,
          brightness: Brightness.dark,
        ),
        useMaterial3: true,
      ),
      home: const MainHomePage(),
    );
  }
}
import 'package:shared_preferences/shared_preferences.dart';

class Model {

  static const String _prefContinuousScan = 'continuousScan';
  static const String _prefScanInterval = 'scanInterval';
  static const String _prefBeepOnScan = 'beepOnScan';
  static const String _prefFlashOnScan = 'flashOnScan';
  static const String _prefLockOrientation = 'lockOrientation';
  static const String _prefStartScanOnLaunch = 'startScanOnLaunch';
  static const String _prefSelectedBeepSound = 'selectedBeepSound';
  static const String _prefScanAreaRestrictionLevel = 'scanAreaRestrictionLevel';
  static const String _prefColorHue = 'colorHue';
  static const String _prefColorSaturation = 'colorSaturation';
  static const String _prefColorBrightness = 'colorBrightness';
  static const String _prefThemeNumber = 'themeNumber';
  static const String _prefLanguageCode = 'languageCode';

  static bool _ready = false;
  static bool _continuousScan = false;
  static double _scanInterval = 1.0;
  static int _scanAreaRestrictionLevel = 0;
  static bool _startScanOnLaunch = false;
  static bool _beepOnScan = true;
  static int _selectedBeepSound = 1;
  static bool _flashOnScan = true;
  static bool _lockOrientation = false;
  static int _colorHue = 250;
  static double _colorSaturation = 0.6;
  static double _colorBrightness = 1.0;
  static int _themeNumber = 0;
  static String _languageCode = '';

  static bool get continuousScan => _continuousScan;
  static double get scanInterval => _scanInterval;
  static int get scanAreaRestrictionLevel => _scanAreaRestrictionLevel;
  static bool get startScanOnLaunch => _startScanOnLaunch;
  static bool get beepOnScan => _beepOnScan;
  static int get selectedBeepSound => _selectedBeepSound;
  static bool get flashOnScan => _flashOnScan;
  static bool get lockOrientation => _lockOrientation;
  static int get colorHue => _colorHue;
  static double get colorSaturation => _colorSaturation;
  static double get colorBrightness => _colorBrightness;
  static int get themeNumber => _themeNumber;
  static String get languageCode => _languageCode;

  static Future<void> ensureReady() async {
    if (_ready) {
      return;
    }
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    //
    _continuousScan = prefs.getBool(_prefContinuousScan) ?? false;
    _scanInterval = prefs.getDouble(_prefScanInterval) ?? 1.0;
    _scanAreaRestrictionLevel = prefs.getInt(_prefScanAreaRestrictionLevel) ?? 0;
    _startScanOnLaunch = prefs.getBool(_prefStartScanOnLaunch) ?? false;
    _beepOnScan = prefs.getBool(_prefBeepOnScan) ?? true;
    _selectedBeepSound = prefs.getInt(_prefSelectedBeepSound) ?? 1;
    _flashOnScan = prefs.getBool(_prefFlashOnScan) ?? true;
    _lockOrientation = prefs.getBool(_prefLockOrientation) ?? false;
    _colorHue = (prefs.getInt(_prefColorHue) ?? 250).clamp(0, 360);
    _colorSaturation = (prefs.getDouble(_prefColorSaturation) ?? 0.6).clamp(0.0, 1.0);
    _colorBrightness = (prefs.getDouble(_prefColorBrightness) ?? 1.0).clamp(0.0, 1.0);
    _themeNumber = (prefs.getInt(_prefThemeNumber) ?? 0).clamp(0, 2);
    _languageCode = prefs.getString(_prefLanguageCode) ?? '';
    _ready = true;
  }

  static Future<void> setContinuousScan(bool value) async {
    _continuousScan = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_prefContinuousScan, value);
  }

  static Future<void> setScanInterval(double value) async {
    _scanInterval = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setDouble(_prefScanInterval, value);
  }

  static Future<void> setScanAreaRestrictionLevel(int value) async {
    _scanAreaRestrictionLevel = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefScanAreaRestrictionLevel, value);
  }

  static Future<void> setStartScanOnLaunch(bool value) async {
    _startScanOnLaunch = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_prefStartScanOnLaunch, value);
  }

  static Future<void> setBeepOnScan(bool value) async {
    _beepOnScan = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_prefBeepOnScan, value);
  }

  static Future<void> setSelectedBeepSound(int value) async {
    _selectedBeepSound = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefSelectedBeepSound, value);
  }

  static Future<void> setFlashOnScan(bool value) async {
    _flashOnScan = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_prefFlashOnScan, value);
  }

  static Future<void> setLockOrientation(bool value) async {
    _lockOrientation = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_prefLockOrientation, value);
  }

  static Future<void> setColorHue(int value) async {
    _colorHue = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefColorHue, value);
  }

  static Future<void> setColorSaturation(double value) async {
    _colorSaturation = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setDouble(_prefColorSaturation, value);
  }

  static Future<void> setColorBrightness(double value) async {
    _colorBrightness = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setDouble(_prefColorBrightness, value);
  }

  static Future<void> setThemeNumber(int value) async {
    _themeNumber = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefThemeNumber, value);
  }

  static Future<void> setLanguageCode(String value) async {
    _languageCode = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefLanguageCode, value);
  }

}
import 'dart:ui';

Locale? parseLocaleTag(String tag) {
  if (tag.isEmpty) {
    return null;
  }
  final parts = tag.split('-');
  final language = parts[0];
  String? script, country;
  if (parts.length >= 2) {
    parts[1].length == 4 ? script = parts[1] : country = parts[1];
  }
  if (parts.length >= 3) {
    parts[2].length == 4 ? script = parts[2] : country = parts[2];
  }
  return Locale.fromSubtags(
    languageCode: language,
    scriptCode: script,
    countryCode: country,
  );
}
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class DuplicateRemovalEntry {
  const DuplicateRemovalEntry({required this.data, required this.removedCount});

  final String data;
  final int removedCount;
}

class ScanProvider extends ChangeNotifier {
  List<String> _scanResults = [];
  static const String _scanResultsKey = 'scan_results';
  List<String> get scanResults => _scanResults;

  Future<void> loadScanResults() async {
    final prefs = await SharedPreferences.getInstance();
    _scanResults = prefs.getStringList(_scanResultsKey) ?? [];
    notifyListeners();
  }

  Future<void> addScanResult(String result) async {
    _scanResults.add(result);
    await _saveResults();
  }

  Future<void> deleteScanResult(int index) async {
    if (index >= 0 && index < _scanResults.length) {
      _scanResults.removeAt(index);
      await _saveResults();
    }
  }

  Future<void> deleteLastScanResult() async {
    if (_scanResults.isNotEmpty) {
      _scanResults.removeLast();
      await _saveResults();
    }
  }

  Future<void> deleteAllScanResults() async {
    _scanResults.clear();
    await _saveResults();
  }

  Future<List<DuplicateRemovalEntry>> removeDuplicateScanResults() async {
    final seenKeys = <String>{};
    final removalCounts = <String, int>{};
    final displayTexts = <String, String>{};
    final indexesToRemove = <int>[];

    for (var i = 0; i < _scanResults.length; i++) {
      final entry = _scanResults[i];
      final parts = entry.split(',');

      final hasContent = parts.length >= 3;
      final format = hasContent ? parts[1] : '';
      final content = hasContent ? parts.sublist(2).join(',') : entry;
      final key = hasContent ? '$format::$content' : entry;

      displayTexts.putIfAbsent(key, () => content);

      if (!seenKeys.add(key)) {
        removalCounts.update(key, (value) => value + 1, ifAbsent: () => 1);
        indexesToRemove.add(i);
      }
    }

    if (indexesToRemove.isEmpty) {
      return const <DuplicateRemovalEntry>[];
    }

    indexesToRemove.sort((a, b) => b.compareTo(a));
    for (final index in indexesToRemove) {
      _scanResults.removeAt(index);
    }

    await _saveResults();

    return removalCounts.entries
        .map(
          (entry) => DuplicateRemovalEntry(
            data: displayTexts[entry.key] ?? entry.key,
            removedCount: entry.value,
          ),
        )
        .toList();
  }

  Future<void> _saveResults() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setStringList(_scanResultsKey, _scanResults);
    notifyListeners();
  }

  String getFormattedResults() {
    return _scanResults.map((res) {
      final parts = res.split(',');
      if (parts.length >= 2) {
        parts[1] = parts[1].split('.').last;
        return parts.join(',');
      }
      return res;
    }).join('\n');
  }

  String getLastScanContent() {
    if (_scanResults.isEmpty) return '';
    final parts = _scanResults.last.split(',');
    if (parts.length >= 3) {
      return parts.sublist(2).join(',');
    }
    return _scanResults.last;
  }

  String toCsv() {
    return _scanResults
        .map((line) {
          final parts = line.split(',');
          if (parts.length >= 3) {
            final timestamp = parts[0];
            final format = parts[1];
            final content =
                '"${parts.sublist(2).join(',').replaceAll('"', '""')}"';
            return '"$timestamp","$format",$content';
          }
          return line;
        })
        .join('\n');
  }
}
import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:intl/intl.dart';

import 'package:barcodereader/l10n/app_localizations.dart';
import 'package:barcodereader/model.dart';

class ScannerPage extends StatefulWidget {
  final Function(String result) onScan;
  const ScannerPage({super.key, required this.onScan});
  @override
  State<ScannerPage> createState() => _ScannerPageState();
}

class _ScannerPageState extends State<ScannerPage> {
  final MobileScannerController _scannerController = MobileScannerController();
  bool _isScanPaused = false;
  bool _isFlashing = false;
  final Color _flashColor = HSVColor.fromAHSV(1,Model.colorHue.toDouble(),0.5,1).toColor();

  @override
  void initState() {
    super.initState();
    _setOrientation();
  }

  void _setOrientation() {
    if (Model.lockOrientation) {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.portraitDown,
      ]);
    }
  }

  @override
  void dispose() {
    _scannerController.dispose();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final mediaSize = MediaQuery.of(context).size;
    final scanWindow = _calculateScanWindow(mediaSize, Model.scanAreaRestrictionLevel);
    return Scaffold(
      appBar: AppBar(
        backgroundColor: _isFlashing ? _flashColor : Colors.grey[700],
        foregroundColor: Colors.black,
        actions: [
          IconButton(
            icon: ValueListenableBuilder<MobileScannerState>(
              valueListenable: _scannerController,
              builder: (context, state, child) {
                switch (state.torchState) {
                  case TorchState.off:
                    return Icon(
                      Icons.flash_off,
                      color: _isFlashing ? Colors.grey : Colors.white,
                    );
                  case TorchState.on:
                    return const Icon(Icons.flash_on, color: Colors.yellow);
                  default:
                    return const Icon(Icons.no_flash, color: Colors.grey);
                }
              },
            ),
            onPressed: () => _scannerController.toggleTorch(),
          ),
          IconButton(
            icon: const Icon(Icons.flip_camera_ios),
            onPressed: () => _scannerController.switchCamera(),
          ),
        ],
      ),
      body: Stack(children: [
        MobileScanner(
          scanWindow: scanWindow,
          controller: _scannerController,
          onDetect: (capture) {
            if (_isScanPaused) {
              return;
            }
            final List<Barcode> barcodes = capture.barcodes;
            if (barcodes.isNotEmpty) {
              if (mounted) {
                setState(() {
                  _isScanPaused = true;
                });
              }
              final String code = barcodes.first.rawValue ??
                  AppLocalizations.of(context)!.noData;
              final String format = barcodes.first.format.name;
              final String result =
                  '${DateFormat('yyyyMMdd_HHmmss').format(DateTime.now())},$format,$code';
              widget.onScan(result);
              if (Model.beepOnScan) {
                final soundId = Model.selectedBeepSound;
                AudioPlayer().play(AssetSource('sound/beep$soundId.mp3'));
              }
              if (Model.flashOnScan) {
                if (mounted) {
                  setState(() {
                    _isFlashing = true;
                  });
                }
              }
              if (Model.continuousScan) {
                if (Model.flashOnScan) {
                  Timer(const Duration(milliseconds: 200), () {
                    if (mounted) {
                      setState(() {
                        _isFlashing = false;
                      });
                    }
                  });
                }
                final interval = (Model.scanInterval * 1000).toInt();
                Timer(Duration(milliseconds: interval), () {
                  if (mounted) {
                    setState(() {
                      _isScanPaused = false;
                    });
                  }
                });
              } else {
                final popDelay = Model.flashOnScan ? 200 : 50;
                Timer(Duration(milliseconds: popDelay), () {
                  if (mounted) {
                    Navigator.of(context).pop();
                  }
                });
              }
            }
          }),
        if (scanWindow != null) _buildScanWindowOverlay(context, scanWindow),
      ]),
    );
  }

  Rect? _calculateScanWindow(Size size, int restrictionLevel) {
    if (restrictionLevel <= 0) {
      return null;
    }
    double heightDivisor;
    double widthFactor;
    switch (restrictionLevel) {
      case 1:
        heightDivisor = 1;
        widthFactor = 1;
        break;
      case 2:
        heightDivisor = 1.5;
        widthFactor = 1;
        break;
      case 3:
        heightDivisor = 2;
        widthFactor = 1;
        break;
      case 4:
        heightDivisor = 2.5;
        widthFactor = 1;
        break;
      case 5:
        heightDivisor = 3;
        widthFactor = 1;
        break;
      case 6:
        heightDivisor = 3.5;
        widthFactor = 1;
        break;
      case 7:
        heightDivisor = 4;
        widthFactor = 1;
        break;
      case 8:
        heightDivisor = 4.5;
        widthFactor = 1;
        break;
      default:
        return null;
    }
    final double width = size.width * widthFactor;
    final double height = size.width / heightDivisor;
    final Offset center = Offset(size.width / 2, size.height / 3);
    final double clampedWidth = width.clamp(0.0, size.width);
    final double clampedHeight = height.clamp(0.0, size.height);
    return Rect.fromCenter(
      center: center,
      width: clampedWidth,
      height: clampedHeight,
    );
  }

  Widget _buildScanWindowOverlay(BuildContext context, Rect scanWindow) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final screenWidth = constraints.maxWidth;
        final screenHeight = constraints.maxHeight;
        return CustomPaint(
          size: Size(screenWidth, screenHeight),
          painter: _ScanWindowOverlayPainter(scanWindow),
        );
      },
    );
  }
}

// CustomPainter を使用してオーバーレイを描画
class _ScanWindowOverlayPainter extends CustomPainter {
  final Rect scanWindow;
  _ScanWindowOverlayPainter(this.scanWindow);
  @override
  void paint(Canvas canvas, Size size) {
    final screenRect = Rect.fromLTWH(0, 0, size.width, size.height);
    // 暗くする色
    final paint = Paint()..color = Colors.black.withValues(alpha: 0.6);
    // Path を作成し、画面全体からスキャンウィンドウの領域をくり抜く
    final Path path = Path()
      ..addRect(screenRect) // 画面全体の矩形を追加
      ..addRect(scanWindow); // スキャンウィンドウの矩形を追加(これからくり抜く)
    // Path.fillType を EvenOdd に設定すると、重なり合う領域がくり抜かれる
    path.fillType = PathFillType.evenOdd;
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant _ScanWindowOverlayPainter oldDelegate) {
    return oldDelegate.scanWindow != scanWindow;
  }

}
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'package:barcodereader/l10n/app_localizations.dart';
import 'package:barcodereader/ad_manager.dart';
import 'package:barcodereader/ad_banner_widget.dart';
import 'package:barcodereader/ad_ump_status.dart';
import 'package:barcodereader/model.dart';
import 'package:barcodereader/loading_screen.dart';
import 'package:barcodereader/theme_color.dart';

class SettingPage extends StatefulWidget {
  const SettingPage({super.key});
  @override
  State<SettingPage> createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  late AdManager _adManager;
  late UmpConsentController _adUmp;
  AdUmpState _adUmpState = AdUmpState.initial;
  int _themeNumber = 0;
  String _languageCode = '';
  late ThemeColor _themeColor;
  bool _isReady = false;
  bool _isFirst = true;
  //
  late bool _continuousScan;
  late double _scanInterval;
  late int _scanAreaRestrictionLevel;
  late bool _startScanOnLaunch;
  late bool _beepOnScan;
  late int _selectedBeepSound;
  late bool _flashOnScan;
  late bool _lockOrientation;
  late int _colorHue;
  late double _colorSaturation;
  late double _colorBrightness;
  late Color _accentColor;

  @override
  void initState() {
    super.initState();
    _initState();
  }

  void _initState() async {
    _adManager = AdManager();
    _continuousScan = Model.continuousScan;
    _scanInterval = Model.scanInterval;
    _scanAreaRestrictionLevel = Model.scanAreaRestrictionLevel;
    _startScanOnLaunch = Model.startScanOnLaunch;
    _beepOnScan = Model.beepOnScan;
    _selectedBeepSound = Model.selectedBeepSound;
    _flashOnScan = Model.flashOnScan;
    _lockOrientation = Model.lockOrientation;
    _colorHue = Model.colorHue;
    _colorSaturation = Model.colorSaturation;
    _colorBrightness = Model.colorBrightness;
    _themeNumber = Model.themeNumber;
    _languageCode = Model.languageCode;
    //
    _adUmp = UmpConsentController();
    _refreshConsentInfo();
    //
    _accentColor = _getRainbowAccentColor(_colorHue, _colorSaturation, _colorBrightness);
    setState(() {
      _isReady = true;
    });
  }

  @override
  void dispose() {
    _adManager.dispose();
    super.dispose();
  }

  void _onApply() async {
    await Model.setContinuousScan(_continuousScan);
    await Model.setScanInterval(_scanInterval);
    await Model.setScanAreaRestrictionLevel(_scanAreaRestrictionLevel);
    await Model.setStartScanOnLaunch(_startScanOnLaunch);
    await Model.setBeepOnScan(_beepOnScan);
    await Model.setSelectedBeepSound(_selectedBeepSound);
    await Model.setFlashOnScan(_flashOnScan);
    await Model.setLockOrientation(_lockOrientation);
    await Model.setColorHue(_colorHue);
    await Model.setColorSaturation(_colorSaturation);
    await Model.setColorBrightness(_colorBrightness);
    await Model.setThemeNumber(_themeNumber);
    await Model.setLanguageCode(_languageCode);
    if (mounted) {
      Navigator.of(context).pop(true);
    }
  }

  String _scanAreaRestrictionLabel(AppLocalizations l, int value) {
    return value <= 0 ? l.scanAreaRestrictionNone : value.toString();
  }

  Future<void> _refreshConsentInfo() async {
    _adUmpState = await _adUmp.updateConsentInfo(current: _adUmpState);
    if (mounted) {
      setState(() {});
    }
  }

  Color _getRainbowAccentColor(int hue, double saturation, double brightness) {
    return HSVColor.fromAHSV(1.0, hue.toDouble(), saturation, brightness).toColor();
  }

  Future<void> _onTapPrivacyOptions() async {
    final err = await _adUmp.showPrivacyOptions();
    await _refreshConsentInfo();
    if (err != null && mounted) {
      final l = AppLocalizations.of(context)!;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('${l.cmpErrorOpeningSettings} ${err.message}')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return LoadingScreen();
    }
    if (_isFirst) {
      _isFirst = false;
      _themeColor = ThemeColor(themeNumber: Model.themeNumber, context: context);
    }
    final AppLocalizations l = AppLocalizations.of(context)!;
    final TextTheme t = Theme.of(context).textTheme;
    return Scaffold(
      backgroundColor: _themeColor.backColor,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        title: Text(l.setting),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.close),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          IconButton(icon: const Icon(Icons.check), onPressed: _onApply),
          const SizedBox(width: 10),
        ],
      ),
      body: SafeArea(
        child:Column(children:[
          Expanded(
            child: GestureDetector(
              onTap: () => FocusScope.of(context).unfocus(),  //背景タップでキーボードを仕舞う
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.only(left: 12, right: 12, top: 4, bottom: 100),
                  child: Column(children: [
                    _buildContinuousScan(l, t),
                    _buildLimitScan(l, t),
                    _buildLaunch(l, t),
                    _buildBeep(l, t),
                    _buildOrientation(l, t),
                    _buildColorScheme(l, t),
                    _buildTheme(l, t),
                    _buildLanguage(l, t),
                    _buildCmp(l, t),
                  ]),
                ),
              ),
            ),
          ),
        ]),
      ),
      bottomNavigationBar: AdBannerWidget(adManager: _adManager),
    );
  }

  Widget _buildContinuousScan(AppLocalizations l, TextTheme t) {
    return SizedBox(
      width: double.infinity,
      child: Card(
        margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Column(children: [
          SwitchListTile(
            title: Text(l.continuousScan, style: t.bodyMedium),
            value: _continuousScan,
            onChanged: (value) => setState(() => _continuousScan = value),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(l.scanInterval(_scanInterval.toStringAsFixed(1))),
                Slider(
                  value: _scanInterval,
                  min: 0.0,
                  max: 3.0,
                  divisions: 15,
                  label: '${_scanInterval.toStringAsFixed(1)}s',
                  onChanged: (value) {
                    setState(() {
                      _scanInterval = value;
                    });
                  },
                ),
              ],
            ),
          ),
        ])
      )
    );
  }

  Widget _buildLimitScan(AppLocalizations l, TextTheme t) {
    return SizedBox(
      width: double.infinity,
      child: Card(
        margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Padding(
          padding: const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 8),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '${l.scanAreaRestriction}: ${_scanAreaRestrictionLabel(l, _scanAreaRestrictionLevel)}',
              ),
              Slider(
                value: _scanAreaRestrictionLevel.toDouble(),
                min: 0,
                max: 8,
                divisions: 8,
                label: _scanAreaRestrictionLabel(l, _scanAreaRestrictionLevel),
                onChanged: (value) {
                  setState(() {
                    _scanAreaRestrictionLevel = value.round();
                  });
                },
              ),
            ],
          ),
        ),
      )
    );
  }

  Widget _buildLaunch(AppLocalizations l, TextTheme t) {
    return SizedBox(
      width: double.infinity,
      child: Card(
        margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: SwitchListTile(
          title: Text(l.startScanOnLaunch, style: t.bodyMedium),
          value: _startScanOnLaunch,
          onChanged: (value) =>
            setState(() => _startScanOnLaunch = value),
        ),
      )
    );
  }

  Widget _buildBeep(AppLocalizations l, TextTheme t) {
    return SizedBox(
      width: double.infinity,
      child: Card(
        margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Column(children: [
          SwitchListTile(
            title: Text(l.beepOnScan, style: t.bodyMedium),
            value: _beepOnScan,
            onChanged: (value) => setState(() => _beepOnScan = value),
          ),
          ListTile(
            title: Text(l.beepSound, style: t.bodyMedium),
            trailing: DropdownButton<int>(
              value: _selectedBeepSound,
              items: List.generate(14, (index) {
                final soundNum = index + 1;
                return DropdownMenuItem(
                  value: soundNum,
                  child: Text(
                    l.beepSoundName(
                      soundNum.toString(),
                    ),
                  ),
                );
              }),
              onChanged: (value) {
                if (value != null) {
                  setState(() => _selectedBeepSound = value);
                  AudioPlayer().play(AssetSource('sound/beep$value.mp3'));
                }
              },
            ),
          ),
          SwitchListTile(
            title: Text(l.flashOnScan, style: t.bodyMedium),
            value: _flashOnScan,
            onChanged: (value) => setState(() => _flashOnScan = value),
          ),
        ])
      )
    );
  }

  Widget _buildOrientation(AppLocalizations l, TextTheme t) {
    return SizedBox(
      width: double.infinity,
      child: Card(
        margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: SwitchListTile(
          title: Text(l.lockOrientation, style: t.bodyMedium),
          value: _lockOrientation,
          onChanged: (value) => setState(() => _lockOrientation = value),
        ),
      )
    );
  }

  Widget _buildColorScheme(AppLocalizations l, TextTheme t) {
    return Card(
      margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 16, right: 16, top: 16),
            child: Row(
              children: [
                Expanded(
                  child: Text(
                    l.colorScheme,
                    style: t.bodyMedium,
                    softWrap: true,
                    overflow: TextOverflow.visible,
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 16, right: 16, top: 4),
            child: Row(
              children: [
                Expanded(
                  child: Text(
                    l.colorScheme1,
                    style: t.bodySmall,
                    softWrap: true,
                    overflow: TextOverflow.visible,
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 16, right: 16),
            child: Row(
              children: <Widget>[
                Text(_colorHue.toStringAsFixed(0)),
                Expanded(
                  child: SliderTheme(
                    data: SliderTheme.of(context).copyWith(
                      activeTrackColor: _accentColor,
                      inactiveTrackColor: _accentColor.withValues(alpha: 0.3),
                      thumbColor: _accentColor,
                      overlayColor: _accentColor.withValues(alpha: 0.2),
                      valueIndicatorColor: _accentColor,
                    ),
                    child: Slider(
                      value: _colorHue.toDouble(),
                      min: 0,
                      max: 360,
                      divisions: 360,
                      label: _colorHue.toString(),
                      onChanged: (double value) {
                        setState(() {
                          _colorHue = value.toInt();
                          _accentColor = _getRainbowAccentColor(_colorHue, _colorSaturation, _colorBrightness);
                        });
                      }
                    ),
                  )
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 16, right: 16),
            child: Row(
              children: <Widget>[
                Text(_colorSaturation.toStringAsFixed(1)),
                Expanded(
                  child: SliderTheme(
                    data: SliderTheme.of(context).copyWith(
                      activeTrackColor: _accentColor,
                      inactiveTrackColor: _accentColor.withValues(alpha: 0.3),
                      thumbColor: _accentColor,
                      overlayColor: _accentColor.withValues(alpha: 0.2),
                      valueIndicatorColor: _accentColor,
                    ),
                    child: Slider(
                      value: _colorSaturation,
                      min: 0.0,
                      max: 1.0,
                      divisions: 10,
                      label: _colorSaturation.toStringAsFixed(1),
                      onChanged: (double value) {
                        setState(() {
                          _colorSaturation = value;
                          _accentColor = _getRainbowAccentColor(_colorHue, _colorSaturation, _colorBrightness);
                        });
                      }
                    ),
                  )
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 16, right: 16),
            child: Row(
              children: <Widget>[
                Text(_colorBrightness.toStringAsFixed(1)),
                Expanded(
                  child: SliderTheme(
                    data: SliderTheme.of(context).copyWith(
                      activeTrackColor: _accentColor,
                      inactiveTrackColor: _accentColor.withValues(alpha: 0.3),
                      thumbColor: _accentColor,
                      overlayColor: _accentColor.withValues(alpha: 0.2),
                      valueIndicatorColor: _accentColor,
                    ),
                    child: Slider(
                      value: _colorBrightness,
                      min: 0.0,
                      max: 1.0,
                      divisions: 10,
                      label: _colorBrightness.toStringAsFixed(1),
                      onChanged: (double value) {
                        setState(() {
                          _colorBrightness = value;
                          _accentColor = _getRainbowAccentColor(_colorHue, _colorSaturation, _colorBrightness);
                        });
                      }
                    ),
                  )
                ),
              ],
            ),
          ),
        ],
      )
    );
  }

  Widget _buildTheme(AppLocalizations l, TextTheme t) {
    return Card(
      margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: Row(
          children: [
            Expanded(
              child: Text(l.theme, style: t.bodyMedium),
            ),
            DropdownButton<int>(
              value: _themeNumber,
              items: [
                DropdownMenuItem(value: 0, child: Text(l.systemSetting)),
                DropdownMenuItem(value: 1, child: Text(l.lightTheme)),
                DropdownMenuItem(value: 2, child: Text(l.darkTheme)),
              ],
              onChanged: (value) {
                if (value != null) {
                  setState(() {
                    _themeNumber = value;
                  });
                }
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLanguage(AppLocalizations l, TextTheme t) {
    final Map<String,String> languageNames = {
      'en': 'English',
      'af': 'Afrikaans',
      'ar': 'العربية',
      'bg': 'Български',
      'bn': 'বাংলা',
      'bs': 'Bosanski',
      'ca': 'Català',
      'cs': 'Čeština',
      'da': 'Dansk',
      'de': 'Deutsch',
      'el': 'Ελληνικά',
      'es': 'Español',
      'et': 'Eesti',
      'fa': 'فارسی',
      'fi': 'Suomi',
      'fr': 'Français',
      'he': 'עברית',
      'hi': 'हिन्दी',
      'hr': 'Hrvatski',
      'hu': 'Magyar',
      'id': 'Bahasa Indonesia',
      'it': 'Italiano',
      'ja': '日本語',
      'ko': '한국어',
      'lt': 'Lietuvių',
      'lv': 'Latviešu',
      'ms': 'Bahasa Melayu',
      'my': 'မြန်မာ',
      'nl': 'Nederlands',
      'pa': 'ਪੰਜਾਬੀ',
      'pl': 'Polski',
      'pt': 'Português',
      'ro': 'Română',
      'ru': 'Русский',
      'sk': 'Slovenčina',
      'sr': 'Српски',
      'sv': 'Svenska',
      'sw': 'Kiswahili',
      'ta': 'தமிழ்',
      'th': 'ไทย',
      'tl': 'Tagalog',
      'tr': 'Türkçe',
      'uk': 'Українська',
      'ur': 'اردو',
      'vi': 'Tiếng Việt',
      'zh': '中文',
      'zu': 'isiZulu',
    };
    return Card(
      margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
        child: Row(
          children: [
            Expanded(
              child: Text(l.language, style: t.bodyMedium),
            ),
            DropdownButton<String?>(
              value: _languageCode,
              items: [
                DropdownMenuItem(value: '', child: Text('Default')),
                ...languageNames.entries.map((entry) => DropdownMenuItem<String?>(
                  value: entry.key,
                  child: Text(entry.value),
                )),
              ],
              onChanged: (String? value) {
                setState(() {
                  _languageCode = value ?? '';
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCmp(AppLocalizations l, TextTheme t) {
    final showButton = _adUmpState.privacyStatus == PrivacyOptionsRequirementStatus.required;
    String statusLabel = l.cmpCheckingRegion;
    IconData statusIcon = Icons.help_outline;
    switch (_adUmpState.privacyStatus) {
      case PrivacyOptionsRequirementStatus.required:
        statusLabel = l.cmpRegionRequiresSettings;
        statusIcon = Icons.privacy_tip_outlined;
        break;
      case PrivacyOptionsRequirementStatus.notRequired:
        statusLabel = l.cmpRegionNoSettingsRequired;
        statusIcon = Icons.check_circle_outline;
        break;
      case PrivacyOptionsRequirementStatus.unknown:
        statusLabel = l.cmpRegionCheckFailed;
        statusIcon = Icons.error_outline;
        break;
    }
    return Card(
      margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              l.cmpSettingsTitle,
              style: t.bodyMedium,
            ),
            const SizedBox(height: 8),
            Text(
              l.cmpConsentDescription,
              style: t.bodySmall,
            ),
            const SizedBox(height: 16),
            Center(
              child: Column(
                children: [
                  Chip(
                    avatar: Icon(statusIcon, size: 18),
                    label: Text(statusLabel),
                  ),
                  const SizedBox(height: 6),
                  Text(
                    '${l.cmpConsentStatusLabel} ${_adUmpState.consentStatus.localized(context)}',
                    style: t.bodySmall,
                  ),
                  if (showButton) ...[
                    const SizedBox(height: 16),
                    ElevatedButton.icon(
                      onPressed: _adUmpState.isChecking
                          ? null
                          : _onTapPrivacyOptions,
                      icon: const Icon(Icons.settings),
                      label: Text(
                        _adUmpState.isChecking
                            ? l.cmpConsentStatusChecking
                            : l.cmpOpenConsentSettings,
                      ),
                    ),
                    const SizedBox(height: 12),
                    OutlinedButton.icon(
                      onPressed: _adUmpState.isChecking
                          ? null
                          : _refreshConsentInfo,
                      icon: const Icon(Icons.refresh),
                      label: Text(l.cmpRefreshStatus),
                    ),
                    const SizedBox(height: 12),
                    OutlinedButton.icon(
                      onPressed: () async {
                        final messenger = ScaffoldMessenger.of(context);
                        final message = l.cmpResetStatusDone;
                        await ConsentInformation.instance.reset();
                        await _refreshConsentInfo();
                        if (!mounted) {
                          return;
                        }
                        messenger.showSnackBar(
                          SnackBar(content: Text(message)),
                        );
                      },
                      icon: const Icon(Icons.delete_sweep_outlined),
                      label: Text(l.cmpResetStatus),
                    ),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }


}
import 'package:flutter/material.dart';

import 'package:barcodereader/model.dart';

class ThemeColor {
  final int? themeNumber;
  final BuildContext context;

  ThemeColor({this.themeNumber, required this.context});

  Brightness get _effectiveBrightness {
    switch (themeNumber) {
      case 1:
        return Brightness.light;
      case 2:
        return Brightness.dark;
      default:
        return Theme.of(context).brightness;
    }
  }

  bool get _isLight => _effectiveBrightness == Brightness.light;

  Color _getRainbowAccentColor(int hue, double saturation, double brightness) {
    return HSVColor.fromAHSV(1, hue.toDouble(), saturation, brightness).toColor();
  }

  //main page
  Color get mainBackColor => _isLight ? Color.fromRGBO(221, 221, 221, 1.0) : Color.fromRGBO(51, 51, 51, 1.0);
  Color get mainForeColor => _isLight ? Color.fromRGBO(34, 34, 34, 1.0) : Color.fromRGBO(221, 221, 221, 1.0);

  Color get mainButtonColor1 => _isLight
      ? _getRainbowAccentColor(Model.colorHue, 0.4 * Model.colorSaturation, 1.0 * Model.colorBrightness)
      : _getRainbowAccentColor(Model.colorHue, 1.0 * Model.colorSaturation, 0.4 * Model.colorBrightness);
  Color get mainButtonColor2 => _isLight
      ? _getRainbowAccentColor(Model.colorHue, 0.5 * Model.colorSaturation, 1.0 * Model.colorBrightness)
      : _getRainbowAccentColor(Model.colorHue, 1.0 * Model.colorSaturation, 0.35 * Model.colorBrightness);
  Color get mainButtonColor3 => _isLight
      ? _getRainbowAccentColor(Model.colorHue, 0.6 * Model.colorSaturation, 1.0 * Model.colorBrightness)
      : _getRainbowAccentColor(Model.colorHue, 1.0 * Model.colorSaturation, 0.3 * Model.colorBrightness);
  Color get mainResultBackColor => _isLight ? Color.fromRGBO(255,255,255,1) : Color.fromRGBO(0,0,0,1);
  //setting page
  Color get backColor => _isLight ? Colors.grey[300]! : Colors.grey[900]!;
  Color get cardColor => _isLight ? Colors.white : Colors.grey[800]!;
  Color get appBarForegroundColor => _isLight ? Colors.grey[700]! : Colors.white70;
  Color get dropdownColor => cardColor;
  Color get borderColor => _isLight ? Colors.grey[300]! : Colors.grey[700]!;
  Color get inputFillColor => _isLight ? Colors.grey[50]! : Colors.grey[900]!;
}
import 'package:flutter/material.dart';

class ThemeModeNumber {
  static ThemeMode numberToThemeMode(int value) {
    switch (value) {
      case 1:
        return ThemeMode.light;
      case 2:
        return ThemeMode.dark;
      default:
        return ThemeMode.system;
    }
  }
}