generateImageUrl method

  1. @override
Future<Uri> generateImageUrl({
  1. String prompt = 'A modern office workspace with natural light',
  2. Duration timeout = const Duration(seconds: 20),
})
override

Generate an image URL given a prompt.

Implementation

@override
Future<Uri> generateImageUrl({
  String prompt = 'A modern office workspace with natural light',
  Duration timeout = const Duration(seconds: 20),
}) async {
  if (!imageEndpointFallback) {
    final resp = await http
        .post(
          Uri.parse(_imgBaseUrl),
          headers: {
            HttpHeaders.contentTypeHeader: 'application/json',
            HttpHeaders.authorizationHeader: 'Bearer $_apiKey',
          },
          body: jsonEncode({'prompt': prompt, 'n': 1, 'size': '512x512'}),
        )
        .timeout(timeout);

    if (resp.statusCode >= 200 && resp.statusCode < 300) {
      final data = jsonDecode(resp.body) as Map<String, dynamic>;
      final url = (data['data']?[0]?['url'] ?? '').toString();
      if (url.isNotEmpty) return Uri.parse(url);
      throw StateError('Empty AI image URL');
    } else {
      throw HttpException('AI image error: ${resp.statusCode} ${resp.body}');
    }
  }

  final seed = prompt.hashCode.abs() % 1000;
  return Uri.parse('https://picsum.photos/seed/$seed/600/400');
}