所以,我刚刚开始从事一个 flutter 项目,对整个体验还很陌生。我刚刚通过创建几个更新、删除和添加文档的按钮,成功地将 firebase firestore 集成到我的项目中。但是,我还想添加一个 Streambuilder 以及在同一页面上更新的列表。我分别尝试了每个任务,它们都工作得很好,但是当我将两者结合起来时,流构建器不显示任何数据,并且按钮不会单击。如何将按钮和 Streambuilder 合并到一个正文或一页中?我可以做什么来将这两个元素合并到小部件构建方法中的一个页面上?同样,如果我在主体中使用 Streambuilder 而不是子小部件标签,这两个元素似乎可以单独工作。
不工作页面的图片。请注意,当鼠标悬停在按钮上时,按钮不会被选择,并且 Streambuilder 会无限加载:https://i.stack.imgur.com/XnfVJ.png https://i.stack.imgur.com/XnfVJ.pngFirebase数据截图(安全设置允许用户访问数据):https://i.stack.imgur.com/oSsOL.png https://i.stack.imgur.com/oSsOL.png
这是我的 main.dart 代码:
final databaseReference = Firestore.instance;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('FireStore Demo'),
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
RaisedButton(
child: Text('Create Record'),
onPressed: () {
createRecord();
},
),
RaisedButton(
child: Text('View Record'),
onPressed: () {
getData();
},
),
RaisedButton(
child: Text('Update Record'),
onPressed: () {
updateData();
},
),
RaisedButton(
child: Text('Delete Record'),
onPressed: () {
deleteData();
},
),
StreamBuilder<QuerySnapshot>(
stream: databaseReference.collection('books').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) return new Text('Loading...');
return new ListView(
children: snapshot.data.documents.map((DocumentSnapshot document) {
return new ListTile(
title: new Text(document['title']),
subtitle: new Text('${document['description']} description'),
);
}).toList(),
);
},
)
],
)),
//center
);
}
void createRecord() async {
await databaseReference.collection("books")
.document("1")
.setData({
'title': 'Mastering Flutter',
'description': 'Programming Guide for Dart'
});
DocumentReference ref = await databaseReference.collection("books")
.add({
'title': 'Flutter in Action',
'description': 'Complete Programming Guide to learn Flutter'
});
print(ref.documentID);
}
void getData() {
databaseReference
.collection("books")
.getDocuments()
.then((QuerySnapshot snapshot) {
snapshot.documents.forEach((f) => print('${f.data}}'));
});
}
void updateData() {
try {
databaseReference
.collection('books')
.document('1')
.updateData({'description': 'Head First Flutter'});
} catch (e) {
print(e.toString());
}
}
void deleteData() {
try {
databaseReference
.collection('books')
.document('1')
.delete();
} catch (e) {
print(e.toString());
}
}
}