DEV Community

Jhin Lee
Jhin Lee

Posted on

How to use Firebase Emulator suite for Flutter

The Firebase provides an emulator suite for the local dev environment. The suite allows us to run the Firebase on the local machine. So, we can locally use Cloud Firestore, Realtime Database, Cloud Storage for Firebase, Authentication, Firebase Hosting, Cloud Functions (beta), Pub/Sub (beta), and Firebase Extensions (beta) for the app we are working on.

More detail can be found at https://firebase.google.com/docs/emulator-suite

Image description

Pre-Requisite

The Flutter project is initialized for the Firebase: https://firebase.google.com/docs/flutter/setup

Install the Emulator Suite

Setup the Emulator Suite with this command under the project directory:

firebase init emulators
Enter fullscreen mode Exit fullscreen mode

Start the Emulator Suite

firebase emulators:start
Enter fullscreen mode Exit fullscreen mode

Run the Flutter app using the Emulators

Add this lines of code in the main() in main.dart

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // Initialize Firebase
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  // Use Firebase Emulators
  if (kDebugMode) { // Only for debug mode.
    try {
      final emulatorHost = defaultTargetPlatform == TargetPlatform.android
          ? "10.0.2.2"
          : "localhost";
      FirebaseStorage.instance.useStorageEmulator(emulatorHost, 9199);
      FirebaseFirestore.instance.useFirestoreEmulator(emulatorHost, 8080);
    } catch (e) {
      // ignore: avoid_print
      print(e);
    }
  }
  // Start Flutter Application
  runApp(const MyApp());
}
Enter fullscreen mode Exit fullscreen mode

The code example makes the app use FireStorage and Firestore Emulators in debug mode. It also provides Web UI(http://localhost:4000) for easy inspection.

Top comments (0)