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'; void doNetworkRequest(ScaffoldMessengerState? sm, {required Future Function() req, Function(Map body)? onOK, bool Function()? onNetworkErr, bool Function()? onUnknownErr, Function()? onAnyErr, Function()? after, bool Function(Map)? onServerErr}) async { Response res; try { res = await req(); } catch (_) { // network error bool showBar = true; if (onNetworkErr != null) { showBar = onNetworkErr(); } if (showBar && sm != null) { showSimpleSnackbar(sm, text: 'Network Error', action: 'Dismiss'); } if (onAnyErr != null) { onAnyErr(); } 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) { showSimpleSnackbar(sm, text: errorAsString(res.body), action: 'OK'); } if (onAnyErr != null) { onAnyErr(); } } } catch (_) { bool showBar = true; if (onUnknownErr != null) { showBar = onUnknownErr(); } if (showBar && sm != null) { showSimpleSnackbar(sm, text: 'Unknown Error', action: 'OK'); } } if (after != null) { after(); } }