【发布时间】:2020-12-28 07:32:06
【问题描述】:
我有一个流构建器调用一个未来函数。 我需要流生成器自动更新,但只有在我关闭并重新打开应用程序时才会刷新我该怎么办,请给我一个解决方案。 我的代码:
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}]}
每当我在数据库中添加另一个值时,流都不会自动刷新,我需要关闭并重新打开选项卡。
在代码中,我将其设为异步,但即使它没有自动更新。
请给我一个解决方案,我很震惊。 提前致谢。
【问题讨论】: