Lets talk to Gemini Ai

We need an Api Key , you can generate one from

To use the Gemini API, you'll need an API key. If you don't already have one, create a key in Google AI Studio.

Get an API key

Secure your API key

Keep your API key secure. We strongly recommend that you do not include the API key directly in your code, or check files that contain the key into version control systems. Instead, you should use a secrets store for your API key.

All the snippets in this quickstart assume that you're accessing your API key as a process environment variable. If you're developing a Flutter app, you can use String.fromEnvironment and pass --dart-define=API_KEY=$API_KEY to flutter build or flutter run to compile with the API key since the process environment will be different when running the app.

Create a new file consts.dart to store api key , we can also use environments.

const apiKey = "";

Chat logic is in char_widget.dart

we will be using Gemini model : gemini-1.0-pro

in the initState let's initialise the model, for this, we will need to import in pubspec.yaml

flutter pub add google_generative_ai
google_generative_ai

create variable for model and chat session

late final GenerativeModel _model;
late final ChatSession _chat;
void initState() {
    super.initState();
    _model = GenerativeModel(
      model: 'gemini-1.0-pro',
      apiKey: apiKey,
    );
     
    _chat = _model.startChat(history: [
      Content.text(
          "Let's play a two-player game where I have to guess the names of movies from the emojis and then I will ask the same."),
      Content.model(
          [TextPart("Here's the first one: 🍫🏭👦🏻. What movie is this?")])
    ]);
  }

We have created a chat session with some context and a prompt

The chat conversation can be displayed in the list, modify listviewbuilder to show the chat messages between AI and user

ListView.builder(
            shrinkWrap: true,
            controller: _scrollController,
            itemBuilder: (context, idx) {
              var content = _chat.history.toList()[idx];
              var text = content.parts
                  .whereType<TextPart>()
                  .map<String>((e) => e.text)
                  .join('');
              return MessageWidget(
                text: text,
                isFromUser: content.role == 'user',
              );
            },
            itemCount: _chat.history.length,
          ),

When the user types a message _sendChatMessage is called

Future<void> _sendChatMessage(String message) async {
    setState(() {
      _loading = true;
    });

    try {
      var response = await _chat.sendMessage(
        Content.text(message),
      );
      var text = response.text;

      if (text == null) {
        _showError('Empty response.');
        return;
      } else {
        setState(() {
          _loading = false;
          _scrollDown();
        });
      }
    } catch (e) {
      _showError(e.toString());
      setState(() {
        _loading = false;
      });
    } finally {
      _textController.clear();
      setState(() {
        _loading = false;
      });
      _textFieldFocus.requestFocus();
    }
  }

Last updated