在Flutter应用程序中显示Firestore数据库中的文档,可以按照以下步骤进行操作:
dependencies:
flutter:
sdk: flutter
firebase_core: ^1.0.0
cloud_firestore: ^2.0.0
flutter pub get
命令以获取新添加的依赖。import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
import 'package:cloud_firestore/cloud_firestore.dart';
final FirebaseFirestore firestore = FirebaseFirestore.instance;
final CollectionReference documentsRef = firestore.collection('documents');
void getDocuments() {
documentsRef.get().then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
print(doc.data());
});
});
}
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class DocumentScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Firestore Documents'),
),
body: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('documents').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
return ListView(
children: snapshot.data.docs.map((DocumentSnapshot document) {
return ListTile(
title: Text(document.data()['title']),
subtitle: Text(document.data()['description']),
);
}).toList(),
);
},
),
);
}
}
以上代码使用了StreamBuilder来监听Firestore中文档的实时变化,并将数据展示在ListView中。
推荐的腾讯云相关产品:腾讯云开发平台(Tencent Cloud Base),链接地址:https://cloud.tencent.com/product/tcb
领取专属 10元无门槛券
手把手带您无忧上云