I want to display all the users of my firestore database as a list.
I tried this but some errors appear.
StreamBuilder(
stream:chatservice.retrieveUsers(),
builder: (ctx, usersnapshot) {
if (usersnapshot.connectionState == ConnectionState.waiting) {
return Container(
child: Center(child: CircularProgressIndicator()));
} else {
var document = usersnapshot.data;
return ListView.builder(
itemCount: document.length,
shrinkWrap: true,
padding: EdgeInsets.only(top: 16),
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return ConversationList(
name: document[index]['name'],
);
},
);
}
},
)
chatservice.retrieveUsers():
Stream<QuerySnapshot> retrieveUsers() {
Stream<QuerySnapshot> queryUsers = _usercollection.snapshots();
return queryUsers;
}
i got this solution ,
this is work great ^^
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('Users').snapshots(),
builder: (ctx, AsyncSnapshot<QuerySnapshot> usersnapshot) {
if (usersnapshot.connectionState == ConnectionState.waiting) {
return Container(
child: Center(child: CircularProgressIndicator()));
} else {
return Expanded(
child: ListView.builder(
itemCount: usersnapshot.data.docs.length,
itemBuilder: (context, index) {
DocumentSnapshot document = usersnapshot.data.docs[index];
if (document.id == auth.currentUser.uid) {
return Container(height: 0);
}
return ConversationList(
name: document.data()["name"] +
" " +
document.data()["lastname"],
messageText: document.data()["lastname"],
imageUrl:
"https://cdn3.vectorstock.com/i/1000x1000/30/97/flat-business-man-user-profile-avatar-icon-vector-4333097.jpg",
isMessageRead: false,
);
},
),
);
}
},
)
Related
I'm building a flutter chat app for my personal learning project where the data will be retrieved from Firebase Realtime database.
I got this code from a tutorial but it is showing errors. How to solve this?
StreamBuilder(
stream: dbRef.onValue,
builder: (context, snapshot) {
if (snapshot.hasData) {
print("Error on the way");
messages.clear();
DataSnapshot dataValues = snapshot.data.snapshot; //Error: The getter snapshot is not defined for the type 'Object';
Map<dynamic, dynamic> values = dataValues.value;
values.forEach((key, values) {
messages.add(values);
});
return new ListView.builder(
shrinkWrap: true,
itemCount: messages.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Name: " + messages[index]["Text"]),
Text("Time: " + messages[index]["TextTime"]),
],
),
);
},
);
}
},
),
This solved the problem.
StreamBuilder(
stream: _dbRef.onValue,
builder: (context, snapshot) {
List<Message> messageList = [];
if (snapshot.hasData &&
snapshot.data != null &&
(snapshot.data! as DatabaseEvent).snapshot.value !=
null) {
final myMessages = Map<dynamic, dynamic>.from(
(snapshot.data! as DatabaseEvent).snapshot.value
as Map<dynamic, dynamic>); //typecasting
myMessages.forEach((key, value) {
final currentMessage = Map<String, dynamic>.from(value);
messageList.add(Message(
author: currentMessage['Author'],
authorId: currentMessage['Author_ID'],
text: currentMessage['Text'],
time: currentMessage['Time'],));
}); //created a class called message and added all messages in a List of class message
return ListView.builder(
reverse: true,
itemCount: messageList.length,
itemBuilder: (context, index) {
return ChattingDesign(
message: messageList[index],
dbpathToMsgChnl:
'TextChannels/${widget.channels['ChannelName']}/Messages',
showName: shouldShowName(
index,
messageList.length - 1,
messageList,
),
);
},
);
} else {
return Center(
child: Text(
'Say Hi...',
style: TextStyle(
color: Colors.white,
fontSize: 21,
fontWeight: FontWeight.w400),
),
);
}
},
),
According to the DataSnapshot Class Documentation there is no field called snapshot
I think there is a typo in your code.
Try this
StreamBuilder(
stream: dbRef.onValue,
builder: (context, snapshot) {
if (snapshot.hasData) {
print("Error on the way");
messages.clear();
DataSnapshot dataValues = snapshot.data! as DataSnapshot ; //here's the typo;
Map<dynamic, dynamic> values = dataValues.value;
values.forEach((key, values) {
messages.add(values);
});
return new ListView.builder(
shrinkWrap: true,
itemCount: messages.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Name: " + messages[index]["Text"]),
Text("Time: " + messages[index]["TextTime"]),
],
),
);
},
);
}
},
),
The documents on the tax page do not appear on the screen. I am getting the following _CastError (Null check operator used on a null value). Is there anyone who can help?
firestore_db_services.dart
#override
Stream<List<Vergi>> getHizmetler(String currentUserID) {
var snapShot = _firebaseFirestoreDB
.collection("hizmetler")
.doc(currentUserID)
.collection("vergi")
.orderBy("aciklamaDate")
.snapshots();
return snapShot.map(
(vergiListesi) => vergiListesi.docs
.map(
(vergi) => Vergi.fromMap(vergi.data()),
)
.toList(),
);
}
vergi.dart
Expanded(
child: StreamBuilder<List<Vergi>?>(
stream: _userModel.getHizmetler(_currentUser.userID),
builder: (context, snapShot) {
if (snapShot.hasError) {
return Center(
child: MyIndicator(),
);
}
if (snapShot.connectionState == ConnectionState.waiting) {
return Text("Yükleniyor...");
}
List<Vergi>? tumVergiListesi = snapShot.data;
return ListView.builder(
itemCount: tumVergiListesi!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
tumVergiListesi[index].aciklama.toString(),
),
subtitle: Text(
tumVergiListesi[index].fiyat.toString(),
),
);
},
);
},
),
),
Try returning snapshots from getHizmetler function and not the list you are currently returning:
Stream<QuerySnapshot>getHizmetler(String currentUserID) {
return _firebaseFirestoreDB
.collection("hizmetler")
.doc(currentUserID)
.collection("vergi")
.orderBy("aciklamaDate")
.snapshots();
}
Adjust your StreamBuilder like:
StreamBuilder<QuerySnapshot>(
stream: _userModel.getHizmetler(_currentUser.userID),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
// error handling
return ...;
}
if (snapshot.connectionState == ConnectionState.waiting) {
// progress indicator
return ...;
}
if (snapshot.hasData) {
// here you can do the conversion you like, result will be in:
// snapshot.data!.docs
}
}
)
I want to access data from firestore but there are errors, how can i do that?
I cant use .docs in snapshot.
StreamBuilder(
stream: messageStream,
builder: (context, snapshot) {
return snapshot.hasData
? ListView.builder(
padding: EdgeInsets.only(bottom: 70, top: 16),
reverse: true,
itemCount: snapshot.data.docs.length, // error
itemBuilder: (BuildContext context, int index) {
DocumentSnapshot ds =
snapshot.data!.docs[index]; // error
return _buildMessage(
ds["message"], myUserName == ds["sendBy"]);
},
)
: Center(
child: CircularProgressIndicator(),
);
},
),
Stream:
getChatRoomMessages(chatRoomId) async {
return FirebaseFirestore.instance.collection("chatRooms").doc(chatRoomId).collection("chats").orderBy("ts", descending: true).snapshots();}
in the StreamBuilder you have to use AsyncSnapshot in with your snapshot property. That was what got it working for me
StreamBuilder<QuerySnapshot>(
stream: DatabaseMethods().getChatRoomMessages(chatRoomId),
builder: (context, AsyncSnapshot snapshot) { <<<< insert here
return snapshot.hasData
? ListView.builder(
padding: EdgeInsets.only(bottom: 70, top: 16),
reverse: true,
itemCount: snapshot.data!.docs.length, // error
itemBuilder: (BuildContext context, int index) {
DocumentSnapshot ds =
snapshot.data!.docs[index]; // error
return _buildMessage(
ds["message"], myUserName == ds["sendBy"]);
},
)
: Center(
child: CircularProgressIndicator(),
);
},
),
I found a solution:
StreamBuilder<QuerySnapshot>(
stream: DatabaseMethods().getChatRoomMessages(chatRoomId),
builder: (context, snapshot) {
return snapshot.hasData
? ListView.builder(
padding: EdgeInsets.only(bottom: 70, top: 16),
reverse: true,
itemCount: snapshot.data!.docs.length, // error
itemBuilder: (BuildContext context, int index) {
DocumentSnapshot ds =
snapshot.data!.docs[index]; // error
return _buildMessage(
ds["message"], myUserName == ds["sendBy"]);
},
)
: Center(
child: CircularProgressIndicator(),
);
},
),
my this code is showing me error that querysnapshot is not a subtype of a list. can you edit my code and tell me how to make this error free.
buildProfilePosts() {
if (_isLoading) {
return Center(
child: Text(
"Loading...",
style: TextStyle(fontFamily: "QuickSand"),
),
);
}
return StreamBuilder(
stream: postsRef.document(widget.profileId).collection('userPosts').orderBy('timestamp', descending: true).snapshots(),
builder: (context, snapshot) {
return Column(
children: snapshot.data,
);
}
);
}
children is a property inside the widget Column, it takes a list of widgets. You should do the following:
child: Column(children: <Widget>[
StreamBuilder(
stream: postsRef.document(widget.profileId).collection('userPosts').orderBy('timestamp', descending: true).snapshots(),,
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
contentPadding: EdgeInsets.all(8.0),
title:
Text(snapshot.data.documents[index].data["name"]),
);
});
} else if (snapshot.connectionState == ConnectionState.none) {
return Text("No data");
}
return CircularProgressIndicator();
},
),
]),
Assuming you have a name field in your document.
Try
Column(
children: <Widget>[
...List.generate(
snapshot.data.length,
(index) {
return Container(
child: Text(snapshot.data[index].yourobject),
);
},
),
],
),
buildComments() {
return StreamBuilder(
stream: commentRef
.document(postId)
.collection('comments')
.orderBy('timestamp', descending: false)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return circularProgress();
}
List<Comment> comments = [];
snapshot.data.documents.forEach((doc) {
print(comments);
comments.add(Comment.fromDocument(doc));
});
return ListView(
children: comments,
);
});
}
I was trying to convert it in list view.builder but it gives me error you can can't use list instead of Widget, Can anyone solve this problem.
You should do the following:
if (snapshot.connectionState == ConnectionState.done) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
contentPadding: EdgeInsets.all(8.0),
title: Text(snapshot.data.documents[index].data["name"]),
);
});
Assuming you have name in the document.