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'],
    );
  }
}
相关推荐
jcLee9516 小时前
Flutter/Dart:使用日志模块Logger Easier
flutter·log4j·dart·logger
tmacfrank16 小时前
Flutter 异步编程简述
flutter
tmacfrank17 小时前
Flutter 基础知识总结
flutter
叫我菜菜就好18 小时前
【Flutter_Web】Flutter编译Web第三篇(网络请求篇):dio如何改造方法,变成web之后数据如何处理
前端·网络·flutter
AiFlutter1 天前
Flutter-底部分享弹窗(showModalBottomSheet)
java·前端·flutter
m0_748247802 天前
Flutter Intl包使用指南:实现国际化和本地化
前端·javascript·flutter
迷雾漫步者2 天前
Flutter组件————PageView
flutter·跨平台·dart
迷雾漫步者2 天前
Flutter组件————FloatingActionButton
前端·flutter·dart
coder_pig3 天前
📝小记:Ubuntu 部署 Jenkins 打包 Flutter APK
flutter·ubuntu·jenkins
捡芝麻丢西瓜3 天前
flutter自学笔记5- dart 编码规范
flutter·dart