跳到主要内容

CloudBase Flutter

Pub Version

CloudBase Flutter SDK 让您可以在 Flutter 应用中使用云开发的能力,包括身份认证、数据模型、MySQL 数据库、云函数、云托管、APIs 等功能,使用方式请参考CloudBase Flutter SDK,也可以参考示例代码

提示

CloudBase Flutter SDK 已与 HTTP API 全面对齐

SDK 按照功能用途分为以下类别:

  • 认证登录:用户注册和登录相关的 API 方法,支持多种登录方式。
  • 会话管理:管理用户会话状态和令牌的 API 方法。
  • 用户管理:获取、更新和管理用户信息的 API 方法。
  • 身份源管理:管理第三方身份源绑定和解绑的 API 方法。
  • 密码管理:密码重置和修改相关的 API 方法。
  • 验证管理:验证码发送、验证和重发、图形验证码创建、验证和管理相关的 API 方法。
  • 数据模型:数据模型 CRUD 操作。
  • 数据源查询:查询数据源聚合列表、详情、Schema 和表名。
  • MySQL 数据库:MySQL RESTful 数据库操作。
  • 云函数:调用云函数和函数型云托管。
  • 云托管:调用云托管容器服务。
  • APIs:调用 APIs 接口。

基础使用示例

accessKey 可前往 云开发平台/API Key 配置 中生成

import 'package:cloudbase_flutter/cloudbase_flutter.dart';

// 初始化(异步)
final app = await CloudBase.init(
env: 'your-env-id', // 替换为您的环境ID
region: 'ap-shanghai', // 地域,默认为上海
accessKey: 'your-key', // 填入生成的 Publishable Key
authConfig: AuthConfig(
detectSessionInUrl: true, // 可选:自动检测 URL 中的 OAuth 参数
),
);

final auth = app.auth;

认证登录

signUp

Future<SignUpRes> auth.signUp(SignUpReq params)

注册新用户账户,采用智能注册并登录流程。

  • 创建一个新的用户账户
  • 采用智能注册并登录流程:发送验证码 → 等待用户输入 → 智能判断用户存在性 → 自动登录或注册并登录
  • 如果用户已存在则直接登录,如果用户不存在则注册新用户并自动登录

参数

params
SignUpReq

返回

Future
SignUpRes

示例

final result = await auth.signUp(SignUpReq(
email: 'user@example.com',
password: 'securePassword123',
nickname: '新用户',
));

if (result.error != null) {
print('注册失败: ${result.error!.message}');
return;
}

// 验证码验证
final verifyResult = await result.data!.verifyOtp!(
VerifyOtpParams(token: '123456'),
);

if (verifyResult.isSuccess) {
print('注册成功: ${verifyResult.data?.user?.id}');
}

signInAnonymously

Future<SignInRes> auth.signInAnonymously({String? providerToken})

匿名登录,创建一个临时匿名用户账户。

  • 创建一个临时匿名用户账户
  • 无需提供任何身份验证信息
  • 适合需要临时访问权限的场景

参数

providerToken
String?

第三方平台令牌,用于关联第三方平台身份

返回

Future
SignInRes

示例

final result = await auth.signInAnonymously();

if (result.isSuccess) {
print('匿名登录成功');
print('用户ID: ${result.data?.user?.id}');
print('是否匿名: ${result.data?.user?.isAnonymous}');
} else {
print('匿名登录失败: ${result.error!.message}');
}

signInWithPassword

Future<SignInRes> auth.signInWithPassword(SignInWithPasswordReq params)

使用密码登录。支持通过用户名、邮箱或手机号进行登录。

参数

params
SignInWithPasswordReq

返回

Future
SignInRes

示例

final result = await auth.signInWithPassword(
SignInWithPasswordReq(
email: 'user@example.com',
password: 'securePassword123',
),
);

if (result.isSuccess) {
print('登录成功: ${result.data?.user?.id}');
} else {
print('登录失败: ${result.error!.message}');
}

signInWithOtp

Future<SignInWithOtpRes> auth.signInWithOtp(SignInWithOtpReq params)

使用 OTP(一次性验证码)登录。调用后发送验证码,需通过返回的 verifyOtp 回调完成验证。

参数

params
SignInWithOtpReq

返回

Future
SignInWithOtpRes

示例

final result = await auth.signInWithOtp(
SignInWithOtpReq(email: 'user@example.com'),
);

if (result.error != null) {
print('发送验证码失败: ${result.error!.message}');
return;
}

