├── example ├── linux │ ├── .gitignore │ ├── main.cc │ ├── flutter │ │ ├── generated_plugin_registrant.h │ │ ├── generated_plugin_registrant.cc │ │ ├── generated_plugins.cmake │ │ └── CMakeLists.txt │ ├── my_application.h │ ├── my_application.cc │ └── CMakeLists.txt ├── ios │ ├── Flutter │ │ ├── Debug.xcconfig │ │ ├── Release.xcconfig │ │ └── AppFrameworkInfo.plist │ ├── Runner │ │ ├── Runner-Bridging-Header.h │ │ ├── Assets.xcassets │ │ │ ├── LaunchImage.imageset │ │ │ │ ├── LaunchImage.png │ │ │ │ ├── LaunchImage@2x.png │ │ │ │ ├── LaunchImage@3x.png │ │ │ │ ├── README.md │ │ │ │ └── Contents.json │ │ │ └── AppIcon.appiconset │ │ │ │ ├── Icon-App-20x20@1x.png │ │ │ │ ├── Icon-App-20x20@2x.png │ │ │ │ ├── Icon-App-20x20@3x.png │ │ │ │ ├── Icon-App-29x29@1x.png │ │ │ │ ├── Icon-App-29x29@2x.png │ │ │ │ ├── Icon-App-29x29@3x.png │ │ │ │ ├── Icon-App-40x40@1x.png │ │ │ │ ├── Icon-App-40x40@2x.png │ │ │ │ ├── Icon-App-40x40@3x.png │ │ │ │ ├── Icon-App-60x60@2x.png │ │ │ │ ├── Icon-App-60x60@3x.png │ │ │ │ ├── Icon-App-76x76@1x.png │ │ │ │ ├── Icon-App-76x76@2x.png │ │ │ │ ├── Icon-App-1024x1024@1x.png │ │ │ │ ├── Icon-App-83.5x83.5@2x.png │ │ │ │ └── Contents.json │ │ ├── AppDelegate.swift │ │ ├── Base.lproj │ │ │ ├── Main.storyboard │ │ │ └── LaunchScreen.storyboard │ │ └── Info.plist │ ├── Runner.xcodeproj │ │ ├── project.xcworkspace │ │ │ ├── contents.xcworkspacedata │ │ │ └── xcshareddata │ │ │ │ ├── WorkspaceSettings.xcsettings │ │ │ │ └── IDEWorkspaceChecks.plist │ │ └── xcshareddata │ │ │ └── xcschemes │ │ │ └── Runner.xcscheme │ ├── Runner.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ │ ├── WorkspaceSettings.xcsettings │ │ │ └── IDEWorkspaceChecks.plist │ ├── RunnerTests │ │ └── RunnerTests.swift │ └── .gitignore ├── macos │ ├── Flutter │ │ ├── Flutter-Debug.xcconfig │ │ ├── Flutter-Release.xcconfig │ │ └── GeneratedPluginRegistrant.swift │ ├── Runner │ │ ├── Configs │ │ │ ├── Debug.xcconfig │ │ │ ├── Release.xcconfig │ │ │ ├── Warnings.xcconfig │ │ │ └── AppInfo.xcconfig │ │ ├── Assets.xcassets │ │ │ └── AppIcon.appiconset │ │ │ │ ├── app_icon_128.png │ │ │ │ ├── app_icon_16.png │ │ │ │ ├── app_icon_256.png │ │ │ │ ├── app_icon_32.png │ │ │ │ ├── app_icon_512.png │ │ │ │ ├── app_icon_64.png │ │ │ │ ├── app_icon_1024.png │ │ │ │ └── Contents.json │ │ ├── AppDelegate.swift │ │ ├── Release.entitlements │ │ ├── DebugProfile.entitlements │ │ ├── MainFlutterWindow.swift │ │ └── Info.plist │ ├── .gitignore │ ├── Runner.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ ├── Runner.xcodeproj │ │ ├── project.xcworkspace │ │ │ └── xcshareddata │ │ │ │ └── IDEWorkspaceChecks.plist │ │ └── xcshareddata │ │ │ └── xcschemes │ │ │ └── Runner.xcscheme │ └── RunnerTests │ │ └── RunnerTests.swift ├── web │ ├── favicon.png │ ├── icons │ │ ├── Icon-192.png │ │ ├── Icon-512.png │ │ ├── Icon-maskable-192.png │ │ └── Icon-maskable-512.png │ ├── manifest.json │ └── index.html ├── android │ ├── gradle.properties │ ├── app │ │ ├── src │ │ │ ├── main │ │ │ │ ├── res │ │ │ │ │ ├── mipmap-hdpi │ │ │ │ │ │ └── ic_launcher.png │ │ │ │ │ ├── mipmap-mdpi │ │ │ │ │ │ └── ic_launcher.png │ │ │ │ │ ├── mipmap-xhdpi │ │ │ │ │ │ └── ic_launcher.png │ │ │ │ │ ├── mipmap-xxhdpi │ │ │ │ │ │ └── ic_launcher.png │ │ │ │ │ ├── mipmap-xxxhdpi │ │ │ │ │ │ └── ic_launcher.png │ │ │ │ │ ├── drawable │ │ │ │ │ │ └── launch_background.xml │ │ │ │ │ ├── drawable-v21 │ │ │ │ │ │ └── launch_background.xml │ │ │ │ │ ├── values │ │ │ │ │ │ └── styles.xml │ │ │ │ │ └── values-night │ │ │ │ │ │ └── styles.xml │ │ │ │ ├── kotlin │ │ │ │ │ └── com │ │ │ │ │ │ └── example │ │ │ │ │ │ └── example │ │ │ │ │ │ └── MainActivity.kt │ │ │ │ └── AndroidManifest.xml │ │ │ ├── debug │ │ │ │ └── AndroidManifest.xml │ │ │ └── profile │ │ │ │ └── AndroidManifest.xml │ │ └── build.gradle │ ├── gradle │ │ └── wrapper │ │ │ └── gradle-wrapper.properties │ ├── .gitignore │ ├── build.gradle │ └── settings.gradle ├── screenshots │ ├── gemini_cover.jpeg │ └── gemini_screenshot.png ├── windows │ ├── runner │ │ ├── resources │ │ │ └── app_icon.ico │ │ ├── resource.h │ │ ├── utils.h │ │ ├── runner.exe.manifest │ │ ├── flutter_window.h │ │ ├── main.cpp │ │ ├── CMakeLists.txt │ │ ├── utils.cpp │ │ ├── flutter_window.cpp │ │ ├── Runner.rc │ │ └── win32_window.h │ ├── .gitignore │ ├── flutter │ │ ├── generated_plugin_registrant.h │ │ ├── generated_plugin_registrant.cc │ │ ├── generated_plugins.cmake │ │ └── CMakeLists.txt │ └── CMakeLists.txt ├── README.md ├── lib │ ├── widgets │ │ ├── item_image_view.dart │ │ └── chat_input_box.dart │ ├── sections │ │ ├── text_only.dart │ │ ├── embed_content.dart │ │ ├── embed_batch_contents.dart │ │ ├── chat.dart │ │ ├── response_widget_stream.dart │ │ ├── chat_stream.dart │ │ ├── text_and_image.dart │ │ └── stream.dart │ └── main.dart ├── .gitignore ├── test │ └── widget_test.dart ├── analysis_options.yaml ├── .metadata └── pubspec.yaml ├── assets ├── img.png ├── moon.jpg └── json_models │ ├── generation_config.json │ ├── gemini_model.json │ └── gemini_response.json ├── analysis_options.yaml ├── lib ├── src │ ├── utils │ │ ├── candidate_extension.dart │ │ ├── gemini_exception.dart │ │ └── gemini_exception_handler_mixin.dart │ ├── models │ │ ├── parts │ │ │ ├── parts.g.dart │ │ │ ├── parts.dart │ │ │ └── parts.freezed.dart │ │ ├── gemini_safety │ │ │ ├── gemini_safety.dart │ │ │ ├── gemini_safety_category.dart │ │ │ └── gemini_safety_threshold.dart │ │ ├── content │ │ │ ├── content.dart │ │ │ └── content.g.dart │ │ ├── safety_ratings │ │ │ ├── safety_ratings.dart │ │ │ └── safety_ratings.g.dart │ │ ├── prompt_feedback │ │ │ ├── prompt_feedback.dart │ │ │ ├── prompt_feedback.g.dart │ │ │ └── prompt_feedback.freezed.dart │ │ ├── candidates │ │ │ ├── candidates.dart │ │ │ └── candidates.g.dart │ │ ├── gemini_response │ │ │ ├── gemini_response.dart │ │ │ └── gemini_response.g.dart │ │ ├── generation_config │ │ │ ├── generation_config.dart │ │ │ └── generation_config.g.dart │ │ └── gemini_model │ │ │ ├── gemini_model.dart │ │ │ └── gemini_model.g.dart │ ├── repository │ │ ├── api_interface.dart │ │ └── gemini_interface.dart │ ├── widgets │ │ └── gemini_response_type_view.dart │ ├── provider │ │ └── gemini_response_provider.dart │ ├── implement │ │ └── gemini_service.dart │ └── config │ │ └── constants.dart └── flutter_gemini.dart ├── .metadata ├── test ├── features │ ├── list_models_test.dart │ ├── info_test.dart │ ├── count_tokens_test.dart │ ├── text_test.dart │ ├── text_and_image_test.dart │ └── chat_test.dart └── flutter_gemini_test.dart ├── .gitignore ├── pubspec.yaml ├── CHANGELOG.md └── LICENSE /example/linux/.gitignore: -------------------------------------------------------------------------------- 1 | flutter/ephemeral 2 | -------------------------------------------------------------------------------- /example/ios/Flutter/Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include "Generated.xcconfig" 2 | -------------------------------------------------------------------------------- /example/ios/Flutter/Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include "Generated.xcconfig" 2 | -------------------------------------------------------------------------------- /example/ios/Runner/Runner-Bridging-Header.h: -------------------------------------------------------------------------------- 1 | #import "GeneratedPluginRegistrant.h" 2 | -------------------------------------------------------------------------------- /assets/img.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/assets/img.png -------------------------------------------------------------------------------- /assets/moon.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/assets/moon.jpg -------------------------------------------------------------------------------- /example/macos/Flutter/Flutter-Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include "ephemeral/Flutter-Generated.xcconfig" 2 | -------------------------------------------------------------------------------- /example/macos/Flutter/Flutter-Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include "ephemeral/Flutter-Generated.xcconfig" 2 | -------------------------------------------------------------------------------- /example/web/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/web/favicon.png -------------------------------------------------------------------------------- /example/android/gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs=-Xmx1536M 2 | android.useAndroidX=true 3 | android.enableJetifier=true 4 | -------------------------------------------------------------------------------- /example/macos/Runner/Configs/Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include "../../Flutter/Flutter-Debug.xcconfig" 2 | #include "Warnings.xcconfig" 3 | -------------------------------------------------------------------------------- /example/web/icons/Icon-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/web/icons/Icon-192.png -------------------------------------------------------------------------------- /example/web/icons/Icon-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/web/icons/Icon-512.png -------------------------------------------------------------------------------- /example/macos/Runner/Configs/Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include "../../Flutter/Flutter-Release.xcconfig" 2 | #include "Warnings.xcconfig" 3 | -------------------------------------------------------------------------------- /example/screenshots/gemini_cover.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/screenshots/gemini_cover.jpeg -------------------------------------------------------------------------------- /example/macos/.gitignore: -------------------------------------------------------------------------------- 1 | # Flutter-related 2 | **/Flutter/ephemeral/ 3 | **/Pods/ 4 | 5 | # Xcode-related 6 | **/dgph 7 | **/xcuserdata/ 8 | -------------------------------------------------------------------------------- /example/web/icons/Icon-maskable-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/web/icons/Icon-maskable-192.png -------------------------------------------------------------------------------- /example/web/icons/Icon-maskable-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/web/icons/Icon-maskable-512.png -------------------------------------------------------------------------------- /example/screenshots/gemini_screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/screenshots/gemini_screenshot.png -------------------------------------------------------------------------------- /example/windows/runner/resources/app_icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/windows/runner/resources/app_icon.ico -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /assets/json_models/generation_config.json: -------------------------------------------------------------------------------- 1 | { 2 | "stopSequences": [ 3 | "Title" 4 | ], 5 | "temperature": 1.0, 6 | "maxOutputTokens": 800, 7 | "topP": 0.8, 8 | "topK": 10 9 | } -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png -------------------------------------------------------------------------------- /example/android/app/src/main/kotlin/com/example/example/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.example.example 2 | 3 | import io.flutter.embedding.android.FlutterActivity 4 | 5 | class MainActivity: FlutterActivity() { 6 | } 7 | -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AP2Topper0127/flutter_gemini/HEAD/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png -------------------------------------------------------------------------------- /example/linux/main.cc: -------------------------------------------------------------------------------- 1 | #include "my_application.h" 2 | 3 | int main(int argc, char** argv) { 4 | g_autoptr(MyApplication) app = my_application_new(); 5 | return g_application_run(G_APPLICATION(app), argc, argv); 6 | } 7 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/ios/Runner.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/macos/Runner.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:flutter_lints/flutter.yaml 2 | 3 | # Additional information about this file can be found at 4 | # https://dart.dev/guides/language/analysis-options 5 | analyzer: 6 | errors: 7 | invalid_annotation_target: ignore -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-all.zip 6 | -------------------------------------------------------------------------------- /example/macos/Runner/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | import Cocoa 2 | import FlutterMacOS 3 | 4 | @NSApplicationMain 5 | class AppDelegate: FlutterAppDelegate { 6 | override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { 7 | return true 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /lib/src/utils/candidate_extension.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter_gemini/src/models/candidates/candidates.dart'; 2 | 3 | /// [CandidateExtension] used when wanna get [output] simply 4 | extension CandidateExtension on Candidates { 5 | String? get output => content?.parts?.lastOrNull?.text; 6 | } 7 | -------------------------------------------------------------------------------- /example/macos/Runner/Release.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PreviewsEnabled 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PreviewsEnabled 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.metadata: -------------------------------------------------------------------------------- 1 | # This file tracks properties of this Flutter project. 2 | # Used by Flutter tool to assess capabilities and perform upgrades etc. 3 | # 4 | # This file should be version controlled and should not be manually edited. 5 | 6 | version: 7 | revision: "2f708eb8396e362e280fac22cf171c2cb467343c" 8 | channel: "stable" 9 | 10 | project_type: package 11 | -------------------------------------------------------------------------------- /example/android/.gitignore: -------------------------------------------------------------------------------- 1 | gradle-wrapper.jar 2 | /.gradle 3 | /captures/ 4 | /gradlew 5 | /gradlew.bat 6 | /local.properties 7 | GeneratedPluginRegistrant.java 8 | 9 | # Remember to never publicly share your keystore. 10 | # See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app 11 | key.properties 12 | **/*.keystore 13 | **/*.jks 14 | -------------------------------------------------------------------------------- /example/macos/Flutter/GeneratedPluginRegistrant.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | import FlutterMacOS 6 | import Foundation 7 | 8 | import file_selector_macos 9 | 10 | func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { 11 | FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) 12 | } 13 | -------------------------------------------------------------------------------- /example/ios/RunnerTests/RunnerTests.swift: -------------------------------------------------------------------------------- 1 | import Flutter 2 | import UIKit 3 | import XCTest 4 | 5 | class RunnerTests: XCTestCase { 6 | 7 | func testExample() { 8 | // If you add code to the Runner application, consider adding tests here. 9 | // See https://developer.apple.com/documentation/xctest for more information about using XCTest. 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /example/macos/RunnerTests/RunnerTests.swift: -------------------------------------------------------------------------------- 1 | import FlutterMacOS 2 | import Cocoa 3 | import XCTest 4 | 5 | class RunnerTests: XCTestCase { 6 | 7 | func testExample() { 8 | // If you add code to the Runner application, consider adding tests here. 9 | // See https://developer.apple.com/documentation/xctest for more information about using XCTest. 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /example/windows/.gitignore: -------------------------------------------------------------------------------- 1 | flutter/ephemeral/ 2 | 3 | # Visual Studio user-specific files. 4 | *.suo 5 | *.user 6 | *.userosscache 7 | *.sln.docstates 8 | 9 | # Visual Studio build-related files. 10 | x64/ 11 | x86/ 12 | 13 | # Visual Studio cache files 14 | # files ending in .cache can be ignored 15 | *.[Cc]ache 16 | # but keep track of directories ending in .cache 17 | !*.[Cc]ache/ 18 | -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md: -------------------------------------------------------------------------------- 1 | # Launch Screen Assets 2 | 3 | You can customize the launch screen with your own desired assets by replacing the image files in this directory. 4 | 5 | You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. -------------------------------------------------------------------------------- /example/linux/flutter/generated_plugin_registrant.h: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #ifndef GENERATED_PLUGIN_REGISTRANT_ 8 | #define GENERATED_PLUGIN_REGISTRANT_ 9 | 10 | #include 11 | 12 | // Registers Flutter plugins. 13 | void fl_register_plugins(FlPluginRegistry* registry); 14 | 15 | #endif // GENERATED_PLUGIN_REGISTRANT_ 16 | -------------------------------------------------------------------------------- /example/windows/flutter/generated_plugin_registrant.h: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #ifndef GENERATED_PLUGIN_REGISTRANT_ 8 | #define GENERATED_PLUGIN_REGISTRANT_ 9 | 10 | #include 11 | 12 | // Registers Flutter plugins. 13 | void RegisterPlugins(flutter::PluginRegistry* registry); 14 | 15 | #endif // GENERATED_PLUGIN_REGISTRANT_ 16 | -------------------------------------------------------------------------------- /example/windows/flutter/generated_plugin_registrant.cc: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #include "generated_plugin_registrant.h" 8 | 9 | #include 10 | 11 | void RegisterPlugins(flutter::PluginRegistry* registry) { 12 | FileSelectorWindowsRegisterWithRegistrar( 13 | registry->GetRegistrarForPlugin("FileSelectorWindows")); 14 | } 15 | -------------------------------------------------------------------------------- /example/android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/android/app/src/profile/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/macos/Runner/DebugProfile.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | com.apple.security.cs.allow-jit 8 | 9 | com.apple.security.network.server 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /example/ios/Runner/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | import Flutter 3 | 4 | @UIApplicationMain 5 | @objc class AppDelegate: FlutterAppDelegate { 6 | override func application( 7 | _ application: UIApplication, 8 | didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? 9 | ) -> Bool { 10 | GeneratedPluginRegistrant.register(with: self) 11 | return super.application(application, didFinishLaunchingWithOptions: launchOptions) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /example/macos/Runner/MainFlutterWindow.swift: -------------------------------------------------------------------------------- 1 | import Cocoa 2 | import FlutterMacOS 3 | 4 | class MainFlutterWindow: NSWindow { 5 | override func awakeFromNib() { 6 | let flutterViewController = FlutterViewController() 7 | let windowFrame = self.frame 8 | self.contentViewController = flutterViewController 9 | self.setFrame(windowFrame, display: true) 10 | 11 | RegisterGeneratedPlugins(registry: flutterViewController) 12 | 13 | super.awakeFromNib() 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /example/linux/my_application.h: -------------------------------------------------------------------------------- 1 | #ifndef FLUTTER_MY_APPLICATION_H_ 2 | #define FLUTTER_MY_APPLICATION_H_ 3 | 4 | #include 5 | 6 | G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, 7 | GtkApplication) 8 | 9 | /** 10 | * my_application_new: 11 | * 12 | * Creates a new Flutter-based application. 13 | * 14 | * Returns: a new #MyApplication. 15 | */ 16 | MyApplication* my_application_new(); 17 | 18 | #endif // FLUTTER_MY_APPLICATION_H_ 19 | -------------------------------------------------------------------------------- /lib/src/utils/gemini_exception.dart: -------------------------------------------------------------------------------- 1 | class GeminiException implements Exception { 2 | /// A message describing the response error. 3 | final Object message; 4 | 5 | /// http response status code 6 | final int? statusCode; 7 | 8 | /// [GeminiException] for unexpected errors 9 | const GeminiException( 10 | this.message, { 11 | this.statusCode, 12 | }); 13 | 14 | @override 15 | String toString() { 16 | return '**GeminiException** => $message\n\tStatus Code: $statusCode'; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /example/windows/runner/resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | // Used by Runner.rc 4 | // 5 | #define IDI_APP_ICON 101 6 | 7 | // Next default values for new objects 8 | // 9 | #ifdef APSTUDIO_INVOKED 10 | #ifndef APSTUDIO_READONLY_SYMBOLS 11 | #define _APS_NEXT_RESOURCE_VALUE 102 12 | #define _APS_NEXT_COMMAND_VALUE 40001 13 | #define _APS_NEXT_CONTROL_VALUE 1001 14 | #define _APS_NEXT_SYMED_VALUE 101 15 | #endif 16 | #endif 17 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/drawable/launch_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/drawable-v21/launch_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /example/linux/flutter/generated_plugin_registrant.cc: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #include "generated_plugin_registrant.h" 8 | 9 | #include 10 | 11 | void fl_register_plugins(FlPluginRegistry* registry) { 12 | g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = 13 | fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); 14 | file_selector_plugin_register_with_registrar(file_selector_linux_registrar); 15 | } 16 | -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "LaunchImage.png", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "filename" : "LaunchImage@2x.png", 11 | "scale" : "2x" 12 | }, 13 | { 14 | "idiom" : "universal", 15 | "filename" : "LaunchImage@3x.png", 16 | "scale" : "3x" 17 | } 18 | ], 19 | "info" : { 20 | "version" : 1, 21 | "author" : "xcode" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /lib/src/models/parts/parts.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'parts.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | _$PartsImpl _$$PartsImplFromJson(Map json) => _$PartsImpl( 10 | text: json['text'] as String?, 11 | ); 12 | 13 | Map _$$PartsImplToJson(_$PartsImpl instance) => 14 | { 15 | 'text': instance.text, 16 | }; 17 | -------------------------------------------------------------------------------- /lib/src/models/parts/parts.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/foundation.dart'; 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | 4 | part 'parts.freezed.dart'; 5 | part 'parts.g.dart'; 6 | 7 | /// [Parts] is the value in the response of request 8 | @unfreezed 9 | class Parts with _$Parts { 10 | factory Parts({ 11 | String? text, 12 | }) = _Parts; 13 | 14 | factory Parts.fromJson(Map json) => _$PartsFromJson(json); 15 | 16 | static List jsonToList(List list) => 17 | list.map((e) => Parts.fromJson(e as Map)).toList(); 18 | } 19 | -------------------------------------------------------------------------------- /test/features/list_models_test.dart: -------------------------------------------------------------------------------- 1 | import 'dart:developer'; 2 | import 'package:flutter_test/flutter_test.dart'; 3 | import 'package:flutter_gemini/flutter_gemini.dart'; 4 | import '../flutter_gemini_test.dart'; 5 | 6 | void main() { 7 | Gemini.init(apiKey: apiKey, enableDebugging: true); 8 | 9 | test('Check Gemini\'s generated model list', () async { 10 | /// an instance 11 | final gemini = Gemini.instance; 12 | await gemini 13 | .listModels() 14 | .then((models) => log(models.toString())) 15 | .catchError((e) => log('listModels', error: e)); 16 | }); 17 | } 18 | -------------------------------------------------------------------------------- /test/features/info_test.dart: -------------------------------------------------------------------------------- 1 | import 'dart:developer'; 2 | import 'package:flutter_test/flutter_test.dart'; 3 | import 'package:flutter_gemini/flutter_gemini.dart'; 4 | import '../flutter_gemini_test.dart'; 5 | 6 | void main() { 7 | Gemini.init(apiKey: apiKey, enableDebugging: true); 8 | 9 | test('Check Gemini\'s generated model info', () async { 10 | /// an instance 11 | final gemini = Gemini.instance; 12 | await gemini 13 | .info(model: 'gemini-pro') 14 | .then((info) => log(info.toString())) 15 | .catchError((e) => log('text input exception', error: e)); 16 | }); 17 | } 18 | -------------------------------------------------------------------------------- /lib/src/repository/api_interface.dart: -------------------------------------------------------------------------------- 1 | import 'package:dio/dio.dart'; 2 | import '../models/gemini_safety/gemini_safety.dart'; 3 | import '../models/generation_config/generation_config.dart'; 4 | 5 | /// [ApiInterface] is api helper service class 6 | abstract class ApiInterface { 7 | GenerationConfig? generationConfig; 8 | List? safetySettings; 9 | 10 | Future post( 11 | String route, { 12 | required Map? data, 13 | GenerationConfig? generationConfig, 14 | List? safetySettings, 15 | }); 16 | 17 | Future get(String route); 18 | } 19 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # example 2 | 3 | A new Flutter project. 4 | 5 | ## Getting Started 6 | 7 | This project is a starting point for a Flutter application. 8 | 9 | A few resources to get you started if this is your first Flutter project: 10 | 11 | - [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) 12 | - [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) 13 | 14 | For help getting started with Flutter development, view the 15 | [online documentation](https://docs.flutter.dev/), which offers tutorials, 16 | samples, guidance on mobile development, and a full API reference. 17 | -------------------------------------------------------------------------------- /test/features/count_tokens_test.dart: -------------------------------------------------------------------------------- 1 | import 'dart:developer'; 2 | import 'package:flutter_test/flutter_test.dart'; 3 | import 'package:flutter_gemini/flutter_gemini.dart'; 4 | import '../flutter_gemini_test.dart'; 5 | 6 | void main() { 7 | Gemini.init(apiKey: apiKey, enableDebugging: true); 8 | 9 | test('check gemini to generate simple text', () async { 10 | /// an instance 11 | final gemini = Gemini.instance; 12 | await gemini 13 | .countTokens("Write a story about a magic backpack.") 14 | .then((value) => log((value ?? 0).toString())) 15 | .catchError((e) => log('text input exception', error: e)); 16 | }); 17 | } 18 | -------------------------------------------------------------------------------- /test/features/text_test.dart: -------------------------------------------------------------------------------- 1 | import 'dart:developer'; 2 | import 'package:flutter_test/flutter_test.dart'; 3 | import 'package:flutter_gemini/flutter_gemini.dart'; 4 | import '../flutter_gemini_test.dart'; 5 | 6 | void main() { 7 | Gemini.init(apiKey: apiKey, enableDebugging: true); 8 | 9 | test('check gemini to generate simple text', () async { 10 | /// an instance 11 | final gemini = Gemini.instance; 12 | await gemini 13 | .text("Write a story about a magic backpack.") 14 | .then((value) => log(value?.content?.parts?.last.text ?? '')) 15 | .catchError((e) => log('text input exception', error: e)); 16 | }); 17 | } 18 | -------------------------------------------------------------------------------- /lib/src/models/gemini_safety/gemini_safety.dart: -------------------------------------------------------------------------------- 1 | import 'gemini_safety_category.dart'; 2 | import 'gemini_safety_threshold.dart'; 3 | 4 | /// [SafetySetting] 5 | ///Safety Settings 6 | /// Safety settings are part of the request you send to the text service. 7 | /// It can be adjusted for each request you make to the API. 8 | /// The following table lists the categories that you can set and describes the type of harm that each category encompasses. 9 | class SafetySetting { 10 | final SafetyCategory category; 11 | final SafetyThreshold threshold; 12 | 13 | SafetySetting({ 14 | required this.category, 15 | required this.threshold, 16 | }); 17 | } 18 | -------------------------------------------------------------------------------- /example/macos/Runner/Configs/Warnings.xcconfig: -------------------------------------------------------------------------------- 1 | WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings 2 | GCC_WARN_UNDECLARED_SELECTOR = YES 3 | CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES 4 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE 5 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES 6 | CLANG_WARN_PRAGMA_PACK = YES 7 | CLANG_WARN_STRICT_PROTOTYPES = YES 8 | CLANG_WARN_COMMA = YES 9 | GCC_WARN_STRICT_SELECTOR_MATCH = YES 10 | CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES 11 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES 12 | GCC_WARN_SHADOW = YES 13 | CLANG_WARN_UNREACHABLE_CODE = YES 14 | -------------------------------------------------------------------------------- /example/lib/widgets/item_image_view.dart: -------------------------------------------------------------------------------- 1 | import 'dart:typed_data'; 2 | 3 | import 'package:flutter/material.dart'; 4 | 5 | class ItemImageView extends StatelessWidget { 6 | final Uint8List bytes; 7 | const ItemImageView({super.key, required this.bytes}); 8 | 9 | @override 10 | Widget build(BuildContext context) { 11 | return Padding( 12 | padding: const EdgeInsets.all(4), 13 | child: ClipRRect( 14 | borderRadius: BorderRadius.circular(12), 15 | child: Image.memory( 16 | bytes, 17 | width: 110, 18 | height: 110, 19 | fit: BoxFit.cover, 20 | ), 21 | ), 22 | ); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /lib/src/models/content/content.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/foundation.dart'; 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | import '../parts/parts.dart'; 4 | part 'content.freezed.dart'; 5 | part 'content.g.dart'; 6 | 7 | /// [Content] is the value in request response 8 | @unfreezed 9 | class Content with _$Content { 10 | factory Content({ 11 | List? parts, 12 | String? role, 13 | }) = _Content; 14 | 15 | factory Content.fromJson(Map json) => 16 | _$ContentFromJson(json); 17 | 18 | static List jsonToList(List list) => 19 | list.map((e) => Content.fromJson(e as Map)).toList(); 20 | } 21 | -------------------------------------------------------------------------------- /example/macos/Runner/Configs/AppInfo.xcconfig: -------------------------------------------------------------------------------- 1 | // Application-level settings for the Runner target. 2 | // 3 | // This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the 4 | // future. If not, the values below would default to using the project name when this becomes a 5 | // 'flutter create' template. 6 | 7 | // The application's name. By default this is also the title of the Flutter window. 8 | PRODUCT_NAME = example 9 | 10 | // The application's bundle identifier 11 | PRODUCT_BUNDLE_IDENTIFIER = com.example.example 12 | 13 | // The copyright displayed in application information 14 | PRODUCT_COPYRIGHT = Copyright © 2023 com.example. All rights reserved. 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Miscellaneous 2 | *.class 3 | *.log 4 | *.pyc 5 | *.swp 6 | .DS_Store 7 | .atom/ 8 | .buildlog/ 9 | .history 10 | .svn/ 11 | migrate_working_dir/ 12 | 13 | # IntelliJ related 14 | *.iml 15 | *.ipr 16 | *.iws 17 | .idea/ 18 | 19 | *.env 20 | 21 | # The .vscode folder contains launch configuration and tasks you configure in 22 | # VS Code which you may wish to be included in version control, so this line 23 | # is commented out by default. 24 | #.vscode/ 25 | 26 | # Flutter/Dart/Pub related 27 | # Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. 28 | /pubspec.lock 29 | **/doc/api/ 30 | .dart_tool/ 31 | .packages 32 | build/ 33 | -------------------------------------------------------------------------------- /example/ios/.gitignore: -------------------------------------------------------------------------------- 1 | **/dgph 2 | *.mode1v3 3 | *.mode2v3 4 | *.moved-aside 5 | *.pbxuser 6 | *.perspectivev3 7 | **/*sync/ 8 | .sconsign.dblite 9 | .tags* 10 | **/.vagrant/ 11 | **/DerivedData/ 12 | Icon? 13 | **/Pods/ 14 | **/.symlinks/ 15 | profile 16 | xcuserdata 17 | **/.generated/ 18 | Flutter/App.framework 19 | Flutter/Flutter.framework 20 | Flutter/Flutter.podspec 21 | Flutter/Generated.xcconfig 22 | Flutter/ephemeral/ 23 | Flutter/app.flx 24 | Flutter/app.zip 25 | Flutter/flutter_assets/ 26 | Flutter/flutter_export_environment.sh 27 | ServiceDefinitions.json 28 | Runner/GeneratedPluginRegistrant.* 29 | 30 | # Exceptions to above rules. 31 | !default.mode1v3 32 | !default.mode2v3 33 | !default.pbxuser 34 | !default.perspectivev3 35 | -------------------------------------------------------------------------------- /lib/flutter_gemini.dart: -------------------------------------------------------------------------------- 1 | library flutter_gemini; 2 | 3 | export 'src/init.dart'; 4 | export 'src/models/gemini_model/gemini_model.dart'; 5 | export 'src/models/candidates/candidates.dart'; 6 | export 'src/models/gemini_response/gemini_response.dart'; 7 | export 'src/models/gemini_safety/gemini_safety.dart'; 8 | export 'src/models/content/content.dart'; 9 | export 'src/models/parts/parts.dart'; 10 | export 'src/models/generation_config/generation_config.dart'; 11 | export 'src/models/gemini_safety/gemini_safety_category.dart'; 12 | export 'src/models/gemini_safety/gemini_safety_threshold.dart'; 13 | export 'src/utils/candidate_extension.dart'; 14 | export 'src/widgets/gemini_response_type_view.dart'; 15 | export 'src/utils/gemini_exception.dart'; 16 | -------------------------------------------------------------------------------- /lib/src/models/gemini_safety/gemini_safety_category.dart: -------------------------------------------------------------------------------- 1 | enum SafetyCategory { 2 | /// [harassment] 3 | /// Negative or harmful comments targeting identity and/or protected attributes. 4 | harassment('HARM_CATEGORY_HARASSMENT'), 5 | 6 | /// [hateSpeech] 7 | /// Content that is rude, disrespectful, or profane. 8 | hateSpeech('HARM_CATEGORY_HATE_SPEECH'), 9 | 10 | /// [sexuallyExplicit] 11 | /// Contains references to sexual acts or other lewd content. 12 | sexuallyExplicit('HARM_CATEGORY_SEXUALLY_EXPLICIT'), 13 | 14 | /// [dangerous] 15 | /// Promotes, facilitates, or encourages harmful acts. 16 | dangerous('HARM_CATEGORY_DANGEROUS_CONTENT'); 17 | 18 | const SafetyCategory(this.value); 19 | final String value; 20 | } 21 | -------------------------------------------------------------------------------- /example/android/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext.kotlin_version = '1.7.10' 3 | repositories { 4 | google() 5 | mavenCentral() 6 | } 7 | 8 | dependencies { 9 | classpath 'com.android.tools.build:gradle:7.3.0' 10 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 11 | } 12 | } 13 | 14 | allprojects { 15 | repositories { 16 | google() 17 | mavenCentral() 18 | } 19 | } 20 | 21 | rootProject.buildDir = '../build' 22 | subprojects { 23 | project.buildDir = "${rootProject.buildDir}/${project.name}" 24 | } 25 | subprojects { 26 | project.evaluationDependsOn(':app') 27 | } 28 | 29 | tasks.register("clean", Delete) { 30 | delete rootProject.buildDir 31 | } 32 | -------------------------------------------------------------------------------- /lib/src/models/safety_ratings/safety_ratings.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/foundation.dart'; 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | 4 | part 'safety_ratings.freezed.dart'; 5 | part 'safety_ratings.g.dart'; 6 | 7 | /// [SafetyRatings] is the value in the response of request 8 | @unfreezed 9 | class SafetyRatings with _$SafetyRatings { 10 | factory SafetyRatings({ 11 | String? category, 12 | String? probability, 13 | }) = _SafetyRatings; 14 | 15 | factory SafetyRatings.fromJson(Map json) => 16 | _$SafetyRatingsFromJson(json); 17 | 18 | static List jsonToList(List list) => list 19 | .map((e) => SafetyRatings.fromJson(e as Map)) 20 | .toList(); 21 | } 22 | -------------------------------------------------------------------------------- /example/windows/runner/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_UTILS_H_ 2 | #define RUNNER_UTILS_H_ 3 | 4 | #include 5 | #include 6 | 7 | // Creates a console for the process, and redirects stdout and stderr to 8 | // it for both the runner and the Flutter library. 9 | void CreateAndAttachConsole(); 10 | 11 | // Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string 12 | // encoded in UTF-8. Returns an empty std::string on failure. 13 | std::string Utf8FromUtf16(const wchar_t* utf16_string); 14 | 15 | // Gets the command line arguments passed in as a std::vector, 16 | // encoded in UTF-8. Returns an empty std::vector on failure. 17 | std::vector GetCommandLineArguments(); 18 | 19 | #endif // RUNNER_UTILS_H_ 20 | -------------------------------------------------------------------------------- /lib/src/models/safety_ratings/safety_ratings.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'safety_ratings.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | _$SafetyRatingsImpl _$$SafetyRatingsImplFromJson(Map json) => 10 | _$SafetyRatingsImpl( 11 | category: json['category'] as String?, 12 | probability: json['probability'] as String?, 13 | ); 14 | 15 | Map _$$SafetyRatingsImplToJson(_$SafetyRatingsImpl instance) => 16 | { 17 | 'category': instance.category, 18 | 'probability': instance.probability, 19 | }; 20 | -------------------------------------------------------------------------------- /lib/src/models/content/content.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'content.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | _$ContentImpl _$$ContentImplFromJson(Map json) => 10 | _$ContentImpl( 11 | parts: (json['parts'] as List?) 12 | ?.map((e) => Parts.fromJson(e as Map)) 13 | .toList(), 14 | role: json['role'] as String?, 15 | ); 16 | 17 | Map _$$ContentImplToJson(_$ContentImpl instance) => 18 | { 19 | 'parts': instance.parts, 20 | 'role': instance.role, 21 | }; 22 | -------------------------------------------------------------------------------- /example/android/settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | def flutterSdkPath = { 3 | def properties = new Properties() 4 | file("local.properties").withInputStream { properties.load(it) } 5 | def flutterSdkPath = properties.getProperty("flutter.sdk") 6 | assert flutterSdkPath != null, "flutter.sdk not set in local.properties" 7 | return flutterSdkPath 8 | } 9 | settings.ext.flutterSdkPath = flutterSdkPath() 10 | 11 | includeBuild("${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle") 12 | 13 | plugins { 14 | id "dev.flutter.flutter-gradle-plugin" version "1.0.0" apply false 15 | } 16 | } 17 | 18 | include ":app" 19 | 20 | apply from: "${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle/app_plugin_loader.gradle" 21 | -------------------------------------------------------------------------------- /lib/src/models/prompt_feedback/prompt_feedback.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/foundation.dart'; 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | import '../safety_ratings/safety_ratings.dart'; 4 | part 'prompt_feedback.freezed.dart'; 5 | part 'prompt_feedback.g.dart'; 6 | 7 | /// [PromptFeedback] is the value in the response of request 8 | @unfreezed 9 | class PromptFeedback with _$PromptFeedback { 10 | factory PromptFeedback({ 11 | List? safetyRatings, 12 | }) = _PromptFeedback; 13 | 14 | factory PromptFeedback.fromJson(Map json) => 15 | _$PromptFeedbackFromJson(json); 16 | 17 | static List jsonToList(List list) => list 18 | .map((e) => PromptFeedback.fromJson(e as Map)) 19 | .toList(); 20 | } 21 | -------------------------------------------------------------------------------- /lib/src/models/prompt_feedback/prompt_feedback.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'prompt_feedback.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | _$PromptFeedbackImpl _$$PromptFeedbackImplFromJson(Map json) => 10 | _$PromptFeedbackImpl( 11 | safetyRatings: (json['safetyRatings'] as List?) 12 | ?.map((e) => SafetyRatings.fromJson(e as Map)) 13 | .toList(), 14 | ); 15 | 16 | Map _$$PromptFeedbackImplToJson( 17 | _$PromptFeedbackImpl instance) => 18 | { 19 | 'safetyRatings': instance.safetyRatings, 20 | }; 21 | -------------------------------------------------------------------------------- /lib/src/models/candidates/candidates.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/foundation.dart'; 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | import '../content/content.dart'; 4 | import '../safety_ratings/safety_ratings.dart'; 5 | part 'candidates.freezed.dart'; 6 | part 'candidates.g.dart'; 7 | 8 | /// [Candidates] is the value in request response 9 | @unfreezed 10 | class Candidates with _$Candidates { 11 | factory Candidates({ 12 | Content? content, 13 | String? finishReason, 14 | int? index, 15 | List? safetyRatings, 16 | }) = _Candidates; 17 | 18 | factory Candidates.fromJson(Map json) => 19 | _$CandidatesFromJson(json); 20 | 21 | static List jsonToList(List list) => 22 | list.map((e) => Candidates.fromJson(e as Map)).toList(); 23 | } 24 | -------------------------------------------------------------------------------- /test/features/text_and_image_test.dart: -------------------------------------------------------------------------------- 1 | import 'dart:developer'; 2 | import 'dart:io'; 3 | import 'package:flutter_test/flutter_test.dart'; 4 | import 'package:flutter_gemini/flutter_gemini.dart'; 5 | import '../flutter_gemini_test.dart'; 6 | 7 | void main() { 8 | Gemini.init(apiKey: apiKey, enableDebugging: true); 9 | 10 | test('Check Gemini\'s generated simple text and image response', () async { 11 | /// an instance 12 | final gemini = Gemini.instance; 13 | final file = File('assets/img.png'); 14 | await gemini 15 | .textAndImage( 16 | text: "What is this picture?", 17 | images: [ 18 | file.readAsBytesSync(), 19 | ], 20 | ) 21 | .then((value) => log(value?.output ?? '')) 22 | .catchError((e) => log('textAndImageInput exception', error: e)); 23 | }); 24 | } 25 | -------------------------------------------------------------------------------- /lib/src/models/gemini_response/gemini_response.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/foundation.dart'; 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | import '../candidates/candidates.dart'; 4 | import '../prompt_feedback/prompt_feedback.dart'; 5 | part 'gemini_response.freezed.dart'; 6 | part 'gemini_response.g.dart'; 7 | 8 | /// [GeminiResponse] is the value in the response of request 9 | @unfreezed 10 | class GeminiResponse with _$GeminiResponse { 11 | factory GeminiResponse({ 12 | List? candidates, 13 | PromptFeedback? promptFeedback, 14 | }) = _GeminiResponse; 15 | 16 | factory GeminiResponse.fromJson(Map json) => 17 | _$GeminiResponseFromJson(json); 18 | 19 | static List jsonToList(List list) => list 20 | .map((e) => GeminiResponse.fromJson(e as Map)) 21 | .toList(); 22 | } 23 | -------------------------------------------------------------------------------- /lib/src/models/generation_config/generation_config.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/foundation.dart'; 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | 4 | part 'generation_config.freezed.dart'; 5 | part 'generation_config.g.dart'; 6 | 7 | /// [GenerationConfig] is used when we want to declare response types 8 | @unfreezed 9 | class GenerationConfig with _$GenerationConfig { 10 | factory GenerationConfig({ 11 | List? stopSequences, 12 | double? temperature, 13 | int? maxOutputTokens, 14 | double? topP, 15 | int? topK, 16 | }) = _GenerationConfig; 17 | 18 | factory GenerationConfig.fromJson(Map json) => 19 | _$GenerationConfigFromJson(json); 20 | 21 | static List jsonToList(List list) => list 22 | .map((e) => GenerationConfig.fromJson(e as Map)) 23 | .toList(); 24 | } 25 | -------------------------------------------------------------------------------- /example/linux/flutter/generated_plugins.cmake: -------------------------------------------------------------------------------- 1 | # 2 | # Generated file, do not edit. 3 | # 4 | 5 | list(APPEND FLUTTER_PLUGIN_LIST 6 | file_selector_linux 7 | ) 8 | 9 | list(APPEND FLUTTER_FFI_PLUGIN_LIST 10 | ) 11 | 12 | set(PLUGIN_BUNDLED_LIBRARIES) 13 | 14 | foreach(plugin ${FLUTTER_PLUGIN_LIST}) 15 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) 16 | target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) 17 | list(APPEND PLUGIN_BUNDLED_LIBRARIES $) 18 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) 19 | endforeach(plugin) 20 | 21 | foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) 22 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) 23 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) 24 | endforeach(ffi_plugin) 25 | -------------------------------------------------------------------------------- /lib/src/models/gemini_safety/gemini_safety_threshold.dart: -------------------------------------------------------------------------------- 1 | enum SafetyThreshold { 2 | /// [blockNone] 3 | /// Always show regardless of probability of unsafe content 4 | blockNone('BLOCK_NONE'), 5 | 6 | /// [blockOnlyHigh] 7 | /// Block when high probability of unsafe content 8 | blockOnlyHigh('BLOCK_ONLY_HIGH'), 9 | 10 | /// [blockMediumAndAbove] 11 | /// Block when medium or high probability of unsafe content 12 | blockMediumAndAbove('BLOCK_MEDIUM_AND_ABOVE'), 13 | 14 | /// [blockLowAndAbove] 15 | /// Block when low, medium or high probability of unsafe content 16 | blockLowAndAbove('BLOCK_LOW_AND_ABOVE'), 17 | 18 | /// [harmBlockThresholdUnspecified] 19 | /// Threshold is unspecified, block using default threshold 20 | harmBlockThresholdUnspecified('HARM_BLOCK_THRESHOLD_UNSPECIFIED'); 21 | 22 | const SafetyThreshold(this.value); 23 | final String value; 24 | } 25 | -------------------------------------------------------------------------------- /example/windows/flutter/generated_plugins.cmake: -------------------------------------------------------------------------------- 1 | # 2 | # Generated file, do not edit. 3 | # 4 | 5 | list(APPEND FLUTTER_PLUGIN_LIST 6 | file_selector_windows 7 | ) 8 | 9 | list(APPEND FLUTTER_FFI_PLUGIN_LIST 10 | ) 11 | 12 | set(PLUGIN_BUNDLED_LIBRARIES) 13 | 14 | foreach(plugin ${FLUTTER_PLUGIN_LIST}) 15 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) 16 | target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) 17 | list(APPEND PLUGIN_BUNDLED_LIBRARIES $) 18 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) 19 | endforeach(plugin) 20 | 21 | foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) 22 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) 23 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) 24 | endforeach(ffi_plugin) 25 | -------------------------------------------------------------------------------- /example/ios/Flutter/AppFrameworkInfo.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | App 9 | CFBundleIdentifier 10 | io.flutter.flutter.app 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | App 15 | CFBundlePackageType 16 | FMWK 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1.0 23 | MinimumOSVersion 24 | 11.0 25 | 26 | 27 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | # Miscellaneous 2 | *.class 3 | *.log 4 | *.pyc 5 | *.swp 6 | .DS_Store 7 | .atom/ 8 | .buildlog/ 9 | .history 10 | .svn/ 11 | migrate_working_dir/ 12 | 13 | # IntelliJ related 14 | *.iml 15 | *.ipr 16 | *.iws 17 | .idea/ 18 | *.env 19 | 20 | # The .vscode folder contains launch configuration and tasks you configure in 21 | # VS Code which you may wish to be included in version control, so this line 22 | # is commented out by default. 23 | #.vscode/ 24 | 25 | # Flutter/Dart/Pub related 26 | **/doc/api/ 27 | **/ios/Flutter/.last_build_id 28 | .dart_tool/ 29 | .flutter-plugins 30 | .flutter-plugins-dependencies 31 | .packages 32 | .pub-cache/ 33 | .pub/ 34 | /build/ 35 | 36 | # Symbolication related 37 | app.*.symbols 38 | 39 | # Obfuscation related 40 | app.*.map.json 41 | 42 | # Android Studio will place build artifacts here 43 | /android/app/debug 44 | /android/app/profile 45 | /android/app/release 46 | 47 | .env -------------------------------------------------------------------------------- /lib/src/models/gemini_model/gemini_model.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/foundation.dart'; 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | 4 | part 'gemini_model.freezed.dart'; 5 | part 'gemini_model.g.dart'; 6 | 7 | /// [GeminiModel] is the AI model and declares AI options 8 | @unfreezed 9 | class GeminiModel with _$GeminiModel { 10 | factory GeminiModel({ 11 | String? name, 12 | String? version, 13 | String? displayName, 14 | String? description, 15 | int? inputTokenLimit, 16 | int? outputTokenLimit, 17 | List? supportedGenerationMethods, 18 | double? temperature, 19 | double? topP, 20 | int? topK, 21 | }) = _GeminiModel; 22 | 23 | factory GeminiModel.fromJson(Map json) => 24 | _$GeminiModelFromJson(json); 25 | 26 | static List jsonToList(List list) => 27 | list.map((e) => GeminiModel.fromJson(e as Map)).toList(); 28 | } 29 | -------------------------------------------------------------------------------- /example/windows/runner/runner.exe.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PerMonitorV2 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /lib/src/models/gemini_response/gemini_response.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'gemini_response.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | _$GeminiResponseImpl _$$GeminiResponseImplFromJson(Map json) => 10 | _$GeminiResponseImpl( 11 | candidates: (json['candidates'] as List?) 12 | ?.map((e) => Candidates.fromJson(e as Map)) 13 | .toList(), 14 | promptFeedback: json['promptFeedback'] == null 15 | ? null 16 | : PromptFeedback.fromJson( 17 | json['promptFeedback'] as Map), 18 | ); 19 | 20 | Map _$$GeminiResponseImplToJson( 21 | _$GeminiResponseImpl instance) => 22 | { 23 | 'candidates': instance.candidates, 24 | 'promptFeedback': instance.promptFeedback, 25 | }; 26 | -------------------------------------------------------------------------------- /example/web/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "short_name": "example", 4 | "start_url": ".", 5 | "display": "standalone", 6 | "background_color": "#0175C2", 7 | "theme_color": "#0175C2", 8 | "description": "A new Flutter project.", 9 | "orientation": "portrait-primary", 10 | "prefer_related_applications": false, 11 | "icons": [ 12 | { 13 | "src": "icons/Icon-192.png", 14 | "sizes": "192x192", 15 | "type": "image/png" 16 | }, 17 | { 18 | "src": "icons/Icon-512.png", 19 | "sizes": "512x512", 20 | "type": "image/png" 21 | }, 22 | { 23 | "src": "icons/Icon-maskable-192.png", 24 | "sizes": "192x192", 25 | "type": "image/png", 26 | "purpose": "maskable" 27 | }, 28 | { 29 | "src": "icons/Icon-maskable-512.png", 30 | "sizes": "512x512", 31 | "type": "image/png", 32 | "purpose": "maskable" 33 | } 34 | ] 35 | } 36 | -------------------------------------------------------------------------------- /example/windows/runner/flutter_window.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_FLUTTER_WINDOW_H_ 2 | #define RUNNER_FLUTTER_WINDOW_H_ 3 | 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | #include "win32_window.h" 10 | 11 | // A window that does nothing but host a Flutter view. 12 | class FlutterWindow : public Win32Window { 13 | public: 14 | // Creates a new FlutterWindow hosting a Flutter view running |project|. 15 | explicit FlutterWindow(const flutter::DartProject& project); 16 | virtual ~FlutterWindow(); 17 | 18 | protected: 19 | // Win32Window: 20 | bool OnCreate() override; 21 | void OnDestroy() override; 22 | LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, 23 | LPARAM const lparam) noexcept override; 24 | 25 | private: 26 | // The project to run. 27 | flutter::DartProject project_; 28 | 29 | // The Flutter instance hosted by this window. 30 | std::unique_ptr flutter_controller_; 31 | }; 32 | 33 | #endif // RUNNER_FLUTTER_WINDOW_H_ 34 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 15 | 18 | 19 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/values-night/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 15 | 18 | 19 | -------------------------------------------------------------------------------- /lib/src/models/candidates/candidates.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'candidates.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | _$CandidatesImpl _$$CandidatesImplFromJson(Map json) => 10 | _$CandidatesImpl( 11 | content: json['content'] == null 12 | ? null 13 | : Content.fromJson(json['content'] as Map), 14 | finishReason: json['finishReason'] as String?, 15 | index: json['index'] as int?, 16 | safetyRatings: (json['safetyRatings'] as List?) 17 | ?.map((e) => SafetyRatings.fromJson(e as Map)) 18 | .toList(), 19 | ); 20 | 21 | Map _$$CandidatesImplToJson(_$CandidatesImpl instance) => 22 | { 23 | 'content': instance.content, 24 | 'finishReason': instance.finishReason, 25 | 'index': instance.index, 26 | 'safetyRatings': instance.safetyRatings, 27 | }; 28 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: flutter_gemini 2 | description: Flutter Google Gemini SDK. Google Gemini is a set of cutting-edge large language models 3 | (LLMs) designed to be the driving force behind Google's future AI initiatives. 4 | version: 2.0.4 5 | homepage: https://github.com/babakcode/flutter_gemini 6 | topics: 7 | - gemini 8 | - ai 9 | - google-gemini 10 | - flutter-gemini 11 | screenshots: 12 | - description: Flutter_Gemini example screenshot 13 | path: example/screenshots/gemini_screenshot.png 14 | - description: Flutter_Gemini example 15 | path: example/screenshots/gemini_cover.jpeg 16 | 17 | platforms: 18 | android: 19 | ios: 20 | web: 21 | linux: 22 | windows: 23 | macos: 24 | 25 | environment: 26 | sdk: '>=3.0.0 <4.0.0' 27 | 28 | dependencies: 29 | dio: ^5.4.3+1 30 | flutter: 31 | sdk: flutter 32 | 33 | freezed_annotation: ^2.4.1 34 | json_annotation: ^4.8.1 35 | mime: ^1.0.5 36 | 37 | dev_dependencies: 38 | flutter_test: 39 | sdk: flutter 40 | flutter_lints: ^2.0.0 41 | json_convert: ^1.1.0 42 | build_runner: ^2.4.7 43 | json_serializable: ^6.7.1 44 | freezed: ^2.4.5 45 | 46 | flutter: 47 | -------------------------------------------------------------------------------- /example/test/widget_test.dart: -------------------------------------------------------------------------------- 1 | // This is a basic Flutter widget test. 2 | // 3 | // To perform an interaction with a widget in your test, use the WidgetTester 4 | // utility in the flutter_test package. For example, you can send tap and scroll 5 | // gestures. You can also use WidgetTester to find child widgets in the widget 6 | // tree, read text, and verify that the values of widget properties are correct. 7 | 8 | import 'package:flutter/material.dart'; 9 | import 'package:flutter_test/flutter_test.dart'; 10 | 11 | import 'package:example/main.dart'; 12 | 13 | void main() { 14 | testWidgets('Counter increments smoke test', (WidgetTester tester) async { 15 | // Build our app and trigger a frame. 16 | await tester.pumpWidget(const MyApp()); 17 | 18 | // Verify that our counter starts at 0. 19 | expect(find.text('0'), findsOneWidget); 20 | expect(find.text('1'), findsNothing); 21 | 22 | // Tap the '+' icon and trigger a frame. 23 | await tester.tap(find.byIcon(Icons.add)); 24 | await tester.pump(); 25 | 26 | // Verify that our counter has incremented. 27 | expect(find.text('0'), findsNothing); 28 | expect(find.text('1'), findsOneWidget); 29 | }); 30 | } 31 | -------------------------------------------------------------------------------- /lib/src/models/generation_config/generation_config.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'generation_config.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | _$GenerationConfigImpl _$$GenerationConfigImplFromJson( 10 | Map json) => 11 | _$GenerationConfigImpl( 12 | stopSequences: (json['stopSequences'] as List?) 13 | ?.map((e) => e as String) 14 | .toList(), 15 | temperature: (json['temperature'] as num?)?.toDouble(), 16 | maxOutputTokens: json['maxOutputTokens'] as int?, 17 | topP: (json['topP'] as num?)?.toDouble(), 18 | topK: json['topK'] as int?, 19 | ); 20 | 21 | Map _$$GenerationConfigImplToJson( 22 | _$GenerationConfigImpl instance) => 23 | { 24 | 'stopSequences': instance.stopSequences, 25 | 'temperature': instance.temperature, 26 | 'maxOutputTokens': instance.maxOutputTokens, 27 | 'topP': instance.topP, 28 | 'topK': instance.topK, 29 | }; 30 | -------------------------------------------------------------------------------- /example/macos/Runner/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIconFile 10 | 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | $(FLUTTER_BUILD_NAME) 21 | CFBundleVersion 22 | $(FLUTTER_BUILD_NUMBER) 23 | LSMinimumSystemVersion 24 | $(MACOSX_DEPLOYMENT_TARGET) 25 | NSHumanReadableCopyright 26 | $(PRODUCT_COPYRIGHT) 27 | NSMainNibFile 28 | MainMenu 29 | NSPrincipalClass 30 | NSApplication 31 | 32 | 33 | -------------------------------------------------------------------------------- /lib/src/widgets/gemini_response_type_view.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:flutter_gemini/flutter_gemini.dart'; 3 | import 'package:flutter_gemini/src/provider/gemini_response_provider.dart'; 4 | 5 | class GeminiResponseTypeView extends StatelessWidget { 6 | final Widget Function( 7 | BuildContext context, Widget? child, String? response, bool loading) 8 | builder; 9 | 10 | final Widget? child; 11 | 12 | GeminiResponseTypeView({ 13 | super.key, 14 | required this.builder, 15 | this.child, 16 | }) { 17 | Gemini.instance.typeProvider ??= GeminiResponseProvider(); 18 | } 19 | 20 | @override 21 | Widget build(BuildContext context) { 22 | return Align( 23 | alignment: Alignment.bottomCenter, 24 | child: ListenableBuilder( 25 | listenable: Gemini.instance.typeProvider!, 26 | child: child, 27 | builder: (context, child) { 28 | return builder( 29 | context, 30 | child, 31 | Gemini.instance.typeProvider!.lastTypeResponseOrNull, 32 | Gemini.instance.typeProvider!.loading, 33 | ); 34 | }), 35 | ); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /test/features/chat_test.dart: -------------------------------------------------------------------------------- 1 | import 'dart:developer'; 2 | import 'package:flutter_test/flutter_test.dart'; 3 | import 'package:flutter_gemini/flutter_gemini.dart'; 4 | import '../flutter_gemini_test.dart'; 5 | 6 | void main() { 7 | Gemini.init(apiKey: apiKey, enableDebugging: true); 8 | 9 | test('Check Gemini\'s generated simple chat responding', () async { 10 | /// an instance 11 | final gemini = Gemini.instance; 12 | 13 | await gemini 14 | .chat([ 15 | Content(parts: [ 16 | Parts( 17 | text: 'Write the first line of a story about a magic backpack.') 18 | ], role: 'user'), 19 | Content(parts: [ 20 | Parts( 21 | text: 22 | 'In the bustling city of Meadow brook, lived a young girl named Sophie. She was a bright and curious soul with an imaginative mind.') 23 | ], role: 'model'), 24 | Content(parts: [ 25 | Parts(text: 'Can you set it in a quiet village in 1600s France?') 26 | ], role: 'user'), 27 | ]) 28 | .then((value) => log(value?.output ?? 'without output')) 29 | .catchError((e) => log('chat', error: e)); 30 | }); 31 | } 32 | -------------------------------------------------------------------------------- /test/flutter_gemini_test.dart: -------------------------------------------------------------------------------- 1 | import 'dart:developer'; 2 | import 'package:flutter_test/flutter_test.dart'; 3 | import 'package:flutter_gemini/flutter_gemini.dart'; 4 | 5 | const apiKey = '--- Your Gemini Api Key ---'; 6 | 7 | void main() { 8 | Gemini.init(apiKey: apiKey, enableDebugging: true); 9 | 10 | test('check gemini to generate simple text', () async { 11 | /// an instance 12 | final gemini = Gemini.instance; 13 | 14 | await gemini 15 | .chat([ 16 | Content(parts: [ 17 | Parts( 18 | text: 'Write the first line of a story about a magic backpack.') 19 | ], role: 'user'), 20 | Content(parts: [ 21 | Parts( 22 | text: 23 | 'In the bustling city of Meadow brook, lived a young girl named Sophie. She was a bright and curious soul with an imaginative mind.') 24 | ], role: 'model'), 25 | Content(parts: [ 26 | Parts(text: 'Can you set it in a quiet village in 1600s France?') 27 | ], role: 'user'), 28 | ]) 29 | .then((value) => log(value?.output ?? 'without output')) 30 | .catchError((e) => log('chat', error: e)); 31 | }); 32 | } 33 | -------------------------------------------------------------------------------- /lib/src/utils/gemini_exception_handler_mixin.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'package:dio/dio.dart'; 3 | import 'package:flutter_gemini/src/repository/api_interface.dart'; 4 | import 'package:flutter_gemini/src/utils/gemini_exception.dart'; 5 | 6 | mixin GeminiExceptionHandler on ApiInterface { 7 | Future handler(Future Function() request) async { 8 | try { 9 | final res = await request(); 10 | 11 | int statusCode = res.statusCode ?? 200; 12 | if (statusCode >= 200 && statusCode < 300) { 13 | return res; 14 | } 15 | 16 | throw GeminiException(res.data?['error'], statusCode: statusCode); 17 | } catch (e) { 18 | if (e is DioException) { 19 | final data = e.response?.data; 20 | 21 | if (data is ResponseBody) { 22 | throw GeminiException( 23 | e.message ?? 'Something went wrong!', 24 | statusCode: e.response!.statusCode, 25 | ); 26 | } 27 | 28 | throw GeminiException(e.message ?? 'Something went wrong!', 29 | statusCode: -1); 30 | } else if (e is SocketException) { 31 | throw GeminiException(e.message, statusCode: -1); 32 | } 33 | 34 | throw GeminiException(e, statusCode: -1); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /lib/src/provider/gemini_response_provider.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | 3 | import 'package:flutter/material.dart'; 4 | 5 | class GeminiResponseProvider extends ChangeNotifier { 6 | String? response; 7 | int _charIndex = 0; 8 | bool _loading = false; 9 | String? lastTypeResponseOrNull; 10 | 11 | set loading(bool set) { 12 | if (_loading != set) { 13 | _loading = set; 14 | notifyListeners(); 15 | } 16 | } 17 | 18 | bool get loading => _loading; 19 | 20 | GeminiResponseProvider() { 21 | Timer.periodic(const Duration(milliseconds: 2), (timer) { 22 | if (response == null || lastTypeResponseOrNull == response) { 23 | return; 24 | } 25 | 26 | if (lastTypeResponseOrNull != response && 27 | _charIndex <= (response?.length ?? -1)) { 28 | lastTypeResponseOrNull = response?.substring(0, _charIndex++); 29 | 30 | notifyListeners(); 31 | } 32 | }); 33 | } 34 | 35 | void clear() { 36 | response = null; 37 | lastTypeResponseOrNull = null; 38 | _charIndex = 0; 39 | loading = true; 40 | } 41 | 42 | void add(String? text) { 43 | if (text == null) { 44 | return; 45 | } 46 | if (response == null) { 47 | response = text; 48 | } else { 49 | response = "${response!}$text"; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /example/windows/runner/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "flutter_window.h" 6 | #include "utils.h" 7 | 8 | int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, 9 | _In_ wchar_t *command_line, _In_ int show_command) { 10 | // Attach to console when present (e.g., 'flutter run') or create a 11 | // new console when running with a debugger. 12 | if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { 13 | CreateAndAttachConsole(); 14 | } 15 | 16 | // Initialize COM, so that it is available for use in the library and/or 17 | // plugins. 18 | ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); 19 | 20 | flutter::DartProject project(L"data"); 21 | 22 | std::vector command_line_arguments = 23 | GetCommandLineArguments(); 24 | 25 | project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); 26 | 27 | FlutterWindow window(project); 28 | Win32Window::Point origin(10, 10); 29 | Win32Window::Size size(1280, 720); 30 | if (!window.Create(L"example", origin, size)) { 31 | return EXIT_FAILURE; 32 | } 33 | window.SetQuitOnClose(true); 34 | 35 | ::MSG msg; 36 | while (::GetMessage(&msg, nullptr, 0, 0)) { 37 | ::TranslateMessage(&msg); 38 | ::DispatchMessage(&msg); 39 | } 40 | 41 | ::CoUninitialize(); 42 | return EXIT_SUCCESS; 43 | } 44 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 2.0.5 2 | * ## new feature 3 | * prompt 4 | 5 | ## 2.0.4-dev.1 6 | * ## new feature 7 | * reInitialize 8 | * add mime type from Uint8List 9 | 10 | ## 2.0.3 11 | * ## new feature 12 | * GeminiException( message , statusCode) 13 | 14 | ## 2.0.1 15 | * ## new feature 16 | * Decode utf-8 17 | * streamChat 18 | 19 | ## 2.0.0 20 | * work for lower Dart SDK version 21 | 22 | ## 2.0.0-dev-1 23 | 24 | * ## Add new crucial features 25 | * ##### streamGenerateContent 26 | * The model usually gives a response once it finishes generating the entire output. To speed up interactions, you can opt not to wait for the complete result and instead use streaming to manage partial results. 27 | * ##### batchEmbedContents 28 | * ##### embedContent 29 | * Embedding is a method that transforms information, like text, into a list of floating-point numbers in an array. Gemini enables the representation of text, such as words or sentences, in a vectorized form. This facilitates the comparison of embeddings, allowing for the identification of similarities between texts through mathematical techniques like cosine similarity. For instance, texts with similar subject matter or sentiment should exhibit similar embeddings. 30 | * ## Updates 31 | * #### textAndImage 32 | * Convert the image property to the `images` 33 | ```diff 34 | - image: file.readAsBytesSync(), /// image 35 | + images: [file.readAsBytesSync()] /// list of images 36 | ``` 37 | 38 | ## 1.0.1 39 | 40 | * update pubspec 41 | 42 | ## 1.0.0 43 | 44 | * first publish 45 | -------------------------------------------------------------------------------- /example/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | # This file configures the analyzer, which statically analyzes Dart code to 2 | # check for errors, warnings, and lints. 3 | # 4 | # The issues identified by the analyzer are surfaced in the UI of Dart-enabled 5 | # IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be 6 | # invoked from the command line by running `flutter analyze`. 7 | 8 | # The following line activates a set of recommended lints for Flutter apps, 9 | # packages, and plugins designed to encourage good coding practices. 10 | include: package:flutter_lints/flutter.yaml 11 | 12 | linter: 13 | # The lint rules applied to this project can be customized in the 14 | # section below to disable rules from the `package:flutter_lints/flutter.yaml` 15 | # included above or to enable additional rules. A list of all available lints 16 | # and their documentation is published at https://dart.dev/lints. 17 | # 18 | # Instead of disabling a lint rule for the entire project in the 19 | # section below, it can also be suppressed for a single line of code 20 | # or a specific dart file by using the `// ignore: name_of_lint` and 21 | # `// ignore_for_file: name_of_lint` syntax on the line or in the file 22 | # producing the lint. 23 | rules: 24 | # avoid_print: false # Uncomment to disable the `avoid_print` rule 25 | # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule 26 | 27 | # Additional information about this file can be found at 28 | # https://dart.dev/guides/language/analysis-options 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2023, Babak Gahremanzadeh (BabakCode) 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | 8 | 1. Redistributions of source code must retain the above copyright notice, this 9 | list of conditions and the following disclaimer. 10 | 11 | 2. Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | 3. Neither the name of the copyright holder nor the names of its 16 | contributors may be used to endorse or promote products derived from 17 | this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 23 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 25 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 26 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 27 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "size" : "16x16", 5 | "idiom" : "mac", 6 | "filename" : "app_icon_16.png", 7 | "scale" : "1x" 8 | }, 9 | { 10 | "size" : "16x16", 11 | "idiom" : "mac", 12 | "filename" : "app_icon_32.png", 13 | "scale" : "2x" 14 | }, 15 | { 16 | "size" : "32x32", 17 | "idiom" : "mac", 18 | "filename" : "app_icon_32.png", 19 | "scale" : "1x" 20 | }, 21 | { 22 | "size" : "32x32", 23 | "idiom" : "mac", 24 | "filename" : "app_icon_64.png", 25 | "scale" : "2x" 26 | }, 27 | { 28 | "size" : "128x128", 29 | "idiom" : "mac", 30 | "filename" : "app_icon_128.png", 31 | "scale" : "1x" 32 | }, 33 | { 34 | "size" : "128x128", 35 | "idiom" : "mac", 36 | "filename" : "app_icon_256.png", 37 | "scale" : "2x" 38 | }, 39 | { 40 | "size" : "256x256", 41 | "idiom" : "mac", 42 | "filename" : "app_icon_256.png", 43 | "scale" : "1x" 44 | }, 45 | { 46 | "size" : "256x256", 47 | "idiom" : "mac", 48 | "filename" : "app_icon_512.png", 49 | "scale" : "2x" 50 | }, 51 | { 52 | "size" : "512x512", 53 | "idiom" : "mac", 54 | "filename" : "app_icon_512.png", 55 | "scale" : "1x" 56 | }, 57 | { 58 | "size" : "512x512", 59 | "idiom" : "mac", 60 | "filename" : "app_icon_1024.png", 61 | "scale" : "2x" 62 | } 63 | ], 64 | "info" : { 65 | "version" : 1, 66 | "author" : "xcode" 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /lib/src/models/gemini_model/gemini_model.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'gemini_model.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | _$GeminiModelImpl _$$GeminiModelImplFromJson(Map json) => 10 | _$GeminiModelImpl( 11 | name: json['name'] as String?, 12 | version: json['version'] as String?, 13 | displayName: json['displayName'] as String?, 14 | description: json['description'] as String?, 15 | inputTokenLimit: json['inputTokenLimit'] as int?, 16 | outputTokenLimit: json['outputTokenLimit'] as int?, 17 | supportedGenerationMethods: 18 | (json['supportedGenerationMethods'] as List?) 19 | ?.map((e) => e as String) 20 | .toList(), 21 | temperature: (json['temperature'] as num?)?.toDouble(), 22 | topP: (json['topP'] as num?)?.toDouble(), 23 | topK: json['topK'] as int?, 24 | ); 25 | 26 | Map _$$GeminiModelImplToJson(_$GeminiModelImpl instance) => 27 | { 28 | 'name': instance.name, 29 | 'version': instance.version, 30 | 'displayName': instance.displayName, 31 | 'description': instance.description, 32 | 'inputTokenLimit': instance.inputTokenLimit, 33 | 'outputTokenLimit': instance.outputTokenLimit, 34 | 'supportedGenerationMethods': instance.supportedGenerationMethods, 35 | 'temperature': instance.temperature, 36 | 'topP': instance.topP, 37 | 'topK': instance.topK, 38 | }; 39 | -------------------------------------------------------------------------------- /example/ios/Runner/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /example/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 14 | 18 | 22 | 23 | 24 | 25 | 26 | 27 | 29 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /example/ios/Runner/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleDisplayName 8 | Example 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | example 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | $(FLUTTER_BUILD_NAME) 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | $(FLUTTER_BUILD_NUMBER) 25 | LSRequiresIPhoneOS 26 | 27 | UILaunchStoryboardName 28 | LaunchScreen 29 | UIMainStoryboardFile 30 | Main 31 | UISupportedInterfaceOrientations 32 | 33 | UIInterfaceOrientationPortrait 34 | UIInterfaceOrientationLandscapeLeft 35 | UIInterfaceOrientationLandscapeRight 36 | 37 | UISupportedInterfaceOrientations~ipad 38 | 39 | UIInterfaceOrientationPortrait 40 | UIInterfaceOrientationPortraitUpsideDown 41 | UIInterfaceOrientationLandscapeLeft 42 | UIInterfaceOrientationLandscapeRight 43 | 44 | CADisableMinimumFrameDurationOnPhone 45 | 46 | UIApplicationSupportsIndirectInputEvents 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /example/.metadata: -------------------------------------------------------------------------------- 1 | # This file tracks properties of this Flutter project. 2 | # Used by Flutter tool to assess capabilities and perform upgrades etc. 3 | # 4 | # This file should be version controlled and should not be manually edited. 5 | 6 | version: 7 | revision: "2f708eb8396e362e280fac22cf171c2cb467343c" 8 | channel: "stable" 9 | 10 | project_type: app 11 | 12 | # Tracks metadata for the flutter migrate command 13 | migration: 14 | platforms: 15 | - platform: root 16 | create_revision: 2f708eb8396e362e280fac22cf171c2cb467343c 17 | base_revision: 2f708eb8396e362e280fac22cf171c2cb467343c 18 | - platform: android 19 | create_revision: 2f708eb8396e362e280fac22cf171c2cb467343c 20 | base_revision: 2f708eb8396e362e280fac22cf171c2cb467343c 21 | - platform: ios 22 | create_revision: 2f708eb8396e362e280fac22cf171c2cb467343c 23 | base_revision: 2f708eb8396e362e280fac22cf171c2cb467343c 24 | - platform: linux 25 | create_revision: 2f708eb8396e362e280fac22cf171c2cb467343c 26 | base_revision: 2f708eb8396e362e280fac22cf171c2cb467343c 27 | - platform: macos 28 | create_revision: 2f708eb8396e362e280fac22cf171c2cb467343c 29 | base_revision: 2f708eb8396e362e280fac22cf171c2cb467343c 30 | - platform: web 31 | create_revision: 2f708eb8396e362e280fac22cf171c2cb467343c 32 | base_revision: 2f708eb8396e362e280fac22cf171c2cb467343c 33 | - platform: windows 34 | create_revision: 2f708eb8396e362e280fac22cf171c2cb467343c 35 | base_revision: 2f708eb8396e362e280fac22cf171c2cb467343c 36 | 37 | # User provided section 38 | 39 | # List of Local paths (relative to this file) that should be 40 | # ignored by the migrate tool. 41 | # 42 | # Files that are not part of the templates will be ignored by default. 43 | unmanaged_files: 44 | - 'lib/main.dart' 45 | - 'ios/Runner.xcodeproj/project.pbxproj' 46 | -------------------------------------------------------------------------------- /example/lib/widgets/chat_input_box.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | 3 | class ChatInputBox extends StatelessWidget { 4 | final TextEditingController? controller; 5 | final VoidCallback? onSend, onClickCamera; 6 | 7 | const ChatInputBox({ 8 | super.key, 9 | this.controller, 10 | this.onSend, 11 | this.onClickCamera, 12 | }); 13 | 14 | @override 15 | Widget build(BuildContext context) { 16 | return Card( 17 | margin: const EdgeInsets.all(8), 18 | child: Row( 19 | crossAxisAlignment: CrossAxisAlignment.end, 20 | children: [ 21 | if (onClickCamera != null) 22 | Padding( 23 | padding: const EdgeInsets.all(4.0), 24 | child: IconButton( 25 | onPressed: onClickCamera, 26 | color: Theme.of(context).colorScheme.onSecondary, 27 | icon: const Icon(Icons.file_copy_rounded)), 28 | ), 29 | Expanded( 30 | child: TextField( 31 | controller: controller, 32 | minLines: 1, 33 | maxLines: 6, 34 | cursorColor: Theme.of(context).colorScheme.inversePrimary, 35 | textInputAction: TextInputAction.newline, 36 | keyboardType: TextInputType.multiline, 37 | decoration: const InputDecoration( 38 | contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 4), 39 | hintText: 'Message', 40 | border: InputBorder.none, 41 | ), 42 | onTapOutside: (event) => 43 | FocusManager.instance.primaryFocus?.unfocus(), 44 | )), 45 | Padding( 46 | padding: const EdgeInsets.all(4), 47 | child: FloatingActionButton.small( 48 | onPressed: onSend, 49 | child: const Icon(Icons.send_rounded), 50 | ), 51 | ) 52 | ], 53 | ), 54 | ); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /example/windows/runner/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.14) 2 | project(runner LANGUAGES CXX) 3 | 4 | # Define the application target. To change its name, change BINARY_NAME in the 5 | # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer 6 | # work. 7 | # 8 | # Any new source files that you add to the application should be added here. 9 | add_executable(${BINARY_NAME} WIN32 10 | "flutter_window.cpp" 11 | "main.cpp" 12 | "utils.cpp" 13 | "win32_window.cpp" 14 | "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" 15 | "Runner.rc" 16 | "runner.exe.manifest" 17 | ) 18 | 19 | # Apply the standard set of build settings. This can be removed for applications 20 | # that need different build settings. 21 | apply_standard_settings(${BINARY_NAME}) 22 | 23 | # Add preprocessor definitions for the build version. 24 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") 25 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") 26 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") 27 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") 28 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") 29 | 30 | # Disable Windows macros that collide with C++ standard library functions. 31 | target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") 32 | 33 | # Add dependency libraries and include directories. Add any application-specific 34 | # dependencies here. 35 | target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) 36 | target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") 37 | target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") 38 | 39 | # Run the Flutter tool portions of the build. This must not be removed. 40 | add_dependencies(${BINARY_NAME} flutter_assemble) 41 | -------------------------------------------------------------------------------- /example/windows/runner/utils.cpp: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | 10 | void CreateAndAttachConsole() { 11 | if (::AllocConsole()) { 12 | FILE *unused; 13 | if (freopen_s(&unused, "CONOUT$", "w", stdout)) { 14 | _dup2(_fileno(stdout), 1); 15 | } 16 | if (freopen_s(&unused, "CONOUT$", "w", stderr)) { 17 | _dup2(_fileno(stdout), 2); 18 | } 19 | std::ios::sync_with_stdio(); 20 | FlutterDesktopResyncOutputStreams(); 21 | } 22 | } 23 | 24 | std::vector GetCommandLineArguments() { 25 | // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. 26 | int argc; 27 | wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); 28 | if (argv == nullptr) { 29 | return std::vector(); 30 | } 31 | 32 | std::vector command_line_arguments; 33 | 34 | // Skip the first argument as it's the binary name. 35 | for (int i = 1; i < argc; i++) { 36 | command_line_arguments.push_back(Utf8FromUtf16(argv[i])); 37 | } 38 | 39 | ::LocalFree(argv); 40 | 41 | return command_line_arguments; 42 | } 43 | 44 | std::string Utf8FromUtf16(const wchar_t* utf16_string) { 45 | if (utf16_string == nullptr) { 46 | return std::string(); 47 | } 48 | int target_length = ::WideCharToMultiByte( 49 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 50 | -1, nullptr, 0, nullptr, nullptr) 51 | -1; // remove the trailing null character 52 | int input_length = (int)wcslen(utf16_string); 53 | std::string utf8_string; 54 | if (target_length <= 0 || target_length > utf8_string.max_size()) { 55 | return utf8_string; 56 | } 57 | utf8_string.resize(target_length); 58 | int converted_length = ::WideCharToMultiByte( 59 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 60 | input_length, utf8_string.data(), target_length, nullptr, nullptr); 61 | if (converted_length == 0) { 62 | return std::string(); 63 | } 64 | return utf8_string; 65 | } 66 | -------------------------------------------------------------------------------- /example/android/app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "com.android.application" 3 | id "kotlin-android" 4 | id "dev.flutter.flutter-gradle-plugin" 5 | } 6 | 7 | def localProperties = new Properties() 8 | def localPropertiesFile = rootProject.file('local.properties') 9 | if (localPropertiesFile.exists()) { 10 | localPropertiesFile.withReader('UTF-8') { reader -> 11 | localProperties.load(reader) 12 | } 13 | } 14 | 15 | def flutterVersionCode = localProperties.getProperty('flutter.versionCode') 16 | if (flutterVersionCode == null) { 17 | flutterVersionCode = '1' 18 | } 19 | 20 | def flutterVersionName = localProperties.getProperty('flutter.versionName') 21 | if (flutterVersionName == null) { 22 | flutterVersionName = '1.0' 23 | } 24 | 25 | android { 26 | namespace "com.example.example" 27 | compileSdkVersion flutter.compileSdkVersion 28 | ndkVersion flutter.ndkVersion 29 | 30 | compileOptions { 31 | sourceCompatibility JavaVersion.VERSION_1_8 32 | targetCompatibility JavaVersion.VERSION_1_8 33 | } 34 | 35 | kotlinOptions { 36 | jvmTarget = '1.8' 37 | } 38 | 39 | sourceSets { 40 | main.java.srcDirs += 'src/main/kotlin' 41 | } 42 | 43 | defaultConfig { 44 | // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). 45 | applicationId "com.example.example" 46 | // You can update the following values to match your application needs. 47 | // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. 48 | minSdkVersion flutter.minSdkVersion 49 | targetSdkVersion flutter.targetSdkVersion 50 | versionCode flutterVersionCode.toInteger() 51 | versionName flutterVersionName 52 | } 53 | 54 | buildTypes { 55 | release { 56 | // TODO: Add your own signing config for the release build. 57 | // Signing with the debug keys for now, so `flutter run --release` works. 58 | signingConfig signingConfigs.debug 59 | } 60 | } 61 | } 62 | 63 | flutter { 64 | source '../..' 65 | } 66 | 67 | dependencies {} 68 | -------------------------------------------------------------------------------- /example/web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | Flutter Gemini 33 | 34 | 35 | 39 | 40 | 41 | 42 | 43 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /example/lib/sections/text_only.dart: -------------------------------------------------------------------------------- 1 | import 'package:example/widgets/chat_input_box.dart'; 2 | import 'package:flutter/material.dart'; 3 | import 'package:flutter_gemini/flutter_gemini.dart'; 4 | import 'package:flutter_markdown/flutter_markdown.dart'; 5 | import 'package:lottie/lottie.dart'; 6 | 7 | class SectionTextInput extends StatefulWidget { 8 | const SectionTextInput({super.key}); 9 | 10 | @override 11 | State createState() => _SectionTextInputState(); 12 | } 13 | 14 | class _SectionTextInputState extends State { 15 | final controller = TextEditingController(); 16 | final gemini = Gemini.instance; 17 | String? searchedText, result; 18 | bool _loading = false; 19 | 20 | bool get loading => _loading; 21 | 22 | set loading(bool set) => setState(() => _loading = set); 23 | 24 | @override 25 | Widget build(BuildContext context) { 26 | return Column( 27 | children: [ 28 | if (searchedText != null) 29 | MaterialButton( 30 | color: Colors.blue.shade700, 31 | onPressed: () { 32 | setState(() { 33 | searchedText = null; 34 | result = null; 35 | }); 36 | }, 37 | child: Text('search: $searchedText')), 38 | Expanded( 39 | child: loading 40 | ? Lottie.asset('assets/lottie/ai.json') 41 | : result != null 42 | ? Padding( 43 | padding: const EdgeInsets.all(8.0), 44 | child: Markdown(data: result!), 45 | ) 46 | : const Center(child: Text('Search something!'))), 47 | ChatInputBox( 48 | controller: controller, 49 | onSend: () { 50 | if (controller.text.isNotEmpty) { 51 | searchedText = controller.text; 52 | controller.clear(); 53 | loading = true; 54 | 55 | gemini.text(searchedText!).then((value) { 56 | result = value?.content?.parts?.last.text; 57 | loading = false; 58 | }); 59 | } 60 | }, 61 | ), 62 | ], 63 | ); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /example/lib/sections/embed_content.dart: -------------------------------------------------------------------------------- 1 | import 'package:example/widgets/chat_input_box.dart'; 2 | import 'package:flutter/material.dart'; 3 | import 'package:flutter_gemini/flutter_gemini.dart'; 4 | import 'package:lottie/lottie.dart'; 5 | 6 | class SectionEmbedContent extends StatefulWidget { 7 | const SectionEmbedContent({super.key}); 8 | 9 | @override 10 | State createState() => _SectionEmbedContentState(); 11 | } 12 | 13 | class _SectionEmbedContentState extends State { 14 | final controller = TextEditingController(); 15 | final gemini = Gemini.instance; 16 | String? searchedText; 17 | List? result; 18 | bool _loading = false; 19 | 20 | bool get loading => _loading; 21 | 22 | set loading(bool set) => setState(() => _loading = set); 23 | 24 | @override 25 | Widget build(BuildContext context) { 26 | return Column( 27 | children: [ 28 | if (searchedText != null) 29 | MaterialButton( 30 | color: Colors.blue.shade700, 31 | onPressed: () { 32 | setState(() { 33 | searchedText = null; 34 | result = null; 35 | }); 36 | }, 37 | child: Text('search: $searchedText')), 38 | Expanded( 39 | child: loading 40 | ? Lottie.asset('assets/lottie/ai.json') 41 | : result != null 42 | ? Padding( 43 | padding: const EdgeInsets.all(8.0), 44 | child: SingleChildScrollView( 45 | child: Text(result?.toString() ?? '')), 46 | ) 47 | : const Center(child: Text('Search something!'))), 48 | ChatInputBox( 49 | controller: controller, 50 | onSend: () { 51 | if (controller.text.isNotEmpty) { 52 | searchedText = controller.text; 53 | controller.clear(); 54 | loading = true; 55 | 56 | gemini.embedContent(searchedText!).then((value) { 57 | result = value; 58 | loading = false; 59 | }); 60 | } 61 | }, 62 | ), 63 | ], 64 | ); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /example/lib/sections/embed_batch_contents.dart: -------------------------------------------------------------------------------- 1 | import 'package:example/widgets/chat_input_box.dart'; 2 | import 'package:flutter/material.dart'; 3 | import 'package:flutter_gemini/flutter_gemini.dart'; 4 | import 'package:lottie/lottie.dart'; 5 | 6 | class SectionBatchEmbedContents extends StatefulWidget { 7 | const SectionBatchEmbedContents({super.key}); 8 | 9 | @override 10 | State createState() => 11 | _SectionTextInputStreamState(); 12 | } 13 | 14 | class _SectionTextInputStreamState extends State { 15 | final controller = TextEditingController(); 16 | final gemini = Gemini.instance; 17 | String? searchedText; 18 | List?>? result; 19 | bool _loading = false; 20 | 21 | bool get loading => _loading; 22 | 23 | set loading(bool set) => setState(() => _loading = set); 24 | 25 | @override 26 | Widget build(BuildContext context) { 27 | return Column( 28 | children: [ 29 | if (searchedText != null) 30 | MaterialButton( 31 | color: Colors.blue.shade700, 32 | onPressed: () { 33 | setState(() { 34 | searchedText = null; 35 | result = null; 36 | }); 37 | }, 38 | child: Text('search: $searchedText')), 39 | Expanded( 40 | child: loading 41 | ? Lottie.asset('assets/lottie/ai.json') 42 | : result != null 43 | ? Padding( 44 | padding: const EdgeInsets.all(8.0), 45 | child: SingleChildScrollView( 46 | child: Text(result?.toString() ?? '')), 47 | ) 48 | : const Center(child: Text('Search something!'))), 49 | ChatInputBox( 50 | controller: controller, 51 | onSend: () { 52 | if (controller.text.isNotEmpty) { 53 | searchedText = controller.text; 54 | controller.clear(); 55 | loading = true; 56 | 57 | gemini.batchEmbedContents([searchedText!]).then((value) { 58 | result = value; 59 | loading = false; 60 | }); 61 | } 62 | }, 63 | ) 64 | ], 65 | ); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /example/windows/runner/flutter_window.cpp: -------------------------------------------------------------------------------- 1 | #include "flutter_window.h" 2 | 3 | #include 4 | 5 | #include "flutter/generated_plugin_registrant.h" 6 | 7 | FlutterWindow::FlutterWindow(const flutter::DartProject& project) 8 | : project_(project) {} 9 | 10 | FlutterWindow::~FlutterWindow() {} 11 | 12 | bool FlutterWindow::OnCreate() { 13 | if (!Win32Window::OnCreate()) { 14 | return false; 15 | } 16 | 17 | RECT frame = GetClientArea(); 18 | 19 | // The size here must match the window dimensions to avoid unnecessary surface 20 | // creation / destruction in the startup path. 21 | flutter_controller_ = std::make_unique( 22 | frame.right - frame.left, frame.bottom - frame.top, project_); 23 | // Ensure that basic setup of the controller was successful. 24 | if (!flutter_controller_->engine() || !flutter_controller_->view()) { 25 | return false; 26 | } 27 | RegisterPlugins(flutter_controller_->engine()); 28 | SetChildContent(flutter_controller_->view()->GetNativeWindow()); 29 | 30 | flutter_controller_->engine()->SetNextFrameCallback([&]() { 31 | this->Show(); 32 | }); 33 | 34 | // Flutter can complete the first frame before the "show window" callback is 35 | // registered. The following call ensures a frame is pending to ensure the 36 | // window is shown. It is a no-op if the first frame hasn't completed yet. 37 | flutter_controller_->ForceRedraw(); 38 | 39 | return true; 40 | } 41 | 42 | void FlutterWindow::OnDestroy() { 43 | if (flutter_controller_) { 44 | flutter_controller_ = nullptr; 45 | } 46 | 47 | Win32Window::OnDestroy(); 48 | } 49 | 50 | LRESULT 51 | FlutterWindow::MessageHandler(HWND hwnd, UINT const message, 52 | WPARAM const wparam, 53 | LPARAM const lparam) noexcept { 54 | // Give Flutter, including plugins, an opportunity to handle window messages. 55 | if (flutter_controller_) { 56 | std::optional result = 57 | flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, 58 | lparam); 59 | if (result) { 60 | return *result; 61 | } 62 | } 63 | 64 | switch (message) { 65 | case WM_FONTCHANGE: 66 | flutter_controller_->engine()->ReloadSystemFonts(); 67 | break; 68 | } 69 | 70 | return Win32Window::MessageHandler(hwnd, message, wparam, lparam); 71 | } 72 | -------------------------------------------------------------------------------- /example/ios/Runner/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /lib/src/implement/gemini_service.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'package:dio/dio.dart'; 3 | import 'package:flutter/foundation.dart'; 4 | import 'package:flutter_gemini/src/repository/api_interface.dart'; 5 | import 'package:flutter_gemini/src/utils/gemini_exception_handler_mixin.dart'; 6 | import '../init.dart'; 7 | import '../models/gemini_safety/gemini_safety.dart'; 8 | import '../models/generation_config/generation_config.dart'; 9 | 10 | /// [GeminiService] is api helper service class 11 | class GeminiService extends ApiInterface with GeminiExceptionHandler { 12 | final Dio dio; 13 | final String apiKey; 14 | CancelToken? cancelToken; 15 | 16 | GeminiService(this.dio, {required this.apiKey}) { 17 | if (!kReleaseMode && (Gemini.enableDebugging ?? false)) { 18 | dio.interceptors 19 | .add(LogInterceptor(requestBody: true, responseBody: true)); 20 | } 21 | } 22 | 23 | @override 24 | Future post( 25 | String route, { 26 | required Map? data, 27 | GenerationConfig? generationConfig, 28 | List? safetySettings, 29 | bool isStreamResponse = false, 30 | }) async { 31 | /// add local safetySettings or global safetySetting which added 32 | /// in [init] constructor 33 | cancelToken ??= CancelToken(); 34 | if (safetySettings != null || this.safetySettings != null) { 35 | final listSafetySettings = safetySettings ?? this.safetySettings ?? []; 36 | final items = []; 37 | for (final safetySetting in listSafetySettings) { 38 | items.add({ 39 | 'category': safetySetting.category.value, 40 | 'threshold': safetySetting.threshold.value, 41 | }); 42 | } 43 | data?['safetySettings'] = items; 44 | } 45 | 46 | /// add local generationConfig or global generationConfig which added 47 | /// in [init] constructor 48 | if (generationConfig != null || this.generationConfig != null) { 49 | data?['generationConfig'] = 50 | generationConfig?.toJson() ?? this.generationConfig?.toJson() ?? {}; 51 | } 52 | 53 | return handler(() => dio.post( 54 | route, 55 | data: jsonEncode(data), 56 | queryParameters: {'key': apiKey}, 57 | options: Options( 58 | responseType: 59 | isStreamResponse == true ? ResponseType.stream : null), 60 | cancelToken: cancelToken, 61 | )); 62 | } 63 | 64 | @override 65 | Future get(String route) async { 66 | cancelToken ??= CancelToken(); 67 | return handler(() => dio.get(route, 68 | queryParameters: {'key': apiKey}, cancelToken: cancelToken)); 69 | } 70 | 71 | Future cancelRequest() async { 72 | if (cancelToken != null) { 73 | cancelToken!.cancel(); 74 | cancelToken = null; 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /example/lib/sections/chat.dart: -------------------------------------------------------------------------------- 1 | import 'package:example/widgets/chat_input_box.dart'; 2 | import 'package:flutter/material.dart'; 3 | import 'package:flutter_gemini/flutter_gemini.dart'; 4 | import 'package:flutter_markdown/flutter_markdown.dart'; 5 | 6 | class SectionChat extends StatefulWidget { 7 | const SectionChat({super.key}); 8 | 9 | @override 10 | State createState() => _SectionChatState(); 11 | } 12 | 13 | class _SectionChatState extends State { 14 | final controller = TextEditingController(); 15 | final gemini = Gemini.instance; 16 | bool _loading = false; 17 | 18 | bool get loading => _loading; 19 | 20 | set loading(bool set) => setState(() => _loading = set); 21 | final List chats = []; 22 | 23 | @override 24 | Widget build(BuildContext context) { 25 | return Column( 26 | children: [ 27 | Expanded( 28 | child: chats.isNotEmpty 29 | ? Align( 30 | alignment: Alignment.bottomCenter, 31 | child: SingleChildScrollView( 32 | reverse: true, 33 | child: ListView.builder( 34 | itemBuilder: chatItem, 35 | shrinkWrap: true, 36 | physics: const NeverScrollableScrollPhysics(), 37 | itemCount: chats.length, 38 | reverse: false, 39 | ), 40 | ), 41 | ) 42 | : const Center(child: Text('Search something!'))), 43 | if (loading) const CircularProgressIndicator(), 44 | ChatInputBox( 45 | controller: controller, 46 | onSend: () { 47 | if (controller.text.isNotEmpty) { 48 | final searchedText = controller.text; 49 | chats.add( 50 | Content(role: 'user', parts: [Parts(text: searchedText)])); 51 | controller.clear(); 52 | loading = true; 53 | 54 | gemini.chat(chats).then((value) { 55 | chats.add(Content( 56 | role: 'model', parts: [Parts(text: value?.output)])); 57 | loading = false; 58 | }); 59 | } 60 | }, 61 | ), 62 | ], 63 | ); 64 | } 65 | 66 | Widget chatItem(BuildContext context, int index) { 67 | final Content content = chats[index]; 68 | 69 | return Card( 70 | elevation: 0, 71 | color: 72 | content.role == 'model' ? Colors.blue.shade800 : Colors.transparent, 73 | child: Padding( 74 | padding: const EdgeInsets.all(8.0), 75 | child: Column( 76 | crossAxisAlignment: CrossAxisAlignment.start, 77 | children: [ 78 | Text(content.role ?? 'role'), 79 | Markdown( 80 | shrinkWrap: true, 81 | physics: const NeverScrollableScrollPhysics(), 82 | data: 83 | content.parts?.lastOrNull?.text ?? 'cannot generate data!'), 84 | ], 85 | ), 86 | ), 87 | ); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /example/lib/sections/response_widget_stream.dart: -------------------------------------------------------------------------------- 1 | import 'package:example/widgets/chat_input_box.dart'; 2 | import 'package:flutter/material.dart'; 3 | import 'package:flutter_gemini/flutter_gemini.dart'; 4 | import 'package:flutter_markdown/flutter_markdown.dart'; 5 | import 'package:lottie/lottie.dart'; 6 | 7 | class ResponseWidgetSection extends StatefulWidget { 8 | const ResponseWidgetSection({super.key}); 9 | 10 | @override 11 | State createState() => _SectionTextInputStreamState(); 12 | } 13 | 14 | class _SectionTextInputStreamState extends State { 15 | final controller = TextEditingController(); 16 | final gemini = Gemini.instance; 17 | String? searchedText, result, _finishReason; 18 | bool _loading = false; 19 | 20 | String? get finishReason => _finishReason; 21 | bool get loading => _loading; 22 | 23 | set finishReason(String? set) { 24 | if (set != _finishReason) { 25 | setState(() => _finishReason = set); 26 | } 27 | } 28 | 29 | set loading(bool set) { 30 | if (set != loading) { 31 | setState(() => _loading = set); 32 | } 33 | } 34 | 35 | @override 36 | Widget build(BuildContext context) { 37 | return Column( 38 | children: [ 39 | if (searchedText != null) 40 | MaterialButton( 41 | color: Colors.blue.shade700, 42 | onPressed: () { 43 | setState(() { 44 | searchedText = null; 45 | result = null; 46 | }); 47 | }, 48 | child: Text('search: $searchedText')), 49 | Expanded( 50 | child: loading 51 | ? Lottie.asset('assets/lottie/ai.json') 52 | : result != null 53 | ? GeminiResponseTypeView( 54 | builder: (context, child, response, loading) => 55 | Markdown(data: response ?? '')) 56 | : const Center(child: Text('Search something!'))), 57 | if (finishReason != null) Text(finishReason!), 58 | ChatInputBox( 59 | controller: controller, 60 | onSend: () { 61 | if (controller.text.isNotEmpty) { 62 | searchedText = controller.text; 63 | controller.clear(); 64 | loading = true; 65 | result = null; 66 | finishReason = null; 67 | 68 | gemini 69 | .streamGenerateContent(searchedText!, 70 | generationConfig: GenerationConfig( 71 | maxOutputTokens: 2000, 72 | temperature: 0.9, 73 | topP: 0.1, 74 | topK: 16, 75 | )) 76 | .listen((value) { 77 | result = (result ?? '') + (value.output ?? ''); 78 | 79 | if (value.finishReason != 'STOP') { 80 | finishReason = 'Finish reason is `RECITATION`'; 81 | } 82 | loading = false; 83 | }); 84 | } 85 | }, 86 | ), 87 | ], 88 | ); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /example/linux/flutter/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This file controls Flutter-level build steps. It should not be edited. 2 | cmake_minimum_required(VERSION 3.10) 3 | 4 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") 5 | 6 | # Configuration provided via flutter tool. 7 | include(${EPHEMERAL_DIR}/generated_config.cmake) 8 | 9 | # TODO: Move the rest of this into files in ephemeral. See 10 | # https://github.com/flutter/flutter/issues/57146. 11 | 12 | # Serves the same purpose as list(TRANSFORM ... PREPEND ...), 13 | # which isn't available in 3.10. 14 | function(list_prepend LIST_NAME PREFIX) 15 | set(NEW_LIST "") 16 | foreach(element ${${LIST_NAME}}) 17 | list(APPEND NEW_LIST "${PREFIX}${element}") 18 | endforeach(element) 19 | set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) 20 | endfunction() 21 | 22 | # === Flutter Library === 23 | # System-level dependencies. 24 | find_package(PkgConfig REQUIRED) 25 | pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) 26 | pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) 27 | pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) 28 | 29 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") 30 | 31 | # Published to parent scope for install step. 32 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) 33 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) 34 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) 35 | set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) 36 | 37 | list(APPEND FLUTTER_LIBRARY_HEADERS 38 | "fl_basic_message_channel.h" 39 | "fl_binary_codec.h" 40 | "fl_binary_messenger.h" 41 | "fl_dart_project.h" 42 | "fl_engine.h" 43 | "fl_json_message_codec.h" 44 | "fl_json_method_codec.h" 45 | "fl_message_codec.h" 46 | "fl_method_call.h" 47 | "fl_method_channel.h" 48 | "fl_method_codec.h" 49 | "fl_method_response.h" 50 | "fl_plugin_registrar.h" 51 | "fl_plugin_registry.h" 52 | "fl_standard_message_codec.h" 53 | "fl_standard_method_codec.h" 54 | "fl_string_codec.h" 55 | "fl_value.h" 56 | "fl_view.h" 57 | "flutter_linux.h" 58 | ) 59 | list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") 60 | add_library(flutter INTERFACE) 61 | target_include_directories(flutter INTERFACE 62 | "${EPHEMERAL_DIR}" 63 | ) 64 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") 65 | target_link_libraries(flutter INTERFACE 66 | PkgConfig::GTK 67 | PkgConfig::GLIB 68 | PkgConfig::GIO 69 | ) 70 | add_dependencies(flutter flutter_assemble) 71 | 72 | # === Flutter tool backend === 73 | # _phony_ is a non-existent file to force this command to run every time, 74 | # since currently there's no way to get a full input/output list from the 75 | # flutter tool. 76 | add_custom_command( 77 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} 78 | ${CMAKE_CURRENT_BINARY_DIR}/_phony_ 79 | COMMAND ${CMAKE_COMMAND} -E env 80 | ${FLUTTER_TOOL_ENVIRONMENT} 81 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" 82 | ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} 83 | VERBATIM 84 | ) 85 | add_custom_target(flutter_assemble DEPENDS 86 | "${FLUTTER_LIBRARY}" 87 | ${FLUTTER_LIBRARY_HEADERS} 88 | ) 89 | -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "size" : "20x20", 5 | "idiom" : "iphone", 6 | "filename" : "Icon-App-20x20@2x.png", 7 | "scale" : "2x" 8 | }, 9 | { 10 | "size" : "20x20", 11 | "idiom" : "iphone", 12 | "filename" : "Icon-App-20x20@3x.png", 13 | "scale" : "3x" 14 | }, 15 | { 16 | "size" : "29x29", 17 | "idiom" : "iphone", 18 | "filename" : "Icon-App-29x29@1x.png", 19 | "scale" : "1x" 20 | }, 21 | { 22 | "size" : "29x29", 23 | "idiom" : "iphone", 24 | "filename" : "Icon-App-29x29@2x.png", 25 | "scale" : "2x" 26 | }, 27 | { 28 | "size" : "29x29", 29 | "idiom" : "iphone", 30 | "filename" : "Icon-App-29x29@3x.png", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "size" : "40x40", 35 | "idiom" : "iphone", 36 | "filename" : "Icon-App-40x40@2x.png", 37 | "scale" : "2x" 38 | }, 39 | { 40 | "size" : "40x40", 41 | "idiom" : "iphone", 42 | "filename" : "Icon-App-40x40@3x.png", 43 | "scale" : "3x" 44 | }, 45 | { 46 | "size" : "60x60", 47 | "idiom" : "iphone", 48 | "filename" : "Icon-App-60x60@2x.png", 49 | "scale" : "2x" 50 | }, 51 | { 52 | "size" : "60x60", 53 | "idiom" : "iphone", 54 | "filename" : "Icon-App-60x60@3x.png", 55 | "scale" : "3x" 56 | }, 57 | { 58 | "size" : "20x20", 59 | "idiom" : "ipad", 60 | "filename" : "Icon-App-20x20@1x.png", 61 | "scale" : "1x" 62 | }, 63 | { 64 | "size" : "20x20", 65 | "idiom" : "ipad", 66 | "filename" : "Icon-App-20x20@2x.png", 67 | "scale" : "2x" 68 | }, 69 | { 70 | "size" : "29x29", 71 | "idiom" : "ipad", 72 | "filename" : "Icon-App-29x29@1x.png", 73 | "scale" : "1x" 74 | }, 75 | { 76 | "size" : "29x29", 77 | "idiom" : "ipad", 78 | "filename" : "Icon-App-29x29@2x.png", 79 | "scale" : "2x" 80 | }, 81 | { 82 | "size" : "40x40", 83 | "idiom" : "ipad", 84 | "filename" : "Icon-App-40x40@1x.png", 85 | "scale" : "1x" 86 | }, 87 | { 88 | "size" : "40x40", 89 | "idiom" : "ipad", 90 | "filename" : "Icon-App-40x40@2x.png", 91 | "scale" : "2x" 92 | }, 93 | { 94 | "size" : "76x76", 95 | "idiom" : "ipad", 96 | "filename" : "Icon-App-76x76@1x.png", 97 | "scale" : "1x" 98 | }, 99 | { 100 | "size" : "76x76", 101 | "idiom" : "ipad", 102 | "filename" : "Icon-App-76x76@2x.png", 103 | "scale" : "2x" 104 | }, 105 | { 106 | "size" : "83.5x83.5", 107 | "idiom" : "ipad", 108 | "filename" : "Icon-App-83.5x83.5@2x.png", 109 | "scale" : "2x" 110 | }, 111 | { 112 | "size" : "1024x1024", 113 | "idiom" : "ios-marketing", 114 | "filename" : "Icon-App-1024x1024@1x.png", 115 | "scale" : "1x" 116 | } 117 | ], 118 | "info" : { 119 | "version" : 1, 120 | "author" : "xcode" 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /example/lib/main.dart: -------------------------------------------------------------------------------- 1 | import 'package:example/sections/chat.dart'; 2 | import 'package:example/sections/chat_stream.dart'; 3 | import 'package:example/sections/embed_batch_contents.dart'; 4 | import 'package:example/sections/embed_content.dart'; 5 | import 'package:example/sections/response_widget_stream.dart'; 6 | import 'package:example/sections/stream.dart'; 7 | import 'package:example/sections/text_and_image.dart'; 8 | import 'package:example/sections/text_only.dart'; 9 | import 'package:flutter/material.dart'; 10 | import 'package:flutter_gemini/flutter_gemini.dart'; 11 | 12 | void main() async { 13 | /// flutter run --dart-define=apiKey='Your Api Key' 14 | Gemini.init( 15 | apiKey: const String.fromEnvironment('apiKey'), enableDebugging: true); 16 | 17 | // Gemini.reInitialize(apiKey: "new api key", enableDebugging: false); 18 | 19 | runApp(const MyApp()); 20 | } 21 | 22 | class MyApp extends StatelessWidget { 23 | const MyApp({super.key}); 24 | 25 | @override 26 | Widget build(BuildContext context) { 27 | return MaterialApp( 28 | title: 'Flutter Gemini', 29 | themeMode: ThemeMode.dark, 30 | debugShowCheckedModeBanner: false, 31 | darkTheme: ThemeData.dark().copyWith( 32 | colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), 33 | cardTheme: CardTheme(color: Colors.blue.shade900)), 34 | home: const MyHomePage(), 35 | ); 36 | } 37 | } 38 | 39 | class SectionItem { 40 | final int index; 41 | final String title; 42 | final Widget widget; 43 | 44 | SectionItem(this.index, this.title, this.widget); 45 | } 46 | 47 | class MyHomePage extends StatefulWidget { 48 | const MyHomePage({super.key}); 49 | 50 | @override 51 | State createState() => _MyHomePageState(); 52 | } 53 | 54 | class _MyHomePageState extends State { 55 | int _selectedItem = 0; 56 | 57 | final _sections = [ 58 | SectionItem(0, 'Stream text', const SectionTextStreamInput()), 59 | SectionItem(1, 'textAndImage', const SectionTextAndImageInput()), 60 | SectionItem(2, 'chat', const SectionChat()), 61 | SectionItem(3, 'Stream chat', const SectionStreamChat()), 62 | SectionItem(4, 'text', const SectionTextInput()), 63 | SectionItem(5, 'embedContent', const SectionEmbedContent()), 64 | SectionItem(6, 'batchEmbedContents', const SectionBatchEmbedContents()), 65 | SectionItem( 66 | 7, 'response without setState()', const ResponseWidgetSection()), 67 | ]; 68 | 69 | @override 70 | Widget build(BuildContext context) { 71 | return Scaffold( 72 | appBar: AppBar( 73 | backgroundColor: Theme.of(context).colorScheme.inversePrimary, 74 | title: Text(_selectedItem == 0 75 | ? 'Flutter Gemini' 76 | : _sections[_selectedItem].title), 77 | actions: [ 78 | PopupMenuButton( 79 | initialValue: _selectedItem, 80 | onSelected: (value) => setState(() => _selectedItem = value), 81 | itemBuilder: (context) => _sections.map((e) { 82 | return PopupMenuItem(value: e.index, child: Text(e.title)); 83 | }).toList(), 84 | child: const Icon(Icons.more_vert_rounded), 85 | ) 86 | ], 87 | ), 88 | body: IndexedStack( 89 | index: _selectedItem, 90 | children: _sections.map((e) => e.widget).toList(), 91 | ), 92 | ); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /example/windows/runner/Runner.rc: -------------------------------------------------------------------------------- 1 | // Microsoft Visual C++ generated resource script. 2 | // 3 | #pragma code_page(65001) 4 | #include "resource.h" 5 | 6 | #define APSTUDIO_READONLY_SYMBOLS 7 | ///////////////////////////////////////////////////////////////////////////// 8 | // 9 | // Generated from the TEXTINCLUDE 2 resource. 10 | // 11 | #include "winres.h" 12 | 13 | ///////////////////////////////////////////////////////////////////////////// 14 | #undef APSTUDIO_READONLY_SYMBOLS 15 | 16 | ///////////////////////////////////////////////////////////////////////////// 17 | // English (United States) resources 18 | 19 | #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) 20 | LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US 21 | 22 | #ifdef APSTUDIO_INVOKED 23 | ///////////////////////////////////////////////////////////////////////////// 24 | // 25 | // TEXTINCLUDE 26 | // 27 | 28 | 1 TEXTINCLUDE 29 | BEGIN 30 | "resource.h\0" 31 | END 32 | 33 | 2 TEXTINCLUDE 34 | BEGIN 35 | "#include ""winres.h""\r\n" 36 | "\0" 37 | END 38 | 39 | 3 TEXTINCLUDE 40 | BEGIN 41 | "\r\n" 42 | "\0" 43 | END 44 | 45 | #endif // APSTUDIO_INVOKED 46 | 47 | 48 | ///////////////////////////////////////////////////////////////////////////// 49 | // 50 | // Icon 51 | // 52 | 53 | // Icon with lowest ID value placed first to ensure application icon 54 | // remains consistent on all systems. 55 | IDI_APP_ICON ICON "resources\\app_icon.ico" 56 | 57 | 58 | ///////////////////////////////////////////////////////////////////////////// 59 | // 60 | // Version 61 | // 62 | 63 | #if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) 64 | #define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD 65 | #else 66 | #define VERSION_AS_NUMBER 1,0,0,0 67 | #endif 68 | 69 | #if defined(FLUTTER_VERSION) 70 | #define VERSION_AS_STRING FLUTTER_VERSION 71 | #else 72 | #define VERSION_AS_STRING "1.0.0" 73 | #endif 74 | 75 | VS_VERSION_INFO VERSIONINFO 76 | FILEVERSION VERSION_AS_NUMBER 77 | PRODUCTVERSION VERSION_AS_NUMBER 78 | FILEFLAGSMASK VS_FFI_FILEFLAGSMASK 79 | #ifdef _DEBUG 80 | FILEFLAGS VS_FF_DEBUG 81 | #else 82 | FILEFLAGS 0x0L 83 | #endif 84 | FILEOS VOS__WINDOWS32 85 | FILETYPE VFT_APP 86 | FILESUBTYPE 0x0L 87 | BEGIN 88 | BLOCK "StringFileInfo" 89 | BEGIN 90 | BLOCK "040904e4" 91 | BEGIN 92 | VALUE "CompanyName", "com.example" "\0" 93 | VALUE "FileDescription", "example" "\0" 94 | VALUE "FileVersion", VERSION_AS_STRING "\0" 95 | VALUE "InternalName", "example" "\0" 96 | VALUE "LegalCopyright", "Copyright (C) 2023 com.example. All rights reserved." "\0" 97 | VALUE "OriginalFilename", "example.exe" "\0" 98 | VALUE "ProductName", "example" "\0" 99 | VALUE "ProductVersion", VERSION_AS_STRING "\0" 100 | END 101 | END 102 | BLOCK "VarFileInfo" 103 | BEGIN 104 | VALUE "Translation", 0x409, 1252 105 | END 106 | END 107 | 108 | #endif // English (United States) resources 109 | ///////////////////////////////////////////////////////////////////////////// 110 | 111 | 112 | 113 | #ifndef APSTUDIO_INVOKED 114 | ///////////////////////////////////////////////////////////////////////////// 115 | // 116 | // Generated from the TEXTINCLUDE 3 resource. 117 | // 118 | 119 | 120 | ///////////////////////////////////////////////////////////////////////////// 121 | #endif // not APSTUDIO_INVOKED 122 | -------------------------------------------------------------------------------- /example/lib/sections/chat_stream.dart: -------------------------------------------------------------------------------- 1 | import 'package:example/widgets/chat_input_box.dart'; 2 | import 'package:flutter/material.dart'; 3 | import 'package:flutter_gemini/flutter_gemini.dart'; 4 | import 'package:flutter_markdown/flutter_markdown.dart'; 5 | 6 | class SectionStreamChat extends StatefulWidget { 7 | const SectionStreamChat({super.key}); 8 | 9 | @override 10 | State createState() => _SectionStreamChatState(); 11 | } 12 | 13 | class _SectionStreamChatState extends State { 14 | final controller = TextEditingController(); 15 | final gemini = Gemini.instance; 16 | bool _loading = false; 17 | 18 | bool get loading => _loading; 19 | 20 | set loading(bool set) => setState(() => _loading = set); 21 | final List chats = []; 22 | 23 | @override 24 | Widget build(BuildContext context) { 25 | return Column( 26 | children: [ 27 | Expanded( 28 | child: chats.isNotEmpty 29 | ? Align( 30 | alignment: Alignment.bottomCenter, 31 | child: SingleChildScrollView( 32 | reverse: true, 33 | child: ListView.builder( 34 | itemBuilder: chatItem, 35 | shrinkWrap: true, 36 | physics: const NeverScrollableScrollPhysics(), 37 | itemCount: chats.length, 38 | reverse: false, 39 | ), 40 | ), 41 | ) 42 | : const Center(child: Text('Search something!'))), 43 | if (loading) const CircularProgressIndicator(), 44 | ChatInputBox( 45 | controller: controller, 46 | onSend: () { 47 | if (controller.text.isNotEmpty) { 48 | final searchedText = controller.text; 49 | chats.add( 50 | Content(role: 'user', parts: [Parts(text: searchedText)])); 51 | controller.clear(); 52 | loading = true; 53 | 54 | gemini.streamChat(chats).listen((value) { 55 | print("-------------------------------"); 56 | print(value.output); 57 | loading = false; 58 | setState(() { 59 | if (chats.isNotEmpty && 60 | chats.last.role == value.content?.role) { 61 | chats.last.parts!.last.text = 62 | '${chats.last.parts!.last.text}${value.output}'; 63 | } else { 64 | chats.add(Content( 65 | role: 'model', parts: [Parts(text: value.output)])); 66 | } 67 | }); 68 | }); 69 | } 70 | }, 71 | ), 72 | ], 73 | ); 74 | } 75 | 76 | Widget chatItem(BuildContext context, int index) { 77 | final Content content = chats[index]; 78 | 79 | return Card( 80 | elevation: 0, 81 | color: 82 | content.role == 'model' ? Colors.blue.shade800 : Colors.transparent, 83 | child: Padding( 84 | padding: const EdgeInsets.all(8.0), 85 | child: Column( 86 | crossAxisAlignment: CrossAxisAlignment.start, 87 | children: [ 88 | Text(content.role ?? 'role'), 89 | Markdown( 90 | shrinkWrap: true, 91 | physics: const NeverScrollableScrollPhysics(), 92 | data: 93 | content.parts?.lastOrNull?.text ?? 'cannot generate data!'), 94 | ], 95 | ), 96 | ), 97 | ); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /assets/json_models/gemini_model.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "models/chat-bison-001", 4 | "version": "001", 5 | "displayName": "Chat Bison", 6 | "description": "Chat-optimized generative language model.", 7 | "inputTokenLimit": 4096, 8 | "outputTokenLimit": 1024, 9 | "supportedGenerationMethods": ["generateMessage", "countMessageTokens"], 10 | "temperature": 0.25, 11 | "topP": 0.95, 12 | "topK": 40 13 | }, 14 | { 15 | "name": "models/text-bison-001", 16 | "version": "001", 17 | "displayName": "Text Bison", 18 | "description": "Model targeted for text generation.", 19 | "inputTokenLimit": 8196, 20 | "outputTokenLimit": 1024, 21 | "supportedGenerationMethods": [ 22 | "generateText", 23 | "countTextTokens", 24 | "createTunedTextModel" 25 | ], 26 | "temperature": 0.7, 27 | "topP": 0.95, 28 | "topK": 40 29 | }, 30 | { 31 | "name": "models/embedding-gecko-001", 32 | "version": "001", 33 | "displayName": "Embedding Gecko", 34 | "description": "Obtain a distributed representation of a text.", 35 | "inputTokenLimit": 1024, 36 | "outputTokenLimit": 1, 37 | "supportedGenerationMethods": ["embedText", "countTextTokens"] 38 | }, 39 | { 40 | "name": "models/embedding-gecko-002", 41 | "version": "002", 42 | "displayName": "Embedding Gecko 002", 43 | "description": "Obtain a distributed representation of a text.", 44 | "inputTokenLimit": 2048, 45 | "outputTokenLimit": 1, 46 | "supportedGenerationMethods": ["embedText", "countTextTokens"] 47 | }, 48 | { 49 | "name": "models/gemini-pro", 50 | "version": "001", 51 | "displayName": "Gemini Pro", 52 | "description": "The best model for scaling across a wide range of tasks", 53 | "inputTokenLimit": 30720, 54 | "outputTokenLimit": 2048, 55 | "supportedGenerationMethods": ["generateContent", "countTokens"], 56 | "temperature": 0.9, 57 | "topP": 1, 58 | "topK": 1 59 | }, 60 | { 61 | "name": "models/gemini-pro-vision", 62 | "version": "001", 63 | "displayName": "Gemini Pro Vision", 64 | "description": 65 | "The best image understanding model to handle a broad range of applications", 66 | "inputTokenLimit": 12288, 67 | "outputTokenLimit": 4096, 68 | "supportedGenerationMethods": ["generateContent", "countTokens"], 69 | "temperature": 0.4, 70 | "topP": 1, 71 | "topK": 32 72 | }, 73 | { 74 | "name": "models/gemini-ultra", 75 | "version": "001", 76 | "displayName": "Gemini Ultra", 77 | "description": "The most capable model for highly complex tasks", 78 | "inputTokenLimit": 30720, 79 | "outputTokenLimit": 2048, 80 | "supportedGenerationMethods": ["generateContent", "countTokens"], 81 | "temperature": 0.9, 82 | "topP": 1, 83 | "topK": 32 84 | }, 85 | { 86 | "name": "models/embedding-001", 87 | "version": "001", 88 | "displayName": "Embedding 001", 89 | "description": "Obtain a distributed representation of a text.", 90 | "inputTokenLimit": 2048, 91 | "outputTokenLimit": 1, 92 | "supportedGenerationMethods": ["embedContent", "countTextTokens"] 93 | }, 94 | { 95 | "name": "models/aqa", 96 | "version": "001", 97 | "displayName": "Model that performs Attributed Question Answering.", 98 | "description": 99 | "Model trained to return answers to questions that are grounded in provided sources, along with estimating answerable probability.", 100 | "inputTokenLimit": 7168, 101 | "outputTokenLimit": 1024, 102 | "supportedGenerationMethods": ["generateAnswer"], 103 | "temperature": 0.2, 104 | "topP": 1, 105 | "topK": 40 106 | } 107 | ] -------------------------------------------------------------------------------- /example/lib/sections/text_and_image.dart: -------------------------------------------------------------------------------- 1 | import 'dart:typed_data'; 2 | 3 | import 'package:example/widgets/chat_input_box.dart'; 4 | import 'package:flutter/material.dart'; 5 | import 'package:flutter_gemini/flutter_gemini.dart'; 6 | import 'package:flutter_markdown/flutter_markdown.dart'; 7 | import 'package:image_picker/image_picker.dart'; 8 | import 'package:lottie/lottie.dart'; 9 | 10 | class SectionTextAndImageInput extends StatefulWidget { 11 | const SectionTextAndImageInput({super.key}); 12 | 13 | @override 14 | State createState() => 15 | _SectionTextAndImageInputState(); 16 | } 17 | 18 | class _SectionTextAndImageInputState extends State { 19 | final ImagePicker picker = ImagePicker(); 20 | final controller = TextEditingController(); 21 | final gemini = Gemini.instance; 22 | String? searchedText, result; 23 | bool _loading = false; 24 | 25 | Uint8List? selectedImage; 26 | 27 | bool get loading => _loading; 28 | 29 | set loading(bool set) => setState(() => _loading = set); 30 | 31 | @override 32 | Widget build(BuildContext context) { 33 | return Column( 34 | children: [ 35 | if (searchedText != null) 36 | MaterialButton( 37 | color: Colors.blue.shade700, 38 | onPressed: () { 39 | setState(() { 40 | searchedText = null; 41 | result = null; 42 | }); 43 | }, 44 | child: Text('search: $searchedText')), 45 | Expanded( 46 | child: Padding( 47 | padding: const EdgeInsets.all(8.0), 48 | child: Row( 49 | mainAxisAlignment: MainAxisAlignment.center, 50 | children: [ 51 | Expanded( 52 | flex: 2, 53 | child: loading 54 | ? Lottie.asset('assets/lottie/ai.json') 55 | : result != null 56 | ? Markdown( 57 | data: result!, 58 | padding: 59 | const EdgeInsets.symmetric(horizontal: 12), 60 | ) 61 | : const Center( 62 | child: Text('Search something!'), 63 | ), 64 | ), 65 | if (selectedImage != null) 66 | Expanded( 67 | flex: 1, 68 | child: ClipRRect( 69 | borderRadius: BorderRadius.circular(32), 70 | child: Image.memory( 71 | selectedImage!, 72 | fit: BoxFit.cover, 73 | ), 74 | ), 75 | ) 76 | ], 77 | ), 78 | ), 79 | ), 80 | ChatInputBox( 81 | controller: controller, 82 | onClickCamera: () async { 83 | // Capture a photo. 84 | final XFile? photo = 85 | await picker.pickImage(source: ImageSource.camera); 86 | 87 | if (photo != null) { 88 | photo.readAsBytes().then((value) => setState(() { 89 | selectedImage = value; 90 | })); 91 | } 92 | }, 93 | onSend: () { 94 | if (controller.text.isNotEmpty && selectedImage != null) { 95 | searchedText = controller.text; 96 | controller.clear(); 97 | loading = true; 98 | 99 | gemini.textAndImage( 100 | text: searchedText!, images: [selectedImage!]).then((value) { 101 | result = value?.content?.parts?.last.text; 102 | loading = false; 103 | }); 104 | } 105 | }, 106 | ), 107 | ], 108 | ); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /assets/json_models/gemini_response.json: -------------------------------------------------------------------------------- 1 | { 2 | "candidates": [ 3 | { 4 | "content": { 5 | "parts": [ 6 | { 7 | "text": "Once upon a time, in a small town nestled at the foot of towering mountains, there lived a young girl named Lily. Lily was an adventurous and imaginative child, always dreaming of exploring the world beyond her home. One day, while wandering through the attic of her grandmother's house, she stumbled upon a dusty old backpack tucked away in a forgotten corner. Intrigued, Lily opened the backpack and discovered that it was an enchanted one. Little did she know that this magical backpack would change her life forever.\n\nAs Lily touched the backpack, it shimmered with an otherworldly light. She reached inside and pulled out a map that seemed to shift and change before her eyes, revealing hidden paths and distant lands. Curiosity tugged at her heart, and without hesitation, Lily shouldered the backpack and embarked on her first adventure.\n\nWith each step she took, the backpack adjusted to her needs. When the path grew treacherous, the backpack transformed into sturdy hiking boots, providing her with the confidence to navigate rocky terrains. When a sudden rainstorm poured down, the backpack transformed into a cozy shelter, shielding her from the elements.\n\nAs days turned into weeks, Lily's journey took her through lush forests, across treacherous rivers, and to the summits of towering mountains. The backpack became her loyal companion, guiding her along the way, offering comfort, protection, and inspiration.\n\nAmong her many adventures, Lily encountered a lost fawn that she gently carried in the backpack's transformed cradle. She helped a friendly giant navigate a dense fog by using the backpack's built-in compass. And when faced with a raging river, the backpack magically transformed into a sturdy raft, transporting her safely to the other side.\n\nThrough her travels, Lily discovered the true power of the magic backpack. It wasn't just a magical object but a reflection of her own boundless imagination and tenacity. She realized that the world was hers to explore, and the backpack was a tool to help her reach her full potential.\n\nAs Lily returned home, enriched by her adventures and brimming with stories, she decided to share the magic of the backpack with others. She organized a special adventure club, where children could embark on their own extraordinary journeys using the backpack's transformative powers. Together, they explored hidden worlds, learned valuable lessons, and formed lifelong friendships.\n\nAnd so, the legend of the magic backpack lived on, passed down from generation to generation. It became a reminder that even the simplest objects can hold extraordinary power when combined with imagination, courage, and a sprinkle of magic." 8 | } 9 | ], 10 | "role": "model" 11 | }, 12 | "finishReason": "STOP", 13 | "index": 0, 14 | "safetyRatings": [ 15 | { 16 | "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", 17 | "probability": "NEGLIGIBLE" 18 | }, 19 | { 20 | "category": "HARM_CATEGORY_HATE_SPEECH", 21 | "probability": "NEGLIGIBLE" 22 | }, 23 | { 24 | "category": "HARM_CATEGORY_HARASSMENT", 25 | "probability": "NEGLIGIBLE" 26 | }, 27 | { 28 | "category": "HARM_CATEGORY_DANGEROUS_CONTENT", 29 | "probability": "NEGLIGIBLE" 30 | } 31 | ] 32 | } 33 | ], 34 | "promptFeedback": { 35 | "safetyRatings": [ 36 | { 37 | "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", 38 | "probability": "NEGLIGIBLE" 39 | }, 40 | { 41 | "category": "HARM_CATEGORY_HATE_SPEECH", 42 | "probability": "NEGLIGIBLE" 43 | }, 44 | { 45 | "category": "HARM_CATEGORY_HARASSMENT", 46 | "probability": "NEGLIGIBLE" 47 | }, 48 | { 49 | "category": "HARM_CATEGORY_DANGEROUS_CONTENT", 50 | "probability": "NEGLIGIBLE" 51 | } 52 | ] 53 | } 54 | } -------------------------------------------------------------------------------- /example/windows/runner/win32_window.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_WIN32_WINDOW_H_ 2 | #define RUNNER_WIN32_WINDOW_H_ 3 | 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | // A class abstraction for a high DPI-aware Win32 Window. Intended to be 11 | // inherited from by classes that wish to specialize with custom 12 | // rendering and input handling 13 | class Win32Window { 14 | public: 15 | struct Point { 16 | unsigned int x; 17 | unsigned int y; 18 | Point(unsigned int x, unsigned int y) : x(x), y(y) {} 19 | }; 20 | 21 | struct Size { 22 | unsigned int width; 23 | unsigned int height; 24 | Size(unsigned int width, unsigned int height) 25 | : width(width), height(height) {} 26 | }; 27 | 28 | Win32Window(); 29 | virtual ~Win32Window(); 30 | 31 | // Creates a win32 window with |title| that is positioned and sized using 32 | // |origin| and |size|. New windows are created on the default monitor. Window 33 | // sizes are specified to the OS in physical pixels, hence to ensure a 34 | // consistent size this function will scale the inputted width and height as 35 | // as appropriate for the default monitor. The window is invisible until 36 | // |Show| is called. Returns true if the window was created successfully. 37 | bool Create(const std::wstring& title, const Point& origin, const Size& size); 38 | 39 | // Show the current window. Returns true if the window was successfully shown. 40 | bool Show(); 41 | 42 | // Release OS resources associated with window. 43 | void Destroy(); 44 | 45 | // Inserts |content| into the window tree. 46 | void SetChildContent(HWND content); 47 | 48 | // Returns the backing Window handle to enable clients to set icon and other 49 | // window properties. Returns nullptr if the window has been destroyed. 50 | HWND GetHandle(); 51 | 52 | // If true, closing this window will quit the application. 53 | void SetQuitOnClose(bool quit_on_close); 54 | 55 | // Return a RECT representing the bounds of the current client area. 56 | RECT GetClientArea(); 57 | 58 | protected: 59 | // Processes and route salient window messages for mouse handling, 60 | // size change and DPI. Delegates handling of these to member overloads that 61 | // inheriting classes can handle. 62 | virtual LRESULT MessageHandler(HWND window, 63 | UINT const message, 64 | WPARAM const wparam, 65 | LPARAM const lparam) noexcept; 66 | 67 | // Called when CreateAndShow is called, allowing subclass window-related 68 | // setup. Subclasses should return false if setup fails. 69 | virtual bool OnCreate(); 70 | 71 | // Called when Destroy is called. 72 | virtual void OnDestroy(); 73 | 74 | private: 75 | friend class WindowClassRegistrar; 76 | 77 | // OS callback called by message pump. Handles the WM_NCCREATE message which 78 | // is passed when the non-client area is being created and enables automatic 79 | // non-client DPI scaling so that the non-client area automatically 80 | // responds to changes in DPI. All other messages are handled by 81 | // MessageHandler. 82 | static LRESULT CALLBACK WndProc(HWND const window, 83 | UINT const message, 84 | WPARAM const wparam, 85 | LPARAM const lparam) noexcept; 86 | 87 | // Retrieves a class instance pointer for |window| 88 | static Win32Window* GetThisFromHandle(HWND const window) noexcept; 89 | 90 | // Update the window frame's theme to match the system theme. 91 | static void UpdateTheme(HWND const window); 92 | 93 | bool quit_on_close_ = false; 94 | 95 | // window handle for top level window. 96 | HWND window_handle_ = nullptr; 97 | 98 | // window handle for hosted content. 99 | HWND child_content_ = nullptr; 100 | }; 101 | 102 | #endif // RUNNER_WIN32_WINDOW_H_ 103 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 37 | 38 | 39 | 40 | 43 | 49 | 50 | 51 | 52 | 53 | 63 | 65 | 71 | 72 | 73 | 74 | 80 | 82 | 88 | 89 | 90 | 91 | 93 | 94 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 37 | 38 | 39 | 40 | 43 | 49 | 50 | 51 | 52 | 53 | 63 | 65 | 71 | 72 | 73 | 74 | 80 | 82 | 88 | 89 | 90 | 91 | 93 | 94 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /example/windows/flutter/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This file controls Flutter-level build steps. It should not be edited. 2 | cmake_minimum_required(VERSION 3.14) 3 | 4 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") 5 | 6 | # Configuration provided via flutter tool. 7 | include(${EPHEMERAL_DIR}/generated_config.cmake) 8 | 9 | # TODO: Move the rest of this into files in ephemeral. See 10 | # https://github.com/flutter/flutter/issues/57146. 11 | set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") 12 | 13 | # === Flutter Library === 14 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") 15 | 16 | # Published to parent scope for install step. 17 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) 18 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) 19 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) 20 | set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) 21 | 22 | list(APPEND FLUTTER_LIBRARY_HEADERS 23 | "flutter_export.h" 24 | "flutter_windows.h" 25 | "flutter_messenger.h" 26 | "flutter_plugin_registrar.h" 27 | "flutter_texture_registrar.h" 28 | ) 29 | list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") 30 | add_library(flutter INTERFACE) 31 | target_include_directories(flutter INTERFACE 32 | "${EPHEMERAL_DIR}" 33 | ) 34 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") 35 | add_dependencies(flutter flutter_assemble) 36 | 37 | # === Wrapper === 38 | list(APPEND CPP_WRAPPER_SOURCES_CORE 39 | "core_implementations.cc" 40 | "standard_codec.cc" 41 | ) 42 | list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") 43 | list(APPEND CPP_WRAPPER_SOURCES_PLUGIN 44 | "plugin_registrar.cc" 45 | ) 46 | list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") 47 | list(APPEND CPP_WRAPPER_SOURCES_APP 48 | "flutter_engine.cc" 49 | "flutter_view_controller.cc" 50 | ) 51 | list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") 52 | 53 | # Wrapper sources needed for a plugin. 54 | add_library(flutter_wrapper_plugin STATIC 55 | ${CPP_WRAPPER_SOURCES_CORE} 56 | ${CPP_WRAPPER_SOURCES_PLUGIN} 57 | ) 58 | apply_standard_settings(flutter_wrapper_plugin) 59 | set_target_properties(flutter_wrapper_plugin PROPERTIES 60 | POSITION_INDEPENDENT_CODE ON) 61 | set_target_properties(flutter_wrapper_plugin PROPERTIES 62 | CXX_VISIBILITY_PRESET hidden) 63 | target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) 64 | target_include_directories(flutter_wrapper_plugin PUBLIC 65 | "${WRAPPER_ROOT}/include" 66 | ) 67 | add_dependencies(flutter_wrapper_plugin flutter_assemble) 68 | 69 | # Wrapper sources needed for the runner. 70 | add_library(flutter_wrapper_app STATIC 71 | ${CPP_WRAPPER_SOURCES_CORE} 72 | ${CPP_WRAPPER_SOURCES_APP} 73 | ) 74 | apply_standard_settings(flutter_wrapper_app) 75 | target_link_libraries(flutter_wrapper_app PUBLIC flutter) 76 | target_include_directories(flutter_wrapper_app PUBLIC 77 | "${WRAPPER_ROOT}/include" 78 | ) 79 | add_dependencies(flutter_wrapper_app flutter_assemble) 80 | 81 | # === Flutter tool backend === 82 | # _phony_ is a non-existent file to force this command to run every time, 83 | # since currently there's no way to get a full input/output list from the 84 | # flutter tool. 85 | set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") 86 | set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) 87 | add_custom_command( 88 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} 89 | ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} 90 | ${CPP_WRAPPER_SOURCES_APP} 91 | ${PHONY_OUTPUT} 92 | COMMAND ${CMAKE_COMMAND} -E env 93 | ${FLUTTER_TOOL_ENVIRONMENT} 94 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" 95 | windows-x64 $ 96 | VERBATIM 97 | ) 98 | add_custom_target(flutter_assemble DEPENDS 99 | "${FLUTTER_LIBRARY}" 100 | ${FLUTTER_LIBRARY_HEADERS} 101 | ${CPP_WRAPPER_SOURCES_CORE} 102 | ${CPP_WRAPPER_SOURCES_PLUGIN} 103 | ${CPP_WRAPPER_SOURCES_APP} 104 | ) 105 | -------------------------------------------------------------------------------- /lib/src/repository/gemini_interface.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | import 'dart:typed_data'; 3 | import 'package:flutter_gemini/src/models/candidates/candidates.dart'; 4 | import '../../flutter_gemini.dart'; 5 | 6 | abstract class GeminiInterface { 7 | /// [listModels] 8 | /// If you `GET` the `models` directory, it used the `list` method to list 9 | /// all of the models available through the API, including both the Gemini and PaLM family models. 10 | Future> listModels(); 11 | 12 | /// [info] 13 | /// If you `GET` a model's URL, the API used the `get` method to return 14 | /// information about that model such as version, display name, input token limit, etc. 15 | Future info({required String model}); 16 | 17 | /// [text] Use the `generateContent` method to generate a response 18 | /// from the model given an input message. 19 | /// If the input contains only text, use the `gemini-pro` model. 20 | Future text( 21 | String text, { 22 | String? modelName, 23 | List? safetySettings, 24 | GenerationConfig? generationConfig, 25 | }); 26 | 27 | /// [Embedding] is a technique used to represent information as a 28 | /// list of floating point numbers in an array. 29 | /// With Gemini, you can represent text (words, sentences, and blocks of text) 30 | /// in a vectorized form, making it easier to compare and contrast embeddings. 31 | /// For example, two texts that share a similar subject matter or sentiment 32 | /// should have similar embeddings, which can be identified through mathematical 33 | /// comparison techniques such as cosine similarity. 34 | /// 35 | /// Use the `embedding-001` model with either [embedContent] or [batchEmbedContents] 36 | Future?>?> batchEmbedContents( 37 | List texts, { 38 | String? modelName, 39 | List? safetySettings, 40 | GenerationConfig? generationConfig, 41 | }); 42 | 43 | /// [embedContent] description in upper comments 44 | Future?> embedContent( 45 | String text, { 46 | String? modelName, 47 | List? safetySettings, 48 | GenerationConfig? generationConfig, 49 | }); 50 | 51 | /// [countTokens] When using long prompts, it might be useful to count tokens 52 | /// before sending any content to the model. 53 | Future countTokens( 54 | String text, { 55 | String? modelName, 56 | List? safetySettings, 57 | GenerationConfig? generationConfig, 58 | }); 59 | 60 | /// [streamGenerateContent] By default, the model returns a response after 61 | /// completing the entire generation process. 62 | /// You can achieve faster interactions by not waiting 63 | /// for the entire result, and instead use streaming to handle partial results. 64 | Stream streamGenerateContent( 65 | String text, { 66 | List? images, 67 | String? modelName, 68 | List? safetySettings, 69 | GenerationConfig? generationConfig, 70 | }); 71 | 72 | Stream streamChat( 73 | List chats, { 74 | String? modelName, 75 | List? safetySettings, 76 | GenerationConfig? generationConfig, 77 | }); 78 | 79 | /// [chat] or `Multi-turn conversations` 80 | /// Using Gemini, you can build freeform conversations across multiple turns. 81 | Future chat( 82 | List chats, { 83 | String? modelName, 84 | List? safetySettings, 85 | GenerationConfig? generationConfig, 86 | }); 87 | 88 | /// [textAndImage] If the input contains both text and image, use 89 | /// the `gemini-pro-vision` model. The following snippets help you build a request and send it to the REST API. 90 | Future textAndImage({ 91 | required String text, 92 | required List images, 93 | String? modelName, 94 | List? safetySettings, 95 | GenerationConfig? generationConfig, 96 | }); 97 | 98 | // cancel request 99 | Future cancelRequest(); 100 | } 101 | -------------------------------------------------------------------------------- /example/linux/my_application.cc: -------------------------------------------------------------------------------- 1 | #include "my_application.h" 2 | 3 | #include 4 | #ifdef GDK_WINDOWING_X11 5 | #include 6 | #endif 7 | 8 | #include "flutter/generated_plugin_registrant.h" 9 | 10 | struct _MyApplication { 11 | GtkApplication parent_instance; 12 | char** dart_entrypoint_arguments; 13 | }; 14 | 15 | G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) 16 | 17 | // Implements GApplication::activate. 18 | static void my_application_activate(GApplication* application) { 19 | MyApplication* self = MY_APPLICATION(application); 20 | GtkWindow* window = 21 | GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); 22 | 23 | // Use a header bar when running in GNOME as this is the common style used 24 | // by applications and is the setup most users will be using (e.g. Ubuntu 25 | // desktop). 26 | // If running on X and not using GNOME then just use a traditional title bar 27 | // in case the window manager does more exotic layout, e.g. tiling. 28 | // If running on Wayland assume the header bar will work (may need changing 29 | // if future cases occur). 30 | gboolean use_header_bar = TRUE; 31 | #ifdef GDK_WINDOWING_X11 32 | GdkScreen* screen = gtk_window_get_screen(window); 33 | if (GDK_IS_X11_SCREEN(screen)) { 34 | const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); 35 | if (g_strcmp0(wm_name, "GNOME Shell") != 0) { 36 | use_header_bar = FALSE; 37 | } 38 | } 39 | #endif 40 | if (use_header_bar) { 41 | GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); 42 | gtk_widget_show(GTK_WIDGET(header_bar)); 43 | gtk_header_bar_set_title(header_bar, "example"); 44 | gtk_header_bar_set_show_close_button(header_bar, TRUE); 45 | gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); 46 | } else { 47 | gtk_window_set_title(window, "example"); 48 | } 49 | 50 | gtk_window_set_default_size(window, 1280, 720); 51 | gtk_widget_show(GTK_WIDGET(window)); 52 | 53 | g_autoptr(FlDartProject) project = fl_dart_project_new(); 54 | fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); 55 | 56 | FlView* view = fl_view_new(project); 57 | gtk_widget_show(GTK_WIDGET(view)); 58 | gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); 59 | 60 | fl_register_plugins(FL_PLUGIN_REGISTRY(view)); 61 | 62 | gtk_widget_grab_focus(GTK_WIDGET(view)); 63 | } 64 | 65 | // Implements GApplication::local_command_line. 66 | static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { 67 | MyApplication* self = MY_APPLICATION(application); 68 | // Strip out the first argument as it is the binary name. 69 | self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); 70 | 71 | g_autoptr(GError) error = nullptr; 72 | if (!g_application_register(application, nullptr, &error)) { 73 | g_warning("Failed to register: %s", error->message); 74 | *exit_status = 1; 75 | return TRUE; 76 | } 77 | 78 | g_application_activate(application); 79 | *exit_status = 0; 80 | 81 | return TRUE; 82 | } 83 | 84 | // Implements GObject::dispose. 85 | static void my_application_dispose(GObject* object) { 86 | MyApplication* self = MY_APPLICATION(object); 87 | g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); 88 | G_OBJECT_CLASS(my_application_parent_class)->dispose(object); 89 | } 90 | 91 | static void my_application_class_init(MyApplicationClass* klass) { 92 | G_APPLICATION_CLASS(klass)->activate = my_application_activate; 93 | G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; 94 | G_OBJECT_CLASS(klass)->dispose = my_application_dispose; 95 | } 96 | 97 | static void my_application_init(MyApplication* self) {} 98 | 99 | MyApplication* my_application_new() { 100 | return MY_APPLICATION(g_object_new(my_application_get_type(), 101 | "application-id", APPLICATION_ID, 102 | "flags", G_APPLICATION_NON_UNIQUE, 103 | nullptr)); 104 | } 105 | -------------------------------------------------------------------------------- /example/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: example 2 | description: A new Flutter project. 3 | # The following line prevents the package from being accidentally published to 4 | # pub.dev using `flutter pub publish`. This is preferred for private packages. 5 | publish_to: 'none' # Remove this line if you wish to publish to pub.dev 6 | 7 | # The following defines the version and build number for your application. 8 | # A version number is three numbers separated by dots, like 1.2.43 9 | # followed by an optional build number separated by a +. 10 | # Both the version and the builder number may be overridden in flutter 11 | # build by specifying --build-name and --build-number, respectively. 12 | # In Android, build-name is used as versionName while build-number used as versionCode. 13 | # Read more about Android versioning at https://developer.android.com/studio/publish/versioning 14 | # In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. 15 | # Read more about iOS versioning at 16 | # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html 17 | # In Windows, build-name is used as the major, minor, and patch parts 18 | # of the product and file versions while build-number is used as the build suffix. 19 | version: 1.0.0+1 20 | 21 | environment: 22 | sdk: '>=3.1.3 <4.0.0' 23 | 24 | # Dependencies specify other packages that your package needs in order to work. 25 | # To automatically upgrade your package dependencies to the latest versions 26 | # consider running `flutter pub upgrade --major-versions`. Alternatively, 27 | # dependencies can be manually updated by changing the version numbers below to 28 | # the latest version available on pub.dev. To see which dependencies have newer 29 | # versions available, run `flutter pub outdated`. 30 | dependencies: 31 | flutter: 32 | sdk: flutter 33 | 34 | 35 | # The following adds the Cupertino Icons font to your application. 36 | # Use with the CupertinoIcons class for iOS style icons. 37 | cupertino_icons: ^1.0.2 38 | flutter_gemini: 39 | path: ../ 40 | lottie: ^2.7.0 41 | flutter_markdown: ^0.6.18+2 42 | image_picker: ^1.0.5 43 | 44 | dev_dependencies: 45 | flutter_test: 46 | sdk: flutter 47 | 48 | # The "flutter_lints" package below contains a set of recommended lints to 49 | # encourage good coding practices. The lint set provided by the package is 50 | # activated in the `analysis_options.yaml` file located at the root of your 51 | # package. See that file for information about deactivating specific lint 52 | # rules and activating additional ones. 53 | flutter_lints: ^2.0.0 54 | 55 | # For information on the generic Dart part of this file, see the 56 | # following page: https://dart.dev/tools/pub/pubspec 57 | 58 | # The following section is specific to Flutter packages. 59 | flutter: 60 | 61 | # The following line ensures that the Material Icons font is 62 | # included with your application, so that you can use the icons in 63 | # the material Icons class. 64 | uses-material-design: true 65 | 66 | # To add assets to your application, add an assets section, like this: 67 | assets: 68 | - assets/lottie/ 69 | 70 | # An image asset can refer to one or more resolution-specific "variants", see 71 | # https://flutter.dev/assets-and-images/#resolution-aware 72 | 73 | # For details regarding adding assets from package dependencies, see 74 | # https://flutter.dev/assets-and-images/#from-packages 75 | 76 | # To add custom fonts to your application, add a fonts section here, 77 | # in this "flutter" section. Each entry in this list should have a 78 | # "family" key with the font family name, and a "fonts" key with a 79 | # list giving the asset and other descriptors for the font. For 80 | # example: 81 | # fonts: 82 | # - family: Schyler 83 | # fonts: 84 | # - asset: fonts/Schyler-Regular.ttf 85 | # - asset: fonts/Schyler-Italic.ttf 86 | # style: italic 87 | # - family: Trajan Pro 88 | # fonts: 89 | # - asset: fonts/TrajanPro.ttf 90 | # - asset: fonts/TrajanPro_Bold.ttf 91 | # weight: 700 92 | # 93 | # For details regarding fonts from package dependencies, 94 | # see https://flutter.dev/custom-fonts/#from-packages 95 | -------------------------------------------------------------------------------- /example/windows/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Project-level configuration. 2 | cmake_minimum_required(VERSION 3.14) 3 | project(example LANGUAGES CXX) 4 | 5 | # The name of the executable created for the application. Change this to change 6 | # the on-disk name of your application. 7 | set(BINARY_NAME "example") 8 | 9 | # Explicitly opt in to modern CMake behaviors to avoid warnings with recent 10 | # versions of CMake. 11 | cmake_policy(VERSION 3.14...3.25) 12 | 13 | # Define build configuration option. 14 | get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) 15 | if(IS_MULTICONFIG) 16 | set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" 17 | CACHE STRING "" FORCE) 18 | else() 19 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) 20 | set(CMAKE_BUILD_TYPE "Debug" CACHE 21 | STRING "Flutter build mode" FORCE) 22 | set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS 23 | "Debug" "Profile" "Release") 24 | endif() 25 | endif() 26 | # Define settings for the Profile build mode. 27 | set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") 28 | set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") 29 | set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") 30 | set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") 31 | 32 | # Use Unicode for all projects. 33 | add_definitions(-DUNICODE -D_UNICODE) 34 | 35 | # Compilation settings that should be applied to most targets. 36 | # 37 | # Be cautious about adding new options here, as plugins use this function by 38 | # default. In most cases, you should add new options to specific targets instead 39 | # of modifying this function. 40 | function(APPLY_STANDARD_SETTINGS TARGET) 41 | target_compile_features(${TARGET} PUBLIC cxx_std_17) 42 | target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") 43 | target_compile_options(${TARGET} PRIVATE /EHsc) 44 | target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") 45 | target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") 46 | endfunction() 47 | 48 | # Flutter library and tool build rules. 49 | set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") 50 | add_subdirectory(${FLUTTER_MANAGED_DIR}) 51 | 52 | # Application build; see runner/CMakeLists.txt. 53 | add_subdirectory("runner") 54 | 55 | 56 | # Generated plugin build rules, which manage building the plugins and adding 57 | # them to the application. 58 | include(flutter/generated_plugins.cmake) 59 | 60 | 61 | # === Installation === 62 | # Support files are copied into place next to the executable, so that it can 63 | # run in place. This is done instead of making a separate bundle (as on Linux) 64 | # so that building and running from within Visual Studio will work. 65 | set(BUILD_BUNDLE_DIR "$") 66 | # Make the "install" step default, as it's required to run. 67 | set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) 68 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) 69 | set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) 70 | endif() 71 | 72 | set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") 73 | set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") 74 | 75 | install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" 76 | COMPONENT Runtime) 77 | 78 | install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 79 | COMPONENT Runtime) 80 | 81 | install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 82 | COMPONENT Runtime) 83 | 84 | if(PLUGIN_BUNDLED_LIBRARIES) 85 | install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" 86 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 87 | COMPONENT Runtime) 88 | endif() 89 | 90 | # Fully re-copy the assets directory on each build to avoid having stale files 91 | # from a previous install. 92 | set(FLUTTER_ASSET_DIR_NAME "flutter_assets") 93 | install(CODE " 94 | file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") 95 | " COMPONENT Runtime) 96 | install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" 97 | DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) 98 | 99 | # Install the AOT library on non-Debug builds only. 100 | install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 101 | CONFIGURATIONS Profile;Release 102 | COMPONENT Runtime) 103 | -------------------------------------------------------------------------------- /example/lib/sections/stream.dart: -------------------------------------------------------------------------------- 1 | import 'dart:typed_data'; 2 | import 'package:example/widgets/chat_input_box.dart'; 3 | import 'package:example/widgets/item_image_view.dart'; 4 | import 'package:flutter/material.dart'; 5 | import 'package:flutter_gemini/flutter_gemini.dart'; 6 | import 'package:flutter_markdown/flutter_markdown.dart'; 7 | import 'package:image_picker/image_picker.dart'; 8 | import 'package:lottie/lottie.dart'; 9 | 10 | class SectionTextStreamInput extends StatefulWidget { 11 | const SectionTextStreamInput({super.key}); 12 | 13 | @override 14 | State createState() => _SectionTextInputStreamState(); 15 | } 16 | 17 | class _SectionTextInputStreamState extends State { 18 | final ImagePicker picker = ImagePicker(); 19 | final controller = TextEditingController(); 20 | final gemini = Gemini.instance; 21 | String? searchedText, 22 | // result, 23 | _finishReason; 24 | 25 | List? images; 26 | 27 | String? get finishReason => _finishReason; 28 | 29 | set finishReason(String? set) { 30 | if (set != _finishReason) { 31 | setState(() => _finishReason = set); 32 | } 33 | } 34 | 35 | @override 36 | Widget build(BuildContext context) { 37 | return Column( 38 | children: [ 39 | if (searchedText != null) 40 | MaterialButton( 41 | color: Colors.blue.shade700, 42 | onPressed: () { 43 | setState(() { 44 | searchedText = null; 45 | finishReason = null; 46 | // result = null; 47 | }); 48 | }, 49 | child: Text('search: $searchedText')), 50 | Expanded(child: GeminiResponseTypeView( 51 | builder: (context, child, response, loading) { 52 | if (loading) { 53 | return Lottie.asset('assets/lottie/ai.json'); 54 | } 55 | 56 | if (response != null) { 57 | return Markdown( 58 | data: response, 59 | selectable: true, 60 | ); 61 | } else { 62 | return const Center(child: Text('Search something!')); 63 | } 64 | }, 65 | )), 66 | 67 | /// if the returned finishReason isn't STOP 68 | if (finishReason != null) Text(finishReason!), 69 | 70 | if (images != null) 71 | Container( 72 | height: 120, 73 | padding: const EdgeInsets.symmetric(horizontal: 4), 74 | alignment: Alignment.centerLeft, 75 | child: Card( 76 | child: ListView.builder( 77 | itemBuilder: (context, index) => ItemImageView( 78 | bytes: images!.elementAt(index), 79 | ), 80 | itemCount: images!.length, 81 | scrollDirection: Axis.horizontal, 82 | ), 83 | ), 84 | ), 85 | 86 | /// imported from local widgets 87 | ChatInputBox( 88 | controller: controller, 89 | onClickCamera: () { 90 | picker.pickMultiImage().then((value) async { 91 | final imagesBytes = []; 92 | for (final file in value) { 93 | imagesBytes.add(await file.readAsBytes()); 94 | } 95 | 96 | if (imagesBytes.isNotEmpty) { 97 | setState(() { 98 | images = imagesBytes; 99 | }); 100 | } 101 | }); 102 | }, 103 | onSend: () { 104 | if (controller.text.isNotEmpty) { 105 | print('request'); 106 | 107 | searchedText = controller.text; 108 | controller.clear(); 109 | gemini 110 | .streamGenerateContent(searchedText!, 111 | images: images, 112 | modelName: 'models/gemini-1.5-flash-latest') 113 | .handleError((e) { 114 | if (e is GeminiException) { 115 | print(e); 116 | } 117 | }).listen((value) { 118 | setState(() { 119 | images = null; 120 | }); 121 | // result = (result ?? '') + (value.output ?? ''); 122 | 123 | if (value.finishReason != 'STOP') { 124 | finishReason = 'Finish reason is `${value.finishReason}`'; 125 | } 126 | }); 127 | } 128 | }, 129 | ) 130 | ], 131 | ); 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /lib/src/config/constants.dart: -------------------------------------------------------------------------------- 1 | import '../models/gemini_model/gemini_model.dart'; 2 | 3 | class Constants { 4 | Constants._(); 5 | static const String defaultModel = 'models/gemini-1.0-pro'; 6 | static const String defaultVersion = 'v1beta'; 7 | static const String defaultGenerateType = 'generateContent'; 8 | static const String baseUrl = 'https://generativelanguage.googleapis.com/'; 9 | 10 | static List get geminiDefaultModels => [ 11 | { 12 | "name": "models/chat-bison-001", 13 | "version": "001", 14 | "displayName": "Chat Bison", 15 | "description": "Chat-optimized generative language model.", 16 | "inputTokenLimit": 4096, 17 | "outputTokenLimit": 1024, 18 | "supportedGenerationMethods": [ 19 | "generateMessage", 20 | "countMessageTokens" 21 | ], 22 | "temperature": 0.25, 23 | "topP": 0.95, 24 | "topK": 40 25 | }, 26 | { 27 | "name": "models/text-bison-001", 28 | "version": "001", 29 | "displayName": "Text Bison", 30 | "description": "Model targeted for text generation.", 31 | "inputTokenLimit": 8196, 32 | "outputTokenLimit": 1024, 33 | "supportedGenerationMethods": [ 34 | "generateText", 35 | "countTextTokens", 36 | "createTunedTextModel" 37 | ], 38 | "temperature": 0.7, 39 | "topP": 0.95, 40 | "topK": 40 41 | }, 42 | { 43 | "name": "models/embedding-gecko-001", 44 | "version": "001", 45 | "displayName": "Embedding Gecko", 46 | "description": "Obtain a distributed representation of a text.", 47 | "inputTokenLimit": 1024, 48 | "outputTokenLimit": 1, 49 | "supportedGenerationMethods": ["embedText", "countTextTokens"] 50 | }, 51 | { 52 | "name": "models/embedding-gecko-002", 53 | "version": "002", 54 | "displayName": "Embedding Gecko 002", 55 | "description": "Obtain a distributed representation of a text.", 56 | "inputTokenLimit": 2048, 57 | "outputTokenLimit": 1, 58 | "supportedGenerationMethods": ["embedText", "countTextTokens"] 59 | }, 60 | { 61 | "name": "models/gemini-pro", 62 | "version": "001", 63 | "displayName": "Gemini Pro", 64 | "description": 65 | "The best model for scaling across a wide range of tasks", 66 | "inputTokenLimit": 30720, 67 | "outputTokenLimit": 2048, 68 | "supportedGenerationMethods": ["generateContent", "countTokens"], 69 | "temperature": 0.9, 70 | "topP": 1, 71 | "topK": 1 72 | }, 73 | { 74 | "name": "models/gemini-pro-vision", 75 | "version": "001", 76 | "displayName": "Gemini Pro Vision", 77 | "description": 78 | "The best image understanding model to handle a broad range of applications", 79 | "inputTokenLimit": 12288, 80 | "outputTokenLimit": 4096, 81 | "supportedGenerationMethods": ["generateContent", "countTokens"], 82 | "temperature": 0.4, 83 | "topP": 1, 84 | "topK": 32 85 | }, 86 | { 87 | "name": "models/gemini-ultra", 88 | "version": "001", 89 | "displayName": "Gemini Ultra", 90 | "description": "The most capable model for highly complex tasks", 91 | "inputTokenLimit": 30720, 92 | "outputTokenLimit": 2048, 93 | "supportedGenerationMethods": ["generateContent", "countTokens"], 94 | "temperature": 0.9, 95 | "topP": 1, 96 | "topK": 32 97 | }, 98 | { 99 | "name": "models/embedding-001", 100 | "version": "001", 101 | "displayName": "Embedding 001", 102 | "description": "Obtain a distributed representation of a text.", 103 | "inputTokenLimit": 2048, 104 | "outputTokenLimit": 1, 105 | "supportedGenerationMethods": ["embedContent", "countTextTokens"] 106 | }, 107 | { 108 | "name": "models/aqa", 109 | "version": "001", 110 | "displayName": "Model that performs Attributed Question Answering.", 111 | "description": 112 | "Model trained to return answers to questions that are grounded in provided sources, along with estimating answerable probability.", 113 | "inputTokenLimit": 7168, 114 | "outputTokenLimit": 1024, 115 | "supportedGenerationMethods": ["generateAnswer"], 116 | "temperature": 0.2, 117 | "topP": 1, 118 | "topK": 40 119 | } 120 | ].map((e) => GeminiModel.fromJson(e)).toList(); 121 | } 122 | -------------------------------------------------------------------------------- /lib/src/models/parts/parts.freezed.dart: -------------------------------------------------------------------------------- 1 | // coverage:ignore-file 2 | // GENERATED CODE - DO NOT MODIFY BY HAND 3 | // ignore_for_file: type=lint 4 | // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark 5 | 6 | part of 'parts.dart'; 7 | 8 | // ************************************************************************** 9 | // FreezedGenerator 10 | // ************************************************************************** 11 | 12 | T _$identity(T value) => value; 13 | 14 | final _privateConstructorUsedError = UnsupportedError( 15 | 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); 16 | 17 | Parts _$PartsFromJson(Map json) { 18 | return _Parts.fromJson(json); 19 | } 20 | 21 | /// @nodoc 22 | mixin _$Parts { 23 | @JsonKey(name: 'text') 24 | String? get text => throw _privateConstructorUsedError; 25 | @JsonKey(name: 'text') 26 | set text(String? value) => throw _privateConstructorUsedError; 27 | 28 | Map toJson() => throw _privateConstructorUsedError; 29 | @JsonKey(ignore: true) 30 | $PartsCopyWith get copyWith => throw _privateConstructorUsedError; 31 | } 32 | 33 | /// @nodoc 34 | abstract class $PartsCopyWith<$Res> { 35 | factory $PartsCopyWith(Parts value, $Res Function(Parts) then) = 36 | _$PartsCopyWithImpl<$Res, Parts>; 37 | @useResult 38 | $Res call({@JsonKey(name: 'text') String? text}); 39 | } 40 | 41 | /// @nodoc 42 | class _$PartsCopyWithImpl<$Res, $Val extends Parts> 43 | implements $PartsCopyWith<$Res> { 44 | _$PartsCopyWithImpl(this._value, this._then); 45 | 46 | // ignore: unused_field 47 | final $Val _value; 48 | // ignore: unused_field 49 | final $Res Function($Val) _then; 50 | 51 | @pragma('vm:prefer-inline') 52 | @override 53 | $Res call({ 54 | Object? text = freezed, 55 | }) { 56 | return _then(_value.copyWith( 57 | text: freezed == text 58 | ? _value.text 59 | : text // ignore: cast_nullable_to_non_nullable 60 | as String?, 61 | ) as $Val); 62 | } 63 | } 64 | 65 | /// @nodoc 66 | abstract class _$$PartsImplCopyWith<$Res> implements $PartsCopyWith<$Res> { 67 | factory _$$PartsImplCopyWith( 68 | _$PartsImpl value, $Res Function(_$PartsImpl) then) = 69 | __$$PartsImplCopyWithImpl<$Res>; 70 | @override 71 | @useResult 72 | $Res call({@JsonKey(name: 'text') String? text}); 73 | } 74 | 75 | /// @nodoc 76 | class __$$PartsImplCopyWithImpl<$Res> 77 | extends _$PartsCopyWithImpl<$Res, _$PartsImpl> 78 | implements _$$PartsImplCopyWith<$Res> { 79 | __$$PartsImplCopyWithImpl( 80 | _$PartsImpl _value, $Res Function(_$PartsImpl) _then) 81 | : super(_value, _then); 82 | 83 | @pragma('vm:prefer-inline') 84 | @override 85 | $Res call({ 86 | Object? text = freezed, 87 | }) { 88 | return _then(_$PartsImpl( 89 | text: freezed == text 90 | ? _value.text 91 | : text // ignore: cast_nullable_to_non_nullable 92 | as String?, 93 | )); 94 | } 95 | } 96 | 97 | /// @nodoc 98 | @JsonSerializable() 99 | class _$PartsImpl with DiagnosticableTreeMixin implements _Parts { 100 | _$PartsImpl({@JsonKey(name: 'text') this.text}); 101 | 102 | factory _$PartsImpl.fromJson(Map json) => 103 | _$$PartsImplFromJson(json); 104 | 105 | @override 106 | @JsonKey(name: 'text') 107 | String? text; 108 | 109 | @override 110 | String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { 111 | return 'Parts(text: $text)'; 112 | } 113 | 114 | @override 115 | void debugFillProperties(DiagnosticPropertiesBuilder properties) { 116 | super.debugFillProperties(properties); 117 | properties 118 | ..add(DiagnosticsProperty('type', 'Parts')) 119 | ..add(DiagnosticsProperty('text', text)); 120 | } 121 | 122 | @JsonKey(ignore: true) 123 | @override 124 | @pragma('vm:prefer-inline') 125 | _$$PartsImplCopyWith<_$PartsImpl> get copyWith => 126 | __$$PartsImplCopyWithImpl<_$PartsImpl>(this, _$identity); 127 | 128 | @override 129 | Map toJson() { 130 | return _$$PartsImplToJson( 131 | this, 132 | ); 133 | } 134 | } 135 | 136 | abstract class _Parts implements Parts { 137 | factory _Parts({@JsonKey(name: 'text') String? text}) = _$PartsImpl; 138 | 139 | factory _Parts.fromJson(Map json) = _$PartsImpl.fromJson; 140 | 141 | @override 142 | @JsonKey(name: 'text') 143 | String? get text; 144 | @JsonKey(name: 'text') 145 | set text(String? value); 146 | @override 147 | @JsonKey(ignore: true) 148 | _$$PartsImplCopyWith<_$PartsImpl> get copyWith => 149 | throw _privateConstructorUsedError; 150 | } 151 | -------------------------------------------------------------------------------- /example/linux/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Project-level configuration. 2 | cmake_minimum_required(VERSION 3.10) 3 | project(runner LANGUAGES CXX) 4 | 5 | # The name of the executable created for the application. Change this to change 6 | # the on-disk name of your application. 7 | set(BINARY_NAME "example") 8 | # The unique GTK application identifier for this application. See: 9 | # https://wiki.gnome.org/HowDoI/ChooseApplicationID 10 | set(APPLICATION_ID "com.example.example") 11 | 12 | # Explicitly opt in to modern CMake behaviors to avoid warnings with recent 13 | # versions of CMake. 14 | cmake_policy(SET CMP0063 NEW) 15 | 16 | # Load bundled libraries from the lib/ directory relative to the binary. 17 | set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") 18 | 19 | # Root filesystem for cross-building. 20 | if(FLUTTER_TARGET_PLATFORM_SYSROOT) 21 | set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) 22 | set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) 23 | set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) 24 | set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) 25 | set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) 26 | set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) 27 | endif() 28 | 29 | # Define build configuration options. 30 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) 31 | set(CMAKE_BUILD_TYPE "Debug" CACHE 32 | STRING "Flutter build mode" FORCE) 33 | set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS 34 | "Debug" "Profile" "Release") 35 | endif() 36 | 37 | # Compilation settings that should be applied to most targets. 38 | # 39 | # Be cautious about adding new options here, as plugins use this function by 40 | # default. In most cases, you should add new options to specific targets instead 41 | # of modifying this function. 42 | function(APPLY_STANDARD_SETTINGS TARGET) 43 | target_compile_features(${TARGET} PUBLIC cxx_std_14) 44 | target_compile_options(${TARGET} PRIVATE -Wall -Werror) 45 | target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") 46 | target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") 47 | endfunction() 48 | 49 | # Flutter library and tool build rules. 50 | set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") 51 | add_subdirectory(${FLUTTER_MANAGED_DIR}) 52 | 53 | # System-level dependencies. 54 | find_package(PkgConfig REQUIRED) 55 | pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) 56 | 57 | add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") 58 | 59 | # Define the application target. To change its name, change BINARY_NAME above, 60 | # not the value here, or `flutter run` will no longer work. 61 | # 62 | # Any new source files that you add to the application should be added here. 63 | add_executable(${BINARY_NAME} 64 | "main.cc" 65 | "my_application.cc" 66 | "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" 67 | ) 68 | 69 | # Apply the standard set of build settings. This can be removed for applications 70 | # that need different build settings. 71 | apply_standard_settings(${BINARY_NAME}) 72 | 73 | # Add dependency libraries. Add any application-specific dependencies here. 74 | target_link_libraries(${BINARY_NAME} PRIVATE flutter) 75 | target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) 76 | 77 | # Run the Flutter tool portions of the build. This must not be removed. 78 | add_dependencies(${BINARY_NAME} flutter_assemble) 79 | 80 | # Only the install-generated bundle's copy of the executable will launch 81 | # correctly, since the resources must in the right relative locations. To avoid 82 | # people trying to run the unbundled copy, put it in a subdirectory instead of 83 | # the default top-level location. 84 | set_target_properties(${BINARY_NAME} 85 | PROPERTIES 86 | RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" 87 | ) 88 | 89 | 90 | # Generated plugin build rules, which manage building the plugins and adding 91 | # them to the application. 92 | include(flutter/generated_plugins.cmake) 93 | 94 | 95 | # === Installation === 96 | # By default, "installing" just makes a relocatable bundle in the build 97 | # directory. 98 | set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") 99 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) 100 | set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) 101 | endif() 102 | 103 | # Start with a clean build bundle directory every time. 104 | install(CODE " 105 | file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") 106 | " COMPONENT Runtime) 107 | 108 | set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") 109 | set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") 110 | 111 | install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" 112 | COMPONENT Runtime) 113 | 114 | install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 115 | COMPONENT Runtime) 116 | 117 | install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 118 | COMPONENT Runtime) 119 | 120 | foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) 121 | install(FILES "${bundled_library}" 122 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 123 | COMPONENT Runtime) 124 | endforeach(bundled_library) 125 | 126 | # Fully re-copy the assets directory on each build to avoid having stale files 127 | # from a previous install. 128 | set(FLUTTER_ASSET_DIR_NAME "flutter_assets") 129 | install(CODE " 130 | file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") 131 | " COMPONENT Runtime) 132 | install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" 133 | DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) 134 | 135 | # Install the AOT library on non-Debug builds only. 136 | if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") 137 | install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 138 | COMPONENT Runtime) 139 | endif() 140 | -------------------------------------------------------------------------------- /lib/src/models/prompt_feedback/prompt_feedback.freezed.dart: -------------------------------------------------------------------------------- 1 | // coverage:ignore-file 2 | // GENERATED CODE - DO NOT MODIFY BY HAND 3 | // ignore_for_file: type=lint 4 | // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark 5 | 6 | part of 'prompt_feedback.dart'; 7 | 8 | // ************************************************************************** 9 | // FreezedGenerator 10 | // ************************************************************************** 11 | 12 | T _$identity(T value) => value; 13 | 14 | final _privateConstructorUsedError = UnsupportedError( 15 | 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); 16 | 17 | PromptFeedback _$PromptFeedbackFromJson(Map json) { 18 | return _PromptFeedback.fromJson(json); 19 | } 20 | 21 | /// @nodoc 22 | mixin _$PromptFeedback { 23 | @JsonKey(name: 'safetyRatings') 24 | List? get safetyRatings => throw _privateConstructorUsedError; 25 | @JsonKey(name: 'safetyRatings') 26 | set safetyRatings(List? value) => 27 | throw _privateConstructorUsedError; 28 | 29 | Map toJson() => throw _privateConstructorUsedError; 30 | @JsonKey(ignore: true) 31 | $PromptFeedbackCopyWith get copyWith => 32 | throw _privateConstructorUsedError; 33 | } 34 | 35 | /// @nodoc 36 | abstract class $PromptFeedbackCopyWith<$Res> { 37 | factory $PromptFeedbackCopyWith( 38 | PromptFeedback value, $Res Function(PromptFeedback) then) = 39 | _$PromptFeedbackCopyWithImpl<$Res, PromptFeedback>; 40 | @useResult 41 | $Res call( 42 | {@JsonKey(name: 'safetyRatings') List? safetyRatings}); 43 | } 44 | 45 | /// @nodoc 46 | class _$PromptFeedbackCopyWithImpl<$Res, $Val extends PromptFeedback> 47 | implements $PromptFeedbackCopyWith<$Res> { 48 | _$PromptFeedbackCopyWithImpl(this._value, this._then); 49 | 50 | // ignore: unused_field 51 | final $Val _value; 52 | // ignore: unused_field 53 | final $Res Function($Val) _then; 54 | 55 | @pragma('vm:prefer-inline') 56 | @override 57 | $Res call({ 58 | Object? safetyRatings = freezed, 59 | }) { 60 | return _then(_value.copyWith( 61 | safetyRatings: freezed == safetyRatings 62 | ? _value.safetyRatings 63 | : safetyRatings // ignore: cast_nullable_to_non_nullable 64 | as List?, 65 | ) as $Val); 66 | } 67 | } 68 | 69 | /// @nodoc 70 | abstract class _$$PromptFeedbackImplCopyWith<$Res> 71 | implements $PromptFeedbackCopyWith<$Res> { 72 | factory _$$PromptFeedbackImplCopyWith(_$PromptFeedbackImpl value, 73 | $Res Function(_$PromptFeedbackImpl) then) = 74 | __$$PromptFeedbackImplCopyWithImpl<$Res>; 75 | @override 76 | @useResult 77 | $Res call( 78 | {@JsonKey(name: 'safetyRatings') List? safetyRatings}); 79 | } 80 | 81 | /// @nodoc 82 | class __$$PromptFeedbackImplCopyWithImpl<$Res> 83 | extends _$PromptFeedbackCopyWithImpl<$Res, _$PromptFeedbackImpl> 84 | implements _$$PromptFeedbackImplCopyWith<$Res> { 85 | __$$PromptFeedbackImplCopyWithImpl( 86 | _$PromptFeedbackImpl _value, $Res Function(_$PromptFeedbackImpl) _then) 87 | : super(_value, _then); 88 | 89 | @pragma('vm:prefer-inline') 90 | @override 91 | $Res call({ 92 | Object? safetyRatings = freezed, 93 | }) { 94 | return _then(_$PromptFeedbackImpl( 95 | safetyRatings: freezed == safetyRatings 96 | ? _value.safetyRatings 97 | : safetyRatings // ignore: cast_nullable_to_non_nullable 98 | as List?, 99 | )); 100 | } 101 | } 102 | 103 | /// @nodoc 104 | @JsonSerializable() 105 | class _$PromptFeedbackImpl 106 | with DiagnosticableTreeMixin 107 | implements _PromptFeedback { 108 | _$PromptFeedbackImpl({@JsonKey(name: 'safetyRatings') this.safetyRatings}); 109 | 110 | factory _$PromptFeedbackImpl.fromJson(Map json) => 111 | _$$PromptFeedbackImplFromJson(json); 112 | 113 | @override 114 | @JsonKey(name: 'safetyRatings') 115 | List? safetyRatings; 116 | 117 | @override 118 | String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { 119 | return 'PromptFeedback(safetyRatings: $safetyRatings)'; 120 | } 121 | 122 | @override 123 | void debugFillProperties(DiagnosticPropertiesBuilder properties) { 124 | super.debugFillProperties(properties); 125 | properties 126 | ..add(DiagnosticsProperty('type', 'PromptFeedback')) 127 | ..add(DiagnosticsProperty('safetyRatings', safetyRatings)); 128 | } 129 | 130 | @JsonKey(ignore: true) 131 | @override 132 | @pragma('vm:prefer-inline') 133 | _$$PromptFeedbackImplCopyWith<_$PromptFeedbackImpl> get copyWith => 134 | __$$PromptFeedbackImplCopyWithImpl<_$PromptFeedbackImpl>( 135 | this, _$identity); 136 | 137 | @override 138 | Map toJson() { 139 | return _$$PromptFeedbackImplToJson( 140 | this, 141 | ); 142 | } 143 | } 144 | 145 | abstract class _PromptFeedback implements PromptFeedback { 146 | factory _PromptFeedback( 147 | {@JsonKey(name: 'safetyRatings') 148 | List? safetyRatings}) = _$PromptFeedbackImpl; 149 | 150 | factory _PromptFeedback.fromJson(Map json) = 151 | _$PromptFeedbackImpl.fromJson; 152 | 153 | @override 154 | @JsonKey(name: 'safetyRatings') 155 | List? get safetyRatings; 156 | @JsonKey(name: 'safetyRatings') 157 | set safetyRatings(List? value); 158 | @override 159 | @JsonKey(ignore: true) 160 | _$$PromptFeedbackImplCopyWith<_$PromptFeedbackImpl> get copyWith => 161 | throw _privateConstructorUsedError; 162 | } 163 | --------------------------------------------------------------------------------