大数据列表中的分页 - Flutter

Pagination in a Large List of Data - Flutter

我想在大量数据列表中进行分页。我一直在寻找Flutter中的分页,但他们都在展示使用加载更多或延迟加载的方式,但我想一页一页地加载数据。所以,如果我有一个 100 条数据列表,在第一页上会有 1-10 的数据列表,第二页:11-20,...是否有任何资源可供我使用?

我已经给了你一个完整的例子。如果您有任何问题,请告诉我。此外,您需要检查 page is not < 0 > max available page.

查看操作演示:https://dartpad.dev/?null_safety=true&id=45a5415abd0ae0fa87caac53e3b7f3e3

要点:https://gist.github.com/omishah/45a5415abd0ae0fa87caac53e3b7f3e3

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;
  MyHomePage({Key? key, required this.title}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final List<int> _data = List.generate(100, (i) => i); // generate a sample data ( integers ) list of 100 length
  int _page = 0; // default page to 0
  final int _perPage = 10; // per page items you want to show

  @override
  Widget build(BuildContext context) {
    final dataToShow =
        _data.sublist((_page * _perPage), ((_page * _perPage) + _perPage)); // extract a list of items to show on per page basis

    return Scaffold(
        body: Column(children: [
      Row(children: [
        ElevatedButton(
          onPressed: () => {
            setState(() {
              _page -= 1;
            })
          },
          child: const Text('Prev'),
        ),
        ElevatedButton(
          onPressed: () => {
            setState(() {
              _page += 1;
            })
          },
          child: const Text('Next'),
        )
      ]),
      ListView.builder(
        shrinkWrap: true,
        itemCount: dataToShow.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text('${dataToShow[index]}'),
          );
        },
      )
    ]));
  }
}