connection_manager

์šฉ๋„

๋„คํŠธ์›Œํฌ ์š”์ฒญ์‹œ ์ธํ„ฐ๋„ท ์—ฐ๊ฒฐ ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•˜๊ณ  ์ธํ„ฐ๋„ท ์ž์ฒด๊ฐ€ ์—ฐ๊ฒฐ์ด ๋˜์–ด ์žˆ์ง€ ์•Š์€ ๊ฒฝ์šฐ ๋„คํŠธ์›Œํฌ ์š”์ฒญ์„ ์•„์˜ˆ ๋‚ ๋ฆฌ์ง€ ์•Š๊ณ  ๋ฐ”๋กœ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•˜๊ธฐ ์œ„ํ•จ์ด๋‹ค.

๊ตฌํ˜„

connectivity_plus ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

flutter pub add connectivity_plus
import 'package:connectivity_plus/connectivity_plus.dart';

class ConnectionManager {
  final Connectivity connectivity;

  ConnectionManager({
    required this.connectivity,
  });

  Future<bool> get isConnected async {
    final ConnectivityResult connectivityResult =
    await connectivity.checkConnectivity();
    return ((connectivityResult == ConnectivityResult.wifi) ||
        (connectivityResult == ConnectivityResult.mobile));
  }
}

์‚ฌ์šฉ

ํ”„๋กœ์ ํŠธ์— ์‚ฌ์šฉํ–ˆ๋˜ ์‹ค์ œ ์ฝ”๋“œ๋ฅผ ๋ฐœ์ทŒํ•ด์™”๋‹ค. ํ˜„์žฌ ํ…œํ”Œ๋ฆฟ ์ฝ”๋“œ๋ฅผ ๊ตฌํ˜„์ค‘์ธ ๋ ˆํฌ์ง€ํ† ๋ฆฌ์—๋Š” ์œ„ ์ฝ”๋“œ(ConnectionManager) ๊นŒ์ง€๋งŒ ๊ตฌํ˜„ํ•ด๋‘์—ˆ๋‹ค.

  @override
  Future<Either<AppException, MealSummaryModel>> getMealSummary(
      int mealId) async {
    bool isConnected = await connectionManager.isConnected;
    if (!isConnected) {
      return Left(AppException(TextManager.internetNotConnected.tr()));
    }

    try {
      final response = await apiClient.get('/meal/summary/$mealId');
      MealSummaryModel mealSummary =
          MealSummaryModel.fromResponse(response.data);

      return Right(mealSummary);
    } on DioException catch (_) {
      return Left(AppException(TextManager.mealFetchFailedMessage.tr()));
    }
  }

Last updated