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

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

所以基本上,我试图从数据库中获取数据,但我无法得到它。当命令读取操作时,过程只是继续进行,没有任何结束,所以我不得不故意将其计时。我能够将数据写入数据库。这是算法显示我在做什么

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)
}

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

firebase firebase-realtime-database flutter
1个回答
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;
        });
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.