Flutter - Integrate Google Gemini API
Last Updated :
21 Apr, 2025
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:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Use Case Diagram - Unified Modeling Language (UML) A Use Case Diagram in Unified Modeling Language (UML) is a visual representation that illustrates the interactions between users (actors) and a system. It captures the functional requirements of a system, showing how different users engage with various use cases, or specific functionalities, within
9 min read
Half Wave Rectifier A Half-wave rectifier is an electronic device that is used to convert Alternating current (AC) to Direct current (DC). A half-wave rectifier allows either a positive or negative half-cycle of AC to pass and blocks the other half-cycle. Half-wave rectifier selectively allows only one half-cycle of th
15 min read
Flutter Tutorial This Flutter Tutorial is specifically designed for beginners and experienced professionals. It covers both the basics and advanced concepts of the Flutter framework.Flutter is Googleâs mobile SDK that builds native Android and iOS apps from a single codebase. It was developed in December 2017. When
7 min read
What is Agile Methodology? The Agile methodology is a proper way of managing the project with breaking them into smaller phases which is iteration. It basically focus on flexibility of the project which we can change and improve the team work regularly as per requirements.Table of ContentWhat is Agile?What is the Agile Method
14 min read
How to Download and Install the Google Play Store The Google Play Store is the heartbeat of your Android experienceâhome to millions of apps, games, and updates that keep your device functional, fun, and secure. But what if your phone or tablet doesnât have it pre-installed?In this step-by-step guide, youâll learn how to safely download and install
6 min read
Top 8 Software Development Life Cycle (SDLC) Models used in Industry Software development models are various processes or methods that are chosen for project development depending on the objectives and goals of the project. Many development life cycle models have been developed to achieve various essential objectives. Models specify the various steps of the process a
9 min read
IEEE 802.11 Architecture The IEEE 802.11 standard, commonly known as Wi-Fi, outlines the architecture and defines the MAC and physical layer specifications for wireless LANs (WLANs). Wi-Fi uses high-frequency radio waves instead of cables for connecting the devices in LAN. Given the mobility of WLAN nodes, they can move unr
9 min read
Schmitt Trigger We use Schmitt Triggers in digital electronics. It is used for rejecting the noise from the input signals by using the hysteresis curve. To provide accurate and more stable results, it uses two threshold voltages i.e., upper threshold voltage (VUT) and lower threshold voltage (VLT). It is mainly use
11 min read