ソースコード source code

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

● ご注意 ● このページで公開しているのはDartコードのみです。アプリの動作には画像・音声・多言語テキストなどの追加データが必要なため、ここに掲載している情報だけではアプリを完全に再現することはできません。 ● アプリは継続的に機能拡張しているため、ストアで公開している最新版とコード内容が異なる場合があります。 ● コードはコピーして自由にご利用いただけますが、著作権は放棄していません。そのため、コード全体の再掲載はご遠慮ください。一部の引用や改変しての再掲載は問題ありません。個人利用・商用利用を問わず、アプリ開発の参考として自由にお使いください。 ● このコードは「お手本」として公開しているものではありません。ミニアプリとして作成しているため、変数名など細部に配慮していない箇所や誤りが含まれる可能性があります。参考程度にご覧ください。 ● 他の開発者の公開コードを参考にした部分も含まれています。アプリ開発の熟練者が書いたコードではない点もご了承ください。 ● ここはエンジニア向けの技術情報共有サービスではないため、詳細な説明は省略しています。GitHub などでの公開予定はありません。 ● 本コードは無保証であり、動作や品質を保証するものではありません。
Copyright© エーオーシステム株式会社

● Notice ● Only the Dart source code is provided on this page. Additional assets such as images, audio files, and multilingual text are required for the application to function. Therefore, the information here alone is not sufficient to fully reproduce the app. ● The app is continuously being improved, so the code published here may differ from the latest version available on the app stores. ● You are free to copy and use the code, but the copyright is not waived. For this reason, please refrain from redistributing (reposting) the entire code. Partial quotation or redistribution of modified portions is allowed. You may use the code freely for reference in your own app development, whether for personal or commercial use. ● This code is not intended to serve as a coding example or best practice. As this is a small sample app, some variable names and details may lack refinement, and there may be mistakes. Please use it only as a reference. ● Some parts of the code are based on publicly available examples from other developers. Please note that this code was not written by an expert in Android app development. ● This is not a technical knowledge-sharing service for engineers, so detailed explanations are omitted. There are no plans to publish the code on GitHub. ● The code is provided "as is" without any warranty of any kind.
Copyright© ao-system, Inc.

下記コードの最終ビルド日: 2026-01-21

name: recorder
description: "recorder"

publish_to: 'none'

version: 1.0.6+7

environment:
  sdk: ^3.10.7

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:      #flutter gen-l10n
    sdk: flutter
  cupertino_icons: ^1.0.8
  intl: ^0.20.2
  shared_preferences: ^2.3.2
  google_mobile_ads: ^7.0.0
  permission_handler: ^12.0.1
  flutter_sound: ^9.30.0
  just_audio: ^0.10.5
  path_provider: ^2.1.5
  share_plus: ^12.0.1
  google_fonts: ^7.0.2
  flutter_svg: ^2.2.3
  wakelock_plus: ^1.4.0
  vibration: ^3.1.5

dev_dependencies:
  flutter_lints: ^6.0.0
  flutter_launcher_icons: ^0.14.3    #flutter pub run flutter_launcher_icons
  flutter_native_splash: ^2.3.6     #flutter pub run flutter_native_splash:create

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: '#222222'
  image: 'assets/image/splash.png'
  color_dark: '#222222'
  image_dark: 'assets/image/splash.png'
  fullscreen: true
  android_12:
    icon_background_color: '#222222'
    image: 'assets/image/splash.png'
    icon_background_color_dark: '#222222'
    image_dark: 'assets/image/splash.png'

flutter:
  uses-material-design: true
  generate: true

  assets:
    - assets/icon/
    - assets/image/
    - assets/sound/
import 'package:flutter/cupertino.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'package:recorder/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 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:recorder/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 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:intl/intl.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wakelock_plus/wakelock_plus.dart';

import 'package:recorder/parse_locale_tag.dart';
import 'package:recorder/recorded_audio.dart';
import 'package:recorder/recorder_controller.dart';
import 'package:recorder/setting_page.dart';
import 'package:recorder/theme_color.dart';
import 'package:recorder/theme_mode_number.dart';
import 'package:recorder/ad_manager.dart';
import 'package:recorder/loading_screen.dart';
import 'package:recorder/model.dart';
import 'package:recorder/main.dart';
import 'package:recorder/ad_banner_widget.dart';


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

