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

90 lines
2.0 KiB
Dart
Raw Normal View History

2019-09-25 11:06:36 +02:00
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:git_touch/scaffolds/utils.dart';
2019-09-30 11:13:12 +02:00
class RefreshStatefulScaffoldPayload<T> {
bool loading;
String error;
T data;
void Function() refresh;
RefreshStatefulScaffoldPayload(
this.loading, this.error, this.data, this.refresh);
}
2019-09-25 11:06:36 +02:00
class RefreshStatefulScaffold<T> extends StatefulWidget {
final Widget title;
2019-09-30 11:13:12 +02:00
final Widget Function(RefreshStatefulScaffoldPayload<T> payload) bodyBuilder;
final Future<T> Function() fetchData;
final Widget Function(RefreshStatefulScaffoldPayload<T> payload)
actionBuilder;
2019-09-25 11:06:36 +02:00
RefreshStatefulScaffold({
@required this.title,
@required this.bodyBuilder,
2019-09-30 11:13:12 +02:00
@required this.fetchData,
this.actionBuilder,
2019-09-25 11:06:36 +02:00
});
@override
_RefreshStatefulScaffoldState createState() =>
_RefreshStatefulScaffoldState();
}
class _RefreshStatefulScaffoldState<T>
extends State<RefreshStatefulScaffold<T>> {
bool _loading;
2019-09-30 11:13:12 +02:00
T _data;
2019-09-25 11:06:36 +02:00
String _error = '';
2019-09-30 11:13:12 +02:00
RefreshStatefulScaffoldPayload get _payload =>
RefreshStatefulScaffoldPayload(_loading, _error, _data, _refresh);
2019-09-25 11:06:36 +02:00
@override
void initState() {
super.initState();
_refresh();
}
Future<void> _refresh() async {
try {
setState(() {
_error = '';
_loading = true;
});
2019-09-30 11:13:12 +02:00
_data = await widget.fetchData();
2019-09-25 11:06:36 +02:00
} catch (err) {
_error = err.toString();
throw err;
} finally {
if (mounted) {
setState(() {
_loading = false;
});
}
}
}
Widget get _trailing {
2019-09-30 11:13:12 +02:00
if (widget.actionBuilder == null) return null;
return widget.actionBuilder(_payload);
2019-09-25 11:06:36 +02:00
}
@override
Widget build(BuildContext context) {
return CommonScaffold(
title: widget.title,
2019-09-25 12:47:34 +02:00
body: RefreshWrapper(
onRefresh: _refresh,
body: ErrorLoadingWrapper(
bodyBuilder: () => widget.bodyBuilder(_payload),
error: _error,
2019-09-30 11:13:12 +02:00
loading: _data == null,
2019-09-25 12:47:34 +02:00
reload: _refresh,
),
),
2019-09-25 11:06:36 +02:00
trailing: _trailing,
);
}
}