tencent cloud

Getting Started
Last updated:2026-03-03 15:41:28
Getting Started
Last updated: 2026-03-03 15:41:28

Relevant Resources

SDK source code download see Flutter SDK.
For the example Demo, see Flutter SDK Demo.
For the SDK change log, see CHANGELOG.
For SDK frequently asked questions, see Flutter SDK FAQ.
The Pub repository can be found at Pub Repository.

Environment Configuration and Preparation

You need a pure Flutter project or a Flutter native hybrid project. This application can be your existing project or a new empty project you create. For details, see Flutter Development Guide.
Flutter version requirements:
sdk: ">=2.15.0 <4.0.0"
flutter: ">=2.5.0"

Installing the SDK

tencentcloud_cos_sdk_plugin is currently compatible with iOS and Android, implemented by bridging the native Android and iOS COS SDK through the Flutter Plugin.
1. Run the following command.
flutter pub add tencentcloud_cos_sdk_plugin
2. This will add a line to your package's pubspec.yaml (and run an implicit flutter pub get).
Note:
To avoid compatibility risks caused by automatic upgrades (for example, ^1.2.0 will upgrade to 1.2.5 and other minor versions), it is recommended to fix the version number in production environments. You can refer to the changelog to confirm the stability of the current version.
dependencies:
tencentcloud_cos_sdk_plugin: 1.2.6
3. In your Dart code, you can use import to import, and then start using.
import 'package:tencentcloud_cos_sdk_plugin/cos.dart';
Note:
To continuously track and optimize the quality of the SDK and provide you with a better user experience, we have introduced the Tencent Beacon SDK. Tencent Beacon only monitors the request performance on the COS side and will not report business-side data.
If you want to disable this feature, you can replace tencentcloud_cos_sdk_plugin with tencentcloud_cos_sdk_plugin_nobeacon during dependency introduction and import.

Initialize COS Service

Note:
It is recommended that users use temporary keys to call the SDK, further enhancing security through temporary authorization. When applying for temporary keys, please follow the principle of least privilege to prevent leakage of resources beyond the target bucket or objects.
If you must use permanent keys, it is recommended to follow the principle of least privilege to restrict the scope of permissions for the permanent keys.
For your business security, please refer to Upload Security Restrictions for file uploads.

Set API Access Key

Single-Use Temporary Key
Temporary Key Callback
Fixed Key (for testing only)
Set the individual key to the sessionCredentials parameter of specific COS operation methods (such as the upload method), and this key is only used for the current COS operation (such as upload and so on).
// Obtain temporary keys (controlled at the business layer)
String tmpSecretId = "SECRETID"; // Temporary key SecretId
String tmpSecretKey = "SECRETKEY"; // Temporary key SecretKey
String sessionToken = "SESSIONTOKEN"; // Temporary key Token
int expiredTime = 1556183496;//Expiration timestamp of the temporary key, in seconds
// It is recommended to return the server time as the signature start time to prevent request expiration due to excessive local time deviation on the user's device
int startTime = 1556182000; // Start time of the temporary key's validity, in seconds
SessionQCloudCredentials sessionQCloudCredentials = SessionQCloudCredentials(
secretId: tmpSecretId,
secretKey: tmpSecretKey,
token: sessionToken,
startTime: startTime,
expiredTime: expiredTime
);
// Subsequently, pass sessionQCloudCredentials to specific COS operation methods
Note:
The COS Flutter SDK version must be greater than or equal to v1.2.4.
Provide a callback method to the COS SDK for obtaining temporary keys. The SDK will use this callback to retrieve temporary keys when first initialized and when the cached temporary keys are about to expire.
import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:tencentcloud_cos_sdk_plugin/fetch_credentials.dart';
import 'package:tencentcloud_cos_sdk_plugin/pigeon.dart';