class _MainHomePageState extends State<MainHomePage> with TickerProviderStateMixin {
  late AdManager _adManager;
  late ThemeColor _themeColor;
  bool _isReady = false;
  bool _isFirst = true;
  //
  late RecorderController _recorderController;
  bool _isStopPressed = false;
  late AnimationController _spinLeft;
  late AnimationController _spinRight;
  double _spinLeftDirection = 1.0;  // 1 = 時計回り, -1 = 反時計回り
  double _spinRightDirection = 1.0;
  //
  double _knobX = 0.77; // -0.77 から +0.77
  bool _isDraggingVolume = false;
  double _volume = 0.0; // 0.0〜1.0
  //

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _initState();
    });
  }

  void _initState() async {
    _adManager = AdManager();
    _wakelock();
    _recorderController = RecorderController();
    //マイク権限チェック
    final status = await Permission.microphone.request();
    if (!status.isGranted) {
      await _checkMicPermissionLoop();
    }
    //
    await _recorderController.init();
    _spinLeft = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 4),
    );
    _spinRight = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    );
    // 状態監視
    _recorderController.isRecording.addListener(_updateSpin);
    _recorderController.isPlaying.addListener(_updateSpin);
    _recorderController.isRewinding.addListener(_updateSpin);
    if (mounted) {
      setState(() {
        _isReady = true;
      });
    }
  }

  @override
  void dispose() {
    _spinLeft.dispose();
    _spinRight.dispose();
    super.dispose();
  }

  Future<void> _checkMicPermissionLoop() async {
    while (true) {
      final status = await Permission.microphone.request();
      if (status.isGranted) {
        return;
      }
      await _showMicPermissionDialog();
    }
  }

  Future<void> _showMicPermissionDialog() async {
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return AlertDialog(
          title: const Text("Microphone permission required"),
          content: const Text(
            "Microphone permission is required to use the recording feature.",
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                // ダイアログが閉じ切るのを待ってから設定を開く
                Future.delayed(const Duration(milliseconds: 300), () {
                  openAppSettings();
                });
              },
              child: const Text("OK"),
            ),
          ],
        );
      },
    );
  }

  void _wakelock() {
    if (Model.wakelockEnabled) {
      WakelockPlus.enable();
    } else {
      WakelockPlus.disable();
    }
  }

  String _format(Duration d) {
    final m = d.inMinutes.remainder(60).toString().padLeft(2, '0');
    final s = d.inSeconds.remainder(60).toString().padLeft(2, '0');
    return "$m:$s";
  }

  void _updateSpin() {
    final rec = _recorderController.isRecording.value;
    final play = _recorderController.isPlaying.value;
    final rew = _recorderController.isRewinding.value;
    if (rew) {
      _spinLeft.duration = const Duration(milliseconds: 600);
      _spinRight.duration = const Duration(milliseconds: 200);
      _spinLeftDirection = 1.0;
      _spinRightDirection = 1.0;
      _spinLeft.repeat();
      _spinRight.repeat();
      return;
    }
    if (rec || play) {
      _spinLeft.duration = const Duration(milliseconds: 6000);
      _spinRight.duration = const Duration(milliseconds: 2000);
      _spinLeftDirection = -1.0;
      _spinRightDirection = -1.0;
      _spinLeft.repeat();
      _spinRight.repeat();
      return;
    }
    _spinLeft.stop();
    _spinRight.stop();
  }

  void _openSetting() async {
    final updatedSettings = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => SettingPage(),
      ),
    );
    if (updatedSettings != null) {
      if (mounted) {
        final mainState = context.findAncestorStateOfType<MainAppState>();
        if (mainState != null) {
          mainState
            ..locale = parseLocaleTag(Model.languageCode)
            ..themeMode = ThemeModeNumber.numberToThemeMode(Model.themeNumber)
            ..setState(() {});
        }
        _wakelock();
      }
      if (mounted) {
        setState(() {
          _isFirst = true;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isReady == false) {
      return const LoadingScreen();
    }
    if (_isFirst) {
      _isFirst = false;
      _themeColor = ThemeColor(context: context);
    }
    final t = Theme.of(context).textTheme;
    return Scaffold(
      backgroundColor: _themeColor.mainBackColor,
      body: Stack(children:[
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [_themeColor.mainBackColor2, _themeColor.mainBackColor],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
            image: DecorationImage(
              image: AssetImage('assets/image/tile.png'),
              repeat: ImageRepeat.repeat,
              opacity: 0.1,
            ),
          ),
        ),
        SafeArea(
          child: Column(
            children: [
              SizedBox(
                height: 42,
                child: Row(
                  children: [
                    const SizedBox(width: 16),
                    Text('RECORDER',
                      style: t.titleMedium?.copyWith(
                        fontFamily: GoogleFonts.orbitron().fontFamily,
                        color: _themeColor.mainForeColor,
                      ),
                    ),
                    const Spacer(),
                    IconButton(
                      onPressed: _openSetting,
                      icon: Icon(Icons.settings,color: _themeColor.mainForeColor.withValues(alpha: 0.6)),
                    ),
                  ],
                )
              ),
              _buildRecorder(),
              Expanded(
                child: SingleChildScrollView(
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        SingleChildScrollView(
                          child: _buildAudioList(),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ]
          ),
        ),
      ]),
      bottomNavigationBar: AdBannerWidget(adManager: _adManager),
    );
  }

  Widget _buildRecorder() {
    return Padding(
      padding: const EdgeInsets.only(left: 12, right: 12, top: 0, bottom: 8),
      child: AspectRatio(
        aspectRatio: 1024 / 763,
        child: Stack(
          children: [
            Image.asset(_themeColor.mainRecorderBody),
            //録音中に表示
            Positioned.fill(
              child: Align(
                alignment: const Alignment(0, 0.3),
                child: _buildRecordingListenable()
              )
            ),
            _buildSpinLeft(),
            _buildSpinRight(),
            _buildVolumeKnob(),
            _buildStopButton(),
            _buildRewindButton(),
            _buildPlayButton(),
            _buildRecButton(),
          ]
        )
      )
    );
  }

  Widget _buildRecordingListenable() {
    return ValueListenableBuilder<bool>(
      valueListenable: _recorderController.isRecording,
      builder: (_, recording, __) {
        if (!recording) {
          return const SizedBox.shrink();
        }
        return ValueListenableBuilder<Duration>(
          valueListenable: _recorderController.recordingElapsed,
          builder: (_, elapsed, __) {
            return Padding(
              padding: const EdgeInsets.only(top: 8),
              child: Text(
                _format(elapsed), // mm:ss に整形
                style: GoogleFonts.robotoMono(
                  fontSize: 18,
                  color: _themeColor.mainForeColor.withValues(alpha: 0.7),
                ),
              ),
            );
          },
        );
      },
    );
  }

  Widget _buildSpinLeft() {
    return Positioned.fill(
      child: Align(
        alignment: const Alignment(-0.445, -0.255),
        child: FractionallySizedBox(
          widthFactor: 106 / 1024,
          child: AnimatedBuilder(
            animation: _spinLeft,
            builder: (_, child) {
              return Transform.rotate(
                angle: _spinLeft.value * 2 * 3.141592 * _spinLeftDirection,
                child: child,
              );
            },
            child: Image.asset('assets/image/recorder_spin.png'),
          ),
        ),
      ),
    );
  }

  Widget _buildSpinRight() {
    return Positioned.fill(
      child: Align(
        alignment: const Alignment(0.445, -0.255),
        child: FractionallySizedBox(
          widthFactor: 106 / 1024,
          child: AnimatedBuilder(
            animation: _spinRight,
            builder: (_, child) {
              return Transform.rotate(
                angle: _spinRight.value * 2 * 3.141592 * _spinRightDirection,
                child: child,
              );
            },
            child: Image.asset('assets/image/recorder_spin.png'),
          ),
        ),
      ),
    );
  }

  Widget _buildVolumeKnob() {
    final screenWidth = MediaQuery.of(context).size.width;
    return Stack(
      alignment: Alignment.center,
      children: [
        Align(
          alignment: Alignment(_knobX, -1.02),
          child: FractionallySizedBox(
            widthFactor: 120 / 1024,
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onHorizontalDragStart: (_) {
                setState(() => _isDraggingVolume = true);
              },
              onHorizontalDragUpdate: (details) {
                setState(() {
                  _knobX += (details.delta.dx / screenWidth) * 2.8;
                  _knobX = _knobX.clamp(-0.77, 0.77);
                  _volume = (_knobX - (-0.77)) / (0.77 - (-0.77));
                  _recorderController.setVolume(_volume);
                });
              },
              onHorizontalDragEnd: (_) {
                setState(() => _isDraggingVolume = false);
              },
              child: Image.asset(
                'assets/image/recorder_knob.png',
                fit: BoxFit.contain,
              ),
            ),
          ),
        ),
        if (_isDraggingVolume)
          Positioned(
            top: 20,
            child: Align(
              alignment: Alignment(_knobX, 0),
              child: Container(
                padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
                decoration: BoxDecoration(
                  color: Colors.black.withValues(alpha: 0.7),
                  borderRadius: BorderRadius.circular(6),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Icon(Icons.volume_up, color: Colors.white, size: 16),
                    const SizedBox(width: 4),
                    Text(
                      "${(_volume * 100).toStringAsFixed(0)}%",
                      style: const TextStyle(color: Colors.white, fontSize: 14),
                    ),
                  ],
                ),
              ),
            ),
          ),
      ],
    );
  }

  Widget _buildStopButton() {
    return ValueListenableBuilder<bool>(
      valueListenable: _recorderController.isRewinding,
      builder: (_, isRewinding, __) {
        final enabled = !isRewinding;
        return Align(
          alignment: const Alignment(-0.973, 0.97),
          child: FractionallySizedBox(
            widthFactor: 242 / 1024,
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTapDown: enabled
                ? (_) {
                  setState(() => _isStopPressed = true);
                  _recorderController.stopRecording();
                  _recorderController.stopPlay();
                }
                : null,
              onTapUp: enabled
                ? (_) {
                  setState(() => _isStopPressed = false);
                }
                : null,
              onTapCancel: enabled
                ? () {
                  setState(() => _isStopPressed = false);
                }
                : null,
              child: Image.asset(
                _isStopPressed
                  ? 'assets/image/recorder_stop.png'
                  : 'assets/image/recorder_transparent.png',
                fit: BoxFit.contain,
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildRewindButton() {
    return ValueListenableBuilder<bool>(
      valueListenable: _recorderController.isRecording,
      builder: (_, isRecording, __) {
        return ValueListenableBuilder<bool>(
          valueListenable: _recorderController.isPlaying,
          builder: (_, isPlaying, __) {
            return ValueListenableBuilder<bool>(
              valueListenable: _recorderController.isRewinding,
              builder: (_, isRewinding, __) {
                final enabled = !isRecording && !isPlaying && !isRewinding;
                return Align(
                  alignment: const Alignment(-0.323, 0.97),
                  child: FractionallySizedBox(
                    widthFactor: 242 / 1024,
                    child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTapDown: enabled
                        ? (_) {
                          _recorderController.rewind();
                        }
                        : null,
                      child: Image.asset(
                        isRewinding
                          ? 'assets/image/recorder_rewind.png'
                          : 'assets/image/recorder_transparent.png',
                        fit: BoxFit.contain,
                      ),
                    ),
                  ),
                );
              },
            );
          },
        );
      },
    );
  }

  Widget _buildPlayButton() {
    return ValueListenableBuilder<bool>(
      valueListenable: _recorderController.isRecording,
      builder: (_, isRecording, __) {
        return ValueListenableBuilder<bool>(
          valueListenable: _recorderController.isPlaying,
          builder: (_, isPlaying, __) {
            return ValueListenableBuilder<bool>(
              valueListenable: _recorderController.isRewinding,
              builder: (_, isRewinding, __) {
                final enabled = !(isRecording || isRewinding);
                final pressed = isPlaying;
                return Align(
                  alignment: const Alignment(0.327, 0.97),
                  child: FractionallySizedBox(
                    widthFactor: 242 / 1024,
                    child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTapDown: enabled
                        ? (_) async {
                          if (_recorderController.isPlaying.value) {
                            _recorderController.stopPlay();
                          } else {
                            if (Model.rewindEnabled) {
                              await _recorderController.rewind();
                            }
                            _recorderController.playLatest();
                          }
                        }
                        : null,
                      child: Image.asset(
                        pressed
                          ? 'assets/image/recorder_play.png'
                          : 'assets/image/recorder_transparent.png',
                        fit: BoxFit.contain,
                      ),
                    ),
                  ),
                );
              },
            );
          },
        );
      },
    );
  }

  Widget _buildRecButton() {
    return ValueListenableBuilder<bool>(
      valueListenable: _recorderController.isRecording,
      builder: (_, isRecording, __) {
        return ValueListenableBuilder<bool>(
          valueListenable: _recorderController.isPlaying,
          builder: (_, isPlaying, __) {
            return ValueListenableBuilder<bool>(
              valueListenable: _recorderController.isRewinding,
              builder: (_, isRewinding, __) {
                final enabled = !(isPlaying || isRewinding);
                final pressed = isRecording;
                return Align(
                  alignment: const Alignment(0.975, 0.97),
                  child: FractionallySizedBox(
                    widthFactor: 242 / 1024,
                    child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTapDown: enabled
                        ? (_) {
                          if (_recorderController.isRecording.value) {
                            _recorderController.stopRecording();
                          } else {
                            _recorderController.startRecording();
                          }
                        }
                        : null,
                      child: Image.asset(
                        pressed
                          ? 'assets/image/recorder_rec.png'
                          : 'assets/image/recorder_transparent.png',
                        fit: BoxFit.contain,
                      ),
                    ),
                  ),
                );
              },
            );
          },
        );
      },
    );
  }

  Widget _buildAudioList() {
    return ValueListenableBuilder<List<RecordedAudio>>(
      valueListenable: _recorderController.audios,
      builder: (_, list, __) {
        if (list.isEmpty) {
          return const SizedBox.shrink();
        }
        return Column(children:[
          Column(children: list.map((audio) => _buildAudioCard(audio)).toList()),
          const SizedBox(height: 200),
        ]);
      },
    );
  }

  Widget _buildAudioCard(RecordedAudio audio) {
    return Card(
      margin: const EdgeInsets.symmetric(vertical: 3, horizontal: 12),
      color: _themeColor.mainCardColor,
      shape: RoundedRectangleBorder(
        side: BorderSide(
          color: _themeColor.mainAccentForeColor2,
          width: 1,
        ),
        borderRadius: BorderRadius.zero,
      ),
      child: ListTile(
        contentPadding: const EdgeInsetsDirectional.only(start: 12, end: 2),
        leading: _buildAudioCardLeading(),
        title: _buildAudioCardTitle(audio),
        trailing: _buildAudioCardTrailing(audio),
        onTap: () async {
          if (Model.rewindEnabled) {
            await _recorderController.rewind();
          }
          _recorderController.play(audio.path);
        },
      ),
    );
  }

  Widget _buildAudioCardLeading() {
    return SvgPicture.asset('assets/image/icon_cassette.svg',
      width: 24,
      colorFilter: ColorFilter.mode(
        _themeColor.mainAccentForeColor,
        BlendMode.srcIn,
      ),
    );
  }

  Widget _buildAudioCardTitle(RecordedAudio audio) {
    final t = Theme.of(context).textTheme;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        //日付 + 総秒数
        Text(
          "${DateFormat('yyyy-MM-dd HH:mm:ss').format(audio.createdAt)}\n${audio.duration.inSeconds} sec.",
          style: GoogleFonts.orbitron(
            fontSize: t.bodyMedium?.fontSize,
            color: _themeColor.mainAccentForeColor,
          ),
        ),
        //再生中だけ経過時間を表示
        StreamBuilder<Duration>(
          stream: _recorderController.player.positionStream,
          builder: (context, snapshot) {
            final pos = snapshot.data ?? Duration.zero;
            return StreamBuilder<Duration?>(
              stream: _recorderController.player.durationStream,
              builder: (context, snapshot2) {
                final dur = snapshot2.data ?? Duration.zero;
                //再生中の音声と一致していなければ非表示
                if (!_recorderController.isPlaying.value ||
                    _recorderController.currentPlayingPath != audio.path) {
                  return const SizedBox.shrink();
                }
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "${_format(pos)} / ${_format(dur)}",
                      style: GoogleFonts.robotoMono(
                        fontSize: t.bodyMedium?.fontSize,
                        color: _themeColor.mainAccentForeColor,
                      ),
                    ),
                    SliderTheme(
                      data: SliderTheme.of(context).copyWith(
                        trackHeight: 2,
                        thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 6),
                        overlayShape: const RoundSliderOverlayShape(overlayRadius: 8),
                        minThumbSeparation: 0,
                      ),
                      child: Slider(
                        value: (() {
                          final posMs = pos.inMilliseconds;
                          final durMs = dur.inMilliseconds;
                          //揺れ防止:duration を超えたら duration に固定
                          final safePos = posMs > durMs ? durMs : posMs;
                          return safePos.toDouble();
                        })(),
                        min: 0,
                        max: dur.inMilliseconds.toDouble(),
                        activeColor: _themeColor.mainAccentForeColor,
                        inactiveColor: _themeColor.mainAccentForeColor.withValues(alpha: 0.3),
                        onChanged: (value) {
                          _recorderController.player.seek(
                            Duration(milliseconds: value.toInt()),
                          );
                        },
                      ),
                    )
                  ],
                );
              },
            );
          },
        ),
      ],
    );
  }

  Widget _buildAudioCardTrailing(RecordedAudio audio) {
    return PopupMenuButton<String>(
      icon: Icon(Icons.more_vert, color: _themeColor.mainAccentForeColor),
      onSelected: (value) async {
        if (value == 'share') {
          _recorderController.sendAudio(audio.id);
        } else if (value == 'delete') {
          final result = await showDialog<bool>(
            context: context,
            builder: (context) {
              return AlertDialog(
                title: Text("delete?"),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.pop(context, false),
                    child: Text("Cancel"),
                  ),
                  TextButton(
                    onPressed: () => Navigator.pop(context, true),
                    child: Text("Delete"),
                  ),
                ],
              );
            },
          );
          if (result == true) {
            _recorderController.deleteAudio(audio.id);
          }
        }
      },
      itemBuilder: (context) => [
        PopupMenuItem(
          value: 'share',
          child: Row(
            children: [
              Icon(Icons.share, color: _themeColor.mainAccentForeColor),
              const SizedBox(width: 8),
              Text("Share"),
            ],
          ),
        ),
        PopupMenuItem(
          value: 'delete',
          child: Row(
            children: [
              Icon(Icons.delete_outline, color: _themeColor.mainAccentForeColor),
              const SizedBox(width: 8),
              Text("Delete"),
            ],
          ),
        ),
      ],
    );
  }

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

