I have a stream connected to a Firebase document and I am constantly listening to any changes of the document.
I want to update some parts of my app when document is changed so I made the stream globally available and I use StreamBuilders on different screens so the latest data will be available ob the screen.
Will there be a problem with the global stream and multiple StreamBuilders? How does the app work when the StreamBuilders are created on multiple screens?
This is my global stream:
Stream userDocGlobalStream =
Firestore.instance.collection("user").document(CurrentUserDetails.id).snapshots();
This is the build method of one of my screens widget (I change the color of a button depending on the stream data):
#override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
return StreamBuilder(
stream: userDocGlobalStream,
builder: (context, snapShot) {
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
side: BorderSide(color: theme.primaryColor)),
elevation: 30,
child: Container(
margin: EdgeInsets.all(10),
child: Column(
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment
.stretch, //need to use it to strech the items horizontally
children: <Widget>[
Container(
//to think, it is used for the background color of the picture. can undo it later
decoration: BoxDecoration(
color: theme.primaryColor.withAlpha(10),
borderRadius: BorderRadius.circular(10),
),
padding: EdgeInsets.all(10),
child: GestureDetector(
onTap: () {}, //go to user profile when pressed.
child: CircleAvatar(
radius: 70,
backgroundImage: NetworkImage(userImageUrl),
),
),
),
],
),
Container(
margin: EdgeInsets.symmetric(vertical: 10),
child: FittedBox(
child: Text(
"Username : $username ",
),
),
),
Container(
margin: EdgeInsets.symmetric(vertical: 10),
child: FittedBox(
child: Text(
"interests : ${interests.toString().replaceAll("[", "").replaceAll("]", "")} ",
),
),
),
Container(
margin: EdgeInsets.symmetric(vertical: 10),
child: FittedBox(
child: Text("Distance from you : $distanceFromUser KM"),
),
), //to do address and km from you should go here
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
IconButton(
color: theme.primaryColor,
icon: Icon(Icons.chat),
onPressed: () {}, //send a message to the user
),
IconButton(
color: Colors.cyan,
icon: CurrentUserDetails.friendRequestsSent.contains(
userId) //to do=> THE ICON MUST CHANGE WITH EVERY CHANGE OF THE DATA
? Icon(
Icons.person,
color: Colors.black,
)
: CurrentUserDetails.friends.contains(userId)
? Icon(
Icons.person,
color: Colors.green,
)
: Icon(Icons.person_add),
onPressed: () {
try {
//to do
CurrentUserDetails.friendRequestsSent
.contains(userId)
? DoNothingAction()
//Cancel the sent request:
: CurrentUserDetails.friendRequestsReceived
.contains(userId)
? DoNothingAction()
//accept friend request:
: CurrentUserDetails.friends
.contains(userId)
? DoNothingAction()
//delete the friend:
: DatabaseManagement().sendFriendRequest(
CurrentUserDetails.id,
userId); //userId is the id of the user we are showing the widget for
} catch (e) {
showDialog(
context: context,
builder: (ctx) => DialogueWidget(
titleText: "Error occured",
contentText:
e.toString(), //to do+> change the er
),
);
}
} //send friend request when this button is pressed
),
IconButton(
color: Colors.red[300],
icon: Icon(Icons.location_on),
onPressed:
() {}, //show a map with a users location details on it.
)
],
)
],
),
),
);
},
);
}
}
StreamBuilder automatically starts and ends listening of provided stream:, so there will be no problem when using one broadcast stream in multiple places around the app. Even nested listening to one stream is not an issue.
Here are some helpful links if you want to dig deeper:
https://dart.dev/tutorials/language/streams
https://api.flutter.dev/flutter/widgets/StreamBuilder-class.html
Related
I'm building a system. Purpose product search. But I'm having a problem with this search. I want this search system like this: If what the person is looking for is in any value, it should be returned as a result. For example, if the person is looking for shoes as a product, when I type sho, I want it to come to the listView.
Or let me give you another example: Finding the glass when typing gla for glass. How can I make this search system?
Firestore:
I tried a code like this:
Container(
height: 200,
child: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance.collection("bolatAktar").where("urunAdi", isEqualTo: _arananUrun).snapshots(), // !!!!!!!!!!!!!!<<<<<<<<<<<<<<<<<<<<<
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
else {
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
return InkWell(
child: ListTile(
leading: Icon(Icons.label),
title: Text(snapshot.data!.docs[index].data()["urunAdi"], style: TextStyle(fontSize: 20),),
),
onTap: () {
showModalBottomSheet(
isScrollControlled:true,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
),
),
context: context,
builder: (context) {
return FractionallySizedBox(
heightFactor: 0.93,
child: Container(
padding: EdgeInsets.all(25),
height: MediaQuery.of(context).size.height * 0.5,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Product name:", style: TextStyle(fontSize: 20)),
SizedBox(height: 10),
TextFormField(
style: TextStyle(fontSize: 19),
decoration: InputDecoration(
border: OutlineInputBorder(),
),
initialValue: snapshot.data!.docs[index].data()["urunAdi"],
),
]
)
),
);
}
);
},
);
},
);
}
},
),
),
Result:
Thank you in advance for your help and valuable information.
Google Firestore: Query on substring of a property value (text search)
Is there a way to search sub string at Firestore?
Firestore Comparison Operators - contains, does not contain, starts with
I have reviewed the above topics, but they did not contribute because they are not up to date.
flutter application streambuilder in real time
this is group chat app
I need to get bool chat vale from firebase firestore if true or false in real time without exit page and re open to update the value Or any way to prevent the user from sending a message in the group when the value of Chat is equal to False
this is my code
StreamBuilder(builder: (context, snapshot) {
if(chat == false){
return Container(
child:
Padding(
padding: const EdgeInsets.symmetric(horizontal: 30,vertical: 5),
child: Row(
children: [
Image.network('https://upload.wikimedia.org/wikipedia/commons/thumb/f/f0/Error.svg/1200px-Error.svg.png',height: 25,width: 25,),
SizedBox(width: 20,),
Expanded(child: Text('Only admin can send message',style: TextStyle(fontSize: 10),maxLines: 1,overflow: TextOverflow.ellipsis,))
],
),
)
);
}else{
return Padding(
padding: const EdgeInsets.all(10.0),
child: Material(
borderRadius: BorderRadius.circular(50),
color: ColorConstants.appColor,
child: Padding(
padding: const EdgeInsets.only(bottom: 4.0,top: 4.0,left: 1.5,right: 1.5),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(50)
),
child:
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(child: TextField(
controller: messageedit,
onChanged: (value){
messageText = value;
},
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(
vertical: 10,
horizontal: 20
),
hintText: 'Write your message .... ',
border: InputBorder.none
),
)),
IconButton(onPressed: () {
messageedit.clear();
_firestore.collection("messages").add({
'text': messageText,
'sender' : email,
'time' : FieldValue.serverTimestamp(),
}).whenComplete(() => sendNotification('$messageText', '$email'));
}, icon: Icon(Icons.send_rounded,color: ColorConstants.appColor,))
],
)
),
),
),
);
}
},stream: _firestore.collection('admin').doc('admin').snapshots(),),
your code has the wrong implementation.
when providing the doc it should be the docId ({DOCID}) on firestore
e.g.: _firestore.collection('admin').doc({DOCID}).snapshots()
i don't get how do you create the chat variable
i don't see anywhere in the code where do you process snapshot data from firestore
check the flutter fire documentation for the correct implementation
this is my users collection in cloud fire store:
users collection
this is the function that gets users from users collection in firestore
Stream<QuerySnapshot> fetchUsersInSearch() {
return Firestore.instance.collection('users').snapshots();
}
i use this method
final emailResults = snapshot.data.documents
.where((u) => u['email'].contains(query));
in the following streamBuilder to fetch users by their email.
i have this streamBuilder to populate the data on screen
return StreamBuilder<QuerySnapshot>(
stream: DatabaseService().fetchUsersInSearch(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
final emailResults = snapshot.data.documents
.where((u) => u['email'].contains(query));
if (!snapshot.hasData) {
return Container(
color: Theme.of(context).primaryColor,
child: Center(
child: Text(
'',
style: TextStyle(
fontSize: 16, color: Theme.of(context).primaryColor),
),
),
);
}
if (emailResults.length > 0) {
return Container(
color: Theme.of(context).primaryColor,
child: ListView(
children: emailResults
.map<Widget>((u) => GestureDetector(
child: Padding(
padding: const EdgeInsets.all(0.1),
child: Container(
padding: EdgeInsets.symmetric(vertical: 5),
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
border: Border(
bottom: BorderSide(
width: 0.3, color: Colors.grey[50]))),
child: ListTile(
leading: CircleAvatar(
backgroundColor:
Theme.of(context).primaryColor,
backgroundImage:
NetworkImage(u['userAvatarUrl']),
radius: 20,
),
title: Container(
padding: EdgeInsets.only(left: 10),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(u['email'],
style: TextStyle(
fontSize: 16,
color: Theme.of(context)
.accentColor),
overflow: TextOverflow.ellipsis),
SizedBox(
height: 5,
),
],
),
),
),
),
),
onTap: () {
showUserProfile(u['id']);
},
))
.toList(),
),
);
} else {
return Container(
color: Theme.of(context).primaryColor,
child: Center(
child: Text(
'No results found',
style: TextStyle(
fontSize: 16,
color: Theme.of(context).accentColor,
),
),
),
);
}
});
this is working perfectly and fetching users inside a listView by their email...
p.s: the (query) is a string i type in a seach bar.
how can i make a query to fetch users by their otherUsernames...the second field in the screenshot of the users collection ?!
i tried this:
final otherUsernamesResults = snapshot.data.documents
.where((u) => u['otherUsernames'].contains(query));
but its returning this error:
The method 'contains' was called on null.
Receiver: null
Tried calling: contains("#username1")
what am i doing wrong here ?!!
any help would be much appreciated..
Try this:-
Stream<QuerySnapshot> getUsers() {
final usersCollection = FirebaseFirestore.instance.collection('users');
return usersCollection.where('otherUsernames', arrayContainsAny: ['username1', 'username2']);
}
For firestore version 0.16.0
The issue here is that when I fetch the data, I am suppose to fetch it for the current user but it is rather fetching data for all users within that collection.
I have done reading and watched a number of videos for a possible solution but I can't seem to find how to do this. Your help is needed please. Thanks.
A excerpt of the bode is below.
File image;
TextEditingController loginNameController = TextEditingController();
TextEditingController loginPhoneController = TextEditingController();
TextEditingController loginAddressController = TextEditingController();
clearForm() {
setState(() {
image = null;
loginNameController.clear();
loginPhoneController.clear();
loginAddressController.clear();
});
}
//=====> FOR INSTANCES OF FIREBASE <=====
final auth = FirebaseAuth.instance;
final db = FirebaseFirestore.instance;
User user = FirebaseAuth.instance.currentUser;
body: Padding(
padding: EdgeInsets.only(left: 20, right: 20),
child: StreamBuilder(
stream: db.collection("collection name").snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot){
if (!snapshot.hasData) {
return Center(
child: spinkit,
);
}
return ListView.builder (
itemCount: snapshot.data.docs.length,
itemBuilder: (BuildContext context, int index){
return Stack(
children: [
Column(
children: [
Stack(
children: [
// ===> RETRIEVING USER DETAILS AND SHOWING IT IN A ROW <===
Container(
padding : EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CircleAvatar(
backgroundColor: Palette.mainColor,
radius: 50,
child: ClipOval(
child: SizedBox(
height: 150,
width: 150,
child: image == null ? Center(
// child: Image.asset("asset/images/placeholder.png", fit: BoxFit.cover,),
child: Image.network(snapshot.data.documents[index].get("image")),
):
Image.file(image, fit: BoxFit.cover,),
),
),
),
SizedBox(width: 16,),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 0),
child: Text(snapshot.data.documents[index].get("Name"),
style: TextStyle(
letterSpacing: 2,
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.bold,
),),
),
SizedBox(height: 5,),
Text(snapshot.data.documents[index].get("Address"),
style: TextStyle(
letterSpacing: 2,
color: Colors.black54,
fontSize: 16,
),),
SizedBox(height: 5,),
Text(snapshot.data.documents[index].get("Number"),
style: TextStyle(
letterSpacing: 2,
color: Colors.black54,
fontSize: 16,
),),
],
),
),
Padding(
padding: EdgeInsets.only(left: 0, bottom: 15),
child: IconButton(
icon:Icon(Icons.edit, color: Palette.mainColor, ),
onPressed: () { },
),
),
],
),
),
],
),
],
),
],
);
},
);
},
),
)
The collection name is members
Try like this, stream of your widget should be like this, as said above.
db.collection("Users").document(user.uid).snapshots();
for length in Listview.builder, change it too
snapshot.data.length;
And last, All the data which you fetch data like this should change into
from:
snapshot.data.documents[index].get("image")
To:
snapshot.data["image"]
Note I didn't test it. So, it might or might not work.
First of All use a DocumentSnapshot Shown below:
StreamBuilder<DocumentSnapshot>
Make a collection to get current user Profile data.
db.collection("Users").doc(user.uid).snapshots();
Remove ListView.builder
To get an Email Address use the below Line
Text('${streamSnapshot.data['Email Address']}'),
Here is the complete Article https://medium.com/#kamranktk807/fetch-user-data-from-firestore-and-show-them-in-profile-screen-using-flutter-609d2533e703
By the way I sol this problem with the help of a Professional Flutter Developer SHAKIR ZAHID [shakirzahid191#gmail.com].
In my Flutter app, I am using ModalProgressHUD to show a spinner when I click on save buttons in my form screens and it stops spinner once data successfully writes to Firebase.
I have this screen that uses Listview.builder to display a list of all my expenses and I want to automatically show spinner as soon as the page displays, and to stop spinner once all the data from Firebase fully loads.
I need assistance in doing this. I've pasted excerpt of my code as shown below. Thanks in advance.
//class wide declaration
bool showSpinner = true;
Widget build(BuildContext context) {
ExpenseNotifier expenseNotifier = Provider.of<ExpenseNotifier>(context);
Future<void> _resfreshList() async {
expenseNotifier.getExpenses(expenseNotifier);
var expenseList = ExpenseNotifier.getExpenses(expenseNotifier);
if (expenseList != null) {
setState(() {
showSpinner = false;
});
}
return Scaffold(
body: ModalProgressHUD(
inAsyncCall: showSpinner,
child: RefreshIndicator(
onRefresh: _resfreshList,
child: Consumer<ExpenseNotifier>(
builder: (context, expense, child) {
return expense == null
? Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
PaddingClass(bodyImage: 'images/empty.png'),
SizedBox(
height: 20.0,
),
Text(
'You don\'t have any expenses',
style: kLabelTextStyle,
),
],
)
: ListView.separated(
itemBuilder: (context, int index) {
var myExpense = expense.expenseList[index];
return Card(
elevation: 8.0,
color: Colors.white70,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
RegularExpenseTextPadding(
regText:
'${_formattedDate(myExpense.updatedAt)}',
),
Container(
margin: EdgeInsets.all(20.0),
padding: const EdgeInsets.all(15.0),
decoration: BoxDecoration(
borderRadius:
BorderRadius.all(Radius.circular(5.0)),
border: Border.all(
color: kThemeStyleBorderHighlightColour),
),
child: Row(
children: <Widget>[
Expanded(
flex: 5,
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Text(
'${myExpense.amount}',
style: kRegularTextStyle,
),
SizedBox(
height: 20.0,
),
Text(
myExpense.description,
style: kRegularTextStyle,
),
],
),
),
Expanded(
flex: 1,
child: GestureDetector(
onTap: () {
expenseNotifier.currentExpense =
expenseNotifier
.expenseList[index];
Navigator.of(context).push(
MaterialPageRoute(builder:
(BuildContext context) {
return ExpenseDetailsScreen();
}));
},
child: Icon(
FontAwesomeIcons.caretDown,
color: kThemeIconColour,
),
),
),
],
),
),
],
),
);
},
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
height: 20.0,
);
},
itemCount: expenseNotifier.expenseList.length,
);
},
),
),
),
);
}
this is an example from my app:
bool _isLoading = false; <- default false
bool _isInit = true; <- to mae it only load once
#override
void initState() {
if (_isInit) {
// activating spinner
_isLoading = true;
// your function here <------
_isInit = false;
super.initState();
}
Initstate gets called before the user can see any kind of thin in your app, so this is the perfect place to make your firebase data load. with this logic from above the loading spinner shows as long you are receiving the data. And your body looks like the following then:
#override
Widget build(BuildContext context) {
return _isLoading <- is loading condition true? shows spinner
? Center(child: CircularProgressIndicator()) <- loading spinner
// else shows your content of the app
: SafeArea(
child: Container()
....