如何检查我的cloudfirestore集合是否包含任何文档



我正在尝试检查我的消防仓库收藏"付款";包含字符串userActive包含在任何名为参与者的文档字段数组中的任何文档,如果它不执行操作或执行不同的操作,这是我迄今为止尝试过的,但它不起作用

import 'package:flutter/material.dart';
import 'package:wallet_app/send.dart';
import 'package:wallet_app/send_money.dart';
import 'package:wallet_app/recieve.dart';
import 'package:wallet_app/load.dart';
import 'package:wallet_app/account.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:wallet_app/CardScreen.dart';
import 'package:flutter_icons/flutter_icons.dart';

class HomeScreener extends StatefulWidget{
HomeScreen createState()=> HomeScreen();
}

class HomeScreen extends State<HomeScreener> {
HomeScreen createState() => HomeScreen();

final databaseReference = FirebaseFirestore.instance;




var userId = "dAIdrQggsrxvQ4KUo2aJ";
var userActive = "kim";
var userHasData = 0;

checkDatabase()async {

final docSnapshot = await FirebaseFirestore.instance
.collection('payments')
.where('participants', arrayContains: userActive)
.getDocuments();
if(docSnapshot.documents.isEmpty) {
// Your queried documents do not exist
userHasData = 1;
}
else if(docSnapshot.documents.isEmpty){
// Your queried documents do not exist
}
userHasData = 2;     
}

@override
Widget build(BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height,
width: double.infinity,
child: Stack(
children: <Widget>[
//Container for top data
Container(

margin: EdgeInsets.symmetric(horizontal: 32, vertical: 32),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text("Hello " + "$userActive", style: TextStyle(color: Colors.white, fontSize: 28, fontWeight: FontWeight.w700),),
Container(
margin: EdgeInsets.only(top: 20),
child: Row(
children: <Widget>[
// Icon(Icons.notifications, color: Colors.lightBlue[100],),
SizedBox(width: 16,),
CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
child: ClipOval(
child: Image.asset("assets/newdp.png", fit: BoxFit.contain,), 
),
)
],
),
)
],
),
Text("What would you like to do today?", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 16, color: Colors.blue[100]),),
SizedBox(height : 40,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
child: Column(
children: <Widget>[
Container(

decoration: BoxDecoration(
color: Color.fromRGBO(243, 245, 248, 1),
borderRadius: BorderRadius.all(Radius.circular(18))
),
child:IconButton(
icon: Icon(Icons.send, color: Colors.blue[900], size: 30,),
onPressed: () { 


Navigator.push(
context,
MaterialPageRoute(builder: (context) => sendPager()),
);
},


), 
padding: EdgeInsets.all(3),
),
SizedBox(
height: 10,
),
Text("Send", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Colors.blue[100]),),
],
),
),
Container(
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Color.fromRGBO(243, 245, 248, 1),
borderRadius: BorderRadius.all(Radius.circular(18))
),
child:IconButton(
icon: Icon(Icons.account_balance, color: Colors.blue[900], size: 30,),
onPressed: () { 


Navigator.push(
context,
MaterialPageRoute(builder: (context) => loadPager()),
);
},


), 
padding: EdgeInsets.all(3),
),
SizedBox(
height: 10,
),
Text("Account", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Colors.blue[100]),), 
],
),
),
Container(
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Color.fromRGBO(243, 245, 248, 1),
borderRadius: BorderRadius.all(Radius.circular(18))
),
child:IconButton(
icon: Icon(Icons.people, color: Colors.blue[900], size: 30,),
onPressed: () { 


Navigator.push(
context,
MaterialPageRoute(builder: (context) => loadPager()),
);
},


), 
padding: EdgeInsets.all(3),
),
SizedBox(
height: 10,
),
Text("Recipients", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Colors.blue[100]),),
],
),
),
Container(
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Color.fromRGBO(243, 245, 248, 1),
borderRadius: BorderRadius.all(Radius.circular(18))
),
child:IconButton(
icon: Icon(Icons.add, color: Colors.blue[900], size: 30,),
onPressed: () { 

databaseReference.collection("payments").add(
{
"amount_paid" : "2444242",
"amount_received" : "33535",
"currency_received" : "¥",
"currency_sent" :"K",
'date':FieldValue.serverTimestamp(),
"participants" :["kim", "john"  ],
"receiver_name" : "john",
"sender_name" : "kim"

}).then((value){
print("================================sucess=============================================================");
print(value.documentID);
});


Navigator.push(
context,
MaterialPageRoute(builder: (context) => loadPager()),
);
},


), 
padding: EdgeInsets.all(3),
),
SizedBox(
height: 10,
),
Text("Invite", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Colors.blue[100]),),
],
),
)
],
)
],
),
),

