How to call another table attribute with uid? - firebase flutter - firebase

My problem similar to this How to compare UID and another child key in Firebase?
I'm trying to create a similar code from that thread but it didn't work
This is my firebase https://imgur.com/ZpU8ODO
StreamBuilder(
stream: FirebaseDatabase.instance
.reference()
.child("questions")
.onValue,
builder: (BuildContext context, AsyncSnapshot<Event> snapshot) {
if (snapshot.hasData) {
Map<dynamic, dynamic> map = snapshot.data.snapshot.value;
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 1,
childAspectRatio: MediaQuery.of(context).size.width / (MediaQuery.of(context).size.height / 4),
mainAxisSpacing: 16.0,
),
itemCount: map.values.toList().length,
padding: EdgeInsets.only(left: 16, right: 16, top: 16),
itemBuilder: (BuildContext context, int index) {
return Container(
color: bgSecondaryColor,
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Flexible(
child: Text(
parse(parse(map.values.toList()[index]["question"]).body.text).documentElement.text,
),
),
Container(
child: Column(
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage('https://mdn.mozillademos.org/files/7693/catfront.png'),
backgroundColor: Colors.lightGreen,
radius: 24.0,
),
Text(
//I want to call the "name" attribute in users here,
),
],
),
),
],
),
],
),
);
},
Sorry im a total newbie in both flutter and firebase. Kind regards from me. Thank you

Related

How do I Group and List data according to date using Flutter, Firebase - Firestore Database?

I need to have a list of hotels grouped by the dates available (group by - the date they have been added). Please let me know what can be done. The following is my code. Thanks in advance.
StreamBuilder(
stream: FirebaseFirestore.instance
.collection('hotels')
.snapshots(),
builder:
(context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
return ListView.builder(
itemCount: snapshot.data?.docs.length,
itemBuilder: (context, index) {
return Stack(
children: [
I want to have the date specified above each grouped list
//the date captured from the group by condition
Text("${example date}", style: TextStyle(
color: Colors.white
),),
Container(
child: Column(
children: [
Column(
crossAxisAlignment:
CrossAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.only(
right: 10.0),
child: Text(
"${snapshot.data!.docs[index]['name']
.toString()}",
style: TextStyle(
fontSize: 14,
color: Colors.white,
),
),
),
],
),
], ), ), ],);}); }, ),
This has already been answered here: Flutter/Dart how to groupBy list of maps
The package collection implements the groupBy function.

How to Retrieve data from firebase realtime database according to App Language on Flutter?

