All Products
Search
Document Center

HTTPDNS:Integrate the Flutter SDK

Last Updated:Mar 06, 2026

This topic describes how to integrate HTTPDNS using the Flutter SDK. For information about the basic principles of HTTPDNS integration, see Client Integration Overview.

Flutter is an open-source application development framework from Google. It lets you build beautiful, natively compiled, multi-platform applications from a single codebase.

We provide a pure Dart HTTPDNS SDK that does not require native platform SDKs. This topic also shows you how to integrate and use HTTPDNS in common Flutter networking frameworks. This SDK is available on GitHub and pub.dev.

The following sections provide instructions and best practices for using the SDK:

1. Getting started

1.1. Activate the service

To activate HTTPDNS, see Quick Start.

1.2. Obtain configurations

Obtain your AccountId, SecretKey, and AESSecretKey from the development configurations in the EMAS console. You will need this information to initialize the software development kit (SDK). For more information, see Development configurations.

2. Installation and configuration

2.1. Add the Flutter dependency

In your Flutter project's pubspec.yaml file, add the following dependencies:

dependencies:
  flutter:
    sdk: flutter
  aliyun_httpdns: ^2.0.0  # Get the latest version number from the SDK release notes
  dio: ^5.9.0  # Dio networking library
  http: ^1.2.0  # http package

After adding the dependencies, run flutter pub get.

Note

Starting from version 2.0.0, this SDK is a pure Dart implementation. It does not require native Android or iOS dependencies and can be used immediately after installation.

3. Configuration and usage

3.1. Initialization configuration

After the application starts, you must initialize the plugin before you can use HTTPDNS features. The initialization process involves configuring your AccountId, SecretKey, and other settings, and enabling features. The following code provides an example:

// Initialize HTTPDNS
final config = AliyunHttpdnsConfig(
  accountId: Your AccountId,
  secretKey: 'Your SecretKey',
  httpsEnabled: true,
  persistentCacheEnabled: true,
  reuseExpiredIPEnabled: true,
  preResolveAfterNetworkChanged: true,
  ipRankingDatasource: {
    'www.aliyun.com': 443,
  },
);
await AliyunHttpdns.init(config);

// Enable logging (optional)
AliyunHttpdns.setLogEnabled(true);

// Set pre-resolve hosts
await AliyunHttpdns.setPreResolveHosts(['www.aliyun.com'], ipType: HttpdnsIpType.auto);
Important
  • If you set the httpsEnabled parameter to true, your billing increases. For more information, see Billing.

  • If you have high security requirements for domain name information or SDNS parameters, you can configure the aesSecretKey parameter to enable content-layer encryption for resolution requests. Using content encryption increases your billing. For more information, see Billing.

3.1.1. Log configuration

To output HTTPDNS logs during application development, you can call the log output control method to enable logging. The following code provides an example:

AliyunHttpdns.setLogEnabled(true);

// Custom log handler (optional)
AliyunHttpdns.setLogHandler((message) {
  print(message);
});

3.1.2. SessionId recording

While the application is running, you can call the method to retrieve the sessionId and record it in your application's data collection system. The sessionId identifies a single application run. It can be used to query resolution logs for a specific run during online troubleshooting. The following code provides an example:

final sessionId = AliyunHttpdns.getSessionId();
print("SessionId = $sessionId");

3.2. Domain name resolution

3.2.1. Pre-resolution

When you need to resolve a domain name in advance, you can call the pre-resolve method. The following code provides an example:

await AliyunHttpdns.setPreResolveHosts(["www.aliyun.com", "www.example.com"], ipType: HttpdnsIpType.auto);

After the call, the SDK initiates domain name resolution and caches the result in memory. Subsequent requests can then use the cached result.

3.2.2. Domain name resolution

When you need to resolve a domain name, you can call the domain name resolution method to retrieve the IP address. The following code provides an example:

Future<void> _resolve() async {
  final result = await AliyunHttpdns.resolveHostSyncNonBlocking('www.aliyun.com', ipType: HttpdnsIpType.auto);
  final ipv4List = result?.ips ?? [];
  final ipv6List = result?.ipv6s ?? [];
  print('IPv4: $ipv4List');
  print('IPv6: $ipv6List');
}

