chat_app_live_stream
chat_app_live_stream copied to clipboard
be aware of using StreamBuilder in build()
One more things for other people using this example as starting point for their own efforts (as i ve done) .Putting StreamBuilder() together with a firestore Stream inside Flutter build() method is pretty costly. Flutter rebuilds the Chat widget everytime the textfield gets focused. Thus doing firestore reads even though nothing happened except you focusing the textfield. If you have a big chatroom this in fact costs money big time.
I put the StreamBuilder in initState() and let it create a Widget which i placed as instance variable and used further down in the build method.
@override
void initState() {
super.initState();
temp = StreamBuilder<QuerySnapshot>(
stream: _firestore
.collection('messages')
.orderBy('date')
.snapshots(),
builder: (context, snapshot) {
print("Only StreamBuilder");
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
List<DocumentSnapshot> docs = snapshot.data.documents;
print("Length: ${docs.length}");
List<Widget> messages = docs
.map((doc) => Message(
from: doc.data['from'],
text: doc.data['text'],
me: widget.user.email == doc.data['from'],
))
.toList();
return ListView(
controller: scrollController,
children: <Widget>[
...messages,
],
);
},
);
}
and later on in the code:
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: temp),
Feel free to comment on that approach.