강의

멘토링

로드맵

Inflearn Community Q&A

pdh9809275514's profile image
pdh9809275514

asked

[Code Factory] [Intermediate] Flutter Real Practice! State Management, Cache Management, Code Generation, GoRouter, Authentication Logic, etc. Essential Skills to Become an Intermediate!

Working with Dio onRequest Interceptor

nRequest Interceptor 작업하기 부분 storage 질문드립니다.

Written on

·

323

2

여기서 data.dart에 있는 storage를 사용하지 않고 새로 생성해서 사용하는 이유가 무엇인가요??

class CustomIntercepter extends Interceptor {
  final FlutterSecureStorage storage;

  CustomIntercepter({required this.storage});

  // 1) 요청을 보낼 때
  @override
  void onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    print('[REQ] [${options.method}] ${options.uri}');

    if (options.headers['accessToken'] == 'true') {
      options.headers.remove('accessToken');

      final token = await storage.read(key: ACCESS_TOKEN_KEY);

      options.headers.addAll({'authorization': 'Bearer $token'});
    }
    return super.onRequest(options, handler);
  }

  // 2) 응답을 받을 때
  // 3) 에러가 났을 때
}
flutter하이브리드-앱

Answer 1

3

codefactory님의 프로필 이미지
codefactory
Instructor

안녕하세요!

다시한번 코드를 읽어보시면 새로 생성은 없습니다!

외부에서 주입받고 있을 뿐입니다.

감사합니다!

pdh9809275514님의 프로필 이미지
pdh9809275514
Questioner

아 제가 잘못 글을 작성했는데, 바로 data.dart에 있는걸 사용하지 않고 굳이 주입받아서 사용하는 이유가 있나요??

codefactory님의 프로필 이미지
codefactory
Instructor

Dependency Injection 테크닉입니다. 하나의 인스턴스를 돌려쓰면서 불필요한 신규 생성을 막아서 메모리를 덜 쓰고 버그를 방지 할 수 있습니다 (OOP를 이용하면 실제로 같은 클래스의 '다른' 인스턴스를 사용하다 실수하는 경우가 많습니다). 그보다 더 중요한건 테스트코드 작성할때 mocking이 매우 편리합니다.

pdh9809275514님의 프로필 이미지
pdh9809275514
Questioner

감사합니다!

pdh9809275514's profile image
pdh9809275514

asked

Ask a question