class LoadingScreen extends StatelessWidget {
  const LoadingScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey,
      body: const Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
              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:google_mobile_ads/google_mobile_ads.dart';

import "package:recorder/home_page.dart";
import 'package:recorder/l10n/app_localizations.dart';
import 'package:recorder/loading_screen.dart';
import 'package:recorder/model.dart';
import 'package:recorder/parse_locale_tag.dart';
import 'package:recorder/theme_mode_number.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      systemNavigationBarColor: Colors.transparent,
      statusBarColor: Colors.transparent,
      systemNavigationBarContrastEnforced: false,
      systemStatusBarContrastEnforced: false,
    ),
  );
  MobileAds.instance.initialize();
  runApp(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;

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

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

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

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(body: Center(child: LoadingScreen())),
      );
    }
    final seed = _getRainbowAccentColor(Model.schemeColor);
    final colorSchemeLight = ColorScheme.fromSeed(seedColor: seed, brightness: Brightness.light);
    final colorSchemeDark = ColorScheme.fromSeed(seedColor: seed, brightness: Brightness.dark);
    //アイコンテーマを生成する関数、または直接指定
    IconThemeData buildIconTheme(ColorScheme colors) => IconThemeData(
      color: colors.primary,
      size: 24,
    );
    final commonElevatedButtonTheme = ElevatedButtonThemeData(
      style: ElevatedButton.styleFrom(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
    );
    final commonSliderTheme = SliderThemeData(
      activeTrackColor: null,
      thumbColor: null,
      showValueIndicator: ShowValueIndicator.onDrag,
      thumbShape: RoundSliderThumbShape(enabledThumbRadius: 10),
      valueIndicatorTextStyle: TextStyle(color: Colors.black),
    );
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
      locale: locale,
      themeMode: themeMode,
      theme: ThemeData(
        useMaterial3: true,
        colorScheme: ColorScheme.fromSeed(seedColor: seed, brightness: Brightness.light),
        sliderTheme: commonSliderTheme,
        elevatedButtonTheme: commonElevatedButtonTheme,
        iconTheme: buildIconTheme(colorSchemeLight),
      ),
      darkTheme: ThemeData(
        useMaterial3: true,
        colorScheme: ColorScheme.fromSeed(seedColor: seed, brightness: Brightness.dark),
        sliderTheme: commonSliderTheme,
        elevatedButtonTheme: commonElevatedButtonTheme,
        iconTheme: buildIconTheme(colorSchemeDark),
      ),
      home: const MainHomePage(),
    );
  }
}
import 'dart:ui' as ui;
import 'package:shared_preferences/shared_preferences.dart';

import 'package:recorder/l10n/app_localizations.dart';

class Model {
  Model._();

  static const String _prefVibrateEnabled = 'vibrateEnabled';
  static const String _prefSoundEnabled = 'soundEnabled';
  static const String _prefSoundVolume = 'soundVolume';
  static const String _prefRewindEnabled = 'rewindEnabled';
  static const String _prefWakelockEnabled = 'wakelockEnabled';
  static const String _prefSchemeColor = 'schemeColor';
  static const String _prefThemeNumber = 'themeNumber';
  static const String _prefLanguageCode = 'languageCode';

  static bool _ready = false;
  static bool _vibrateEnabled = true;
  static bool _soundEnabled = true;
  static double _soundVolume = 0.2;
  static bool _rewindEnabled = true;
  static bool _wakelockEnabled = false;
  static int _schemeColor = 110;
  static int _themeNumber = 0;
  static String _languageCode = '';

  static bool get vibrateEnabled => _vibrateEnabled;
  static bool get soundEnabled => _soundEnabled;
  static double get soundVolume => _soundVolume;
  static bool get rewindEnabled => _rewindEnabled;
  static bool get wakelockEnabled => _wakelockEnabled;
  static int get schemeColor => _schemeColor;
  static int get themeNumber => _themeNumber;
  static String get languageCode => _languageCode;

