Auth with refresh token in Flutter: solved exercise
Auth with refresh token in Flutter: solved exercise
Implement login, token storage, and automatic refresh in Flutter.
Problem statement
Simulate token expiration and transparent refresh for the user.
Flutter solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
| import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: ExercisePage()));
}
class ExercisePage extends StatefulWidget {
const ExercisePage({super.key});
@override
State<ExercisePage> createState() => _ExercisePageState();
}
class _ExercisePageState extends State<ExercisePage> {
bool loading = false;
String message = 'Initial state';
Future<void> runExercise() async {
setState(() {
loading = true;
message = 'Processing...';
});
await Future<void>.delayed(const Duration(milliseconds: 700));
if (!mounted) return;
setState(() {
loading = false;
message = 'Exercise completed';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Flutter solved exercise')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(message),
const SizedBox(height: 12),
ElevatedButton(
onPressed: loading ? null : runExercise,
child: Text(loading ? 'Loading...' : 'Run'),
),
],
),
),
);
}
}
|
Expected result
A working minimal screen to practice: auth, refresh token, session.
Common mistakes
- Not separating loading, success, and error states.
- Coupling UI and data in a single class.
- Skipping state validation before navigation or rendering.
Practical use
This pattern appears in real apps to improve robustness, maintainability, and UX.
Recommended next exercise
Guided practice and next step
FAQ
What do you practice in this exercise?
You practice auth, refresh token, session with a practical production-oriented scenario.
Is this exercise useful for a portfolio?
Yes. You can adapt it and present a clear implementation with technical rationale.
What should I do next?
Connect it to a real API or local persistence depending on your product goal.