flutter - 如何自动刷新 Stream Builder
问题描述
我有一个流构建器调用未来函数。我需要流生成器自动更新,但只有在我关闭并重新打开应用程序时才会刷新我该怎么办,请给我一个解决方案。我的代码:
StreamBuilder(
stream: _databaseService.fetchNames(uid, 'Users').asStream(),
builder: (context, AsyncSnapshot snapshot) {
print(snapshot);
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Container(
child: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(secondaryColor),
)),
);
break;
case ConnectionState.active:
return Container(
child: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(secondaryColor),
)),
);
break;
case ConnectionState.done:
if (snapshot.data == 'No data') {
return Container(
child: Center(child: Text('No Chats')),
);
} else if (snapshot.data != 'No data') {
List names = snapshot.data['collection'];
return ListView(
physics: BouncingScrollPhysics(),
padding: EdgeInsets.only(top: 10),
children: names
.map((e) => ListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChatScreen(
username: e['name'],
receiverUid: e['id'])));
},
leading: CircleAvatar(
backgroundColor: secondaryColor,
child: Icon(
Icons.person,
color: Colors.white,
),
),
title: Padding(
padding: const EdgeInsets.only(top: 5.0),
child: Text(
e['name'].toString()[0].toUpperCase() +
e['name'].toString().substring(
1,
),
style: TextStyle(fontSize: 25),
),
)))
.toList(),
);
}
break;
case ConnectionState.none:
return Container(
child: Center(child: Text('No network')),
);
break;
}
return Container(
child: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(secondaryColor),
)),
);
},
)
我的未来功能:
Future fetchNamesId(documentName, collectionName) async {
Response response = await post(url,
headers: {
"Content-Type": "application/json; charset=utf-8",
},
body: jsonEncode(
{"documentName": documentName, "collectionName": collectionName}));
if (response.body == "No data") {
return "No data";
}
return jsonDecode(response.body);
}
这是我得到的数据流,即 sanpshot.data:
{collection: [{id: 7hgIFK07xwhDGM82kJiQyGua36E3, name: bvc}, {id: Fgtf4ikE0QPifgknq5AVUdxCV2V2, name: vee}, {id: GbYWYJXcKwMmjsbx99QCvw0gWVL2, name: luu}, {id: egkH6fX7B2db54V1ALYWbKAXwG33, name: dia}]}
每当我在数据库中添加另一个值时,流不会自动刷新,我需要关闭并重新打开选项卡。
在代码中,我将其设为异步,但即使它没有自动更新。
请给我一个解决方案,我很震惊。提前致谢。
解决方案
我建议使用提供者。您可以像这样将 StreamBuilder 包装到 StreamProvider :
@override
Widget build(BuildContext context) {
return StreamProvider<whatever your stream returns>.value(
value: your stream,
child: StreamBuilder(...
推荐阅读
- google-app-maker - 从手机编辑应用程序时,如何将小部件拖到页面上?
- c - 在 C 中保持纵横比(ncurses)
- python - 调整 MobileNet 训练数据的百分比
- c# - DataGridView 并从 XML 解析字符串
- html - 无法将行中的列居中
- sql - 引用同一数据集中其他列的列
- php - 当页面上有多个表单时,使用 ajax 提交表单
- c - 为什么我不能为 C 函数外部的全局变量赋值?
- java - Ionic 2 地理围栏上的后台服务不会触发
- node.js - MongooseJS - 如何在 Mongoose Populate Virtuals 的文档数组中指定对象的字段?