  static Future<void> ensureReady() async {
    if (_ready) {
      return;
    }
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    //
    _vibrateEnabled = prefs.getBool(_prefVibrateEnabled) ?? true;
    _soundEnabled = prefs.getBool(_prefSoundEnabled) ?? true;
    _soundVolume = (prefs.getDouble(_prefSoundVolume) ?? 0.2).clamp(0.0, 1.0);
    _rewindEnabled = prefs.getBool(_prefRewindEnabled) ?? true;
    _wakelockEnabled = prefs.getBool(_prefWakelockEnabled) ?? false;
    _schemeColor = (prefs.getInt(_prefSchemeColor) ?? 110).clamp(0, 360);
    _themeNumber = (prefs.getInt(_prefThemeNumber) ?? 0).clamp(0, 2);
    _languageCode = prefs.getString(_prefLanguageCode) ?? ui.PlatformDispatcher.instance.locale.languageCode;
    _languageCode = _resolveLanguageCode(_languageCode);
    _ready = true;
  }

  static String _resolveLanguageCode(String code) {
    final supported = AppLocalizations.supportedLocales;
    if (supported.any((l) => l.languageCode == code)) {
      return code;
    } else {
      return '';
    }
  }

  static Future<void> setVibrateEnabled(bool value) async {
    _vibrateEnabled = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_prefVibrateEnabled, value);
  }

  static Future<void> setSoundEnabled(bool value) async {
    _soundEnabled = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_prefSoundEnabled, value);
  }

  static Future<void> setSoundVolume(double value) async {
    _soundVolume = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setDouble(_prefSoundVolume, value);
  }

  static Future<void> setRewindEnabled(bool value) async {
    _rewindEnabled = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_prefRewindEnabled, value);
  }

  static Future<void> setWakelockEnabled(bool value) async {
    _wakelockEnabled = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_prefWakelockEnabled, value);
  }

  static Future<void> setSchemeColor(int value) async {
    _schemeColor = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefSchemeColor, 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,
  );
}
class RecordedAudio {
  final String id;
  final String path;
  final DateTime createdAt;
  final Duration duration;

  RecordedAudio({
    required this.id,
    required this.path,
    required this.createdAt,
    required this.duration,
  });
}
import 'dart:io';
import 'dart:async';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:just_audio/just_audio.dart' as just;
import 'package:share_plus/share_plus.dart';
import 'package:vibration/vibration.dart';

import 'package:recorder/recorded_audio.dart';
import 'package:recorder/model.dart';

class RecorderController {
  final FlutterSoundRecorder recorder = FlutterSoundRecorder();
  //
  final ValueNotifier<bool> isRecording = ValueNotifier(false);
  final ValueNotifier<bool> isPlaying = ValueNotifier(false);
  final ValueNotifier<bool> isRewinding = ValueNotifier(false);
  final ValueNotifier<List<RecordedAudio>> audios = ValueNotifier([]);
  final recordingElapsed = ValueNotifier<Duration>(Duration.zero);
  DateTime? _recordingStartTime;
  Timer? _timer;
  //
  late just.AudioPlayer player;   //録音データの再生用
  String currentPlayingPath = '';
  //
  late just.AudioPlayer _playerEffect;  //効果音用

  Future<void> init() async {
    await recorder.openRecorder();
    await _loadSavedRecordings();
    player = just.AudioPlayer();
    player.playerStateStream.listen((state) {
      if (state.processingState == just.ProcessingState.completed) {
        isPlaying.value = false;
      }
    });
    _playerEffect = just.AudioPlayer();
    await _playerEffect.setAsset('assets/sound/click.wav');
    //
    if (Model.vibrateEnabled && await Vibration.hasVibrator()) {
      //何もしない。await Vibration.hasVibrator()を一度呼ぶことで次回の戻り速度を速める為。
    }
  }

  Future<void> dispose() async {
    await recorder.closeRecorder();
    await player.dispose();
    await _playerEffect.dispose();
  }

  Future<void> _loadSavedRecordings() async {
    final dir = await getApplicationDocumentsDirectory();
    final files = Directory(dir.path).listSync();
    final List<RecordedAudio> loaded = [];
    for (var f in files) {
      if (f is File && f.path.endsWith('.aac')) {
        final stat = await f.stat();
        // duration は just_audio で取得
        final duration = await getAudioDuration(f.path);
        loaded.add(
          RecordedAudio(
            id: stat.modified.millisecondsSinceEpoch.toString(),
            path: f.path,
            createdAt: stat.modified,
            duration: duration,
          ),
        );
      }
    }
    audios.value = loaded;
  }

  Future<void> _playClickSound() async {
    if (Model.soundEnabled) {
      await _playerEffect.setVolume(Model.soundVolume);
      await _playerEffect.seek(Duration.zero);
      await _playerEffect.play();
    }
    if (Model.vibrateEnabled && await Vibration.hasVibrator()) {
      Vibration.vibrate(duration: 20);
    }
  }

  Future<Duration> getAudioDuration(String path) async {
    final player = just.AudioPlayer();
    await player.setAudioSource(just.AudioSource.uri(Uri.file(path)));
    final duration = player.duration ?? Duration.zero;
    await player.dispose();
    return duration;
  }

  Future<void> setVolume(double volume) async {
    await player.setVolume(volume);
  }

  Future<void> startRecording() async {
    _playClickSound();
    final dir = await getApplicationDocumentsDirectory();
    final timestamp = DateTime.now().millisecondsSinceEpoch;
    final path = '${dir.path}/recording_$timestamp.aac';
    isRecording.value = true;
    _recordingStartTime = DateTime.now();
    recordingElapsed.value = Duration.zero;
    _timer = Timer.periodic(const Duration(milliseconds: 200), (_) {
      if (_recordingStartTime != null) {
        recordingElapsed.value =
            DateTime.now().difference(_recordingStartTime!);
      }
    });
    await recorder.startRecorder(toFile: path);
  }

  Future<void> stopRecording() async {
    _playClickSound();
    if (!isRecording.value) {
      return;
    }
    final path = await recorder.stopRecorder();
    isRecording.value = false;
    _timer?.cancel();
    _timer = null;
    if (path != null) {
      currentPlayingPath = path;
      final duration = await getAudioDuration(path);
      saveRecording(path, duration);
    }
  }

  Future<void> play(String path) async {
    _playClickSound();
    isPlaying.value = true;
    currentPlayingPath = path;
    await player.setAudioSource(just.AudioSource.uri(Uri.file(path)));
    await player.seek(Duration.zero);
    await player.play();
  }

  Future<void> playLatest() async {
    _playClickSound();
    if (currentPlayingPath.isEmpty) {
      return;
    }
    final file = File(currentPlayingPath);
    // ファイルが存在しない場合の処理
    if (!await file.exists()) {
      currentPlayingPath = '';
      return;
    }
    await player.setAudioSource(
      just.AudioSource.uri(Uri.file(currentPlayingPath)),
    );
    isPlaying.value = true;
    await player.play();
  }

  Future<void> stopPlay() async {
    await player.stop();
    isPlaying.value = false;
  }

  Future<void> rewind() async {
    _playClickSound();
    isRewinding.value = true;
    await Future.delayed(const Duration(milliseconds: 500));
    isRewinding.value = false;
  }

  Future<void> saveRecording(String path, Duration duration) async {
    final file = File(path);
    if (!file.existsSync()) {
      return;
    }
    final newAudio = RecordedAudio(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      path: path,
      createdAt: DateTime.now(),
      duration: duration,
    );
    audios.value = [...audios.value, newAudio];
  }

