ponshu-room-lite/lib/services/network_service.dart

91 lines
2.8 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
/// ネットワーク接続状態を管理するサービス
///
/// Phase 1緊急対応: オフライン対応のための基盤サービス
/// - オンライン/オフライン判定
/// - 接続状態変化の監視
class NetworkService {
static final Connectivity _connectivity = Connectivity();
/// 現在のネットワーク接続状態を確認
///
/// Returns: true = オンライン, false = オフライン
///
/// Usage:
/// ```dart
/// if (await NetworkService.isOnline()) {
/// // Gemini API呼び出し
/// } else {
/// // Draft保存
/// }
/// ```
static Future<bool> isOnline() async {
try {
final List<ConnectivityResult> results = await _connectivity.checkConnectivity();
// オフライン判定: 接続がない、または機内モード
if (results.isEmpty || results.contains(ConnectivityResult.none)) {
debugPrint('🔴 Network: OFFLINE');
return false;
}
debugPrint('🟢 Network: ONLINE (${results.join(', ')})');
return true;
} catch (e) {
debugPrint('⚠️ Network check error: $e (assuming offline)');
return false; // エラー時は安全側に倒す(オフライン扱い)
}
}
/// ネットワーク接続状態の変化を監視するStream
///
/// Usage:
/// ```dart
/// StreamSubscription? _subscription;
///
/// void initState() {
/// _subscription = NetworkService.onConnectivityChanged.listen((results) {
/// if (!results.contains(ConnectivityResult.none)) {
/// // オンライン復帰時の処理Draft解析開始など
/// }
/// });
/// }
///
/// void dispose() {
/// _subscription?.cancel();
/// }
/// ```
static Stream<List<ConnectivityResult>> get onConnectivityChanged {
return _connectivity.onConnectivityChanged;
}
/// オンライン復帰を待機する(最大待機時間あり)
///
/// Returns: true = タイムアウト前にオンライン復帰, false = タイムアウト
///
/// Usage:
/// ```dart
/// if (await NetworkService.waitForOnline(timeout: Duration(seconds: 30))) {
/// // オンライン復帰成功
/// }
/// ```
static Future<bool> waitForOnline({Duration timeout = const Duration(seconds: 30)}) async {
if (await isOnline()) return true; // 既にオンラインなら即座に返す
try {
await for (final results in _connectivity.onConnectivityChanged.timeout(timeout)) {
if (!results.contains(ConnectivityResult.none)) {
debugPrint('🟢 Network: Back ONLINE!');
return true;
}
}
return false;
} catch (e) {
debugPrint('⚠️ waitForOnline timeout or error: $e');
return false;
}
}
}