// 用户输入验证码后调用
final loginResult = await result.data!.verifyOtp!(
VerifyOtpParams(token: '123456'),
);

if (loginResult.isSuccess) {
print('OTP 登录成功: ${loginResult.data?.user?.id}');
}

signInWithOAuth

Future<SignInOAuthRes> auth.signInWithOAuth(SignInWithOAuthReq params)

使用 OAuth 第三方平台登录。返回授权 URL,需引导用户跳转至该 URL 完成授权。

参数

params
SignInWithOAuthReq

返回

Future
SignInOAuthRes

示例

final result = await auth.signInWithOAuth(
SignInWithOAuthReq(provider: 'wechat'),
);

if (result.isSuccess) {
final authUrl = result.data!.url!;
print('请跳转到授权页面: $authUrl');
// 引导用户打开 authUrl 进行授权
}

signInWithIdToken

Future<SignInRes> auth.signInWithIdToken(SignInWithIdTokenReq params)

使用 IdToken 登录。适用于已获取第三方平台令牌的场景。

参数

params
SignInWithIdTokenReq

返回

Future
SignInRes

示例

final result = await auth.signInWithIdToken(
SignInWithIdTokenReq(
token: 'provider-id-token',
provider: 'wechat',
),
);

if (result.isSuccess) {
print('IdToken 登录成功: ${result.data?.user?.id}');
} else {
print('登录失败: ${result.error!.message}');
}

signInWithCustomTicket

Future<SignInRes> auth.signInWithCustomTicket(Future<String> Function() getTicketFn)

使用自定义票据登录。通过传入获取票据的异步函数,由服务端生成票据并完成登录。

参数

getTicketFn
Future<String> Function()

获取自定义登录票据的异步函数

返回

Future
SignInRes

示例

final result = await auth.signInWithCustomTicket(() async {
// 从您的服务端获取自定义票据
final ticket = await fetchTicketFromServer();
return ticket;
});

if (result.isSuccess) {
print('自定义票据登录成功: ${result.data?.user?.id}');
} else {
print('登录失败: ${result.error!.message}');
}

会话管理

getSession

Future < SignInRes > auth.getSession();

获取当前会话。如果 Token 已过期会自动刷新。

参数

无参数

返回

Future
SignInRes

示例

final result = await auth.getSession();

if (result.isSuccess) {
final session = result.data?.session;
print('Access Token: ${session?.accessToken}');
print('用户: ${result.data?.user?.id}');
} else {
print('获取会话失败: ${result.error!.message}');
}

refreshSession

Future<SignInRes> auth.refreshSession([String? refreshToken])

刷新会话。使用 Refresh Token 获取新的 Access Token。

参数

refreshToken
String?

刷新令牌(可选,默认使用当前会话的 refreshToken)

返回

Future
SignInRes

示例

final result = await auth.refreshSession();

if (result.isSuccess) {
print('会话已刷新');
print('新 Access Token: ${result.data?.session?.accessToken}');
} else {
print('刷新失败: ${result.error!.message}');
}

setSession

Future<SignInRes> auth.setSession(SetSessionReq params)

设置会话。通过 Refresh Token 恢复会话状态。

参数

params
SetSessionReq

返回

Future
SignInRes

示例

final result = await auth.setSession(
SetSessionReq(refreshToken: 'your-refresh-token'),
);

if (result.isSuccess) {
print('会话设置成功: ${result.data?.user?.id}');
}

signOut

Future<SignOutRes> auth.signOut([SignOutReq? params])

退出登录。清除本地会话并通知服务端吊销令牌。

参数

params
SignOutReq?

登出配置选项(可选)

返回

Future
SignOutRes

示例

await auth.signOut();
print("已退出登录");

onAuthStateChange

OnAuthStateChangeResult auth.onAuthStateChange(OnAuthStateChangeCallback callback)

监听认证状态变化。支持监听登录、登出、Token 刷新和用户更新等事件。

参数

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

状态变化回调函数

返回

OnAuthStateChangeResult
OnAuthStateChangeResult

示例

final result = auth.onAuthStateChange((event, session, info) {
print('认证状态变化: ${event.value}');
if (session != null) {
print('用户: ${session.user?.id}');
}
});

// 取消监听
result.data?.subscription.unsubscribe();

getClaims

Future < GetClaimsRes > auth.getClaims();

获取当前 Access Token 的 JWT Claims(令牌声明)。

参数

无参数

返回

Future
GetClaimsRes

