generateContent method
Generates content using Google Gemini AI based on user input and system instruction.
userInput: The input provided by the user, describing the application or query.systemInstruction: The system's instruction or prompt for the AI model.
Returns the generated content as a string.
Implementation
Future<String> generateContent(
String userInput, String systemInstruction) async {
///https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=GEMINI_API_KEY
final url = Uri.parse(
'https://generativelanguage.googleapis.com/v1beta/models/$model:generateContent?key=$genAiApiKey');
final headers = {'Content-Type': 'application/json'};
final Map<String, dynamic> requestBody = {
'contents': [
{
'parts': [
{'text': systemInstruction},
{'text': userInput},
],
},
],
};
var errormessage = '';
for (int i = 0; i < 3; i++) {
try {
final response = await http.post(url,
headers: headers, body: jsonEncode(requestBody));
if (response.statusCode == 200) {
final Map<String, dynamic> data = jsonDecode(response.body);
return data['candidates'][0]['content']['parts'][0]['text'];
} else {
throw Exception(
'Failed to generate content: ${response.statusCode} ${response.request}');
}
} catch (e) {
print('Network error: $e. Retrying...');
errormessage = e.toString();
await Future.delayed(Duration(seconds: 2));
}
}
throw Exception(
'Failed to generate content after multiple attempts. full error: $errormessage');
}