我正在用flutter web构建一个网站,但我无法将数据从firestore提取到StreamBuilder,因为onSnapshot不工作。。。
我在用这个包https://pub.dev/packages/firebase
我的代码:
import 'package:flutter/material.dart';
import 'package:firebase/firebase.dart';
import 'package:firebase/firestore.dart' as fs;
class Playground extends StatefulWidget {
@override
_PlaygroundState createState() => _PlaygroundState();
}
class _PlaygroundState extends State<Playground> {
@override
Widget build(BuildContext context) {
fs.Firestore dataBase = firestore();
fs.CollectionReference teachersRef = dataBase.collection('teachers');
return Center(
child: Container(
width: 700,
height: 400,
color: Colors.cyanAccent,
child: StreamBuilder(
stream: teste.collection('teachers').onSnapshot,
builder: (context, snapshot) {
if (!snapshot.hasData) return Text('Loading...');
return ListView.builder(
//itemExtent: 30,
itemCount: 4,
itemBuilder: (context, index) {
return Container(
width: 10,
color: Colors.amber,
child: Text(snapshot.data[index]['name']),
);
},
);
},
),
),
);
}}
但我得到的答案是:
'[]'null的动态调用。接收方:"QuerySnapshot"的实例参数:[0]
有人知道如何在Flutter网站上正确使用Firestore吗?
我认为问题与最终构建线有关
child: Text(snapshot.data[index]['name']),
快照数据是来自JScript
导入的QuerySnapshot
,而不是您正在执行的AsyncQuerySnapshot
。
我修改了呼叫,取得了一些成功
child: Text(snapshot.data.docs[index].get('name')),
我认为你的问题在这里:
fs.CollectionReference teachersRef = dataBase.collection('teachers');
试试这个:
final teachersRef = Firestore.instance.collection('teachers');
现在,您可以使用teachersRef获取快照,并在StreamBuilder中使用它
Hi您应该使用firestore()
初始值设定项函数。您应该在代码中有<script src="https://www.gstatic.com/firebasejs/7.2.1/firebase-storage.js"></script>
行,并在main中对其进行初始化。示例代码如下:
!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Your web app title</title>
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/7.2.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.1/firebase-firestore.js"></script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
// your main function
void main(){
initializeApp(
apiKey: "{YOUR API KEY}",
authDomain: "{YOUR AUTH DOMAIN}",
databaseURL: "{YOUR DATABASE URL}",
projectId: "{YOUR PROJECT ID}",
storageBucket: "{YOUR STORAGE BUCKET}",
messagingSenderId: "{YOUR MESSAGING SENDER ID}",
);
runApp(MyApp());
}
使用库的实际类
import 'package:firebase/firestore.dart';
class FirebaseHandler {
FirebaseHandler({Firestore firestoreInstance,})
: _firestore = firestoreInstance ?? firestore(); // firestore() is the default initializer for your firebase APP firestore.
final Firestore _firestore;
Stream getCollection(String collection){
try {
return _firestore.collection(collection + "/").onSnapshot;
} catch (e) {
print('Error retrieving snapshot: $e');
throw '$e';
}
}
}