Overview
CloudBase Flutter SDK enables you to use CloudBase capabilities in Flutter applications, including authentication, data models, MySQL database, cloud functions, cloud hosting, APIs, and more. For usage, please refer to CloudBase Flutter SDK, or check the sample code.
CloudBase Flutter SDK is fully aligned with HTTP API
SDK is categorized by functionality:
- Authentication: API methods for user registration and login, supporting multiple login methods.
- Session Management: API methods for managing user session state and tokens.
- User Management: API methods for retrieving, updating, and managing user information.
- Identity Source Management: API methods for managing third-party identity source binding and unbinding.
- Password Management: API methods for password reset and change.
- Verification Management: API methods for verification code sending, verification, resending, CAPTCHA creation, verification, and management.
- Data Model: Data model CRUD operations.
- Data Source Query: Query data source aggregation list, details, Schema, and table names.
- MySQL Database: MySQL RESTful database operations.
- Cloud Functions: Call cloud functions and function-type cloud hosting.
- Cloud Hosting: Call cloud hosting container services.
- APIs: Call APIs interfaces.
- Cloud Storage: File upload, download, delete, copy, move, and other operations.
Basic Usage Example
- Initialization
- Login Status Check
- User Registration Flow
- Password Login
- Logout
- Listen for State Changes
- Call Cloud Function
accessKey can be generated in CloudBase Platform/API Key Configuration
import 'package:cloudbase_flutter/cloudbase_flutter.dart';
// Initialize (async)
final app = await CloudBase.init(
env: 'your-env-id', // Replace with your environment ID
region: 'ap-shanghai', // Region, default is Shanghai
accessKey: 'your-key', // Fill in the generated Publishable Key
authConfig: AuthConfig(
detectSessionInUrl: true, // Optional: automatically detect OAuth parameters in URL
),
);
final auth = app.auth;
// Check login status
Future<bool> checkAuthStatus() async {
final result = await auth.getSession();
if (result.error != null) {
print('Failed to check login status: ${result.error!.message}');
return false;
}
if (result.data?.session != null) {
print('User is logged in: ${result.data!.user?.id}');
return true;
} else {
print('User is not logged in');
return false;
}
}
// User registration example (two-step verification flow)
Future<void> registerUser(String email, String password) async {
// Step 1: Send verification code
final signUpResult = await auth.signUp(SignUpReq(
email: email,
password: password,
));
if (signUpResult.error != null) {
print('Failed to send verification code: ${signUpResult.error!.message}');
return;
}
print('Verification code sent, waiting for user input...');
// Step 2: Verify verification code and complete registration
final verifyResult = await signUpResult.data!.verifyOtp!(
VerifyOtpParams(token: 'User input verification code'),
);
if (verifyResult.error != null) {
print('Registration failed: ${verifyResult.error!.message}');
} else {
print('Registration successful: ${verifyResult.data?.user?.id}');
}
}
// Password login example
Future<void> loginWithPassword(String email, String password) async {
final result = await auth.signInWithPassword(
SignInWithPasswordReq(email: email, password: password),
);
if (result.error != null) {
print('Login failed: ${result.error!.message}');
} else {
print('Login successful: ${result.data?.user?.id}');
print('Access Token: ${result.data?.session?.accessToken}');
}
}
// Logout example
Future<void> logout() async {
await auth.signOut();
print('Logged out');
}
// Listen for authentication state changes
final result = auth.onAuthStateChange((event, session, info) {
switch (event) {
case AuthStateChangeEvent.signedIn:
print('User signed in');
break;
case AuthStateChangeEvent.signedOut:
print('User signed out');
break;
case AuthStateChangeEvent.tokenRefreshed:
print('Token refreshed');
break;
case AuthStateChangeEvent.userUpdated:
print('User info updated');
break;
default:
break;
}
});
// Unsubscribe
result.data?.subscription.unsubscribe();
// Call cloud function example
final result = await app.callFunction(
name: 'myFunction',
data: {'key': 'value'},
);
if (result.isSuccess) {
print('Execution result: ${result.result}');
} else {
print('Execution failed: ${result.message}');
}
Authentication
signUp
Future<SignUpRes> auth.signUp(SignUpReq params)
Register a new user account using smart registration and login flow.
- Creates a new user account
- Uses smart registration and login flow: send verification code → wait for user input → smart judgment of user existence → auto login or register and login
- If user already exists, directly login; if user does not exist, register new user and auto login
参数
返回
示例
signInAnonymously
Future<SignInRes> auth.signInAnonymously({String? providerToken})
Anonymous login, creates a temporary anonymous user account.
- Creates a temporary anonymous user account
- No identity verification info needed
- Suitable for scenarios requiring temporary access
参数
Third-party platform token, used to associate third-party platform identity
返回
示例
signInWithPassword
Future<SignInRes> auth.signInWithPassword(SignInWithPasswordReq params)
Login with password. Supports login via username, email, or phone number.
参数
返回
示例
signInWithOtp
Future<SignInWithOtpRes> auth.signInWithOtp(SignInWithOtpReq params)
Login with OTP (one-time verification code). After calling, a verification code will be sent. You need to complete verification through the returned verifyOtp callback.
- If the user does not exist, a user will be created by default. You can control whether to automatically create a user with the
shouldCreateUserparameter (default is true)
参数
返回
示例
signInWithOAuth
Future<SignInOAuthRes> auth.signInWithOAuth(SignInWithOAuthReq params)
Login with OAuth third-party platform. Returns authorization URL, you need to guide the user to redirect to this URL to complete authorization.
参数
返回
示例
signInWithIdToken
Future<SignInRes> auth.signInWithIdToken(SignInWithIdTokenReq params)
Login with IdToken. Suitable for scenarios where third-party platform tokens have been obtained.
参数
返回
示例
signInWithCustomTicket
Future<SignInRes> auth.signInWithCustomTicket(Future<String> Function() getTicketFn)
Login with custom ticket. By passing an async function to get the ticket, the server generates the ticket and completes the login.
参数
Async function to get custom login ticket
返回
示例
Session Management
getSession
Future<SignInRes> auth.getSession();
Get current session. If token has expired, it will be automatically refreshed.
参数
无参数
返回
示例
refreshSession
Future<SignInRes> auth.refreshSession([String? refreshToken])
Refresh session. Use Refresh Token to get a new Access Token.
参数
Refresh token (optional, defaults to current session's refreshToken)
返回
示例
setSession
Future<SignInRes> auth.setSession(SetSessionReq params)
Set session. Restore session state with Refresh Token.
参数
返回
示例
signOut
Future<SignOutRes> auth.signOut([SignOutReq? params])
Logout. Clear local session and notify server to revoke token.
参数
Logout configuration options (optional)
返回
示例
onAuthStateChange
OnAuthStateChangeResult auth.onAuthStateChange(OnAuthStateChangeCallback callback)
Listen for authentication state changes. Supports listening for login, logout, token refresh, and user update events.
参数
State change callback function
返回
示例
getClaims
Future<GetClaimsRes> auth.getClaims();
Get JWT Claims of current Access Token (token claims).
参数
无参数
返回
示例
User Management
getUser
Future<GetUserRes> auth.getUser();
Get current logged-in user info.
参数
无参数
返回
示例
refreshUser
Future<SignInRes> auth.refreshUser();
Refresh user info. Re-fetch the latest user data from server and update local session.
参数
无参数
返回
示例
updateUser
Future<UpdateUserRes> auth.updateUser(UpdateUserReq params)
Update user info. If updating email or phone number, verification code verification is required.
参数
返回
示例
deleteUser
Future<CloudBaseResponse<void>> auth.deleteUser(DeleteUserReq params)
Delete current user. Password is required for security verification.
参数
返回
示例
Identity Source Management
getUserIdentities
Future<GetUserIdentitiesRes> auth.getUserIdentities();
Get the list of identity sources bound to the current user.
参数
无参数
返回
示例
linkIdentity
Future<LinkIdentityRes> auth.linkIdentity(LinkIdentityReq params)
Bind third-party identity source. Will redirect to third-party authorization page to complete binding.
参数
返回
示例
unlinkIdentity
Future<CloudBaseResponse<void>> auth.unlinkIdentity(UnlinkIdentityReq params)
Unbind third-party identity source.
参数
返回
示例
Password Management
resetPasswordForEmail
Future<ResetPasswordForEmailRes> auth.resetPasswordForEmail(String emailOrPhone, {String? redirectTo})
Reset password via email or phone number. After calling, a verification code will be sent. You need to complete password reset through the returned updateUser callback.
参数
Email or phone number
Redirect URL
返回
示例
resetPasswordForOld
Future<SignInRes> auth.resetPasswordForOld(ResetPasswordForOldReq params)
Reset password with old password.
参数
返回
示例
reauthenticate
Future<ReauthenticateRes> auth.reauthenticate();
Re-authenticate. Send verification code to user's email or phone number. After verification, sensitive operations can be performed (such as setting a new password).
参数
无参数
返回
示例
Verification Management
getVerification
Future<GetVerificationRes> auth.getVerification(GetVerificationReq params)
Send verification code. Supports sending to email or phone number.
参数
返回
示例
verify
Future<VerifyRes> auth.verify(VerifyReq params)
Verify verification code (for email/phone verification).
参数
返回
示例
verifyOAuth
Future<SignInRes> auth.verifyOAuth(VerifyOAuthReq params)
Verify OAuth callback. Handle the callback after user authorization on third-party platform.
参数
返回
示例
verifyOtp
Future<SignInRes> auth.verifyOtp(VerifyOtpParams params)
Verify OTP (one-time password). Used to verify the verification code sent by signInWithOtp or signUp.
参数
返回
示例
resend
Future<ResendRes> auth.resend(ResendReq params)
Resend verification code.
参数
返回
示例
getCaptchaToken
Future<GetCaptchaTokenRes> auth.getCaptchaToken()
Get CAPTCHA token. Used to get CAPTCHA verification token before sending verification code.
参数
无参数
返回
示例
createCaptchaData
Future<CreateCaptchaDataRes> auth.createCaptchaData(CreateCaptchaDataReq params)
Create CAPTCHA verification data. Used to initialize CAPTCHA challenge.
参数
返回
示例
verifyCaptchaData
Future<VerifyCaptchaDataRes> auth.verifyCaptchaData(VerifyCaptchaDataReq params)
Verify CAPTCHA. Validate user's CAPTCHA response.