示例

final result = await auth.getClaims();

if (result.isSuccess) {
final claims = result.data?.claims;
print('用户ID: ${claims?.sub}');
print('邮箱: ${claims?.email}');
print('用户组: ${claims?.groups}');
print('过期时间: ${claims?.exp}');
}

用户管理

getUser

Future < GetUserRes > auth.getUser();

获取当前登录用户信息。

参数

无参数

返回

Future
GetUserRes

示例

final result = await auth.getUser();

if (result.isSuccess) {
final user = result.data?.user;
print('用户ID: ${user?.id}');
print('邮箱: ${user?.id}');
print('昵称: ${user?.userMetadata?.nickName}');
} else {
print('获取用户信息失败: ${result.error!.message}');
}

refreshUser

Future < SignInRes > auth.refreshUser();

刷新用户信息。重新从服务端获取最新的用户数据并更新本地会话。

参数

无参数

返回

Future
SignInRes

示例

final result = await auth.refreshUser();

if (result.isSuccess) {
print('用户信息已刷新: ${result.data?.user?.id}');
}

updateUser

Future<UpdateUserRes> auth.updateUser(UpdateUserReq params)

更新用户信息。如果更新邮箱或手机号,需要通过验证码验证。

参数

params
UpdateUserReq

返回

Future
UpdateUserRes

示例

final result = await auth.updateUser(
UpdateUserReq(nickname: '新昵称', avatarUrl: 'https://example.com/avatar.png'),
);

if (result.isSuccess) {
print('用户信息已更新: ${result.data?.user?.userMetadata?.nickName}');
}

deleteUser

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

删除当前用户。需要提供密码进行安全验证。

参数

params
DeleteUserReq

返回

Future
CloudBaseResponse<void>

示例

final result = await auth.deleteUser(
DeleteUserReq(password: 'currentPassword'),
);

if (result.isSuccess) {
print('用户已删除');
} else {
print('删除失败: ${result.error!.message}');
}

身份源管理

getUserIdentities

Future < GetUserIdentitiesRes > auth.getUserIdentities();

获取当前用户已绑定的身份源列表。

参数

无参数

返回

Future
GetUserIdentitiesRes

示例

final result = await auth.getUserIdentities();

if (result.isSuccess) {
for (final identity in result.data?.identities ?? []) {
print('身份源: ${identity.name} (${identity.provider})');
}
}

linkIdentity

Future<LinkIdentityRes> auth.linkIdentity(LinkIdentityReq params)

绑定第三方身份源。会跳转到第三方授权页面完成绑定。

参数

params
LinkIdentityReq

返回

Future
LinkIdentityRes

示例

final result = await auth.linkIdentity(
LinkIdentityReq(provider: 'wechat'),
);

if (result.isSuccess) {
print('身份源绑定成功: ${result.data?.provider}');
}

unlinkIdentity

Future<CloudBaseResponse<void>> auth.unlinkIdentity(UnlinkIdentityReq params)

解绑第三方身份源。

参数

params
UnlinkIdentityReq

返回

Future
CloudBaseResponse<void>

示例

final result = await auth.unlinkIdentity(
UnlinkIdentityReq(provider: 'wechat'),
);

if (result.isSuccess) {
print('身份源已解绑');
}

密码管理

resetPasswordForEmail

Future<ResetPasswordForEmailRes> auth.resetPasswordForEmail(String emailOrPhone, {String? redirectTo})

通过邮箱或手机号重置密码。调用后发送验证码,需通过返回的 updateUser 回调完成密码重置。

参数

emailOrPhone
String

邮箱或手机号

redirectTo
String?

重定向地址

返回

Future
ResetPasswordForEmailRes

示例

final result = await auth.resetPasswordForEmail('user@example.com');

if (result.error != null) {
print('发送验证码失败: ${result.error!.message}');
return;
}

// 用户收到验证码后
final resetResult = await result.data!.updateUser!(
UpdateUserAttributes(nonce: '123456', password: 'newPassword123'),
);

if (resetResult.isSuccess) {
print('密码重置成功,已自动登录');
}

resetPasswordForOld

Future<SignInRes> auth.resetPasswordForOld(ResetPasswordForOldReq params)

通过旧密码重置密码。

参数

params
ResetPasswordForOldReq

返回

Future
SignInRes

示例

final result = await auth.resetPasswordForOld(
ResetPasswordForOldReq(
oldPassword: 'oldPassword123',
newPassword: 'newPassword456',
),
);

