Streams 与 Flutter-Listview 的正确使用
Correct use of Streams with Flutter-Listview
我正在尝试在 flutter
中使用 firebase-firestore
显示实时聊天屏幕(相当于 whatsapp 的主屏幕)。
工作:创建所有联系人“同行”的列表。看看我的列表视图:
Container(
child: StreamBuilder(
stream:
//FirebaseFirestore.instance.collection('users').snapshots(),
FirebaseFirestore.instance
.collection('users')
.doc(currentUserId)
.collection('peers')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(themeColor),
),
);
} else {
return ListView.builder(
padding: EdgeInsets.all(10.0),
itemBuilder: (context, index) =>
buildItem(context, snapshot.data.documents[index]),
itemCount: snapshot.data.documents.length,
);
}
},
),
),
不工作:正在为每个图块加载特定数据,例如最后一条消息 或名称。我在创建第一个列表时无法查询(第一个查询 returns peer-ids,第二个 returns peer-id 的用户数据)。我的 buildItem
方法由另一个 streambuilder 组成,但是,一旦第一个 streambuilder 进行更改,应用程序就会冻结。
Widget buildItem(BuildContext context, DocumentSnapshot document) {
return StreamBuilder<DocumentSnapshot>(
stream: FirebaseFirestore.instance
.collection('users')
.doc(document.data()['peerId'])
.snapshots(),
builder: ...
这是嵌套流的正确方法吗?简单的列表视图有很好的文档记录,但我在 google 上找不到这方面的好例子。感谢任何帮助。
尝试在 initState 中只创建一次流并将其传递给此方法:
//in initState
peersStream = FirebaseFirestore.instance
.collection('users')
.doc(currentUserId)
.collection('peers')
.snapshots(),
然后在StreamBuilder
中使用stream: peersStream
。
此外,建议对小部件使用 widget-classes over 方法:
我正在尝试在 flutter
中使用 firebase-firestore
显示实时聊天屏幕(相当于 whatsapp 的主屏幕)。
工作:创建所有联系人“同行”的列表。看看我的列表视图:
Container(
child: StreamBuilder(
stream:
//FirebaseFirestore.instance.collection('users').snapshots(),
FirebaseFirestore.instance
.collection('users')
.doc(currentUserId)
.collection('peers')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(themeColor),
),
);
} else {
return ListView.builder(
padding: EdgeInsets.all(10.0),
itemBuilder: (context, index) =>
buildItem(context, snapshot.data.documents[index]),
itemCount: snapshot.data.documents.length,
);
}
},
),
),
不工作:正在为每个图块加载特定数据,例如最后一条消息 或名称。我在创建第一个列表时无法查询(第一个查询 returns peer-ids,第二个 returns peer-id 的用户数据)。我的 buildItem
方法由另一个 streambuilder 组成,但是,一旦第一个 streambuilder 进行更改,应用程序就会冻结。
Widget buildItem(BuildContext context, DocumentSnapshot document) {
return StreamBuilder<DocumentSnapshot>(
stream: FirebaseFirestore.instance
.collection('users')
.doc(document.data()['peerId'])
.snapshots(),
builder: ...
这是嵌套流的正确方法吗?简单的列表视图有很好的文档记录,但我在 google 上找不到这方面的好例子。感谢任何帮助。
尝试在 initState 中只创建一次流并将其传递给此方法:
//in initState
peersStream = FirebaseFirestore.instance
.collection('users')
.doc(currentUserId)
.collection('peers')
.snapshots(),
然后在StreamBuilder
中使用stream: peersStream
。
此外,建议对小部件使用 widget-classes over 方法: