import 'package:flutter/material.dart'; import 'package:outbag_app/backend/errors.dart'; import 'package:outbag_app/backend/request.dart'; import 'package:outbag_app/backend/user.dart'; import 'package:outbag_app/tools/snackbar.dart'; void doNetworkRequest(ScaffoldMessengerState? sm, {required Future Function(User?) req, Function(Map)? onOK, bool Function()? onNetworkErr, bool Function()? onUnknownErr, bool Function()? onUserErr, Function()? after, bool Function(Map)? onServerErr, bool needUser = true}) async { User? user; try { user = await User.fromDisk(); } catch (_) { // no user data available if (needUser) { // show error & quit bool showBar = true; if (onUserErr != null) { showBar = onUserErr(); } if (showBar && sm != null) { showSimpleSnackbar(sm, text: 'No user found', action: 'Authorize', onTap: () { try { // try to remove broken user User.removeDisk(); } catch (_) {} }); } if (after != null) { after(); } return; } } Response res; try { res = await req(user); } catch (_) { // network error bool showBar = true; if (onNetworkErr != null) { showBar = onNetworkErr(); } if (showBar && sm != null) { showSimpleSnackbar(sm, text: 'Network Error', action: 'Dismiss'); } 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'); } } } catch (e) { bool showBar = true; print(e); if (onUnknownErr != null) { showBar = onUnknownErr(); } if (showBar && sm != null) { showSimpleSnackbar(sm, text: 'Unknown Error', action: 'OK'); } } if (after != null) { after(); } }