Skip to content

Commit

Permalink
feat(database, android): automatically map the host to 10.0.2.2 when …
Browse files Browse the repository at this point in the history
…using useDatabaseEmulator to match other plugins (#11976)

* feat(database, android): automatically map the host to 10.0.2.2  when using useDatabaseEmulator to match other plugins

* format
  • Loading branch information
Lyokone committed Dec 13, 2023
1 parent 2ed6d54 commit 6c6c589
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 8 deletions.
Expand Up @@ -10,6 +10,7 @@ import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'
show FirebasePluginPlatform;
import 'package:firebase_database_platform_interface/firebase_database_platform_interface.dart';
import 'package:flutter/foundation.dart';

export 'package:firebase_database_platform_interface/firebase_database_platform_interface.dart'
show ServerValue, TransactionHandler, DatabaseEventType, Transaction;
Expand Down
Expand Up @@ -75,8 +75,26 @@ class FirebaseDatabase extends FirebasePluginPlatform {
///
/// Note: Must be called immediately, prior to accessing FirebaseFirestore methods.
/// Do not use with production credentials as emulator traffic is not encrypted.
void useDatabaseEmulator(String host, int port) {
_delegate.useDatabaseEmulator(host, port);
void useDatabaseEmulator(
String host,
int port, {
bool automaticHostMapping = true,
}) {
assert(host.isNotEmpty);
assert(!port.isNegative);

String mappedHost = host;

// Android considers localhost as 10.0.2.2 - automatically handle this for users.
if (defaultTargetPlatform == TargetPlatform.android && !kIsWeb) {
if ((mappedHost == 'localhost' || mappedHost == '127.0.0.1') &&
automaticHostMapping) {
// ignore: avoid_print
print('Mapping Database Emulator host "$mappedHost" to "10.0.2.2".');
mappedHost = '10.0.2.2';
}
}
_delegate.useDatabaseEmulator(mappedHost, port);
}

/// Returns a [DatabaseReference] accessing the root of the database.
Expand Down
Expand Up @@ -4,7 +4,6 @@

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:tests/firebase_options.dart';
Expand All @@ -22,11 +21,8 @@ late FirebaseDatabase database;
const emulatorPort = 9000;

// Android device emulators consider localhost of the host machine as 10.0.2.2
// so let's use that if running on Android.
final emulatorHost =
(!kIsWeb && defaultTargetPlatform == TargetPlatform.android)
? '10.0.2.2'
: 'localhost';
// but should be automatically mapped by the useDatabaseEmulator function.
const emulatorHost = 'localhost';

void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
Expand Down

0 comments on commit 6c6c589

Please sign in to comment.