I'm using a stream data to load data from API when app start up.But it had a problem, when It load the SearchPage widget, snapshot has data but when I change to other screen and back to SearchPage widget, it lost all data.
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);
}
Code when I call Stream data:
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,
))
);}