SDKs

Dart / Flutter

Flutter App 与 Dart 服务端上的地道 Dart 写法

简单场景用 http 包,需要拦截器和重试就用 dio。下面用 http 演示 —— 它在 Flutter 的 Dart SDK 里开箱即用。

pubspec.yaml

dependencies:
  http: ^1.2.2

配置

import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

const api = 'https://openapi.thunderbit.com/openapi/v1';
final headers = <String, String>{
  'Authorization': 'Bearer ${Platform.environment['THUNDERBIT_API_KEY']}',
  'Content-Type': 'application/json',
};

Distill 一个页面

Future<String> distill(String url) async {
  final res = await http.post(
    Uri.parse('$api/distill'),
    headers: headers,
    body: jsonEncode({'url': url}),
  );
  if (res.statusCode >= 400) throw Exception(res.body);
  final body = jsonDecode(res.body) as Map<String, dynamic>;
  return body['data']['markdown'] as String;
}

Extract 结构化数据

Future<Map<String, dynamic>> extract(String url) async {
  final res = await http.post(
    Uri.parse('$api/extract'),
    headers: headers,
    body: jsonEncode({
      'url': url,
      'schema': {
        'type': 'object',
        'properties': {
          'name':  {'type': 'string'},
          'price': {'type': 'number'},
        },
        'required': ['name', 'price'],
      },
    }),
  );
  return (jsonDecode(res.body) as Map<String, dynamic>)['data'];
}

Flutter UI 小贴士

把调用包在 FutureBuilder 里,UI 就不会卡住 —— 生产环境让 Dart 服务端(而不是 Flutter App)持有 API Key。

Batch 任务提交后,让服务端的 webhook handler 来干活。详见 Webhooks

官方 Dart SDK 正在开发中,敬请期待。