if (result.isSuccess) {
print('密码修改成功');
} else {
print('密码修改失败: ${result.error!.message}');
}

reauthenticate

Future < ReauthenticateRes > auth.reauthenticate();

重新认证。发送验证码到用户邮箱或手机号,验证后可进行敏感操作(如设置新密码)。

参数

无参数

返回

Future
ReauthenticateRes

示例

final result = await auth.reauthenticate();

if (result.error != null) {
print('发送验证码失败: ${result.error!.message}');
return;
}

final authResult = await result.data!.updateUser!(
UpdateUserAttributes(nonce: '123456', password: 'newSecurePassword'),
);

if (authResult.isSuccess) {
print('重新认证成功');
}

验证管理

getVerification

Future<CloudBaseResponse<GetVerificationResData>> auth.getVerification({String? email, String? phoneNumber})

发送验证码到邮箱或手机号。

参数

email
String?

邮箱(与 phoneNumber 二选一)

phoneNumber
String?

手机号(与 email 二选一)

返回

Future
CloudBaseResponse<GetVerificationResData>

示例

final result = await auth.getVerification(email: 'user@example.com');

if (result.isSuccess) {
print('验证码已发送,验证ID: ${result.data?.verificationId}');
print('是否已注册用户: ${result.data?.isUser}');
}

verify

Future<CloudBaseResponse<VerifyCodeResData>> auth.verify({required String verificationId, required String verificationCode})

验证验证码。

参数

verificationId
String

验证 ID

verificationCode
String

验证码

返回

Future
CloudBaseResponse<VerifyCodeResData>

示例

final result = await auth.verify(
verificationId: 'verification-id',
verificationCode: '123456',
);

if (result.isSuccess) {
print('验证成功,令牌: ${result.data?.verificationToken}');
}

verifyOtp

Future<SignInRes> auth.verifyOtp(VerifyOtpReq params)

验证 OTP 并登录。

参数

params
VerifyOtpReq

返回

Future
SignInRes

示例

final result = await auth.verifyOtp(VerifyOtpReq(
email: 'user@example.com',
token: '123456',
messageId: 'message-id',
));

if (result.isSuccess) {
print('验证并登录成功: ${result.data?.user?.id}');
}

resend

Future<ResendRes> auth.resend(ResendReq params)

重发验证码。

参数

params
ResendReq

返回

Future
ResendRes

示例

final result = await auth.resend(
ResendReq(email: 'user@example.com', type: ResendType.signup),
);

if (result.isSuccess) {
print('验证码已重发,消息ID: ${result.data?.messageId}');
}

getCaptchaToken

Future<String?> app.captcha.getCaptchaToken({bool forceNew, required String state})

获取有效的验证码 Token,在多次出现密码输入错误或频繁发送验证码时会要求提供验证码 Token。优先从缓存获取,若无缓存则自动创建验证码并弹出验证界面。支持自定义验证码处理器或使用内置弹窗。

参数

forceNew
bool

是否强制创建新验证码(默认 false)

state
String

状态标识

返回

Future
String?

验证码 Token,失败时为 null

示例

// 初始化时配置 navigatorKey
final navigatorKey = GlobalKey<NavigatorState>();

final app = await CloudBase.init(
env: 'your-env-id',
captchaConfig: CaptchaConfig(navigatorKey: navigatorKey),
);

// 获取验证码 Token(自动弹出验证码弹窗)
final token = await app.captcha.getCaptchaToken(state: 'login');
print('Captcha Token: $token');

createCaptchaData

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

创建验证码数据。返回验证码图片数据和 Token。

参数

state
String

状态标识

返回

Future
CreateCaptchaDataRes

示例

final captchaData = await app.captcha.createCaptchaData(state: 'login');
print('验证码图片: ${captchaData.data}');
print('Token: ${captchaData.token}');

verifyCaptchaData

Future<VerifyCaptchaRes> app.captcha.verifyCaptchaData({required String token, required String key})

验证用户输入的验证码。

参数

token
String

验证码 Token

key
String

用户输入的验证码

返回

Future
VerifyCaptchaRes

示例

final result = await app.captcha.verifyCaptchaData(
token: captchaData.token,
key: '用户输入的验证码',
);
print('验证码 Token: ${result.captchaToken}');

clearCaptchaToken

Future<void> app.captcha.clearCaptchaToken()

清除本地缓存的验证码 Token。

参数

无参数

返回

Future
void

无返回值

示例

