skip to Main Content

I am trying to implement indefinite scrolling with ListView.build:

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatefulWidget {
      @override
      State<MyApp> createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      final entries = [];
    
      void addData(num ind) async {
        await Future.delayed(const Duration(seconds: 5));
        entries.add(ind);
        print("$ind added");
        setState(() {});
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              if (index >= entries.length) {
                addData(index);
                return const Center(child: CircularProgressIndicator());
              }
              return SizedBox(
                height: 50,
                child: Center(child: Text('Entry ${entries[index]}')),
              );
            },
          ),
        );
      }
    }

As a result I see 8 items on the screen, but the ListView.builder built 24 items.

Why is that? How can I change it?

I would like to get data added for visible items only.

2

Answers


  1. Perhaps the logic should be

    home: ListView.builder(
      itemCount: entries.length + 1,
      itemBuilder: (BuildContext context, int index) {
        if (index == entries.length) {
          addData(index);
          return const Center(child: CircularProgressIndicator());
        }
        return SizedBox(
          height: 50,
          child: Center(child: Text('Entry ${entries[index]}')),
        );
      },
    ),
    

    Else other visible item will be filed with progress indication while itemCount is null.

    Login or Signup to reply.
  2. https://pub.dev/packages/inview_notifier_list
    Maybe this is what you are looking for.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search