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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法从Firebase数据库中读取数据 - 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)
}

绝望地需要帮助。我将非常感谢社区。没有明显的理由出现。

答案

这是从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;
        });
    });
}

以上是关于无法从Firebase数据库中读取数据 - Flutter的主要内容,如果未能解决你的问题,请参考以下文章

无法从 Firebase 读取用户数据

“从 Firebase 读取数据”,更新 2.8.1 后无法正常工作

从 Firebase 读取数据并保存到数组中 (Swift)

从Firebase读取数据到Android目前没有代码

无法将数据从 Firebase 附加到数组 SwiftUI

从Firebase实时数据库读取Android数据并在RecyclerView上显示