//draggable sheet
DraggableScrollableSheet(
builder: (context, scrollController){
return Container(
decoration: BoxDecoration(
color: Color.fromRGBO(243, 245, 248, 1),
borderRadius: BorderRadius.only(topLeft: Radius.circular(40), topRight: Radius.circular(40))
),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(height: 24,),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text("Recent Transactions", style: TextStyle(fontWeight: FontWeight.w900, fontSize: 24, color: Colors.black),),
Text("See all", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 16, color: Colors.grey[800]),)
],
),
padding: EdgeInsets.symmetric(horizontal: 32),
),
SizedBox(height: 24,),
//Container for buttons
Container(
padding: EdgeInsets.symmetric(horizontal: 32),
child: Row(
children: <Widget>[
Container(
child: Text("All", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Colors.grey[900]),),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20)),
boxShadow: [BoxShadow(color: Colors.grey[200], blurRadius: 10.0, spreadRadius: 4.5)]
),
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
),
SizedBox(width: 16,),
Container(
child: Row(
children: <Widget>[
CircleAvatar(
radius: 8,
backgroundColor: Colors.green,
),
SizedBox(
width: 8,
),
Text("Recieved", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Colors.grey[900]),),
],
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20)),
boxShadow: [BoxShadow(color: Colors.grey[200], blurRadius: 10.0, spreadRadius: 4.5)]
),
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
),
SizedBox(width: 16,),
Container(
child: Row(
children: <Widget>[
CircleAvatar(
radius: 8,
backgroundColor: Colors.orange,
),
SizedBox(
width: 8,
),
Text("Transfer", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Colors.grey[900]),),
],
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20)),
boxShadow: [BoxShadow(color: Colors.grey[200], blurRadius: 10.0, spreadRadius: 4.5)]
),
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
)
],
),
),
SizedBox(height: 16,),
//Container Listview for expenses and incomes
Container(
child: Text(" ", style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Colors.grey[500]),),
padding: EdgeInsets.symmetric(horizontal: 32),
),                      

SizedBox(height: 5),

StreamBuilder( 
stream: FirebaseFirestore.instance.collection("payments").where('participants', arrayContains: userActive).snapshots(),
builder: (context, snapshot){

checkDatabase();

return Container ( child:ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.documents.length,
padding: EdgeInsets.all(0),
controller: ScrollController(keepScrollOffset: false),
itemBuilder: (context, index){
DocumentSnapshot documentSnapshot = snapshot.data.docs[index];

//if(snapshot.connectionState == ConnectionState.active && snapshot.hasData) {
if(userHasData == 1){
print(" no Data!!!");
return Center(child: Text("No Data"));


}




else if (userHasData == 2){ 


print("Found Data!!!");
if(documentSnapshot.data()["receiver_name"] == userActive )  {         


return Container(
margin: EdgeInsets.symmetric(horizontal: 32,vertical: 5),
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20))
),
child: Row(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.grey[100],
borderRadius: BorderRadius.all(Radius.circular(18))
),
child: Icon(Icons.attach_money, color: Colors.lightBlue[900],),
padding: EdgeInsets.all(12),
),
SizedBox(width: 16,),
Expanded(

child: Column(

crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[

Text("Recieved", style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Colors.grey[900]),) ,


Text("" + documentSnapshot.data()["currency_received"] + documentSnapshot.data()["amount_received"], style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Colors.grey[500]),),





],
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[


Text("+ " + documentSnapshot.data()["currency_sent"] + documentSnapshot.data()["amount_paid"].toString(), style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Colors.lightGreen),),


Text(documentSnapshot.data()["date"].toDate().toString(), style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Colors.grey[500]),),                                
],
),
],
),
);

}else if (documentSnapshot.data()["sender_name"] == userActive){

return Container(
margin: EdgeInsets.symmetric(horizontal: 32,vertical: 5),
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20))
),
child: Row(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.grey[100],
borderRadius: BorderRadius.all(Radius.circular(18))
),
child: Icon(Icons.attach_money, color: Colors.lightBlue[900],),
padding: EdgeInsets.all(12),
),
SizedBox(width: 16,),
Expanded(

child: Column(

crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[

Text("Sent", style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Colors.grey[900]),) ,


Text("" +  documentSnapshot.data()["currency_received"] + documentSnapshot.data()["amount_received"], style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Colors.grey[500]),),





],
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[


Text("- " + documentSnapshot.data()["currency_sent"] + documentSnapshot.data()["amount_paid"].toString(), style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Colors.orange),),


Text(documentSnapshot.data()["date"].toDate().toString(), style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Colors.grey[500]),),

],
),
],
),
);







}






}




//  }    return Center(child: const CircularProgressIndicator());



}





)
);

}



),


],
),
controller: scrollController,
),
);
},
initialChildSize: 0.65,
minChildSize: 0.65,
maxChildSize: 1,
)
],
),
);
}
}

尝试使用.exists:

final docSnapshot = await Firestore.instance.collection('payments').document("document_id").get();
if (docSnapshot.exists){
//document exists
}
else{
//document does not exists 
}

对于所有文档:

final doc = await Firestore.instance.collection('payments').getDocuments();

if (doc.documents.isEmpty){
//Collection is empty 
}
else{
//collection has documents
}

您可以在元素中使用逻辑之前应用该逻辑,就像在类的开头使用futureBuilder一样。您可以使用上述逻辑设置bool,然后使用visibility小部件仅在文档可用时显示futureBuilder


对于您的情况:

final docSnapshot = await Firestore.instance
.collection('bus_information_user')
.where('participants', arrayContains: userActive)
.getDocuments();
if(docSnapshot.documents.isEmpty){
// Your queried dosuments does not exist
}
else{
// Your queried dosuments does exist
}

Ps:我还没有试过最后一部分,但应该完成这项工作。

最新更新