Open In App

Flutter - Integrate Google Gemini API

Last Updated : 21 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Currently, Artificial Intelligence is blooming all around. You must have heard about the ChatGPT, Bard and now Google has come up with a very new Artificial intelligence Gemini which responds to users in a truly human-like way. You can connect Google Gemini with Flutter in a very simple and quick way. Let's learn how to do that. A sample video is given below to get an idea of what we are going to do in this article.

Step-by-Step Implementation

Step 1: Create a new Flutter Application

Create a new Flutter application using the command Prompt. To create a new app, write the following command and run it.

flutter create app_name

To know more about it refer this article: Creating a Simple Application in Flutter.

Step 2: Adding the Dependency

To add the dependency to the pubspec.yaml file, add  flutter_gemini as a dependency in the dependencies part of the pubspec.yaml file, as shown below:

Dart
dependencies:
     flutter:
       sdk: flutter
     flutter_gemini: ^3.0.0

Now, run the below command in the terminal.

flutter pub get

Or

Run the below command in the terminal.

flutter pub add flutter_gemini


Step 3: Import dependencies

To use libraries, import all of them in the respective .dart file,

import 'package:flutter_gemini/flutter_gemini.dart';

Step 4: Generate the Gemini API key

To generate Google Gemini API key, Click here and You can refer to this article to know about how to access and Use Google Gemini API Key (with Examples).


Step 5: Working with main.dart

Add the boilerplate code below in main.dart to initialize the Firebase in the main function and create a basic structure with an MaterialApp.

main.dart:

main.dart
import 'package:flutter/material.dart';
import 'package:flutter_gemini/flutter_gemini.dart';


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

// Main application widget
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false, 
      home: ChatScreen(),
    );
  }
}

// Stateful widget for the chat screen
class ChatScreen extends StatefulWidget {
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

// State class for ChatScreen
class _ChatScreenState extends State<ChatScreen> {
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GFG Chatbot'), // App bar title
        backgroundColor: Colors.green, // App bar background color
        foregroundColor: Colors.white, // App bar text color
      ),
      body: // Code Here
    );
  }
}


Step 6: Initialize variables

- Initialize the required global variable outside every class and main method:

Dart
// API key for Gemini initialization
const apiKey = 'YOUR_API_KEY';


- Initialize Gemini with the API key inside the main method:

Dart
void main() {
  // Initialize Gemini with the API key and enable debugging
  Gemini.init(apiKey: apiKey, enableDebugging: true);
  runApp(MyApp());
}


- Initialize the required variables in the _ChatScreenState class.

Dart
// Controller for the input field
final TextEditingController _controller = TextEditingController(); 
// List to store chat messages
final List<Map<String, String>> _messages = [];


Step 4: Create the _sendMessage method

Create a method to handle sending requests and collecting responses.

Dart
// Function to handle sending a message
void _sendMessage() async {
    final inputText = _controller.text.trim(); // Get and trim the input text
    if (inputText.isEmpty) return; // Do nothing if input is empty
    
    // Add the user's message to the chat
    setState(() {
        _messages.add({'sender': 'user', 'text': inputText});
    });
    
    _controller.clear(); // Clear the input field
    
    // Prepare the input for the Gemini API
    final parts = [Part.text(inputText)];
    final response = await Gemini.instance
    .prompt(parts: parts); // Get the response from Gemini
    
    // Add the bot's response to the chat
    setState(() {
        _messages.add({
            'sender': 'bot',
            'text':
            response?.output ?? 'No response generated', // Handle null response
        });
    });
}


Step 8: Develop UI

- ListView.builder(): To display the chats in a scrollable and vertical list.

Dart
ListView.builder(
    // Number of messages
    itemCount: _messages.length, 
    itemBuilder: (context, index) {
        final message = _messages[index];
        // Check if the message is from the user
        final isUser = message['sender'] == 'user'; 
        return Align(
            alignment: isUser
            ? Alignment.centerRight
            : Alignment.centerLeft, 
            child: Container(
                margin: EdgeInsets.symmetric(
                vertical: 4, horizontal: 8), 
                padding: EdgeInsets.all(12), 
                decoration: BoxDecoration(
                            color: isUser
                            ? Colors.blue[100]
                            : Colors.grey[300], 
                            borderRadius:
                            BorderRadius.circular(8), 
                           ),
                child:Text(message['text'] ?? ''), 
            ),
        );
    },
),


