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
Implementing Rest API in Flutter
Along with building a UI in Flutter, we can also integrate it with the backend. Most applications use APIs to display user data. We will use the http package, which provides advanced methods to perform operations. REST APIs use simple HTTP calls to communicate with JSON data because:It uses await
5 min read
Flutter - Using Google fonts
Any UI developer that builds an application has to deal with fonts. Google Fonts provides a wide range of fonts that can be used to improve the fonts of the User Interface. Flutter provides a Google fonts package that can be used to implements various available fonts. Some fonts that are available f
3 min read
How to Integrate Google Maps in Flutter Applications?
We all have seen that Google Maps is used by many applications such as Ola, Uber, Swiggy, and others. We must set up an API project with the Google Maps Platform in order to integrate Google Maps into our Flutter application. In this article, we will look at How to Integrate Google Maps in Flutter A
4 min read
Flutter - How to Get Instagram Username Data
Flutter is a cross-platform application development toolkit developed and maintained by Google. Flutter redefines cross-platform app development by combining great design with superb capabilities. Flutter was released to the public in 2017, and since then many large corporations have shifted towards
3 min read
Flutter - Save Password in Google Account
When you are using different websites and apps, you can see there is an option available to store the password in Google so that you can use it in the future and donât need to remember it. You can fill many things from autofill in Google for future reference. We can do this from the flutter built-in
5 min read
Flutter - How to Integrate Mapbox
Maps have become an aspect of our routines. Whether you're exploring a city looking for a coffee shop or keeping tabs on delivery maps is incredibly valuable. When it comes to creating apps incorporating maps not only improves the user experience but is also frequently necessary, for applications th
7 min read
SQLite in Flutter
SQLite is a very popular choice of local storage database. It is an SQL lightweight and serverless database engine that is highly efficient and user-friendly. Flutter, Google's UI toolkit for building natively compiled applications, doesn't come with built-in support for local data storage but provi
5 min read
Google Sign In With Firebase in Flutter
Firebase is a product of Google that helps developers to build, manage, and grow their apps easily. It helps developers build their apps faster and more securely. No programming is required on the Firebase side which makes it easy to use its features more efficiently. Google Sign-in with Firebase in
6 min read
Integrating Maps and Geolocation Services Flutter
In today's Android application, incorporating maps and geolocation services is essential. Whether it be finding the user's location, finding nearby travel places, or providing navigation, these features might really enhance the user experience and ease it down. Flutter, Google's UI toolkit for build
6 min read
Flutter - Create TypeAdapters in Hive
Flutter is open source framework from which we can create cross-platform applications with a single codebase. Hive is a local device storage that stores data in your phone storage. We store user profiles and tokens whether they are logged in or not like that thing. To deeply understand what hive ple
3 min read