Skip to main content

CloudBase Flutter

Pub Version

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.

Note

CloudBase Flutter SDK is fully aligned with HTTP API

SDKs are divided into the following categories by feature purpose:


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;

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.

参数

params
SignUpReq

返回

Future
SignUpRes

示例

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}');
}

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

参数

providerToken
String?

Third-party platform token, used for associating third-party platform identity

返回

Future
SignInRes

示例

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}');
}

signInWithPassword

Future<SignInRes> auth.signInWithPassword(SignInWithPasswordReq params)

Log in using password. Support through userName, mailbox or mobile number to log in.

参数

params
SignInWithPasswordReq

返回

Future
SignInRes

示例

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}');
}

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.

参数

params
SignInWithOtpReq

返回

Future
SignInWithOtpRes

示例

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.

参数

params
SignInWithOAuthReq

返回

Future
SignInOAuthRes

示例

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.

参数

params
SignInWithIdTokenReq

返回

Future
SignInRes

示例

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.

参数

getTicketFn
Future<String> Function()

Async function for custom login invoice retrieval

返回

Future
SignInRes

示例

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.

参数

无参数

返回

Future
SignInRes

示例

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.

参数

refreshToken
String?

Refresh token (optional, by default uses the refreshToken of the current session)

返回

Future
SignInRes

示例

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.

参数

params
SetSessionReq

返回

Future
SignInRes

示例

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.

参数

params
SignOutReq?

Logout configuration option (selectable)

返回

Future
SignOutRes

示例

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.

参数

callback
void Function(AuthStateChangeEvent, Session?, AuthStateChangeInfo?)

Status change callback function

返回

OnAuthStateChangeResult
OnAuthStateChangeResult

示例

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.

参数

无参数

返回

Future
GetClaimsRes

示例

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.

参数

无参数

返回

Future
GetUserRes

示例

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.

参数

无参数

返回

Future
SignInRes

示例

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.

参数

params
UpdateUserReq

返回

Future
UpdateUserRes

示例

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}');
}

deleteUser

Future<CloudBaseResponse<void>> auth.deleteUser(DeleteUserReq params)

Delete the current user. Password is required for security verification.

参数

params
DeleteUserReq

返回

Future
CloudBaseResponse<void>

示例

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.

参数

无参数

返回

Future
GetUserIdentitiesRes

示例

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.

参数

params
LinkIdentityReq

返回

Future
LinkIdentityRes

示例

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.

参数

params
UnlinkIdentityReq

返回

Future
CloudBaseResponse<void>

示例

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.

参数

emailOrPhone
String

mailbox or mobile number

redirectTo
String?

redirect address

返回

Future
ResetPasswordForEmailRes

示例

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.

参数

params
ResetPasswordForOldReq

返回

Future
SignInRes

示例

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.

参数

无参数

返回

Future
ReauthenticateRes

示例

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.

参数

email
String?

mailbox (choose either mailbox or phoneNumber)

phoneNumber
String?

mobile number (choose either mobile number or email)

返回

Future
CloudBaseResponse<GetVerificationResData>

示例

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.

参数

verificationId
String

verification ID

verificationCode
String

Captcha

返回

Future
CloudBaseResponse<VerifyCodeResData>

示例

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.

参数

params
VerifyOtpReq

返回

Future
SignInRes

示例

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.

参数

params
ResendReq

返回

Future
ResendRes

示例

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.

参数

forceNew
bool

Whether to force creating a new Captcha (default false)

state
String

Status identifier

返回

Future
String?

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');

createCaptchaData

Future<CreateCaptchaDataRes> app.captcha.createCaptchaData({required String state})

Create Captcha data. Return image data and Token.

参数

state
String

Status identifier

返回

Future
CreateCaptchaDataRes

示例

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.

参数

token
String

Captcha Token

key
String

user input verification code

返回

Future
VerifyCaptchaRes

示例

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.

参数

无参数

返回

Future
void

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.

参数

modelName
String

data model flag

recordId
String

Data ID

返回

Future
ModelFindResponse

示例

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.

参数

modelName
String

data model flag

filter
Map<String, dynamic>?

Filter criteria, format: {'where': {'_id': {'\$eq': 'foobar'}}}

select
Map<String, dynamic>?

Field filtering, format: {'\$master': true} or {'field': true}

返回

Future
ModelFindResponse

示例

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.

参数

modelName
String

data model flag

filter
Map<String, dynamic>?

Filter criteria, format: {'where': {'field': {'\$eq': 'value'}}}

select
Map<String, dynamic>?

Field filtering, format: {'\$master': true} or {'field': true}

pageSize
int?

Page size. Default 10

pageNumber
int?

Page number. Default 1

getCount
bool?

Whether to return the total count

orderBy
List<Map<String, String>>?

Sorting order, up to 3 fields, format: [{'field': 'desc'}]

返回

Future
ModelFindManyResponse

示例

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).

参数

modelName
String

data model flag

pageSize
int?

Page size

pageNumber
int?

Page number. Default 1

getCount
bool?

Whether to return the total count (default false)

返回

Future
ModelFindManyResponse

示例

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.

参数

modelName
String

data model flag

data
Map<String, dynamic>

data content

返回

Future
ModelCreateResponse

示例

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.

参数

modelName
String

data model flag

data
List<Map<String, dynamic>>

Batch data list

返回

Future
ModelCreateManyResponse

示例

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.

参数

modelName
String

data model flag

filter
Map<String, dynamic>

filtering condition

data
Map<String, dynamic>

update data

返回

Future
ModelUpdateDeleteResponse

示例

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.

参数

modelName
String

data model flag

filter
Map<String, dynamic>

filtering condition

data
Map<String, dynamic>

update data

返回

Future
ModelUpdateDeleteManyResponse

示例

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.

参数

modelName
String

data model flag

filter
Map<String, dynamic>

filtering condition

create
Map<String, dynamic>?

Data content created if does not exist

update
Map<String, dynamic>?

Data content updated if exists

返回

Future
ModelUpsertResponse

示例

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.

参数

modelName
String

data model flag

recordId
String

Data ID

返回

Future
ModelUpdateDeleteResponse

示例

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.

参数

modelName
String

data model flag

filter
Map<String, dynamic>

filtering condition

返回

Future
ModelUpdateDeleteResponse

示例

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.

参数

modelName
String

data model flag

filter
Map<String, dynamic>

filtering condition

返回

Future
ModelUpdateDeleteManyResponse

示例

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.

参数

sqlTemplate
String

SQL statement, supports parameter placeholder {{ var }}

parameter
List<ModelMysqlParameter>?

SQL parameter list

config
ModelMysqlConfig?

Execution configuration (timeout, preparedStatements, dbLinkName)

返回

Future
ModelMysqlCommandResponse

示例

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.

参数

pageSize
int

Entries per page

envId
String?

Environment ID (selectable, by default using the initial env)

pageIndex
int?

Page number

queryAll
int?

Query all (0 or 1)

dataSourceIds
List<String>?

Data source ID list

dataSourceNames
List<String>?

Data source name list

dataSourceType
String?

Data source type

queryBindToApp
int?

Query data sources bound to the application (0 or 1)

queryConnector
int?

Query connectors (0 or 1)

querySystemModel
bool?

Query system model

返回

Future
AggregateDataSourceListResponse

示例

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.

参数

datasourceId
String?

Data source ID (cannot both be empty with dataSourceName)

dataSourceName
String?

Data source name (cannot both be empty with datasourceId)

viewId
String?

view ID

queryPublish
int?

Query published data sources (0 trial, 1 publish)

queryModelRelation
bool?

Whether to query association relationships

dbInstanceType
String?

DB type of the instance

databaseTableName
String?

Database table name

返回

Future
DataSourceAggregateDetailResponse

示例

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.

参数

tableNames
List<String>

Data table name list

返回

Future
DataSourceByTableNameResponse

示例

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).

参数

idList
List<String>?

Data source ID list

nameList
List<String>?

Data source identifier list

pageNum
int?

Page number. Default 1

pageSize
int?

Entries per page. Default 10

queryAll
bool?

Query all

queryFilterList
List<DataSourceQueryFilter>?

Query filter condition list

onlyFlexDb
bool?

Query flexdb type only

返回

Future
BasicDataSourceListResponse

示例

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.

参数

datasourceId
String?

Data source ID (cannot both be empty with dataSourceName)

dataSourceName
String?

Data source name (cannot both be empty with datasourceId)

viewId
String?

view ID

queryPublish
int?

Query published data sources (0 trial, 1 publish)

queryModelRelation
bool?

Whether to query association relationships

dbInstanceType
String?

DB type of the instance

databaseTableName
String?

Database table name

返回

Future
BasicDataSourceResponse

示例

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.

参数

dataSourceNameList
List<String>?

Data source name list (optional, query all if not provided)

返回

Future
DataSourceSchemaListResponse

示例

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.

参数

dataSourceName
String?

Data source name

返回

Future
DataSourceTableNameResponse

示例

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
String

Table name

schema
String?

Database name

instance
String?

Database instance flag (requires collocation with schema)

options
MySqlQueryOptions?

Query option

返回

Future
MySqlResponse

示例

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');
}
}

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
String

Table name

data
dynamic

Insert data, single Map or batch List<Map>

upsert
bool

Whether Upsert Mode is enabled (false by default)

onConflict
String?

Upsert conflict field

返回

Future
MySqlWriteResponse

示例

final result = await app.mysql.insert(
table: 'users',
data: {'name': 'Zhang San', 'age': 25},
);

if (result.isSuccess) {
print('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
String

Table name

data
Map<String, dynamic>

data to be updated

filters
Map<String, String>

WHERE condition (cannot be empty)

返回

Future
MySqlWriteResponse

示例

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
String

Table name

filters
Map<String, String>

WHERE condition (cannot be empty)

返回

Future
MySqlWriteResponse

示例

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
String

Table name

filters
Map<String, String>?

filtering condition

返回

Future
MySqlCountResponse

示例

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.

参数

name
String

Function/service name

type
FunctionType

Invocation type: FunctionType.function (default)/FunctionType.cloudrun

data
Map<String, dynamic>?

Request data

method
HttpMethod

HTTP method (valid only for cloudrun type, default POST)

path
String

HTTP path (valid only for cloudrun type, default /)

header
Map<String, String>?

HTTP request header (valid only for cloudrun type)

parse
bool

Whether to parse the return object (valid only for function type, default true)

返回

Future
FunctionResponse

示例

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}');
}

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.

参数

name
String

Cloud hosting service name

method
HttpMethod

HTTP request method (default GET)

path
String

HTTP request path (default /)

header
Map<String, String>?

HTTP request header

data
Map<String, dynamic>?

HTTP request body

返回

Future
CloudRunResponse

示例

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.

参数

apiName
String

API Name

返回

ApiMethodProxy
ApiMethodProxy

API method proxy object, supports chained calls

ApiResponse
ApiResponse

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');