await app.captcha.clearCaptchaToken();
print("验证码 Token 已清除");

数据模型

getById

Future<ModelFindResponse> app.models.getById({required String modelName, required String recordId})

根据 ID 获取单条数据。

参数

modelName
String

数据模型标识

recordId
String

数据 ID

返回

Future
ModelFindResponse

示例

final result = await app.models.getById(
modelName: 'user',
recordId: '123',
);

if (result.isSuccess) {
print('记录: ${result.record}');
} else {
print('查询失败: ${result.message}');
}

get

Future<ModelFindResponse> app.models.get({required String modelName, Map<String, dynamic>? filter, Map<String, dynamic>? select})

根据条件获取单条数据。

参数

modelName
String

数据模型标识

filter
Map<String, dynamic>?

筛选条件,格式:{'where': {'_id': {'\$eq': 'foobar'}}}

select
Map<String, dynamic>?

字段筛选,格式:{'\$master': true} 或 {'field': true}

返回

Future
ModelFindResponse

示例

final result = await app.models.get(
modelName: 'user',
filter: {'where': {'_id': {'\$eq': '123'}}},
select: {'\$master': true},
);

if (result.isSuccess) {
print('记录: ${result.record}');
} else {
print('查询失败: ${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,
})

查询多条数据。支持筛选条件、字段筛选、分页和排序。

参数

modelName
String

数据模型标识

filter
Map<String, dynamic>?

筛选条件,格式:{'where': {'field': {'\$eq': 'value'}}}

select
Map<String, dynamic>?

字段筛选,格式:{'\$master': true} 或 {'field': true}

pageSize
int?

分页大小,默认 10

pageNumber
int?

分页页码,默认 1

getCount
bool?

是否返回总数

orderBy
List<Map<String, String>>?

