【发布时间】:2022-08-24 09:26:31
【问题描述】:
我想要做的是在我的 Firebase 数据库上获取密钥的值。
这是我的代码
import \'package:firebase_database/firebase_database.dart\';
import \'package:comment_app/post.dart\';
final dataReference = FirebaseDatabase.instance.ref().child(\'posts/\');
DatabaseReference savePost(Post post) {
final id = dataReference.child(\'posts/\').push();
id.set(post.toJson());
return id;
}
void updatePost(Post post, DatabaseReference id) {
id.update(post.toJson());
}
Future<List<Post>> getAllMessages() async {
DataSnapshot? dataSnapshot =
(await dataReference.child(\'posts/\').once()) as DataSnapshot;
List<Post> posts = [];
if (dataSnapshot.value != null) {
dataSnapshot.value.forEach((key, value){ //Error highlights the forEach here.
Post post = createPost(value);
post.setId(dataReference.child(\'posts/\' + key));
posts.add(post);
});
}
return posts;
}
这是 post.dart 的代码
import \'package:comment_app/authentication/database.dart\';
import \'package:firebase_auth/firebase_auth.dart\';
import \'package:firebase_database/firebase_database.dart\';
class Post {
String body;
String author;
Set userLikes = {};
late DatabaseReference _id;
Post(this.body, this.author);
void likePost(User users) {
if (userLikes.contains(users.uid)) {
userLikes.remove(users.uid);
} else {
userLikes.add(users.uid);
}
this.update();
}
void update() {
updatePost(this, _id);
}
void setId(DatabaseReference id) {
_id = id;
}
Map<String, dynamic> toJson() {
return {
\'author\': author,
\'userLikes\': userLikes.toList(),
\'body\': body,
};
}
}
Post createPost(record) {
Map<String, dynamic> attributes = {\'author\': \'\', \'userLikes\': [], \'body\': \'\'};
record.forEach((key, value) => {attributes[key] = value});
Post post = Post(attributes[\'body\'], attributes[\'author\']);
post.userLikes = Set.from(attributes[\'userLikes\']);
return post;
}
我刚刚开始学习使用 firebase 颤动,我收到了这个错误:
这是错误
方法 \'forEach\' 不能被无条件调用,因为 接收者可以是\'null\'。尝试使调用有条件(使用 \'?.\') 或向目标添加空检查 (\'!\')。
I\'m trying to get the author and body of each key in my firebase database
-
请粘贴并格式化您的代码。不是照片,尤其不是照片的链接。
-
请不要发布您的代码的屏幕截图或其他文本内容。而是发布实际文本,并使用 Stack Overflow 的格式化工具对其进行标记。另见:Why not upload images of code/errors when asking a question?
-
嗨,我已经编辑了我的问题,无论如何感谢我对堆栈溢出不熟悉的信息。
标签: flutter firebase-realtime-database