Skip to content

Instantly share code, notes, and snippets.

@threetwotwo
Last active April 4, 2020 09:25
Show Gist options
  • Save threetwotwo/5132e1b88e010bce38247c84e95ea27d to your computer and use it in GitHub Desktop.
Save threetwotwo/5132e1b88e010bce38247c84e95ea27d to your computer and use it in GitHub Desktop.
Refresh List View
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:agora/ui/shared/loading_indicator.dart';
class RefreshListView extends StatefulWidget {
final ScrollController controller;
final VoidCallback onRefresh;
final VoidCallback onLoadMore;
final Widget child;
final ScrollPhysics physics;
const RefreshListView(
{Key key,
this.controller,
this.onRefresh,
this.child,
this.onLoadMore,
this.physics})
: super(key: key);
@override
_RefreshListViewState createState() => _RefreshListViewState();
}
class _RefreshListViewState extends State<RefreshListView> {
bool isLoadingMore = false;
ScrollController _controller;
_loadMore() async {
if (widget.onLoadMore == null) return;
if (mounted)
setState(() {
isLoadingMore = true;
});
if (widget.onLoadMore != null) {
await widget.onLoadMore();
isLoadingMore = false;
if (mounted) setState(() {});
}
return;
}
@override
void initState() {
_controller = widget.controller ?? ScrollController();
_controller.addListener(() {
if (widget.onLoadMore == null) return;
if (!isLoadingMore &&
_controller.position.pixels >= _controller.position.maxScrollExtent) {
print('load more');
_loadMore();
if (mounted) setState(() {});
///Time out after 15 sec
Future.delayed(Duration(seconds: 15))
..whenComplete(() {
isLoadingMore = false;
if (mounted) setState(() {});
});
}
});
super.initState();
}
@override
Widget build(BuildContext context) {
return CustomScrollView(
controller: _controller,
physics: widget.physics ?? Platform.isAndroid
? BouncingScrollPhysics()
: AlwaysScrollableScrollPhysics(),
slivers: <Widget>[
CupertinoSliverRefreshControl(
refreshIndicatorExtent: 80,
refreshTriggerPullDistance: 120,
onRefresh: widget.onRefresh,
builder: (context, mode, _, __, ___) => LoadingIndicator(),
),
SliverToBoxAdapter(child: widget.child),
if (isLoadingMore)
SliverToBoxAdapter(
child: LoadingIndicator(),
)
],
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment