如何在flutter中使用firebase的子添加事件来检索列表?

问题描述 投票:1回答:2

我想使用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"]);
            },
          );
        },
      ),
    );
  }
}

[更新]这是数据库结构

This is the structure of my database

firebase firebase-realtime-database dart flutter
2个回答
0
投票

尽量不要使用“onChildAdded”。这只能获得最近添加的孩子。你想要所有的孩子,但是想把自己限制在最近的5个(你用limitToLast做的事情)。


-1
投票

我也遇到了这个问题,发现不使用StreamBuilder小部件更容易。当使用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()时,侦听会停止。

© www.soinside.com 2019 - 2024. All rights reserved.