Beginner's Guide to Embedding AI in Flutter Apps

Beginner's Guide to Embedding AI in Flutter Apps

To integrate the Gemini AI API into a Flutter project, you can use the http package to make HTTP requests. Here’s how you can create a basic Flutter app to interact with the Gemini API.

Step 1: Add Dependencies

First, add the http package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  http: ^1.2.2

Run flutter pub get to install the package.

Step 2: Create a Dart Service to Handle the API Request

Create a service in your Flutter project to interact with the Gemini API.

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

class AIService {
  final String apiKey = 'YOUR_API_KEY';

  Future<String> getAIResponse(String inputText) async {
    final String url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:getAIResponse?key=$apiKey';
    final headers = {'Content-Type': 'application/json'};
    final body = jsonEncode({
      'contents': [
        {
          'parts': [
            {'text': inputText}
          ]
        }
      ]
    });

    try {
      final response = await http.post(Uri.parse(url), headers: headers, body: body);
      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        return data['results'][0]['output'] ?? 'No response by AI';
      } else {
        return 'Error: ${response.statusCode} - ${response.body}';
      }
    } catch (e) {
      return 'Error: $e';
    }
  }
}

Step 3: Create a UI to Input Text and Display AI Response

In your main.dart file, create a simple UI to input text and display the response from the Gemini API.

import 'package:flutter/material.dart';
import 'gemini_service.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final TextEditingController _controller = TextEditingController();
  final AIService _aiService = AIService();
  String _response = '';

  void _sendRequest() async {
    final inputText = _controller.text;
    final result = await _aiService.getAIResponse(inputText);
    setState(() {
      _response = result;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('AI Service')),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: [
            TextField(
              controller: _controller,
              decoration: InputDecoration(labelText: 'Enter your input here'),
            ),
            SizedBox(height: 25),
            ElevatedButton(
              onPressed: _sendRequest,
              child: Text('Generate'),
            ),
            SizedBox(height: 25),
            Text(
              _response,
              style: TextStyle(fontSize: 18),
            ),
          ],
        ),
      ),
    );
  }
}

Step 4: Run the Flutter App

Replace 'YOUR_API_KEY' with your actual API key from the Gemini AI platform. After setting this up, you can run the app on your emulator or device to see the AI response.

This basic app allows users to input text and then sends a request to the Gemini API. The AI-generated content is displayed on the screen.


Steps to find an API key from the Google AI Studio website:

Step 1: Sign In to Google AI Studio

  1. Go to Google AI Studio.

  2. Sign in using your Google account.

Step 2: Access the API Section

  1. Once signed in, navigate to the "API & Services" section from the main dashboard or menu.

  2. If this is your first time, you may need to create a new project. Click on "Select a Project" or "Create a Project" if prompted.

Step 3: Enable the Gemini API (or relevant API)

  1. In the "API & Services" section, click on "Library."

  2. Search for the "Gemini" API or any specific AI API you want to use.

  3. Click on the API and then click "Enable" to activate it for your project.

Step 4: Create Credentials (API Key)

  1. After enabling the API, navigate to the "Credentials" tab on the left sidebar.

  2. Click on "Create Credentials" and select "API Key" from the dropdown menu.

  3. Google will generate an API key for you. You can copy this key to your clipboard.

  1. Click on "Edit" next to your API key to add restrictions.

  2. You can restrict the key by IP addresses, referrer URLs, or by the specific API it can access.

  3. Click "Save" to apply the restrictions.

Step 6: Add the API Key to Your Flutter Project

  1. Replace 'YOUR_API_KEY' in your Flutter project's code with the API key you copied.

Step 7: Use the API Key in Your Application

  1. Now that you have the API key, you can use it in your Flutter app to make requests to the Gemini AI API or any other enabled API.

Important Notes:

  • Keep Your API Key Secure: Never share your API key publicly or include it directly in client-side code without precautions. Use environment variables or other secure methods to store it.

  • Monitor Usage: You can monitor your API usage and manage your API keys from the Google Cloud Console.


Integrating AI into Flutter apps can significantly enhance user experience by providing intelligent features and responses. By following the steps outlined in this guide, you can successfully incorporate the Gemini AI API into your Flutter project. From setting up dependencies and creating a service to handle API requests, to designing a user-friendly interface for input and output.

Did you find this article valuable?

Support JoFlee by becoming a sponsor. Any amount is appreciated!