- TextField: To take input from the user.

Dart
TextField(
    // Attach the controller
    controller: _controller, 
    decoration: InputDecoration(
        // Placeholder text
        hintText: 'Type your message...', 
        border: OutlineInputBorder(), 
    ),
),


- ElevatedButton: To call the _sendMessage method.

Dart
ElevatedButton(
    style: ElevatedButton.styleFrom(
        shape: CircleBorder(), 
        padding: EdgeInsets.all(12), 
        backgroundColor: Colors.green, 
        foregroundColor: Colors.white,
    ),
    // Call _sendMessage when pressed
    onPressed: _sendMessage, 
    child: Icon(
            Icons.send, 
            size: 30, 
           ),
),


Complete Source Code

main.dart:

Dart
import 'package:flutter/material.dart';
import 'package:flutter_gemini/flutter_gemini.dart';

// API key for Gemini initialization
const apiKey = 'YOUR_API_KEY';

void main() {
  // Initialize Gemini with the API key and enable debugging
  Gemini.init(apiKey: apiKey, enableDebugging: true);
  runApp(MyApp());
}

// Main application widget
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false, 
      home: ChatScreen(), 
    );
  }
}

// Stateful widget for the chat screen
class ChatScreen extends StatefulWidget {
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

// State class for ChatScreen
class _ChatScreenState extends State<ChatScreen> {
  // Controller for the input field
  final TextEditingController _controller = TextEditingController(); 
  // List to store chat messages
  final List<Map<String, String>> _messages = []; 

  // Function to handle sending a message
  void _sendMessage() async {
    // Get and trim the input text
    final inputText = _controller.text.trim(); 
    // Do nothing if input is empty
    if (inputText.isEmpty) return; 

    // Add the user's message to the chat
    setState(() {
      _messages.add({'sender': 'user', 'text': inputText});
    });
    // Clear the input field
    _controller.clear(); 

    // Prepare the input for the Gemini API
    final parts = [Part.text(inputText)];
     // Get the response from Gemini
    final response = await Gemini.instance
        .prompt(parts: parts);

    // Add the bot's response to the chat
    setState(() {
      _messages.add({
        'sender': 'bot',
        'text': response?.output ?? 'No response generated', // Handle null response
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GFG Chatbot'),
        backgroundColor: Colors.green, 
        foregroundColor: Colors.white, 
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0), 
        child: Column(
          children: [
            // Expanded widget to display the chat messages
            Expanded(
              child: ListView.builder(
                // Number of messages
                itemCount: _messages.length, 
                itemBuilder: (context, index) {
                  final message = _messages[index];
                  // Check if the message is from the user
                  final isUser = message['sender'] =='user'; 
                  return Align(
                    alignment: isUser
                        ? Alignment.centerRight
                        : Alignment.centerLeft, 
                    child: Container(
                      margin: EdgeInsets.symmetric(
                          vertical: 4, horizontal: 8), 
                      padding: EdgeInsets.all(12), 
                      decoration: BoxDecoration(
                        color: isUser
                            ? Colors.blue[100]
                            : Colors.grey[300], 
                        borderRadius:
                            BorderRadius.circular(8), 
                      ),
                      child:
                          Text(message['text'] ?? ''), 
                    ),
                  );
                },
              ),
            ),
            // Input field and send button
            Padding(
              padding:
                  const EdgeInsets.all(8.0), 
              child: Row(
                children: [
                  // Input field for typing messages
                  Expanded(
                    child: TextField(
                      // Attach the controller
                      controller: _controller, 
                      decoration: InputDecoration(
                        // Placeholder text
                        hintText: 'Type your message...', 
                        border: OutlineInputBorder(), 
                      ),
                    ),
                  ),
                  SizedBox(width: 8), 
                  // Send button
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      shape: CircleBorder(), 
                      padding: EdgeInsets.all(12), 
                      backgroundColor: Colors.green,
                      foregroundColor: Colors.white,
                    ),
                    // Call _sendMessage when pressed
                    onPressed: _sendMessage, 
                    child: Icon(
                      Icons.send, 
                      size: 30, 
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}


Output:




Next Article

Similar Reads