git-touch-android-ios-app/lib/scaffolds/refresh.dart

101 lines
2.4 KiB
Dart
Raw Normal View History

2019-02-03 08:50:17 +01:00
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/widgets.dart';
import '../providers/settings.dart';
import '../widgets/loading.dart';
import '../widgets/error_reload.dart';
import '../utils/utils.dart';
2019-02-03 08:50:17 +01:00
// This is a scaffold for pull to refresh
class RefreshScaffold<T> extends StatefulWidget {
final Widget title;
final Widget Function(T payload) bodyBuilder;
final Future<T> Function() onRefresh;
2019-02-06 14:35:52 +01:00
final Widget trailing;
final List<Widget> actions;
2019-02-07 13:28:48 +01:00
final PreferredSizeWidget bottom;
2019-02-03 08:50:17 +01:00
RefreshScaffold({
@required this.title,
@required this.bodyBuilder,
2019-02-03 08:50:17 +01:00
@required this.onRefresh,
2019-02-06 14:35:52 +01:00
this.trailing,
this.actions,
2019-02-07 13:28:48 +01:00
this.bottom,
2019-02-03 08:50:17 +01:00
});
@override
_RefreshScaffoldState createState() => _RefreshScaffoldState();
}
class _RefreshScaffoldState<T> extends State<RefreshScaffold<T>> {
bool loading;
T payload;
String error = '';
@override
void initState() {
super.initState();
_refresh();
}
2019-02-06 14:35:52 +01:00
Widget _buildBody() {
if (error.isNotEmpty) {
return ErrorReload(text: error, reload: _refresh);
} else if (loading) {
2019-02-06 14:35:52 +01:00
return Loading(more: true);
2019-02-03 08:50:17 +01:00
} else {
return widget.bodyBuilder(payload);
}
}
Future<void> _refresh() async {
try {
setState(() {
error = '';
loading = true;
});
payload = await widget.onRefresh();
} catch (err) {
error = err.toString();
} finally {
if (mounted) {
setState(() {
loading = false;
});
}
2019-02-03 08:50:17 +01:00
}
}
@override
Widget build(BuildContext context) {
2019-02-07 07:35:19 +01:00
switch (SettingsProvider.of(context).theme) {
case ThemeMap.cupertino:
2019-02-03 08:50:17 +01:00
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: widget.title, trailing: widget.trailing),
2019-02-03 08:50:17 +01:00
child: SafeArea(
child: CustomScrollView(
slivers: <Widget>[
CupertinoSliverRefreshControl(onRefresh: _refresh),
2019-02-06 14:35:52 +01:00
SliverToBoxAdapter(child: _buildBody())
2019-02-03 08:50:17 +01:00
],
),
),
);
default:
return Scaffold(
appBar: AppBar(
title: widget.title,
actions: widget.actions,
bottom: widget.bottom,
),
body: RefreshIndicator(
onRefresh: _refresh,
child: SingleChildScrollView(child: _buildBody()),
2019-02-03 08:50:17 +01:00
),
);
}
}
}