ExampleAuth
Flutter Auth Flow
A complete authentication flow covering app startup session check, login, registration, and logout using Koolbase Auth.
main.dart — startup session check
Check for an existing session on launch and route accordingly. Also handle version enforcement before showing the app.
lib/main.dart
Dart
import 'package:flutter/material.dart';
import 'package:koolbase_flutter/koolbase_flutter.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Also restores a saved sign-in, if there is one
await Koolbase.initialize(const KoolbaseConfig(
publicKey: 'pk_live_your_key_here',
baseUrl: 'https://api.koolbase.com',
));
// Check version enforcement first
final versionCheck = Koolbase.checkVersion();
if (versionCheck.status == VersionStatus.forceUpdate) {
runApp(ForceUpdateApp(message: versionCheck.message));
return;
}
final user = Koolbase.auth.currentUser;
runApp(MyApp(initialRoute: user != null ? '/home' : '/login'));
}
class MyApp extends StatelessWidget {
final String initialRoute;
const MyApp({required this.initialRoute, super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: initialRoute,
routes: {
'/login': (_) => const LoginScreen(),
'/register': (_) => const RegisterScreen(),
'/home': (_) => const HomeScreen(),
},
);
}
}login_screen.dart
lib/screens/login_screen.dart
Dart
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final _emailCtrl = TextEditingController();
final _passwordCtrl = TextEditingController();
bool _loading = false;
String? _error;
Future<void> _login() async {
setState(() { _loading = true; _error = null; });
try {
await Koolbase.auth.login(
email: _emailCtrl.text.trim(),
password: _passwordCtrl.text,
);
if (mounted) Navigator.pushReplacementNamed(context, '/home');
} on InvalidCredentialsException {
setState(() => _error = 'Invalid email or password.');
} on ContactNotVerifiedException {
setState(() => _error = 'Please verify your email first.');
} on KoolbaseAuthException {
setState(() => _error = 'Login failed. Please try again.');
} finally {
setState(() => _loading = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(controller: _emailCtrl, decoration: const InputDecoration(labelText: 'Email')),
const SizedBox(height: 12),
TextField(controller: _passwordCtrl, obscureText: true, decoration: const InputDecoration(labelText: 'Password')),
if (_error != null) ...[
const SizedBox(height: 12),
Text(_error!, style: const TextStyle(color: Colors.red)),
],
const SizedBox(height: 24),
ElevatedButton(
onPressed: _loading ? null : _login,
child: _loading ? const CircularProgressIndicator() : const Text('Login'),
),
TextButton(
onPressed: () => Navigator.pushNamed(context, '/register'),
child: const Text('Create account'),
),
],
),
),
);
}
}register_screen.dart
lib/screens/register_screen.dart
Dart
Future<void> _register() async {
setState(() { _loading = true; _error = null; });
try {
// Koolbase emails the verification link by itself
final result = await Koolbase.auth.signUp(
email: _emailCtrl.text.trim(),
password: _passwordCtrl.text,
);
if (!result.verificationRequired) {
// This project lets people in before they verify
if (mounted) Navigator.pushReplacementNamed(context, '/home');
return;
}
if (mounted) {
showDialog(
context: context,
builder: (_) => AlertDialog(
title: const Text('Verify your email'),
content: const Text('We sent a verification link to your email. Click it to activate your account.'),
actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))],
),
);
}
} on WeakPasswordException {
setState(() => _error = 'Use at least 8 characters.');
} on KoolbaseAuthException {
// Koolbase never says an email is already taken: that would tell
// strangers who has an account. The owner gets an email instead.
setState(() => _error = 'Registration failed. Please try again.');
} finally {
setState(() => _loading = false);
}
}Logout
lib/screens/home_screen.dart
Dart
Future<void> _logout() async {
await Koolbase.auth.logout();
if (mounted) Navigator.pushReplacementNamed(context, '/login');
}Session persistence
The session token is stored securely on device. On the next app launch,
Koolbase.initialize restores it and Koolbase.auth.currentUser returns the user — no login screen required until the session expires (30 days).