Overview
The CloudBase Flutter SDK enables you to use cloud development abilities in Flutter apps, including identity verification, data model, MySQL database, Serverless Cloud Function (SCF), cloud hosting, APIs and other features. For usage, refer to CloudBase Flutter SDK or see example code.
CloudBase Flutter SDK is fully aligned with HTTP API
SDKs are divided into the following categories by feature purpose:
- Authentication Login: API methods for user registration and sign-in, supporting various login methods.
- Session Management: API methods to manage user session status and token.
- User Management: API methods to get, update, and manage user information.
- Identity Source Management: API methods to manage third-party identity source binding and unbinding. -Password Management: API methods for password reset and modification.
- Verification Management: API methods for verification code sending, verify and resend, graphic verification code creation, verification, and manage.
- Data Model: CRUD operation for data model.
- Data Source Query: Query data source aggregate column, detail, Schema, and table name.
- MySQL Database: MySQL RESTful database operations.
- SCF: Call SCF and functional cloud hosting.
- Cloud Hosting: Call cloud managed Tencent Kubernetes Engine (TKE).
- APIs: Invoke APIs.
Basic usage example
- Initialization configuration
- Login Status Check
- User Registration Process
- Password Login
- Logout
- Listening Status Transition
- Call SCF
accessKey can go to Cloud Development Platform/API Key configuration to generate.
import 'package:cloudbase_flutter/cloudbase_flutter.dart';
//Initialize (async)
final app = await CloudBase.init(
env: 'your-env-id', // Replace this value with your environment ID
region: 'ap-shanghai', // Region, defaults to Shanghai
accessKey: 'your-key', // Fill in the generated Publishable Key
authConfig: AuthConfig(
detectSessionInUrl: true, // Option: 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('check login status failed: ${result.error!.message}');
return false;
}
if (result.data?.session != null) {
print('User logged in: ${result.data!.user?.id}');
return true;
} else {
print('User not logged in');
return false;
}
}
// User registration example (two-step verification process)
Future<void> registerUser(String email, String password) async {
Step 1: Send Captcha
final signUpResult = await auth.signUp(SignUpReq(
email: email,
password: password,
));
if (signUpResult.error != null) {
print('send Captcha failed: ${signUpResult.error!.message}');
return;
}
print('Captcha sent, waiting for user input...');
Step 2: Verify the verification code and complete registration.
final verifyResult = await signUpResult.data!.verifyOtp!(
VerifyOtpParams(token: 'Captcha input by the user')
);
if (verifyResult.error != null) {
print('Registration failed: ${verifyResult.error!.message}');
} else {
print('Registration succeeded: ${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 succeeded: ${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 status changes
final result = auth.onAuthStateChange((event, session, info) {
switch (event) {
case AuthStateChangeEvent.signedIn:
print('User logged in');
break;
case AuthStateChangeEvent.signedOut:
print('User logged out');
break;
case AuthStateChangeEvent.tokenRefreshed:
print('Token updated');
break;
case AuthStateChangeEvent.userUpdated:
print('User information updated');
break;
default:
break;
}
});
// Unsubscription
result.data?.subscription.unsubscribe();
Call SCF 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 login
signUp
Future<SignUpRes> auth.signUp(SignUpReq params)
Register a new user account, use intelligent registration and login process.
-Create a new user account -Use intelligent registration and login process: send verification code → wait for user input → intelligently determine user existence → automatically log in or register and log in -If the user already exists, log in directly; if the user does not exist, register new user and automatically log in.
参数
返回
示例
signInAnonymously
Future<SignInRes> auth.signInAnonymously({String? providerToken})
Anonymous login, create a temporary anonymous user account.
-Create a temporary anonymous user account -No need to provide any authentication information
- Suitable for scenarios where temporary access permission is required
参数
Third-party platform token, used for associating third-party platform identity
返回
示例
signInWithPassword
Future<SignInRes> auth.signInWithPassword(SignInWithPasswordReq params)
Log in using password. Support through userName, mailbox or mobile number to log in.
参数
返回
示例
signInWithOtp
Future<SignInWithOtpRes> auth.signInWithOtp(SignInWithOtpReq params)
Use OTP (one-time verification code) to log in. After calling, send the verification code, and complete the verification through the returned verifyOtp callback.
- If the user does not exist, a default registered user will be created. The automatic creation of the user can be controlled through the
shouldCreateUserparameter, which is set to true by default
参数
返回
示例
signInWithOAuth
Future<SignInOAuthRes> auth.signInWithOAuth(SignInWithOAuthReq params)
Use OAuth third-party platform to log in. Return the authorization URL and guide users to go to the URL to complete authorization.
参数
返回
示例
signInWithIdToken
Future<SignInRes> auth.signInWithIdToken(SignInWithIdTokenReq params)
Use IdToken to log in. Suitable for scenarios where third-party platform tokens are obtained.
参数
返回
示例
signInWithCustomTicket
Future<SignInRes> auth.signInWithCustomTicket(Future<String> Function() getTicketFn)
Use a custom invoice to log in. By importing the async function to obtain the invoice, the server generates the invoice and completes login.
参数
Async function for custom login invoice retrieval
返回
示例
Session Management
getSession
Future < SignInRes > auth.getSession();
Retrieve the current session. If the Token expires, it will automatically refresh.
参数
无参数
返回
示例
refreshSession
Future<SignInRes> auth.refreshSession([String? refreshToken])
Refresh the session. Use the Refresh Token to obtain a new Access Token.
参数
Refresh token (optional, by default uses the refreshToken of the current session)
返回
示例
setSession
Future<SignInRes> auth.setSession(SetSessionReq params)
Set session. Restore session status with Refresh Token.
参数
返回
示例
signOut
Future<SignOutRes> auth.signOut([SignOutReq? params])
Logout. Clean up the local conversation and notify the notification service to revoke the token.
参数
Logout configuration option (selectable)
返回
示例
onAuthStateChange
OnAuthStateChangeResult auth.onAuthStateChange(OnAuthStateChangeCallback callback)
Listen for authentication status changes. Support listening to events such as login, logout, Token refresh, and user update.
参数
Status change callback function
返回
示例
getClaims
Future < GetClaimsRes > auth.getClaims();
Retrieve JWT Claims of the current Access Token.
参数
无参数
返回
示例
User Management
getUser
Future < GetUserRes > auth.getUser();
Obtain currently logged in user information.
参数
无参数
返回
示例
refreshUser
Future < SignInRes > auth.refreshUser();
Refresh user information. Retrieve the latest user data from the server again and update the local conversation.
参数
无参数
返回
示例
updateUser
Future<UpdateUserRes> auth.updateUser(UpdateUserReq params)
Update user information. If updating email or mobile number, need to pass through verification code verification.
参数
返回
示例
deleteUser
Future<CloudBaseResponse<void>> auth.deleteUser(DeleteUserReq params)
Delete the current user. Password is required for security verification.
参数
返回
示例
Identity Source Management
getUserIdentities
Future < GetUserIdentitiesRes > auth.getUserIdentities();
Retrieve the list of bound identity sources for the current user.
参数
无参数
返回
示例
linkIdentity
Future<LinkIdentityRes> auth.linkIdentity(LinkIdentityReq params)
Bind an external identity source. It will redirect to the third-party authorization webpage to complete the binding.
参数
返回
示例
unlinkIdentity
Future<CloudBaseResponse<void>> auth.unlinkIdentity(UnlinkIdentityReq params)
Unbind the third-party identity source.
参数
返回
示例
Password Management
resetPasswordForEmail
Future<ResetPasswordForEmailRes> auth.resetPasswordForEmail(String emailOrPhone, {String? redirectTo})
Reset the password through mailbox or mobile number. After calling, send verification code. The password reset must be done through the returned updateUser callback.
参数
mailbox or mobile number
redirect address
返回
示例
resetPasswordForOld
Future<SignInRes> auth.resetPasswordForOld(ResetPasswordForOldReq params)
Reset the password with the old password.
参数
返回
示例
reauthenticate
Future < ReauthenticateRes > auth.reauthenticate();
Re-authenticate. A verification code is sent to your user email or mobile number. You can perform sensitive operations (such as setting a new password) after verification.
参数
无参数
返回
示例
Verify management
getVerification
Future<CloudBaseResponse<GetVerificationResData>> auth.getVerification({String? email, String? phoneNumber})
Send Captcha to mailbox or mobile number.
参数
mailbox (choose either mailbox or phoneNumber)
mobile number (choose either mobile number or email)
返回
示例
verify
Future<CloudBaseResponse<VerifyCodeResData>> auth.verify({required String verificationId, required String verificationCode})
Verify the verification code.
参数
verification ID
Captcha
返回
示例
verifyOAuth
Future<VerifyOAuthRes> auth.verifyOAuth([VerifyOAuthReq? params])
Verify OAuth callback to complete third-party login or identity binding. If no parameters are passed, it will automatically extract code and state from the current page URL.
参数
OAuth callback parameters (optional, automatically extracted from URL if not provided)
返回
示例
verifyOtp
Future<SignInRes> auth.verifyOtp(VerifyOtpReq params)
Verify OTP and log in.
参数
返回
示例
resend
Future<ResendRes> auth.resend(ResendReq params)
Resend the verification code.
参数
返回
示例
getCaptchaToken
Future<String?> app.captcha.getCaptchaToken({bool forceNew, required String state})
Obtain a valid Captcha Token. When incorrect password input occurs multiple times or verification codes are sent frequently, a Captcha Token is required. Preferentially retrieve from cache. If no cache exists, auto-create Captcha and pop up the verification interface. Support custom Captcha processor or use built-in popup.
参数
Whether to force creating a new Captcha (default false)
Status identifier
返回
Captcha Token. null if failed
示例
createCaptchaData
Future<CreateCaptchaDataRes> app.captcha.createCaptchaData({required String state})
Create Captcha data. Return image data and Token.
参数
Status identifier