I see several questions and answers about Flutter for mobile that use stream builder like this:
body: new StreamBuilder(
stream: Firestore.instance.collection("collection").snapshots(),
builder: (context, snapshot) {
...
I'm trying to do the same on flutter for the web, but in my configuration, the snapshots()
method is unknown, generating an exception while running (and a vscode warning beforehand). Why? Do I have an incorrect setup?
I've followed these steps which I found here and elsewhere:
1) Included firebase as a dependency in pubspec.yaml
dependencies:
flutter:
sdk: flutter
firebase: ^6.0.0
2) Included the firestore js scripts in the index.html body tag:
<script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-firestore.js"></script>
<script src="main.dart.js" type="application/javascript"></script>
3) In main.dart, imported firebase.dart files (using advice given here, though I'm not exactly sure which step above got me access to this package. I'm a flutter nube, if it isn't obvious)
import 'package:flutter/material.dart';
import 'package:firebase/firebase.dart' as fb;
import 'package:firebase/firestore.dart' as fs;
Having followed these steps, I can get this code working....
void main() {
if (fb.apps.length == 0) {
try {
fb.initializeApp(
apiKey: "mike",
authDomain: "myauthdomain",
databaseURL: "mydburl",
projectId: "myproductid",
storageBucket: "mystoragebucket",
);
} catch(e) {
print(e);
}
}
fs.Firestore store = fb.firestore();
fs.CollectionReference ref = store.collection("MyCollection");
ref.onSnapshot.listen((querySnapshot) {
querySnapshot.docs.forEach((doc) {
print(doc.data()); // this works!!
});
});
runApp(MyApp());
}
But, as I mentioned earlier, getting the stream builder working, all of the advice suggests that I can get a stream of snapshots by saying...
class MyList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new StreamBuilder(
stream: fb.firestore().collection('MyCollection').snapshots(),
...
The packages I have running on web don't seem to have anything like the snapshots
method (or property) on a firestore collection reference. Can somebody set me straight?