How To Create An Infinite Scroll In Listview Using Flutter

admin_img Posted By Bajarangi soft , Posted On 27-11-2020

Infinite scrolling is a technique where loading of content is done continuously as the user scrolls down, without any action from the user. This has popularized by social media sites and apps such as Twitter, where Twitter loads more tweets as you scroll down. This is a form of pagination but requires no user input to load the next page but instead watches scroll position.

How To Create An Infinite Scroll In Listview Using Flutter

 Infinite Scroll In Listview
Complete Code For Infinite Scroll In Listview In Flutter
main.dart

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _loadMore();
      }
    });
  }

  _loadMore() {
    setState(() {
      print('loading more,...');
      //if we're at the end of the list, add more items
      _listViewData..addAll(List<String>.from(_listViewData));
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  List<String> _listViewData = [
    "Flutter",
    "Android",
    "iOS",
    "React Native",
    "React",
    "Laravel",
    "Php",
    "Html",
    "Mysql",
    "Oracle",
    "Javascript",
    "Jquery",
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.lightGreen[800],
        title: Text('Infinite Scroll In ListView'),
      ),
      body: ListView.builder(
        itemCount: _listViewData.length,
        controller: _scrollController,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(_listViewData[index]),
          );
        },
      ),
    );
  }
}

Related Post