List<Photo> imgList = [];
Future getCarouselWidget() async {
var firestore = Firestore.instance;
QuerySnapshot qn =
await firestore.collection("history").getDocuments();
List pics = qn.documents
.map((it) => Photo(it['photo'].toString(), it['name'].toString(), it['address'].toString()))
.toList();
return imgList = pics;
}
Hi all, when I make changes in my DB I dont see them in my app? can anybody help me or guid me how to wire this to stream builder or query the stream
StreamBuilder<QuerySnapshot>(
stream: Firestore.instance
.collection('swimfinderlakes')
.snapshots(),
builder: (context, snapshot) {
Every time Firestore has a change, it'll trigger the StreamBuilder. U can then access the most recently update with the snapshot on the builder method. Then you can use it to update the ui accordingly.
StreamBuilder<QuerySnapshot>(
stream: Firestore.instance
.collection('swimfinderlakes')
.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
if (snapshot.hasData) {
List pics = qn.documents
.map((it) => Photo(it['photo'].toString(),
it['name'].toString(), it['address'].toString())).toList();
return pics;
}
} else {
return CircularProgressIndicator();
}
}
Related
I have a StreamBuilder to check for an empty string But I want to turn it to check for an empty array. How can I do that?
bool? checkEmpty = false;
StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance
.collection('widgets')
.doc(widgets)
.snapshots(),
builder: (context, snapshot) {
snapshot.data?.data()?.forEach((key, value) {
if (key == 'imageUrl') {
checkEmpty = value == [];
}
});
return ...
checkEmpty!
? Text('Array is not empty')
: Text('Empty array'),
cast the value type as List then check over it.
try the following:
bool? checkEmpty = false;
StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance
.collection('widgets')
.doc(widgets)
.snapshots(),
builder: (context, snapshot) {
snapshot.data?.data()?.forEach((key, value) {
if (key == 'imageUrl') {
checkEmpty = (value as List).isEmpty;
}
});
return ...
checkEmpty!
? Text('Array is not empty')
: Text('Empty array'),
This is my stream function:
Stream<QuerySnapshot> getPortfolios() {
return db
.collection('users')
.doc(authService.getUser().uid)
.collection('portfolios')
.snapshots();
}
In the StreamBuilder I get the list like this:
portfolios = snapshot.data!.docs;
That gives my a list but a list of JsonQueryDocumentSnapshot. With each item I can do .data() and I get the info I need, but how could I get this map directly in the list without calling extra methods?
I tried this old answer but it doesn't work anymore:
final QuerySnapshot<Object?>? ds = snapshot.data;
final Map<String, dynamic> map = ds!.data; // this .data is not recognised
You can use ".docs" on the snapshot to get a list of QueryDocumentSnapshot which have some of the same properties as a map, so you can directly reference a value like im doing below:
List<QueryDocumentSnapshot> data = snapshot.data!.docs;
String name = data[i]['name']
Here is a full example :
StreamBuilder<QuerySnapshot>(
stream: db.collection('users').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
List<QueryDocumentSnapshot> data = snapshot.data!.docs;
return ListView.builder(
itemCount: snapshot.data!.size,
itemBuilder: (context, i) {
return Text('${data[i]['name']}');
},
);
} else {
return CircularProgressIndicator();
}
},
),
Alternatively you can map the Stream to any object like this:
Stream<QuerySnapshot<Map<String, dynamic>>> snaphot = db
.collection('users')
.doc(authService.getUser().uid)
.collection('portfolios')
.snapshots();
//Map to an object (note that you need to create a "fromJson" method for your object.
Stream<List<YourObject>> dataStream = snaphot.map((list) => list.docs.map((doc) => YourObject.fromJson(doc.data())).toList());
Now you can use the "dataStream" in your stream builder and directly reference the items in the list with "snapshot.data".
// snapshot.data is now the type:
List<YourObject>
I used this code bevor migration
StreamBuilder(
stream: FirebaseDatabase.instance
.ref()
.child('user')
.child(_userID)
.onValue,
builder: (context, snapshot) {
if (snapshot.hasData) {
_networkImageUrl = snapshot.data.snapshot.value["img"];
return Text(_networkImageUrl.toString());
} else {
return Container();
}
}),
after "dart pub upgrade --null-safety" I get the error:
The property 'snapshot' can't be unconditionally accessed because the receiver can be 'null'.
I tried to fix it with "!" but it doesn't work, it keeps the same error
this is the code:
StreamBuilder<DatabaseEvent>(
stream: FirebaseDatabase.instance
.ref()
.child('user')
.child(_userID)
.onValue,
builder: (BuildContext context,AsyncSnapshot snapshot) {
if (snapshot.hasData) {
Map<dynamic, dynamic> userDocument = snapshot.data.snapshot.value;
_networkImageUrl = userDocument["img"]
return Text(_networkImageUrl.toString());
} else {
return Container();
}
}),
Thanks to #h8moss
I try to count all docs from one user in firestore.
My code:
Widget booksWidget(String userData) {
return
StreamBuilder(
stream: FirebaseFirestore.instance
.collection("bookList")
.doc(userData)
.collection(userData)
.orderBy("timestamp", descending: true)
.snapshots(),
builder: (BuildContext context,AsyncSnapshot snapshot) {
if (snapshot.hasData) {
var userDocument = snapshot.data as DocumentSnapshot?;
String books = userDocument?.length.toString();
return Text(books);
}else{
return Text("none");
}
}
);
}
the error:
The getter 'length' isn't defined for the type 'DocumentSnapshot<Object?>'.
thanks for help, streambuilder after migration to null-safety is quite different :(
You're requesting the snapshots of a query, so the snapshot.data that you get is going to be of type QuerySnapshot (and not a DocumentSnapshot? as you assume now).
if (snapshot.hasData) {
var querySnapshot = snapshot.data! as QuerySnapshot;
String books = querySnapshot.docs.length.toString();
...
In cases like this I find it easiest to work from the reference documentation, such as the one for Query.snapshots() here.
I am trying to display post with queries in Page view builder with the help of stream builder but not able to get the data with the separate function I made. I have tried calling the function in stream but then I don't get any data. how can I call the following function in stream. Or do I need to try something else instead of stream builder?
If I do this then it display the Page view builder but with no condition and fetch all the data.
StreamBuilder<QuerySnapshot>(
stream:FirebaseFirestore.instance.collection('users')..doc(auth.currentUser.uid)
.collection('plans').snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot){
if (!snapshot.hasData){
return Text(
"No Data",
);
}if(snapshot.hasData){
return PageView.builder(.........),
And if I call getUserPlan() then I dont get data.
StreamBuilder<QuerySnapshot>(
stream: getUserPlan(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot){
if (!snapshot.hasData){
return Text(
"No Data",
);
}if(snapshot.hasData){
return PageView.builder(.........),
function getUserPlan:- // I want to stream data with all this queries/conditions.
getUserPlan() {
List pUser = [];
FirebaseFirestore.instance.collection('users').doc(auth.currentUser.uid)
.collection('plans').where('pTimeStamp',
isGreaterThanOrEqualTo: DateTime.now())
.orderBy('pTimeStamp', descending: true).get().then((_){
query().get().then((data)async{
if (data.docs.length < 1 ) {
print("no more Plan data");
return;
}
for (var doc in data.docs) {
CreateAccountData temp = CreateAccountData.fromDocument(doc);
var distance = calculateDistance(
currentUser.coordinates['latitude'],
currentUser.coordinates['longitude'],
temp.coordinates['latitude'],
temp.coordinates['longitude']);
temp.distanceBW = distance.round();
if (pUser.any(
(value) => value == temp.uid,
)) {
} else {
if (distance <= currentUser.maxDistance && temp.uid != currentUser.uid && !temp.isBlocked){pUsers.add(temp);}
}
}
if (mounted) setState(() {});
});
});
}
query() {
if (currentUser.showGender == 'everyone') {
return docRef
.where('age',
isGreaterThanOrEqualTo: currentUser.ageRange['min'],
)
.where('age',
isLessThanOrEqualTo:currentUser.ageRange['max'])
.orderBy('age', descending: false).limit(30);
} else {
return docRef
.where('editInfo.userGender', isEqualTo: currentUser.showGender)
.where('age',
isGreaterThanOrEqualTo:currentUser.ageRange['min'],
)
.where('age',
isLessThanOrEqualTo: currentUser.ageRange['max'])
.orderBy('age', descending: false).limit(30);
}
}