排序,最多 3 个字段,格式:[{'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('总数: ${result.total}');
for (final record in result.records) {
print('记录: $record');
}
}

listSimple

Future<ModelFindManyResponse> app.models.listSimple({required String modelName, int? pageSize, int? pageNumber, bool? getCount})

简单查询多条数据(GET 请求,仅支持分页参数)。

参数

modelName
String

数据模型标识

pageSize
int?

分页大小

pageNumber
int?

分页页码,默认 1

getCount
bool?

是否返回总数,默认 false

返回

Future
ModelFindManyResponse

示例

final result = await app.models.listSimple(
modelName: 'user',
pageSize: 10,
pageNumber: 1,
getCount: true,
);

if (result.isSuccess) {
print('总数: ${result.total}');
for (final record in result.records) {
print('记录: $record');
}
}

create

Future<ModelCreateResponse> app.models.create({required String modelName, required Map<String, dynamic> data})

创建单条数据。

参数

modelName
String

数据模型标识

data
Map<String, dynamic>

数据内容

返回

Future
ModelCreateResponse

示例

final result = await app.models.create(
modelName: 'user',
data: {'name': '张三', 'age': 25, 'email': 'test@example.com'},
);

if (result.isSuccess) {
print('创建成功,ID: ${result.id}');
} else {
print('创建失败: ${result.message}');
}

createMany

Future<ModelCreateManyResponse> app.models.createMany({required String modelName, required List<Map<String, dynamic>> data})

批量创建数据。

参数

modelName
String

数据模型标识

data
List<Map<String, dynamic>>

批量数据列表

返回

Future
ModelCreateManyResponse

示例

final result = await app.models.createMany(
modelName: 'user',
data: [
{'name': '张三', 'age': 25},
{'name': '李四', 'age': 30},
],
);

if (result.isSuccess) {
print('批量创建成功,ID 列表: ${result.idList}');
}

update

Future<ModelUpdateDeleteResponse> app.models.update({required String modelName, required Map<String, dynamic> filter, required Map<String, dynamic> data})

更新单条数据。

参数

modelName
String

数据模型标识

filter
Map<String, dynamic>

筛选条件

data
Map<String, dynamic>

更新数据

返回

Future
ModelUpdateDeleteResponse

示例

final result = await app.models.update(
modelName: 'user',
filter: {'where': {'_id': {'\$eq': '123'}}},
data: {'age': 26},
);

if (result.isSuccess) {
print('更新成功,变更 ${result.count} 条');
}

updateMany

Future<ModelUpdateDeleteManyResponse> app.models.updateMany({required String modelName, required Map<String, dynamic> filter, required Map<String, dynamic> data})

批量更新数据。

参数

modelName
String

数据模型标识

filter
Map<String, dynamic>

筛选条件

data
Map<String, dynamic>

更新数据

返回

Future
ModelUpdateDeleteManyResponse

示例

final result = await app.models.updateMany(
modelName: 'user',
filter: {'where': {'age': {'\$lt': 18}}},
data: {'status': 'minor'},
);

if (result.isSuccess) {
print('批量更新成功,变更 ${result.count} 条');
}

upsert

Future<ModelUpsertResponse> app.models.upsert({required String modelName, required Map<String, dynamic> filter, Map<String, dynamic>? create, Map<String, dynamic>? update})

创建或更新单条数据(Upsert)。如果匹配到已有记录则更新,否则创建新记录。

参数

modelName
String

数据模型标识

filter
Map<String, dynamic>

筛选条件

create
Map<String, dynamic>?

不存在时创建的数据内容

update
Map<String, dynamic>?

已存在时更新的数据内容

返回

Future
ModelUpsertResponse

示例

final result = await app.models.upsert(
modelName: 'user',
filter: {'where': {'email': {'\$eq': 'test@example.com'}}},
create: {'name': '张三', 'email': 'test@example.com', 'age': 25},
update: {'age': 26},
);

if (result.isSuccess) {
print('Upsert 成功,变更 ${result.count} 条');
if (result.id != null) {
print('新创建记录 ID: ${result.id}');
}
}

deleteById

Future<ModelUpdateDeleteResponse> app.models.deleteById({required String modelName, required String recordId})

根据 ID 删除单条数据。

参数

modelName
String

数据模型标识

recordId
String

数据 ID

返回

Future
ModelUpdateDeleteResponse

示例

final result = await app.models.deleteById(
modelName: 'user',
recordId: '123',
);

if (result.isSuccess) {
print('删除成功,变更 ${result.count} 条');
}

deleteRecord

Future<ModelUpdateDeleteResponse> app.models.deleteRecord({required String modelName, required Map<String, dynamic> filter})

根据条件删除单条数据。

参数

modelName
String

数据模型标识

filter
Map<String, dynamic>

筛选条件

返回

Future
ModelUpdateDeleteResponse

示例

final result = await app.models.deleteRecord(
modelName: 'user',
filter: {'where': {'_id': {'\$eq': '123'}}},
);

if (result.isSuccess) {
print('删除成功,变更 ${result.count} 条');
}

deleteMany

Future<ModelUpdateDeleteManyResponse> app.models.deleteMany({required String modelName, required Map<String, dynamic> filter})

批量删除数据。

参数

modelName
String

数据模型标识

filter
Map<String, dynamic>

筛选条件

返回

Future
ModelUpdateDeleteManyResponse

示例

final result = await app.models.deleteMany(
modelName: 'user',
filter: {'where': {'status': {'\$eq': 'inactive'}}},
);

if (result.isSuccess) {
print('批量删除成功,变更 ${result.count} 条');
}

mysqlCommand

Future<ModelMysqlCommandResponse> app.models.mysqlCommand({required String sqlTemplate, List<ModelMysqlParameter>? parameter, ModelMysqlConfig? config})

执行 MySQL 命令。支持参数化查询。

参数

sqlTemplate
String

SQL 语句,支持参数占位符 {{ var }}

parameter
List<ModelMysqlParameter>?

SQL 参数列表

config
ModelMysqlConfig?

执行配置(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('执行结果: ${result.executeResultList}');
}

数据源查询

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,
})

根据条件查询数据源聚合列表。envId 可选,默认使用初始化时的环境 ID。

参数

pageSize
int

每页条数

envId
String?

环境 ID(可选,默认使用初始化时的 env)

pageIndex
int?

页码

queryAll
int?

是否查询全部(0 或 1)

dataSourceIds
List<String>?

数据源 ID 列表

dataSourceNames
List<String>?

数据源名称列表

dataSourceType
String?

数据源类型

queryBindToApp
int?

是否查询绑定到应用的数据源(0 或 1)

queryConnector
int?

是否查询连接器(0 或 1)

querySystemModel
bool?

是否查询系统模型

返回

Future
AggregateDataSourceListResponse

示例

final result = await app.models.getAggregateDataSourceList(
pageSize: 10,
pageIndex: 0,
);

if (result.isSuccess) {
print('总数: ${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,
})

根据条件查询数据源聚合详情。datasourceIddataSourceName 不能都为空。

参数

datasourceId
String?

数据源 ID(与 dataSourceName 不能都为空)