// Implement a IFetchCredentials class to handle the process of requesting temporary keys and returning the results.
class FetchCredentials implements IFetchCredentials{
@override
Future<SessionQCloudCredentials> fetchSessionCredentials() async {
// First, obtain the response containing key information from your temporary key server, for example:
var httpClient = HttpClient();
try {
// url for the temporary key server. For the temporary key generation service, see https://www.tencentcloud.com/document/product/436/14048
var stsUrl = "http://stsservice.com/sts";
var request = await httpClient.getUrl(Uri.parse(stsUrl));
var response = await request.close();
if (response.statusCode == HttpStatus.OK) {
var json = await response.transform(utf8.decoder).join();
print(json);

// Then parse the response to obtain temporary key information
var data = jsonDecode(json);
// Finally, return the temporary key information object
return SessionQCloudCredentials(
secretId: data['credentials']['tmpSecretId'], // Temporary key SecretId
secretKey: data['credentials']['tmpSecretKey'], // Temporary key SecretKey
token: data['credentials']['sessionToken'], // Temporary key Token
startTime: data['startTime'], // Temporary key validity start time, in seconds
expiredTime: data['expiredTime']//Expiration timestamp of the temporary key, in seconds
);
} else {
throw ArgumentError();
}
} catch (exception) {
throw ArgumentError();
}
}
}
Here, assume the class name is FetchCredentials. Initialize an instance to provide credentials to the SDK.
await Cos().initWithSessionCredential(FetchCredentials());
You can use Tencent Cloud's permanent keys for local debugging during development. Due to risks of key leakage, you must replace them with temporary keys before deployment.
String SECRET_ID = "SECRETID"; // User's SecretId. It is recommended to use a sub-account key; authorization follows the principle of least privilege to reduce usage risks. For obtaining sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
String SECRET_KEY = "SECRETKEY"; // User's SecretKey. It is recommended to use a sub-account key; authorization follows the principle of least privilege to reduce usage risks. For obtaining sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1

await Cos().initWithPlainSecret(SECRET_ID, SECRET_KEY);

Initialize COS

// The abbreviation for the bucket region, such as ap-guangzhou for Guangzhou
String region = "COS_REGION";
// Create a CosXmlServiceConfig object and modify the default configuration parameters as needed
CosXmlServiceConfig serviceConfig = CosXmlServiceConfig(
region: region,
isDebuggable: true,
isHttps: true,
);
// Register the default COS Service
await Cos().registerDefaultService(serviceConfig);

// Create a TransferConfig object and modify the default configuration parameters as needed
// TransferConfig allows you to set the intelligent chunking threshold. By default, files larger than or equal to 2MB are automatically uploaded in chunks. You can modify the chunking threshold with the following code.
TransferConfig transferConfig = TransferConfig(
forceSimpleUpload: false,
enableVerification: true,
divisionForUpload: 2097152, // Set files larger than or equal to 2MB to be uploaded in chunks
sliceSizeForUpload: 1048576, // Set the default chunk size to 1MB
);
// Register the default COS TransferManger
await Cos().registerDefaultTransferManger(serviceConfig, transferConfig);

// You can also register other instances using registerService and registerTransferManger for subsequent calls.
// Generally, region is used as the registration key
String newRegion = "NEW_COS_REGION";
await Cos().registerService(newRegion, serviceConfig..region = newRegion);
await Cos().registerTransferManger(newRegion, serviceConfig..region = newRegion, transferConfig);

Parameter Description

CosXmlServiceConfig configures the COS service, and its main members are described as follows:
Parameter Name
Description
Type
Default Value
Supported Platforms
Required
region
The region of the bucket. For details, see Regions and Access Domains
String
null
Android and iOS
Yes
isDebuggable
whether it is in debug mode (debug mode prints debug logs)
Bool
false
Android
No
isHttps
Whether to use the https protocol
Bool
true
Android and iOS
No
connectionTimeout
Connection timeout time (in milliseconds)
Int
Android(15000)
iOS(30000)
Android and iOS
No
socketTimeout
Read/write timeout time (in milliseconds)
Int
30000
Android
No
host
Set the host for all requests except GetService.
String
null
Android and iOS
No
hostFormat
Set the format string for the host. The SDK will replace ${bucket} with the actual bucket and ${region} with the actual region.
For example, set hostFormat to ${bucket}.${region}.tencent.com, and your bucket and region are respectively bucket-1250000000 and ap-shanghai, then the final request address is bucket-1250000000.ap-shanghai.tencent.com
Note:
This setting does not affect GetService requests.
String
null
Android
No
port
Set the request port.
Int
null
Android
No
signInUrl
Whether to place the signature in the URL, which is placed in the Header by default.
Bool
false
Android
No
userAgent
ua extension parameters
String
null
Android and iOS
No
dnsCache
Whether to enable DNS resolution caching. When DNS resolution caching is enabled, the DNS resolution results are cached locally. If the system DNS resolution fails, the locally cached DNS results will be used.
Bool
true
Android
No
accelerate
Whether to use Global Accelerator domain names.
Bool
false
Android and iOS
No
TransferConfig configures the COS upload service, and its main members are described as follows:
Parameter Name
Description
Type
Default Value
Supported Platforms
Required
forceSimpleUpload
Whether to force the use of simple upload.
Bool
false
Android
No
enableVerification
Whether to verify the integrity during multipart upload.
Bool
true
Android and iOS
No
divisionForUpload
Set the minimum object size to enable chunked upload.
Int
2097152
Android and iOS
No
sliceSizeForUpload
Set the part size for chunked upload.
Int
1048576
Android and iOS
No

