flutter实现上拉加载下拉刷新

效果如下:

flutter实现上拉加载下拉刷新

使用到的库是easy_refresh

安装请查看官网

接口用的是提供的接口https://reqres.in/

请求接口用到的库是dio

下面主要是介绍如何使用easy_refresh实现上拉加载数据,详细学习其它例子请查看easy_refresh

main.dart全部代码如下

Dart 复制代码
import 'package:flutter/material.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:dio/dio.dart' as MyDio;

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'EasyRefresh',
      home: HomePage(),
    );
  }
}

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _page = 1;
  List<UserData> dataList = [];
  late EasyRefreshController _controller;

  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
    setState(() {
      dataList = [];
      _page = 1;
    });
    initListData();
  }

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

  Future<ApiResponse> _fetchListData(int page) async {
   
    MyDio.Dio dio = MyDio.Dio();
    MyDio.Response response =
        await dio.get('https://reqres.in/api/users', queryParameters: {
      'page': page,
    });
    ApiResponse data = ApiResponse.fromJson(response.data);
    return data;
  }

  void initListData() async {
    final resData = await _fetchListData(_page);

    if (resData.data.isNotEmpty) {
      setState(() {
        dataList = dataList..addAll(resData.data);
        _page = _page + 1;
      });
      _controller.finishRefresh();
      _controller.resetFooter();
      initListData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('EasyRefresh'),
      ),
      body: EasyRefresh(
        controller: _controller,
        header: const ClassicHeader(
            armedText: '下拉加载更多',
            readyText: '正在加载中...',
            showMessage: false,
            processedText: '加载完成',
            processingText: '刷新中...',
            textStyle: TextStyle(color: Color(0xFFFF2B2B))),
        footer: const ClassicFooter(
            noMoreText: '没有更多数据了',
            noMoreIcon: Icon(Icons.mood_rounded),
            showMessage: false,
            processingText: '正在加载中...',
            textStyle: TextStyle(color: Color(0xFF846FFD))),
        onRefresh: () async {
          setState(() {
            dataList = [];
            _page = 1;
          });
          initListData();
        },
        onLoad: () async {
          final resData = await _fetchListData(_page);

          setState(() {
            dataList = dataList..addAll(resData.data);
            _page = _page + 1;
          });

          _controller.finishLoad(resData.data.isEmpty
              ? IndicatorResult.noMore
              : IndicatorResult.success);
          // _fetchListData(_page);
        },
        child: ListView.builder(
          itemBuilder: (context, index) {
            return Card(
              child: Container(
                alignment: Alignment.center,
                height: 80,
                // ignore: unnecessary_string_interpolations
                child: Text('${dataList[index].firstName}'),
              ),
            );
          },
          itemCount: dataList.length,
        ),
      ),
    );
  }
}

class ApiResponse {
  final int page;
  final int perPage;
  final int total;
  final int totalPages;
  final List<UserData> data;
  final Support support;

  ApiResponse(
      {required this.page,
      required this.perPage,
      required this.total,
      required this.totalPages,
      required this.data,
      required this.support});

  factory ApiResponse.fromJson(Map<String, dynamic> json) {
    var list = json['data'] as List;
    List<UserData> dataList = list.map((i) => UserData.fromJson(i)).toList();

    return ApiResponse(
      page: json['page'],
      perPage: json['per_page'],
      total: json['total'],
      totalPages: json['total_pages'],
      data: dataList,
      support: Support.fromJson(json['support']),
    );
  }
}

class UserData {
  final int id;
  final String email;
  final String firstName;
  final String lastName;
  final String avatar;

  UserData(
      {required this.id,
      required this.email,
      required this.firstName,
      required this.lastName,
      required this.avatar});

  factory UserData.fromJson(Map<String, dynamic> json) {
    return UserData(
      id: json['id'],
      email: json['email'],
      firstName: json['first_name'],
      lastName: json['last_name'],
      avatar: json['avatar'],
    );
  }
}

class Support {
  final String url;
  final String text;

  Support({required this.url, required this.text});

  factory Support.fromJson(Map<String, dynamic> json) {
    return Support(
      url: json['url'],
      text: json['text'],
    );
  }
}
相关推荐
君蓦8 小时前
Flutter 本地存储与数据库的使用和优化
flutter
problc18 小时前
Flutter中文字体设置指南:打造个性化的应用体验
android·javascript·flutter
lqj_本人1 天前
鸿蒙next选择 Flutter 开发跨平台应用的原因
flutter·华为·harmonyos
lqj_本人1 天前
Flutter&鸿蒙next 状态管理框架对比分析
flutter·华为·harmonyos
起司锅仔1 天前
Flutter启动流程(2)
flutter
hello world smile2 天前
最全的Flutter中pubspec.yaml及其yaml 语法的使用说明
android·前端·javascript·flutter·dart·yaml·pubspec.yaml
lqj_本人2 天前
Flutter 的 Widget 概述与常用 Widgets 与鸿蒙 Next 的对比
flutter·harmonyos
iFlyCai2 天前
极简实现酷炫动效:Flutter隐式动画指南第二篇之一些酷炫的隐式动画效果
flutter
lqj_本人2 天前
Flutter&鸿蒙next 中使用 MobX 进行状态管理
flutter·华为·harmonyos