### Install Example App Dependencies Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/CLAUDE.md Run this command inside the example/ directory to install its specific dependencies. This is separate from the main package's dependencies. ```bash flutter pub get ``` -------------------------------- ### Install Package Dependencies Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/CLAUDE.md Run this command from the repository root to install dependencies for the main package. Do not run from the example directory. ```bash # Install package deps (run from repo root, NOT from example/) flutter pub get ``` -------------------------------- ### Basic Chat Example Initialization Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/doc/ONBOARDING_AUDIT.md This snippet shows the basic setup for running the example app, registering routes for different chat functionalities. Ensure you are in the 'example/' directory and run 'flutter run'. ```dart void main() { runApp(const MainApp()); } class MainApp extends StatelessWidget { const MainApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( // ... other MaterialApp properties initialRoute: '/', routes: { '/': (context) => const ExampleListScreen(), '/basic': (context) => const BasicChatScreen(), '/streaming': (context) => const StreamingChatScreen(), '/themed': (context) => const ThemedChatScreen(), '/actions': (context) => const ActionsChatScreen(), '/rich': (context) => const RichWidgetsChatScreen(), }, ); } } ``` -------------------------------- ### Quickstart Screen Widget Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/doc/ONBOARDING_AUDIT.md A basic Flutter screen widget demonstrating the integration of AiChatWidget. This example assumes a MaterialApp wrapper and necessary imports are handled by the surrounding application structure. ```dart import 'package:flutter/material.dart'; import 'package:flutter_gen_ai_chat_ui/flutter_gen_ai_chat_ui.dart'; class ChatScreen extends StatefulWidget { const ChatScreen({ super.key, required ChatUser currentUser, required ChatUser aiUser, }); @override State createState() => _ChatScreenState(); } class _ChatScreenState extends State with ChatMessagesControllerMixin { @override void initState() { super.initState(); // Initialize controller ChatMessagesController(currentUser: widget.currentUser, aiUser: widget.aiUser); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('AI Chat'), ), body: AiChatWidget( currentUser: widget.currentUser, aiUser: widget.aiUser, controller: controller, onSendMessage: (String message) { // Handle sending message logic here debugPrint('Message sent: $message'); }, loadingConfig: LoadingConfig( loadingIndicator: const CircularProgressIndicator(), ), inputOptions: InputOptions(sendButtonIcon: const Icon(Icons.send)), welcomeMessageConfig: WelcomeMessageConfig( message: ChatMessage( text: 'Hello! How can I help you today?', user: widget.aiUser, createdAt: DateTime.now(), ), ), exampleQuestions: [ ExampleQuestion( text: 'What is Flutter?', onTap: () => controller.sendMessage('What is Flutter?'), ), ExampleQuestion( text: 'How to use this chat UI?', onTap: () => controller.sendMessage('How to use this chat UI?'), ), ], ), ); } } ``` -------------------------------- ### Minimal Chat UI Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md A basic example demonstrating the minimal setup for a chat UI. This snippet is useful for quickly integrating a functional chat interface. ```dart final messages = [ // ... initial messages ]; final chatController = ChatController( initialMessages: messages, ); // Use ChatView in your widget tree ChatView( chatController: chatController, // ... other ChatView properties ); ``` -------------------------------- ### Run Flutter Gen AI Chat UI Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/README.md Commands to clone the repository, navigate to the example directory, get dependencies, and run the Flutter application. ```bash cd example flutter pub get flutter run ``` -------------------------------- ### Running the Example App Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/README.md Navigate to the example directory and run the Flutter application to explore all features of the chat UI package. ```bash cd example/ flutter run ``` -------------------------------- ### Run Integration Tests Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/CLAUDE.md Navigate to the example directory and run integration tests. These tests interact with the example app. ```bash # Integration tests live under example/integration_test (driver tests against the example app) cd example && flutter test integration_test/ ``` -------------------------------- ### Install Application Executable Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/linux/CMakeLists.txt Installs the main application executable to the root of the installation prefix. This makes the executable available when the bundle is deployed. ```cmake install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) ``` -------------------------------- ### Define Installation Directories Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/windows/CMakeLists.txt Sets variables for the installation directories of bundle data and libraries. ```cmake set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") ``` -------------------------------- ### AiChatWidget Constructor Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md Example demonstrating the usage of the AiChatWidget, a classic chat surface entry point. It highlights controller ownership, rich-widget integration, and action provider setup. ```dart final chatController = ChatMessagesController(); final chatWidget = AiChatWidget( chatMessagesController: chatController, // ... other parameters ); ``` -------------------------------- ### Basic AI Chat UI Implementation Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/README.md A quick start example demonstrating how to set up a basic AI chat interface using AiChatWidget. This includes defining users, a message controller, and handling message sending with simulated AI responses. ```dart import 'package:flutter_gen_ai_chat_ui/flutter_gen_ai_chat_ui.dart'; class ChatScreen extends StatefulWidget { @override _ChatScreenState createState() => _ChatScreenState(); } class _ChatScreenState extends State { final _controller = ChatMessagesController(); final _currentUser = ChatUser(id: 'user', firstName: 'User'); final _aiUser = ChatUser(id: 'ai', firstName: 'AI Assistant'); bool _isLoading = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('AI Chat')), body: AiChatWidget( // Required parameters currentUser: _currentUser, aiUser: _aiUser, controller: _controller, onSendMessage: _handleSendMessage, // Optional parameters loadingConfig: LoadingConfig(isLoading: _isLoading), inputOptions: InputOptions( hintText: 'Ask me anything...', sendOnEnter: true, ), welcomeMessageConfig: WelcomeMessageConfig( title: 'Welcome to AI Chat', questionsSectionTitle: 'Try asking me:', ), exampleQuestions: [ ExampleQuestion(question: "What can you help me with?"), ExampleQuestion(question: "Tell me about your features"), ], ), ); } Future _handleSendMessage(ChatMessage message) async { setState(() => _isLoading = true); try { // Your AI service logic here await Future.delayed(Duration(seconds: 1)); // Simulating API call // Add AI response _controller.addMessage(ChatMessage( text: "This is a response to: ${message.text}", user: _aiUser, createdAt: DateTime.now(), )); } finally { setState(() => _isLoading = false); } } } ``` -------------------------------- ### Define Installation Directories Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/linux/CMakeLists.txt Sets variables for the installation directories within the bundle, specifically for data and libraries. ```cmake set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") ``` -------------------------------- ### Run Standalone File Upload Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/examples-README.md Use this command to run the standalone file upload example for the Flutter Gen AI Chat UI package. This is useful due to potential dependency issues in the main example app. ```bash flutter run -d chrome -t lib/standalone_file_upload_example.dart ``` -------------------------------- ### Install Bundled Plugin Libraries Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/windows/CMakeLists.txt Installs any bundled plugin libraries to the bundle library directory, if they exist. ```cmake if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### AiActionProvider Action Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md Shows how to use AiActionProvider to define and execute custom actions. This example demonstrates an action that pushes an item to a cart. ```dart final actionProvider = AiActionProvider( actions: { 'addToCart': ( Map params, AiActionContext context, ) async { final itemId = params['itemId'] as String; // Logic to add item to cart print('Added item $itemId to cart.'); return {'success': true}; } }, // ... other parameters ); // To execute the action: final context = AiActionContext(/* ... */); await AiActionBuilder.executeAction( actionName: 'addToCart', params: {'itemId': '123'}, context: context, ); ``` -------------------------------- ### Desktop Styling Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/DESIGN_SYSTEM_GUIDE.md Example of styling automatically applied on desktop platforms, characterized by professional rounded corners, subtle button elevation with hover effects, clear input borders, and refined loading indicators. ```dart // Automatically applied on desktop platforms: - Rounded corners: 8px (professional) - Button style: Subtle elevation with hover - Input style: Clear borders, focus rings - Loading: Smaller, refined indicators ``` -------------------------------- ### Install Native Assets Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/windows/CMakeLists.txt Installs native assets provided by build.dart from all packages to the bundle library directory. ```cmake set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### AgentOrchestrator Workflow Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md Demonstrates the typical workflow for AgentOrchestrator, including registration, processing requests, streaming responses, and disposal. ```dart final orchestrator = AgentOrchestrator(); // Register an agent await orchestrator.registerAgent(MyAgent()); // Process a request and stream the response final responseStream = await orchestrator.processRequest('User query'); responseStream.listen((event) { /* handle response */ }); // Dispose of the orchestrator when done await orchestrator.dispose(); ``` -------------------------------- ### Install Flutter Library Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/linux/CMakeLists.txt Installs the main Flutter library file to the lib directory within the bundle. This is a core component for the Flutter runtime. ```cmake install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Set Installation Prefix for Bundle Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/linux/CMakeLists.txt Configures the installation prefix to be the build bundle directory. This ensures that the installed application is relocatable. ```cmake set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() ``` -------------------------------- ### Install AOT Library Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/windows/CMakeLists.txt Installs the Ahead-Of-Time (AOT) compilation library to the bundle data directory, but only for 'Profile' and 'Release' build configurations. ```cmake install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### Install Bundled Plugin Libraries Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/linux/CMakeLists.txt Installs all bundled plugin libraries to the lib directory within the bundle. This ensures that all necessary plugin code is available at runtime. ```cmake foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) ``` -------------------------------- ### Demonstrating Actions with ActionController Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/docs/issues-review/ISSUES.md This example showcases how to use `ActionController`, `AiActionProvider`, and `AiAction` for implementing chatbot actions like calculator, weather, or color generation, utilizing keyword routing. ```dart final actionsChat = ActionsChat( // ... other parameters ... actionProviders: [ // Example: Calculator action AiActionProvider( actions: [ AiAction( keywords: ['calculate', 'math', 'compute'], description: 'Performs mathematical calculations.', onInvoke: (context, arguments) async { // ... calculator logic ... return TextContent('Result: ...'); }, ) ], ) ], ); ``` -------------------------------- ### iOS Styling Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/DESIGN_SYSTEM_GUIDE.md Example of styling automatically applied on iOS devices, including rounded corners, button styles, input styles, and loading indicators. ```dart // Automatically applied on iOS devices: - Rounded corners: 20px - Button style: No elevation, rounded - Input style: Filled background, no borders - Loading: Cupertino-style indicators ``` -------------------------------- ### Update Install Snippet in README Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md Updates the package version in the installation snippet within the README.md file. ```markdown README.md - Install snippet bumped `^2.4.2` → `^2.11.1` ``` -------------------------------- ### Set Installation Prefix for Visual Studio Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/windows/CMakeLists.txt Configures the installation prefix for Visual Studio builds to be adjacent to the executable, enabling in-place running. ```cmake set(BUILD_BUNDLE_DIR "$") set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() ``` -------------------------------- ### Android Styling Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/DESIGN_SYSTEM_GUIDE.md Example of styling automatically applied on Android devices, featuring rounded corners, Material elevation for buttons, outlined input fields, and Material progress indicators. ```dart // Automatically applied on Android devices: - Rounded corners: 16px - Button style: Material elevation - Input style: Outlined with focus states - Loading: Material progress indicators ``` -------------------------------- ### Clean Build Bundle Directory on Install Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/linux/CMakeLists.txt Removes the build bundle directory before installation to ensure a clean state. This is part of the installation process. ```cmake install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) ``` -------------------------------- ### Run All Integration Tests Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/integration_test/README.md Execute all integration tests for the Flutter Gen AI Chat UI example. Replace `` with your target device identifier. ```bash flutter test integration_test/main_test.dart -d ``` -------------------------------- ### Agent/Tool Use Chat UI Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md Illustrates setting up a chat UI for agent or tool usage, enabling more complex interactions. This snippet is relevant for building AI-powered assistants or applications that leverage external tools. ```dart final chatController = ChatController( // ... other properties resultRenderers: { 'tool_code': (String toolCode) async { // ... render tool code result } }, sendOrMicBuilder: ( { required OnSendTap onSendTap, required bool canSend, } ) => SendButton(onPressed: () => onSendTap(text: ''), canSend: canSend), ); // Use ChatView with the controller configured for agent/tool interactions ``` -------------------------------- ### Dart Speech Recognition Implementation Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/doc/COMPATIBILITY.md This Dart code demonstrates initializing speech recognition and requesting microphone permissions. Further methods for listening are not shown. ```dart // Example implementation import 'package:speech_to_text/speech_to_text.dart'; import 'package:permission_handler/permission_handler.dart'; class SpeechImplementation { final SpeechToText _speech = SpeechToText(); Future initializeSpeech() async { // Request microphone permission await Permission.microphone.request(); // Initialize speech recognition bool available = await _speech.initialize(); return available; } // Add methods for starting/stopping listening, etc. } ``` -------------------------------- ### Basic Usage of Design System Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/DESIGN_SYSTEM_GUIDE.md Demonstrates how to use the Linear Design System to get responsive dimensions, spacing, and text styles for UI components. Ensure the widget is built within a context where the design system is available. ```dart class MyResponsiveWidget extends StatelessWidget { @override Widget build(BuildContext context) { // Get responsive dimensions final dimensions = LinearDesignGuidelines.getComponentDimensions(context); final spacing = LinearDesignGuidelines.getSpacing(context, SpacingSize.md); final textStyle = LinearDesignGuidelines.getTextStyle(context, TextStyleType.bodyMedium); return Container( padding: EdgeInsets.all(spacing), constraints: BoxConstraints(maxWidth: dimensions.messageMaxWidth), child: Text('Responsive text!', style: textStyle), ); } } ``` -------------------------------- ### Run Pana Locally for Pub.dev Score Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md This command installs and runs the Pana tool to measure the pub.dev score of a project. Ensure Pana is installed globally before execution. ```bash dart pub global activate pana pana ``` -------------------------------- ### Example of a Formatter Cleanup in Test Files Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md This entry in the diff summary indicates that 15 files in the 'test/' directory were reformatted. This was a cleanup of pre-existing uncommitted edits and did not involve logic changes. ```text 15 test/**/*.dart files — pure `dart format` rewrap, zero logic change (was pre-existing drift from iters 2-7 uncommitted edits). ``` -------------------------------- ### Updating Pubspec and README for Release Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/CLAUDE.md Before releasing, bump the version in pubspec.yaml and update the install snippet in README.md. ```yaml version: 1.2.3 # Example version bump ``` -------------------------------- ### Run All Tests on Chrome Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/integration_test/README.md Execute all integration tests on the Chrome browser. Ensure Chrome is installed and accessible. ```bash flutter test integration_test/main_test.dart -d chrome ``` -------------------------------- ### AI Actions System Quick Start Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/README.md Integrate the AI Actions System to enable your AI to execute functions, display rich results, and maintain human oversight. Define actions with parameters and handlers. ```dart import 'package:flutter_gen_ai_chat_ui/flutter_gen_ai_chat_ui.dart'; class MyAiChat extends StatefulWidget { @override _MyAiChatState createState() => _MyAiChatState(); } class _MyAiChatState extends State { late ChatMessagesController _controller; @override Widget build(BuildContext context) { return AiActionProvider( config: AiActionConfig( actions: [ // Define what your AI can do AiAction( name: 'calculate', description: 'Perform mathematical calculations', parameters: [ ActionParameter.number(name: 'a', description: 'First number', required: true), ActionParameter.number(name: 'b', description: 'Second number', required: true), ActionParameter.string( name: 'operation', description: 'Math operation', required: true, enumValues: ['add', 'subtract', 'multiply', 'divide'] ), ], handler: (params) async { final a = params['a'] as num; final b = params['b'] as num; final op = params['operation'] as String; double result; switch (op) { case 'add': result = a + b; break; case 'subtract': result = a - b; break; case 'multiply': result = a * b; break; case 'divide': result = a / b; break; default: throw 'Unknown operation'; } return ActionResult.createSuccess({ 'result': result, 'equation': '$a $op $b = $result' }); }, // Custom UI for results render: (context, status, params, {result, error}) { if (status == ActionStatus.completed && result?.data != null) { return Card( child: Padding( padding: EdgeInsets.all(16), child: Text( result!.data['equation'], style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), ), ); } return SizedBox.shrink(); }, ), ], ), child: AiChatWidget( // Your existing chat configuration currentUser: currentUser, aiUser: aiUser, controller: _controller, onSendMessage: _handleMessage, ), ); } void _handleMessage(ChatMessage message) { // Add user message _controller.addMessage(message); // Simulate AI deciding to use an action if (message.text.contains('calculate')) { _executeCalculation(message.text); } } void _executeCalculation(String userMessage) async { final actionHook = AiActionHook.of(context); // AI parses user message and calls action final result = await actionHook.executeAction('calculate', { 'a': 15, 'b': 3, 'operation': 'multiply' }); // Add AI response with result _controller.addMessage(ChatMessage( text: result.success ? 'I calculated that for you: ${result.data['equation']}' : 'Sorry, calculation failed: ${result.error}', user: aiUser, )); } } ``` -------------------------------- ### Fixing example/lib/examples/rich_widgets_chat.dart Analyzer Warnings Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md Replaced 'withOpacity' with 'withOpacityCompat' and 'const'-ified widgets to resolve analyzer infos. This ensures the example file is clean and free of lints. ```dart // Replaced withOpacity with withOpacityCompat // const-ified renderer map and _Bar widgets ``` -------------------------------- ### Install flutter_gen_ai_chat_ui Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/AGENTS.md Add the flutter_gen_ai_chat_ui package to your pubspec.yaml file. Import the package into your Dart code. ```yaml dependencies: flutter_gen_ai_chat_ui: ^2.11.1 ``` ```dart import 'package:flutter_gen_ai_chat_ui/flutter_gen_ai_chat_ui.dart'; ``` -------------------------------- ### Update README install snippet version Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md This snippet shows how to update the version number in the README.md installation instructions. Ensure this matches the current stable release to avoid confusion for new users. ```markdown flutter_gen_ai_chat_ui: ^2.11.1 ``` -------------------------------- ### AI Action Execution Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/doc/ONBOARDING_AUDIT.md Shows how to execute a registered AI action using its name and parameters. This is typically called from a UI or controller after an AI has determined which action to take. ```dart AiActionHook.of(context).executeAction("get_weather", {"location": "London"}) ``` -------------------------------- ### Streaming Chat UI Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md Demonstrates how to implement a chat UI that supports streaming responses, allowing for real-time message updates. This is useful for applications requiring dynamic and interactive chat experiences. ```dart final chatController = ChatController( // ... other properties enableMarkdownStreaming: true, streamingWordByWord: true, ); // Use ChatView with the controller configured for streaming ``` -------------------------------- ### ChatMessage Construction Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md Demonstrates how to construct ChatMessage objects for ordinary text and markdown content. ChatMessage is immutable and supports copyWith. ```dart // Ordinary text message final textMessage = ChatMessage( id: '1', content: 'Hello, world!', isUser: false, ); // Markdown message final markdownMessage = ChatMessage.createMarkdown( id: '2', content: '# This is a **markdown** message.', isUser: false, ); ``` -------------------------------- ### Update pubspec.yaml topics Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md This example shows how to expand the 'topics' field in pubspec.yaml to improve pub.dev SEO and relevance signals. It's a quick way to enhance package discoverability. ```yaml topics: - ai - chat - llm - openai - anthropic - gemini - streaming - agent - markdown - rtl ``` -------------------------------- ### Minimal RTL Chat Setup Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/README.md Demonstrates the basic configuration for enabling right-to-left language support in the chat interface. Ensure your app's Localizations are set up or use Directionality widget. ```dart Directionality( textDirection: TextDirection.rtl, child: AiChatWidget( currentUser: ChatUser(id: 'user', name: 'أنت'), aiUser: ChatUser(id: 'ai', name: 'المساعد'), controller: controller, onSendMessage: handleSend, enableMarkdownStreaming: true, exampleQuestions: const [ ExampleQuestion(question: 'ما هي عاصمة العراق؟'), ExampleQuestion(question: 'اكتب لي قصيدة قصيرة'), ], ), ) ``` -------------------------------- ### Install Native Assets Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/linux/CMakeLists.txt Copies native assets provided by build.dart from all packages to the lib directory. These assets are required for certain platform-specific functionalities. ```cmake set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Set CMake Minimum Version and Project Name Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/linux/CMakeLists.txt Specifies the minimum required CMake version and defines the project name. This is a standard CMake setup. ```cmake cmake_minimum_required(VERSION 3.13) project(runner LANGUAGES CXX) ``` -------------------------------- ### Run Flutter Analysis Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md Execute 'flutter analyze' to check for issues in the main project and the example directory. This helps ensure code quality and adherence to Dart conventions. ```bash flutter analyze ``` ```bash flutter analyze example/ ``` -------------------------------- ### Agent Function-Calling Handler Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/doc/ONBOARDING_AUDIT.md Demonstrates the handler signature and parameter types for AI actions. Use ActionParameter.number for numeric inputs and ensure correct type casting in the handler. The result should be created using ActionResult.createSuccess. ```dart AiActionProvider( config: AiActionConfig( actions: [ AiAction( name: "get_weather", description: "Get the current weather in a given location", parameters: { "location": ActionParameter.string(required: true), "unit": ActionParameter.string(required: false, defaultValue: "c") }, handler: (Map params) async { // Example handler logic final location = params["location"] as String; final unit = params["unit"] as String? ?? "c"; // Simulate fetching weather data final weatherData = { "location": location, "temperature": "25", "unit": unit }; return ActionResult.createSuccess(data: weatherData); }, render: (context, data) => Text("Weather in ${data['location']}: ${data['temperature']}${data['unit'] == 'c' ? '°C' : '°F'}"), confirmationConfig: ConfirmationConfig( prompt: (context, params) => Text("Confirm getting weather for ${params['location']}?") ) ) ] ) ) ``` -------------------------------- ### Minimal Chat Interface Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/AGENTS.md This snippet demonstrates the basic setup for an AI chat interface using AiChatWidget. It includes a controller for managing messages and a send message handler. ```dart class ChatScreen extends StatefulWidget { const ChatScreen({super.key}); @override State createState() => _ChatScreenState(); } class _ChatScreenState extends State { final _controller = ChatMessagesController(); final _me = const ChatUser(id: 'user', firstName: 'Me'); final _ai = const ChatUser(id: 'ai', firstName: 'Assistant'); Future _onSend(ChatMessage msg) async { // Call your LLM here. Returning a string is enough for non-streaming. final reply = await myLlmCall(msg.text); _controller.addMessage(ChatMessage( text: reply, user: _ai, createdAt: DateTime.now(), )); } @override Widget build(BuildContext context) => Scaffold( body: AiChatWidget( currentUser: _me, aiUser: _ai, controller: _controller, onSendMessage: _onSend, ), ); } ``` -------------------------------- ### Device-Aware Layout Configuration Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/DESIGN_SYSTEM_GUIDE.md Adapt layout structure based on device capabilities by checking layout configurations. This example shows switching between a single column (mobile) and a sidebar layout (desktop). ```dart class AdaptiveLayout extends StatelessWidget { @override Widget build(BuildContext context) { final layout = LinearDesignGuidelines.getLayoutConfiguration(context); if (layout.stackVertically) { // Mobile: Single column return Column( children: [ _buildHeader(), Expanded(child: _buildContent()), _buildInput(), ], ); } else { // Desktop: Sidebar layout return Row( children: [ if (layout.showSidebar) SizedBox( width: layout.sidebarWidth, child: _buildSidebar(), ), Expanded( child: Column( children: [ _buildHeader(), Expanded(child: _buildContent()), _buildInput(), ], ), ), ], ); } } } ``` -------------------------------- ### Run Welcome Message Test File Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/integration_test/README.md Execute the integration test file for welcome messages. Replace `` with your target device identifier. ```bash flutter test integration_test/welcome_message_test.dart -d ``` -------------------------------- ### CI Workflow Configuration Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md This YAML file defines the CI workflow for the project, including checkout, Flutter setup, dependency installation, Dart formatting check, analysis, and testing. It triggers on push and pull requests to the main branch. ```yaml name: CI on: push: branches: [ main ] pull_request: branches: [ main ] workflow_dispatch: env: FLUTTER_VERSION: "3.16.0" jobs: build: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 - name: Setup Flutter uses: subosito/flutter-action@v2 with: flutter-version: ${{ env.FLUTTER_VERSION }} channel: stable cache: true - name: Install dependencies run: flutter pub get - name: Format check run: dart format --output=none --set-exit-if-changed . - name: Analyze code run: flutter analyze --fatal-infos - name: Run tests run: flutter test --reporter expanded ``` -------------------------------- ### Audit SchedulerBinding and WidgetsBinding Usage Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md This command searches for 'SchedulerBinding' or 'WidgetsBinding.instance' within the lib/src/ directory to identify related asynchronous scheduling mechanisms. ```bash grep -rn 'SchedulerBinding\|WidgetsBinding.instance' lib/src/ ``` -------------------------------- ### AiActionHook Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md Example of using AiActionHook to build UI elements that can trigger actions. This hook is used with AiActionBuilder to execute a registered action. ```dart AiActionHook( actionName: 'performTask', params: {'data': 'someValue'}, builder: (context, executeAction) { return ElevatedButton( onPressed: () async { await executeAction(); }, child: const Text('Perform Task'), ); }, ); ``` -------------------------------- ### Install AOT Library for Non-Debug Builds Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/linux/CMakeLists.txt Installs the Ahead-Of-Time (AOT) compiled library on non-Debug builds. This is used for performance optimization in release and profile builds. ```cmake if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Run All Tests Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/CLAUDE.md Execute all unit tests within the project. ```bash # Run all tests flutter test ``` -------------------------------- ### Install Flutter ICU Data File Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/linux/CMakeLists.txt Installs the Flutter ICU data file to the data directory within the bundle. This file is necessary for internationalization support. ```cmake install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Add RTL Support Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md This snippet demonstrates how to wrap a widget with Directionality.rtl to enable Right-to-Left layout support. It's intended for use in an example application and README documentation. ```dart Directionality.rtl ``` -------------------------------- ### Fixing Deprecated withOpacity in Example App Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/doc/ONBOARDING_AUDIT.md Replaces deprecated `withOpacity` calls with `withOpacityCompat` to maintain compatibility and avoid linter warnings. This ensures the example app adheres to current package conventions. ```dart Color.withOpacityCompat(0.5) ``` -------------------------------- ### RTL Chat Screen Example Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md This screen demonstrates how to wrap the AiChatWidget in Directionality with textDirection set to TextDirection.rtl. It streams a canned Arabic markdown response word-by-word and includes example questions to show per-message bidi auto-detection for mixed conversations. ```dart import "package:flutter/material.dart"; import "package:flutter_gen_ai_chat_ui/flutter_gen_ai_chat_ui.dart"; class RtlChatScreen extends StatefulWidget { const RtlChatScreen({super.key}); @override State createState() => _RtlChatScreenState(); } class _RtlChatScreenState extends State with ChatController { @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.rtl, child: Scaffold( appBar: AppBar( title: const Text("RTL Chat Example"), ), body: AiChatWidget( chatController: this, // ... other AiChatWidget configurations ), ), ); } @override void initState() { super.initState(); // Simulate streaming a canned Arabic response Future.delayed(const Duration(seconds: 1), () { streamMessage( "مرحباً! كيف يمكنني مساعدتك اليوم؟", // Hello! How can I help you today? ); }); } @override Future onMessageSent(String message) async { // Handle user message, potentially stream a response if (message.toLowerCase() == "hello") { streamMessage("أهلاً بك!"); // Welcome! } else if (message.toLowerCase().contains("example")) { streamMessage("هذا مثال على الرد."); // This is an example response. } else { streamMessage("شكراً لرسالتك."); // Thank you for your message. } } } ``` -------------------------------- ### Suggested CHANGELOG.md Entry - Notes Section Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md This is a suggested addition to the 'Notes' section of the CHANGELOG.md file, explaining the new CI workflow and its purpose. ```markdown ### Notes - CI: added `.github/workflows/ci.yml` running `dart format --set-exit- if-changed`, `flutter analyze --fatal-infos`, and `flutter test` on push/PR to `main`. The formatter step closes a gap surfaced by the iter-7 pana run (where `flutter analyze` was green but `pana` flagged unformatted dartdoc rewraps). ``` -------------------------------- ### Find PkgConfig and GTK+ 3.0 Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/linux/CMakeLists.txt Finds and checks for the PkgConfig tool and the GTK+ 3.0 library. These are system-level dependencies required for the application. ```cmake find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) ``` -------------------------------- ### Configure Cross-Building Sysroot Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/linux/CMakeLists.txt Sets up the sysroot and find root path for cross-compilation. This is used when building for a different architecture or platform. ```cmake if(FLUTTER_TARGET_PLATFORM_SYSROOT) set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) endif() ``` -------------------------------- ### Run All Tests on iOS Simulator Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/integration_test/README.md Execute all integration tests on a specified iOS simulator. Replace 'iPhone 16' with your desired simulator name. ```bash flutter test integration_test/main_test.dart -d "iPhone 16" ``` -------------------------------- ### Migrating AiChatWidget Configuration: After Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/doc/MIGRATION.md Illustrates the refactored `AiChatWidget` configuration after migrating from `AiChatConfig` to direct parameters and updated option objects. ```dart AiChatWidget( // Required parameters currentUser: _currentUser, aiUser: _aiUser, controller: _chatController, onSendMessage: _handleSendMessage, // Layout and behavior maxWidth: 800, padding: const EdgeInsets.all(16), enableAnimation: true, enableMarkdownStreaming: true, streamingDuration: const Duration(milliseconds: 50), // Message display and organization messageOptions: MessageOptions( showTime: true, showUserName: true, decoration: BoxDecoration( color: Colors.grey[200], borderRadius: BorderRadius.circular(12), ), ), // Input configuration inputOptions: InputOptions( unfocusOnTapOutside: false, sendOnEnter: true, hintText: 'Ask me anything...', margin: const EdgeInsets.all(16), ), // Loading configuration loadingConfig: LoadingConfig( isLoading: _isLoading, typingIndicatorColor: Colors.blue, ), // Onboarding elements exampleQuestions: [ ExampleQuestion(question: 'What is AI?'), ExampleQuestion(question: 'How do you work?'), ], persistentExampleQuestions: true, welcomeMessageConfig: WelcomeMessageConfig( title: 'Welcome to AI Chat', containerPadding: const EdgeInsets.all(16), ), ) ``` -------------------------------- ### Comment on PR with Pub.dev Link Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/PR_HANDLING_ULTRATHINK.md Example of a comment to be made on a merged pull request, informing the contributor about the release and providing a link to the package on pub.dev. ```bash Published in v2.4.0: https://pub.dev/packages/flutter_gen_ai_chat_ui ``` -------------------------------- ### Commit Message for Feature Addition Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/ULTRATHINK_ENABLE_INTERACTIVE_SELECTION.md Example of a detailed Git commit message following conventional commits, including a co-authored-by line for proper attribution. ```bash git commit -m "feat(input): add enableInteractiveSelection control Add support for controlling text selection interactivity in the chat input field by exposing Flutter's enableInteractiveSelection. - Add enableInteractiveSelection field to InputOptions (default: true) - Wire property through to TextField widget in ChatInput - Include in copyWith method for proper immutability This allows developers to disable text selection for specific UX scenarios while maintaining full backward compatibility. Based on original implementation by devFarzad in branch feat/add-enable-interactive-selection. Co-authored-by: devFarzad " ``` -------------------------------- ### Publish to pub.dev Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/PR_HANDLING_ULTRATHINK.md The command to publish the package to the pub.dev repository. Ensure your package is versioned correctly and all changes are documented before running this. ```bash flutter pub publish ``` -------------------------------- ### Update CHANGELOG.md Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/PR_HANDLING_ULTRATHINK.md Example of how to update the CHANGELOG.md file to reflect new features, changes, and contributors after a release. This format is standard for many Dart/Flutter packages. ```markdown ## [2.4.0] - 2025-11-08 ### Added - ChatSpacingConfig for centralized spacing control (#27 by @ducnguyenenterprise) - Custom icon data support for example questions (#27) - Keyboard dismiss behavior configuration (#27) ### Changed - Improved loading animation speed from 800ms to 300ms (#27) ### Contributors - @ducnguyenenterprise - Thank you! 🙏 ``` -------------------------------- ### Example of a Code Change in CustomChatWidget Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/WORK_LOG.md This diff summary notes a change in `custom_chat_widget.dart` to include an `if (!mounted) return;` guard in the initial-scroll post-frame callback and an explanatory comment. ```diff lib/src/widgets/custom_chat_widget.dart — `if (!mounted) return;` guard in initial-scroll post-frame callback + explanatory comment. ``` -------------------------------- ### Enable Unicode Support Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/windows/CMakeLists.txt Adds preprocessor definitions to enable Unicode support for all projects. ```cmake add_definitions(-DUNICODE -D_UNICODE) ``` -------------------------------- ### Get Interaction Specifications Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/DESIGN_SYSTEM_GUIDE.md Retrieve platform-appropriate interaction specifications for touch targets, hover effects, and animation timings. Ensure WCAG compliance for touch targets. ```dart final interaction = LinearDesignGuidelines.getInteractionSpecs(context); // Touch targets (WCAG compliant) interaction.minTouchTarget // 44px minimum interaction.buttonTouchTarget // Scaled appropriately interaction.iconTouchTarget // Accessible icon sizing // Hover effects (desktop only) interaction.enableHover // false mobile, true desktop interaction.hoverElevation // Subtle elevation interaction.hoverScale // 1.02x growth // Animation timing interaction.quickTransition // 150ms for immediate feedback interaction.standardTransition // 250ms for state changes interaction.slowTransition // 350ms for complex animations // Focus indicators interaction.focusRingWidth // Keyboard navigation interaction.focusRingOffset // Ring positioning ``` -------------------------------- ### Migrating AiChatWidget Configuration: Before Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/doc/MIGRATION.md Shows the configuration of `AiChatWidget` using the older `AiChatConfig` before migration. ```dart AiChatWidget( config: AiChatConfig( userName: 'User', aiName: 'Assistant', hintText: 'Ask me anything...', maxWidth: 800, padding: const EdgeInsets.all(16), enableAnimation: true, showTimestamp: true, persistentExampleQuestions: true, enableMarkdownStreaming: true, streamingDuration: const Duration(milliseconds: 50), inputOptions: InputOptions( sendOnEnter: true, margin: const EdgeInsets.all(16), ), messageOptions: MessageOptions( showTime: true, showUserName: true, decoration: BoxDecoration( color: Colors.grey[200], borderRadius: BorderRadius.circular(12), ), ), loadingConfig: LoadingConfig( isLoading: _isLoading, typingIndicatorColor: Colors.blue, ), exampleQuestions: [ ExampleQuestion(question: 'What is AI?'), ExampleQuestion(question: 'How do you work?'), ], welcomeMessageConfig: WelcomeMessageConfig( title: 'Welcome to AI Chat', containerPadding: const EdgeInsets.all(16), ), ), currentUser: _currentUser, aiUser: _aiUser, controller: _chatController, onSendMessage: _handleSendMessage, ) ``` -------------------------------- ### Custom Scaling Widget Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/DESIGN_SYSTEM_GUIDE.md Create custom scaled widgets by calculating a scale factor based on screen width. This example demonstrates scaling container dimensions and padding. ```dart class MyScaledWidget extends StatelessWidget { @override Widget build(BuildContext context) { final screenWidth = MediaQuery.of(context).size.width; // Get the current scale factor final scaleFactor = _calculateScaleFactor(screenWidth); return Container( width: 100 * scaleFactor, // Scales: 100px → 140px height: 50 * scaleFactor, // Scales: 50px → 70px padding: EdgeInsets.all(8 * scaleFactor), // Scales: 8px → 11.2px child: Text('Scaled content'), ); } double _calculateScaleFactor(double screenWidth) { final clampedWidth = screenWidth.clamp(360.0, 1920.0); final progress = (clampedWidth - 360) / (1440 - 360); return (1.0 + (progress * 0.4)).clamp(1.0, 1.4); } } ``` -------------------------------- ### Apply Standard Build Settings Source: https://github.com/hooshyar/flutter_gen_ai_chat_ui/blob/main/example/windows/runner/CMakeLists.txt Applies a standard set of build settings to the application target. This can be removed if custom build settings are required. ```cmake # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) ```