【发布时间】:2022-01-05 20:32:15
【问题描述】:
我是 Flutter SDK 的新手,我创建了一个带有两个选项卡的 Flutter 应用程序。
在第一个选项卡上,我有一个 ListView,它显示来自 FutureBuilder 的项目,它通过 http 获取数据。
在第二个选项卡上,我有一个 ListView,它显示来自 StreamBuilder 的项目,在将项目从第一个选项卡添加到数据库后,也通过 http 获取数据。
问题是:当我来回切换选项卡时,第二个选项卡不会重新加载 http 调用并显示错误
Bad State:Stream 已被监听。
除非我手动按下刷新按钮(这是一个 setState(() {}); )然后它会再次加载,有没有办法让它在标签更改时重新加载?
这是我的 http 调用:
Future<List> getDataDB() async {
final rep = await http.get(Uri.parse("http://192.168.0.105/fluttertest/public/showfood"));
if (rep.statusCode == 200) {
return jsonDecode(rep.body);
} else {
throw Exception('Failed to load');
}
}
Future<List> getDataOrder() async {
String id = widget.list[widget.index]['id'].toString();
final getb = await http.get(Uri.parse("http://192.168.0.105/fluttertest/public/getbill/"+id));
if (getb.statusCode == 200) {
return jsonDecode(getb.body);
} else {
throw Exception('Failed to load');
}
}
这是我的 StreamBuilder:
child: StreamBuilder<List>(
stream: Stream.periodic(Duration(seconds: 1))
.asyncMap((i) => getDataOrder()),
builder: (context,snapshot){
List<Widget> children;
if(snapshot.hasData){
children = <Widget>[
Expanded(child: BillItems(list:snapshot.data!,tableid:widget.list[widget.index]['id'])),
];
}
else if (snapshot.hasError) {
children = <Widget>[
Text('Error: ${snapshot.error}'),
];
}
else {
children = const <Widget>[
SizedBox(
child: CircularProgressIndicator(),
),
];
}
return Center(
child: Column(
children: children,
),
);
}
),
'''
【问题讨论】: