|
| 1 | +// Copyright 2014 The Flutter Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style license that can be |
| 3 | +// found in the LICENSE file. |
| 4 | + |
| 5 | +import 'package:flutter/material.dart'; |
| 6 | + |
| 7 | +void main() { |
| 8 | + runApp(InfiniteScrollApp()); |
| 9 | +} |
| 10 | + |
| 11 | +class InfiniteScrollApp extends StatelessWidget { |
| 12 | + const InfiniteScrollApp({super.key}); |
| 13 | + |
| 14 | + @override |
| 15 | + Widget build(BuildContext context) { |
| 16 | + return MaterialApp( |
| 17 | + title: 'Infinite Scrolling Flutter', |
| 18 | + home: InfiniteScrollList(), |
| 19 | + ); |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +class InfiniteScrollList extends StatefulWidget { |
| 24 | + const InfiniteScrollList({super.key}); |
| 25 | + |
| 26 | + @override |
| 27 | + InfiniteScrollListState createState() => InfiniteScrollListState(); |
| 28 | +} |
| 29 | + |
| 30 | +class InfiniteScrollListState extends State<InfiniteScrollList> { |
| 31 | + final List<String> items = []; |
| 32 | + final int itemsPerPage = 20; |
| 33 | + final List<String> staticData = [ |
| 34 | + "Hello Flutter", |
| 35 | + "Hello Flutter", |
| 36 | + "Hello Flutter", |
| 37 | + "Hello Flutter", |
| 38 | + "Hello Flutter", |
| 39 | + ]; |
| 40 | + |
| 41 | + @override |
| 42 | + void initState() { |
| 43 | + super.initState(); |
| 44 | + _loadMoreData(); // Load initial data |
| 45 | + } |
| 46 | + |
| 47 | + void _loadMoreData() { |
| 48 | + setState(() { |
| 49 | + final newItems = List.generate(itemsPerPage, (i) { |
| 50 | + return staticData[i % staticData.length]; |
| 51 | + }); |
| 52 | + items.addAll(newItems); |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + @override |
| 57 | + Widget build(BuildContext context) { |
| 58 | + return MaterialApp( |
| 59 | + home: Scaffold( |
| 60 | + appBar: AppBar( |
| 61 | + title: Text("Infinite Scrolling ListView (Static Data)"), |
| 62 | + ), |
| 63 | + body: NotificationListener<ScrollNotification>( |
| 64 | + onNotification: (ScrollNotification scrollInfo) { |
| 65 | + if (scrollInfo.metrics.pixels >= |
| 66 | + scrollInfo.metrics.maxScrollExtent - 50) { |
| 67 | + _loadMoreData(); |
| 68 | + return true; |
| 69 | + } |
| 70 | + return false; |
| 71 | + }, |
| 72 | + child: ListView.builder( |
| 73 | + itemCount: items.length, |
| 74 | + itemBuilder: (context, index) { |
| 75 | + return ListTile(title: Text(items[index])); |
| 76 | + }, |
| 77 | + ), |
| 78 | + ), |
| 79 | + ), |
| 80 | + ); |
| 81 | + } |
| 82 | +} |
0 commit comments