Below is a minimal (but complete) example of how you can wrap your API call in a timeout, reset the logginIn flag, and show a SnackBar when the timeout (or any other error) occurs.
// Somewhere in your widget’s state
bool logginIn = false;
final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey =
GlobalKey<ScaffoldMessengerState>();
// -------------- NEW _tryLogin ---------------
void _tryLogin(String email, String password) async {
// 1. Turn the loader/spinner on.
setState(() => logginIn = true);
try {
// 2. Send the request, but cancel it if it takes > 10 s
final loginResponse = await loginController
.apiLoginRequest(email, password) // <-- your request
.timeout(const Duration(seconds: 10)); // <-- the timeout
// 3. Call your success handler
_loginResponseReceived(loginResponse);
} on TimeoutException catch (_) {
_handleFailure('Something went wrong. Please try again later.');
} catch (e) {
// Any other type of exception (network, parsing, etc.)
_handleFailure('Unexpected error: ${e.toString()}');
} finally {
// 4. Whether success or error, stop the loader
if (mounted) {
setState(() => logginIn = false);
}
}
}
void _handleFailure(String message) {
if (!mounted) return;
// Display a SnackBar (requires a ScaffoldMessenger)
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message)),
);
}
What changed & why:
setState(() => logginIn = true); – immediately shows the loader.
.timeout(const Duration(seconds: 10)) – Dart’s built-in way to abort a Future if it doesn’t finish in time.
• If the timeout is reached, a TimeoutException is thrown.
try / on TimeoutException / catch / finally – clean separation of success, timeout, and other errors.
- Reset
logginIn inside finally so the spinner always stops.
ScaffoldMessenger.of(context).showSnackBar – quick way to surface the “Something went wrong” message.
Hooking the ScaffoldMessenger (optional but recommended):
return MaterialApp(
scaffoldMessengerKey: _scaffoldMessengerKey,
home: MyLoginScreen(),
);
…but if you already have a Scaffold in the widget tree, ScaffoldMessenger.of(context) works out of the box.
That’s it—now your login call will timeout after 10 seconds, the UI will revert to its idle state, and the user will see a clear error message. 🚀