hi im trying to retrive current user info from firebase but its showing me errors this error
this is my code
final auth = FirebaseAuth.instance;
final db = FirebaseFirestore.instance;
User? user = FirebaseAuth.instance.currentUser;
Padding(
padding: EdgeInsets.only(left: 20, right: 20),
child: StreamBuilder(
stream: db
.collection("Users")
.doc("list_students")
.collection("Students")
.doc(user!.uid)
.snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center();
}
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return Stack;
this is a screenshots of my firebase
First of all, try to print 'snapshot' and 'snapshot.data' for you've got proper data from firebase.
You need to cast snapshot.data as a List type before you can call the length method on snapshot.data. I cannot tell from your included code what is the underlying type for snapshot.data.
Another way is to specify AsyncSnapshot<List<String>> snapshot in the builder header, assuming the underlying data type is a List<String>.
Related
I'm currently using stream builder and future builder to call two collections at the same time. I'm having hard time because the stream builder refreshes every time the database changes. Here's my source code:
body: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('thread')
.orderBy('published-time', descending: true)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
} else {
return snapshot.data!.docs.length > 0
? MediaQuery.removePadding(
removeTop: true,
context: context,
child: ListView(
shrinkWrap: true,
children: snapshot.data!.docs.map((DocumentSnapshot postInfo) {
return FutureBuilder<DocumentSnapshot>(
future: userCollection
.doc(postInfo.get('publisher-Id'))
.get(),
My variables are here:
final CollectionReference userCollection =
FirebaseFirestore.instance.collection('users');
final FirebaseAuth _auth = FirebaseAuth.instance;
Also tried calling two streambuilders:
body: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('thread')
.orderBy('published-time', descending: true)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
} else {
return snapshot.data!.docs.length > 0
? MediaQuery.removePadding(
removeTop: true,
context: context,
child: ListView(
shrinkWrap: true,
children: snapshot.data!.docs
.map((DocumentSnapshot postInfo) {
return StreamBuilder<DocumentSnapshot>(
stream: userCollection
.doc(postInfo.get('publisher-Id'))
.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState ==
ConnectionState.done) {
Map<String, dynamic> userInfo =
snapshot.data!.data()
as Map<String, dynamic>;
It doesn't look like there is a better way of calling two collections, but you can achieve less rebuilds by considering some optiomization steps mentioned in this article:
Only wrap the widget that should rebuild during a stream change inside a StreamBuilder
Use the Stream.map to map your stream object into an object that your widget needs to show in UI.
Use the Stream.distinct to create a _DistinctStream in case your widget shouldn’t rebuild when the stream provides the same value in a
row.
Create a separate _DistinctStream for StreamBuilders on initState so that they can save streamed values first if your
streamController streams a new value before the screen's first
build.
I am querying a firestore collection in Flutter using where and arrayContains, for some reason it is not working as expected for me.
StreamBuilder(
stream: (_searchTerm.length >= 3)
? FirebaseFirestore.instance.collection("users").snapshots()
: FirebaseFirestore.instance
.collection('users')
.where('email', arrayContains: _searchTerm)
.snapshots(),
builder: (ctx, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
final results = snapshot.data.docs;
print(results.length);
return ListView.builder(
shrinkWrap: true,
itemCount: results.length,
itemBuilder: (ctx, index) => Text(
results[index].data()['display-name'],
),
);
})
The _searchTerm variable is populated as I type in some values into the textfield and when it hits a length of three characters that's when the above query fires.
For example when I type in test the query should only return the values that contain test in it, but I am getting the whole collection with and without the value test.
Please advice!
EDIT - Posting a screenshot of my firestore data structure
When you do the following:
FirebaseFirestore.instance
.collection('users')
.where('email', arrayContains: _searchTerm)
.snapshots(),
You are looking for documents inside the users collection that have _searchTerm as an item of the email array, property of a user document.
There are two problems:
I don't think the email property of your users is an array.
Firebase does not perform substring searches
I think you will need to use a third-party application for searches on Firestore. A popular one is Algolia that comes with a quite powerful FREE plan.
I am trying to display a realtime chat-screen in flutter with with firebase-firestore (equal to the homescreen of whatsapp).
Working: Creating a list of all the contacts "peers". Have a Look at my Listview:
Container(
child: StreamBuilder(
stream:
//FirebaseFirestore.instance.collection('users').snapshots(),
FirebaseFirestore.instance
.collection('users')
.doc(currentUserId)
.collection('peers')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(themeColor),
),
);
} else {
return ListView.builder(
padding: EdgeInsets.all(10.0),
itemBuilder: (context, index) =>
buildItem(context, snapshot.data.documents[index]),
itemCount: snapshot.data.documents.length,
);
}
},
),
),
not working: Loading specific data for each tile like last message or name. I cant query this at the time of creating my first list (first query returns peer-ids, second returns userdata of a peer-id). My buildItem method consists of another streambuilder, however, as soon as the first streambuilder makes changes, the app freezes.
Widget buildItem(BuildContext context, DocumentSnapshot document) {
return StreamBuilder<DocumentSnapshot>(
stream: FirebaseFirestore.instance
.collection('users')
.doc(document.data()['peerId'])
.snapshots(),
builder: ...
Is this the proper way to nest streams? Simple Listviews are documented quite well, but i couldn't find a good example on this on google. Any help is appreciated.
Try creating your stream just once in initState and pass it onto this method:
//in initState
peersStream = FirebaseFirestore.instance
.collection('users')
.doc(currentUserId)
.collection('peers')
.snapshots(),
Then use stream: peersStream in the StreamBuilder.
Also, it is recommended to use widget-classes over methods for widgets: https://stackoverflow.com/a/53234826/5066615
i have some code:
getFavSalons(AsyncSnapshot<QuerySnapshot> snapshot) {
return snapshot.data.documents
.map((doc) => SalonBlock(
salonName: doc["salonName"],
location: doc["location"],
workTime: doc["workTime"],
rating: doc["rating"],
))
.toList();
}
and part of code where I building list:
StreamBuilder(
stream: Firestore.instance
.collection("customers")
.document("HAQaVqCPRfM7h6yf2liZlLlzuLu2")
.collection("favSalons")
.snapshots(),
builder:
(context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
return Container(
margin:
EdgeInsets.only(bottom: screenHeight * 0.33),
child: new ListView(
children: getFavSalons(snapshot),
),
);
}
return LoadingSalon();
}),
and here I use uid:
.document("HAQaVqCPRfM7h6yf2liZlLlzuLu2")
here I have to use currentUser instead of filling myself. How to do this?
The current user in you application can change at any moment. For example:
When the user starts the application, Firebase automatically restores their previous authentication state. But this requires it to call out to the server, so the user is briefly not signed in (currentUser is null) before it is signed in.
While the user is signed in, Firebase refreshes their authentication state every hour to ensure their sign-in is still valid (and for example their account hasn't been disabled). This means that their sign-in state can change even when you don't explicitly call the API.
For these reasons you can't simply call currentUser and expect it to remain valid. Instead you should attach an auth state change listener, which gives you a stream of authentication states.
In your code that builds the UI, you can use this stream of user data inside another stream builder. So you'll have two nested stream builders:
For the user authentication state.
For the database, based on the current user.
So something like (untested for now):
StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, AsyncSnapshot<User> snapshot) {
if (snapshot.hasData) {
return StreamBuilder(
stream: Firestore.instance
.collection("customers")
.document(snapshot.data.uid)
.collection("favSalons")
.snapshots(),
builder:
(context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
return Container(
margin:
EdgeInsets.only(bottom: screenHeight * 0.33),
child: new ListView(
children: getFavSalons(snapshot),
),
);
}
return LoadingSalon();
}),
}
return Text("Loading user...");
}),
FirebaseUser is currently deprecated, you can get the CurrentUser like shown below;
FirebaseAuth.instance.currentUser;
If you want to know more about what arguments you can use with it check out their documentation;
https://firebase.flutter.dev/docs/auth/usage
Make sure you have firebase_auth imported to your class
Create instances of FirebaseAuth and User like so:
final auth = FirebaseAuth.instance;
User currentUser;
/// Function to get the currently logged in user
void getCurrentUser() {
currentUser = auth.currentUser;
if(currentUser) {
// User is signed in
} else {
// User is not signed in
}
}
You can call the getCurrentUser function in the initState of a Stateful Class to get the current as the Widget is loaded like so:
#override
void initState() {
getCurrentUser();
super.initState();
}
You can now change your previous code to this:
StreamBuilder(
stream: Firestore.instance
.collection("customers")
.document(currentUser.uid)
.collection("favSalons")
.snapshots(),
builder:
(context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData && snapshot.connectionState == ConnectionState.active) {
return Container(
margin:
EdgeInsets.only(bottom: screenHeight * 0.33),
child: new ListView(
children: getFavSalons(snapshot),
),
);
}
return LoadingSalon();
}),
This should work for you now :)
I am fetching data from two different firestore collections and this is my code
StreamBuilder(
stream: Firestore.instance.collection('items').snapshots(),
builder: (BuildContext context, snapshot){
if(snapshot.connectionState == ConnectionState.waiting){
return CupertinoActivityIndicator();
}
if(snapshot.data != null){
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context,index){
return Column(
children: <Widget>[
Text(snapshot.data.documents[index]['name']),
Text(snapshot.data.documents[index]['color']),
Text(snapshot.data.documents[index]['lifetime']),
Container(
child: StreamBuilder(
stream: Firestore.instance.collection('users')
.document(userid).collection('Quantity')
.document(snapshot.data.documents[index]['id']).snapshots(),
builder: (BuildContext context, snap){
if(snapshot.connectionState == ConnectionState.waiting){
return CupertinoActivityIndicator();
}
if(snap.data != null){
return Container(
child: Text(snap.data.documents.length)
);
}
},
),
)
],
);
});
}
},
)
It is giving me error but when I use futurebuilder inside streambuilder everything works fine and I also used stream broadcast but it is also giving me same error.
Here is the code which I used for broadcast stream
StreamController _controller = StreamController.broadcast();
Stream getItems() async*{
Firestore.instance.collection('items').snapshots().listen((data){
_controller.add(data);
})
yield* _controller.stream;
}
You shouldn't create a new Stream inside the StreamBuilder. When you do:
StreamBuilder(
stream: Firestore.instance.collection('items').snapshots(),
And
StreamBuilder(
stream: Firestore.instance.collection('users')
.document(userid).collection('Quantity')
.document(snapshot.data.documents[index]['id']).snapshots(),
Each time your build() function is called a new StreamBuilder is created, so Firestore.instance.collection()...snapshots() is called, returning a new Stream each time.
You should convert your widget to a StatefulWidget and initialize your Stream on initState(), passing it as a class variable to your StreamBuilder. The nested StreamBuilder can also be transformed into a StatefulWidget and created in place, but initialized on the same manner. Just pay attention that you might need a Key for showing it correctly on a ListView.
Also if you want to convert a Single Subscription Stream to a Broadcast Stream you just have to call asBroadcastStream to convert it.