Pic of my database structure I'm trying to get data from the firebase real-time database to a GridView builder using Stream builder according to the app language. But I don't know how to check the App language before choosing the child I'm getting the data from.
Container(
margin: EdgeInsets.only(top: 90.0),
child: Scaffold(
key: _scaffoldKey,
body: Column(
children: [
Expanded(
child: StreamBuilder(
stream: FirebaseDatabase.instance
.reference()
.child('CleaningList')
.onValue,
builder: (BuildContext context,
AsyncSnapshot<Event> snapshot) {
if (snapshot.hasData) {
var map = snapshot.data.snapshot.value
as Map<dynamic, dynamic>;
clothesModels.clear();
map.forEach((key, value) {
var clothesModel = new ClothesModel.fromJson(
json.decode(json.encode(value)));
clothesModel.key = key;
clothesModels.add(clothesModel);
});
return GridView.builder(
padding: EdgeInsets.only(
top: 20.0, right: 26.0, left: 26.0),
itemCount: clothesModels.length,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemBuilder: (context, index) => Container(
alignment: Alignment.center,
child: Column(
crossAxisAlignment:
CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
child: Center(
child: Image.network(
clothesModels[index].image,
width: 40.0,
height: 50.0,
)),
),
Check app language.
Locale myLocale = Localizations.localeOf(context);
provides languageCode.
Visit localeDocs for more information.

How to get data from other collection in streambuilder

I am facing a problem and I cannot solve it, I have a collection "Posts" that contain users' posts, each post contains a uid of the owner of the post, and I have another collection named "users", and each user has his name and photo, I want to get the user's name and image to display on his post.
Posts Collection
Users Collection
I have seen this article but I did not benefit perhaps because I am a beginner.
My Code:
StreamBuilder(
stream: Firestore.instance
.collection('Posts')
.orderBy('date', descending: true)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
const Text('Loading...');
} else {
return ListView.builder(
physics:
NeverScrollableScrollPhysics(),
shrinkWrap: true,
scrollDirection: Axis.vertical,
itemCount: snapshot
.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot mypost =
snapshot
.data.documents[index];
return Stack(
children: <Widget>[
Container(
decoration:
BoxDecoration(
borderRadius:
BorderRadius
.circular(
15.0),
),
child: Padding(
padding:
EdgeInsets
.all(8.0),
child: Column(
children: <
Widget>[
InkWell(
child: Row(
children: <
Widget>[
Container(
width:
32.0,
height:
32.0,
decoration: BoxDecoration(shape: BoxShape.circle, image: DecorationImage(fit: BoxFit.fill, image: NetworkImage(
// user image url
'Owner of post img')))),
SizedBox(
width:
10.0,
),
Text(
'Owner of post Name',
style: TextStyle(
color: Colors.white,
fontSize: 12.0,
fontWeight: FontWeight.bold,
fontFamily: 'BalooDa2'),
),
],
),
),
Padding(
padding:
EdgeInsets.all(
5.0),
child: Text(
'${mypost['text']}',
style: TextStyle(
color: Colors
.white,
fontSize:
16.0,
fontFamily:
'Tajawal',
height:
1.3),
textAlign:
TextAlign
.justify,
textDirection:
TextDirection.rtl),
),
],
),
),
),
],
);
});
}
return Container(
height: 0.0,
width: 0.0,
);
},
),
You can user nested StreamBuilders to fetch user detail from the uid you are getting from posts collection.I have added a query which will match uid from posts data and look for the documents in users collection where uid is equal to uid from posts collection.
StreamBuilder(
stream: Firestore.instance
.collection('Posts')
.orderBy('date', descending: true)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
const Text('Loading...');
} else {
return ListView.builder(
physics:
NeverScrollableScrollPhysics(),
shrinkWrap: true,
scrollDirection: Axis.vertical,
itemCount: snapshot
.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot mypost =
snapshot
.data.documents[index];
return Stack(
children: <Widget>[
Container(
decoration:
BoxDecoration(
borderRadius:
BorderRadius
.circular(
15.0),
),
child: Padding(
padding:
EdgeInsets
.all(8.0),
child: Column(
children: <
Widget>[
StreamBuilder(
stream: Firestore.instance
.collection('users')
.where('uid', isEqualTo: mypost['uid'])
.snapshots(),
builder: (context, snapshot){
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return SizedBox();
case ConnectionState.active:
default:
break;
}
if (snapshot.hasError) print(snapshot.error);
DocumentSnapshot user = snapshot.data.documents[0];
return InkWell(
child: Row(
children: <
Widget>[
Container(
width:
32.0,
height:
32.0,
decoration: BoxDecoration(shape: BoxShape.circle, image: DecorationImage(fit: BoxFit.fill, image: NetworkImage(
// user image url
'${user['uimg']}')))),
SizedBox(
width:
10.0,
),
Text(
'${user['name']}',
style: TextStyle(
color: Colors.white,
fontSize: 12.0,
fontWeight: FontWeight.bold,
fontFamily: 'BalooDa2'),
),
],
),
);
},
),
Padding(
padding:
EdgeInsets.all(
5.0),
child: Text(
'${mypost['text']}',
style: TextStyle(
color: Colors
.white,
fontSize:
16.0,
fontFamily:
'Tajawal',
height:
1.3),
textAlign:
TextAlign
.justify,
textDirection:
TextDirection.rtl),
),
],
),
),
),
],
);
});
}
return Container(
height: 0.0,
width: 0.0,
);
},
),

How to display a list of Firebase users excluding the logged-in user in flutter?

Currently, I have a SteamBuilder fetching data from a "user" collection
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot document = snapshot.data.documents[index];
// else
return user.uid == document['uid']
? null //null should not be returned but the user should be excluded in the below ListTile
// this is causing only the users up to the logged-in user to display and then terminating without rendering other widgets
: ListTile(
contentPadding: EdgeInsets.all(10),
title: Text(
document['name'],
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic),
),
);
});
},
),
What logic should I implement so I exclude the logged-in user from rendering but display all others, can I pass a where() to the snapshot?
I am facing the same problem but here is the solution in below sample code I hope this will work for you.
return ListView.separated(
itemBuilder: (context, index) {
return InkWell(
onTap: () {},
child: Container(
height: snapshot.data.documents[index].data['id'] != uid
? 70.0
: 0.0, // this line for hiding specific cell...
width: MediaQuery.of(context).size.width,
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(snapshot
.data.documents[index].data['nickname']))
],
)
],
),
),
);
},
separatorBuilder: (context, index) {
return snapshot.data.documents[index].data['id'] != uid
? Divider()
: Container(); // this line hide the devider for specific cell..
},
itemCount: snapshot.data.documents.length);

Firebase Streambuilder

I have a map in Firebase Database like this,
'abc#gmail.com' : { food order }
I want to create a stream of this data to update widgets when a new order is placed.
I tried using the below code but it is giving error.
DocumentSnapshot has no instance getter 'length'
StreamBuilder(
stream: Firestore.instance.collection('admin').document('current-orders').snapshots(),
builder: (context, snapshot) {
return snapshot.hasData?Column(
children: <Widget>[
Expanded(
child: Container(
child: Padding(
padding: EdgeInsets.all(10),
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, uid) {
return Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
snapshot.data.keys.toList()[uid],
style: TextStyle(
fontSize: 18, fontWeight: FontWeight.bold),
),
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30)),
color: Colors.blue[200],
child: Text(
'Order Ready',
style: TextStyle(color: Colors.black54),
),
onPressed: () {},
),
],
),
ListView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
itemCount: snapshot.data.values.keys.toList().length,
itemBuilder: (context, orderID) {
return Text(
'${snapshot.data.values.keys[orderID].toString()} : ${snapshot.data.values.values[orderID].toString()}',
//'${_currentOrders[uid].keys.toList()[orderID]} : ${_currentOrders[uid].values.toList()[orderID]}',
style: TextStyle(fontSize: 16),
);
},
),
Padding(
padding: EdgeInsets.only(top: 10),
child: Container(
color: Colors.grey,
height: 1,
),
)
],
);
},
),
),
),
),
],
):Center(child: Text('No orders right now', style: TextStyle(fontSize: 30, color: Colors.black54),),);
}
);
Thank you.

Resources