3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

導入

Flutterを使ってGoogle Generative AI (Gemini) を導入し、AI生成コンテンツを簡単に活用する手順を紹介します。FlutterアプリケーションにAI機能を追加してみましょう。
今回、GoogleのGenerative AIサービス「Gemini」をFlutterアプリに統合し、テキスト生成機能を実装する方法を説明します。

手順

利用するパッケージ

こちらがGiminiを利用する上でメインのパッケージになります。

Geminiを利用するために、以下のパッケージを追加します。

  • google_generative_ai: Google Generative AIのAPIを利用するためのパッケージ(上記と同じ)
  • flutter_dotenv: .envファイルから環境変数を読み込むためのパッケージ

ターミナルで次のコマンドを実行して、これらのパッケージをインストールします。

flutter pub add google_generative_ai
flutter pub add flutter_dotenv

APIキーの取得

Google Generative AIサービスを利用するにはAPIキーが必要です。以下の手順でAPIキーを取得します:

  1. Google AI Studioにアクセスします。
  2. Googleアカウントでログインします。
  3. 「APIキーの取得」セクションで、新しいAPIキーを生成します。
  4. 生成されたAPIキーをメモ(コピー)しておきます。

実装

次に、FlutterアプリにGeminiを利用するためのコードを記述します。

1. .envファイルの作成

プロジェクトのルートディレクトリに.envファイルを作成し、以下のようにAPIキーを設定します。

.env
GEMINI_API_KEY=上記で取得したAPIKey

2. main.dartの編集

main.dartに以下のコードを追加して、環境変数を読み込むようにします:

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

Future main() async {
    // .envファイルを読み込み(この1行を追加)
    await dotenv.load(fileName: ".env");
    
    runApp(MyApp());
}

3. テキスト生成関数の追加

Gemini APIを利用してテキストを生成する関数を作成します。

import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:google_generative_ai/google_generative_ai.dart';
import 'dart:developer';
import 'dart:io';

Future<String> chatting(String inputText) async {
    var apiKey = dotenv.get('GEMINI_API_KEY');
    if (apiKey == null) {
        log('API Key取得失敗');
        exit(1);
    }
    
    final genModel = GenerativeModel(model: 'gemini-pro', apiKey: apiKey);
    final content = [Content.text(inputText)];

    final response = await genModel.generateContent(content);
    String resText = response.text ?? 'Gemini返答失敗';
    return resText;
}

4. テスト

テキスト生成関数が正しく動作するかをテストします。例えば、以下のように簡単なUIを作成し、chatting関数を使って生成されたテキストを表示するようにします:

MyApp.dart
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Gemini Text Generator')),
        body: Center(
          child: FutureBuilder<String>(
            future: chatting('こんにちは、Gemini!'),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return CircularProgressIndicator();
              } else if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              } else {
                return Text(snapshot.data ?? 'レスポンスなし');
              }
            },
          ),
        ),
      ),
    );
  }
}

これで、アプリケーションを実行すると、指定したテキストに対してGeminiから生成された応答が表示されます。

終わりに

Flutterを使用してGoogleのGenerative AI「Gemini」を統合する手順を解説しました。

ぜひ試してみてください!

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?