Flutter开发之ListView使用第三方flutter_refresh加载更多(37)

在Flutter开发之ListView使用第三方pull_to_refresh加载更多(36) 中我们实现了下拉刷新、上拉分页加载的功能。今天介绍另一个ListView使用第三方flutter_refresh 来实现下拉刷新、上拉分页加载。

添加 flutter_refresh 依赖

官方文档:https://pub.flutter-io.cn/packages/flutter_refresh#-installing-tab-
我们可以通过pubspec.yaml文件引入最新版本

dependencies:
  pull_to_refresh: ^1.5.0

导入

import 'package:pull_to_refresh/pull_to_refresh.dart';

使用示例

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'dart:async';
import 'package:flutter_refresh/flutter_refresh.dart';


class ListViewFlutterRefresh extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text('flutter_refresh'),
        ),
        body: new MyFlutterRefreshPage(title: 'Pull to refresh'),
    );
  }
}

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

  @override
  _MyFlutterRefreshPageState createState() => new _MyFlutterRefreshPageState();
}

class _MyFlutterRefreshPageState extends State with TickerProviderStateMixin {

  Widget _itemBuilder(BuildContext context, int index) {
    return new Padding(
      key: new Key(index.toString()),
      padding: new EdgeInsets.all(10.0),
      child: Text(
        "顺序数据:$index",
        style: TextStyle(fontSize: 14.0),
      ),
    );
  }

  int _itemCount;

  @override
  void initState() {
    _itemCount = 10;
    super.initState();
  }

  Future onFooterRefresh() {
    return new Future.delayed(new Duration(seconds: 2), () {
      setState(() {
        _itemCount += 10;
      });
    });
  }

  Future onHeaderRefresh() {
    return new Future.delayed(new Duration(seconds: 2), () {
      setState(() {
        _itemCount = 10;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        body: SafeArea(
            child: Refresh(
              onFooterRefresh: onFooterRefresh,
              onHeaderRefresh: onHeaderRefresh,
              childBuilder: (BuildContext context,
                  {ScrollController controller, ScrollPhysics physics})
              {
                return Container(
                    child: ListView.builder(
                      physics: physics,
                      controller: controller,
                      itemBuilder: _itemBuilder,
                      itemCount: _itemCount,
                    ));
              },
            )
        )
    );
  }
}

效果图下:

Flutter开发之ListView使用第三方flutter_refresh加载更多(37)_第1张图片

综述:这个效果比较符合通用的样式。并且使用也很简单。推荐使用。

翻译来源:

https://pub.flutter-io.cn/packages/flutter_refresh#-readme-tab-

你可能感兴趣的:(Flutter开发教程)