This code is running fine with futurebuilder and i m getting a listview properly.
But i want to see into the documents n print the details in console. I m not getting any idea about how to do this with QuerySnapshot variable.
Future getP() async {
var firestore = Firestore.instance;
var q = await firestore.collection('place_list').getDocuments();
print(q.documents);
return q.documents;
}
I think I have to call it n wait for the responses then print them, can anyone guide me how to do it?
List<Map<String, dynamic>> list =
q.documents.map((DocumentSnapshot doc){
return doc.data;
}).toList();
print(list);
Though the answer is right the current firebase API has changed drastically now to access QuerySnapshot one can follow the below code.
FirebaseFirestore.instance
.collection('users')
.get()
.then((QuerySnapshot querySnapshot) => {
querySnapshot.docs.forEach((doc) {
print(doc["first_name"]);
});
});
And if you are using async/await then first you need to resolve the AsyncSnapshot and then work on it. If you like:
return FutureBuilder(
future: PropertyService(uid:userId).getUserProperties(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
if (snapshot.hasError) {
return Text("Something went wrong");
}
if (snapshot.connectionState == ConnectionState.done) {
snapshot.data.docs.forEach((element) {
Property property = Property.fromJson(element.data());
});
return Text("Demo Text");
}
return LoadingPage();
}
);
taken from url
//But I am not getting all the documents present in my firestore DB collection. The first 10 or so entries are getting printed in the console. //
I think that is standard behavior. If you have one million records it can't print everything in console. To check any particular set of documents you have to filter through where condition in query.
If you have still this problem, I hope this will help you.
This is how I get data from QuerySnapshot:
QuerySnapshot snapshot =
await userCollection.where("uid", isEqualTo: uid).get();
List<Object?> data = snapshot.docs.map((e) {
return e.data();
}).toList();
Map<dynamic, dynamic> userData = data[0] as Map;
print(userData["email"]);
Or you can easily get data by:
QuerySnapshot querySnapshot =
await userCollection.where("uid", isEqualTo: uid).get();
print(querySnapshot.docs[0)['fieldName']);
Related
My below code is returning an empty list, even though it SHOULD return data corresponding to my data stored in my firestore database. Also to note: The otherUserId print statement is not getting printed. How can I fix this issue?
Future<List<String>> getChattingWith(String uid) async {
List<String> chattingWith = [];
try {
// create list of all users user is chatting with
final rooms = await FirebaseFirestore.instance
.collection('rooms')
.where('users', arrayContains: uid)
.get();
for (final room in rooms.docs) {
final users = room['users'] as Map<String, dynamic>;
final otherUserId = users['uid1'] == uid ? users['uid2'] : users['uid1'];
print("otherUserId999: $otherUserId");
chattingWith.add(otherUserId);
}
print("chattingWith: $chattingWith");
return chattingWith;
} catch (error) {
print("error: $error");
return [];
}
}
This part of your code does not match your data structure:
final rooms = await FirebaseFirestore.instance
.collection('rooms')
.where('users', arrayContains: uid)
.get();
Your users is a Map and not an array, so arrayContains won't work here. As said in my answer to your previous question, you have to use dot notation to test nested fields:
final rooms = await FirebaseFirestore.instance
.collection('rooms')
.where('users.uid1', isEqualTo: uid)
.where('users.uid2', isEqualTo: otherValue)
.get();
That 👆 is closest to what you tried in your previous question: Firestore conditional array query. It performs an AND condition on the uid1 and uid2 subfields of users.
If instead you want to get all rooms that the user is a participant in, you need an (additional) field that is an array with the UIDs of all participants.
participantUIDs: ["uid1", "uid2"]
Then you can do:
final rooms = await FirebaseFirestore.instance
.collection('rooms')
.where('participants', arrayContains: uid)
.get();
My Flutter application needs to listen for any changes in a specific Firestore document.
The process is quite simple and is found here in various solutions:
StackOverflow: flutter-firestore-how-to-listen-for-changes-to-one-document
StackOverflow:can-i-listen-to-a-single-document-in-firestore-with-a-streambuilder
StackOverflow:using-stream-building-with-a-specific-firestore-document
StackOverflow: how-to-get-a-specific-firestore-document-with-a-streambuilder
Medium: how-to-get-data-from-firestore-and-show-it-on-flutterbuilder-or-streambuilder-e05
These are all solutions to using a Stream & StreamBuilder and listening for any changes.
Commonly one uses this approach:
Stream<UserModel?> getFirestoreUser(String uid) {
return FirebaseFirestore.instance.collection('users').doc(uid).snapshots().map((event) => event.data()).map((event) => event == null ? null : UserModel.fromJson(event));
}
where:
UserModel has a fromJson(Map<String, dynamic>) factory constructor
and where there exists a users collection with the document ID being uid.
Stream returns a Stream<UserModel?> that can be used later by a Provider.of<UserModel?>(context) or in a StreamBuider<UserModel?>
Problem:
TL;DR - after a Firestore().getCurrentUser(uid) stream is updated (directly, or manually using firestore emulator and changing the document values), the StreamBuilder<UserModel?> below doesn't update.
At all points in app lifecycle (authenticated or not), the stream always returns null (however manually invoking the stream with .first returns the user content, but .last just hangs). See below for more info.
Link to github project.
To get started:
Throw in your own gooogle-services.json file into android/app folder
change all references for com.flutterprojects.myapp to ${your google-services.json package name}
Use local emulator to update firestore changes
More Details:
My issue uses a similar approach, yet the Stream doesn't return anything. My Flutter widget LoggedIn() is used when the FirebaseAuth.instance.currentUser is valid (i.e. not null)
class LoggedIn extends StatelessWidget{
#override
Widget build(BuildContext context) {
// TODO: implement build
return StreamBuilder<UserModel?>(
builder: (context, snapshot) {
print("Checking UserModel from stream provider");
if (snapshot.data == null) {
print("UserModel is null");
return UiLogin();
}
print("UserModel is NOT null");
return UiHome();
},
);
}
}
After a successful authentication, the text Checking UserModel from stream provider is printed to the console, then UserModel is null. At no point does UserModel is NOT null get shown.
After successful authentication (i.e. user registered & document updated), I have a button that I manually invoke the stream and get the first item:
var currentUser = Firestore().getCurrentUser(FirebaseAuth.instance.currentUser!.uid);
var first = await currentUser.first;
print(first);
which returns the UserModel based on the newly added user information.
When running the following code, execution stops on .last, no error, no crash, no app exit, just stops executing.
var currentUser = Firestore().getCurrentUser(FirebaseAuth.instance.currentUser!.uid);
var last = await currentUser.last;
print(last);
BUT
When adding the following, any changes gets updated and printed to the console
Firestore().getCurrentUser(currentUid).listen((data) {
print("Firestore Data Changed");
print("Firestore change value: $data");
});
This means the StreamBuilder<UserModel?> isn't working correctly, as the Stream<UserModel> events do listen() to changes and acknowledge those changes, but the StreamBuilder<UserModel?> changes do not get affected and consistently returns null.
Am I doing something wrong?
Try if (snapshot.hasData) { print("UserModel is null"); return UiLogin(); }
This is working for me. Maybe the connection states are what's missing.
StreamBuilder(
stream: FirebaseFirestore.instance
.collection('users')
.doc(widget.uid)
.collection('contacts')
.doc(widget.client)
.collection('messages')
.orderBy('timestamp', descending: true)
.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError)
return Expanded(
child: Center(child: Text('Problem Getting Your Messages')),
);
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('waiting');
case ConnectionState.waiting:
return Center(child: Text('Waiting'));
case ConnectionState.active:
var snap;
print('active');
if (snapshot.data != null) {
snap = snapshot.data;
}
return Expanded(
child: ListView(
...
);
case ConnectionState.done:
print('done');
return Text('Lost Connection');
}
return Text('NOPE');
},
),
Hey I am trying to get data of my firestore database to display it in a chart. There are some similar Questions on this topic but they couldnt solve my problem. Following the error causing widget:
Widget _buildBody(context) {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('TopTen').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return LinearProgressIndicator();
} else {
List<Klicks> klicks = snapshot.data.docs
.map(
(documentSnapshot) => Klicks.fromMap(documentSnapshot.data()))
.toList();
return _buildChart(context, klicks);
}
}
);
}
After running my App the LinearProcessIndicator is shown quickly and then the errorpage gets displayed with the following message:
Failed assertion: boolean expression must not be null
The relevant error-causing widget was
StreamBuilder<QuerySnapshot>
If I dont quit the App the errormessage gets build all the time.
I've set up the firestore collection called 'TopTen'. As requested this is the 'Klicks' class
class Klicks{
final int gesamtKlicks;
final String name;
Klicks(this.gesamtKlicks,this.name);
Klicks.fromMap(Map<String,dynamic> map)
:assert(map['gesamtKlicks']=!null),
assert(map['name']=!null),
gesamtKlicks=map['gesamtKlicks'],
name=map['name'];
#override
String toString() => "Record <$gesamtKlicks:$name>";
}
And finally the database:
thanks in advance!
I am using my own API. I only want to fetch data once when I log into my account. I found AsyncMemorizer.
AsyncMemoizer _memorizer = AsyncMemoizer();
I have 3 future functions and they return Future. Normally without AsyncMemorizer it works fine but in this case, I had an error.
fetchData(Store store) {
return this._memorizer.runOnce(() async {
return await Future.wait([
fCustomer(store),
fList(store),
fCompanies(store)
]);
});
}
#override
Widget build(BuildContext context) {
Store store = StoreProvider.of<AppState>(context);
return FutureBuilder<List<bool>>(
future: this._fetchData(store),
builder: (
context,
AsyncSnapshot<List<bool>> snapshot,
) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
if (snapshot.data.every((result) => result == true)) {
return screen();
}
return Text("Sıqıntı");
},
);
}}
error:
The following assertion was thrown building HomeScreen(dirty, dependencies: [StoreProvider<AppState>], state: _HomeScreenState#79c31(tickers: tracking 1 ticker)):
type 'Future<dynamic>' is not a subtype of type 'Future<List<bool>>'
I found a solution about it.
AsyncMemoizer _memorizer = AsyncMemoizer<List<bool>>();
Generic AsyncMemorizer works.
I have a collection of following;
I want to return every company in ascending order by companyName and this is how I'm trying;
QuerySnapshot usersComp = await _firestore
.collection('companies')
.where('belongsTo', isEqualTo: curruser.uid)
.orderBy({
'properties': {'companyName'}
}, descending: false).getDocuments();
Code doesn't give any errors but it also doesn't return any value as well. The statement without orderBy works fine.
How can I write a this orderBy in a working way?
edit
This is the whole getCompanies function in FirebaseCrud:
Future<List<Company>> getCompanies() async {
FirebaseUser curruser = await _authService.getCurrentUser();
DocumentSnapshot userSnapshot = await Firestore.instance
.collection('users')
.document(curruser.uid)
.get();
List partners = userSnapshot.data['partners'];
print('partners');
print(partners[0]);
QuerySnapshot usersComp = await _firestore
.collection('companies')
.where('belongsTo', isEqualTo: curruser.uid)
//.orderBy('properties.companyName', descending: false) // code works fine without this line but not as expected
.getDocuments();
List<Company> companies = new List<Company>();
usersComp.documents.forEach((f) {
int indexOfthis = usersComp.documents.indexOf(f);
companies.add(new Company(
uid: partners[indexOfthis],
companyName: f.data['properties']['companyName'],
address: f.data['properties']['address'],
paymentBalance: f.data['currentPaymentBalance'],
revenueBalance: f.data['currentRevenueBalance'],
personOne: new Person(
phoneNumber: f.data['properties']['personOne']['phoneNumber'],
nameAndSurname: f.data['properties']['personOne']
['nameAndSurname']),
personTwo: new Person(
phoneNumber: f.data['properties']['personTwo']['phoneNumber'],
nameAndSurname: f.data['properties']['personTwo']
['nameAndSurname']),
));
});
return companies;
}
Use dot notation to reference properties of objects to use for sorting.
_firestore
.collection('companies')
.where('belongsTo', isEqualTo: curruser.uid)
.orderBy('properties.companyName'),
descending: false)
I created a collection with a few documents, each have a top-level field and a nested field. If I then run a query over it like this:
Firestore.instance.collection("59739861")
.where("location", isEqualTo: "Bay Area")
.orderBy("properties.companyName", descending: false)
.getDocuments().then((querySnapshot) {
print("Got ${querySnapshot.documents.length} documents");
querySnapshot.documents.forEach((doc) {
print("${doc.documentID}: ${doc.data['properties']}");
});
});
I have added these three documents in my database:
location: "Bay Area", properties.companyName: "Google"
location: "Bay Area", properties.companyName: "Facebook"
location: "Seattle", properties.companyName: "Microsoft"
With the above query, I get the following output printed:
flutter: KJDLLam4xvCJEyc7Gmnh: {companyName: Facebook}
flutter: TMmrOiKTYQWFBmJpughg: {companyName: Google}
I have no idea why you're getting different output.
Just in case it matters, I run the app in an iOS simulator and use this version of the Firestore plugin:
cloud_firestore: ^0.13.0+1