I want to user a StreamController
to control a StreamBuilder
that gets data from a collection in Firestore
. This will enable me to use a RefereshIndicator
so that when I pull down on the list, it refreshes/ fetches more data if there is any.
I used most of the information in this article. My current code is below
class _Lists extends State<List> {
StreamController _controller;
final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
@override
void initState() {
_controller = new StreamController();
loadPosts();
super.initState();
}
Future fetchPost() async {
return await .
Firestore.instance.collection(_locationState).snapshots();
}
Future<Null> _handleRefresh() async {
count++;
print(count);
fetchPost().then((res) async {
_controller.add(res);
showSnack();
return null;
});
}
showSnack() {
return scaffoldKey.currentState.showSnackBar(
SnackBar(
content: Text('New content loaded'),
),
);
}
loadPosts() async {
fetchPost().then((res) async {
print(res.document);
_controller.add(res);
return res;
});
}
@override
Widget build(BuildContext context) {
final topBar = AppBar(Title("List"));
bottom: TabBar(
indicatorColor: Colors.blueAccent,
indicatorWeight: 3.0,
//indicatorSize: 2.0,
indicatorPadding:
const EdgeInsets.only(bottom: 10.0, left: 47.0, right:
47.0),
tabs: [
Tab(
child: Image(
image: AssetImage("MyImage1"),
width: 65.0,
height: 65.0,
),
),
Tab(
child: Image(
image: AssetImage("Image2"),
width: 90.0,
height: 90.0,
),
),
],
),
return DefaultTabController(
length: 2,
child: Scaffold(
key: scaffoldKey,
appBar: topBar,
body: StreamBuilder(
stream: _controller.stream,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return Text(snapshot.error);
}
if (snapshot.connectionState == ConnectionState.active) {
List aList = new List();
aList.clear();
for (DocumentSnapshot _doc in snapshot.data.documents) {
Model _add = new Model.from(_doc);
aList.add(_add);
}
return TabBarView(
children: <Widget>[
RefreshIndicator(
onRefresh: _handleRefresh,
child: ListView.builder(
itemCount: aList.length,
itemBuilder: (context, index) {
return Card(aList[index]);
},
),
),
Icon(Icons.directions_transit),
],
);
} else {
return Container(
child: Center(child: CircularProgressIndicator()));
}
})));
}
}
}
The Problem I have with this is I keep getting the error
flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY
╞═══════════════════════════════════════════════════════════
flutter: The following NoSuchMethodError was thrown building
StreamBuilder<dynamic>(dirty, state:
flutter: _StreamBuilderBaseState<dynamic,
AsyncSnapshot<dynamic>>#53c04):
flutter: Class '_BroadcastStream<QuerySnapshot>' has no instance getter 'documents'.
flutter: Receiver: Instance of '_BroadcastStream<QuerySnapshot>'
flutter: Tried calling: documents
Any ideas on how to go about using the StreamController
with data from Firestore
?