在我的 flutter 开发过程中,我遇到了许多 Firebase 插件相互不合作的问题,并且在缩小兼容包版本的范围时遇到了相当大的困难。我最近添加了 firebase_database,但似乎找不到一个稳定的配置,可以让我实际使用实时连接而不会使我的应用程序崩溃。
如果任何人都可以分享他们使用过的类似设置并且可以确认其稳定,这将极大地帮助我缩小出现问题的可能性。
这是我的 pubspec.yaml 的相关部分:
environment:
sdk: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
firebase_core: ^2.1.0
firebase_auth: ^4.0.0
cloud_firestore: ^4.9.0
firebase_database: ^10.2.7
firebase_analytics: ^10.0.0
cloud_functions: ^4.0.0
#firebase_messaging will be needed eventually, but not now.
很久以前,我发现一个页面,直接列出了哪些版本是要一起使用的,但一年多以来一直无法再次找到它。如果它仍然存在,有人可以给我发一个链接吗?我想更永久地解决 firebase 依赖问题,因为这对我来说是一个反复出现的问题。
作为第二个问题,这是我的应用程序中导致崩溃的相关部分。我很难找出问题所在,因为每当我听它时,我的应用程序都会立即崩溃,但这似乎与返回 _dbRef 的任何属性有关。
import 'package:firebase_database/firebase_database.dart';
class RealtimeService {
final DatabaseReference _dbRef = FirebaseDatabase.instance.ref();
String encodeFirebaseKey(String key) {
return Uri.encodeComponent(key);
}
String decodeFirebaseKey(String encodedKey) {
return Uri.decodeComponent(encodedKey);
}
Stream<Map<String, Conversation>> getConversationsStream(String userEmail) {
// Check for null _dbRef
if (_dbRef == null) {
print('Error: _dbRef is null');
return Stream.error('Database reference is null');
}
String encodedEmail = encodeFirebaseKey(userEmail);
// Listen for values and handle potential errors inside asyncMap
return _dbRef
.child('userConversations')
.child(encodedEmail)
.onValue
.asyncMap((event) async {
print('mark 1');
try {
print('mark 2');
Map<String, dynamic> userConvos = event.snapshot.value as Map<
String,
dynamic> ?? {};
if (userConvos.isEmpty) {
return {}; // Return empty map if no conversations found
}
// Fetching details of each conversation and mapping it to a list
Map<String, Conversation> conversations = {};
await Future.wait(userConvos.keys.map((convoId) async {
DataSnapshot convoSnapshot = (await _dbRef.child('conversations')
.child(convoId)
.once()).snapshot;
if (convoSnapshot.value != null) {
conversations[convoId] = ConversationObject.fromMap(
map: convoSnapshot.value as Map<String, dynamic>);
}
}));
return conversations;
} catch (e) {
print('Error in asyncMap: $e');
throw e;
}
});
}
}
我能够追踪问题。默认情况下,Uri.encodeComponent() 方法不会转义句点 (.) 字符,因为它被视为 URI 组件中的安全字符。但是,由于 Firebase 实时数据库键不允许句点,因此我调整了编码函数以直接处理句点。
String encodeFirebaseKey(String key) {
return Uri.encodeComponent(key).replaceAll('.', '%2E');
}
String decodeFirebaseKey(String encodedKey) {
return Uri.decodeComponent(encodedKey.replaceAll('%2E', '.'));
}
因此,对于任何试图寻找 Firebase 兼容版本的人来说,我原来的问题中列出的 pubspec 是一个有效的配置。
仍在寻找一种更强大的方法来缩小兼容包的范围。