dataSourceName
String?

数据源名称(与 datasourceId 不能都为空)

viewId
String?

视图 ID

queryPublish
int?

查询发布数据源(0 体验, 1 发布)

queryModelRelation
bool?

是否查询关联关系

dbInstanceType
String?

实例 DB 类型

databaseTableName
String?

数据库表名

返回

Future
DataSourceAggregateDetailResponse

示例

final result = await app.models.getDataSourceAggregateDetail(
dataSourceName: 'user',
);

if (result.isSuccess) {
print('Schema: ${result.dataSource?.schema}');
print('名称: ${result.dataSource?.title}');
}

getDataSourceByTableName

Future<DataSourceByTableNameResponse> app.models.getDataSourceByTableName({required List<String> tableNames})

根据数据库表名称查询数据源 Schema 定义。

参数

tableNames
List<String>

数据表名称列表

返回

Future
DataSourceByTableNameResponse

示例

final result = await app.models.getDataSourceByTableName(
tableNames: ['user_table', 'order_table'],
);

if (result.isSuccess) {
for (final info in result.dataSourceTableInfos) {
print('表: ${info.tableName}, 数据源: ${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,
})

根据条件查询基础数据源信息列表(POST 请求,支持过滤条件)。

参数

idList
List<String>?

数据源 ID 列表

nameList
List<String>?

数据源标识列表

pageNum
int?

页码,默认 1

pageSize
int?

每页条数,默认 10

queryAll
bool?

是否查询全部

queryFilterList
List<DataSourceQueryFilter>?

查询过滤条件列表

onlyFlexDb
bool?

是否仅查询 flexdb 类型

返回

Future
BasicDataSourceListResponse

示例

final result = await app.models.getBasicDataSourceList(
pageSize: 10,
pageNum: 1,
queryFilterList: [
DataSourceQueryFilter(name: 'Type', values: ['database']),
],
);

if (result.isSuccess) {
print('总数: ${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,
})

根据条件查询基础数据源信息。datasourceIddataSourceName 不能都为空。

参数

datasourceId
String?

数据源 ID(与 dataSourceName 不能都为空)

dataSourceName
String?

数据源名称(与 datasourceId 不能都为空)

viewId
String?

视图 ID

queryPublish
int?

查询发布数据源(0 体验, 1 发布)

queryModelRelation
bool?

是否查询关联关系

dbInstanceType
String?

实例 DB 类型

databaseTableName
String?

数据库表名

返回

Future
BasicDataSourceResponse

示例

final result = await app.models.getBasicDataSource(
dataSourceName: 'user',
);

if (result.isSuccess) {
print('数据源: ${result.dataSource?.name}');
print('类型: ${result.dataSource?.type}');
}

getSchemaList

Future<DataSourceSchemaListResponse> app.models.getSchemaList({List<String>? dataSourceNameList})

查询环境下所有数据源 Schema。不传参数则查询全部。

参数

dataSourceNameList
List<String>?

数据源名称列表(可选,不传则查询全部)

返回

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

根据数据源名称查询对应的数据库表名称。

参数

dataSourceName
String?

数据源名称

返回

Future
DataSourceTableNameResponse

示例

final result = await app.models.getTableName(
dataSourceName: 'user',
);

if (result.isSuccess) {
print('表名: ${result.tableName}');
print('数据库类型: ${result.dbType}');
}

MySQL 数据库

query

Future<MySqlResponse> app.mysql.query({required String table, String? schema, String? instance, MySqlQueryOptions? options})

查询 MySQL 数据。支持字段筛选、分页、排序和条件过滤。

支持的过滤运算符:eq(等于)、neq(不等于)、gt(大于)、gte(大于等于)、lt(小于)、lte(小于等于)、like(模糊匹配)、in(在列表中)、is(判断 null)

参数

table
String

表名

schema
String?

数据库名

instance
String?

数据库实例标识(需搭配 schema)

options
MySqlQueryOptions?

查询选项

返回

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('总数: ${result.total}');
for (final row in result.data) {
print('记录: $row');
}
}

insert

Future<MySqlWriteResponse> app.mysql.insert({required String table, required dynamic data, String? schema, String? instance, bool upsert, String? onConflict})

插入数据。支持单条和批量插入,以及 Upsert 模式。

参数

table
String

表名

data
dynamic

插入数据,单条 Map 或批量 List<Map>

upsert
bool

是否开启 Upsert 模式(默认 false)

onConflict
String?

Upsert 冲突字段

