### Custom Welcome Message Example Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/ChatViewModel.md Example of creating a custom welcome message dynamically and passing it to LlmChatView. ```dart class ChatPage extends StatefulWidget { @override State createState() => _ChatPageState(); } class _ChatPageState extends State { late String welcomeMessage; @override void initState() { super.initState(); final userName = 'Alice'; welcomeMessage = 'Hello $userName! Welcome to the AI Chat Assistant.'; } @override Widget build(BuildContext context) { return LlmChatView( provider: FirebaseProvider(model: model), welcomeMessage: welcomeMessage, suggestions: [ 'What is my account status?', 'Help with my order', 'Chat with support', ], responseBuilder: (context, response) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SelectableText(response), SizedBox(height: 8), ActionChip( label: const Text('Copy'), onPressed: () { Clipboard.setData(ClipboardData(text: response)); }, ), ], ); }, ); } } ``` -------------------------------- ### Complete LlmChatView Configuration Example Source: https://github.com/flutter/ai/blob/main/_autodocs/configuration.md This example demonstrates a full configuration of the LlmChatView widget, including custom styling, strings, suggestions, and error handling. It shows how to integrate with Firebase for AI model interaction. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final customStyle = LlmChatViewStyle( backgroundColor: Color(0xFFF5F5F5), messageSpacing: 12.0, userMessageStyle: UserMessageStyle( textStyle: TextStyle(fontSize: 16, color: Colors.black87), decoration: BoxDecoration( color: Color(0xFFE3F2FD), borderRadius: BorderRadius.circular(16), ), ), llmMessageStyle: LlmMessageStyle( decoration: BoxDecoration( color: Color(0xFFEEEEEE), borderRadius: BorderRadius.circular(16), ), padding: EdgeInsets.all(12), ), chatInputStyle: ChatInputStyle( hintText: 'Ask me anything...', decoration: BoxDecoration( border: Border.all(color: Color(0xFFCCCCCC)), borderRadius: BorderRadius.circular(24), ), ), ); final customStrings = LlmChatViewStrings( send: 'Send', typeAMessage: 'Your message here...', // ... other strings ); return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('AI Chat')), body: LlmChatView( provider: FirebaseProvider( model: FirebaseAI.vertexAI().generativeModel( model: 'gemini-2.0-flash', ), chatGenerationConfig: GenerationConfig(temperature: 0.7), ), style: customStyle, strings: customStrings, suggestions: ['Hello', 'Help me with something'], welcomeMessage: 'Welcome to AI Chat!', enableAttachments: true, enableVoiceNotes: true, onErrorCallback: (context, error) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Error: ${error.message}')), ); }, ), ), ); } } ``` -------------------------------- ### Suggestions Example Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/ChatViewModel.md Provides predefined suggestions to guide users when the chat is empty. This enhances user experience by offering quick-start prompts. ```dart suggestions: [ 'What is Flutter?', 'How do I use widgets?', 'Tell me a joke', ] ``` -------------------------------- ### Default ActionButtonStyle Examples Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/ActionButtonStyle.md Examples demonstrating how to create default styles for submit and record button types. ```dart final sendStyle = ActionButtonStyle.defaultStyle( ActionButtonType.submit, strings: customStrings, ); final recordStyle = ActionButtonStyle.defaultStyle( ActionButtonType.record, ); ``` -------------------------------- ### Simple LlmChatView Initialization Source: https://github.com/flutter/ai/blob/main/_autodocs/README.md Basic setup for the LlmChatView widget with a required FirebaseProvider. ```dart return Scaffold( body: LlmChatView( provider: FirebaseProvider(model: model), ), ); ``` -------------------------------- ### Flutter App Setup with FirebaseProvider Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/FirebaseProvider.md Initialize Firebase and set up FirebaseProvider within a Flutter application. This example demonstrates integrating FirebaseAI with LlmChatView for a chat interface. ```dart import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_ai/firebase_ai.dart'; import 'package:flutter_ai_toolkit/flutter_ai_toolkit.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(const MyApp()); } class ChatPage extends StatelessWidget { @override Widget build(BuildContext context) { final provider = FirebaseProvider( model: FirebaseAI.vertexAI().generativeModel( model: 'gemini-2.0-flash', ), ); return Scaffold( appBar: AppBar(title: const Text('Firebase AI Chat')), body: LlmChatView( provider: provider, suggestions: ['Hello', 'How are you?'], enableAttachments: true, ), ); } } ``` -------------------------------- ### Example of copyWith() Usage Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmChatViewStyle.md Demonstrates how to create a new LlmChatViewStyle by copying an existing one and overriding specific properties. ```dart final baseStyle = LlmChatViewStyle.defaultStyle(); final customStyle = baseStyle.copyWith( backgroundColor: Colors.black, messageSpacing: 16.0, padding: const EdgeInsets.all(16), ); ``` -------------------------------- ### Welcome Message Example Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/ChatViewModel.md An optional welcome message to greet users when they first open the chat interface. It can be customized to provide initial guidance. ```dart welcomeMessage: 'Welcome to the AI Assistant! How can I help you today?' ``` -------------------------------- ### LinkAttachment Creation Example Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/Attachment.md Demonstrates how to create LinkAttachment instances, showing both inferred and explicitly set MIME types. ```dart final link = LinkAttachment( name: 'Flutter Documentation', url: Uri.parse('https://flutter.dev/docs'), ); // MIME type inferred as 'text/html' final pdfLink = LinkAttachment( name: 'Flutter Guide', url: Uri.parse('https://example.com/guide.pdf'), mimeType: 'application/pdf', // Explicitly set ); ``` -------------------------------- ### Dart Code Block Example Source: https://github.com/flutter/ai/blob/main/_autodocs/MANIFEST.md Illustrates the standard Markdown formatting for Dart code examples within the documentation. ```dart // Dart code example ``` -------------------------------- ### Resolve ActionButtonStyle Example Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/ActionButtonStyle.md Example showing how to resolve a style, overriding the icon color of a default stop button. ```dart final resolved = ActionButtonStyle.resolve( ActionButtonStyle(iconColor: Colors.red), defaultStyle: ActionButtonStyle.defaultStyle(ActionButtonType.stop), ); // Result: Stop button style with custom red color ``` -------------------------------- ### Full ChatMessage Usage Example Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/ChatMessage.md Demonstrates creating a conversation, handling user messages, simulating LLM streaming responses, and serializing/deserializing the conversation. ```dart import 'package:flutter_ai_toolkit/flutter_ai_toolkit.dart'; void main() async { // Create a simple conversation List history = []; // User sends message history.add(ChatMessage.user('What is Flutter?', [])); // LLM responds with streaming final response = ChatMessage.llm(); history.add(response); // Simulate streaming response final stream = provider.generateStream('What is Flutter?'); await for (final chunk in stream) { response.append(chunk); print('Current response: ${response.text}'); } // Serialize conversation final savedConversation = history.map((m) => m.toJson()).toList(); await storage.saveMessages(savedConversation); // Restore conversation final loaded = (await storage.loadMessages()) .map(ChatMessage.fromJson) .toList(); provider.history = loaded; } ``` -------------------------------- ### generateStream Example Usage Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmProvider.md Demonstrates how to call generateStream and handle the resulting text stream, including error and completion callbacks. ```dart final stream = provider.generateStream( 'Translate this image to text', attachments: [imageAttachment], ); stream.listen( (chunk) => print('Received: $chunk'), onError: (error) => print('Error: $error'), onDone: () => print('Complete'), ); ``` -------------------------------- ### Dark Theme Customization Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmChatViewStyle.md Provides an example of how to create a dark theme for the `LlmChatView` by setting appropriate background and message colors. ```APIDOC ## Dark Theme Customization ### Description Applies a dark theme to the `LlmChatView` by adjusting background and message container colors. ### Parameters - **backgroundColor** (Color) - The dark background color for the chat view. - **userMessageStyle.decoration.color** (Color) - The dark background color for user message bubbles. - **llmMessageStyle.decoration.color** (Color) - The dark background color for LLM message bubbles. ### Example ```dart final darkStyle = LlmChatViewStyle( backgroundColor: Color(0xFF121212), userMessageStyle: UserMessageStyle( decoration: BoxDecoration(color: Color(0xFF1E1E1E), borderRadius: BorderRadius.circular(12)), ), llmMessageStyle: LlmMessageStyle( decoration: BoxDecoration(color: Color(0xFF2C2C2C), borderRadius: BorderRadius.circular(12)), ), ); ``` ``` -------------------------------- ### Basic LlmChatView Configuration Source: https://github.com/flutter/ai/blob/main/_autodocs/README.md Configure the LlmChatView with a basic FirebaseProvider. This is the minimal setup required to display a chat interface. ```dart LlmChatView( provider: FirebaseProvider(model: model), ) ``` -------------------------------- ### Custom Styled Chat Buttons Example Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/ActionButtonStyle.md Demonstrates how to customize individual action button styles within the LlmChatView. ```dart import 'package:flutter/material.dart'; import 'package:flutter_ai_toolkit/flutter_ai_toolkit.dart'; class CustomStyledChat extends StatelessWidget { @override Widget build(BuildContext context) { final customStyle = LlmChatViewStyle( // Customize individual button styles submitButtonStyle: ActionButtonStyle( icon: Icons.send, iconColor: Colors.blue, iconDecoration: BoxDecoration( color: Colors.blue.shade50, shape: BoxShape.circle, boxShadow: [ BoxShadow( color: Colors.blue.withOpacity(0.3), blurRadius: 8, ), ], ), text: 'Send Message', textStyle: TextStyle( fontSize: 12, color: Colors.blue, fontWeight: FontWeight.w500, ), ), recordButtonStyle: ActionButtonStyle( icon: Icons.mic, iconColor: Colors.red, text: 'Record', ), stopButtonStyle: ActionButtonStyle( icon: Icons.stop_circle, iconColor: Colors.red, iconDecoration: BoxDecoration( color: Colors.red.shade50, shape: BoxShape.circle, ), ), attachFileButtonStyle: ActionButtonStyle( icon: Icons.attach_file, iconColor: Colors.green, text: 'Attach', ), ); return Scaffold( appBar: AppBar(title: const Text('Custom Buttons')), body: LlmChatView( provider: myProvider, style: customStyle, ), ); } } ``` -------------------------------- ### Usage Example: Creating and Sending Attachments Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/Attachment.md Shows how to create various attachment types (image, file, link) and send them in a chat message using the provider. ```dart import 'package:flutter_ai_toolkit/flutter_ai_toolkit.dart'; import 'package:image_picker/image_picker.dart'; import 'package:file_selector/file_selector.dart'; Future attachmentExample() async { final ImagePicker picker = ImagePicker(); final attachments = []; // Attach an image final image = await picker.pickImage(source: ImageSource.gallery); if (image != null) { final imageAttachment = await ImageFileAttachment.fromFile(image); attachments.add(imageAttachment); } // Attach a PDF file const xFileFilter = XTypeGroup( label: 'PDFs', extensions: ['pdf'], ); final file = await openFile(acceptedTypeGroups: [xFileFilter]); if (file != null) { final fileAttachment = await FileAttachment.fromFile(file); attachments.add(fileAttachment); } // Attach a link attachments.add(LinkAttachment( name: 'Reference', url: Uri.parse('https://api.example.com/docs'), )); // Send message with attachments await provider.sendMessageStream( 'Please analyze these files', attachments: attachments, ).forEach(print); ``` -------------------------------- ### Basic LlmChatView Usage Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmChatView.md This snippet shows the basic setup for LlmChatView, including Firebase initialization and configuration with a generative model. It demonstrates how to set up the chat interface with suggestions, a welcome message, and attachment/voice note capabilities. ```dart import 'package:flutter/material.dart'; import 'package:firebase_ai/firebase_ai.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter_ai_toolkit/flutter_ai_toolkit.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: ChatPage(), ); } } class ChatPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('AI Chat')), body: LlmChatView( provider: FirebaseProvider( model: FirebaseAI.vertexAI().generativeModel( model: 'gemini-2.0-flash', ), ), style: LlmChatViewStyle( backgroundColor: Colors.white, ), suggestions: [ 'What is Flutter?', 'How do I use Firebase?', 'Tell me a joke', ], welcomeMessage: 'Welcome! Ask me anything.', enableAttachments: true, enableVoiceNotes: true, ), ); } } ``` -------------------------------- ### Example of Resolving LlmChatViewStyle Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmChatViewStyle.md Demonstrates how to create a custom style by overriding specific properties and falling back to default styles for others. ```dart final resolved = LlmChatViewStyle.resolve( LlmChatViewStyle(backgroundColor: Colors.white), defaultStyle: LlmChatViewStyle.defaultStyle(), ); // Result: Custom background with default styling for all other properties ``` -------------------------------- ### Basic LlmChatView Styling Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmChatViewStyle.md Provides a comprehensive example of styling LlmChatView with custom colors, message styles, input styles, and spacing. ```dart import 'package:flutter/material.dart'; import 'package:flutter_ai_toolkit/flutter_ai_toolkit.dart'; class ChatPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Custom Styled Chat')), body: LlmChatView( provider: myProvider, style: LlmChatViewStyle( // Background backgroundColor: Color(0xFFF5F5F5), menuColor: Colors.white, progressIndicatorColor: Colors.blue, // Message styling userMessageStyle: UserMessageStyle( textStyle: TextStyle(fontSize: 16), decoration: BoxDecoration( color: Colors.blue.shade100, borderRadius: BorderRadius.circular(12), ), ), llmMessageStyle: LlmMessageStyle( textStyle: TextStyle(fontSize: 16), decoration: BoxDecoration( color: Colors.grey.shade200, borderRadius: BorderRadius.circular(12), ), ), // Input styling chatInputStyle: ChatInputStyle( hintText: 'Type your message...', backgroundColor: Colors.white, decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(8), ), ), // Spacing messageSpacing: 12.0, padding: EdgeInsets.all(16), margin: EdgeInsets.symmetric(vertical: 8), // Suggestions suggestionStyle: SuggestionStyle( textStyle: TextStyle(fontSize: 14), decoration: BoxDecoration( color: Colors.blue.shade50, borderRadius: BorderRadius.circular(20), border: Border.all(color: Colors.blue), ), ), ), ), ); } } ``` -------------------------------- ### MessageOrigin Getters Example Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/MessageOrigin.md Demonstrates how to use the `isUser` and `isLlm` getters to check the origin of a message. ```dart final origin = MessageOrigin.user; print(origin.isUser); // true print(origin.isLlm); // false ``` -------------------------------- ### sendMessageStream Example Usage Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmProvider.md Shows how to use sendMessageStream to get a response based on the current conversation and verifies that the history is updated. ```dart final stream = provider.sendMessageStream('What was I asking before?'); await stream.forEach((chunk) { print('Streaming: $chunk'); }); // History now contains the user message and full LLM response print('Chat history: ${provider.history}'); ``` -------------------------------- ### EchoProvider Usage Example Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/EchoProvider.md Demonstrates how to use EchoProvider to generate streams of messages, both with and without file attachments. This is useful for testing chat interfaces and message handling. ```dart import 'package:flutter_ai_toolkit/flutter_ai_toolkit.dart'; import 'dart:io'; import 'dart:typed_data'; void testEchoProvider() { final provider = EchoProvider(); // Test simple echo final stream = provider.generateStream('Test message'); stream.listen(print); // Test with attachments final file = FileAttachment( name: 'document.txt', mimeType: 'text/plain', bytes: Uint8List.fromList([1, 2, 3]), ); final attachmentStream = provider.generateStream( 'Document contents', [file], ); attachmentStream.listen(print); } void testWithLlmChatView() { // Use EchoProvider for testing UI without Firebase return Scaffold( body: LlmChatView( provider: EchoProvider(), suggestions: ['Hello', 'Test'], ), ); } ``` -------------------------------- ### LlmChatView with Suggestions Source: https://github.com/flutter/ai/blob/main/_autodocs/README.md Configure the LlmChatView to display suggestion chips to the user. These suggestions can guide the user's interaction with the AI. ```dart LlmChatView( provider: provider, suggestions: ['What is Flutter?', 'How do I build widgets?'], ) ``` -------------------------------- ### Response Builder Example Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/ChatViewModel.md Implement a custom ResponseBuilder to control how LLM responses are rendered. This allows for advanced formatting like syntax highlighting or markdown. ```dart responseBuilder: (context, response) { return SelectableText( response, style: Theme.of(context).textTheme.bodyMedium, ); } ``` -------------------------------- ### Building a Message Display with Alignment and Styling Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/MessageOrigin.md An example of a `StatelessWidget` that displays a list of messages, aligning them to the right for user messages and left for LLM messages, and applying different bubble colors. ```dart class ConversationView extends StatelessWidget { final LlmProvider provider; @override Widget build(BuildContext context) { return ListView.builder( itemCount: provider.history.length, itemBuilder: (context, index) { final message = provider.history.elementAt(index); return Container( alignment: message.origin.isUser ? Alignment.centerRight : Alignment.centerLeft, padding: EdgeInsets.all(8), child: Bubble( color: message.origin.isUser ? Colors.blue : Colors.grey, child: Text(message.text ?? ''), ), ); }, ); } } ``` -------------------------------- ### Spanish Localization Example Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmChatViewStrings.md Provides a Spanish localization for LlmChatViewStrings. Use this when the application's locale is Spanish. ```dart const spanishStrings = LlmChatViewStrings( addAttachment: 'Agregar archivo', attachFile: 'Adjuntar archivo', takePhoto: 'Tomar foto', stop: 'Parar', close: 'Cerrar', cancel: 'Cancelar', copyToClipboard: 'Copiar al portapapeles', editMessage: 'Editar mensaje', attachImage: 'Adjuntar imagen', recordAudio: 'Grabar audio', submitMessage: 'Enviar mensaje', closeMenu: 'Cerrar menú', unableToRecordAudio: 'No se puede grabar audio', unsupportedImageSource: 'Fuente de imagen no compatible', unableToPickImage: 'No se puede seleccionar imagen', unableToPickFile: 'No se puede seleccionar archivo', unableToPickUrl: 'No se puede seleccionar URL', messageCopiedToClipboard: 'Mensaje copiado al portapapeles', editing: 'Editando', error: 'Error', cancelMessage: 'Cancelar', submit: 'Enviar', send: 'Enviar', typeAMessage: 'Escribe un mensaje...', recording: 'Grabando', tapToStop: 'Toca para parar', tapToRecord: 'Toca para grabar', releaseToCancel: 'Suelta para cancelar', ); LlmChatView( provider: myProvider, strings: spanishStrings, ) ``` -------------------------------- ### ChatMessage.llm Factory Constructor and Streaming Example Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/ChatMessage.md Creates an LLM-originated message with an empty initial state, suitable for streaming responses. Use the `append()` method to add text as it arrives. ```dart factory ChatMessage.llm() ``` ```dart final response = ChatMessage.llm(); provider.history.add(response); // As response streams in: stream.listen((chunk) { response.append(chunk); }); ``` -------------------------------- ### Custom LLM Message Styling Example Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmMessageStyle.md Demonstrates how to apply custom styling to LLM messages within a LlmChatView, including icon, decoration, and markdown options. ```dart import 'package:flutter/material.dart'; import 'package:flutter_markdown_plus/flutter_markdown_plus.dart'; import 'package:flutter_ai_toolkit/flutter_ai_toolkit.dart'; class CustomChatView extends StatelessWidget { @override Widget build(BuildContext context) { return LlmChatView( provider: myProvider, style: LlmChatViewStyle( llmMessageStyle: LlmMessageStyle( icon: Icons.smart_toy, iconColor: Colors.deepPurple, iconDecoration: BoxDecoration( color: Colors.deepPurple.shade50, shape: BoxShape.circle, ), decoration: BoxDecoration( color: Colors.grey.shade100, borderRadius: BorderRadius.only( topLeft: Radius.circular(4), topRight: Radius.circular(20), bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20), ), border: Border.all( color: Colors.grey.shade300, width: 1, ), ), markdownStyle: MarkdownStyleData( p: TextStyle(fontSize: 16, height: 1.5), code: TextStyle( backgroundColor: Colors.grey.shade200, fontFamily: 'monospace', ), ), maxWidth: 500, minWidth: 200, flex: 8, padding: EdgeInsets.all(16), margin: EdgeInsets.symmetric(vertical: 8, horizontal: 4), ), ), ); } } ``` -------------------------------- ### Default LlmChatViewStrings Instance Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmChatViewStrings.md Provides a static default instance of LlmChatViewStrings with standard English strings. Useful for quick setup. ```dart static const LlmChatViewStrings defaults = LlmChatViewStrings() ``` ```dart final defaultStrings = LlmChatViewStrings.defaults; print(defaultStrings.send); // 'Send' ``` -------------------------------- ### Example Usage of Custom LlmChatViewStrings Source: https://github.com/flutter/ai/blob/main/_autodocs/types.md Provide custom string values when creating an instance of LlmChatViewStrings to override default labels. This custom instance can then be passed to LlmChatView. ```dart final customStrings = LlmChatViewStrings( addAttachment: 'Ajouter une pièce jointe', typeAMessage: 'Tapez votre message...', ); LlmChatView( provider: provider, strings: customStrings, ) ``` -------------------------------- ### Message Sender Example Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/ChatViewModel.md Use a custom messageSender to augment prompts or add logging before sending messages to the LLM. This overrides the default provider's sendMessageStream method. ```dart messageSender: (prompt, {required attachments}) { final augmented = 'You are a helpful assistant.\n\nUser: $prompt'; return provider.sendMessageStream(augmented, attachments: attachments); } ``` -------------------------------- ### Get Chat History Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmProvider.md Example of how to retrieve and iterate through the current chat history. ```dart for (final message in provider.history) { print('${message.origin}: ${message.text}'); } ``` -------------------------------- ### LlmChatView with Welcome Message and Suggestions Source: https://github.com/flutter/ai/blob/main/_autodocs/README.md Configure a welcome message and initial user suggestions for the LlmChatView. ```dart return Scaffold( body: LlmChatView( provider: provider, welcomeMessage: 'Welcome to AI Assistant!', suggestions: ['Hello', 'What can you do?'], ), ); ``` -------------------------------- ### Add Dependencies to pubspec.yaml Source: https://github.com/flutter/ai/blob/main/README.md Install the required packages for Firebase AI integration in your Flutter project. ```sh $ flutter pub add flutter_ai_toolkit firebase_ai firebase_core ``` -------------------------------- ### LlmChatViewStyle Constructor Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmChatViewStyle.md Demonstrates how to create a fully customized `LlmChatViewStyle` by providing values for various styling properties, including message appearance, input field, and spacing. ```APIDOC ## LlmChatViewStyle Constructor ### Description Initializes a new `LlmChatViewStyle` with custom visual properties for the chat view. ### Parameters - **backgroundColor** (Color) - The background color of the chat view. - **menuColor** (Color) - The color of the menu elements. - **progressIndicatorColor** (Color) - The color of the progress indicator. - **userMessageStyle** (UserMessageStyle) - Styling for user messages. - **llmMessageStyle** (LlmMessageStyle) - Styling for LLM messages. - **chatInputStyle** (ChatInputStyle) - Styling for the chat input field. - **messageSpacing** (double) - Spacing between messages. - **padding** (EdgeInsetsGeometry) - Padding around the chat view content. - **margin** (EdgeInsetsGeometry) - Margin around the chat view. - **suggestionStyle** (SuggestionStyle) - Styling for suggestion chips. - **submitButtonStyle** (ActionButtonStyle) - Styling for the submit button. - **stopButtonStyle** (ActionButtonStyle) - Styling for the stop button. - **recordButtonStyle** (ActionButtonStyle) - Styling for the record button. ### Example ```dart final customStyle = LlmChatViewStyle( backgroundColor: Color(0xFFF5F5F5), menuColor: Colors.white, progressIndicatorColor: Colors.blue, userMessageStyle: UserMessageStyle( textStyle: TextStyle(fontSize: 16), decoration: BoxDecoration(color: Colors.blue.shade100, borderRadius: BorderRadius.circular(12)), ), llmMessageStyle: LlmMessageStyle( textStyle: TextStyle(fontSize: 16), decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(12)), ), chatInputStyle: ChatInputStyle( hintText: 'Type your message...', backgroundColor: Colors.white, decoration: BoxDecoration(border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(8)), ), messageSpacing: 12.0, padding: EdgeInsets.all(16), margin: EdgeInsets.symmetric(vertical: 8), suggestionStyle: SuggestionStyle( textStyle: TextStyle(fontSize: 14), decoration: BoxDecoration(color: Colors.blue.shade50, borderRadius: BorderRadius.circular(20), border: Border.all(color: Colors.blue)), ), submitButtonStyle: ActionButtonStyle(icon: Icons.send, iconColor: Colors.blue), stopButtonStyle: ActionButtonStyle(icon: Icons.stop_circle, iconColor: Colors.red), recordButtonStyle: ActionButtonStyle(icon: Icons.mic, iconColor: Colors.red), ); ``` ``` -------------------------------- ### Initialize EchoProvider Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/EchoProvider.md Instantiate the EchoProvider, optionally with initial chat history. ```dart final provider = EchoProvider(); // Or with initial history final saved = await loadSavedMessages(); final provider = EchoProvider(history: saved); ``` -------------------------------- ### Handle LlmCancelException in a Stream Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmException.md Example of how to catch and handle a LlmCancelException when processing a message stream. This is useful for user-initiated cancellations. ```dart import 'package:flutter_ai_toolkit/flutter_ai_toolkit.dart'; try { await provider.sendMessageStream('Prompt').toList(); } catch (e) { if (e is LlmCancelException) { print('User cancelled the operation'); } } ``` -------------------------------- ### Create Basic LlmChatView Source: https://github.com/flutter/ai/blob/main/_autodocs/README.md Instantiate the LlmChatView widget, providing the initialized LLM provider. This sets up the basic chat interface. ```dart LlmChatView( provider: provider, suggestions: ['Hello', 'How are you?'], welcomeMessage: 'Welcome to AI Chat!', ) ``` -------------------------------- ### Handle LlmFailureException in a Stream Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmException.md Example of catching and handling a LlmFailureException, printing the specific error message. This is useful for diagnosing operational failures. ```dart try { await provider.sendMessageStream('Prompt').toList(); } catch (e) { if (e is LlmFailureException) { print('Operation failed: ${e.message}'); } } ``` -------------------------------- ### Accessing and Customizing Default Styles Source: https://github.com/flutter/ai/blob/main/_autodocs/configuration.md Demonstrates how to obtain the default style configuration and then override specific properties to create a custom style. ```dart final defaults = LlmChatViewStyle.defaultStyle(); // Customize specific property final custom = defaults.copyWith( backgroundColor: Colors.black, messageSpacing: 16.0, ); ``` -------------------------------- ### Instantiate LlmChatView Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/ChatViewModel.md Pass configuration parameters to LlmChatView for it to create a ChatViewModel. ```dart LlmChatView( provider: myProvider, style: myStyle, suggestions: ['Hello', 'Help'], welcomeMessage: 'Welcome!', responseBuilder: customResponseBuilder, messageSender: customMessageSender, speechToText: customSpeechToText, enableAttachments: true, enableVoiceNotes: true, strings: customStrings, ) ``` -------------------------------- ### Get Default Light Theme Style Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmChatViewStyle.md Returns the default light theme style for the chat view. All properties are initialized with sensible defaults. ```dart factory LlmChatViewStyle.defaultStyle() ``` -------------------------------- ### Default ActionButtonStyle Factory Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/ActionButtonStyle.md Creates a default styled button for a specified action type. Use this to get pre-defined styles for common actions. ```dart factory ActionButtonStyle.defaultStyle( ActionButtonType type, { LlmChatViewStrings? strings, }) ``` -------------------------------- ### ChatViewModel Constructor Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/ChatViewModel.md The constructor for ChatViewModel initializes the chat interface with various configurations including the LLM provider, styling, suggestions, welcome message, response builder, message sender, speech-to-text converter, attachment and voice note enablement, and localized strings. ```APIDOC ## ChatViewModel Constructor ### Description Initializes the ChatViewModel with all necessary state and configuration for the LlmChatView widget. ### Parameters All parameters are required positional arguments. - **provider** (LlmProvider) - Required - The LLM provider for the chat interface. - **style** (LlmChatViewStyle?) - Required - Optional style configuration for the chat view. - **suggestions** (List) - Required - Predefined suggestions to display when the chat history is empty. - **welcomeMessage** (String?) - Required - Optional welcome message displayed when the chat is first opened. - **responseBuilder** (ResponseBuilder?) - Required - Optional custom builder for rendering LLM responses. - **messageSender** (LlmStreamGenerator?) - Required - Optional custom message sender. - **speechToText** (SpeechToTextConverter?) - Required - Optional custom speech-to-text converter for voice input. - **enableAttachments** (bool) - Required - Whether file and image attachments are enabled. - **enableVoiceNotes** (bool) - Required - Whether voice recording is enabled. - **strings** (LlmChatViewStrings) - Optional - Localized strings used throughout the chat interface. Defaults to `const LlmChatViewStrings()`. ``` -------------------------------- ### ImageFileAttachment Class Definition Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/Attachment.md Represents an image file attachment, extending FileAttachment. It enforces that the MIME type must start with 'image/' through an assertion. ```dart final class ImageFileAttachment extends FileAttachment { ImageFileAttachment({ required String name, required String mimeType, required Uint8List bytes, }) : assert(Attachment._isImage(mimeType)); } ``` -------------------------------- ### Creating Chat Messages Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/MessageOrigin.md Shows how to create user and LLM messages using factory constructors and how to access and check their origins. ```dart import 'package:flutter_ai_toolkit/flutter_ai_toolkit.dart'; // User message using factory constructor final userMsg = ChatMessage.user('Hello, AI!', []); // LLM message using factory constructor final llmMsg = ChatMessage.llm(); // Access origin print(userMsg.origin); // MessageOrigin.user print(llmMsg.origin); // MessageOrigin.llm // Check origin if (userMsg.origin.isUser) { print('This is a user message'); } if (llmMsg.origin.isLlm) { print('This is an LLM message'); } ``` -------------------------------- ### Validating Conversation Flow Logic Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/MessageOrigin.md A function to validate if a conversation history follows the correct alternating pattern of user and LLM messages, starting with the user. ```dart bool isValidConversation(Iterable history) { if (history.isEmpty) return true; var lastOrigin = MessageOrigin.llm; // User goes first for (final msg in history) { // Messages must alternate between user and LLM if (msg.origin == lastOrigin) { return false; } lastOrigin = msg.origin; } return true; } ``` -------------------------------- ### LlmChatView Constructor Parameters Source: https://github.com/flutter/ai/blob/main/_autodocs/MANIFEST.md Provides a reference to the constructor parameters for the LlmChatView widget. Refer to LlmChatView.md for a detailed table of over 30 options. ```dart See [LlmChatView.md](./api-reference/LlmChatView.md) - Parameters table (30+ options) ``` -------------------------------- ### UserMessageStyle Constructor Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/UserMessageStyle.md Initializes a UserMessageStyle object with optional text style and decoration. ```APIDOC ## UserMessageStyle() ### Description Initializes a UserMessageStyle object with optional text style and decoration. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor ```dart const UserMessageStyle({ this.textStyle, this.decoration, }) ``` ### Properties - **textStyle** (TextStyle?) - Optional - Text style for user message content - **decoration** (Decoration?) - Optional - Background and border decoration ``` -------------------------------- ### Handle LlmFailureException in Dart Source: https://github.com/flutter/ai/blob/main/_autodocs/errors.md Catch LlmFailureException to handle errors that are not due to cancellation. This example demonstrates accessing the error message property for more specific error reporting. ```dart try { await provider.sendMessageStream('Prompt').toList(); } on LlmFailureException catch (e) { print('Operation failed: ${e.message}'); // Error message examples: // 'Network connection timeout' // 'Authentication failed' // 'Rate limit exceeded' // 'Invalid API key' } ``` -------------------------------- ### Implement Custom LLM Provider in Dart Source: https://github.com/flutter/ai/blob/main/_autodocs/README.md Demonstrates how to create a custom LLM provider by extending the LlmProvider interface and implementing necessary methods for streaming responses and managing chat history. ```dart class MyProvider extends LlmProvider with ChangeNotifier { final List _history = []; @override Stream generateStream( String prompt, { Iterable attachments = const {}, }) async* { // Generate response yield 'Response text'; } @override Stream sendMessageStream( String prompt, { Iterable attachments = const {}, } ) async* { final userMsg = ChatMessage.user(prompt, attachments); final llmMsg = ChatMessage.llm(); _history.addAll([userMsg, llmMsg]); yield* generateStream(prompt, attachments: attachments).map((chunk) { llmMsg.append(chunk); return chunk; }); notifyListeners(); } @override Iterable get history => _history; @override set history(Iterable messages) { _history.clear(); _history.addAll(messages); notifyListeners(); } } ``` -------------------------------- ### Enable Network Access on macOS Source: https://github.com/flutter/ai/blob/main/README.md Add the 'com.apple.security.network.client' key to your *.entitlements file to enable network access for your macOS application. ```xml ... com.apple.security.network.client ``` -------------------------------- ### Custom LlmProvider with Exception Handling Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmException.md Demonstrates how to implement a custom LlmProvider and handle various exceptions by throwing appropriate LlmException types. This is useful for managing errors gracefully in custom API integrations. ```dart class CustomProvider extends LlmProvider { @override Stream sendMessageStream( String prompt, { Iterable attachments = const [], }) async* { try { // Perform API call final response = await apiClient.sendPrompt(prompt); // Yield response chunks for (final chunk in response.chunks) { yield chunk; } } on OperationCanceledException { throw const LlmCancelException(); } on ApiException catch (e) { throw LlmFailureException('API error: ${e.message}'); } on SocketException { throw const LlmFailureException('Network connection failed'); } } } ``` -------------------------------- ### Custom Error Handling with LlmChatView Source: https://github.com/flutter/ai/blob/main/_autodocs/errors.md Provide a custom onErrorCallback to LlmChatView for specific handling of LlmFailureException. This example shows how to parse the error message and display a tailored alert dialog. ```dart LlmChatView( provider: provider, onErrorCallback: (context, error) { if (error is LlmFailureException) { // Specific error handling final message = switch (error.message) { String m when m.contains('timeout') => 'Request took too long', String m when m.contains('auth') => 'Authentication failed', String m when m.contains('rate') => 'Too many requests', _ => 'An error occurred: ${error.message}', }; showDialog( context: context, builder: (context) => AlertDialog( title: Text('Error'), content: Text(message), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: Text('Retry'), ), ], ), ); } }, ) ``` -------------------------------- ### LlmChatView with Default Strings Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmChatViewStrings.md Demonstrates how to use the LlmChatView widget without providing custom strings, which will automatically use the default set. ```dart LlmChatView( provider: myProvider, // Uses LlmChatViewStrings.defaults if not provided ) ``` -------------------------------- ### Handle LlmCancelException in Dart Source: https://github.com/flutter/ai/blob/main/_autodocs/errors.md Use a try-catch block to specifically catch and handle LlmCancelException, which is thrown when an LLM operation is cancelled. This example shows how to print a message when cancellation occurs. ```dart try { await provider.sendMessageStream('Prompt').toList(); } on LlmCancelException { print('User cancelled the operation'); } ``` -------------------------------- ### ActionButtonStyle Constructor Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/ActionButtonStyle.md Initializes an ActionButtonStyle with optional icon, color, decoration, text, and text style properties. ```APIDOC ## ActionButtonStyle Constructor ```dart const ActionButtonStyle({ this.icon, this.iconColor, this.iconDecoration, this.text, this.textStyle, }) ``` ### Properties | Property | Type | Description | |----------|------|-------------| | icon | IconData? | Button icon to display | | iconColor | Color? | Color of the icon | | iconDecoration | Decoration? | Background decoration around icon | | text | String? | Tooltip or label text | | textStyle | TextStyle? | Text appearance | ``` -------------------------------- ### Widget Test for LlmChatView Welcome Message Source: https://github.com/flutter/ai/blob/main/_autodocs/README.md Write a widget test to verify that the LlmChatView displays the correct welcome message when using EchoProvider. ```dart testWidgets('Chat displays welcome message', (tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: LlmChatView( provider: EchoProvider(), welcomeMessage: 'Welcome!', ), ), ), ); expect(find.text('Welcome!'), findsOneWidget); }); ``` -------------------------------- ### Replace Chat History Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/FirebaseProvider.md Replaces the entire chat history with a new set of messages, effectively starting a new conversation session. This setter also notifies listeners of the change. ```dart set history(Iterable history) ``` ```dart // Restore a saved conversation final savedMessages = await loadConversation('conversation-id'); provider.history = savedMessages; // Clear the conversation provider.history = []; ``` -------------------------------- ### Custom User Message Styling in LlmChatView Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/UserMessageStyle.md Example of how to apply a custom UserMessageStyle within an LlmChatView. This demonstrates overriding text style and decoration properties like color and border radius. ```dart import 'package:flutter/material.dart'; import 'package:flutter_ai_toolkit/flutter_ai_toolkit.dart'; class CustomChatView extends StatelessWidget { @override Widget build(BuildContext context) { return LlmChatView( provider: myProvider, style: LlmChatViewStyle( userMessageStyle: UserMessageStyle( textStyle: TextStyle( fontSize: 16, color: Colors.white, fontWeight: FontWeight.w500, ), decoration: BoxDecoration( color: Colors.blue, borderRadius: BorderRadius.only( topLeft: Radius.circular(20), topRight: Radius.circular(4), bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20), ), boxShadow: [ BoxShadow( color: Colors.blue.withOpacity(0.3), blurRadius: 8, offset: Offset(0, 2), ), ], ), ), ), ); } } ``` -------------------------------- ### EchoProvider Constructor Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/EchoProvider.md Initializes a new instance of the EchoProvider. It can optionally be initialized with a pre-existing chat history. ```APIDOC ## EchoProvider Constructor ### Description Initializes a new instance of the EchoProvider. It can optionally be initialized with a pre-existing chat history. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Signature ```dart EchoProvider({Iterable? history}) ``` ### Parameters - **history** (Iterable) - Optional - Optional initial chat history ### Example ```dart final provider = EchoProvider(); // Or with initial history final saved = await loadSavedMessages(); final provider = EchoProvider(history: saved); ``` ``` -------------------------------- ### Directory Structure Overview Source: https://github.com/flutter/ai/blob/main/_autodocs/MANIFEST.md Provides a visual representation of the documentation's directory structure, showing the location of various reference files. ```markdown output/ ├── README.md # Start here - overview and quick links ├── MANIFEST.md # This file - navigation and structure ├── types.md # Type definitions ├── configuration.md # Configuration options ├── errors.md # Error handling └── api-reference/ # Individual component references ├── LlmChatView.md ├── LlmProvider.md ├── ChatMessage.md ├── ChatViewModel.md ├── FirebaseProvider.md ├── EchoProvider.md ├── Attachment.md ├── MessageOrigin.md ├── LlmException.md ├── LlmChatViewStyle.md ├── UserMessageStyle.md ├── LlmMessageStyle.md ├── ActionButtonStyle.md └── LlmChatViewStrings.md ``` -------------------------------- ### Initialize FirebaseProvider Source: https://github.com/flutter/ai/blob/main/_autodocs/README.md Initialize the FirebaseProvider with a specific generative model. This is the first step to integrating AI chat functionality. ```dart final provider = FirebaseProvider( model: FirebaseAI.vertexAI().generativeModel( model: 'gemini-2.0-flash', ), ); ``` -------------------------------- ### Implementing a Logging Error Wrapper Provider Source: https://github.com/flutter/ai/blob/main/_autodocs/errors.md Create a wrapper provider like LoggingProvider to intercept and log errors from an inner LlmProvider before re-throwing them. This helps in debugging and monitoring without altering the core error handling logic. ```dart class LoggingProvider extends LlmProvider { final LlmProvider _inner; @override Stream sendMessageStream( String prompt, { Iterable attachments = const [], } ) async* { try { yield* _inner.sendMessageStream(prompt, attachments: attachments); } catch (e) { // Log the error logger.error('LLM error: $e', stackTrace: StackTrace.current); // Re-throw for caller to handle rethrow; } } } ``` -------------------------------- ### LlmMessageStyle Constructor Source: https://github.com/flutter/ai/blob/main/_autodocs/api-reference/LlmMessageStyle.md Configures the visual style for LLM messages, including icons, background decorations, text markdown styling, and layout constraints. ```APIDOC ## LlmMessageStyle() ### Description Constructs a style configuration for Language Model messages, allowing customization of visual elements and layout behavior. ### Parameters #### Named Parameters - **icon** (IconData?): Optional. The leading icon for LLM messages. Defaults to null. - **iconColor** (Color?): Optional. The color of the icon. Defaults to null. - **iconDecoration** (Decoration?): Optional. The background decoration applied around the icon. Defaults to null. - **decoration** (Decoration?): Optional. The background and border decoration for the message bubble. Defaults to null. - **markdownStyle** (MarkdownStyleData?): Optional. Configuration for rendering Markdown within the message. Defaults to null. - **maxWidth** (double): Optional. The maximum width constraint for the message bubble. Defaults to 600.0. - **minWidth** (double): Optional. The minimum width constraint for the message bubble. Defaults to 300.0. - **flex** (int): Optional. The flex factor used in a row layout to determine relative sizing. Defaults to 6. - **padding** (EdgeInsetsGeometry): Optional. The inner padding within the message bubble. Defaults to `EdgeInsets.all(12.0)`. - **margin** (EdgeInsetsGeometry): Optional. The outer margin around the message bubble. Defaults to `EdgeInsets.symmetric(vertical: 4.0)`. ```