2023-03-23 14:48:53 +01:00
|
|
|
import 'package:flutter/material.dart';
|
|
|
|
import 'package:outbag_app/backend/errors.dart';
|
|
|
|
import 'package:outbag_app/backend/request.dart';
|
|
|
|
import 'package:outbag_app/tools/snackbar.dart';
|
2023-03-29 15:14:27 +02:00
|
|
|
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
|
2023-03-23 14:48:53 +01:00
|
|
|
|
|
|
|
void doNetworkRequest(ScaffoldMessengerState? sm,
|
2023-03-25 17:18:46 +01:00
|
|
|
{required Future<Response> Function() req,
|
|
|
|
Function(Map<String, dynamic> body)? onOK,
|
2023-03-23 14:48:53 +01:00
|
|
|
bool Function()? onNetworkErr,
|
|
|
|
bool Function()? onUnknownErr,
|
2023-03-24 21:10:42 +01:00
|
|
|
Function()? onAnyErr,
|
2023-03-23 14:48:53 +01:00
|
|
|
Function()? after,
|
2023-03-25 17:18:46 +01:00
|
|
|
bool Function(Map<String, dynamic>)? onServerErr}) async {
|
2023-03-29 15:14:27 +02:00
|
|
|
AppLocalizations? trans = (sm!=null)?AppLocalizations.of(sm.context):null;
|
|
|
|
|
2023-03-23 14:48:53 +01:00
|
|
|
Response res;
|
|
|
|
try {
|
2023-03-25 17:18:46 +01:00
|
|
|
res = await req();
|
2023-03-23 14:48:53 +01:00
|
|
|
} catch (_) {
|
|
|
|
// network error
|
|
|
|
bool showBar = true;
|
|
|
|
|
|
|
|
if (onNetworkErr != null) {
|
|
|
|
showBar = onNetworkErr();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (showBar && sm != null) {
|
2023-03-29 15:14:27 +02:00
|
|
|
showSimpleSnackbar(sm, text: trans!.errorNetwork, action: trans.dismiss);
|
2023-03-23 14:48:53 +01:00
|
|
|
}
|
2023-03-24 21:10:42 +01:00
|
|
|
if (onAnyErr != null) {
|
|
|
|
onAnyErr();
|
|
|
|
}
|
2023-03-23 14:48:53 +01:00
|
|
|
if (after != null) {
|
|
|
|
after();
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
if (res.res == Result.ok) {
|
|
|
|
if (onOK != null) {
|
|
|
|
await onOK(res.body);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// server error
|
|
|
|
bool showBar = true;
|
|
|
|
|
|
|
|
if (onServerErr != null) {
|
|
|
|
showBar = onServerErr(res.body);
|
|
|
|
}
|
|
|
|
if (showBar && sm != null) {
|
2023-03-29 15:14:27 +02:00
|
|
|
showSimpleSnackbar(sm, text: errorAsString(res.body, trans!), action: trans.ok);
|
2023-03-23 14:48:53 +01:00
|
|
|
}
|
2023-03-24 21:10:42 +01:00
|
|
|
if (onAnyErr != null) {
|
|
|
|
onAnyErr();
|
|
|
|
}
|
2023-03-23 14:48:53 +01:00
|
|
|
}
|
2023-03-24 21:10:42 +01:00
|
|
|
} catch (_) {
|
2023-03-23 14:48:53 +01:00
|
|
|
bool showBar = true;
|
|
|
|
|
|
|
|
if (onUnknownErr != null) {
|
|
|
|
showBar = onUnknownErr();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (showBar && sm != null) {
|
2023-03-29 15:14:27 +02:00
|
|
|
showSimpleSnackbar(sm, text: trans!.errorUnknown, action: trans.ok);
|
2023-03-23 14:48:53 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (after != null) {
|
|
|
|
after();
|
|
|
|
}
|
|
|
|
}
|