返回

Future
MySqlWriteResponse

示例

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

if (result.isSuccess) {
print('插入成功');
}

update (MySQL)

Future<MySqlWriteResponse> app.mysql.update({required String table, required Map<String, dynamic> data, required Map<String, String> filters, String? schema, String? instance})

更新 MySQL 数据。必须提供 WHERE 条件。

参数

table
String

表名

data
Map<String, dynamic>

要更新的数据

filters
Map<String, String>

WHERE 条件(不能为空)

返回

Future
MySqlWriteResponse

示例

final result = await app.mysql.update(
table: 'users',
data: {'age': 26},
filters: {'name': 'eq.张三'},
);

if (result.isSuccess) {
print('更新成功');
} else {
print('更新失败: ${result.message}');
}

delete (MySQL)

Future<MySqlWriteResponse> app.mysql.delete({required String table, required Map<String, String> filters, String? schema, String? instance})

删除 MySQL 数据。必须提供 WHERE 条件。

参数

table
String

表名

filters
Map<String, String>

WHERE 条件(不能为空)

返回

Future
MySqlWriteResponse

示例

final result = await app.mysql.delete(
table: 'users',
filters: {'name': 'eq.张三'},
);

if (result.isSuccess) {
print('删除成功');
}

count

Future<MySqlCountResponse> app.mysql.count({required String table, Map<String, String>? filters, String? schema, String? instance})

统计 MySQL 数据数量。

参数

table
String

表名

filters
Map<String, String>?

筛选条件

返回

Future
MySqlCountResponse

示例

final result = await app.mysql.count(
table: 'users',
filters: {'age': 'gt.18'},
);

if (result.isSuccess) {
print('符合条件的数据量: ${result.count}');
} else {
print('统计失败: ${result.message}');
}

云函数

callFunction

Future<FunctionResponse> app.callFunction({
required String name,
FunctionType type,
Map<String, dynamic>? data,
HttpMethod method,
String path,
Map<String, String>? header,
bool parse,
})

调用云函数。支持基础云函数和函数型云托管两种类型的统一调用。

参数

name
String

函数/服务名称

type
FunctionType

调用类型:FunctionType.function(默认)/ FunctionType.cloudrun

data
Map<String, dynamic>?

请求数据

method
HttpMethod

HTTP 方法(仅 cloudrun 类型有效,默认 POST)

path
String

HTTP 路径(仅 cloudrun 类型有效,默认 /)

header
Map<String, String>?

HTTP 请求头(仅 cloudrun 类型有效)

parse
bool

是否解析返回对象(仅 function 类型有效,默认 true)

返回

Future
FunctionResponse

示例

final result = await app.callFunction(
name: 'myFunction',
data: {'action': 'getUserList', 'pageSize': 10},
);

if (result.isSuccess) {
print('执行结果: ${result.result}');
} else {
print('执行失败: ${result.message}');
}

云托管

callContainer

Future<CloudRunResponse> app.callContainer({
required String name,
HttpMethod method,
String path,
Map<String, String>? header,
Map<String, dynamic>? data,
})

调用云托管容器服务。支持自定义 HTTP 方法、路径和请求头。

参数

name
String

云托管服务名

method
HttpMethod

HTTP 请求方法(默认 GET)

path
String

HTTP 请求路径(默认 /)

header
Map<String, String>?

HTTP 请求头

data
Map<String, dynamic>?

HTTP 请求体

返回

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('响应数据: ${result.result}');
} else {
print('请求失败: ${result.message}');
}

APIs

apis[name]

ApiMethodProxy app.apis[String apiName]

调用 API 网关接口。支持通过下标运算符获取 API 代理对象,进行链式调用。支持 GET、POST、PUT、DELETE、HEAD、OPTIONS、PATCH 方法。

参数

apiName
String

API 名称

返回

ApiMethodProxy
ApiMethodProxy

API 方法代理对象,支持链式调用

ApiResponse
ApiResponse

API 响应

示例

// POST 请求
final result = await app.apis['myApi'].post(
path: '/users',
body: {'name': '张三', 'age': 25},
);

if (result.isSuccess) {
print('响应数据: ${result.data}');
}

// GET 请求
final getResult = await app.apis['myApi'].get(path: '/users/123');

// PUT 请求
final putResult = await app.apis['myApi'].put(
path: '/users/123',
body: {'name': '李四'},
);

// DELETE 请求
final deleteResult = await app.apis['myApi'].delete(path: '/users/123');