Flutter学习笔记(二)-列表上拉刷新&上拉获取更多

Flutter 是什么

  • https://www.jianshu.com/p/ad10724e6e30

Flutter上拉获取更多&下拉刷新实现

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_app/loading_dialog.dart';

class ListPageState extends StatefulWidget {
  @override
  State createState() {
    return _ListState();
  }
}

class _ListState extends State {
  ScrollController _scrollController = new ScrollController();
  bool _isRefresh = false;
  bool _isLoadingMore = false;
  String _prefix = "";

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      double pixels = _scrollController.position.pixels;
      double maxScrollExtent = _scrollController.position.maxScrollExtent;
      print("scroller $pixels");
      if (pixels == maxScrollExtent) {
        _loadMore();
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Offstage(
          child: Text("header"),
          offstage: true,
        ),
        Expanded(
          child: RefreshIndicator(
            child: ListView.builder(
              itemBuilder: _itemBuilder,
              itemCount: 20,
              controller: _scrollController,
              physics: _isLoadingMore || _isRefresh
                  ? NeverScrollableScrollPhysics()
                  : ClampingScrollPhysics(),
            ),
            onRefresh: _onRefresh,
            displacement: 40.0,
          ),
        ),
        Offstage(
          child: getLoadMoreWidget(),
          offstage: !_isLoadingMore,
        ),
      ],
    );
  }

  Widget getLoadMoreWidget() {
    return Center(
      child: Text("loading more ...", style: TextStyle(fontSize: 20.0)),
      heightFactor: 2.0,
    );
  }

  Widget _itemBuilder(BuildContext context, int index) {
    return ListTile(
      title: Text(
        "Item: $index $_prefix",
      ),
    );
  }

  Future _loadMore() async {
    print("loadMore");
    setState(() {
      _isLoadingMore = true;
    });
    showDialog(
        context: context, //BuildContext对象
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new LoadingDialog(
            //调用对话框
            text: '正在获取详情...',
          );
        });
    await Future.delayed(Duration(seconds: 10), () {
      setState(() {
        print("loadMore done");
        _isLoadingMore = false;
        Navigator.pop(context);
      });
    });
  }

  Future _onRefresh() async {
    setState(() {
      _isRefresh = true;
    });
    await Future.delayed(Duration(seconds: 10), () {
      setState(() {
        Random _random = new Random();
        double next = _random.nextDouble();
        _prefix = "$next";
        setState(() {
          _isRefresh = false;
        });
      });
    });
  }
}

你可能感兴趣的:(Flutter学习笔记(二)-列表上拉刷新&上拉获取更多)