auth_state_manager 0.1.1
auth_state_manager: ^0.1.1 copied to clipboard
This package helps you to monitor auth statuses in your app.
Auth State Manager #
Auth state manager helps you to monitor auth changes in your app. This package is suitable if you use HTTP requests in your app and you require access-tokens for APIs. The package will save the access-token to shared preferences and returns it when you need.
Installation #
- Add the latest version of package to your pubspec.yaml (and run
dart pub get):
dependencies:
auth_state_manager: ^0.1.1
- Import the package in
main.dart
import 'package:auth_state_manager/auth_state_manager.dart';
- Initialize
AuthStateManager.- Make sure to add
asynctomain()function. - Make sure to initialize
FlutterBindingbyWidgetsFlutterBinding.ensureInitialized(); - Make sure
awaitAuthStateManagerinitialization.
- Make sure to add
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await AuthStateManager.initializeAuthState();
runApp(
const MaterialApp(
home: MyApp(),
),
);
}
Usage #
- Wrap your root widget with
AuthStateListenerand provide widgets for bothauthenticatedandunAuthenticatedstates. This will help you to control authentication flow of your app. If you did not authorize yetAuthStateListenerreturnsunAuthenticatedwidget, if you logged in before it returnsauthenticated.
@override
Widget build(BuildContext context) {
return const AuthStateListener(
authenticated: MainScreen(),
unAuthenticated: LoginScreen(),
);
}
- Save your access-token to
AuthStateby
await AuthStateManager.instance.setToken('MyToken');
setToken() is async so make sure to await it. Note that saving your token will not trigger Auth State Change. To change the Auth State you should use login() function.
final bool isSuccessful =
await AuthStateManager.instance.setToken('MyToken');
if (isSuccessful) {
AuthStateManager.instance.login();
}
- Delete access-token and signOut by
AuthStateManager.instance.logOut();
logOut() function will delete access-token and trigger Auth State Change.
- Listen to auth status changes by
late final StreamSubscription _authStateSub;
@override
void initState() {
super.initState();
_authStateSub = AuthStateManager.instance.authStateAsStream.listen((state) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('isAuthenticated: $state'),
),
);
});
}
@override
void dispose() {
super.dispose();
_authStateSub.cancel();
}
AuthStateManager.instance.authStateAsStream returns Stream<bool> which you can listen to.
Example #
Check out to github repository /example for more information.