Access COS Service

PUT Object
Downloading an Object
Note:
For more complete examples, visit GitHub.
The SDK supports uploading local files and binary data. The following example uses the upload of a local file:
// Obtain the TransferManager
CosTransferManger transferManager = Cos().getDefaultTransferManger();
//CosTransferManger transferManager = Cos().getTransferManger("newRegion");
// Bucket name in the format of bucketname-appid, where appid must be included. You can view the bucket name in the COS console: https://console.tencentcloud.com/cos5/bucket
String bucket = "examplebucket-1250000000";
String cosPath = "exampleobject"; // The location identifier of the object in the bucket, also known as the object key
String srcPath = "absolute path of the local file"; // absolute path of the local file
// If an UploadId for an initialized multipart upload exists, assign its value to uploadId for resuming; otherwise, assign null
String? _uploadId;

// Upload success callback
successCallBack(Map<String?, String?>? header, CosXmlResult? result) {
// todo Upload success follow-up logic
}
// Upload failure callback
failCallBack(clientException, serviceException) {
// todo Upload failure follow-up logic
if (clientException != null) {
print(clientException);
}
if (serviceException != null) {
print(serviceException);
}
}
// Upload status callback, which allows you to view the task progress
stateCallback(state) {
// todo notify transfer state
}
// Upload progress callback
progressCallBack(complete, target) {
// todo Do something to update progress...
}
// Initialization chunk complete callback
initMultipleUploadCallback(
String bucket, String cosKey, String uploadId) {
// Used to resume the upload next time, uploadId
_uploadId = uploadId;
}
// Start upload
TransferTask transferTask = await transferManager.upload(bucket, cosPath,
filePath: srcPath,
uploadId: _uploadId,
resultListener: ResultListener(successCallBack, failCallBack),
stateCallback: stateCallback,
progressCallBack: progressCallBack,
initMultipleUploadCallback: initMultipleUploadCallback,
// Configure a single-use temporary key here; if not using the single-use temporary key method, do not pass this parameter
sessionCredentials: sessionQCloudCredentials
);
// Pause task
//transferTask.pause();
// Resume task
//transferTask.resume();
// Cancel task
//transferTask.cancel();
Note:
For more complete examples, visit GitHub.
// The advanced download API supports resuming from breakpoints, so it initiates a HEAD request to obtain file information before downloading.
// If you are using a temporary key or accessing with a sub-account, ensure that the permission list includes the HeadObject permission.

// TransferManager supports resuming downloads from breakpoints; you only need to ensure the bucket, cosPath, and savePath
// If the parameters are consistent, the SDK will resume downloading from the last position.

// Obtain the TransferManager
CosTransferManger transferManager = Cos().getDefaultTransferManger();
//CosTransferManger transferManager = Cos().getTransferManger("newRegion");
// Bucket name in the format of bucketname-appid, where appid must be included. You can view the bucket name in the COS console: https://console.tencentcloud.com/cos5/bucket
String bucket = "examplebucket-1250000000";
String cosPath = "exampleobject"; // The location identifier of the object in the bucket, also known as the object key
String downloadPath = "absolute path of the local file"; // absolute path to save the local file

// Download success callback
successCallBack(Map<String?, String?>? header, CosXmlResult? result) {
// todo Download success follow-up logic
}
// Download failure callback
failCallBack(clientException, serviceException) {
// todo Download failure follow-up logic
if (clientException != null) {
print(clientException);
}
if (serviceException != null) {
print(serviceException);
}
}
// Download status callback, which allows you to view the task progress
stateCallback(state) {
// todo notify transfer state
}
// Download progress callback
progressCallBack(complete, target) {
// todo Do something to download progress...
}
// Start download
TransferTask transferTask = await transferManager.download(bucket, cosPath, downloadPath,
resultListener: ResultListener(successCallBack, failCallBack),
stateCallback: stateCallback,
progressCallBack: progressCallBack,
// Configure a single-use temporary key here; if not using the single-use temporary key method, do not pass this parameter
sessionCredentials: sessionQCloudCredentials
);
// Pause task
//transferTask.pause();
// Resume task
//transferTask.resume();
// Cancel task
//transferTask.cancel();

FAQs

For common issues you may encounter during usage, refer to Flutter SDK FAQ for solutions.
Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback