Uday Singh
11/26/2025, 5:25 AMRahul Rijhwani
11/26/2025, 5:40 AMUday Singh
11/26/2025, 5:56 AMRahul Rijhwani
11/26/2025, 6:35 AMimport 'package:descope/descope.dart';
import 'package:flutter/foundation.dart';
class SessionNotifier extends ChangeNotifier {
DescopeSession? _session;
DescopeSession? get session => _session;
void setSession(DescopeSession? newSession) {
final oldToken = _session?.sessionJwt;
final newToken = newSession?.sessionJwt;
_session = newSession;
// 🔑 Only fire when token actually changes
if (oldToken != newToken) {
notifyListeners();
}
}
}
Make this a singleton or provide it via Provider/Riverpod/whatever DI you use.
2. Use it whenever you log in / refresh
After Descope login / verify:
final authResponse = await Descope.otp.verify(
method: DeliveryMethod.email,
loginId: 'user@example.com',
code: code,
);
final session = DescopeSession.fromAuthenticationResponse(authResponse);
Descope.sessionManager.manageSession(session);
// Update your notifier (this will trigger callback if token changed)
sessionNotifier.setSession(Descope.sessionManager.session);
When refreshing session:
await Descope.sessionManager.refreshSessionIfNeeded();
sessionNotifier.setSession(Descope.sessionManager.session);
Rule: never change session directly without passing through sessionNotifier.setSession.
3. Add your “callback” listener
Wherever you want the callback (similar to useEffect):
late final SessionNotifier sessionNotifier;
@override
void initState() {
super.initState();
sessionNotifier = yourGlobalSessionNotifier; // however you access it
sessionNotifier.addListener(() {
final token = sessionNotifier.session?.sessionJwt;
// ✅ This is your callback: token just updated
print('Session token updated: $token');
// Put your side-effect here (send to backend, save, etc.)
});
}
@override
void dispose() {
sessionNotifier.removeListener(() {});
super.dispose();
}
4. Use the current token for API calls
When you make API calls:
final token = sessionNotifier.session?.sessionJwt;
// use it in Authorization header etc.
Every time Descope updates the session (login or refresh), you call sessionNotifier.setSession(...) → it detects token change → addListener fires → you get your “session token updated” callback. This is the Flutter equivalent of useEffect([sessionToken]).Uday Singh
11/26/2025, 6:38 AMRahul Rijhwani
11/26/2025, 6:39 AM