Flutter : retreive documents from Firestore in stream - android

I want to retreive documents from my message collection; but i don't get the result and i have no error from flutter. Here ise my code
body: new Center(
child: new StreamBuilder(
stream: Firestore.instance.collection("messages").snapshots(),
builder: (context, snapshot){
if(!snapshot.hasData) return const Text("Chargement ...");
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index)=> new Text("papa"),
);
}
),
)
and here is my firebase database

Use new Text(document['papa'])
Check docs: https://pub.dartlang.org/packages/cloud_firestore

Related

I can't get a return from flutterfire realtime database emulator?

I have already done everything for the setup I'm sure. I connected my project in the firebase console, and I was able to get my app to run after an await firebase initialize (options : options...etc.) once I finished with the flutterfire CLI config.
But now I can't get the actual value from my json file in the realtime database emulator. All I can get is null. Maybe I am not referring to the json right, but my json right now is just:
{ "hello" : "hi" }
so I don't think that's the problem. This is how I'm calling the database.
final _database = FirebaseDatabase.instance.ref();
and I'm using a future builder.
child:FutureBuilder(
future: _database.child('http://{$host_number}/?ns=nimble-autumn-{$project_id_number}/hello').get(),
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return ListView.builder(
//shrinkWrap: true,
scrollDirection: Axis.vertical,
physics: AlwaysScrollableScrollPhysics(),
itemCount: gocrazy.length,
itemBuilder: (BuildContext context, int index) {
return PostCard(
status: public[0], comments: [snapshot.toString()]);
//rags[index]);
},
);
}
else {
return Column(
children: <Widget>[
SizedBox(
width: 60,
height: 60,
child: CircularProgressIndicator(),
),
Padding(
padding: EdgeInsets.only(top: 16),
child: Text('Awaiting result...'),
),
]
);
};
And the UI will complete with the if statement because I am using .toString() and this what I get (if I use .value it will cause null error).
It says invalid Firebase Database data path. So what is the valid way to put it? I am using:
'http://{$host_number}/?ns=nimble-autumn-{$projectid}/hello'
but using 'nimble-autumn-projectid/hello' or 'hello' will just have the futurebuilder hang indefinitely.

Accessing data from a sub collection in Firebase

I have a collection named 'room', inside which I've a document named 'users', inside the doc I've another collection named 'users' inside which I've filed named 'userName'. I want to access the 'userName'
Image 1, Image 2, Image 3
Heres what I've tried
StreamBuilder(
stream: FirebaseFirestore.instance.collection(widget.roomId).doc("users").collection("users").snapshots(),
builder: (context, newSnapshot){
final documents = newSnapshot.data?.docs;
if (newSnapshot.connectionState == ConnectionState.waiting){
return Text("WAITING");
}
return ListView.builder(
itemCount: documents?.length,
itemBuilder: (context, index) => Container(
height: 25,
child: Text(documents![index]["usersName"] ?? "nothing found"),
));
},
),
Seems like you have misspelled the userName key in your text widget
child: Text(documents![index['usersName']??'Nothing found');
should be
child: Text(documents![index]['userName']??'Nothing found');

How can I display last StreamBuilder data when snapshot.data is null?

I'm making a to-do list with Flutter and Firebase Firestore, but I have a slight problem. Whenever I add a new task, snapshot.data becomes null. If I do not add a check for snapshot.connectionState and render a different widget according to that, I get the following error: NoSuchMethodError (NoSuchMethodError: The getter 'docs' was called on null.
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('tasks')
.doc(widget.uid)
.collection('mytasks')
.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: SizedBox(
height: 100, width: 100, child: CircularProgressIndicator()),
);
} else {
> final docs = snapshot.data.docs;
return ListView.builder(
itemCount: docs.length,
itemBuilder: (ctx, index) {
final currTask = docs[index];
return Dismissible(
direction: DismissDirection.startToEnd,
key: UniqueKey(),
onDismissed: (_) async {
FirebaseFirestore.instance
.collection('tasks')
.doc(widget.uid)
.collection('mytasks')
.doc(currTask['id'])
.delete();
.
.
.
I don't want to have to display a CircularProgressIndicator or an empty screen. I want the tasks to remain visible and seamlessly add new tasks. How can I achieve that? I know what I asked for in the question title might be a little silly, what should I do instead?

Flutter, cloud fire store query method, where not working properly

I am trying to make a search feature in an app where I search for a store (from the Cloud Firestore database) using their query method where but I keep getting the same result, which is the first store on "list". No matter what I search.
StreamBuilder(
builder: (context , snapshot) {
if(snapshot.hasError) {
return Center(
child: Text(snapshot.error.toString()),
);
}//end if
if (snapshot.hasData) {
QuerySnapshot querysnapshot = snapshot.data;
List<QueryDocumentSnapshot> documents = querysnapshot.docs;
processData(documents);
print("here : " + stores[0].name.toString());
print("search: " + searchQuery);
print("array length: " + stores.length.toString());
return Container(
child: ListView.builder(
itemBuilder: (context , index) {
return Center(
child: Text(stores[index].name.toString()),
);
},
itemCount: stores.length,
),
height: height,
);
} else {
return Container(
child: Center(
child: Text("Snapshot has no data"),
),
);
}//end if-else
},
stream: FirebaseFirestore.instance.collection('Stores').where('name' , isEqualTo: name).snapshots(),
)
sorry I made an idiotic mistake. I forgot to use to search variable instead of the name variable in the where function!

order data by timestamp in descending order from firestore

im failing to order my data by timestamp in descending order, error keeps saying have positioned it wrong
StreamBuilder(
stream: Firestore.instance.collection("payments").orderBy("timestamp", "desc").where('participants', arrayContains: userActive).snapshots(),
builder: (context, snapshot){
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.documents[index].data();
You should use the following:
orderBy("timestamp", descending : true)
https://github.com/FirebaseExtended/flutterfire/blob/f5a408f0aed529da5602d4562964d60ff50d2a7e/packages/cloud_firestore/cloud_firestore/lib/src/query.dart#L224

Categories

Resources