Hello I am developing MobileApp with Flutter and Firebase
I have a question about the Stream builder.
In my code, I am getting the data with Stream builder from Firebase, I got the date what I needed, but my question is I want to change the stream in the screen Once I press any button.
For example which is my initial stream,
gvDatabaseService.postCollectionReference
.doc(widget.hiveCode)
.collection('Posts')
.snapshots()
Once I press button I want to change the stream like this
gvDatabaseService.postCollectionReference
.doc(widget.hiveCode)
.collection('Posts')
.where('isOpened', isEqualTo: false)
.snapshots()
So what I did , I declare variable named stream, in iniState I defined initial value. Also by making button that change stream with setState, I changed stream. It actually work and I got the data that I needed, however I feel it seems like bit weird. I am just wondering if which way is proper way or not..
Thanks for reading, I am waiting for your help...
class PostMainScreen extends StatefulWidget {
final String hiveCode;
PostMainScreen({
Key key,
@required this.hiveCode,
}) : super(key: key);
@override
_PostMainScreenState createState() => _PostMainScreenState();
}
class _PostMainScreenState extends State<PostMainScreen> {
//Variable ——————————————————————————————————
Authentication authentication;
var stream;
//—————————————————————————————————— Variable
//Functions——————————————————————————————————
@override
void initState() {
super.initState();
// getSnapshot();
stream = gvDatabaseService.postCollectionReference
.doc(widget.hiveCode)
.collection('Posts')
.snapshots();
}
buildHeader() {
return Container(
height: getMQHeight(context: context) * 0.3,
width: getMQWidth(context: context),
color: Colors.blue,
child: Center(
child: InkWell(
onTap: () {
setState(() {
stream = gvDatabaseService.postCollectionReference
.doc(widget.hiveCode)
.collection('Posts')
.where('isOpened', isEqualTo: false)
.snapshots();
});
print('here2');
},
child: Text('Click'),
),
),
);
}
buildPostList() {
return Expanded(
child: Container(
width: getMQWidth(context: context),
color: Colors.red,
child: StreamBuilder<QuerySnapshot>(
stream: stream,
builder: (context, snapshots) {
if (!snapshots.hasData) {
return LoadingScreen();
} else {
List<AnnouncementBox> annList = [];
snapshots.data.docs.forEach((post) {
annList.add(AnnouncementBox(
post: Post.fromDocument(post),
));
});
return ListView(
children: annList,
);
}
},
)),
);
}
buildBody() {
return Container(
child: Column(
children: [buildHeader(), buildPostList()],
),
);
}
//——————————————————————————————————Functions
@override
Widget build(BuildContext context) {
authentication = Provider.of<Authentication>(context, listen: true);
return Scaffold(
body: buildBody(),
);
}
}