4. Flutter best practices

4.1. How it works

This example shows a more direct way to integrate HTTPDNS by implementing a custom HTTP client adapter:

  1. Create a custom HTTP client adapter to intercept network requests.

  2. In the adapter, call the HTTPDNS plugin to resolve domain names to IP addresses.

  3. Use the resolved IP addresses to create direct socket connections.

  4. For HTTPS connections, ensure that Server Name Indication (SNI) is correctly set to the original domain name.

This method directly integrates HTTPDNS features at the HTTP client level for simple and efficient implementation.

4.2. Example

This example provides a complete Flutter application that demonstrates how to integrate HTTPDNS features.

4.2.1. Custom HTTP client adapter implementation

For the custom adapter implementation, see the lib/net/httpdns_http_client_adapter.dart file. This solution was designed and implemented by the EMAS team. If you reference this solution, please provide attribution. The adapter intercepts HTTP requests, calls HTTPDNS for domain name resolution, and uses the resolved IP address to create a socket connection.

This example supports three networking libraries: Dio, HttpClient, and the http package. The code is as follows:

import 'dart:io';
import 'package:dio/io.dart';
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart';
import 'package:flutter/foundation.dart';
import 'package:aliyun_httpdns/aliyun_httpdns.dart';

// Dio adapter
IOHttpClientAdapter buildHttpdnsHttpClientAdapter() {
  final HttpClient client = HttpClient();
  _configureHttpClient(client);
  _configureConnectionFactory(client);

  final IOHttpClientAdapter adapter = IOHttpClientAdapter(createHttpClient: () => client)
    ..validateCertificate = (cert, host, port) => true;
  return adapter;
}

// Native HttpClient
HttpClient buildHttpdnsNativeHttpClient() {
  final HttpClient client = HttpClient();
  _configureHttpClient(client);
  _configureConnectionFactory(client);
  return client;
}

// http package adapter
http.Client buildHttpdnsHttpPackageClient() {
  final HttpClient httpClient = buildHttpdnsNativeHttpClient();
  return IOClient(httpClient);
}

// HttpClient basic configuration
void _configureHttpClient(HttpClient client) {
  client.findProxy = (Uri _) => 'DIRECT';
  client.idleTimeout = const Duration(seconds: 30);
  client.maxConnectionsPerHost = 8;
}

// Configure a connection factory based on HTTPDNS
// This solution was designed and implemented by the EMAS team. Provide attribution if you reference it.
void _configureConnectionFactory(HttpClient client) {
  client.connectionFactory = (Uri uri, String? proxyHost, int? proxyPort) async {
    final String domain = uri.host;
    final bool https = uri.scheme.toLowerCase() == 'https';
    final int port = uri.port == 0 ? (https ? 443 : 80) : uri.port;

    final List<InternetAddress> targets = await _resolveTargets(domain);
    final Object target = targets.isNotEmpty ? targets.first : domain;

    if (!https) {
      return Socket.startConnect(target, port);
    }

    // HTTPS: First TCP, then TLS (SNI=domain name), and keep it cancellable
    bool cancelled = false;
    final Future<ConnectionTask<Socket>> rawStart = Socket.startConnect(target, port);
    final Future<Socket> upgraded = rawStart.then((task) async {
      final Socket raw = await task.socket;
      if (cancelled) {
        raw.destroy();
        throw const SocketException('Connection cancelled');
      }
      final SecureSocket secure = await SecureSocket.secure(
        raw,
        host: domain, // Important: Use the original domain name as the SNI
      );
      if (cancelled) {
        secure.destroy();
        throw const SocketException('Connection cancelled');
      }
      return secure;
    });
    return ConnectionTask.fromSocket(
      upgraded,
      () {
        cancelled = true;
        try {
          rawStart.then((t) => t.cancel());
        } catch (_) {}
      },
    );
  };
}

// Resolve the target IP list through HTTPDNS
Future<List<InternetAddress>> _resolveTargets(String domain) async {
  try {
    final result = await AliyunHttpdns.resolveHostSyncNonBlocking(domain, ipType: HttpdnsIpType.auto);
    final List<String> ipv4 = result?.ips ?? [];
    final List<String> ipv6 = result?.ipv6s ?? [];
    final List<InternetAddress> targets = [
      ...ipv4.map(InternetAddress.tryParse).whereType<InternetAddress>(),
      ...ipv6.map(InternetAddress.tryParse).whereType<InternetAddress>(),
    ];
    if (targets.isEmpty) {
      debugPrint('[dio] HTTPDNS no result for $domain, fallback to system DNS');
    } else {
      debugPrint('[dio] HTTPDNS resolved $domain -> ${targets.first.address}');
    }
    return targets;
  } catch (e) {
    debugPrint('[dio] HTTPDNS resolve failed: $e, fallback to system DNS');
    return const <InternetAddress>[];
  }
}

4.2.2. Adapter integration and usage

For adapter integration, see the lib/main.dart file. First, initialize HTTPDNS. Then, configure the networking library to use the custom adapter. The following code provides an example:

class _MyHomePageState extends State<MyHomePage> {
  late final Dio _dio;
  late final HttpClient _httpClient;
  late final http.Client _httpPackageClient;

  @override
  void initState() {
    super.initState();
    
    // Initialize HTTPDNS
    _initHttpDnsOnce();
    
    // Configure the networking library to use the HTTPDNS adapter
    _dio = Dio();
    _dio.httpClientAdapter = buildHttpdnsHttpClientAdapter();
    _dio.options.headers['Connection'] = 'keep-alive';
    
    _httpClient = buildHttpdnsNativeHttpClient();
    _httpPackageClient = buildHttpdnsHttpPackageClient();
  }

  Future<void> _initHttpDnsOnce() async {
    try {
      final config = AliyunHttpdnsConfig(
        accountId: Your AccountId,
        secretKey: 'Your SecretKey',
        httpsEnabled: true,
        reuseExpiredIPEnabled: true,
      );
      await AliyunHttpdns.init(config);
      AliyunHttpdns.setLogEnabled(true);
      
      // Set pre-resolve hosts
      await AliyunHttpdns.setPreResolveHosts(['www.aliyun.com'], ipType: HttpdnsIpType.auto);
    } catch (e) {
      debugPrint('[httpdns] init failed: $e');
    }
  }
}

When you use the configured networking library to make a request, it automatically uses HTTPDNS for domain name resolution:

// Use Dio
final response = await _dio.get('https://www.aliyun.com');

// Use HttpClient
final request = await _httpClient.getUrl(Uri.parse('https://www.aliyun.com'));
final response = await request.close();

// Use the http package
final response = await _httpPackageClient.get(Uri.parse('https://www.aliyun.com'));

4.2.3. Clean up resources

When the component is destroyed, you must clean up the related resources:

@override
void dispose() {
  _urlController.dispose();
  _httpClient.close();
  _httpPackageClient.close();
  super.dispose();
}

5. API

5.1. Log output control

Controls whether logs are printed.

AliyunHttpdns.setLogEnabled(true);

5.2. Initialization

This method initializes the configuration and should be called when the application starts.

// Create a configuration
final config = AliyunHttpdnsConfig(
  accountId: Your AccountId,                        // Required
  secretKey: 'your_secret_key',             // Optional
  aesSecretKey: 'your_aes_secret_key',      // Optional
  region: HttpdnsRegion.cn,                 // Default: Chinese mainland
  httpsEnabled: true,                        // Default: true
  persistentCacheEnabled: true,              // Persistent cache
  reuseExpiredIPEnabled: true,               // Reuse expired IP
  preResolveAfterNetworkChanged: true,       // Pre-resolve after network change
  ipRankingDatasource: {                     // IP ranking configuration (optional)
    'www.aliyun.com': 443,
  },
  timeout: 2,                                // Request timeout (seconds)
);

// Initialize the SDK
await AliyunHttpdns.init(config);

// Enable logging (optional)
AliyunHttpdns.setLogEnabled(true);

Initialization parameters:

Parameter Name

Type

Required

Features

accountId

int

Required parameter

Account ID

secretKey

String?

Optional parameters

The key to add a signature.

aesSecretKey

String?

Optional parameters

The key to encrypt data.

