Flutter分页加载插件flutter_pagination的使用

发布于 1周前 作者 songsunli 来自 Flutter

Flutter分页加载插件flutter_pagination的使用

使用分页在Flutter中

示例1:不使用分组

import 'package:flutter/material.dart';
import 'package:flutter_pagination/flutter_pagination.dart';
import 'package:flutter_pagination/widgets/button_styles.dart';

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int currentPage = 1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Pagination Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Current Page: $currentPage'),
            SizedBox(height: 20),
            Pagination(
              paginateButtonStyles: PaginateButtonStyles(),
              prevButtonStyles: PaginateSkipButton(
                  borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(20),
                      bottomLeft: Radius.circular(20))),
              nextButtonStyles: PaginateSkipButton(
                  borderRadius: const BorderRadius.only(
                      topRight: Radius.circular(20),
                      bottomRight: Radius.circular(20))),
              onPageChange: (number) {
                setState(() {
                  currentPage = number;
                });
              },
              useGroup: false,
              totalPage: 30,
              show: 2,
              currentPage: currentPage,
            ),
          ],
        ),
      ),
    );
  }
}

示例2:使用分组

import 'package:flutter/material.dart';
import 'package:flutter_pagination/flutter_pagination.dart';
import 'package:flutter_pagination/widgets/button_styles.dart';

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int currentPage = 1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Pagination Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Current Page: $currentPage'),
            SizedBox(height: 20),
            Pagination(
              width: MediaQuery.of(context).size.width * .6, // 这个属性是可选的
              paginateButtonStyles: PaginateButtonStyles(),
              prevButtonStyles: PaginateSkipButton(
                  borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(20),
                      bottomLeft: Radius.circular(20))),
              nextButtonStyles: PaginateSkipButton(
                  borderRadius: const BorderRadius.only(
                      topRight: Radius.circular(20),
                      bottomRight: Radius.circular(20))),
              onPageChange: (number) {
                setState(() {
                  currentPage = number;
                });
              },
              useGroup: true,
              totalPage: 30,
              show: 4,
              currentPage: currentPage,
            ),
          ],
        ),
      ),
    );
  }
}

注意事项

  • 如果显示值大于总页数,将会抛出错误。
  • 高度值默认为50,并且仅在分组分页中生效。宽度也是如此。

样式设置

import 'package:flutter/material.dart';
import 'package:flutter_pagination/flutter_pagination.dart';
import 'package:flutter_pagination/widgets/button_styles.dart';

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int currentPage = 1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Pagination Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Current Page: $currentPage'),
            SizedBox(height: 20),
            Pagination(
              paginateButtonStyles: PaginateButtonStyles(
                  backgroundColor: Colors.pink,
                  activeBackgroundColor: Colors.black,
                  activeTextStyle: const TextStyle(color: Colors.red)),
              prevButtonStyles: PaginateSkipButton(
                  buttonBackgroundColor: Colors.orange,
                  icon: const Icon(
                    Icons.arrow_back_ios,
                    size: 30,
                  ),
                  borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(20),
                      bottomLeft: Radius.circular(20))),
              nextButtonStyles: PaginateSkipButton(
                  buttonBackgroundColor: Colors.purple,
                  icon: const Icon(
                    Icons.arrow_right_alt,
                    color: Colors.white,
                  ),
                  borderRadius: const BorderRadius.only(
                      topRight: Radius.circular(20),
                      bottomRight: Radius.circular(20))),
              onPageChange: (number) {
                setState(() {
                  currentPage = number;
                });
              },
              useGroup: true,
              totalPage: 30,
              show: 4,
              currentPage: currentPage,
            ),
          ],
        ),
      ),
    );
  }
}

必填字段

字段名称 类型
totalPage integer
currentPage integer
onPageChange (number) => void
nextButtonStyles PaginateSkipButton
prevButtonStyles PaginateSkipButton
paginateButtonStyles PaginateButtonStyles

希望这些示例和说明对你有所帮助!如果你有任何问题或需要进一步的帮助,请随时提问。


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

1 回复

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


当然,下面是一个关于如何在Flutter中使用flutter_pagination插件进行分页加载的示例代码。这个插件允许你轻松地实现分页加载功能,特别是在滚动列表(如ListView)中。

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

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

然后,运行flutter pub get来安装依赖。

以下是一个完整的示例,展示了如何使用flutter_pagination进行分页加载:

import 'package:flutter/material.dart';
import 'package:flutter_pagination/flutter_pagination.dart';
import 'dart:convert';

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  final PaginationController _paginationController = PaginationController(1);

  List<String> items = [];

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  Future<void> _fetchData() async {
    try {
      // 模拟从服务器获取数据
      String response = await fetchData(_paginationController.page);
      List<dynamic> fetchedData = jsonDecode(response);
      
      setState(() {
        if (_paginationController.page == 1) {
          items = fetchedData.cast<String>();
        } else {
          items.addAll(fetchedData.cast<String>());
        }
      });
    } catch (error) {
      print("Error fetching data: $error");
    }
  }

  Future<String> fetchData(int page) async {
    // 这里使用模拟数据,通常你会调用你的API
    String mockData = '''
      [
        {"id": "1", "name": "Item ${(page - 1) * 10 + 1}"},
        {"id": "2", "name": "Item ${(page - 1) * 10 + 2}"},
        {"id": "3", "name": "Item ${(page - 1) * 10 + 3}"},
        {"id": "4", "name": "Item ${(page - 1) * 10 + 4}"},
        {"id": "5", "name": "Item ${(page - 1) * 10 + 5}"},
        {"id": "6", "name": "Item ${(page - 1) * 10 + 6}"},
        {"id": "7", "name": "Item ${(page - 1) * 10 + 7}"},
        {"id": "8", "name": "Item ${(page - 1) * 10 + 8}"},
        {"id": "9", "name": "Item ${(page - 1) * 10 + 9}"},
        {"id": "10", "name": "Item ${(page - 1) * 10 + 10}"}
      ]
    ''';
    return mockData;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Pagination Example'),
      ),
      body: Pagination<String>(
        paginationController: _paginationController,
        builder: (context, dataList, itemCount) {
          return ListView.builder(
            itemCount: itemCount,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(dataList[index]),
              );
            },
          );
        },
        onPageChanged: (page, itemCount) {
          _fetchData();
        },
        itemCountPerPage: 10,  // 每页的项目数量
      ),
    );
  }
}

代码解释

  1. 依赖安装:确保flutter_pagination已经添加到你的pubspec.yaml文件中。

  2. PaginationController:创建一个PaginationController实例来管理分页状态。

  3. 数据获取_fetchData方法模拟从服务器获取数据,并将数据添加到列表中。在实际应用中,你会调用你的API来获取数据。

  4. 分页组件:使用Pagination组件来构建分页列表。builder属性用于构建列表项,onPageChanged回调用于在页面改变时获取新数据。

  5. ListView.builder:使用ListView.builder来构建列表项,根据Pagination组件提供的数据和数量来渲染列表。

这样,你就可以在Flutter应用中实现分页加载功能了。确保替换模拟数据部分为你的实际API调用逻辑。

回到顶部