[Flutter] context 없이 screen navigate 하기

하스레·2023년 2월 6일
0

context 없이 navigate를 할 수 있을까?

api 요청에 대한 응답으로 refresh token 만료 Exception이 왓을 때, 위젯과 관련없는 클래스에서 로그인 페이지로 navigate를 하는 방법을 찾아야 했다. 여기서 관건은, context를 사용할 수 없다는 것이었다.

방법 1 - 실패: restart_app 라이브러리 사용

구글링을 해보니 많이들 restart_app이라는 라이브러리를 추천하길래 다운로드하여 사용해보았으나,
flutter clean을 하고 다시 런해도, vscode를 껐다 켜도, flutter upgrade후 다시 다 해봐도!! 뭘 해도 다음과 같은 에러가 계속 발생하여 포기할 수 밖에 없었다...ㅠㅠ

unhandled exception: missingpluginexception(no implementation found for method restartapp on channel restart)

방법 2 - 성공: navigatorkey 사용

더 구글링을 해보니 navigatorkey를 사용하는 방법을 찾을 수 있었다.
감사한 스택오버플로우 글

  1. 먼저 main.dart에 global 변수로 다음과 같이 한 줄을 추가한다.
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); //추가!

void main() {
  runApp(CupertinoApp(
    title: 'Navigate without context',
    initialRoute: '/',
    navigatorKey: navigatorKey, // important
    onGenerateRoute: ...
  ));
}
  1. 사용하려는 파일에 main.dart를 import하고 다음과 같이 navigatorkey를 사용하면 context없이 화면을 전환할 수 있다!
import 'package:{내 어플리케이션 패키지 이름}/main.dart'; //꼭 추가!!!

abstract class API {
  static Future<dynamic> get() async {
     // call some api
     ...
     // then you want to navigate to specific screen like login
     navigatorKey.currentState?.pushNamed('/login'); // navigate to login, with null-aware check
  }
}

참고
https://stackoverflow.com/questions/52962112/how-to-navigate-without-context-in-flutter-app

profile
Software Developer

0개의 댓글