region

HttpdnsRegion

Optional Parameters

The area where the endpoint is deployed. Default: cn.

httpsEnabled

bool

Optional parameters

Specifies whether to use the HTTPS resolution link. Default: true.

persistentCacheEnabled

bool

Optional parameters

Specifies whether to enable the persistent cache. Default: false.

reuseExpiredIPEnabled

bool

Optional parameters

Specifies whether to allow the reuse of expired IP addresses. Default: false.

preResolveAfterNetworkChanged

bool

Optional parameters

Specifies whether to automatically refresh resolutions when the network changes. Default: false.

discardExpiredAfterSeconds

int?

Optional parameters

The expiration time for discarding cached data, in seconds.

ipRankingDatasource

Map<String, int>?

Optional parameters

IP ranking configuration. A map of domain names and ports.

timeout

int

Optional parameters

The request timeout duration in seconds. Default: 2.

Important

If you set the httpsEnabled parameter to true, your billing will increase. For more information, see Billing.

If you have high security requirements for domain name information or Secure DNS (SDNS) parameters, you can configure the aesSecretKey parameter to enable content-layer encryption for resolution requests. Enabling content encryption increases your billing. For more information, see Billing.

5.3. Domain name resolution

Resolves a specified domain name. The SDK provides three resolution methods:

5.3.1 Synchronous non-blocking resolution (recommended)

Immediately returns the cached result. If the cache is not hit, it returns null and initiates a request in the background.

final result = await AliyunHttpdns.resolveHostSyncNonBlocking(
  'www.aliyun.com', 
  ipType: HttpdnsIpType.auto,
);

// With SDNS parameters
final result2 = await AliyunHttpdns.resolveHostSyncNonBlocking(
  'www.aliyun.com',
  ipType: HttpdnsIpType.auto,
  sdnsParams: {'key': 'value'},
  cacheKey: 'custom_cache_key',
);

5.3.2 Synchronous blocking resolution

Blocks until a result is obtained or the request times out.

final result = await AliyunHttpdns.resolveHostSync(
  'www.aliyun.com',
  ipType: HttpdnsIpType.auto,
);

// With SDNS parameters
final result2 = await AliyunHttpdns.resolveHostSync(
  'www.aliyun.com',
  ipType: HttpdnsIpType.auto,
  sdnsParams: {'key': 'value'},
  cacheKey: 'custom_cache_key',
);

5.3.3 Asynchronous callback resolution

Returns the resolution result through a callback function.

await AliyunHttpdns.resolveHostAsync(
  'www.aliyun.com',
  ipType: HttpdnsIpType.auto,
  callback: (result) {
    print('Resolution result: $result');
  },
);

// With SDNS parameters
await AliyunHttpdns.resolveHostAsync(
  'www.aliyun.com',
  ipType: HttpdnsIpType.auto,
  sdnsParams: {'key': 'value'},
  cacheKey: 'custom_cache_key',
  callback: (result) {
    print('Resolution result: $result');
  },
);

Parameter description

Parameter name

Type

Required

Feature

host

String

Required parameters

The domain name to resolve.

ipType

HttpdnsIpType

Optional parameters

Requested IP type: auto, v4, v6, or both.

sdnsParams

Map<String, String>?

Optional parameters

SDNS parameters for custom resolution.

cacheKey

String?

This parameter is optional.

A custom cache key.

Returned data structure (ResolveResult)

Field Name

Type

Feature

host

String

The domain name.

ips

List

A list of IPv4 addresses.

ipv6s

List

A list of IPv6 addresses.

ttl

int

The IPv4 TTL in seconds.

v6ttl

int

The IPv6 TTL in seconds.

5.4. Pre-resolve domain names

Pre-resolves one or more domain names and caches the results in the SDK. Subsequent resolution requests for these domains can retrieve results directly from the cache, which improves resolution speed.

await AliyunHttpdns.setPreResolveHosts(
  ["www.aliyun.com"], 
  ipType: HttpdnsIpType.auto
);

Parameters:

Parameter name

Type

Required

Features

hosts

List

Required parameters

A list of domain names to pre-resolve.

ipType

HttpdnsIpType

Optional parameters

