generateImageUrl method
Future<Uri>
generateImageUrl({
- String prompt = 'A modern office workspace with natural light',
- Duration timeout = const Duration(seconds: 20),
override
Generate an image URL given a prompt (you can return any fetchable image URL).
Implementation
@override
Future<Uri> generateImageUrl({
String prompt = 'A modern office workspace with natural light',
Duration timeout = const Duration(seconds: 20),
}) async {
// If you have DALL·E, use this section:
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}');
}
}
// Fallback to Picsum if you don’t have image API access.
// You can still seed by prompt hash to get a stable image.
final seed = prompt.hashCode.abs() % 1000;
return Uri.parse('https://picsum.photos/seed/$seed/600/400');
}