  Future<void> deleteAudio(String id) async {
    final target = audios.value.firstWhere((a) => a.id == id);
    final file = File(target.path);
    if (await file.exists()) {
      await file.delete();
    }
    audios.value = audios.value.where((a) => a.id != id).toList();
    if (currentPlayingPath == target.path) {
      currentPlayingPath = '';
      isPlaying.value = false;
    }
  }

  Future<void> sendAudio(String id) async {
    final audio = audios.value.firstWhere((a) => a.id == id);
    await SharePlus.instance.share(
      ShareParams(
        files: [XFile(audio.path)],
      ),
    );
  }

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

import "package:recorder/l10n/app_localizations.dart";
import "package:recorder/ad_banner_widget.dart";
import "package:recorder/ad_manager.dart";
import "package:recorder/ad_ump_status.dart";
import 'package:recorder/loading_screen.dart';
import 'package:recorder/theme_color.dart';
import 'package:recorder/model.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;
  //
  bool _vibrateEnabled = true;
  bool _soundEnabled = true;
  double _soundVolume = 0.5;
  bool _rewindEnabled = true;
  bool _wakelockEnabled = false;
  int _schemeColor = 0;
  Color _accentColor = Colors.red;

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

  void _initState() async {
    _adManager = AdManager();
    _themeNumber = Model.themeNumber;
    _languageCode = Model.languageCode;
    //
    _adUmp = UmpConsentController();
    _refreshConsentInfo();
    //
    _vibrateEnabled = Model.vibrateEnabled;
    _soundEnabled = Model.soundEnabled;
    _soundVolume = Model.soundVolume;
    _rewindEnabled = Model.rewindEnabled;
    _wakelockEnabled = Model.wakelockEnabled;
    _schemeColor = Model.schemeColor;
    _accentColor = _getRainbowAccentColor(_schemeColor);
    setState(() {
      _isReady = true;
    });
  }

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

  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) {
      final l = AppLocalizations.of(context)!;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('${l.cmpErrorOpeningSettings} ${err.message}')),
      );
    }
  }

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

  void _onApply() async {
    await Model.setVibrateEnabled(_vibrateEnabled);
    await Model.setSoundEnabled(_soundEnabled);
    await Model.setSoundVolume(_soundVolume);
    await Model.setRewindEnabled(_rewindEnabled);
    await Model.setWakelockEnabled(_wakelockEnabled);
    await Model.setSchemeColor(_schemeColor);
    await Model.setThemeNumber(_themeNumber);
    await Model.setLanguageCode(_languageCode);
    if (!mounted) {
      return;
    }
    Navigator.of(context).pop(true);
  }

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return LoadingScreen();
    }
    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,
        leading: IconButton(
          icon: const Icon(Icons.close),
          onPressed: () => Navigator.of(context).pop(false)
        ),
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 10),
            child:IconButton(
              icon: const Icon(Icons.check),
              onPressed: _onApply,
            )
          ),
        ],
      ),
      body: SafeArea(
        child: Column(children:[
          Expanded(
            child: GestureDetector(
              onTap: () => FocusScope.of(context).unfocus(),  //背景タップでキーボードを仕舞う
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.only(left: 16, right: 16, top: 0, bottom: 100),
                  child: Column(children: [
                    _buildSoundEnabled(l),
                    _buildRewindEnabled(l),
                    _buildWakelockEnabled(l),
                    _buildSchemeColor(l),
                    _buildTheme(l),
                    _buildLanguage(l),
                    _buildCmp(l),
                  ]),
                ),
              ),
            ),
          ),
        ])
      ),
      bottomNavigationBar: AdBannerWidget(adManager: _adManager),
    );
  }

  Widget _buildSoundEnabled(AppLocalizations l) {
    final TextTheme t = Theme.of(context).textTheme;
    return Column(
      children: [
        Card(
          margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(12),
              topRight: Radius.circular(12),
              bottomLeft: Radius.circular(0),
              bottomRight: Radius.circular(0),
            ),
          ),
          color: _themeColor.cardColor,
          elevation: 0,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
            child: Row(
              children: [
                Expanded(
                  child: Text(
                    l.vibrateEnabled,
                    style: t.bodyMedium,
                  ),
                ),
                Switch(
                  value: _vibrateEnabled,
                  onChanged: (value) {
                    setState(() {
                      _vibrateEnabled = value;
                    });
                  },
                ),
              ],
            ),
          ),
        ),
        Card(
          margin: const EdgeInsets.only(left: 0, top: 2, right: 0, bottom: 0),
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(0),
              topRight: Radius.circular(0),
              bottomLeft: Radius.circular(0),
              bottomRight: Radius.circular(0),
            ),
          ),
          color: _themeColor.cardColor,
          elevation: 0,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
            child: Row(
              children: [
                Expanded(
                  child: Text(
                    l.soundEnabled,
                    style: t.bodyMedium,
                  ),
                ),
                Switch(
                  value: _soundEnabled,
                  onChanged: (value) {
                    setState(() {
                      _soundEnabled = value;
                    });
                  },
                ),
              ],
            ),
          ),
        ),
        Card(
          margin: const EdgeInsets.only(left: 0, top: 2, right: 0, bottom: 0),
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(0),
              topRight: Radius.circular(0),
              bottomLeft: Radius.circular(12),
              bottomRight: Radius.circular(12),
            ),
          ),
          color: _themeColor.cardColor,
          elevation: 0,
          child: Padding(
            padding: const EdgeInsets.only(left: 16, right: 16, top: 12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  l.soundVolume,
                  style: t.bodyMedium,
                ),
                Row(
                  children: [
                    Text(
                      _soundVolume.toStringAsFixed(1),
                      style: t.bodySmall,
                    ),
                    Expanded(
                      child: Slider(
                        value: _soundVolume,
                        min: 0.0,
                        max: 1.0,
                        divisions: 10,
                        label: _soundVolume.toStringAsFixed(1),
                        onChanged: (double value) {
                          setState(() {
                            _soundVolume = value;
                          });
                        },
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
        )
      ]
    );
  }

  Widget _buildRewindEnabled(AppLocalizations l) {
    final TextTheme t = Theme.of(context).textTheme;
    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: 4),
        child: Row(
          children: [
            Expanded(
              child: Text(
                l.rewindEnabled,
                style: t.bodyMedium,
              ),
            ),
            Switch(
              value: _rewindEnabled,
              onChanged: (value) {
                setState(() {
                  _rewindEnabled = value;
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildWakelockEnabled(AppLocalizations l) {
    final TextTheme t = Theme.of(context).textTheme;
    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: 4),
        child: Row(
          children: [
            Expanded(
              child: Text(
                l.wakelockEnabled,
                style: t.bodyMedium,
              ),
            ),
            Switch(
              value: _wakelockEnabled,
              onChanged: (value) {
                setState(() {
                  _wakelockEnabled = value;
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSchemeColor(AppLocalizations l) {
    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: [
                Text(l.colorScheme),
                const Spacer(),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 16, right: 16),
            child: Row(
              children: <Widget>[
                Text(_schemeColor.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: _schemeColor.toDouble(),
                      min: 0,
                      max: 360,
                      divisions: 360,
                      label: _schemeColor.toString(),
                      onChanged: (double value) {
                        setState(() {
                          _schemeColor = value.toInt();
                          _accentColor = _getRainbowAccentColor(_schemeColor);
                        });
                      }
                    )
                  )
                ),
              ],
            ),
          ),
        ],
      )
    );
  }

  Widget _buildTheme(AppLocalizations l) {
    final TextTheme t = Theme.of(context).textTheme;
    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: 4),
        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) {
    final Map<String,String> languageNames = {
      'af': 'af: Afrikaans',
      'ar': 'ar: العربية',
      'bg': 'bg: Български',
      'bn': 'bn: বাংলা',
      'bs': 'bs: Bosanski',
      'ca': 'ca: Català',
      'cs': 'cs: Čeština',
      'da': 'da: Dansk',
      'de': 'de: Deutsch',
      'el': 'el: Ελληνικά',
      'en': 'en: English',
      'es': 'es: Español',
      'et': 'et: Eesti',
      'fa': 'fa: فارسی',
      'fi': 'fi: Suomi',
      'fil': 'fil: Filipino',
      'fr': 'fr: Français',
      'gu': 'gu: ગુજરાતી',
      'he': 'he: עברית',
      'hi': 'hi: हिन्दी',
      'hr': 'hr: Hrvatski',
      'hu': 'hu: Magyar',
      'id': 'id: Bahasa Indonesia',
      'it': 'it: Italiano',
      'ja': 'ja: 日本語',
      //'jv': 'jv: Basa Jawa',    //flutterのサポート外
      'km': 'km: ខ្មែរ',
      'kn': 'kn: ಕನ್ನಡ',
      'ko': 'ko: 한국어',
      'lt': 'lt: Lietuvių',
      'lv': 'lv: Latviešu',
      'ml': 'ml: മലയാളം',
      'mr': 'mr: मराठी',
      'ms': 'ms: Bahasa Melayu',
      'my': 'my: မြန်မာ',
      'ne': 'ne: नेपाली',
      'nl': 'nl: Nederlands',
      'or': 'or: ଓଡ଼ିଆ',
      'pa': 'pa: ਪੰਜਾਬੀ',
      'pl': 'pl: Polski',
      'pt': 'pt: Português',
      'ro': 'ro: Română',
      'ru': 'ru: Русский',
      'si': 'si: සිංහල',
      'sk': 'sk: Slovenčina',
      'sr': 'sr: Српски',
      'sv': 'sv: Svenska',
      'sw': 'sw: Kiswahili',
      'ta': 'ta: தமிழ்',
      'te': 'te: తెలుగు',
      'th': 'th: ไทย',
      'tl': 'tl: Tagalog',
      'tr': 'tr: Türkçe',
      'uk': 'uk: Українська',
      'ur': 'ur: اردو',
      'uz': 'uz: Oʻzbekcha',
      'vi': 'vi: Tiếng Việt',
      'zh': 'zh: 中文',
      'zu': 'zu: isiZulu',
    };
    final TextTheme t = Theme.of(context).textTheme;
    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) {
    final TextTheme t = Theme.of(context).textTheme;
    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:recorder/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;
    }
  }

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

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

  //main page
  Color get mainBackColor => _isLight ? Color.fromRGBO(150, 150, 150, 1.0) : Color.fromRGBO(20, 20, 20, 1.0);
  Color get mainBackColor2 => _isLight ? Color.fromRGBO(60, 60, 60, 1.0) : Color.fromRGBO(0, 0, 0, 1.0);
  Color get mainCardColor => _isLight ? Color.fromRGBO(255,255,255,0.5) : Color.fromRGBO(0,0,0,0.1);
  Color get mainForeColor => _isLight ? Color.fromRGBO(200, 200, 200, 1.0) : Color.fromRGBO(200, 200, 200, 1.0);
  Color get mainAccentForeColor => _isLight ? _getRainbowAccentColor(Model.schemeColor,1,0.5) : _getRainbowAccentColor(Model.schemeColor,0.4,1.0);
  Color get mainAccentForeColor2 => _isLight ? _getRainbowAccentColor(Model.schemeColor,0.5,0.7) : _getRainbowAccentColor(Model.schemeColor,1,0.4);
  //main page image
  String get mainRecorderBody => _isLight ? 'assets/image/recorder_body.png' : 'assets/image/recorder_body_dark.png';
  //setting page
  Color get backColor => _isLight ? Colors.grey[200]! : 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;
    }
  }
}