我想使用Stream对象使用firebase的子添加方法从我的firebase实时数据库中检索列表。我已经配置了我的应用程序,如下所示,但我只加载了1个“问题”(最新的一个),其余的根本没有加载。
我的数据库中确实有5个以上的问题。如何从实时数据库中获取5个最新问题的列表?
class _QuestionPageState extends State<QuestionsPage> {
List _questions = [];
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
body: new StreamBuilder(
stream: FirebaseDatabase.instance
.reference()
.child('questions')
.limitToLast(5)
.onChildAdded,
builder: (context, snap) {
if (snap.hasError) return new Text('Error: ${snap.error}');
if (snap.data == null)
return new Center(
child: new CircularProgressIndicator(),
);
print(snap.data.snapshot.key);
print(snap.data.snapshot);
final question = snap.data.snapshot.value;
this._questions.add(question);
return new ListView.builder(
itemCount: this._questions.length,
itemBuilder: (context, index) {
print("question");
print(this._questions[index]["meta"]["question"]);
return new Text(this._questions[index]["meta"]["question"]);
},
);
},
),
);
}
}
[更新] 这是数据库结构
答案 0 :(得分:0)
尽量不要使用&#34; onChildAdded&#34;。这只能获得最近添加的孩子。你想要所有的孩子,但是想把自己限制在最近的5个(你使用limitToLast做的事情)。
答案 1 :(得分:-1)
我也遇到了这个问题,发现不使用StreamBuilder Widget更加容易。使用StreamBuilder时,我必须使用.onValue而不是.onChildAdded才能返回所有子项,但是.onValue以无法预测的顺序返回了子项,因为它以地图的形式返回。
相反,我认为最好创建一个StreamSubscription并在initState()中调用它,如下所示。新的子级将添加到数组中,并且该数组用于构建ListView。我正在索引0处插入新的子项,以便最新的帖子位于表的顶部。
class NotificationsFeedPage extends StatefulWidget {
@override
_NotificationsFeedPageState createState() => _NotificationsFeedPageState();
}
class _NotificationsFeedPageState extends State<NotificationsFeedPage> {
List <Notification> notificationList = [];
StreamSubscription <Event> updates;
@override
void initState() {
// TODO: implement initState
super.initState();
updates = FirebaseDatabase.instance.reference().child('notifications').child(currentUser.uid).limitToLast(50).onChildAdded.listen((data) {
notificationList.insert(0, Notification.fromFireBase(data.snapshot));
setState(() {
});
} );
}
@override
void dispose() {
// TODO: implement dispose
updates.cancel();
super.dispose();
}
通知是自定义类,如下所示:
class Notification {
String name;
bool isComment;
String user;
String comment;
Notification.fromFireBase(DataSnapshot snapshot) {
this.name = snapshot.value["name"] ?? 'Unknown user';
this.isComment = snapshot.value["isComment"] ?? false;
this.user = snapshot.value["user"] ?? '';
this.comment = snapshot.value["comment"] ?? '';
}
}
此操作将继续进行监听,直到处理完该视图为止。调用updates.cancel()时,监听会停止。