SliverChildListDelegate and children initState

1.8k views Asked by At

It is required to implement lazy loading of content and components via API using SliverList on the page. I assumed that it is possible to load content through the API in children by accessing the API initState, but in this way, since SliverChildListDelegate removes a component when scrolling, the call initState and API access occurs every time. So, the only correct way noat to do each API call is to load all the necessary information in the parent component and pass it to the children? However, this way the page will be drawn only when the last of its element will be loaded, and would like to load the components and their information without slowing down the rendering of already loaded content.

Steteless Parent

    SliverList(
            delegate: SliverChildListDelegate([
              HomeSlider(), // every time calling initState when come and out of viewport
              Container(
                height: 3000, // Space for test
                color: Colors.black,
              ),
            ]),
          ),

Statefull child

 @override
  void initState() {
    fetchSlides();

    super.initState();
  }

  Future<void> fetchSlides() async {
    final response = await Request().get('/sliders');

    setState(() {
      slides = response.data['sliders'];
    });
  }
1

There are 1 answers

0
Afridi Kayal On BEST ANSWER

By making children widgets with AutomaticKeepAliveClientMixin, they don't get rebuilt every time in sliver lists.

Try this in your child widgets:

class _SomeChildState extends State<SomeChild> with AutomaticKeepAliveClientMixin {

    @override
    bool get wantKeepAlive => true; // You can add custom logic based on whether you want to remove the child or not.

    @override
    Widget build(BuildContext context) {
        super.build(context); // You need to call super.build(context)
        return ... // Your widget
    }
}