lemmur-app-android/lib/hooks/delayed_loading.dart

45 lines
1.1 KiB
Dart
Raw Normal View History

2020-09-16 01:27:49 +02:00
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'ref.dart';
class DelayedLoading {
final bool pending;
final bool loading;
final void Function() start;
final void Function() cancel;
const DelayedLoading({
@required this.pending,
@required this.loading,
@required this.start,
@required this.cancel,
});
}
/// When loading is [.start()]ed, it goes into a pending state
/// and loading is triggered after [delayDuration].
/// Everything can be reset with [.cancel()]
2020-09-19 12:27:57 +02:00
DelayedLoading useDelayedLoading(
[Duration delayDuration = const Duration(milliseconds: 500)]) {
2020-09-16 23:22:04 +02:00
final loading = useState(false);
final pending = useState(false);
final timerHandle = useRef<Timer>(null);
2020-09-16 01:27:49 +02:00
return DelayedLoading(
loading: loading.value,
pending: pending.value,
start: () {
timerHandle.current = Timer(delayDuration, () => loading.value = true);
pending.value = true;
},
cancel: () {
timerHandle.current?.cancel();
pending.value = false;
loading.value = false;
},
);
}