如何解决无法使用 Stream flutter 再次加载数据
我在应用程序启动时使用流数据从 API 加载数据。但是它有一个问题,当它加载 SearchPage 小部件时,快照有数据但是当我切换到其他屏幕并返回到 SearchPage 小部件时,它丢失所有数据。
class _SearchPageState extends State<SearchPage> with TickerProviderStateMixin {
final locationsstream = StreamController<List<Weather>>.broadcast();
late final AnimationController _controller = AnimationController(
duration: const Duration(seconds: 2),vsync: this,)..repeat(reverse: true);
late final Animation<double> _animation = CurvedAnimation(
parent: _controller,curve: Curves.elasticOut,);
@override
void dispose() {
_controller.dispose();
super.dispose();
locationsstream.close();
}
@override
void initState() {
loadData();
// Todo: implement initState
super.initState();
}
void loadData() async {
WeatherRepo weatherRepo = WeatherRepo();
List<Weather> RSS = await weatherRepo.loadMainLocations();
locationsstream.sink.add(RSS);
}
Container(
height: 300,child: StreamBuilder<List<Weather>>(
stream: locationsstream.stream,initialData: null,builder: (context,snap) {
if (!snap.hasData) {
return Container(
child: Center(
child: CircularProgressIndicator(),),);
}
final data = snap.data;
return Container(
height: 300,child: CarouselSlider(
items: <Widget>[
for (Weather w in data!) MainLocation(location: w),],options: CarouselOptions(
height: 300.0,autoplay: true,autoplayInterval: Duration(seconds: 3),autoplayAnimationDuration: Duration(milliseconds: 2000),autoplayCurve: Curves.fastOutSlowIn,enlargeCenterPage: true,scrollDirection: Axis.horizontal,))
);}
解决方法
试试这个
final StreamController<List<Weather>> locationsStream =
StreamController<List<Weather>>.broadcast();
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
await loadData();
});
}
void loadData() async {
WeatherRepo weatherRepo = WeatherRepo();
List<Weather> rss = await weatherRepo.loadMainLocations();
locationsStream.add(rss);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。