lemmur-app-android/lib/util/delayed_action.dart

29 lines
813 B
Dart
Raw Normal View History

2021-02-24 20:52:18 +01:00
import 'package:flutter/material.dart';
2021-04-05 20:14:39 +02:00
import 'package:lemmy_api_client/v3.dart';
2021-02-24 20:52:18 +01:00
import '../hooks/delayed_loading.dart';
/// Executes an API action that uses [DelayedLoading], has a try-catch
2021-03-10 08:34:30 +01:00
/// that displays a [SnackBar] when the action fails
2021-02-24 20:52:18 +01:00
Future<void> delayedAction<T>({
required BuildContext context,
required DelayedLoading delayedLoading,
required String instanceHost,
required LemmyApiQuery<T> query,
void Function(T)? onSuccess,
void Function(T?)? cleanup,
2021-02-24 20:52:18 +01:00
}) async {
T? val;
2021-02-24 20:52:18 +01:00
try {
delayedLoading.start();
2021-04-05 20:14:39 +02:00
val = await LemmyApiV3(instanceHost).run<T>(query);
onSuccess?.call(val as T);
2021-02-24 20:52:18 +01:00
} catch (e) {
2021-03-10 08:34:30 +01:00
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(e.toString())));
} finally {
cleanup?.call(val);
delayedLoading.cancel();
2021-02-24 20:52:18 +01:00
}
}