[Flutter] FlutterError (Binding has not yet been initialized.The "instance" getter on the ServicesBinding binding mixin is only available once that binding has been initialized. 해결방법

2023-11-14


사진: Unsplash 의 Toby Hughes


1. 원인

 

firebase와 flutter 앱을 연동하는 과정에서 아래와 같은 오류가 발생했다. 

 

FlutterError (Binding has not yet been initialized.
The "instance" getter on the ServicesBinding binding mixin is only available once that binding has been initialized.
Typically, this is done by calling "WidgetsFlutterBinding.ensureInitialized()" or "runApp()" (the latter calls the former). Typically this call is done in the "void main()" method. The "ensureInitialized" method is idempotent; calling it multiple times is not harmful. After calling that method, the "instance" getter will return the binding.
In a test, one can call "TestWidgetsFlutterBinding.ensureInitialized()" as the first line in the test's "main()" method to initialize the binding.
If ServicesBinding is a custom binding mixin, there must also be a custom binding class, like WidgetsFlutterBinding, but that mixes in the selected binding, and that is the class that must be constructed before using the "instance" getter.)

 


에러가 발생한 코드는 아래와 같다.

 

void main() async {
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
}

 

에러의 원인은 ServicesBinding 이 초기화되지 않은 상태에서 getter 함수를 호출하여 발생한 것이 원인이다. 이를 해결하는 방법을 알아보자. 쉽게 말해 비동기로 동작하는 함수에서 ServicesBinding 이 초기화 되지 않은 상태에서 이와 관련된 함수들을 호출하려고 하니 오류가 발생하는 것이다.


사실 해결 방법은 어렵지 않다. Firebase.initializeApp 호출전 WidgetsFlutterBinding.ensureInitialized(); 를 통해서 runApp을 호출하기 전 WidgetsBinding을 구현하는 바인딩의 인스턴스를 반환하도록 해준다. 

https://api.flutter.dev/flutter/widgets/WidgetsFlutterBinding/ensureInitialized.html

 

ensureInitialized method - WidgetsFlutterBinding class - widgets library - Dart API

WidgetsBinding ensureInitialized() Returns an instance of the binding that implements WidgetsBinding. If no binding has yet been initialized, the WidgetsFlutterBinding class is used to create and initialize one. You only need to call this method if you nee

api.flutter.dev


그럼 코드는 아래와 같은 형태를 가지게 된다.

 

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
}

메인 이미지 출처 : 사진: UnsplashToby Hughes