问题描述
我在应用程序启动时使用流数据从 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);
}