SDKs

Dart / Flutter

Flutter app 與 Dart server 上的 Dart 地道寫法

簡單場景用 http 套件,需要 interceptor 與重試就用 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 server(不是 Flutter app)持有 API Key。

批次任務則是先提交,再讓伺服器端的 Webhook handler 處理。參見 Webhooks

官方 Dart SDK 開發中 —— 敬請期待。