Requested IP type: auto, v4, v6, or both.

5.5. Get SessionId

Retrieves the SessionId, which is used for troubleshooting and tracking issues.

final sessionId = await AliyunHttpdns.getSessionId();
print("SessionId = $sessionId");

No parameters are required. Returns the current session ID.

5.6. Clear cache

Clears the DNS resolution cache.

// Clear all caches
await AliyunHttpdns.cleanHostCache(null);

// Clear the cache for a specified domain name
await AliyunHttpdns.cleanHostCache(['www.aliyun.com']);

5.7. Auto-refresh pre-resolved domains on network change

Sets whether to automatically refresh the cache for pre-resolved domain names when the network environment changes. This is set through the initialization configuration.

final config = AliyunHttpdnsConfig(
  accountId: Your AccountId,
  secretKey: 'your_secret_key',
  preResolveAfterNetworkChanged: true,  // Auto-refresh on network change
);
await AliyunHttpdns.init(config);

5.8. Persistent cache configuration

Sets whether to enable the persistent cache feature. When enabled, the SDK saves resolution results to the local device. After the app restarts, it can load the cached results from the local device. This is set through the initialization configuration.

final config = AliyunHttpdnsConfig(
  accountId: Your AccountId,
  secretKey: 'your_secret_key',
  persistentCacheEnabled: true,              // Enable persistent cache
  discardExpiredAfterSeconds: 86400,         // Optional, discard cache expired for more than 1 day
);
await AliyunHttpdns.init(config);

Parameters:

Parameter Name

Type

Required

Features

persistentCacheEnabled

bool

Optional parameters

Specifies whether to enable the persistent cache. Default: false.

discardExpiredAfterSeconds

int?

Optional parameters

The expiration threshold in seconds. When the app starts, it discards cached records that have been expired for longer than this duration.

5.9 IP Preference

Specifies a list of domain names for which to perform IP ranking. When enabled, the SDK performs TCP speed tests on the resolved IP addresses and sorts them to ensure that the first IP address in the list has the best availability. This is set through the initialization configuration:

final config = AliyunHttpdnsConfig(
  accountId: Your AccountId,
  secretKey: 'your_secret_key',
  ipRankingDatasource: {
    'www.aliyun.com': 443,
  },
);
await AliyunHttpdns.init(config);

Parameters:

Parameter name

Type

Required

Features

ipRankingDatasource

Map<String, int>?

Optional parameters

A map of domain names and ports, such as {'www.aliyun.com': 443}.

5.10 Custom TTL

You can set a callback function to modify the TTL of a resolution result.

AliyunHttpdns.setTtlChanger((host, ipType, ttl) {
  // Return the modified TTL
  return ttl * 2;
});

5.11 SDNS global parameters

Sets global SDNS parameters. All resolution requests carry these parameters.

AliyunHttpdns.setSdnsGlobalParams({
  'key1': 'value1',
  'key2': 'value2',
});

5.12 Correct signature time

If the client time is inconsistent with the server time, you can use this method to calibrate the time.

AliyunHttpdns.setAuthCurrentTime(serverTimestamp);

6. Version upgrade guide

6.1 Guide to upgrading from version 1.x to 2.0.0

Version 2.0.0 is refactored into a pure Dart implementation. The main advantages are:

  • No dependency on Android or iOS native SDKs, which simplifies project configuration and version management.

  • Consistent cross-platform behavior, which makes debugging and maintenance easier.

  • Reduced package size and no native bridge overhead.

This upgrade involves some API changes, mainly in the initialization method and parameter types. Follow the steps below to complete the upgrade.

Detailed upgrade steps

1. Update the dependency version

pubspec.yaml

dependencies:aliyun_httpdns: ^2.0.0

Run the update:

flutter pub upgrade aliyun_httpdns
Note

Version 2.0.0 is a pure Dart implementation. You can delete configurations related to the native SDK in your project, such as the HTTPDNS dependency in build.gradle and the AlicloudHTTPDNS dependency in podspec.

2. Refactor the initialization code

Before upgrade (1.x)

// 1.x: Two-stage initialization
await AliyunHttpdns.init(
  accountId: Your AccountId,
  secretKey: "your_secret_key",
  aesSecretKey: "your_aes_key",
);

