在Flutter中添加记录时,Cloud Firestore无法正确更新

时间:2018-02-02 19:02:17

标签: firebase dart flutter

我正在开发一个Flutter应用,我正在使用cloud_firestore插件。我有一组提交,我使用StreamBuilder来显示它们(我假设它会在流更改时更新)。我真的从插件示例中获取了示例,因为没有太多关于如何使用插件执行操作的文档。当我添加记录时,我显示的文档列表会变长,但它似乎是复制其中一个提交而不是插入新提交。添加后,新提交不会显示。以下是我如何显示列表的代码:

// At the top of the class home.dart. 
final submissions = Firestore.instance.collection('submissions');

// This is in submission-list.dart and the above submissions 
// is passed in to the contructor
Widget build(BuildContext context) {
    return new StreamBuilder<QuerySnapshot>(
      stream: submissions
          .where('owner_uid', isEqualTo: this.user.uid)
          .orderBy('timestamp', descending: true)
          .snapshots,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (!snapshot.hasData) return new Text('Loading...');
        return new ListView(
          children: snapshot.data.documents.map((DocumentSnapshot document) {
            var date = _formatDate(document['timestamp']);
            String body = _constructCardBody(document['weight'],
                bodyFat: document['bodyFat']);
            String id = document.documentID;
            return new SubmissionCard(id: id, title: date, body: body, submissions: submissions);
          }).toList(),
        );
      },
    );
  }

这是submission-card.dart的完整内容:

import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

import '../utils/logger.dart';
import './block-button.dart';

class SubmissionCard extends StatefulWidget {
  final String id;
  final String title;
  final String body;
  final CollectionReference submissions;

  SubmissionCard({this.id, this.title, this.body, this.submissions});

  @override
  State<StatefulWidget> createState() =>
      new _SubmissionCardState(id: this.id, title: this.title, body: this.body, submissions: this.submissions);
}

class _SubmissionCardState extends State<SubmissionCard> {
  final String id;
  final String title;
  final String body;
  bool showActionButtons = false;
  final CollectionReference submissions;

  _SubmissionCardState({this.id, this.title, this.body, this.submissions});

  void _showEditScreen() {}

  void _showActionButtons() {
    setState(() {
      showActionButtons = true;
    });
  }

  void _hideActionButtons() {
    setState(() {
      showActionButtons = false;
    });
  }

  Future<Null> _deleteSubmission() async {
    try {
      await submissions.document(id).delete();
      await Logger.log('error', 'stackTrace');
    } catch (error, stackTrace) {
      await Logger.log(error, stackTrace);
    }
  }

  void _closeDialog() {
    Navigator.of(context).pop();
    _hideActionButtons();
  }

  Future<Null> _warnAboutDeletion() async {
    return showDialog(
        context: context,
        child: new SimpleDialog(
          title: new Text('Are you sure?'),
          children: <Widget>[
            new SimpleDialogOption(
              onPressed: () {
                this._deleteSubmission();
                this._closeDialog();
              },
              child: new Text("I'm sure. Delete it."),
            ),
            new SimpleDialogOption(
              onPressed: _closeDialog,
              child: new Text("Nope. Take me back."),
            ),
          ],
        )
    );
  }

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onLongPress: _showActionButtons,
      onTap: _hideActionButtons,
      child: new Card(
        elevation: showActionButtons ? 8.0 : 2.0,
        key: new GlobalKey(),
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            new ListTile(
              trailing: showActionButtons
                  ? new Row(
                      children: <Widget>[
                        new IconButton(
                          padding: const EdgeInsets.all(0.0),
                          icon: const Icon(Icons.edit),
                          onPressed: _showEditScreen,
                          color: Colors.black12,
                          splashColor: Colors.black26,
                          highlightColor: Colors.black12,
                        ),
                        new IconButton(
                          padding: const EdgeInsets.all(0.0),
                          icon: const Icon(Icons.delete),
                          onPressed: _warnAboutDeletion,
                          color: Colors.redAccent,
                          splashColor: Colors.black26,
                          highlightColor: Colors.black12,
                        ),
                      ],
                    )
                  : new Container(),
              isThreeLine: true,
              title: new Text(title),
              subtitle: new Text(
                body,
                style: new TextStyle(height: 3.0),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

链接到回购:https://github.com/dericgw/bodwatch

之前,当我使用Firebase时,此集合会自动更新。我以前从未见过这种奇怪的行为。现在,我是Flutter和Dart的新手,所以我肯定会错过一些东西。

1 个答案:

答案 0 :(得分:1)

您需要在Firebase控制台中添加索引。

在您的情况下,您需要多个索引。 1. owner_uid,升序 2.时间戳记,降序

问题应该解决。