CloudBase Flutter
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
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.
参数
返回
示例
final result = await auth.signUp(SignUpReq(
email: 'user@example.com',
password: 'securePassword123',
nickname: 'new user',
));
if (result.error != null) {
print('Registration failed: ${result.error!.message}');
return;
}
// Verification code verification
final verifyResult = await result.data!.verifyOtp!(
VerifyOtpParams(token: '123456'),
);
if (verifyResult.isSuccess) {
print('Registration succeeded: ${verifyResult.data?.user?.id}');
}
final result = await auth.signUp(SignUpReq(
phone: '13800138000',
password: 'securePassword123',
));
if (result.error != null) {
print('send Captcha failed: ${result.error!.message}');
return;
}
final verifyResult = await result.data!.verifyOtp!(
VerifyOtpParams(token: '123456'),
);
if (verifyResult.isSuccess) {
print('Registration succeeded: ${verifyResult.data?.user?.phone}');
}
final result = await auth.signUp(SignUpReq(
email: 'user@example.com',
password: 'password123',
));
if (result.error != null) {
final code = result.error!.code;
switch (code) {
case 'email_already_exists':
print('Mailbox is registered');
break;
case 'password_too_weak':
print('Password strength insufficient');
break;
case 'invalid_email':
print('Incorrect email format');
break;
default:
print('Registration failed: ${result.error!.message}');
}
}
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
返回
示例
final result = await auth.signInAnonymously();
if (result.isSuccess) {
print('Anonymous login success');
print('User ID: ${result.data?.user?.id}');
print('Anonymous or not: ${result.data?.user?.isAnonymous}');
} else {
print('Anonymous login failed: ${result.error!.message}');
}
Step 1: Anonymous login
final anonymousResult = await auth.signInAnonymously();
if (anonymousResult.error != null) {
print('Anonymous login failed: ${anonymousResult.error!.message}');
return;
}
print('Anonymous login success, prepare to upgrade to official user');
Step 2. Bind the email (input anonymousToken when registering)
final upgradeResult = await auth.signUp(SignUpReq(
email: 'user@example.com',
password: 'securePassword123',
anonymousToken: anonymousResult.data?.session?.accessToken,
));
if (upgradeResult.error != null) {
print('upgrade failed: ${upgradeResult.error!.message}');
return;
}
// Step 3: Verify the Captcha
final verifyResult = await upgradeResult.data!.verifyOtp!(
VerifyOtpParams(token: '123456'),
);
if (verifyResult.isSuccess) {
print('Anonymous user promotion success');
}
signInWithPassword
Future<SignInRes> auth.signInWithPassword(SignInWithPasswordReq params)
Log in using password. Support through userName, mailbox or mobile number to log in.
参数
返回
示例
final result = await auth.signInWithPassword(
SignInWithPasswordReq(
email: 'user@example.com',
password: 'securePassword123',
),
);
if (result.isSuccess) {
print('Login succeeded: ${result.data?.user?.id}');
} else {
print('login failed: ${result.error!.message}');
}
final result = await auth.signInWithPassword(
SignInWithPasswordReq(
email: 'user@example.com',
password: 'wrongPassword',
),
);
if (result.error != null) {
switch (result.error!.code) {
case 'invalid_credentials':
print('Incorrect username or password');
break;
case 'user_not_found':
print('User does not exist');
break;
default:
print('login failed: ${result.error!.message}');
}
}
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.
参数
返回
示例
final result = await auth.signInWithOtp(
SignInWithOtpReq(email: 'user@example.com'),
);
if (result.error != null) {
print('send Captcha failed: ${result.error!.message}');
return;
}
// Call after the user enters the Captcha
final loginResult = await result.data!.verifyOtp!(
VerifyOtpParams(token: '123456'),
);
if (loginResult.isSuccess) {
print('OTP login succeeded: ${loginResult.data?.user?.id}');
}
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.
参数
返回
示例
final result = await auth.signInWithOAuth(
SignInWithOAuthReq(provider: 'wechat'),
);
if (result.isSuccess) {
final authUrl = result.data!.url!;
print('Please navigate to the authorization page: $authUrl');
// Guide user to open authUrl to authorize
}
signInWithIdToken
Future<SignInRes> auth.signInWithIdToken(SignInWithIdTokenReq params)
Use IdToken to log in. Suitable for scenarios where third-party platform tokens are obtained.
参数
返回
示例
final result = await auth.signInWithIdToken(
SignInWithIdTokenReq(
token: 'provider-id-token',
provider: 'wechat',
),
);
if (result.isSuccess) {
print('IdToken login succeeded: ${result.data?.user?.id}');
} else {
print('login failed: ${result.error!.message}');
}
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
返回
示例
final result = await auth.signInWithCustomTicket(() async {
// Retrieve a custom invoice from your server
final ticket = await fetchTicketFromServer();
return ticket;
});
if (result.isSuccess) {
print('Login succeeded with custom invoice: ${result.data?.user?.id}');
} else {
print('login failed: ${result.error!.message}');
}
Session Management
getSession
Future < SignInRes > auth.getSession();
Retrieve the current session. If the Token expires, it will automatically refresh.
参数
无参数
返回
示例
final result = await auth.getSession();
if (result.isSuccess) {
final session = result.data?.session;
print('Access Token: ${session?.accessToken}');
print('User: ${result.data?.user?.id}');
} else {
print('get conversation failed: ${result.error!.message}');
}
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)
返回
示例
final result = await auth.refreshSession();
if (result.isSuccess) {
print('session updated')
print('New Access Token: ${result.data?.session?.accessToken}');
} else {
print('refresh failed: ${result.error!.message}');
}
setSession
Future<SignInRes> auth.setSession(SetSessionReq params)
Set session. Restore session status with Refresh Token.
参数
返回
示例
final result = await auth.setSession(
SetSessionReq(refreshToken: 'your-refresh-token'),
);
if (result.isSuccess) {
print('Session setting is successful: ${result.data?.user?.id}');
}
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)
返回
示例
await auth.signOut();
print("logged out");
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
返回
示例
final result = auth.onAuthStateChange((event, session, info) {
print('authentication status transition: ${event.value}');
if (session != null) {
print('User: ${session.user?.id}');
}
});
// Cancel listening
result.data?.subscription.unsubscribe();
getClaims
Future < GetClaimsRes > auth.getClaims();
Retrieve JWT Claims of the current Access Token.
参数
无参数
返回
示例
final result = await auth.getClaims();
if (result.isSuccess) {
final claims = result.data?.claims;
print('User ID: ${claims?.sub}');
print('Mailbox: ${claims?.email}');
print('User group: ${claims?.groups}');
print('Expiration time: ${claims?.exp}');
}
User Management
getUser
Future < GetUserRes > auth.getUser();
Obtain currently logged in user information.
参数
无参数
返回
示例
final result = await auth.getUser();
if (result.isSuccess) {
final user = result.data?.user;
print('User ID: ${user?.id}');
print('Mailbox: ${user?.id}');
print('Nickname: ${user?.userMetadata?.nickName}');
} else {
print('failed to obtain user information: ${result.error!.message}');
}
refreshUser
Future < SignInRes > auth.refreshUser();
Refresh user information. Retrieve the latest user data from the server again and update the local conversation.
参数
无参数
返回
示例
final result = await auth.refreshUser();
if (result.isSuccess) {
print('User information updated: ${result.data?.user?.id}');
}
updateUser
Future<UpdateUserRes> auth.updateUser(UpdateUserReq params)
Update user information. If updating email or mobile number, need to pass through verification code verification.
参数
返回
示例
final result = await auth.updateUser(
UpdateUserReq(nickname: 'new nickname', avatarUrl: 'https://example.com/avatar.png')
);
if (result.isSuccess) {
print('User information updated: ${result.data?.user?.userMetadata?.nickName}');
}
final result = await auth.updateUser(
UpdateUserReq(email: 'new@example.com'),
);
if (result.isSuccess && result.data?.verifyOtp != null) {
final verifyResult = await result.data!.verifyOtp!(
UpdateUserVerifyParams(token: '123456'),
);
if (verifyResult.isSuccess) {
print('Mailbox update succeeded: ${verifyResult.data?.user?.id}');
}
}
deleteUser
Future<CloudBaseResponse<void>> auth.deleteUser(DeleteUserReq params)
Delete the current user. Password is required for security verification.
参数
返回
示例
final result = await auth.deleteUser(
DeleteUserReq(password: 'currentPassword'),
);
if (result.isSuccess) {
print('User deleted');
} else {
print('Deletion failed: ${result.error!.message}');
}
Identity Source Management
getUserIdentities
Future < GetUserIdentitiesRes > auth.getUserIdentities();
Retrieve the list of bound identity sources for the current user.
参数
无参数
返回
示例
final result = await auth.getUserIdentities();
if (result.isSuccess) {
for (final identity in result.data?.identities ?? []) {
print('Identity source: ${identity.name} (${identity.provider})');
}
}
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.
参数
返回
示例
final result = await auth.linkIdentity(
LinkIdentityReq(provider: 'wechat'),
);
if (result.isSuccess) {
print('Identity source binding succeeded: ${result.data?.provider}');
}
unlinkIdentity
Future<CloudBaseResponse<void>> auth.unlinkIdentity(UnlinkIdentityReq params)
Unbind the third-party identity source.
参数
返回
示例
final result = await auth.unlinkIdentity(
UnlinkIdentityReq(provider: 'wechat'),
);
if (result.isSuccess) {
print('Identity source unbound');
}
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
返回
示例
final result = await auth.resetPasswordForEmail('user@example.com');
if (result.error != null) {
print('send Captcha failed: ${result.error!.message}');
return;
}
// User received verification code
final resetResult = await result.data!.updateUser!(
UpdateUserAttributes(nonce: '123456', password: 'newPassword123'),
);
if (resetResult.isSuccess) {
print('Password reset successful, auto login');
}
resetPasswordForOld
Future<SignInRes> auth.resetPasswordForOld(ResetPasswordForOldReq params)
Reset the password with the old password.
参数
返回
示例
final result = await auth.resetPasswordForOld(
ResetPasswordForOldReq(
oldPassword: 'oldPassword123',
newPassword: 'newPassword456',
),
);
if (result.isSuccess) {
print('Password modification succeeded');
} else {
print('password change failure: ${result.error!.message}');
}
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.
参数
无参数
返回
示例
final result = await auth.reauthenticate();
if (result.error != null) {
print('send Captcha failed: ${result.error!.message}');
return;
}
final authResult = await result.data!.updateUser!(
UpdateUserAttributes(nonce: '123456', password: 'newSecurePassword'),
);
if (authResult.isSuccess) {
print('authentication succeeded again');
}
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)
返回
示例
final result = await auth.getVerification(email: 'user@example.com');
if (result.isSuccess) {
print('Captcha sent, validation ID: ${result.data?.verificationId}');
print('Verify whether user is registered: ${result.data?.isUser}');
}
verify
Future<CloudBaseResponse<VerifyCodeResData>> auth.verify({required String verificationId, required String verificationCode})
Verify the verification code.
参数
verification ID
Captcha
返回
示例
final result = await auth.verify(
verificationId: 'verification-id',
verificationCode: '123456',
);
if (result.isSuccess) {
print('Verification succeeds, token: ${result.data?.verificationToken}');
}
verifyOtp
Future<SignInRes> auth.verifyOtp(VerifyOtpReq params)
Verify OTP and log in.
参数
返回
示例
final result = await auth.verifyOtp(VerifyOtpReq(
email: 'user@example.com',
token: '123456',
messageId: 'message-id',
));
if (result.isSuccess) {
print('Verification and login succeeded: ${result.data?.user?.id}');
}
resend
Future<ResendRes> auth.resend(ResendReq params)
Resend the verification code.
参数
返回
示例
final result = await auth.resend(
ResendReq(email: 'user@example.com', type: ResendType.signup),
);
if (result.isSuccess) {
print('Verification code resent, message ID: ${result.data?.messageId}');
}
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
示例
// Configure navigatorKey during initialization
final navigatorKey = GlobalKey<NavigatorState>();
final app = await CloudBase.init(
env: 'your-env-id',
captchaConfig: CaptchaConfig(navigatorKey: navigatorKey),
);
// Get a Captcha Token (automatic pop-up Captcha window)
final token = await app.captcha.getCaptchaToken(state: 'login');
print('Captcha Token: $token');
// Set a custom processor
app.captcha.onCaptchaRequired = (String captchaImageData) async {
// Customize display of the Captcha image and obtain user input
final userInput = await showMyCustomCaptchaDialog(captchaImageData);
return userInput;
};
final token = await app.captcha.getCaptchaToken(state: 'register');
createCaptchaData
Future<CreateCaptchaDataRes> app.captcha.createCaptchaData({required String state})
Create Captcha data. Return image data and Token.
参数
Status identifier
返回
示例
final captchaData = await app.captcha.createCaptchaData(state: 'login');
print('Captcha image: ${captchaData.data}');
print('Token: ${captchaData.token}');
verifyCaptchaData
Future<VerifyCaptchaRes> app.captcha.verifyCaptchaData({required String token, required String key})
Validate user input verification code.
参数
Captcha Token
user input verification code
返回
示例
final result = await app.captcha.verifyCaptchaData(
token: captchaData.token,
key: 'user input verification code'
);
print('Captcha Token: ${result.captchaToken}');
clearCaptchaToken
Future<void> app.captcha.clearCaptchaToken()
Clear the verification code Token in local cache.
参数
无参数
返回
no return value
示例
await app.captcha.clearCaptchaToken();
print("Captcha Token cleared");
Data Model
getById
Future<ModelFindResponse> app.models.getById({required String modelName, required String recordId})
Retrieve a single data record based on ID.
参数
data model flag
Data ID
返回
示例
final result = await app.models.getById(
modelName: 'user',
recordId: '123',
);
if (result.isSuccess) {
print('Record: ${result.record}');
} else {
print('Query failed: ${result.message}');
}
get
Future<ModelFindResponse> app.models.get({required String modelName, Map<String, dynamic>? filter, Map<String, dynamic>? select})
Retrieve a single data record based on conditions.
参数
data model flag
Filter criteria, format: {'where': {'_id': {'\$eq': 'foobar'}}}
Field filtering, format: {'\$master': true} or {'field': true}
返回
示例
final result = await app.models.get(
modelName: 'user',
filter: {'where': {'_id': {'\$eq': '123'}}},
select: {'\$master': true},
);
if (result.isSuccess) {
print('Record: ${result.record}');
} else {
print('Query failed: ${result.message}');
}
list
Future<ModelFindManyResponse> app.models.list({
required String modelName,
Map<String, dynamic>? filter,
Map<String, dynamic>? select,
int? pageSize,
int? pageNumber,
bool? getCount,
List<Map<String, String>>? orderBy,
})
Query multiple data entries. Supports filtering conditions, field filtering, pagination, and sorting.
参数
data model flag
Filter criteria, format: {'where': {'field': {'\$eq': 'value'}}}
Field filtering, format: {'\$master': true} or {'field': true}
Page size. Default 10
Page number. Default 1
Whether to return the total count
Sorting order, up to 3 fields, format: [{'field': 'desc'}]
返回
示例
final result = await app.models.list(
modelName: 'user',
pageSize: 10,
pageNumber: 1,
getCount: true,
orderBy: [{'createdAt': 'desc'}],
filter: {'where': {'age': {'\$gt': 18}}},
);
if (result.isSuccess) {
print('Total: ${result.total}');
for (final record in result.records) {
print('Record: $record');
}
}
listSimple
Future<ModelFindManyResponse> app.models.listSimple({required String modelName, int? pageSize, int? pageNumber, bool? getCount})
Simple query for multiple data (GET request, only supports pagination parameters).
参数
data model flag
Page size
Page number. Default 1
Whether to return the total count (default false)
返回
示例
final result = await app.models.listSimple(
modelName: 'user',
pageSize: 10,
pageNumber: 1,
getCount: true,
);
if (result.isSuccess) {
print('Total: ${result.total}');
for (final record in result.records) {
print('Record: $record');
}
}
create
Future<ModelCreateResponse> app.models.create({required String modelName, required Map<String, dynamic> data})
Creating a single data entry.
参数
data model flag
data content
返回
示例
final result = await app.models.create(
modelName: 'user',
data: {'name': 'Zhang San', 'age': 25, 'email': 'test@example.com'},
);
if (result.isSuccess) {
print('Creation succeeded, ID: ${result.id}');
} else {
print('Creation failed: ${result.message}');
}
createMany
Future<ModelCreateManyResponse> app.models.createMany({required String modelName, required List<Map<String, dynamic>> data})
Batch create data.
参数
data model flag
Batch data list
返回
示例
final result = await app.models.createMany(
modelName: 'user',
data: [
{'name': 'Zhang San', 'age': 25},
{'name': 'Li Si', 'age': 30},
],
);
if (result.isSuccess) {
print('Batch creation succeeded, ID list: ${result.idList}');
}
update
Future<ModelUpdateDeleteResponse> app.models.update({required String modelName, required Map<String, dynamic> filter, required Map<String, dynamic> data})
Updating a single data entry.
参数
data model flag
filtering condition
update data
返回
示例
final result = await app.models.update(
modelName: 'user',
filter: {'where': {'_id': {'\$eq': '123'}}},
data: {'age': 26},
);
if (result.isSuccess) {
print('Update successful, modified ${result.count} items');
}
updateMany
Future<ModelUpdateDeleteManyResponse> app.models.updateMany({required String modelName, required Map<String, dynamic> filter, required Map<String, dynamic> data})
Batch update data.
参数
data model flag
filtering condition
update data
返回
示例
final result = await app.models.updateMany(
modelName: 'user',
filter: {'where': {'age': {'\$lt': 18}}},
data: {'status': 'minor'},
);
if (result.isSuccess) {
print('Batch update successful, modified ${result.count} items');
}
upsert
Future<ModelUpsertResponse> app.models.upsert({required String modelName, required Map<String, dynamic> filter, Map<String, dynamic>? create, Map<String, dynamic>? update})
Create or update single data entry (Upsert). If matched to existing record, refresh; otherwise, create new record.
参数
data model flag
filtering condition
Data content created if does not exist
Data content updated if exists
返回
示例
final result = await app.models.upsert(
modelName: 'user',
filter: {'where': {'email': {'\$eq': 'test@example.com'}}},
create: {'name': 'Zhang San', 'email': 'test@example.com', 'age': 25},
update: {'age': 26},
);
if (result.isSuccess) {
print('Upsert successful, modified ${result.count} items');
if (result.id != null) {
print('New record ID: ${result.id}');
}
}
deleteById
Future<ModelUpdateDeleteResponse> app.models.deleteById({required String modelName, required String recordId})
Delete a single data record based on ID.
参数
data model flag
Data ID
返回
示例
final result = await app.models.deleteById(
modelName: 'user',
recordId: '123',
);
if (result.isSuccess) {
print('Deleted successfully, modified ${result.count} items');
}
deleteRecord
Future<ModelUpdateDeleteResponse> app.models.deleteRecord({required String modelName, required Map<String, dynamic> filter})
Delete a single data record based on conditions.
参数
data model flag
filtering condition
返回
示例
final result = await app.models.deleteRecord(
modelName: 'user',
filter: {'where': {'_id': {'\$eq': '123'}}},
);
if (result.isSuccess) {
print('Deleted successfully, modified ${result.count} items');
}
deleteMany
Future<ModelUpdateDeleteManyResponse> app.models.deleteMany({required String modelName, required Map<String, dynamic> filter})
Batch delete data.
参数
data model flag
filtering condition
返回
示例
final result = await app.models.deleteMany(
modelName: 'user',
filter: {'where': {'status': {'\$eq': 'inactive'}}},
);
if (result.isSuccess) {
print('Batch deleted successfully, modified ${result.count} items');
}
mysqlCommand
Future<ModelMysqlCommandResponse> app.models.mysqlCommand({required String sqlTemplate, List<ModelMysqlParameter>? parameter, ModelMysqlConfig? config})
Execute MySQL commands. Supports parameterized queries.
参数
SQL statement, supports parameter placeholder {{ var }}
SQL parameter list
Execution configuration (timeout, preparedStatements, dbLinkName)
返回
示例
final result = await app.models.mysqlCommand(
sqlTemplate: 'select * from `users` where _id = {{ _id }}',
parameter: [
ModelMysqlParameter(key: '_id', type: 'STRING', value: '123'),
],
);
if (result.isSuccess) {
print('Execution result: ${result.executeResultList}');
}
Data source query
getAggregateDataSourceList
Future<AggregateDataSourceListResponse> app.models.getAggregateDataSourceList({
required int pageSize,
String? envId,
int? pageIndex,
int? queryAll,
List<String>? dataSourceIds,
List<String>? dataSourceNames,
String? dataSourceType,
List<String>? viewIds,
List<String>? appIds,
int? appLinkStatus,
int? queryBindToApp,
int? queryConnector,
List<String>? channelList,
bool? queryDataSourceRelationList,
String? dbInstanceType,
List<String>? databaseTableNames,
bool? querySystemModel,
})
Query the aggregate column list of the data source based on conditions. envId is selectable, by default using the initial environment ID.
参数
Entries per page
Environment ID (selectable, by default using the initial env)
Page number
Query all (0 or 1)
Data source ID list
Data source name list
Data source type
Query data sources bound to the application (0 or 1)
Query connectors (0 or 1)
Query system model
返回
示例
final result = await app.models.getAggregateDataSourceList(
pageSize: 10,
pageIndex: 0,
);
if (result.isSuccess) {
print('Total: ${result.count}');
for (final ds in result.rows) {
print('${ds.name}: ${ds.title} (type: ${ds.type})');
}
}
getDataSourceAggregateDetail
Future<DataSourceAggregateDetailResponse> app.models.getDataSourceAggregateDetail({
String? datasourceId,
String? dataSourceName,
String? viewId,
int? queryPublish,
bool? queryModelRelation,
String? dbInstanceType,
String? databaseTableName,
})
Query data source aggregated details based on conditions. datasourceId and dataSourceName cannot both be empty.
参数
Data source ID (cannot both be empty with dataSourceName)
Data source name (cannot both be empty with datasourceId)
view ID
Query published data sources (0 trial, 1 publish)
Whether to query association relationships
DB type of the instance
Database table name
返回
示例
final result = await app.models.getDataSourceAggregateDetail(
dataSourceName: 'user',
);
if (result.isSuccess) {
print('Schema: ${result.dataSource?.schema}');
print('Name: ${result.dataSource?.title}');
}
getDataSourceByTableName
Future<DataSourceByTableNameResponse> app.models.getDataSourceByTableName({required List<String> tableNames})
Query the data source Schema definition based on database table name.
参数
Data table name list
返回
示例
final result = await app.models.getDataSourceByTableName(
tableNames: ['user_table', 'order_table'],
);
if (result.isSuccess) {
for (final info in result.dataSourceTableInfos) {
print('Table: ${info.tableName}, Data source: ${info.name}');
}
}
getBasicDataSourceList
Future<BasicDataSourceListResponse> app.models.getBasicDataSourceList({
List<String>? idList,
List<String>? nameList,
int? pageNum,
int? pageSize,
bool? queryAll,
List<DataSourceQueryFilter>? queryFilterList,
bool? onlyFlexDb,
})
Query basic data source information list based on conditions (POST request, supports filter conditions).
参数
Data source ID list
Data source identifier list
Page number. Default 1
Entries per page. Default 10
Query all
Query filter condition list
Query flexdb type only
返回
示例
final result = await app.models.getBasicDataSourceList(
pageSize: 10,
pageNum: 1,
queryFilterList: [
DataSourceQueryFilter(name: 'Type', values: ['database']),
],
);
if (result.isSuccess) {
print('Total: ${result.total}');
for (final ds in result.dataSourceList) {
print('${ds.name}: ${ds.title}');
}
}
getBasicDataSource
Future<BasicDataSourceResponse> app.models.getBasicDataSource({
String? datasourceId,
String? dataSourceName,
String? viewId,
int? queryPublish,
bool? queryModelRelation,
String? dbInstanceType,
String? databaseTableName,
})
Query basic data source information based on conditions. datasourceId and dataSourceName cannot both be empty.
参数
Data source ID (cannot both be empty with dataSourceName)
Data source name (cannot both be empty with datasourceId)
view ID
Query published data sources (0 trial, 1 publish)
Whether to query association relationships
DB type of the instance
Database table name
返回
示例
final result = await app.models.getBasicDataSource(
dataSourceName: 'user',
);
if (result.isSuccess) {
print('Data source: ${result.dataSource?.name}');
print('Type: ${result.dataSource?.type}');
}
getSchemaList
Future<DataSourceSchemaListResponse> app.models.getSchemaList({List<String>? dataSourceNameList})
Query the Schema of all data sources in the query environment. Query all if no parameter is provided.
参数
Data source name list (optional, query all if not provided)
返回
示例
final result = await app.models.getSchemaList(
dataSourceNameList: ['user', 'order'],
);
if (result.isSuccess) {
for (final rel in result.dataSourceRelationInfoList) {
print('${rel.name}: ${rel.title}');
}
}
getTableName
Future<DataSourceTableNameResponse> app.models.getTableName({String? dataSourceName})
Query the corresponding database table name based on data source name.
参数
Data source name
返回
示例
final result = await app.models.getTableName(
dataSourceName: 'user',
);
if (result.isSuccess) {
print('Table name: ${result.tableName}');
print('Database type: ${result.dbType}');
}
MySQL database
query
Future<MySqlResponse> app.mysql.query({required String table, String? schema, String? instance, MySqlQueryOptions? options})
Query MySQL data. Supports field filtering, pagination, sorting, and conditional filtering.
Supported filtering operators: eq (equal), neq (not equal), gt (greater than), gte (greater than or equal to), lt (less than), lte (less than or equal to), like (fuzzy matching), in (in the list), is (judge null)
参数
Table name
Database name
Database instance flag (requires collocation with schema)
Query option
返回
示例
final result = await app.mysql.query(
table: 'users',
options: MySqlQueryOptions(
select: '*',
limit: 10,
offset: 0,
order: 'id.asc',
withCount: true,
),
);
if (result.isSuccess) {
print('Total: ${result.total}');
for (final row in result.data) {
print('Record: $row');
}
}
final result = await app.mysql.query(
table: 'users',
options: MySqlQueryOptions(
select: 'id,name,age',
filters: {'age': 'gt.18', 'name': 'like.% zhang %'},
limit: 20,
),
);
if (result.isSuccess) {
print('Queried ${result.data.length} record');
}
insert
Future<MySqlWriteResponse> app.mysql.insert({required String table, required dynamic data, String? schema, String? instance, bool upsert, String? onConflict})
Insert data. Support single and batch insertion as well as Upsert Mode.
参数
Table name
Insert data, single Map or batch List<Map>
Whether Upsert Mode is enabled (false by default)
Upsert conflict field
返回
示例
final result = await app.mysql.insert(
table: 'users',
data: {'name': 'Zhang San', 'age': 25},
);
if (result.isSuccess) {
print('insertion successful');
}
final result = await app.mysql.insert(
table: 'users',
data: [
{'name': 'Zhang San', 'age': 25},
{'name': 'Li Si', 'age': 30},
],
);
if (result.isSuccess) {
print('batch insertion successful');
}
update (MySQL)
Future<MySqlWriteResponse> app.mysql.update({required String table, required Map<String, dynamic> data, required Map<String, String> filters, String? schema, String? instance})
Update MySQL data. Must provide WHERE conditions.
参数
Table name
data to be updated
WHERE condition (cannot be empty)
返回
示例
final result = await app.mysql.update(
table: 'users',
data: {'age': 26},
filters: {'name': 'eq.Zhang San'},
);
if (result.isSuccess) {
print('update succeeded');
} else {
print('update failed: ${result.message}');
}
delete (MySQL)
Future<MySqlWriteResponse> app.mysql.delete({required String table, required Map<String, String> filters, String? schema, String? instance})
Delete MySQL data. Must provide WHERE conditions.
参数
Table name
WHERE condition (cannot be empty)
返回
示例
final result = await app.mysql.delete(
table: 'users',
filters: {'name': 'eq.Zhang San'},
);
if (result.isSuccess) {
print('Deleted successfully');
}
count
Future<MySqlCountResponse> app.mysql.count({required String table, Map<String, String>? filters, String? schema, String? instance})
Statistics of MySQL data amount.
参数
Table name
filtering condition
返回
示例
final result = await app.mysql.count(
table: 'users',
filters: {'age': 'gt.18'},
);
if (result.isSuccess) {
print('Data that meets the criteria: ${result.count}');
} else {
print('Statistics failed: ${result.message}');
}
Cloud Function
callFunction
Future<FunctionResponse> app.callFunction({
required String name,
FunctionType type,
Map<String, dynamic>? data,
HttpMethod method,
String path,
Map<String, String>? header,
bool parse,
})
Call SCF. Support unified calls for two types: basic cloud function and functional cloud hosting.
参数
Function/service name
Invocation type: FunctionType.function (default)/FunctionType.cloudrun
Request data
HTTP method (valid only for cloudrun type, default POST)
HTTP path (valid only for cloudrun type, default /)
HTTP request header (valid only for cloudrun type)
Whether to parse the return object (valid only for function type, default true)
返回
示例
final result = await app.callFunction(
name: 'myFunction',
data: {'action': 'getUserList', 'pageSize': 10},
);
if (result.isSuccess) {
print('Execution result: ${result.result}');
} else {
print('Execution failed: ${result.message}');
}
final result = await app.callFunction(
name: 'myService',
type: FunctionType.cloudrun,
method: HttpMethod.post,
path: '/api/users',
data: {'name': 'Zhang San'},
header: {'X-Custom-Header': 'value'},
);
if (result.isSuccess) {
print('Execution result: ${result.result}');
}
Cloud hosting
callContainer
Future<CloudRunResponse> app.callContainer({
required String name,
HttpMethod method,
String path,
Map<String, String>? header,
Map<String, dynamic>? data,
})
Call cloud managed TKE. Support customization of HTTP method, path and request header.
参数
Cloud hosting service name
HTTP request method (default GET)
HTTP request path (default /)
HTTP request header
HTTP request body
返回
示例
final result = await app.callContainer(
name: 'my-service',
method: HttpMethod.post,
path: '/api/data',
data: {'key': 'value'},
header: {'X-Custom': 'header'},
);
if (result.isSuccess) {
print('Response data: ${result.result}');
} else {
print('Request failure: ${result.message}');
}
APIs
apis[name]
ApiMethodProxy app.apis[String apiName]
Call the API Gateway API. Support obtaining the API proxy object through the subscript operator to perform chained calls. Support GET, POST, PUT, DELETE, HEAD, OPTIONS, and PATCH methods.
参数
API Name
返回
API method proxy object, supports chained calls
API response
示例
// POST request
final result = await app.apis['myApi'].post(
path: '/users',
body: {'name': 'Zhang San', 'age': 25},
);
if (result.isSuccess) {
print('Response data: ${result.data}');
}
// GET request
final getResult = await app.apis['myApi'].get(path: '/users/123');
// PUT request
final putResult = await app.apis['myApi'].put(
path: '/users/123',
body: {'name': 'Jerry'},
);
// DELETE request
final deleteResult = await app.apis['myApi'].delete(path: '/users/123');
final result = await app.apis.callApi(CallApiOptions(
name: 'myApi',
method: 'POST',
path: '/users',
body: {'name': 'test'},
headers: {'X-Custom': 'value'},
));
if (result.isSuccess) {
print('Response: ${result.data}');
}