Flutter分页加载插件flutter_easy_paginate的使用

Flutter分页加载插件flutter_easy_paginate的使用

简介

Flutter Easy Paginate Platform License

flutter_easy_paginate 是一个用于 Flutter 应用程序的分页加载插件。它可以轻松集成到各种滚动小部件中,如 ListViewGridViewColumn 等。

特性

  • 无缝分页:当滚动到达底部时自动加载下一页的数据。
  • 自定义加载器:可以显示默认加载器或提供自己的自定义加载器小部件。
  • 灵活的滚动方向:支持垂直和水平滚动。

安装

在你的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  flutter_easy_paginate: ^1.2.0

使用方法

以下是一个简单的示例,展示了如何在 ListView 中使用 flutter_easy_paginate 插件:

import 'package:flutter/material.dart';
import 'package:flutter_easy_paginate/flutter_easy_paginate.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Easy Paginate',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyListView(),
    );
  }
}

class MyListView extends StatefulWidget {
  const MyListView({super.key});

  @override
  State<MyListView> createState() => _MyListViewState();
}

class _MyListViewState extends State<MyListView> {
  final List<String> _items = List.generate(20, (index) => 'Item $index');
  final ScrollController _scrollController = ScrollController();
  int page = 1;

  Future<void> _fetchNextPage() async {
    // 模拟API调用
    await Future.delayed(const Duration(seconds: 3));

    setState(() {
      _items.addAll(
          List.generate(20, (index) => 'Item ${_items.length + index}'));
      page++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        scrolledUnderElevation: 0.0,
        title: const Text('Paginate Example'),
        backgroundColor: Colors.deepPurple,
        foregroundColor: Colors.white,
        primary: true,
      ),
      body: Paginate(
        scrollController: _scrollController,
        onNextPage: _fetchNextPage,
        loader: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              "Loading...",
              style: TextStyle(
                fontSize: 18.0,
                color: Colors.grey,
              ),
            ),
          ],
        ),
        child: ListView.builder(
          itemCount: _items.length,
          controller: _scrollController,
          itemBuilder: (context, index) {
            return Card(
              color: Colors.white,
              margin: const EdgeInsets.symmetric(
                vertical: 8.0,
                horizontal: 16.0,
              ),
              child: ListTile(
                leading: CircleAvatar(
                  backgroundColor: Colors.deepPurple,
                  child: Text(
                    _items[index].split(' ')[1],
                    style: const TextStyle(color: Colors.white),
                  ),
                ),
                title: Text(
                  _items[index],
                  style: const TextStyle(fontWeight: FontWeight.bold),
                ),
                subtitle: const Text(
                  'This is a description of the item.',
                  style: TextStyle(color: Colors.grey),
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}

自定义加载器

你可以自定义加载器的样式。例如,将默认的加载器替换为一个简单的文本:

Paginate(
  scrollController: _scrollController,
  onNextPage: _fetchNextPage,
  loader: const Text("Loading..."),
  child: ListView.builder(
    controller: _scrollController,
    itemCount: _items.length,
    itemBuilder: (context, index) {
      return ListTile(
        title: Text(_items[index]),
      );
    },
  ),
);

更多关于Flutter分页加载插件flutter_easy_paginate的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter分页加载插件flutter_easy_paginate的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 flutter_easy_paginate 插件实现分页加载的示例代码。这个插件主要用于在 Flutter 应用中实现分页加载列表的功能。

首先,确保你已经在 pubspec.yaml 文件中添加了 flutter_easy_paginate 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_easy_paginate: ^x.y.z  # 请替换为最新版本号

然后运行 flutter pub get 以获取依赖。

接下来是一个完整的示例代码,展示如何使用 flutter_easy_paginate 来实现分页加载:

import 'package:flutter/material.dart';
import 'package:flutter_easy_paginate/flutter_easy_paginate.dart';

void main() {
  runApp(MyApp());
}

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final List<String> dummyData = List.generate(50, (index) => "Item $index");
  int currentPage = 1;
  int itemsPerPage = 10;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Easy Paginate Demo'),
      ),
      body: EasyPaginate(
        key: PageStorageKey<String>('page_storage'),
        controller: PagingController(initialPage: currentPage),
        pageLength: dummyData.length ~/ itemsPerPage, // 总页数
        onLoadMore: loadMore,
        itemBuilder: (context, index) {
          int itemIndex = (currentPage - 1) * itemsPerPage + index;
          return ListTile(
            title: Text(dummyData[itemIndex]),
          );
        },
      ),
    );
  }

  Future<void> loadMore() async {
    // 模拟网络请求或其他耗时操作
    await Future.delayed(Duration(seconds: 1));
    setState(() {
      currentPage += 1;
    });
  }
}

代码说明:

  1. 依赖导入:确保 flutter_easy_paginate 已经被添加到 pubspec.yaml 文件中。

  2. 数据准备:在 _MyHomePageState 类中,我们创建了一个包含 50 个字符串项的 dummyData 列表,模拟分页数据。

  3. 分页控制:使用 PagingController 控制分页逻辑,并设置初始页为第一页 (currentPage = 1)。

  4. 分页长度pageLength 是总页数,这里通过 dummyData.length ~/ itemsPerPage 计算得出。

  5. 加载更多数据onLoadMore 回调函数模拟了一个异步操作(例如网络请求),在加载更多数据后将当前页数 currentPage 增加 1。

  6. 列表项构建itemBuilder 回调函数用于构建每个列表项,根据当前页和索引计算出实际的数据索引,然后生成对应的 ListTile

运行这段代码,你将看到一个支持分页加载的列表,每次滚动到底部时会自动加载下一页的数据。这个示例仅用于演示基本用法,你可以根据实际需求对代码进行扩展和优化。

回到顶部