Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Flutter sample #8

Merged
merged 18 commits into from
Jan 26, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,11 @@ documentation: https://ai.google.dev/docs

## Packages

| Package | Description | Version |
| --- | --- | --- |
| Package | Description | Version |
|----------------------------------------------------| --- | --- |
johnpryan marked this conversation as resolved.
Show resolved Hide resolved
| [google_generative_ai](pkgs/google_generative_ai/) | The Google Generative AI SDK for Dart - allows access to state-of-the-art LLMs. | |
| [samples](samples/) | Dart samples for `package:google_generative_ai`. | |
| [samples/dart](samples/dart/) | Dart samples for `package:google_generative_ai`. | |
| [samples/flutter](samples/flutter/) | Flutter sample for `package:google_generative_ai`. | |

## Contributing

Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion samples/pubspec.yaml → samples/dart/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ environment:
dependencies:
path: ^1.9.0
google_generative_ai:
path: ../pkgs/google_generative_ai
path: ../../pkgs/google_generative_ai

dev_dependencies:
lints: ^3.0.0
File renamed without changes
File renamed without changes
55 changes: 55 additions & 0 deletions samples/flutter_app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# env.json contains the API key for this sample app.
env.json

# Ignore platform-specific directories, since the user will run
# `flutter create` as described in the README
android/
web/
ios/
macos/
linux/
windows/

# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/

# IntelliJ related
*.iml
*.ipr
*.iws
.idea/

# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/

# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.pub-cache/
.pub/
/build/

# Symbolication related
app.*.symbols

# Obfuscation related
app.*.map.json

# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release
45 changes: 45 additions & 0 deletions samples/flutter_app/.metadata
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.

version:
revision: "787a51fa08ee6872245bb809c5d2ee57408d0370"
channel: "main"

project_type: app

# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 787a51fa08ee6872245bb809c5d2ee57408d0370
base_revision: 787a51fa08ee6872245bb809c5d2ee57408d0370
- platform: android
create_revision: 787a51fa08ee6872245bb809c5d2ee57408d0370
base_revision: 787a51fa08ee6872245bb809c5d2ee57408d0370
- platform: ios
create_revision: 787a51fa08ee6872245bb809c5d2ee57408d0370
base_revision: 787a51fa08ee6872245bb809c5d2ee57408d0370
- platform: linux
create_revision: 787a51fa08ee6872245bb809c5d2ee57408d0370
base_revision: 787a51fa08ee6872245bb809c5d2ee57408d0370
- platform: macos
create_revision: 787a51fa08ee6872245bb809c5d2ee57408d0370
base_revision: 787a51fa08ee6872245bb809c5d2ee57408d0370
- platform: web
create_revision: 787a51fa08ee6872245bb809c5d2ee57408d0370
base_revision: 787a51fa08ee6872245bb809c5d2ee57408d0370
- platform: windows
create_revision: 787a51fa08ee6872245bb809c5d2ee57408d0370
base_revision: 787a51fa08ee6872245bb809c5d2ee57408d0370

# User provided section

# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
25 changes: 25 additions & 0 deletions samples/flutter_app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Flutter generative AI sample

A Flutter chat application that uses the `google_generative_ai` package.

## Getting started
Create the project files for each target platform by using the `flutter create`
johnpryan marked this conversation as resolved.
Show resolved Hide resolved
command in this project's directory.

```bash
flutter create .
```

Create a new file, `env.json` to store your API key:

```json
{
"api_key": "<YOUR_API_KEY_HERE>"
}
```

Specify the `env.json` file when you run the app:

```bash
flutter run -d android --dart-define-from-file=env.json
```
3 changes: 3 additions & 0 deletions samples/flutter_app/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
include: package:flutter_lints/flutter.yaml
linter:
rules:
219 changes: 219 additions & 0 deletions samples/flutter_app/lib/main.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import 'package:flutter/material.dart';
import 'package:google_generative_ai/google_generative_ai.dart' hide Text;
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI @natebosch we might want to consider hiding the Text class or renaming it, it conflicts with the Text widget from the Flutter SDK.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#11


void main() {
runApp(const GenerativeAISample());
}

class GenerativeAISample extends StatelessWidget {
const GenerativeAISample({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter + Generative AI',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const ChatScreen(title: 'Flutter + Generative AI'),
);
}
}

class ChatScreen extends StatefulWidget {
const ChatScreen({super.key, required this.title});

final String title;

@override
State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: const ChatWidget(),
);
}
}

class ChatWidget extends StatefulWidget {
const ChatWidget({super.key});

@override
State<ChatWidget> createState() => _ChatWidgetState();
}

class _ChatWidgetState extends State<ChatWidget> {
late final GenerativeModel _model;
late final ChatSession _chat;
late final _textController = TextEditingController();
final List<Message> _messages = [];
bool _loading = false;

@override
void initState() {
super.initState();
_model = GenerativeModel(model: 'gemini-pro', apiKey: const String.fromEnvironment('api_key'));
_chat = _model.startChat();
}

@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: ListView.builder(
itemBuilder: (context, idx) {
var message = _messages[idx];
return MessageWidget(message: message);
},
itemCount: _messages.length,
),
),
Row(
children: [
Expanded(
child: TextField(
decoration:
const InputDecoration(hintText: 'Enter a prompt...'),
controller: _textController,
onSubmitted: (String value) {
_sendChatMessage(value);
},
),
),
if (!_loading)
IconButton(
onPressed: () async {
_sendChatMessage(_textController.text);
},
icon: const Icon(Icons.send),
)
else
const CircularProgressIndicator(),
],
),
],
),
);
}

Future<void> _sendChatMessage(String message) async {
setState(() {
_messages.add(Message(message, isFromUser: true));
_loading = true;
});

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

if (text == null) {
_showError('No response from API.');
return;
} else {
setState(() {
_messages.add(Message(text));
_loading = false;
});
}
} catch (e) {
_showError(e.toString());
setState(() {
_loading = false;
});
} finally {
_textController.clear();
setState(() {
_loading = false;
});
}
}

void _showError(String message) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Something went wrong'),
content: SingleChildScrollView(
child: Text(message),
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('OK'),
)
],
);
},
);
}
}

class Message {
final bool isFromUser;
final String text;
Message(this.text, {this.isFromUser = false});
}

class MessageWidget extends StatelessWidget {
final Message message;

const MessageWidget({
super.key,
required this.message,
});

@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment:
message.isFromUser ? MainAxisAlignment.end : MainAxisAlignment.start,
children: [
Flexible(
child: Container(
constraints: const BoxConstraints(maxWidth: 600),
decoration: BoxDecoration(
color: message.isFromUser
? Theme.of(context).colorScheme.primaryContainer
: Theme.of(context).colorScheme.surfaceVariant,
borderRadius: BorderRadius.circular(8.0),
),
padding: const EdgeInsets.all(8.0),
margin: const EdgeInsets.only(bottom: 8),
child: SelectionArea(
child: Text(message.text),
),
),
),
],
);
}
}
18 changes: 18 additions & 0 deletions samples/flutter_app/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
name: generative_ai_flutter
description: "Sample app for the google_generative_ai package"
publish_to: 'none'
version: 1.0.0
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.6
google_generative_ai:
path: ../../pkgs/google_generative_ai
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.0
flutter:
uses-material-design: true
Loading