await AliyunHttpdns.setHttpsRequestEnabled(true);
await AliyunHttpdns.setPersistentCacheIPEnabled(true);
await AliyunHttpdns.setReuseExpiredIPEnabled(true);
await AliyunHttpdns.setPreResolveAfterNetworkChanged(true);
await AliyunHttpdns.setIPRankingList({'www.aliyun.com': 443});

await AliyunHttpdns.build();

After upgrade (2.0)

final config = AliyunHttpdnsConfig(
  accountId: Your AccountId,
  secretKey: 'your_secret_key',
  aesSecretKey: 'your_aes_key',
  httpsEnabled: true,
  persistentCacheEnabled: true,
  reuseExpiredIPEnabled: true,
  preResolveAfterNetworkChanged: true,
  ipRankingDatasource: {'www.aliyun.com': 443},
);
await AliyunHttpdns.init(config);

Notes:

  • All feature configurations are merged into the AliyunHttpdnsConfig constructor parameters.

  • You no longer need to call the build() method.

  • New configuration parameters such as region, timeout, and discardExpiredAfterSeconds are added.

3. Update the resolution API

Before upgrade (1.x)

final res = await AliyunHttpdns.resolveHostSyncNonBlocking(
  'www.aliyun.com',
  ipType: 'both',
);
final ipv4s = res['ipv4'] ?? [];
final ipv6s = res['ipv6'] ?? [];

After upgrade (2.0)

final result = await AliyunHttpdns.resolveHostSyncNonBlocking(
  'www.aliyun.com',
  ipType: HttpdnsIpType.auto,
);
final ipv4s = result?.ips ?? [];
final ipv6s = result?.ipv6s ?? [];

Notes:

  • ipType is changed from a string to the HttpdnsIpType enumeration (auto, v4, v6, both).

  • The return value is changed from Map<String, List<String>> to a ResolveResult? object.

  • The field names are changed from ipv4/ipv6 to ips/ipv6s.

  • Two new resolution methods, resolveHostSync and resolveHostAsync, are added.

4. Update the pre-resolution API

Before upgrade (1.x)

await AliyunHttpdns.setPreResolveHosts(['www.aliyun.com']);

After upgrade (2.0)

await AliyunHttpdns.setPreResolveHosts(['www.aliyun.com']);
5. Add a custom log handler
AliyunHttpdns.setLogHandler((message) {
  print(message);
});
6. Update the clear cache API

Before upgrade (1.x)

await AliyunHttpdns.cleanAllHostCache();

After upgrade (2.0)

// Clear all caches
await AliyunHttpdns.cleanHostCache(null);

// Clear the cache for a specified domain name (new)
await AliyunHttpdns.cleanHostCache(['www.aliyun.com']);
Note

If your application does not use any of the changed APIs, you do not need to take any action.

API upgrade mapping table (1.x → 2.0)

API category

1.x

2.0

Initialization

init(accountId:, secretKey:) + various set methods + build()

init(AliyunHttpdnsConfig(...))

Enable HTTPS requests

setHttpsRequestEnabled(true)

AliyunHttpdnsConfig(httpsEnabled: true)

Enable expired IPs

setReuseExpiredIPEnabled(true)

AliyunHttpdnsConfig(reuseExpiredIPEnabled: true)

Enable local cache

setPersistentCacheIPEnabled(true)

AliyunHttpdnsConfig(persistentCacheEnabled: true)

Pre-resolve on network change

setPreResolveAfterNetworkChanged(true)

AliyunHttpdnsConfig(preResolveAfterNetworkChanged: true)

Preferred IP

setIPRankingList({...})

AliyunHttpdnsConfig(ipRankingDatasource: {...})

Build service

build()

Not required

Synchronous non-blocking resolution

resolveHostSyncNonBlocking(..., ipType: 'both')

resolveHostSyncNonBlocking(..., ipType: HttpdnsIpType.both)

Synchronous blocking resolution

None

resolveHostSync(...) (new)

Asynchronous callback resolution

None

resolveHostAsync(..., callback: ...) (new)

Return value

Map<String, List<String>> (res['ipv4'])

ResolveResult? (result?.ips)

Set pre-resolve hosts

setPreResolveHosts(..., ipType: 'both')

setPreResolveHosts(..., ipType: HttpdnsIpType.both)

Clear cache

cleanAllHostCache()

cleanHostCache(List<String>?)

Custom TTL

None

setTtlChanger(...) (new)

SDNS global parameters

None

setSdnsGlobalParams({...}) (new)

Custom log handler

None

setLogHandler(...) (new)

Correct signature time

None

setAuthCurrentTime(int) (new)

6.2 Guide to upgrading from version 0.x to 1.0.0

Version 1.0.0 introduces a comprehensive architectural refactoring and API optimization. This upgrade aims to:

  • Unify the configuration pattern: Moves from scattered runtime configurations to a two-stage initialization pattern (init + build). This resolves configuration timing issues and improves SDK stability.

  • Standardize the resolution API: Redesigns the resolution API architecture to provide a unified resolveHostSyncNonBlocking method. This method returns structured data instead of a JSON string.

  • Design with static methods: Switches from a singleton pattern to static method calls. This simplifies usage and removes the need to create instances.

  • Optimize performance: Improves resolution performance and resource utilization efficiency through API optimization and internal implementation enhancements.

This is a major, backward-incompatible change. Although the changes are significant, you only need to modify the APIs that your application uses. The following upgrade steps and the old-to-new API mapping table can help you systematically complete this important upgrade.

Detailed upgrade steps

1. Update the dependency version

pubspec.yaml

dependencies:aliyun_httpdns: ^1.0.0

Run the update:

flutter pub upgrade aliyun_httpdns
2. Refactor the initialization code

Before upgrade

// Old version: Singleton pattern + one-step initialization
final _aliyunHttpDns = AliyunHttpDns();

await _aliyunHttpDns.init(
  "YOUR_ACCOUNT_ID",              // String type
  secretKey: "your_secret_key",
  aesSecretKey: "your_aes_key",
  region: "",
  timeout: 2000,
  enableHttps: true,
  enableExpireIp: true,
  enableCacheIp: true,
  enableDegradationLocalDns: true,
  preResolveAfterNetworkChanged: true,
  ipRankingMap: {"www.aliyun.com": 80},
  sdnsGlobalParam: {"aa": "bb"},
  bizTags: ["tag1", "tag2"]
);

After upgrade

// New version: Static methods + two-stage initialization

// Stage 1: Initialize basic configurations
await AliyunHttpdns.init(
  accountId: your_account_id,            // int type, required
  secretKey: "your_secret_key",          // Optional
  aesSecretKey: "your_aes_key",          // Optional
);

// Stage 2: Set feature options
await AliyunHttpdns.setHttpsRequestEnabled(true);        // Replaces enableHttps
await AliyunHttpdns.setLogEnabled(true);                 // Replaces enableLog
await AliyunHttpdns.setPersistentCacheIPEnabled(true);   // Replaces enableCacheIp
await AliyunHttpdns.setReuseExpiredIPEnabled(true);      // Replaces enableExpireIp
await AliyunHttpdns.setPreResolveAfterNetworkChanged(true); // Replaces preResolveAfterNetworkChanged

// Stage 3: Build the service (must be called)
await AliyunHttpdns.build();

Notes:

  • The region, timeout, enableDegradationLocalDns, ipRankingMap, sdnsGlobalParam, and bizTags parameters have been removed.

  • A new build() method has been added. It must be called after configuration is complete.

  • All methods are now static. You do not need to create an instance.

3. Update the resolution API

Before upgrade

// Synchronous non-blocking, returns a JSON string
String result = await _aliyunHttpDns.resolve(
  "YOUR_ACCOUNT_ID",          // accountId
  "www.aliyun.com",           // host
  kRequestIpv4AndIpv6,        // requestIpType
);

// Requires manual JSON parsing
Map<String, dynamic> map = json.decode(result);
List<String> ipv4s = List<String>.from(map['ipv4'] ?? []);
List<String> ipv6s = List<String>.from(map['ipv6'] ?? []);

// Use the first IP
String ip = ipv4s.isNotEmpty ? ipv4s.first : '';

After upgrade

// Synchronous non-blocking, returns structured data
Map<String, List<String>> result = await AliyunHttpdns.resolveHostSyncNonBlocking(
  'www.aliyun.com',           // hostname (accountId is not required)
  ipType: 'both',             // Replaces kRequestIpv4AndIpv6
);

// Get the IP list directly
List<String> ipv4s = result['ipv4'] ?? [];
List<String> ipv6s = result['ipv6'] ?? [];

// Use the first IP
String ip = ipv4s.isNotEmpty ? ipv4s.first : '';

Custom resolution parameters:

// Before upgrade
String result = await _aliyunHttpDns.resolve(
  "YOUR_ACCOUNT_ID",
  "www.aliyun.com",
  kRequestIpv4AndIpv6,
  params: {"key": "value"},
  cacheKey: "custom_key"
);

// After upgrade
Map<String, List<String>> result = await AliyunHttpdns.resolveHostSyncNonBlocking(
  'www.aliyun.com',
  ipType: 'both',
  sdnsParams: {"key": "value"},    // Parameter name changed
  cacheKey: "custom_key"
);
4. Update the pre-resolution API

Before upgrade

await _aliyunHttpDns.setPreResolveHosts(
  "YOUR_ACCOUNT_ID",                     // accountId
  ["www.aliyun.com"],
  kRequestIpv4AndIpv6                    // requestIpType
);

After upgrade

await AliyunHttpdns.setPreResolveHosts(
  ["www.aliyun.com"],                     // accountId is not required
  ipType: 'both'                          // Replaces kRequestIpv4AndIpv6
);
5. Update the log configuration

Before upgrade

await _aliyunHttpDns.enableLog(true);

After upgrade

await AliyunHttpdns.setLogEnabled(true);
6. Update SessionId retrieval

Before upgrade

String sessionId = await _aliyunHttpDns.getSessionId("YOUR_ACCOUNT_ID");

After upgrade

String? sessionId = await AliyunHttpdns.getSessionId();
7. Use new features

Clear cache

await AliyunHttpdns.cleanAllHostCache();

Persistent cache configuration

await AliyunHttpdns.setPersistentCacheIPEnabled(true);
Note

If your application does not use any of the incompatible APIs, you do not need to take any action.

API upgrade mapping table

API category

Before upgrade

After upgrade

Create instance

AliyunHttpDns()

Not required. Use static methods directly.

Initialization

init(String accountId, {...})

init({required int accountId, ...})

Build service

None

build() (New, must be called)

Enable HTTPS requests

init(enableHttps: true)

setHttpsRequestEnabled(true)

Enable expired IPs

init(enableExpireIp: true)

setReuseExpiredIPEnabled(true)

Enable local cache

init(enableCacheIp: true)

setPersistentCacheIPEnabled(true)

Pre-resolve on network change

init(preResolveAfterNetworkChanged: true)

setPreResolveAfterNetworkChanged(true)

Control log output

enableLog(bool)

setLogEnabled(bool)

Synchronous non-blocking resolution

resolve(String accountId, String host, String requestIpType)

resolveHostSyncNonBlocking(String hostname, {String ipType})

IPv4 resolution

resolve(..., kRequestIpv4)

resolveHostSyncNonBlocking(..., ipType: 'ipv4')

IPv6 resolution

resolve(..., kRequestIpv6)

resolveHostSyncNonBlocking(..., ipType: 'ipv6')

IPv4 and IPv6 resolution

resolve(..., kRequestIpv4AndIpv6)

resolveHostSyncNonBlocking(..., ipType: 'both')

Auto-select

None

resolveHostSyncNonBlocking(..., ipType: 'auto')

Custom resolution parameters

resolve(..., params: {...})

resolveHostSyncNonBlocking(..., sdnsParams: {...})

Set pre-resolve hosts

setPreResolveHosts(String accountId, List<String>, String requestIpType)

setPreResolveHosts(List<String>, {String ipType})

Get SessionId

getSessionId(String accountId)

getSessionId()

Clear cache

None

cleanAllHostCache()

Correct signature time

setAuthCurrentTime(String accountId, int)

Removed