我正在尝试使用 firebase 模拟器,一切正常,但不适用于存储模拟器。
下面是我正在使用的代码,我也尝试过10.0.2.2,但仍然出现相同的错误。
void main() async {
Bloc.observer = AppBlocObserver();
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
if (USE_EMULATOR) {
await _connectToFirebaseEmulator();
}
runZonedGuarded(() {
runApp(ElectronicCupongs(appTitle: 'LunchBrejk'));
}, (error, stacktrace) {
FirebaseCrashlytics.instance.recordError(error, stacktrace);
});
}
/// Connect to firebase emulator and authentication
Future _connectToFirebaseEmulator() async {
final localHost = Platform.isAndroid ? '127.0.0.1' : 'localhost';
// FirebaseFirestore.instance.settings = Settings(
// host: '$localHost:8080', sslEnabled: false, persistenceEnabled: false);
FirebaseFirestore.instance.useFirestoreEmulator(localHost, 8080);
FirebaseStorage.instance.useStorageEmulator(localHost, 9199);
FirebaseFunctions.instance.useFunctionsEmulator(localHost, 5001);
await FirebaseAuth.instance.useAuthEmulator(localHost, 9099);
}
当 flutter 启动时,我会在调试控制台中看到此信息。
I/flutter ( 7233): Mapping Firestore Emulator host "127.0.0.1" to "10.0.2.2".
I/flutter ( 7233): Mapping Storage Emulator host "127.0.0.1" to "10.0.2.2".
I/flutter ( 7233): Mapping Functions Emulator host "127.0.0.1" to "10.0.2.2".
I/flutter ( 7233): Mapping Auth Emulator host "127.0.0.1" to "10.0.2.2".
所以看起来 flutter 设置正确。但是当我尝试从存储加载图像时,我得到了。
I/flutter ( 7233): CacheManager: Failed to download file from http://localhost:9199/v0/b/default-bucket/o/restaurants%2FR81.jpg?alt=media&token=4983e466-53d1-4f4e-a1d4-09cce1b27ba1 with error:
I/flutter ( 7233): SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 39308
如果我点击链接,我会在浏览器中看到该图像。
我已确保可以通过更改 storage.rules 文件进行读写
顺便说一句,我正在使用cached_network_image,也许它可以处理模拟器?
Android 模拟器使用端口
10.0.2.2
作为本地主机:
您的开发机器上的地址127.0.0.1对应的是 模拟器的环回接口。访问您的计算机上运行的服务 开发机环回接口,使用特殊地址 改为 10.0.2.2。[1]
因此,一个简单的解决方法是在加载图像之前将 localhost
127.0.0.1
替换为 10.0.2.2
:
final String imageUrl = "http://127.0.0.1:9199/...";
if (UniversalPlatform.isAndroid && kDebugMode)
imageUrl = imageUrl.replaceAll("127.0.0.1", "10.0.2.2");
return CachedNetworkImage(imageUrl: imageUrl);
//or
return Image.network(imageUrl);
[1] https://developer.android.com/studio/run/emulator-networking#networkaddresses