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>({
|
2021-04-09 00:11:44 +02:00
|
|
|
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 {
|
2021-04-09 00:11:44 +02:00
|
|
|
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);
|
2021-04-09 00:11:44 +02:00
|
|
|
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())));
|
2021-04-09 00:11:44 +02:00
|
|
|
} finally {
|
|
|
|
cleanup?.call(val);
|
|
|
|
delayedLoading.cancel();
|
2021-02-24 20:52:18 +01:00
|
|
|
}
|
|
|
|
}
|