无法从Firebase数据库读取数据-Flutter

时间:2019-01-12 20:47:57

标签: firebase firebase-realtime-database flutter

因此,基本上,我试图从数据库中获取数据,但无法获取。当命令执行读操作时,该过程将继续进行,没有任何返回结果,因此我不得不故意使其超时。我能够将数据写入数据库。这是显示我在做什么的算法

importing file

//database is initialized in another file which is imported

reference = instance.reference();

Async getData(reference){
reference.once.then(DataSnapshot){print(DataSnapshot)}
}

void main(){
getData(reference)
}

迫切需要帮助。我将非常感谢社区。没有明显的原因出现。

1 个答案:

答案 0 :(得分:0)

这是从Firestore数据库读取数据的示例示例,我建议您将其用于您的应用。

模型[post.dart]

class PostItem {
    final String id;
    final String name;

    PostItem({
        this.id,
        this.name
    })  :   assert(id != null && id.isNotEmpty),
            assert(name != null && name.isNotEmpty);

    PostItem.fromMap(Map<String, dynamic> data)
        : this(
            id: data['id'],
            name: data['name']
        );

    Map<String, dynamic> toMap() => {
        'id': this.id,
        'name': this.name
    };
}

用于管理与Firestore之间的数据的服务[PostStorage.dart]

import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:your_app/models/post.dart';

final CollectionReference postCollection = Firestore.instance.collection('Posts');

class PostStorage {

static PostItem fromDocument(DocumentSnapshot document) => _fromMap(document.data);

static PostItem _fromMap(Map<String, dynamic> data) => new PostItem.fromMap(data);

Map<String, dynamic> _toMap(PostItem item, [Map<String, dynamic> other]) {
    final Map<String, dynamic> result = {};
    if (other != null) {
        result.addAll(other);
    }
    result.addAll(item.toMap());

    return result;
}

/// Returns a stream of data snapshots
Stream<QuerySnapshot> list() {
    Stream<QuerySnapshot> snapshots = postCollection.snapshots();
    return snapshots;
}

Future create(Post post) async {
    final TransactionHandler createTransaction = (Transaction tx) async {
        final DocumentSnapshot newDoc = await tx.get(postCollection.document());
        final PostItem newItem = new PostItem(
            id: newDoc.documentID,
            name: post.name
        );
        final Map<String, dynamic> data = _toMap(newItem, {
            'created': new DateTime.now().toUtc(),
        });
        await tx.set(newDoc.reference, data);

        return data;
    };

    return Firestore.instance.runTransaction(createTransaction)
    .then(_fromMap)
    .catchError((e) {
        print('dart error: $e');
        return null;
    });
}

Future<bool> update(PostItem item) async {
    final TransactionHandler updateTransaction = (Transaction tx) async {
        final DocumentSnapshot doc = await tx.get(postCollection.document(item.id));

        await tx.update(doc.reference, _toMap(item));
        return {'result': true};
    };

    return Firestore.instance.runTransaction(updateTransaction).then((r) {
        return r['result'] == true; // forcefully cast to boolean
    }).catchError((e) {
        print('dart error: $e');
        return false;
    });
}

Future delete(String id) async {
    final TransactionHandler deleteTransaction = (Transaction tx) async {
        final DocumentSnapshot doc = await tx.get(postCollection.document(id));
        await tx.delete(doc.reference);
        return {'result': true};
    };

    return Firestore.instance.runTransaction(deleteTransaction).then((r) => r['result']).catchError((e) {
        print('dart error: $e}');
        return false;
    });
}

}

在您要检索数据的页面中,这是一个很小的代码:

StreamSubscription<QuerySnapshot> postSub;
List<PostItem> listPost = [];
PostStorage postStorage = new PostStorage();

@override
void initState() {
    findPost();
    super.initState();
}

@override
void dispose() {
    postSub?.cancel();
    super.dispose();
}

/// Get all types from DB Firestore
findPost() {
    postSub?.cancel();
    // Listen Firestore
    typeSub = postStorage.list().listen((QuerySnapshot snapshot){
        // Get Value
        final List<PostItem> listPost = snapshot.documents.map(PostStorage.fromDocument).toList();
        setState(() {
            this.listPost = listPost;
        });
    });
}