### Navigate to Plugin Example Directory Source: https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-plugin-authors Change to the plugin's example app directory when working with the example project. ```shell cd path/to/plugin/example/ ``` -------------------------------- ### Build and Run Plugin Example App Source: https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-plugin-authors Verify the plugin's example app builds and runs successfully. Execute this command from the plugin's example directory. ```shell flutter run ``` -------------------------------- ### Configure Xcode command-line tools Source: https://docs.flutter.dev/platform-integration/macos/setup Sets the active Xcode version and performs initial setup. Use this command to point the system to the installed Xcode application and perform first-launch tasks. ```bash $ sudo sh -c 'xcode-select -s /Applications/Xcode.app/Contents/Developer && xcodebuild -runFirstLaunch' ``` -------------------------------- ### Install snapcraft command Source: https://docs.flutter.dev/deployment/linux Install the snapcraft command-line tool on Ubuntu using snap with classic confinement. ```bash $ sudo snap install snapcraft --classic ``` -------------------------------- ### Create Flutter installation directory Source: https://docs.flutter.dev/community/china Creates a new directory for the Flutter SDK and navigates into it. The example uses a 'dev' folder in the user's home or profile directory. ```powershell $ New-Item -Path "$env:USERPROFILE\dev" -ItemType Directory; cd "$env:USERPROFILE\dev" ``` ```bash $ mkdir ~/dev; cd ~/dev ``` ```bash $ mkdir ~/dev; cd ~/dev ``` -------------------------------- ### Xcode Cloud: Post-Clone Script for Flutter Setup Source: https://docs.flutter.dev/deployment/cd This ci_post_clone.sh script, executed after repository cloning in Xcode Cloud, sets up the Flutter SDK, installs iOS artifacts, fetches dependencies, and installs CocoaPods. ```sh #!/bin/sh # Fail this script if any subcommand fails. set -e # The default execution directory of this script is the ci_scripts directory. cd $CI_PRIMARY_REPOSITORY_PATH # change working directory to the root of your cloned repo. # Install Flutter using git. git clone https://github.com/flutter/flutter.git --depth 1 -b stable $HOME/flutter export PATH="$PATH:$HOME/flutter/bin" # Install Flutter artifacts for iOS (--ios), or macOS (--macos) platforms. flutter precache --ios # Install Flutter dependencies. flutter pub get # Install CocoaPods using Homebrew. HOMEBREW_NO_AUTO_UPDATE=1 # disable homebrew's automatic updates. brew install cocoapods ``` -------------------------------- ### Agree to Xcode Licenses Source: https://docs.flutter.dev/platform-integration/ios/setup Execute this command to review and agree to the Xcode licenses after installation and command-line tool setup. ```bash $ sudo xcodebuild -license ``` -------------------------------- ### Run CupertinoSwitch API Example in Bash Source: https://docs.flutter.dev/ui/design/cupertino Execute these commands to navigate to the Flutter examples directory and launch the CupertinoSwitch demo. Ensure you have the Flutter SDK cloned locally. ```bash cd path/to/flutter cd examples/api flutter run lib/cupertino/switch/cupertino_switch.0.dart ``` -------------------------------- ### Create New Flutter App with Gemini CLI Source: https://docs.flutter.dev/ai/gemini-cli-extension Initiates the process to bootstrap a new Flutter project, guiding you through setup and best practices. ```bash /create-app ``` -------------------------------- ### Example: Add Flutter SDK bin to PATH Source: https://docs.flutter.dev/install/add-to-path This example demonstrates adding the Flutter SDK's 'bin' directory to the 'PATH', assuming the SDK is located at '$HOME/develop/flutter'. ```bash $ echo 'export PATH="$HOME/develop/flutter/bin:$PATH"' >> ~/.bash_profile ``` -------------------------------- ### Install built snap locally Source: https://docs.flutter.dev/deployment/linux Install a locally built .snap file with the --dangerous flag to bypass store verification during testing. ```bash $ sudo snap install ./super-cool-app_0.1.0_amd64.snap --dangerous ``` -------------------------------- ### Install prerequisite packages on Debian-based systems Source: https://docs.flutter.dev/platform-integration/linux/setup Use apt-get to install the required build tools and libraries including clang, cmake, and GTK development files. ```bash $ sudo apt-get update -y && sudo apt-get upgrade -y $ sudo apt-get install -y clang cmake ninja-build pkg-config libgtk-3-dev libstdc++-12-dev ``` -------------------------------- ### Open Xcode Workspace for iOS Example App Source: https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-plugin-authors Use this command in the plugin's root directory to open the example app's Xcode workspace. Replace 'ios' with 'macos' if targeting macOS. ```bash open example/ios/Runner.xcworkspace ``` -------------------------------- ### Install SplitCompat in attachBaseContext Source: https://docs.flutter.dev/perf/deferred-components Call SplitCompat.install within the attachBaseContext method to enable dynamic module installation. ```java @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); // Emulates installation of future on demand modules using SplitCompat. SplitCompat.install(this); } ``` -------------------------------- ### Tooltip widget tree test setup in Dart Source: https://docs.flutter.dev/release/breaking-changes/tooltip-semantics-order Example widget tree structure used in accessibility tests to verify tooltip behavior. This demonstrates the test setup before the semantics tree change, showing a Tooltip wrapped in Directionality, Overlay, and ListView. ```dart Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: [ OverlayEntry( builder: (BuildContext context) { return ListView( children: [ const Text('before'), Tooltip( key: tooltipKey, showDuration: const Duration(days: 365), message: 'message', child: const Text('child'), ), const Text('after'), ], ); }, ), ], ), ); ``` -------------------------------- ### Install LXD container manager Source: https://docs.flutter.dev/deployment/linux Install the LXD container manager using snap, which is required for the snap build process. ```bash $ sudo snap install lxd ``` -------------------------------- ### flutter install Source: https://docs.flutter.dev/reference/flutter-cli Install a Flutter app on an attached device. ```APIDOC ## COMMAND flutter install ### Description Install a Flutter app on an attached device. ### Usage `flutter install -d ` ### Arguments - **-d ** (string) - Required - Specifies the device ID to install on. ### Request Example N/A ### Response #### Success Response (0) - **Output** (string) - Installation status. #### Response Example N/A ``` -------------------------------- ### Validate Flutter web setup with flutter devices Source: https://docs.flutter.dev/platform-integration/web/setup Run this command to verify that Flutter can find your installed web browser and see connected web devices. ```bash $ flutter devices Found 1 connected devices: Chrome (web) • chrome • web-javascript • Google Chrome ``` -------------------------------- ### Check Flutter development setup issues Source: https://docs.flutter.dev/platform-integration/android/setup Use this command to diagnose potential problems with your Flutter Android development environment. It reports on installed tools and their status. ```bash $ flutter doctor ``` -------------------------------- ### Example of Absolute Path in Xcode Project File Source: https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-plugin-authors This is a concrete example of an absolute path reference found in the 'project.pbxproj' file. ```plain_text path = /Users/username/path/to/my_plugin/ios/my_plugin; sourceTree = "" ``` -------------------------------- ### Package and sign the macOS application Source: https://docs.flutter.dev/deployment/macos Creates a .pkg installer, signs it with the developer installer certificate, and cleans up intermediate files. ```bash APP_NAME=$(find $(pwd) -name "*.app") PACKAGE_NAME=$(basename "$APP_NAME" .app).pkg xcrun productbuild --component "$APP_NAME" /Applications/ unsigned.pkg INSTALLER_CERT_NAME=$(keychain list-certificates \ | jq '[.[] | select(.common_name | contains("Mac Developer Installer")) | .common_name][0]' \ | xargs) xcrun productsign --sign "$INSTALLER_CERT_NAME" unsigned.pkg "$PACKAGE_NAME" rm -f unsigned.pkg ``` -------------------------------- ### Initialize LXD configuration Source: https://docs.flutter.dev/deployment/linux Configure LXD after installation using interactive prompts; default answers are suitable for most use cases. ```bash $ sudo lxd init Would you like to use LXD clustering? (yes/no) [default=no]: Do you want to configure a new storage pool? (yes/no) [default=yes]: Name of the new storage pool [default=default]: Name of the storage backend to use (btrfs, dir, lvm, zfs, ceph) [default=zfs]: Create a new ZFS pool? (yes/no) [default=yes]: Would you like to use an existing empty disk or partition? (yes/no) [default=no]: Size in GB of the new loop device (1GB minimum) [default=5GB]: Would you like to connect to a MAAS server? (yes/no) [default=no]: Would you like to create a new local network bridge? (yes/no) [default=yes]: What should the new bridge be called? [default=lxdbr0]: What IPv4 address should be used? (CIDR subnet notation, "auto" or "none") [default=auto]: What IPv6 address should be used? (CIDR subnet notation, "auto" or "none") [default=auto]: Would you like LXD to be available over the network? (yes/no) [default=no]: Would you like stale cached images to be updated automatically? (yes/no) [default=yes] Would you like a YAML "lxd init" preseed to be printed? (yes/no) [default=no]: ``` -------------------------------- ### Start Flutter Widget Previewer from command line Source: https://docs.flutter.dev/tools/widget-previewer Launch the Widget Previewer from your Flutter project root to start a local server and open the preview environment in Chrome with automatic hot-reload on file changes. ```shell flutter widget-preview start ``` -------------------------------- ### Start recording to a file Source: https://docs.flutter.dev/cookbook/audio/record Begin recording audio and save it to a specified file path using the defined configuration. ```dart // TODO: Specify the path where the audio file should be saved. final audioFilePath = 'myRecording.wav'; await recorder.start(recordConfig, path: audioFilePath); ``` -------------------------------- ### Create Flutter project for orientation tests Source: https://docs.flutter.dev/cookbook/testing/widget/orientation Initializes a new Flutter project to host the orientation testing examples. ```bash flutter create orientation_tests ``` -------------------------------- ### Flutter Create Output and Setup Instructions Source: https://docs.flutter.dev/testing/native-debugging Output from the flutter create command showing project initialization, file count, and instructions for running the application. Includes links to Flutter documentation and the location of the main app code. ```bash Creating project my_app... Resolving dependencies in my_app... Got dependencies in my_app. Wrote 129 files. All done! You can find general documentation for Flutter at: https://docs.flutter.dev/ Detailed API documentation is available at: https://api.flutter.dev/ If you prefer video documentation, consider: https://www.youtube.com/c/flutterdev In order to run your application, type: $ cd my_app $ flutter run Your application code is in my_app/lib/main.dart. ``` -------------------------------- ### Example output from LoggingActionDispatcher Source: https://docs.flutter.dev/ui/interactivity/actions-and-shortcuts This is an example of the console output generated when an action is invoked using the LoggingActionDispatcher. It displays the action, intent, and context. ```text flutter: Action invoked: SelectAllAction#906fc(SelectAllIntent#a98e3) from Builder(dependencies: _[ActionsMarker]) ``` -------------------------------- ### Install required system libraries for Linux distribution Source: https://docs.flutter.dev/platform-integration/linux/building Command to install the GTK and system libraries required for running Flutter Linux apps on the target system. ```bash $ sudo apt-get install libgtk-3-0 libblkid1 liblzma5 ``` -------------------------------- ### Run Android unit tests via Gradle Source: https://docs.flutter.dev/testing/testing-plugins Execute this command in the example/android directory. Ensure the example application is built at least once before running. ```sh ./gradlew testDebugUnitTest ``` -------------------------------- ### Example Output for Android Device Test Source: https://docs.flutter.dev/testing/integration-tests This shows the expected output when running integration tests on an Android device. ```bash $ flutter test integration_test/app_test.dart 00:04 +0: loading /path/to/counter_app/integration_test/app_test.dart 00:15 +0: loading /path/to/counter_app/integration_test/app_test.dart 00:18 +0: loading /path/to/counter_app/integration_test/app_test.dart 2,387ms Installing build/app/outputs/flutter-apk/app.apk... 612ms 00:21 +1: All tests passed! ``` -------------------------------- ### Verify Android emulator and device setup Source: https://docs.flutter.dev/platform-integration/android/setup Run this combined command to confirm that both emulators and physical devices are correctly recognized by Flutter. It helps validate your setup. ```bash $ flutter emulators && flutter devices ``` -------------------------------- ### Install Codemagic CLI tools Source: https://docs.flutter.dev/deployment/macos Installs the necessary command-line utilities for automating App Store Connect operations via pip. ```bash pip3 install codemagic-cli-tools ``` -------------------------------- ### Add Flutter Post-Install Hook to iOS Podfile Source: https://docs.flutter.dev/add-to-app/ios/project-setup Include the `flutter_post_install` method in your Podfile's `post_install` block. This hook performs additional setup required after CocoaPods finishes installing. ```ruby post_install do |installer| flutter_post_install(installer) if defined?(flutter_post_install) end ``` -------------------------------- ### Install Flutter Extension with Auto-Update Source: https://docs.flutter.dev/ai/gemini-cli-extension Installs the Flutter extension and configures it to automatically receive future updates. ```bash gemini extensions install https://github.com/gemini-cli-extensions/flutter.git --auto-update ``` -------------------------------- ### Desktop integration test results by platform Source: https://docs.flutter.dev/testing/integration-tests Example outputs for Windows, macOS, and Linux showing dependency resolution, device selection, and test completion. Note that Windows paths use backslashes while macOS and Linux use forward slashes. ```text PS C:\path\to\counter_app> flutter test .\integration_test\app_test.dart Resolving dependencies... Downloading packages... flutter_lints 3.0.2 (4.0.0 available) leak_tracker 10.0.4 (10.0.5 available) leak_tracker_flutter_testing 3.0.3 (3.0.5 available) lints 3.0.0 (4.0.0 available) material_color_utilities 0.8.0 (0.11.1 available) meta 1.12.0 (1.15.0 available) test_api 0.7.0 (0.7.1 available) vm_service 14.2.1 (14.2.2 available) Got dependencies! 8 packages have newer versions incompatible with dependency constraints. Try `flutter pub outdated` for more information. Connected devices: Windows (desktop) • windows • windows-x64 • Microsoft Windows [Version 10.0.22631.3593] Chrome (web) • chrome • web-javascript • Google Chrome 124.0.6367.207 Edge (web) • edge • web-javascript • Microsoft Edge 124.0.2478.97 [1]: Windows (windows) [2]: Chrome (chrome) [3]: Edge (edge) Please choose one (or "q" to quit): 1 00:00 +0: loading C:/path/to/counter_app/integration_test/app_test.dart B 00:29 +0: loading C:/path/to/counter_app/counter_app/integration_test/app_test.dart 29.1s √ Built build\windows\x64\runner\Debug\counter_app.exe 00:31 +1: All tests passed! ``` ```text $ flutter test integration_test Resolving dependencies... Downloading packages... flutter_lints 3.0.2 (4.0.0 available) > leak_tracker 10.0.4 (was 10.0.0) (10.0.5 available) > leak_tracker_flutter_testing 3.0.3 (was 2.0.1) (3.0.5 available) > leak_tracker_testing 3.0.1 (was 2.0.1) lints 3.0.0 (4.0.0 available) material_color_utilities 0.8.0 (0.11.1 available) > meta 1.12.0 (was 1.11.0) (1.15.0 available) > test_api 0.7.0 (was 0.6.1) (0.7.1 available) > vm_service 14.2.1 (was 13.0.0) (14.2.2 available) Changed 6 dependencies! 8 packages have newer versions incompatible with dependency constraints. Try `flutter pub outdated` for more information. Connected devices: macOS (desktop) • macos • darwin-arm64 • macOS 14.4.1 23E224 darwin-arm64 Mac Designed for iPad (desktop) • mac-designed-for-ipad • darwin • macOS 14.4.1 23E224 darwin-arm64 Chrome (web) • chrome • web-javascript • Google Chrome 124.0.6367.208 No wireless devices were found. [1]: macOS (macos) [2]: Mac Designed for iPad (mac-designed-for-ipad) [3]: Chrome (chrome) Please choose one (or "q" to quit): 1 00:01 +0: loading /path/to/counter_app/integration_test/app_test.dart R 00:02 +0: loading /path/to/counter_app/integration_test/app_test.dart 846ms 00:03 +0: loading /path/to/counter_app/integration_test/app_test.dart B Building macOS application... ✓ Built build/macos/Build/Products/Debug/counter_app.app 00:32 +1: All tests passed! ``` ```text $ flutter test integration_test/app_test.dart Connected devices: Linux (desktop) • linux • linux-x64 • Ubuntu 22.04.4 LTS 6.5.0-35-generic Chrome (web) • chrome • web-javascript • Google Chrome 104.0.5112.101 [1]: Linux (linux) [2]: Chrome (chrome) Please choose one (or "q" to quit): 1 00:00 +0: /path/to/counter_app/integration_test/app_test.dart B 00:16 +0: /path/to/counter_app/integration_test/app_test.dart ✓ Built build/linux/x64/debug/bundle/counter_app ``` -------------------------------- ### Example Output for iOS Device Test Source: https://docs.flutter.dev/testing/integration-tests This shows the expected output when running integration tests on an iOS device. ```bash $ flutter test integration_test/app_test.dart 00:04 +0: loading /path/to/counter_app/integration_test/app_test.dart 00:15 +0: loading /path/to/counter_app/integration_test/app_test.dart 00:18 +0: loading /path/to/counter_app/integration_test/app_test.dart 2,387ms Xcode build done. 13.5s 00:21 +1: All tests passed! ``` -------------------------------- ### Install Xcode command-line tools on macOS Source: https://docs.flutter.dev/install/with-vs-code Installs the command-line utilities required by Flutter, including Git, on macOS. ```bash $ xcode-select --install ``` -------------------------------- ### Create a stateful SetupFlow widget Source: https://docs.flutter.dev/cookbook/effects/nested-nav Define a stateful widget that accepts a route name parameter to manage the nested setup flow navigation. The SetupFlowState class handles the nested navigation logic for the setup flow pages. ```dart class SetupFlow extends StatefulWidget { const SetupFlow({super.key, required this.setupPageRoute}); final String setupPageRoute; @override State createState() => SetupFlowState(); } class SetupFlowState extends State { //... } ``` -------------------------------- ### Default Page Transition with MaterialApp on Android Source: https://docs.flutter.dev/release/breaking-changes/default-android-page-transition This example shows a basic MaterialApp setup where no page transition is explicitly given, allowing the default PredictiveBackPageTransitionsBuilder to be applied on Android. ```dart MaterialApp( theme: ThemeData( brightness: Brightness.light, ), home: const PageOne(), ); ``` -------------------------------- ### Run Windows unit tests via GoogleTest Source: https://docs.flutter.dev/testing/testing-plugins Run in the example directory. Replace "my_plugin" with your actual plugin project name and "Debug" with "Release" if applicable. ```sh build/windows/plugins/my_plugin/Debug/my_plugin_test.exe ``` -------------------------------- ### PanGestureRecognizer without addPointerPanZoom Source: https://docs.flutter.dev/release/breaking-changes/trackpad-gestures This example shows a `PanGestureRecognizer` setup that will not receive pan gesture callbacks when a trackpad is scrolled, as `recognizer.addPointerPanZoom` is not called. ```dart void main() => runApp(Foo()); class Foo extends StatefulWidget { late final PanGestureRecognizer recognizer; @override void initState() { super.initState(); recognizer = PanGestureRecognizer() ..onStart = _onPanStart ..onUpdate = _onPanUpdate ..onEnd = _onPanEnd; } void _onPanStart(DragStartDetails details) { debugPrint('onStart'); } void _onPanUpdate(DragUpdateDetails details) { debugPrint('onUpdate'); } void _onPanEnd(DragEndDetails details) { debugPrint('onEnd'); } @override Widget build(BuildContext context) { return Listener( onPointerDown: recognizer.addPointer, // recognizer.addPointerPanZoom is not called child: Container() ); } } ``` -------------------------------- ### Set up a Flutter project for web Source: https://docs.flutter.dev/platform-integration/web/building Create a new project with web support or add web capabilities to an existing directory. ```bash $ flutter create my_app ``` ```bash $ flutter create . --platforms web ``` -------------------------------- ### Install Flutter and CocoaPods dependencies Source: https://docs.flutter.dev/deployment/macos Fetches Dart packages and installs the necessary CocoaPods dependencies for the macOS project. ```bash flutter packages pub get ``` ```bash find . -name "Podfile" -execdir pod install \; ``` -------------------------------- ### Install ChromeDriver using Puppeteer Browsers Source: https://docs.flutter.dev/testing/integration-tests Install ChromeDriver to enable web testing. This command uses the `@puppeteer/browsers` Node library for simplified installation. ```bash $ npx @puppeteer/browsers install chromedriver@stable ``` -------------------------------- ### Initialize Repository and Service in main Source: https://docs.flutter.dev/app-architecture/design-patterns/key-value-data Demonstrates dependency injection by passing the service to the repository and the repository to the root app widget. ```dart void main() { // ··· runApp( MainApp( themeRepository: ThemeRepository(SharedPreferencesService()), // ··· ), ); } ``` -------------------------------- ### Initialize Firebase Hosting Source: https://docs.flutter.dev/deployment/web Initializes Firebase Hosting in your project, guiding you through configuration steps for your web app. ```bash firebase init hosting ``` -------------------------------- ### Create a Mac Installer Distribution certificate Source: https://docs.flutter.dev/deployment/macos Generates a new installer certificate if one does not already exist in the account. ```bash app-store-connect certificates create \ --type MAC_INSTALLER_DISTRIBUTION \ --certificate-key=@file:/path/to/cert_key \ --save ``` -------------------------------- ### Verify Flutter and Dart installation Source: https://docs.flutter.dev/install/add-to-path Run these commands to verify that the Flutter and Dart SDKs are correctly configured in your PATH. ```bash $ flutter --version $ dart --version ``` ```bash $ flutter --version $ dart --version ``` -------------------------------- ### Install command line tools on macOS Source: https://docs.flutter.dev/install/quick Triggers the installation of Xcode Command Line Tools, which provides Git and other necessary utilities for macOS development. ```bash $ xcode-select --install ``` -------------------------------- ### SpringDescription.withDampingRatio constructor migration example Source: https://docs.flutter.dev/release/breaking-changes/spring-description-underdamped Demonstrates the SpringDescription.withDampingRatio constructor before and after applying the migration steps to adjust parameters. ```dart const spring = SpringDescription.withDampingRatio( mass: 5.0, stiffness: 6.0, damping: 0.03, ); ``` ```dart const spring = SpringDescription.withDampingRatio( mass: 1, stiffness: 1.87392, ratio: 0.60017287468545, ); ``` -------------------------------- ### Install prerequisite packages on ChromeOS Source: https://docs.flutter.dev/install/with-vs-code Updates the package list and installs essential dependencies for Flutter on ChromeOS. ```bash $ sudo apt-get update -y && sudo apt-get upgrade -y $ sudo apt-get install -y curl git unzip xz-utils zip libglu1-mesa ``` -------------------------------- ### Complete Widget Test Example with Finder and Matcher Source: https://docs.flutter.dev/cookbook/testing/widget/introduction This comprehensive example demonstrates a full Flutter widget test, including widget creation, finding widgets by text, and verifying their presence using `findsOneWidget`. It also includes the `MyWidget` definition. ```dart import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { // Define a test. The TestWidgets function also provides a WidgetTester // to work with. The WidgetTester allows building and interacting // with widgets in the test environment. testWidgets('MyWidget has a title and message', (tester) async { // Create the widget by telling the tester to build it. await tester.pumpWidget(const MyWidget(title: 'T', message: 'M')); // Create the Finders. final titleFinder = find.text('T'); final messageFinder = find.text('M'); // Use the `findsOneWidget` matcher provided by flutter_test to // verify that the Text widgets appear exactly once in the widget tree. expect(titleFinder, findsOneWidget); expect(messageFinder, findsOneWidget); }); } class MyWidget extends StatelessWidget { const MyWidget({super.key, required this.title, required this.message}); final String title; final String message; @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', home: Scaffold( appBar: AppBar(title: Text(title)), body: Center(child: Text(message)), ), ); } } ``` -------------------------------- ### Install Firebase CLI Source: https://docs.flutter.dev/deployment/web Installs or updates the Firebase CLI globally, required for interacting with Firebase services. ```bash npm install -g firebase-tools ``` -------------------------------- ### List Mac Installer Distribution certificates Source: https://docs.flutter.dev/deployment/macos Retrieves and saves existing installer certificates from App Store Connect to the local machine. ```bash app-store-connect certificates list \ --type MAC_INSTALLER_DISTRIBUTION \ --certificate-key=@file:/path/to/cert_key \ --save ``` -------------------------------- ### Build deferred components app bundle Source: https://docs.flutter.dev/perf/deferred-components Builds the app bundle and validates the deferred components setup. ```bash $ flutter build appbundle ``` -------------------------------- ### Initialize app entry points in Compose and Flutter Source: https://docs.flutter.dev/flutter-for/compose-devs Compose uses ComponentActivity as the entry point, while Flutter uses the runApp function to start the application. ```kotlin class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { SampleTheme { Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding -> Greeting( name = "Android", modifier = Modifier.padding(innerPadding) ) } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } ``` ```dart void main() { runApp(const MyApp()); } ``` -------------------------------- ### GitHub Action workflow for Microsoft Store publishing Source: https://docs.flutter.dev/deployment/windows Automates the installation of the MS Store CLI, configuration with Azure AD credentials, and the packaging/publishing of MSIX files. ```yaml - uses: microsoft/setup-msstore-cli@v1 - name: Configure the Microsoft Store CLI run: msstore reconfigure --tenantId $ --clientId $ --clientSecret $ --sellerId $ - name: Install Dart dependencies run: flutter pub get - name: Create MSIX package run: msstore package . - name: Publish MSIX to the Microsoft Store run: msstore publish -v ``` -------------------------------- ### Get Animation Status Notifications in Flutter Source: https://docs.flutter.dev/ui/animations/tutorial Use `addStatusListener()` to receive notifications about an animation's state changes. This example prints the current `AnimationStatus` to the console. ```dart class _LogoAppState extends State with SingleTickerProviderStateMixin { late Animation animation; late AnimationController controller; @override void initState() { super.initState(); controller = AnimationController( duration: const Duration(seconds: 2), vsync: this, ); animation = Tween(begin: 0, end: 300).animate(controller) ..addStatusListener((status) => print('$status')); controller.forward(); } // ... } ``` -------------------------------- ### Run Linux unit tests via GoogleTest Source: https://docs.flutter.dev/testing/testing-plugins Run in the example directory. Replace "my_plugin" with your actual plugin project name and "debug" with "release" if applicable. ```sh build/linux/plugins/x64/debug/my_plugin/my_plugin_test ``` -------------------------------- ### Build and install APKs from AAB Source: https://docs.flutter.dev/perf/deferred-components Generates an APK set from an AAB file and installs it on a connected device. The --local-testing flag enables local emulation of dynamic feature delivery. ```bash $ java -jar bundletool.jar build-apks --bundle=/build/app/outputs/bundle/release/app-release.aab --output=/app.apks --local-testing $ java -jar bundletool.jar install-apks --apks=/app.apks ``` -------------------------------- ### Start iOS Simulator Source: https://docs.flutter.dev/platform-integration/ios/setup Launch the iOS Simulator directly from the terminal for testing Flutter apps. ```bash $ open -a Simulator ``` -------------------------------- ### Shortest Retaining Path Example Source: https://docs.flutter.dev/tools/devtools/memory This example illustrates how DevTools calculates retained size, assigning it only to members of the shortest retaining path when an object has multiple retaining paths. ```text root -> a -> b -> c -> x root -> d -> e -> x (shortest retaining path to `x`) ``` -------------------------------- ### Initialize DatabaseService in main() Source: https://docs.flutter.dev/app-architecture/design-patterns/sql Configures the database factory based on the host platform. Use sqfliteFfiInit for desktop and the default factory for mobile. ```dart void main() { late DatabaseService databaseService; if (kIsWeb) { throw UnsupportedError('Platform not supported'); } else if (Platform.isLinux || Platform.isWindows || Platform.isMacOS) { // Initialize FFI SQLite sqfliteFfiInit(); databaseService = DatabaseService(databaseFactory: databaseFactoryFfi); } else { // Use default native SQLite databaseService = DatabaseService(databaseFactory: databaseFactory); } ​ runApp( MainApp( // ··· todoRepository: TodoRepository(database: databaseService), ), ); } ``` -------------------------------- ### Example Output of debugDumpFocusTree Source: https://docs.flutter.dev/testing/code-debugging This is an example of the console output generated by `debugDumpFocusTree()`, illustrating the detailed structure and state of a Flutter focus tree. ```text flutter: FocusManager#9d096 flutter: │ primaryFocus: FocusScopeNode#926dc(_ModalScopeState flutter: │ Focus Scope [PRIMARY FOCUS]) flutter: │ primaryFocusCreator: FocusScope ← PrimaryScrollController ← flutter: │ _ActionsScope ← Actions ← Builder ← PageStorage ← Offstage ← flutter: │ _ModalScopeStatus ← UnmanagedRestorationScope ← flutter: │ RestorationScope ← AnimatedBuilder ← flutter: │ _ModalScope-[LabeledGlobalKey<_ModalScopeState>#bd53e] flutter: │ ← Semantics ← _RenderTheaterMarker ← _EffectiveTickerMode ← flutter: │ TickerMode ← flutter: │ _OverlayEntryWidget-[LabeledGlobalKey<_OverlayEntryWidgetState>#89dd7] flutter: │ ← _Theater ← Overlay-[LabeledGlobalKey#52f82] ← flutter: │ UnmanagedRestorationScope ← ⋯ flutter: │ flutter: └─rootScope: FocusScopeNode#f4205(Root Focus Scope [IN FOCUS PATH]) flutter: │ IN FOCUS PATH flutter: │ focusedChildren: FocusScopeNode#a0d10(Navigator Scope [IN FOCUS flutter: │ PATH]) flutter: │ flutter: └─Child 1: FocusNode#088ec([IN FOCUS PATH]) flutter: │ context: Focus flutter: │ NOT FOCUSABLE flutter: │ IN FOCUS PATH flutter: │ flutter: └─Child 1: FocusNode#85f70(Shortcuts [IN FOCUS PATH]) flutter: │ context: Focus flutter: │ NOT FOCUSABLE flutter: │ IN FOCUS PATH flutter: │ flutter: └─Child 1: FocusNode#f0c18(Shortcuts [IN FOCUS PATH]) flutter: │ context: Focus flutter: │ NOT FOCUSABLE flutter: │ IN FOCUS PATH flutter: │ flutter: └─Child 1: FocusNode#0749f(Shortcuts [IN FOCUS PATH]) flutter: │ context: Focus flutter: │ NOT FOCUSABLE flutter: │ IN FOCUS PATH flutter: │ flutter: └─Child 1: _FocusTraversalGroupNode#28990(FocusTraversalGroup [IN FOCUS PATH]) flutter: │ context: Focus flutter: │ NOT FOCUSABLE flutter: │ IN FOCUS PATH flutter: │ flutter: └─Child 1: FocusNode#5b515(Shortcuts [IN FOCUS PATH]) flutter: │ context: Focus flutter: │ NOT FOCUSABLE flutter: │ IN FOCUS PATH flutter: │ flutter: └─Child 1: FocusScopeNode#a0d10(Navigator Scope [IN FOCUS PATH]) flutter: │ context: FocusScope flutter: │ IN FOCUS PATH flutter: │ focusedChildren: FocusScopeNode#926dc(_ModalScopeState flutter: │ Focus Scope [PRIMARY FOCUS]) flutter: │ flutter: └─Child 1: _FocusTraversalGroupNode#72c8a(FocusTraversalGroup [IN FOCUS PATH]) flutter: │ context: Focus flutter: │ NOT FOCUSABLE flutter: │ IN FOCUS PATH flutter: │ flutter: └─Child 1: FocusNode#eb709(Navigator [IN FOCUS PATH]) flutter: │ context: Focus flutter: │ IN FOCUS PATH flutter: │ flutter: └─Child 1: FocusScopeNode#926dc(_ModalScopeState Focus Scope [PRIMARY FOCUS]) flutter: │ context: FocusScope flutter: │ PRIMARY FOCUS flutter: │ flutter: └─Child 1: FocusNode#a6b74 flutter: context: Focus ``` -------------------------------- ### Define Stateful Menu Widget in Dart Source: https://docs.flutter.dev/cookbook/effects/staggered-menu-animation Create a stateful Menu widget that displays a list of menu titles and a Get Started button in static locations. This serves as the base structure before adding animations. ```dart class Menu extends StatefulWidget { const Menu({super.key}); @override State createState() => _MenuState(); } class _MenuState extends State { static const _menuTitles = [ 'Declarative Style', 'Premade Widgets', 'Stateful Hot Reload', 'Native Performance', 'Great Community', ]; @override Widget build(BuildContext context) { return Container( color: Colors.white, child: Stack( fit: StackFit.expand, children: [_buildFlutterLogo(), _buildContent()], ), ); } Widget _buildFlutterLogo() { // TODO: We'll implement this later. return Container(); } Widget _buildContent() { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 16), ..._buildListItems(), const Spacer(), _buildGetStartedButton(), ], ); } List _buildListItems() { final listItems = []; for (var i = 0; i < _menuTitles.length; ++i) { listItems.add( Padding( padding: const EdgeInsets.symmetric(horizontal: 36, vertical: 16), child: Text( _menuTitles[i], textAlign: TextAlign.left, style: const TextStyle(fontSize: 24, fontWeight: FontWeight.w500), ), ), ); } return listItems; } Widget _buildGetStartedButton() { return SizedBox( width: double.infinity, child: Padding( padding: const EdgeInsets.all(24), child: ElevatedButton( style: ElevatedButton.styleFrom( shape: const StadiumBorder(), backgroundColor: Colors.blue, padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 14), ), onPressed: () {}, child: const Text( 'Get Started', style: TextStyle(color: Colors.white, fontSize: 22), ), ), ), ); } } ``` -------------------------------- ### Install UPower developer headers Source: https://docs.flutter.dev/platform-integration/platform-channels Required dependency for accessing battery information on Linux systems. ```bash sudo apt install libupower-glib-dev ``` -------------------------------- ### Create a new Flutter project with desktop support Source: https://docs.flutter.dev/desktop Initializes a new Flutter application directory with support for all enabled platforms including desktop. ```bash $ flutter create my_app $ cd my_app ``` -------------------------------- ### Draw on Canvas with React Native (Third-Party Library) Source: https://docs.flutter.dev/flutter-for/react-native-devs This example illustrates drawing on a canvas in React Native using a third-party library like react-native-canvas. It shows how to get a 2D context and perform drawing operations. ```js // React Native const CanvasComp = () => { const handleCanvas = (canvas) => { const ctx = canvas.getContext('2d'); ctx.fillStyle = 'skyblue'; ctx.beginPath(); ctx.arc(75, 75, 50, 0, 2 * Math.PI); ctx.fillRect(150, 100, 300, 300); ctx.stroke(); }; return ( ); } ``` -------------------------------- ### Windows build output Source: https://docs.flutter.dev/testing/native-debugging Example output from building a Flutter Windows application showing successful build completion and executable location. ```text Building Windows application... 31.4s √ Built build\windows\runner\Debug\my_app.exe. ``` -------------------------------- ### Install CocoaPods and Configure Post-Clone Script Source: https://docs.flutter.dev/deployment/cd Shell script to install CocoaPods dependencies in the ios directory. Must be added to git repository and marked as executable using chmod +x. ```bash # Install CocoaPods dependencies. cd ios && pod install # run `pod install` in the `ios` directory. exit 0 ``` ```bash $ git add --chmod=+x ios/ci_scripts/ci_post_clone.sh ``` -------------------------------- ### Install Rosetta 2 on Apple Silicon Source: https://docs.flutter.dev/platform-integration/ios/setup Install Rosetta 2 on Apple Silicon (ARM) Macs for compatibility with certain software. ```bash $ sudo softwareupdate --install-rosetta --agree-to-license ``` -------------------------------- ### Install iOS Dependencies Source: https://docs.flutter.dev/platform-integration/ios/ios-app-clip Execute these commands in the iOS directory to update project dependencies after Podfile changes. ```shell cd ios pod install ``` -------------------------------- ### Code before and after migration in Dart Source: https://docs.flutter.dev/release/breaking-changes/template Template examples showing code structure before and after a breaking change migration. Replace with actual code examples relevant to the specific breaking change. ```dart // Example of code before the change. ``` ```dart // Example of code after the change. ``` -------------------------------- ### Start Flutter application for debugging Source: https://docs.flutter.dev/tools/devtools/cli Navigate to a Flutter project directory and run the app with flutter run. Requires a connected device or open simulator. ```bash cd path/to/flutter/app flutter run ``` -------------------------------- ### flutter bash-completion Source: https://docs.flutter.dev/reference/flutter-cli Output command line shell completion setup scripts. ```APIDOC ## COMMAND flutter bash-completion ### Description Output command line shell completion setup scripts. ### Usage `flutter bash-completion` ### Arguments N/A ### Request Example N/A ### Response #### Success Response (0) - **Output** (string) - Shell completion script content. #### Response Example N/A ``` -------------------------------- ### Initialize and restore the keychain Source: https://docs.flutter.dev/deployment/macos Sets up a temporary keychain for signing and provides the command to restore the login keychain as default. ```bash keychain initialize ``` ```bash keychain use-login ``` -------------------------------- ### Create project directory structure Source: https://docs.flutter.dev/learn/pathway/tutorial/advanced-ui Organize the project by creating `data`, `screens`, and `theme` subdirectories within the `lib` folder. ```bash $ cd rolodex $ mkdir lib/data lib/screens lib/theme ``` -------------------------------- ### Install CocoaPods dependencies Source: https://docs.flutter.dev/add-to-app/ios/project-setup?tab=embed-using-cocoapods Execute this command in the iOS project directory to embed Flutter frameworks and plugins. Always open the .xcworkspace file in Xcode after installation. ```shell pod install ``` -------------------------------- ### Install iOS Pods with Flutter Dependencies Source: https://docs.flutter.dev/add-to-app/ios/project-setup Execute `pod install` in your iOS app project directory. This command integrates the Flutter frameworks and plugins into your Xcode project. ```bash pod install ``` -------------------------------- ### Complete Flutter Camera Application Source: https://docs.flutter.dev/cookbook/plugins/picture-using-camera This comprehensive example demonstrates how to set up a Flutter app to access the device camera, display a preview, capture an image, and then show the captured image on a new screen. ```dart import 'dart:async'; import 'dart:io'; import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; Future main() async { // Ensure that plugin services are initialized so that `availableCameras()` // can be called before `runApp()` WidgetsFlutterBinding.ensureInitialized(); // Obtain a list of the available cameras on the device. final cameras = await availableCameras(); // Get a specific camera from the list of available cameras. final firstCamera = cameras.first; runApp( MaterialApp( theme: ThemeData.dark(), home: TakePictureScreen( // Pass the appropriate camera to the TakePictureScreen widget. camera: firstCamera, ), ), ); } // A screen that allows users to take a picture using a given camera. class TakePictureScreen extends StatefulWidget { const TakePictureScreen({super.key, required this.camera}); final CameraDescription camera; @override TakePictureScreenState createState() => TakePictureScreenState(); } class TakePictureScreenState extends State { late CameraController _controller; late Future _initializeControllerFuture; @override void initState() { super.initState(); // To display the current output from the Camera, // create a CameraController. _controller = CameraController( // Get a specific camera from the list of available cameras. widget.camera, // Define the resolution to use. ResolutionPreset.medium, ); // Next, initialize the controller. This returns a Future. _initializeControllerFuture = _controller.initialize(); } @override void dispose() { // Dispose of the controller when the widget is disposed. _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Take a picture')), // You must wait until the controller is initialized before displaying the // camera preview. Use a FutureBuilder to display a loading spinner until the // controller has finished initializing. body: FutureBuilder( future: _initializeControllerFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { // If the Future is complete, display the preview. return CameraPreview(_controller); } else { // Otherwise, display a loading indicator. return const Center(child: CircularProgressIndicator()); } }, ), floatingActionButton: FloatingActionButton( // Provide an onPressed callback. onPressed: () async { // Take the Picture in a try / catch block. If anything goes wrong, // catch the error. try { // Ensure that the camera is initialized. await _initializeControllerFuture; // Attempt to take a picture and get the file `image` // where it was saved. final image = await _controller.takePicture(); if (!context.mounted) return; // If the picture was taken, display it on a new screen. await Navigator.of(context).push( MaterialPageRoute( builder: (context) => DisplayPictureScreen( // Pass the automatically generated path to // the DisplayPictureScreen widget. imagePath: image.path, ), ), ); } catch (e) { // If an error occurs, log the error to the console. print(e); } }, child: const Icon(Icons.camera_alt), ), ); } } // A widget that displays the picture taken by the user. class DisplayPictureScreen extends StatelessWidget { final String imagePath; const DisplayPictureScreen({super.key, required this.imagePath}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Display the Picture')), // The image is stored as a file on the device. Use the `Image.file` // constructor with the given path to display the image. body: Image.file(File(imagePath)), ); } } ``` -------------------------------- ### Initialize a SwiftUI App Source: https://docs.flutter.dev/flutter-for/swiftui-devs Use the `App` protocol and `@main` attribute to define the entry point for a SwiftUI application. The `WindowGroup` specifies the root view for the app's window. ```swift @main struct MyApp: App { var body: some Scene { WindowGroup { HomePage() } } } ``` -------------------------------- ### Complete Flutter app with Isolate example Source: https://docs.flutter.dev/flutter-for/android-devs Full working example demonstrating a Flutter app that loads JSON data from a network endpoint using an Isolate for background processing and updates the UI with the results. ```dart import 'dart:async'; import 'dart:convert'; import 'dart:isolate'; ​ import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; ​ void main() { runApp(const SampleApp()); } ​ class SampleApp extends StatelessWidget { const SampleApp({super.key}); ​ @override Widget build(BuildContext context) { return MaterialApp( title: 'Sample App', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: const SampleAppPage(), ); } } ​ class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); ​ @override State createState() => _SampleAppPageState(); } ​ class _SampleAppPageState extends State { List> widgets = []; ​ @override void initState() { super.initState(); loadData(); } ​ Widget getBody() { bool showLoadingDialog = widgets.isEmpty; if (showLoadingDialog) { return getProgressDialog(); } else { return getListView(); } } ​ Widget getProgressDialog() { ``` -------------------------------- ### Initialize requirements.md using Gemini Source: https://docs.flutter.dev/ai/best-practices/developer-experience Use this prompt to initialize the project requirements by providing a high-level description and requesting a requirements.md file. ```text I'd like to create a file called requirements.md in the plans folder at the root of the project. here's a description of the project: The application will be an open-source sample hosted on GitHub in the flutter/demos directory. It aims to demonstrate the use of Flutter, Firebase AI Logic, and Gemini to produce an agentic workflow that can solve a small crossword puzzle (one with a size under 10x10)....lots more description of the app along with a sample puzzle screenshot... Ask any questions you may have before you get started. ``` -------------------------------- ### Install prerequisite packages on Linux and ChromeOS Source: https://docs.flutter.dev/install/quick Updates the package manager and installs essential dependencies like curl, git, and GLU libraries for Debian-based distributions. ```bash $ sudo apt-get update -y && sudo apt-get upgrade -y $ sudo apt-get install -y curl git unzip xz-utils zip libglu1-mesa ``` ```bash $ sudo apt-get update -y && sudo apt-get upgrade -y $ sudo apt-get install -y curl git unzip xz-utils zip libglu1-mesa ``` -------------------------------- ### Complete Flutter pubspec.yaml Example Source: https://docs.flutter.dev/tools/pubspec A full example of a Flutter project pubspec file showing all common Flutter-specific fields including dependencies, assets, fonts, and localization configuration. This is the standard structure generated by flutter create. ```yaml name: description: A new Flutter project. publish_to: none version: 1.0.0+1 environment: sdk: ^3.11.0 dependencies: flutter: # Required for every Flutter project sdk: flutter # Required for every Flutter project flutter_localizations: # Required to enable localization sdk: flutter # Required to enable localization cupertino_icons: ^1.0.8 # Only required if you use Cupertino (iOS style) icons dev_dependencies: flutter_test: sdk: flutter # Required for a Flutter project that includes tests flutter_lints: ^6.0.0 # Contains a set of recommended lints for Flutter code flutter: uses-material-design: true # Required if you use the Material icon font generate: true # Enables generation of localized strings from arb files config: # App-specific configuration flags that mirror `flutter config` enable-swift-package-manager: true assets: # Lists assets, such as image files - images/a_dot_burr.png - images/a_dot_ham.png licenses: # Lists additional license files to be bundled with the app - assets/my_license.txt fonts: # Required if your app uses custom fonts - family: Schyler fonts: - asset: fonts/Schyler-Regular.ttf - asset: fonts/Schyler-Italic.ttf style: italic - family: Trajan Pro fonts: - asset: fonts/TrajanPro.ttf - asset: fonts/TrajanPro_Bold.ttf weight: 700 ``` -------------------------------- ### Configure Xcode Command-Line Tools Source: https://docs.flutter.dev/platform-integration/ios/setup Run this command to configure Xcode command-line tools to use the installed Xcode version. Adjust the path if Xcode is installed elsewhere. ```bash $ sudo sh -c 'xcode-select -s /Applications/Xcode.app/Contents/Developer && xcodebuild -runFirstLaunch' ``` -------------------------------- ### Initialize LlmChatView with a welcome message Source: https://docs.flutter.dev/ai/ai-toolkit/feature-integration Use the welcomeMessage parameter to display an initial greeting to users when the chat session starts. ```dart class ChatPage extends StatelessWidget { const ChatPage({super.key}); ​ @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text(App.title)), body: LlmChatView( welcomeMessage: 'Hello and welcome to the Flutter AI Toolkit!', provider: FirebaseProvider( model: FirebaseAI.geminiAI().generativeModel( model: 'gemini-2.5-flash', ), ), ), ); } ``` -------------------------------- ### Initial Flutter App Structure Source: https://docs.flutter.dev/tools/hot-reload A standard Flutter application setup with a StatelessWidget root widget used to demonstrate hot reload behavior. ```dart import 'package:flutter/material.dart'; ​ void main() { runApp(MyApp()); } ​ class MyApp extends StatelessWidget { const MyApp({super.key}); ​ @override Widget build(BuildContext context) { return GestureDetector(onTap: () => print('tapped')); } } ``` -------------------------------- ### Validate Windows development setup Source: https://docs.flutter.dev/platform-integration/windows/setup Commands to check for toolchain issues and verify that Flutter can detect Windows devices. ```bash $ flutter doctor -v ``` ```bash $ flutter devices ``` -------------------------------- ### Initialize YouTube API and list playlist items in Dart Source: https://docs.flutter.dev/data-and-backend/google-apis Instantiate the API with an authenticated client. The example shows fetching the 'Liked List' playlist items. ```dart final youTubeApi = YouTubeApi(authenticatedClient); final favorites = await youTubeApi.playlistItems.list( ['snippet'], playlistId: 'LL', // Liked List ); ``` -------------------------------- ### Legacy android/build.gradle configuration Source: https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply Example of a build.gradle file using the legacy buildscript block to define AGP and Kotlin versions before migration. ```groovy buildscript { ext.kotlin_version = '1.7.10' repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.3.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } allprojects { repositories { google() mavenCentral() } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } tasks.register("clean", Delete) { delete rootProject.buildDir } ``` -------------------------------- ### Initialize AudioRecorder Source: https://docs.flutter.dev/cookbook/audio/record Import the package and create an instance of the AudioRecorder class to manage recording. ```dart import 'package:record/record.dart'; final recorder = AudioRecorder(); ``` -------------------------------- ### iOS App Thinning Size Report example Source: https://docs.flutter.dev/perf/app-size Sample output from an Xcode App Thinning Size Report showing compressed and uncompressed sizes for specific device variants running iOS 13.0. This example is from the default Flutter demo app in version 1.17. ```text Variant: Runner-7433FC8E-1DF4-4299-A7E8-E00768671BEB.ipa Supported variant descriptors: [device: iPhone12,1, os-version: 13.0] and [device: iPhone11,8, os-version: 13.0] App + On Demand Resources size: 5.4 MB compressed, 13.7 MB uncompressed App size: 5.4 MB compressed, 13.7 MB uncompressed On Demand Resources size: Zero KB compressed, Zero KB uncompressed ``` -------------------------------- ### Add flutter_soloud package dependency Source: https://docs.flutter.dev/cookbook/audio/soloud Install the flutter_soloud package using the Flutter CLI. ```bash $ flutter pub add flutter_soloud ``` -------------------------------- ### Build snap with Multipass backend Source: https://docs.flutter.dev/deployment/linux Run snapcraft from the project root directory using the default Multipass VM backend to build the snap. ```bash $ snapcraft ``` -------------------------------- ### Flutter Render Tree Output Example Source: https://docs.flutter.dev/testing/code-debugging Example output from debugDumpRenderTree() showing the hierarchical structure of render objects. Examine the constraints and size fields to understand how layout constraints flow down and sizes flow back up the tree. ```text flutter: RenderView#02c80 flutter: │ debug mode enabled - macos flutter: │ view size: Size(800.0, 600.0) (in physical pixels) flutter: │ device pixel ratio: 1.0 (physical pixels per logical pixel) flutter: │ configuration: Size(800.0, 600.0) at 1.0x (in logical pixels) flutter: │ flutter: └─child: RenderSemanticsAnnotations#fe6b5 flutter: │ needs compositing flutter: │ creator: Semantics ← _FocusInheritedScope ← Focus ← flutter: │ HeroControllerScope ← ScrollConfiguration ← MaterialApp ← flutter: │ MediaQuery ← _MediaQueryFromView ← _ViewScope ← flutter: │ View-[GlobalObjectKey FlutterView#6cffa] ← [root] flutter: │ parentData: flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ flutter: └─child: RenderSemanticsAnnotations#6edef flutter: │ needs compositing flutter: │ creator: Semantics ← _FocusInheritedScope ← Focus ← Shortcuts ← flutter: │ _SharedAppModel ← SharedAppData ← UnmanagedRestorationScope ← flutter: │ RestorationScope ← UnmanagedRestorationScope ← flutter: │ RootRestorationScope ← WidgetsApp-[GlobalObjectKey flutter: │ _MaterialAppState#5c303] ← Semantics ← ⋯ flutter: │ parentData: (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ flutter: └─child: RenderSemanticsAnnotations#e8ce8 flutter: │ needs compositing flutter: │ creator: Semantics ← _FocusInheritedScope ← Focus ← Shortcuts ← flutter: │ DefaultTextEditingShortcuts ← Semantics ← _FocusInheritedScope flutter: │ ← Focus ← Shortcuts ← _SharedAppModel ← SharedAppData ← flutter: │ UnmanagedRestorationScope ← ⋯ flutter: │ parentData: (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ flutter: └─child: RenderSemanticsAnnotations#fc545 flutter: │ needs compositing flutter: │ creator: Semantics ← _FocusInheritedScope ← Focus ← Shortcuts ← flutter: │ Semantics ← _FocusInheritedScope ← Focus ← Shortcuts ← flutter: │ DefaultTextEditingShortcuts ← Semantics ← _FocusInheritedScope flutter: │ ← Focus ← ⋯ flutter: │ parentData: (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ flutter: └─child: RenderTapRegionSurface#ff857 flutter: │ needs compositing flutter: │ creator: TapRegionSurface ← _FocusInheritedScope ← Focus ← flutter: │ FocusTraversalGroup ← _ActionsScope ← Actions ← Semantics ← flutter: │ _FocusInheritedScope ← Focus ← Shortcuts ← Semantics ← flutter: │ _FocusInheritedScope ← ⋯ flutter: │ parentData: (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ behavior: deferToChild flutter: │ flutter: └─child: RenderSemanticsAnnotations#fe316 flutter: │ needs compositing flutter: │ creator: Semantics ← _FocusInheritedScope ← Focus ← Shortcuts ← flutter: │ _ShortcutRegistrarScope ← ShortcutRegistrar ← TapRegionSurface flutter: │ ← _FocusInheritedScope ← Focus ← FocusTraversalGroup ← flutter: │ _ActionsScope ← Actions ← ⋯ flutter: │ parentData: (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ flutter: └─child: RenderSemanticsAnnotations#fa55c flutter: │ needs compositing flutter: │ creator: Semantics ← Localizations ← Semantics ← flutter: │ _FocusInheritedScope ← Focus ← Shortcuts ← flutter: │ _ShortcutRegistrarScope ← ShortcutRegistrar ← TapRegionSurface flutter: │ ← _FocusInheritedScope ← Focus ← FocusTraversalGroup ← ⋯ flutter: │ parentData: (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) ``` -------------------------------- ### Install games_services package Source: https://docs.flutter.dev/cookbook/games/achievements-leaderboard Add the games_services dependency to your Flutter project via the command line. ```shell $ flutter pub add games_services ``` -------------------------------- ### Run integration tests on desktop platforms Source: https://docs.flutter.dev/testing/integration-tests Execute this command from the project root to initiate integration tests. You may be prompted to select a specific desktop platform if multiple devices are available. ```bash $ flutter test integration_test/app_test.dart ``` -------------------------------- ### Example Output for Flutter Drive on Chrome Source: https://docs.flutter.dev/testing/integration-tests This shows the expected output when running Flutter Drive integration tests on the Chrome browser. ```bash Resolving dependencies... leak_tracker 10.0.0 (10.0.5 available) leak_tracker_flutter_testing 2.0.1 (3.0.5 available) leak_tracker_testing 2.0.1 (3.0.1 available) material_color_utilities 0.8.0 (0.11.1 available) meta 1.11.0 (1.14.0 available) test_api 0.6.1 (0.7.1 available) vm_service 13.0.0 (14.2.1 available) Got dependencies! 7 packages have newer versions incompatible with dependency constraints. Try `flutter pub outdated` for more information. Launching integration_test/app_test.dart on Chrome in debug mode... Waiting for connection from debug service on Chrome... 10.9s This app is linked to the debug service: ws://127.0.0.1:51523/3lofIjIdmbs=/ws Debug service listening on ws://127.0.0.1:51523/3lofIjIdmbs=/ws 00:00 +0: end-to-end test tap on the floating action button, verify counter 00:01 +1: (tearDownAll) 00:01 +2: All tests passed! All tests passed. Application finished. ``` -------------------------------- ### Flutter widget constructor example Source: https://docs.flutter.dev/tools/property-editor Example of a Text widget constructor where the Flutter Property Editor can be accessed by placing the cursor anywhere between the widget name and closing parenthesis. ```dart @override Widget build(BuildContext context) { return Text( 'Hello World!', overflow: TextOverflow.clip, ); } ``` -------------------------------- ### Complete Flutter Todo List Test Example Source: https://docs.flutter.dev/cookbook/testing/widget/tap-drag Full integration test demonstrating adding and removing todo items, including the TodoList widget implementation with Dismissible list items. This is a complete, runnable example showing the entire test flow and widget structure. ```dart import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; ​ void main() { testWidgets('Add and remove a todo', (tester) async { // Build the widget. await tester.pumpWidget(const TodoList()); ​ // Enter 'hi' into the TextField. await tester.enterText(find.byType(TextField), 'hi'); ​ // Tap the add button. await tester.tap(find.byType(FloatingActionButton)); ​ // Rebuild the widget with the new item. await tester.pump(); ​ // Expect to find the item on screen. expect(find.text('hi'), findsOneWidget); ​ // Swipe the item to dismiss it. await tester.drag(find.byType(Dismissible), const Offset(500, 0)); ​ // Build the widget until the dismiss animation ends. await tester.pumpAndSettle(); ​ // Ensure that the item is no longer on screen. expect(find.text('hi'), findsNothing); }); } ​ class TodoList extends StatefulWidget { const TodoList({super.key}); ​ @override State createState() => _TodoListState(); } ​ class _TodoListState extends State { static const _appTitle = 'Todo List'; final todos = []; final controller = TextEditingController(); ​ @override Widget build(BuildContext context) { return MaterialApp( title: _appTitle, home: Scaffold( appBar: AppBar(title: const Text(_appTitle)), body: Column( children: [ TextField(controller: controller), Expanded( child: ListView.builder( itemCount: todos.length, itemBuilder: (context, index) { final todo = todos[index]; ​ return Dismissible( key: Key('$todo$index'), onDismissed: (direction) => todos.removeAt(index), background: Container(color: Colors.red), child: ListTile(title: Text(todo)), ); }, ), ), ], ), floatingActionButton: FloatingActionButton( onPressed: () { setState(() { todos.add(controller.text); controller.clear(); }); }, child: const Icon(Icons.add), ), ), ); } } ``` -------------------------------- ### Complete Flutter App with Activity Launcher Source: https://docs.flutter.dev/platform-integration/android/compose-activity Full Flutter application demonstrating method channel setup, activity launching on button press, and basic UI with a floating action button. ```dart import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; // SECTION 1: START COPYING HERE const platformMethodChannel = MethodChannel( // Note: You can change this string value, but it must match // the `CHANNEL` attribute in the next step. 'com.example.flutter_android_activity', ); // SECTION 1: END COPYING HERE void main() { runApp(const MainApp()); } class MainApp extends StatelessWidget { const MainApp({super.key}); // SECTION 2: START COPYING HERE void _launchAndroidActivity() { platformMethodChannel.invokeMethod( // Note: You can change this value, but it must match // the `call.method` value in the next section. 'launchActivity', // Note: You can pass any primitive data types you like. // To pass complex types, use package:pigeon to generate // matching Dart and Kotlin classes that share serialization logic. {'message': 'Hello from Flutter'}, ); } // SECTION 2: END COPYING HERE @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: const Center(child: Text('Hello World!')), floatingActionButton: FloatingActionButton( // SECTION 3: Call `_launchAndroidActivity` somewhere. onPressed: _launchAndroidActivity, // SECTION 3: End tooltip: 'Launch Android activity', child: const Icon(Icons.launch), ), ), ); } } ``` -------------------------------- ### Navigate to Package Directory Source: https://docs.flutter.dev/packages-and-plugins/developing-packages Change to the package directory before running documentation or build commands. ```bash cd ~/dev/mypackage ``` -------------------------------- ### Configure Logging for genui in Dart Source: https://docs.flutter.dev/ai/genui/get-started This example shows how to enable and configure logging for the `genui` package within your `main` method to observe communication between your app and the agent. ```dart import 'package:logging/logging.dart'; import 'package:genui/genui.dart'; final logger = configureGenUiLogging(level: Level.ALL); void main() async { logger.onRecord.listen((record) { debugPrint('${record.loggerName}: ${record.message}'); }); // Additional initialization of bindings and Firebase. } ``` -------------------------------- ### Create a new Flutter project Source: https://docs.flutter.dev/testing/native-debugging?tab=from-vscode-to-xcode-ios Command to initialize a new Flutter application using the command-line interface. ```bash $ flutter create my_app ``` -------------------------------- ### Platform override setup for desktop in main() Source: https://docs.flutter.dev/release/breaking-changes/target-platform-linux-windows Legacy pattern for setting platform override on Linux and Windows before native support was added. This approach is no longer needed after the enum migration. ```dart // Sets a platform override for desktop to avoid exceptions. See // https://docs.flutter.dev/desktop#target-platform-override for more info. void _enablePlatformOverrideForDesktop() { if (!kIsWeb && (Platform.isWindows || Platform.isLinux)) { debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia; } } void main() { _enablePlatformOverrideForDesktop(); runApp(MyApp()); } ``` -------------------------------- ### Example flutter.version.json structure Source: https://docs.flutter.dev/release/breaking-changes/flutter-root-version-file Sample JSON structure of the new version metadata file containing framework, engine, and tooling version information. ```json { "frameworkVersion": "3.33.0-1.0.pre-1070", "channel": "master", "repositoryUrl": "unknown source", "frameworkRevision": "be9526fbaaaab9474e95d196b70c41297eeda2d0", "frameworkCommitDate": "2025-07-22 11:34:11 -0700", "engineRevision": "be9526fbaaaab9474e95d196b70c41297eeda2d0", "engineCommitDate": "2025-07-22 18:34:11.000Z", "engineContentHash": "70fb28dde094789120421d4e807a9c37a0131296", "engineBuildDate": "2025-07-22 11:47:42.829", "dartSdkVersion": "3.10.0 (build 3.10.0-15.0.dev)", "devToolsVersion": "2.48.0", "flutterVersion": "3.33.0-1.0.pre-1070" } ``` -------------------------------- ### Open the SQLite database Source: https://docs.flutter.dev/cookbook/persistence/sqlite Initialize the database connection. Ensure WidgetsFlutterBinding.ensureInitialized() is called if this runs before the app starts. ```dart // Avoid errors caused by flutter upgrade. // Importing 'package:flutter/widgets.dart' is required. WidgetsFlutterBinding.ensureInitialized(); // Open the database and store the reference. final database = openDatabase( // Set the path to the database. Note: Using the `join` function from the // `path` package is best practice to ensure the path is correctly // constructed for each platform. join(await getDatabasesPath(), 'doggie_database.db'), ); ``` -------------------------------- ### Install Flutter extension for Gemini CLI Source: https://docs.flutter.dev/ai/coding-assistants Install the Flutter extension for Gemini CLI to integrate Dart and Flutter MCP server with AI rules and commands for structured app changes. ```bash gemini extensions install https://github.com/gemini-cli-extensions/flutter ``` -------------------------------- ### SpringDescription default constructor migration example Source: https://docs.flutter.dev/release/breaking-changes/spring-description-underdamped Illustrates the SpringDescription default constructor before and after applying the migration formulas to adjust parameters. ```dart const spring = SpringDescription( mass: 20.0, stiffness: 10, damping: 1, ); ``` ```dart const spring = SpringDescription( mass: 1.0, stiffness: 100.499375, damping: 20, ); ``` -------------------------------- ### Launch DevTools from command line Source: https://docs.flutter.dev/tools/devtools/cli Start DevTools using the dart devtools command. Requires dart on your system path. ```bash Serving DevTools at http://127.0.0.1:9100 ``` -------------------------------- ### Windows Path environment variable entry Source: https://docs.flutter.dev/install/add-to-path Example path to add to the User variables Path entry on Windows. ```text %USERPROFILE%\develop\flutter\bin ``` ```text %USERPROFILE%\develop\flutter\bin ``` -------------------------------- ### Play audio stream Source: https://docs.flutter.dev/cookbook/audio/soloud Start playback of a configured audio stream. ```dart final handle = await SoLoud.instance.play(stream); ``` -------------------------------- ### Create a new Flutter project Source: https://docs.flutter.dev/deployment/flavors-ios Initializes a new Flutter project directory to serve as the base for flavor configuration. ```console $ flutter create flavors_example ``` -------------------------------- ### Review CupertinoTabBar code before migration Source: https://docs.flutter.dev/release/breaking-changes/cupertino-tab-bar-localizations Example of code that fails because it lacks a Localizations parent for the CupertinoTabBar. ```dart import 'package:flutter/cupertino.dart'; ​ void main() => runApp(Foo()); ​ class Foo extends StatelessWidget { @override Widget build(BuildContext context) { return MediaQuery( data: const MediaQueryData(), child: CupertinoTabBar( items: const [ BottomNavigationBarItem( icon: Icon(CupertinoIcons.add_circled), label: 'Tab 1', ), BottomNavigationBarItem( icon: Icon(CupertinoIcons.add_circled_solid), label: 'Tab 2', ), ], currentIndex: 1, ), ); } } ``` -------------------------------- ### Initialize a Flutter App Source: https://docs.flutter.dev/flutter-for/swiftui-devs Start a Flutter application by calling `runApp` with an instance of your main widget. This function inflates the given widget and attaches it to the screen. ```dart void main() { runApp(const MyApp()); } ``` -------------------------------- ### Create a new Flutter project Source: https://docs.flutter.dev/ui/internationalization Use this command to initialize a new Flutter project structure from the command line. ```bash $ flutter create ``` -------------------------------- ### Create Basic ArticleWidget Structure Source: https://docs.flutter.dev/learn/pathway/tutorial/listenable-builder Initialize the ArticleWidget with a summary parameter and placeholder text. This is the starting point for building the article display component. ```dart class ArticleWidget extends StatelessWidget { const ArticleWidget({super.key, required this.summary}); final Summary summary; @override Widget build(BuildContext context) { return Text('Article content will be displayed here'); } } ``` -------------------------------- ### Create a new Flutter project Source: https://docs.flutter.dev/platform-integration/ios/app-extensions Initializes a new Flutter application directory to serve as the host for the iOS extension. ```bash $ flutter create example_app_with_extension ``` -------------------------------- ### Build snap with LXD container backend Source: https://docs.flutter.dev/deployment/linux Run snapcraft with the --use-lxd flag to use LXD containers instead of Multipass VMs for the build environment. ```bash $ snapcraft --use-lxd ``` -------------------------------- ### Verify ChromeDriver Version Source: https://docs.flutter.dev/testing/integration-tests Run this command to confirm that ChromeDriver has been successfully installed and is accessible in your PATH. ```bash $ chromedriver --version ChromeDriver 124.0.6367.60 (8771130bd84f76d855ae42fbe02752b03e352f17-refs/branch-heads/6367@{#798}) ``` -------------------------------- ### Define ViewModel with Repository Dependencies (Dart) Source: https://docs.flutter.dev/app-architecture/case-study/ui-layer Illustrates the initial structure of a `HomeViewModel`, showing how to inject `BookingRepository` and `UserRepository` as required constructor arguments and assign them to private fields. ```dart class HomeViewModel { HomeViewModel({ required BookingRepository bookingRepository, required UserRepository userRepository, }) : // Repositories are manually assigned because they're private members. _bookingRepository = bookingRepository, _userRepository = userRepository; final BookingRepository _bookingRepository; final UserRepository _userRepository; // ... } ``` -------------------------------- ### Set up basic path prefix proxy rules Source: https://docs.flutter.dev/platform-integration/web/web-dev-config-file Use the prefix field for simple path matching and optional path replacement. ```yaml server: proxy: - target: "http://localhost:5000/" # Base URL of your backend prefix: "/users/" # Path - target: "http://localhost:3000/" prefix: "/data/" replace: "/report/" # Replacement of path in redirected URL (optional) - target: "http://localhost:4000/" prefix: "/products/" replace: "" ``` -------------------------------- ### Define Navigators in React Native Source: https://docs.flutter.dev/flutter-for/react-native-devs Example of defining `TabNavigator`, `StackNavigator`, and `DrawerNavigator` to structure app navigation in React Native. ```js // React Native const MyApp = TabNavigator( { Home: { screen: HomeScreen }, Notifications: { screen: tabNavScreen } }, { tabBarOptions: { activeTintColor: '#e91e63' } } ); const SimpleApp = StackNavigator({ Home: { screen: MyApp }, stackScreen: { screen: StackScreen } }); export default (MyApp1 = DrawerNavigator({ Home: { screen: SimpleApp }, Screen2: { screen: drawerScreen } })); ``` -------------------------------- ### Initialize Controllers and Adapters in ChatScreen Source: https://docs.flutter.dev/ai/genui/get-started Set up TextEditingController, SurfaceController with CoreCatalogItems, A2uiTransportAdapter, and A2uiAgentConnector in the _ChatScreenState class. These are required for managing UI state, message transport, and agent communication. ```dart class _ChatScreenState extends State { final TextEditingController _textController = TextEditingController(); final SurfaceController _surfaceController = SurfaceController(catalogs: [CoreCatalogItems.asCatalog()]); final A2uiTransportAdapter _transportAdapter = A2uiTransportAdapter(); late final Conversation _uiAgent; late final A2uiAgentConnector _connector; final List _messages = []; ``` -------------------------------- ### Fetch IP Address with Promise/Then Pattern Source: https://docs.flutter.dev/flutter-for/react-native-devs JavaScript example using fetch API with Promise chaining to retrieve IP address from httpbin.org. Demonstrates error handling with catch. ```javascript // JavaScript class Example { _getIPAddress() { const url = 'https://httpbin.org/ip'; return fetch(url) .then(response => response.json()) .then(responseJson => { const ip = responseJson.origin; return ip; }); } } function main() { const example = new Example(); example ._getIPAddress() .then(ip => console.log(ip)) .catch(error => console.error(error)); } main(); ``` -------------------------------- ### Install http package with Flutter Source: https://docs.flutter.dev/flutter-for/uikit-devs Add the http package as a dependency to your Flutter project using the command-line tool. ```bash flutter pub add http ``` -------------------------------- ### Accessing Verbose Help Information Source: https://docs.flutter.dev/reference/flutter-cli Displays comprehensive help documentation for all supported Flutter commands and global options. ```bash $ flutter --help --verbose ``` -------------------------------- ### Perform a Basic HTTP GET Request in Dart Source: https://docs.flutter.dev/flutter-for/android-devs This snippet shows how to make a simple GET request to a URL using the 'http' package. The response body is logged to the console. ```Dart import 'dart:developer' as developer; import 'package:http/http.dart' as http; Future loadData() async { var dataURL = Uri.parse('https://jsonplaceholder.typicode.com/posts'); http.Response response = await http.get(dataURL); developer.log(response.body); } ``` -------------------------------- ### Sample Textures in GLSL Source: https://docs.flutter.dev/ui/design/graphics/fragment-shaders Example of sampling a texture using normalized coordinates derived from FlutterFragCoord and a size uniform. ```glsl #include ​ uniform vec2 uSize; uniform sampler2D uTexture; ​ out vec4 fragColor; ​ void main() { vec2 uv = FlutterFragCoord().xy / uSize; fragColor = texture(uTexture, uv); } ``` -------------------------------- ### Flutter MaterialApp Setup Source: https://docs.flutter.dev/flutter-for/uikit-devs Use MaterialApp as the entry point for Material Design apps. Customize theme colors and divider color using ThemeData. ```dart import 'package:flutter/material.dart'; class SampleApp extends StatelessWidget { const SampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Sample App', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), dividerColor: Colors.grey, ), home: const SampleAppPage(), ); } } ``` -------------------------------- ### Start Flutter or Dart App in Paused State Source: https://docs.flutter.dev/tools/devtools/network Commands to start a Flutter or Dart application in a paused state, enabling network traffic recording from app startup in DevTools. ```bash flutter run --start-paused ... ``` ```bash dart run --pause-isolates-on-start --observe ... ``` -------------------------------- ### Present FlutterViewController in UIKit (Swift) Source: https://docs.flutter.dev/add-to-app/ios/add-flutter-screen This example demonstrates how to present a FlutterViewController from a UIViewController when a button is tapped. It utilizes a FlutterEngine instance initialized in the AppDelegate. ```swift import UIKit import Flutter class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Make a button to call the showFlutter function when pressed. let button = UIButton(type:UIButton.ButtonType.custom) button.addTarget(self, action: #selector(showFlutter), for: .touchUpInside) button.setTitle("Show Flutter!", for: UIControl.State.normal) button.frame = CGRect(x: 80.0, y: 210.0, width: 160.0, height: 40.0) button.backgroundColor = UIColor.blue self.view.addSubview(button) } @objc func showFlutter() { let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine let flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil) present(flutterViewController, animated: true, completion: nil) } } ``` -------------------------------- ### Verify plugin compatibility with CocoaPods Source: https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-plugin-authors Commands to disable Swift Package Manager and navigate to the example app to ensure CocoaPods still works. ```sh flutter config --no-enable-swift-package-manager ``` ```sh cd path/to/plugin/example/ ``` -------------------------------- ### Build and open macOS project in Xcode Source: https://docs.flutter.dev/platform-integration/macos/building Prepares the application for release and opens the generated Xcode workspace. This is a required step before notarization or App Store submission. ```bash flutter build macos open macos/Runner.xcworkspace ``` -------------------------------- ### Federated platform package configuration Source: https://docs.flutter.dev/packages-and-plugins/developing-packages Platform packages use the implements entry to reference the app-facing package they implement. This example shows a Windows implementation package for the hello plugin. ```yaml flutter: plugin: implements: hello platforms: windows: pluginClass: HelloPlugin ``` -------------------------------- ### Implement first milestone using Gemini Source: https://docs.flutter.dev/ai/best-practices/developer-experience Execute this command to begin the implementation phase by focusing on the first milestone defined in the tasks list. ```text Read the @tasks.md file and implement the first milestone. ``` -------------------------------- ### Launch ChromeDriver Server Source: https://docs.flutter.dev/testing/integration-tests Start the ChromeDriver server on a specified port, which Flutter Drive will use to communicate with the browser. ```bash $ chromedriver --port=4444 ``` -------------------------------- ### Migrate CupertinoDynamicColor.opacity to .a Source: https://docs.flutter.dev/release/breaking-changes/wide-gamut-cupertino-dynamic-color This example shows how to migrate from accessing the `opacity` property to directly using the `a` property for the alpha channel. ```dart // Before: Access the alpha channel as a (converted) floating-point value. final x = color.opacity; // After: Access the alpha channel directly. final x = color.a; ``` -------------------------------- ### Example Frame Banner Log Output Source: https://docs.flutter.dev/testing/code-debugging This log output demonstrates the console messages when debugPrintBeginFrameBanner and debugPrintEndFrameBanner are enabled, showing frame timings. ```flutter I/flutter : ▄▄▄▄▄▄▄▄ Frame 12 30s 437.086ms ▄▄▄▄▄▄▄▄ I/flutter : Debug print: Am I performing this work more than once per frame? I/flutter : Debug print: Am I performing this work more than once per frame? I/flutter : ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ``` -------------------------------- ### Perform HTTP GET Request with dart:io in Flutter Source: https://docs.flutter.dev/flutter-for/react-native-devs Illustrates how to use `dart:io`'s `HttpClient` to make a GET request, process the JSON response, and update the UI state. ```dart final Uri url = Uri.parse('https://httpbin.org/ip'); final HttpClient httpClient = HttpClient(); Future getIPAddress() async { final request = await httpClient.getUrl(url); final response = await request.close(); final responseBody = await response.transform(utf8.decoder).join(); final ip = jsonDecode(responseBody)['origin'] as String; setState(() { _ipAddress = ip; }); } ``` -------------------------------- ### Create a basic DraggableCard widget in Flutter Source: https://docs.flutter.dev/cookbook/animation/physics-simulation Initial setup for a stateful widget that will contain the draggable element. ```dart import 'package:flutter/material.dart'; void main() { runApp(const MaterialApp(home: PhysicsCardDragDemo())); } class PhysicsCardDragDemo extends StatelessWidget { const PhysicsCardDragDemo({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: const DraggableCard(child: FlutterLogo(size: 128)), ); } } class DraggableCard extends StatefulWidget { const DraggableCard({required this.child, super.key}); final Widget child; @override State createState() => _DraggableCardState(); } class _DraggableCardState extends State { @override void initState() { super.initState(); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return Align(child: Card(child: widget.child)); } } ``` -------------------------------- ### Initialize HomeScreen widget test dependencies in Dart Source: https://docs.flutter.dev/app-architecture/case-study/testing Use this setup to initialize view models with fake repositories and mock routers before running widget tests. ```Dart void main() { group('HomeScreen tests', () { late HomeViewModel viewModel; late MockGoRouter goRouter; late FakeBookingRepository bookingRepository; ​ setUp(() { bookingRepository = FakeBookingRepository() ..createBooking(kBooking); viewModel = HomeViewModel( bookingRepository: bookingRepository, userRepository: FakeUserRepository(), ); goRouter = MockGoRouter(); when(() => goRouter.push(any())).thenAnswer((_) => Future.value(null)); }); ​ // ... }); } ``` -------------------------------- ### Initialize method channels and platform views in didInitializeImplicitFlutterEngine Source: https://docs.flutter.dev/release/breaking-changes/uiscenedelegate Move logic for creating method channels and platform views from didFinishLaunchingWithOptions to the new engine bridge callback. ```swift func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { // Register plugins with `engineBridge.pluginRegistry` GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) ​ // Create method channels with `engineBridge.applicationRegistrar.messenger()` let batteryChannel = FlutterMethodChannel( name: "samples.flutter.dev/battery", binaryMessenger: engineBridge.applicationRegistrar.messenger() ) ​ // Create platform views with `engineBridge.applicationRegistrar.messenger()` let factory = FLNativeViewFactory(messenger: engineBridge.applicationRegistrar.messenger()) } ``` ```objc func didInitializeImplicitFlutterEngine:(NSObject*)engineBridge { // Register plugins with `engineBridge.pluginRegistry` [GeneratedPluginRegistrant registerWithRegistry:engineBridge.pluginRegistry]; ​ // Create method channels with `engineBridge.applicationRegistrar.messenger` FlutterMethodChannel* batteryChannel = [FlutterMethodChannel methodChannelWithName:@"samples.flutter.dev/battery" binaryMessenger:engineBridge.applicationRegistrar.messenger]; ​ // Create platform views with `engineBridge.applicationRegistrar.messenger` FLNativeViewFactory* factory = [[FLNativeViewFactory alloc] initWithMessenger:engineBridge.applicationRegistrar.messenger]; } ``` -------------------------------- ### Create a minimal Flutter project using CLI Source: https://docs.flutter.dev/learn/pathway/tutorial/set-up-state-project Run this command in your terminal to initialize a new Flutter application with an empty template. ```bash $ flutter create wikipedia_reader --empty ``` -------------------------------- ### Validate Flutter and Dart installation Source: https://docs.flutter.dev/install/add-to-path Verify that the Flutter SDK has been successfully added to PATH by checking the versions of both flutter and dart tools. ```bash $ flutter --version $ dart --version ``` -------------------------------- ### Set Flutter SDK Path for Documentation Source: https://docs.flutter.dev/packages-and-plugins/developing-packages Configure the FLUTTER_ROOT environment variable to point to your Flutter SDK installation. Use the appropriate command for your operating system. ```bash export FLUTTER_ROOT=~/dev/flutter # on macOS or Linux ``` ```bash set FLUTTER_ROOT=~/dev/flutter # on Windows ``` -------------------------------- ### Gradle Plugin Block Removal Example (Kotlin DSL) Source: https://docs.flutter.dev/release/breaking-changes/migrate-to-built-in-kotlin/for-plugin-authors This snippet illustrates the `plugins` block and `kotlinOptions` configuration in a `build.gradle.kts` file, highlighting the elements to be removed during the migration. ```kotlin plugins { id("com.android.library") id("kotlin-android") // ... } android { // ... kotlinOptions { jvmTarget = JavaVersion.VERSION_17.toString() } // ... } ``` -------------------------------- ### Enable Swift Package Manager globally Source: https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers Enables the Swift Package Manager feature for the current Flutter installation. ```sh flutter config --enable-swift-package-manager ``` -------------------------------- ### Dart Shallow vs Retained Size Example Source: https://docs.flutter.dev/tools/devtools/memory This example demonstrates the difference between shallow size (object and its references) and retained size (including retained objects) in Dart, using a large instance within a child object. ```dart class Child{ /// The instance is part of both [parent] and [parent.child] /// retained sizes. final myHugeInstance = MyHugeInstance(); } class Parent { Child? child; } Parent parent = Parent()..child = Child(); ``` -------------------------------- ### Change directory to the Flutter project Source: https://docs.flutter.dev/testing/native-debugging?tab=from-vscode-to-xcode-ios Command to navigate into the newly created project directory. ```bash $ cd my_app ``` -------------------------------- ### Example 1: Container filling screen Source: https://docs.flutter.dev/ui/layout/constraints The screen forces the Container to be exactly the same size as the screen, causing it to fill the entire screen and paint it red. ```dart Container(color: red) ``` -------------------------------- ### Initializing the application entry point Source: https://docs.flutter.dev/flutter-for/xamarin-forms-devs Comparison of the main entry point for Xamarin.Forms using LoadApplication and Flutter using runApp. ```csharp LoadApplication(new App()); ``` ```dart void main() { runApp(const MyApp()); } ``` -------------------------------- ### Gradle Plugin Block Removal Example (Groovy DSL) Source: https://docs.flutter.dev/release/breaking-changes/migrate-to-built-in-kotlin/for-plugin-authors This snippet illustrates the legacy `apply` plugin syntax and `kotlinOptions` configuration in a Groovy `build.gradle` file, highlighting the elements to be removed during the migration. ```groovy apply plugin: 'com.android.library' apply plugin: 'kotlin-android' ... android { // ... kotlinOptions { jvmTarget = JavaVersion.VERSION_17.toString() } // ... } ``` -------------------------------- ### Dominator tree for package import example Source: https://docs.flutter.dev/tools/devtools/app-size This snippet shows the resulting dominator tree for the package import structure where package:a dominates package:d. ```text package:a |__ package:b |__ package:c |__ package:d ``` -------------------------------- ### Flutter Pub Get: Exit Code 69 (TLS error) Source: https://docs.flutter.dev/install/troubleshoot This output shows a `pub get` failure with `exit code: 69`, often due to TLS errors when connecting to pub.dev. It suggests network connectivity or firewall issues. ```bash Running "flutter pub get" in flutter_tools... Resolving dependencies in .../flutter/packages/flutter_tools... (28.0s) Got TLS error trying to find package test at https://pub.dev/. pub get failed command: ".../flutter/bin/cache/dart-sdk/bin/ dart __deprecated_pub --color --directory .../flutter/packages/flutter_tools get --example" pub env: { "FLUTTER_ROOT": ".../flutter", "PUB_ENVIRONMENT": "flutter_cli:get", "PUB_CACHE": ".../.pub-cache", } exit code: 69 ``` -------------------------------- ### Review and sign Xcode licenses Source: https://docs.flutter.dev/platform-integration/macos/setup Review and accept the Xcode license agreement via the terminal. This is a required step after installing or updating Xcode. ```bash $ sudo xcodebuild -license ``` -------------------------------- ### flutter doctor Source: https://docs.flutter.dev/reference/flutter-cli Show information about the installed tooling. ```APIDOC ## COMMAND flutter doctor ### Description Show information about the installed tooling. ### Usage `flutter doctor` ### Arguments N/A ### Request Example N/A ### Response #### Success Response (0) - **Output** (string) - Diagnostic information about Flutter installation. #### Response Example N/A ``` -------------------------------- ### Flutter Widget Tree Dump Output Source: https://docs.flutter.dev/testing/code-debugging Example of a widget tree dump showing nested widgets and their associated render objects. ```text flutter: │ └RichText(softWrap: wrapping at box width, maxLines: unlimited, text: "Dump Widget Tree", dependencies: [Directionality, _LocalizationsScope-[GlobalKey#61ca6]], renderObject: RenderParagraph#d15aa relayoutBoundary=up13) flutter: └PositionedDirectional(dependencies: [Directionality]) flutter: └Positioned(left: 0.0, top: 0.0, bottom: 0.0, width: 20.0) flutter: └Listener(listeners: [down], behavior: translucent, renderObject: RenderPointerListener#d884c) flutter: flutter: ``` -------------------------------- ### Visualizing Code Dependencies with Trees and Graphs Source: https://docs.flutter.dev/tools/devtools/app-size These examples illustrate the difference between a dominator tree's one-to-many relationships and a call graph's many-to-many relationships. ```text package:a |__ package:b | |__ package:d |__ package:c |__ package:d ``` ```text package:a --> package:b --> package:d package:a --> package:c --> ``` -------------------------------- ### Mock SharedPreferences for testing Source: https://docs.flutter.dev/cookbook/persistence/key-value Call this method in your test setup to provide initial values for the mock preference store. ```dart SharedPreferences.setMockInitialValues({'counter': 2}); ``` -------------------------------- ### Specify Initial Route for New FlutterFragment Engine Source: https://docs.flutter.dev/add-to-app/android/add-flutter-fragment Use the initialRoute() method on FlutterFragment.withNewEngine() to specify a starting route for a new Flutter experience. ```kotlin // With a new FlutterEngine. val flutterFragment = FlutterFragment.withNewEngine() .initialRoute("myInitialRoute/") .build() ``` ```java // With a new FlutterEngine. FlutterFragment flutterFragment = FlutterFragment.withNewEngine() .initialRoute("myInitialRoute/") .build(); ``` -------------------------------- ### Navigate to Flutter SDK Directory Source: https://docs.flutter.dev/install/upgrade Change to the Flutter SDK installation directory. The path can be found using flutter doctor --verbose. ```bash $ cd /path/to/flutter ``` -------------------------------- ### Initialize SoLoud with default or custom settings Source: https://docs.flutter.dev/cookbook/audio/soloud Initialize the SoLoud instance before playing any audio. Configure sample rate, buffer size, and channels as needed. ```dart import 'package:flutter_soloud/flutter_soloud.dart'; // Initialize with default settings. await SoLoud.instance.init(); // Or configure with custom settings. await SoLoud.instance.init( sampleRate: 44100, bufferSize: 2048, channels: Channels.stereo, ); ``` -------------------------------- ### Download iOS Platform Support Source: https://docs.flutter.dev/platform-integration/ios/setup Use this command to download necessary iOS platform support and the latest iOS Simulator runtimes. ```bash $ xcodebuild -downloadPlatform iOS ``` -------------------------------- ### Define route constants for nested navigation Source: https://docs.flutter.dev/cookbook/effects/nested-nav Define route name constants for top-level screens and nested setup flow pages. The setup flow routes use a common prefix to allow the top-level Navigator to identify them without knowing individual page names. ```dart const routeHome = '/'; const routeSettings = '/settings'; const routePrefixDeviceSetup = '/setup/'; const routeDeviceSetupStart = '/setup/$routeDeviceSetupStartPage'; const routeDeviceSetupStartPage = 'find_devices'; const routeDeviceSetupSelectDevicePage = 'select_device'; const routeDeviceSetupConnectingPage = 'connecting'; const routeDeviceSetupFinishedPage = 'finished'; ``` -------------------------------- ### Update CHANGELOG.md for Kotlin Migration Source: https://docs.flutter.dev/release/breaking-changes/migrate-to-built-in-kotlin/for-plugin-authors This snippet provides an example of how to document the Kotlin migration and minimum version updates in the plugin's `CHANGELOG.md` file. ```markdown ## - Updates minimum supported SDK version to Flutter 3.44/Dart 3.12. - Migrates to built-in Kotlin ... ``` -------------------------------- ### Create new Flutter project with specified type Source: https://docs.flutter.dev/release/breaking-changes/androidx-migration Creates a new Flutter project of a given type at the specified path. Use this to start fresh if Android Studio migration is unavailable. ```bash flutter create -t ``` -------------------------------- ### Migrate RouteSettings copyWith to constructor Source: https://docs.flutter.dev/release/breaking-changes/routesettings-copywith-migration This migration guide demonstrates how to replace the deprecated `RouteSettings.copyWith` method with direct constructor usage for creating new `RouteSettings` instances. ```dart RouteSettings newSettings = oldSettings.copyWith(name: 'new name'); ``` ```dart RouteSettings newSettings = RouteSettings(name: 'new name', arguments: oldSettings.arguments); ``` -------------------------------- ### System Instruction for Tool-Enabled Model Source: https://docs.flutter.dev/ai/best-practices/tool-calls A static string defining the system instructions to guide the LLM's behavior as a crossword puzzle solver. ```dart static String get clueSolverSystemInstruction => ''' You are an expert crossword puzzle solver. ​ ... ​ ``` -------------------------------- ### Legacy usage of TestWidgetsFlutterBinding.clock Source: https://docs.flutter.dev/release/breaking-changes/test-widgets-flutter-binding-clock Example of code that fails after the migration because the clock type has changed. ```dart testWidgets('some test', (WidgetTester tester) { someApiThatWantsAQuiverClock(tester.binding.clock); }); ``` -------------------------------- ### Tile Widget Build Method Example Source: https://docs.flutter.dev/learn/pathway/tutorial/devtools This snippet defines a `StatelessWidget` named `Tile` with a `build` method that returns a `Container`. It demonstrates how `width`, `height`, and `decoration` properties are set, which can then be inspected and modified in the property editor. ```dart class Tile extends StatelessWidget { const Tile(this.letter, this.hitType, {super.key}); final String letter; final HitType hitType; @override Widget build(BuildContext context) { return Container( width: 60, height: 60, decoration: BoxDecoration( border: Border.all(color: Colors.grey.shade300), color: switch (hitType) { HitType.hit => Colors.green, HitType.partial => Colors.yellow, HitType.miss => Colors.grey, _ => Colors.white, }, ), ); } } ``` -------------------------------- ### Fetch signing files from App Store Connect Source: https://docs.flutter.dev/deployment/ios Download signing profiles and certificates based on the project bundle ID. ```bash app-store-connect fetch-signing-files $(xcode-project detect-bundle-id) \ --platform IOS \ --type IOS_APP_STORE \ --certificate-key=@file:/path/to/cert_key \ --create ``` -------------------------------- ### Declaring custom fonts and assets Source: https://docs.flutter.dev/tools/pubspec Examples of including fonts as individual assets, font families with multiple weights, or simple asset declarations. ```yaml flutter: fonts: - asset: fonts/Roboto-Regular.ttf weight: 900 # Optional style: italic # Optional ``` ```yaml flutter: fonts: - family: Roboto # Optional fonts: - asset: fonts/Roboto-Regular.ttf - asset: fonts/Roboto-Bold.ttf weight: 700 # Optional style: italic # Optional ``` ```yaml flutter: assets: - fonts/Roboto-Regular.ttf ``` -------------------------------- ### Complete FadeInImage example with asset placeholder Source: https://docs.flutter.dev/cookbook/images/fading-in-images Full Flutter app demonstrating FadeInImage.assetNetwork() with a local asset file as placeholder. Requires the asset to be configured in pubspec.yaml. ```dart import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const title = 'Fade in images'; return MaterialApp( title: title, home: Scaffold( appBar: AppBar(title: const Text(title)), body: Center( child: FadeInImage.assetNetwork( placeholder: 'assets/loading.gif', image: 'https://picsum.photos/250?image=9', ), ), ), ); } } ``` -------------------------------- ### Configure PromptBuilder for UI Generation with genui Source: https://docs.flutter.dev/ai/genui/get-started This snippet demonstrates how to set up the `PromptBuilder` with system instructions that explicitly tell the LLM to use `genui` tools for UI generation, ensuring it generates UI based on given words. ```dart final promptBuilder = PromptBuilder.chat( catalog: catalog, instructions: ''' You are an expert in creating funny riddles. Every time I give you a word, you should generate UI that displays one new riddle related to that word. Each riddle should have both a question and an answer. ''', ); ``` -------------------------------- ### Create ParallaxRecipe stateless widget with SingleChildScrollView Source: https://docs.flutter.dev/cookbook/effects/parallax-scrolling Initial setup for a scrollable list container. Use this as the foundation before adding list items. ```Dart class ParallaxRecipe extends StatelessWidget { const ParallaxRecipe({super.key}); @override Widget build(BuildContext context) { return const SingleChildScrollView(child: Column(children: [])); } } ``` -------------------------------- ### Podfile Configuration for Add-to-App App Clips Source: https://docs.flutter.dev/platform-integration/ios/ios-app-clip Extend the existing host project target to include the App Clip target for Flutter pod installation. ```ruby target 'MyApp' do install_all_flutter_pods(flutter_application_path) end ``` ```ruby target 'MyApp' do install_all_flutter_pods(flutter_application_path) end target '' install_all_flutter_pods(flutter_application_path) end ``` -------------------------------- ### Complete FadeInImage example with in-memory placeholder Source: https://docs.flutter.dev/cookbook/images/fading-in-images Full Flutter app demonstrating FadeInImage.memoryNetwork() with a transparent placeholder and loading indicator. Requires transparent_image package dependency. ```dart import 'package:flutter/material.dart'; import 'package:transparent_image/transparent_image.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const title = 'Fade in images'; return MaterialApp( title: title, home: Scaffold( appBar: AppBar(title: const Text(title)), body: Stack( children: [ const Center(child: CircularProgressIndicator()), Center( child: FadeInImage.memoryNetwork( placeholder: kTransparentImage, image: 'https://picsum.photos/250?image=9', ), ), ], ), ), ); } } ``` -------------------------------- ### Complete pubspec.yaml for Package Fonts Example Source: https://docs.flutter.dev/cookbook/design/package-fonts Full `pubspec.yaml` configuration demonstrating how to declare a package dependency and its exported fonts for a complete Flutter application. ```yaml name: package_fonts description: An example of how to use package fonts with Flutter dependencies: awesome_package: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter flutter: fonts: - family: Raleway fonts: - asset: packages/awesome_package/fonts/Raleway-Regular.ttf - asset: packages/awesome_package/fonts/Raleway-Italic.ttf style: italic uses-material-design: true ``` -------------------------------- ### HighlightTextEditingController before BuildContext parameter Source: https://docs.flutter.dev/release/breaking-changes/buildtextspan-buildcontext This example shows a custom `TextEditingController` that highlights text with a specific color. Before the `BuildContext` parameter was added, the color had to be passed during controller instantiation. ```dart class HighlightTextEditingController extends TextEditingController { HighlightTextEditingController(this.highlightColor); final Color highlightColor; @override TextSpan buildTextSpan({TextStyle? style, required bool withComposing}) { return super.buildTextSpan(style: TextStyle(color: highlightColor), withComposing: withComposing); } } ``` -------------------------------- ### Configure Package, Library, and Target Names in Package.swift Source: https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-plugin-authors Define the package name, library name (with underscores replaced by hyphens), and target configuration. Ensure the library name matches the target name and update plugin_name to your actual plugin name. ```swift let package = Package( // TODO: Update your plugin name. name: "plugin_name", platforms: [ .iOS("13.0"), .macOS("10.15") ], products: [ // TODO: Update your library and target names. // If the plugin name contains "_", replace with "-" for the library name .library(name: "plugin-name", targets: ["plugin_name"]) ], dependencies: [], targets: [ .target( ``` -------------------------------- ### Define system instructions for tool usage Source: https://docs.flutter.dev/ai/best-practices/tool-calls Provide explicit instructions to the model on when and how to use the 'returnResult' tool to return the final structured result. ```dart static String get clueSolverSystemInstruction => ''' You are an expert crossword puzzle solver. ​ ... ​ ### Tool: `returnResult` ​ You have a tool to return the final result of the clue solving process. ​ **When to use:** - Use this tool when you have a final answer and confidence score to return. You must use this tool exactly once, and only once, to return the final result. ​ **Function signature:** ```json ${jsonEncode(_returnResultFunction.toJson())} ``` '''; ``` -------------------------------- ### Add Mockito and build_runner dependencies Source: https://docs.flutter.dev/cookbook/testing/unit/mocking Install mockito, build_runner, and http packages using flutter pub add. These are required for code generation and mocking HTTP clients. ```bash $ flutter pub add http dev:mockito dev:build_runner ``` -------------------------------- ### Check for toolchain issues Source: https://docs.flutter.dev/platform-integration/macos/setup Runs a diagnostic check of the local environment. Use this to identify and resolve issues with the Xcode installation or other dependencies. ```bash $ flutter doctor -v ``` -------------------------------- ### iOS build terminal output Source: https://docs.flutter.dev/testing/native-debugging Example output when building a Flutter iOS app with codesigning disabled. ```text Warning: Building for device with codesigning disabled. You will have to manually codesign before deploying to device. Building com.example.myApp for device (ios)... ``` -------------------------------- ### Formulas for migrating SpringDescription.withDampingRatio constructor Source: https://docs.flutter.dev/release/breaking-changes/spring-description-underdamped These formulas guide the migration of SpringDescription.withDampingRatio parameters. First, calculate damping 'c', then apply the default constructor migration, and optionally convert back to a new damping ratio 'new_z'. ```math c = z * 2 * sqrt(m * k) ``` ```math new_z = new_c / 2 / sqrt(new_m * new_k) ``` -------------------------------- ### Example 2: Container with fixed size forced to fill screen Source: https://docs.flutter.dev/ui/layout/constraints Despite requesting a 100x100 size, the Container is forced by the screen to be the same size as the screen, thus filling it. ```dart Container(width: 100, height: 100, color: red) ``` -------------------------------- ### Correct Dialog Display with Navigator API Source: https://docs.flutter.dev/testing/common-errors This example demonstrates the correct approach to displaying a dialog immediately upon navigating to a new screen by pushing multiple routes using the Navigator API. ```dart class FirstScreen extends StatelessWidget { const FirstScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('First Screen')), body: Center( child: ElevatedButton( child: const Text('Launch screen'), onPressed: () { // Navigate to the second screen using a named route. Navigator.pushNamed(context, '/second'); // Immediately show a dialog upon loading the second screen. Navigator.push( context, PageRouteBuilder( barrierDismissible: true, opaque: false, pageBuilder: (_, anim1, anim2) => const MyDialog(), ), ); }, ), ), ); } } ``` -------------------------------- ### Display Current Analytics Setting Source: https://docs.flutter.dev/reference/crash-reporting Check the current analytics and crash reporting configuration for your Flutter installation. ```bash $ flutter config ``` -------------------------------- ### Create a Flutter FFI plugin for macOS Source: https://docs.flutter.dev/platform-integration/macos/c-interop Use the flutter create command with the plugin_ffi template to set up a project for native C/C++ integration. ```bash $ flutter create --platforms=macos --template=plugin_ffi native_add $ cd native_add ``` -------------------------------- ### Basic MaterialApp without custom ScrollBehavior Source: https://docs.flutter.dev/release/breaking-changes/default-scroll-behavior-drag Default MaterialApp configuration before migration. Shows the baseline setup without custom scroll behavior. ```dart MaterialApp( // ... ); ``` -------------------------------- ### Update Flutter Extension for Gemini CLI Source: https://docs.flutter.dev/ai/gemini-cli-extension Updates the installed Flutter extension to its latest available version. ```bash gemini extensions update flutter ``` -------------------------------- ### Initialize temporary keychain Source: https://docs.flutter.dev/deployment/ios Initialize a temporary keychain to isolate distribution certificates from the login keychain. ```bash keychain initialize ``` -------------------------------- ### Create, build, and inspect Linux app dependencies Source: https://docs.flutter.dev/platform-integration/linux/building Commands to create a new Flutter Linux desktop app, build it in release mode, and list its system library dependencies using ldd. ```bash $ flutter create linux_desktop_test $ cd linux_desktop_test $ flutter build linux --release $ ldd build/linux/x64/release/bundle/linux_desktop_test ``` -------------------------------- ### Navigate into Flutter project directory Source: https://docs.flutter.dev/reference/create-new-app Change into the newly created project directory using cd to access the project files and run commands like flutter run. ```bash $ cd my_app ``` -------------------------------- ### Inline Formatting with Multiple Styles in CSS Source: https://docs.flutter.dev/flutter-for/web-devs CSS example demonstrating styled emphasis on a single word using em tag with custom font properties. ```css .grey-box { background-color: #e0e0e0; /* grey 300 */ width: 320px; height: 240px; font: 900 24px Roboto; display: flex; align-items: center; justify-content: center; } .red-box { background-color: #ef5350; /* red 400 */ padding: 16px; color: #ffffff; } .red-box em { font: 300 48px Roboto; font-style: italic; } ``` -------------------------------- ### Kotlin: MethodChannel setup in configureFlutterEngine Source: https://docs.flutter.dev/platform-integration/platform-channels Initialize a MethodChannel in the MainActivity class to establish communication with Flutter. Call setMethodCallHandler to define how platform method calls are processed on the main thread. ```kotlin import androidx.annotation.NonNull import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel class MainActivity: FlutterActivity() { private val CHANNEL = "samples.flutter.dev/battery" override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result -> // This method is invoked on the main thread. // TODO } } } ``` -------------------------------- ### Stop recording and get file path Source: https://docs.flutter.dev/cookbook/audio/record Stop the recorder to finalize the file and retrieve its storage path. ```dart final path = await recorder.stop(); print('Recording stopped. File saved to: $path'); ``` -------------------------------- ### Platform and browser tracing tools Source: https://docs.flutter.dev/perf/faq Commands and URLs for capturing performance traces on Android, Fuchsia, and Chrome. ```text about:tracing ``` ```bash adb systrace ``` ```bash fx traceutil ``` -------------------------------- ### Configure FlutterEngine for MethodChannel in MainActivity.kt Source: https://docs.flutter.dev/platform-integration/android/compose-activity Set up a `MethodChannel` in `configureFlutterEngine` to handle communication between Flutter and native Android. This example handles a 'launchActivity' method call. ```kotlin class MainActivity: FlutterActivity() { // This value must match the `MethodChannel` name in your Dart code. private val CHANNEL = "com.example.flutter_android_activity" override fun configureFlutterEngine(flutterEngine: FlutterEngine) { GeneratedPluginRegistrant.registerWith(flutterEngine) MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call: MethodCall, result: MethodChannel.Result -> when (call.method) { // Note: This must match the first parameter passed to // `platformMethodChannel.invokeMethod` in your Dart code. "launchActivity" -> { try { // Takes an object, in this case a String. val message = call.arguments val intent = Intent(this@MainActivity, SecondActivity::class.java) intent.putExtra("message", message.toString()) startActivity(intent) } catch (e: Exception){} result.success(true) } else -> {} } } } } ``` -------------------------------- ### Configure LLDB Initialization Source: https://docs.flutter.dev/add-to-app/ios/project-setup?tab=embed-using-cocoapods Set the LLDB Init File in the Xcode scheme or append the Flutter LLDB source command to an existing .lldbinit file. ```text $(PROJECT_DIR)/Flutter/flutter_lldbinit ``` ```lldb command source --relative-to-command-file "Flutter/flutter_lldbinit" ``` -------------------------------- ### Login and register snap with snapcraft Source: https://docs.flutter.dev/deployment/linux Authenticate with snapcraft.io and register your app name before publishing to the Snap Store. ```bash $ snapcraft login $ snapcraft register ``` -------------------------------- ### Create ArticleView widget with basic structure Source: https://docs.flutter.dev/learn/pathway/tutorial/listenable-builder Initial ArticleView StatelessWidget with Scaffold, AppBar, and placeholder body. This is the starting point before adding state management. ```dart class ArticleView extends StatelessWidget { ArticleView({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Wikipedia Flutter'), ), body: const Center( child: Text('UI will update here'), ), ); } } ``` -------------------------------- ### SQLite CRUD Operations with sqflite in Flutter Source: https://docs.flutter.dev/cookbook/persistence/sqlite Complete example showing database initialization with onCreate callback, and functions to insert, retrieve, update, and delete Dog records. Requires sqflite and path packages in pubspec.yaml. Use WidgetsFlutterBinding.ensureInitialized() to avoid flutter upgrade errors. ```dart import 'dart:async'; import 'package:flutter/widgets.dart'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; void main() async { // Avoid errors caused by flutter upgrade. // Importing 'package:flutter/widgets.dart' is required. WidgetsFlutterBinding.ensureInitialized(); // Open the database and store the reference. final database = openDatabase( // Set the path to the database. Note: Using the `join` function from the // `path` package is best practice to ensure the path is correctly // constructed for each platform. join(await getDatabasesPath(), 'doggie_database.db'), // When the database is first created, create a table to store dogs. onCreate: (db, version) { // Run the CREATE TABLE statement on the database. return db.execute( 'CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)', ); }, // Set the version. This executes the onCreate function and provides a // path to perform database upgrades and downgrades. version: 1, ); // Define a function that inserts dogs into the database Future insertDog(Dog dog) async { // Get a reference to the database. final db = await database; // Insert the Dog into the correct table. You might also specify the // `conflictAlgorithm` to use in case the same dog is inserted twice. // // In this case, replace any previous data. await db.insert( 'dogs', dog.toMap(), conflictAlgorithm: ConflictAlgorithm.replace, ); } // A method that retrieves all the dogs from the dogs table. Future> dogs() async { // Get a reference to the database. final db = await database; // Query the table for all the dogs. final List> dogMaps = await db.query('dogs'); // Convert the list of each dog's fields into a list of `Dog` objects. return [ for (final {'id': id as int, 'name': name as String, 'age': age as int} in dogMaps) Dog(id: id, name: name, age: age), ]; } Future updateDog(Dog dog) async { // Get a reference to the database. final db = await database; // Update the given Dog. await db.update( 'dogs', dog.toMap(), // Ensure that the Dog has a matching id. where: 'id = ?', // Pass the Dog's id as a whereArg to prevent SQL injection. whereArgs: [dog.id], ); } Future deleteDog(int id) async { // Get a reference to the database. final db = await database; // Remove the Dog from the database. await db.delete( 'dogs', // Use a `where` clause to delete a specific dog. where: 'id = ?', // Pass the Dog's id as a whereArg to prevent SQL injection. whereArgs: [id], ); } // Create a Dog and add it to the dogs table var fido = Dog(id: 0, name: 'Fido', age: 35); await insertDog(fido); // Now, use the method above to retrieve all the dogs. print(await dogs()); // Prints a list that include Fido. // Update Fido's age and save it to the database. fido = Dog(id: fido.id, name: fido.name, age: fido.age + 7); await updateDog(fido); // Print the updated results. print(await dogs()); // Prints Fido with age 42. // Delete Fido from the database. await deleteDog(fido.id); // Print the list of dogs (empty). print(await dogs()); } class Dog { final int id; final String name; final int age; Dog({required this.id, required this.name, required this.age}); // Convert a Dog into a Map. The keys must correspond to the names of the // columns in the database. Map toMap() { return {'id': id, 'name': name, 'age': age}; } // Implement toString to make it easier to see information about // each dog when using the print statement. @override String toString() { return 'Dog{id: $id, name: $name, age: $age}'; } } ``` -------------------------------- ### Initialize method channel in activate Source: https://docs.flutter.dev/platform-integration/platform-channels Set up the battery method channel with the name 'samples.flutter.dev/battery' and attach the method call handler in my_application_activate. ```c static void my_application_activate(GApplication* application) { // ... fl_register_plugins(FL_PLUGIN_REGISTRY(self->view)); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); self->battery_channel = fl_method_channel_new( fl_engine_get_binary_messenger(fl_view_get_engine(view)), "samples.flutter.dev/battery", FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler( self->battery_channel, battery_method_call_handler, self, nullptr); gtk_widget_grab_focus(GTK_WIDGET(self->view)); } ``` -------------------------------- ### Verify Widget Display with integration_test Source: https://docs.flutter.dev/release/breaking-changes/flutter-driver-migration This `integration_test` example loads the main app widget, waits for data to settle, and then uses `expect` with `findsOneWidget` to verify that a specific text widget is displayed. ```dart testWidgets( 'do not select any item, verify please select text is displayed', (tester) async { // load the PlantsApp widget await tester.pumpWidget(const PlantsApp()); // wait for data to load await tester.pumpAndSettle(); // Find widget with 'please select' final finder = find.text('Please select a plant from the list.'); // Check if widget is displayed expect(finder, findsOneWidget); }, ); ``` -------------------------------- ### Overriding CupertinoThemeData.brightness in a subclass Source: https://docs.flutter.dev/release/breaking-changes/nullable-cupertinothemedata-brightness This example demonstrates how to override `CupertinoThemeData.brightness` in a subclass to provide a custom brightness value, such as `Brightness.dark`. ```dart class AlwaysDarkCupertinoThemeData extends CupertinoThemeData { Brightness brightness => Brightness.dark; } ``` -------------------------------- ### Clone and verify Flutter SDK main channel Source: https://docs.flutter.dev/install/archive Clones the main branch and runs the flutter tool to download required dependencies. Use this when installation bundles are not provided for the channel. ```bash $ git clone -b main https://github.com/flutter/flutter.git $ ./flutter/bin/flutter --version ``` -------------------------------- ### Build and export iOS IPA for size analysis Source: https://docs.flutter.dev/perf/app-size Generate an IPA file and open the archive in Xcode to create an App Thinning Size Report. Run this command first to prepare the archive for analysis. ```bash flutter build ipa --export-method development ``` -------------------------------- ### Navigate to Plugin Directory Source: https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-plugin-authors Change to the plugin's top-level directory for running validation and configuration commands. ```shell cd path/to/plugin/ ``` -------------------------------- ### Create an FFI package using Flutter CLI Source: https://docs.flutter.dev/platform-integration/bind-native-code Use this command to initialize a new Flutter FFI package with the recommended template. This sets up the necessary project structure and build hooks. ```bash $ flutter create --template=package_ffi native_add $ cd native_add ``` -------------------------------- ### Configure LLDB Init File Source: https://docs.flutter.dev/add-to-app/ios/project-setup Set the LLDB Init File path in the Xcode scheme or source the Flutter LLDB file from an existing .lldbinit configuration. ```text $(PROJECT_DIR)/Flutter/flutter_lldbinit ``` ```text command source --relative-to-command-file "Flutter/flutter_lldbinit" ``` -------------------------------- ### Update main.dart to use AdaptiveLayout Source: https://docs.flutter.dev/learn/pathway/tutorial/adaptive-layout Configure the main app to use the AdaptiveLayout widget as the home screen. Includes CupertinoApp setup with theme configuration. ```dart import 'package:flutter/cupertino.dart'; import 'package:rolodex/data/contact_group.dart'; import 'package:rolodex/screens/adaptive_layout.dart'; final contactGroupsModel = ContactGroupsModel(); void main() { runApp(const RolodexApp()); } class RolodexApp extends StatelessWidget { const RolodexApp({super.key}); @override Widget build(BuildContext context) { return const CupertinoApp( title: 'Rolodex', theme: CupertinoThemeData( barBackgroundColor: CupertinoDynamicColor.withBrightness( color: Color(0xFFF9F9F9), darkColor: Color(0xFF1D1D1D), ), ), home: AdaptiveLayout(), // New ); } } ``` -------------------------------- ### Load and display network data in a Flutter ListView Source: https://docs.flutter.dev/flutter-for/android-devs This complete example demonstrates fetching JSON data in initState and rendering it in a ListView.builder. It shows the standard pattern for managing asynchronous state within a StatefulWidget. ```dart import 'dart:convert'; ​ import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; ​ void main() { runApp(const SampleApp()); } ​ class SampleApp extends StatelessWidget { const SampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Sample App', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: const SampleAppPage(), ); } } ​ class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); ​ @override State createState() => _SampleAppPageState(); } ​ class _SampleAppPageState extends State { List> widgets = []; ​ @override void initState() { super.initState(); loadData(); } ​ @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: ListView.builder( itemCount: widgets.length, itemBuilder: (context, position) { return getRow(position); }, ), ); } ​ Widget getRow(int i) { return Padding( padding: const EdgeInsets.all(10), child: Text("Row ${widgets[i]["title"]}"), ); } ​ Future loadData() async { final dataURL = Uri.parse('https://jsonplaceholder.typicode.com/posts'); final response = await http.get(dataURL); setState(() { widgets = (jsonDecode(response.body) as List) .cast>(); }); } ​ } ``` -------------------------------- ### Flutter Application Entry Point Source: https://docs.flutter.dev/flutter-for/react-native-devs This snippet shows the `main` function, which serves as the entry point for all Flutter applications. Execution begins here when a Flutter app is launched. ```dart // Dart void main() { print('Hello, this is the main function.'); } ``` -------------------------------- ### Fetch signing files from App Store Connect Source: https://docs.flutter.dev/deployment/macos Downloads provisioning profiles and certificates for the specified macOS bundle ID. ```bash app-store-connect fetch-signing-files YOUR.APP.BUNDLE_ID \ --platform MAC_OS \ --type MAC_APP_STORE \ --certificate-key=@file:/path/to/cert_key \ --create ``` -------------------------------- ### Configure server host, port, and HTTPS settings Source: https://docs.flutter.dev/platform-integration/web/web-dev-config-file Define the binding address, port, and TLS certificate paths for the development server. ```yaml server: host: "0.0.0.0" # Defines the binding address port: 8080 # Specifies the port for the development server https: cert-path: "/path/to/cert.pem" # Path to your TLS certificate cert-key-path: "/path/to/key.pem" # Path to TLS certificate key ``` -------------------------------- ### Regenerate FFI Bindings with ffigen Source: https://docs.flutter.dev/packages-and-plugins/developing-packages Run the ffigen tool to automatically generate Dart bindings from native header files. Requires ffigen package to be installed. ```bash $ dart run tool/ffigen.dart ``` -------------------------------- ### Set System Instructions with User Preferences in Dart Source: https://docs.flutter.dev/ai/ai-toolkit/feature-integration Configure a GenerativeModel with system instructions that incorporate user preferences. The systemInstruction parameter accepts a Content.system() object with custom prompt text that can reference dynamic settings. ```dart class _HomePageState extends State { ... // create a new provider with the given history and the current settings LlmProvider _createProvider([List? history]) => FirebaseProvider( history: history, ..., model: FirebaseAI.geminiAI().generativeModel( model: 'gemini-2.5-flash', ..., systemInstruction: Content.system(''' You are a helpful assistant that generates recipes based on the ingredients and instructions provided as well as my food preferences, which are as follows: ${Settings.foodPreferences.isEmpty ? 'I don\'t have any food preferences' : Settings.foodPreferences} ​ You should keep things casual and friendly. You may generate multiple recipes in a single response, but only if asked. ... ''', ), ), ); ... } ``` -------------------------------- ### Add Flutter SDK PATH to ksh Source: https://docs.flutter.dev/install/add-to-path Add the Flutter bin directory to PATH in ksh by appending to ~/.profile. Replace with your Flutter installation path. ```bash $ echo 'export PATH="/bin:$PATH"' >> ~/.profile ``` ```bash $ echo 'export PATH="$HOME/develop/flutter/bin:$PATH"' >> ~/.profile ``` -------------------------------- ### Set surface size using sheetSize Source: https://docs.flutter.dev/release/breaking-changes/animation-sheet-builder-display Example of setting the testing surface size using the deprecated sheetSize method. ```dart tester.binding.setSurfaceSize(animationSheet.sheetSize(600)); ``` -------------------------------- ### Basic Flutter App Workflow Source: https://docs.flutter.dev/reference/flutter-cli Standard sequence of commands to create, analyze, test, and run a new Flutter project from the terminal. ```bash $ flutter create my_app $ cd my_app $ flutter analyze $ flutter test $ flutter run lib/main.dart ``` -------------------------------- ### Create a Custom Focusable Widget with Flutter Focus Source: https://docs.flutter.dev/ui/interactivity/focus This example demonstrates how to wrap a custom widget with the `Focus` widget to make it focusable. It shows how to use `onFocusChange` to update the UI based on focus state. ```dart import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); static const String _title = 'Focus Sample'; @override Widget build(BuildContext context) { return MaterialApp( title: _title, home: Scaffold( appBar: AppBar(title: const Text(_title)), body: const Column( mainAxisAlignment: MainAxisAlignment.center, children: [MyCustomWidget(), MyCustomWidget()], ), ), ); } } class MyCustomWidget extends StatefulWidget { const MyCustomWidget({super.key}); @override State createState() => _MyCustomWidgetState(); } class _MyCustomWidgetState extends State { Color _color = Colors.white; String _label = 'Unfocused'; @override Widget build(BuildContext context) { return Focus( onFocusChange: (focused) { setState(() { _color = focused ? Colors.black26 : Colors.white; _label = focused ? 'Focused' : 'Unfocused'; }); }, child: Center( child: Container( width: 300, height: 50, alignment: Alignment.center, color: _color, child: Text(_label), ), ), ); } } ``` -------------------------------- ### Java: MethodChannel setup in configureFlutterEngine Source: https://docs.flutter.dev/platform-integration/platform-channels Initialize a MethodChannel in the MainActivity class using Java to establish communication with Flutter. Set a MethodCallHandler to process platform method calls on the main thread. ```java import androidx.annotation.NonNull; import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.plugin.common.MethodChannel; public class MainActivity extends FlutterActivity { private static final String CHANNEL = "samples.flutter.dev/battery"; @Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { super.configureFlutterEngine(flutterEngine); new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL) .setMethodCallHandler( (call, result) -> { // This method is invoked on the main thread. // TODO } ``` -------------------------------- ### Install Flutter Pods for iOS Target Source: https://docs.flutter.dev/add-to-app/ios/project-setup Call `install_all_flutter_pods` for each target in your Podfile that needs to embed Flutter. This ensures all necessary Flutter frameworks and plugins are included. ```ruby target 'MyApp' do install_all_flutter_pods(flutter_application_path) end ``` -------------------------------- ### Migrating SystemContextMenuController.show to showWithItems Source: https://docs.flutter.dev/release/breaking-changes/system_context_menu_controller_show This section demonstrates the migration from the deprecated `SystemContextMenuController.show` method to the new `SystemContextMenuController.showWithItems` method, including how to obtain and format default context menu items. ```dart _controller.show(selectionRect); ``` ```dart final List defaultItems = SystemContextMenu.getDefaultItems(editableTextState); final WidgetsLocalizations localizations = WidgetsLocalizations.of(context); final List defaultItemDatas = defaultItems .map((IOSSystemContextMenuItem item) => item.getData(localizations)) .toList(); _controller.showWithItems(selectionRect, defaultItemDatas); ``` -------------------------------- ### Define Weather Enum in Swift and Dart Source: https://docs.flutter.dev/flutter-for/dart-swift-concurrency Basic enumeration to represent weather states used across the asynchronous examples. ```swift enum Weather: String { case rainy, sunny } ``` ```dart enum Weather { rainy, windy, sunny } ``` -------------------------------- ### Customized analysis_options.yaml with flutter_lints Source: https://docs.flutter.dev/release/breaking-changes/flutter-lints-package Complete example configuration showing how to include flutter_lints and customize lint rules. Demonstrates disabling specific rules and enabling additional rules via the linter section. ```yaml # This file configures the analyzer, which statically analyzes Dart code to # check for errors, warnings, and lints. # # The issues identified by the analyzer are surfaced in the UI of Dart-enabled # IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be # invoked from the command line by running `flutter analyze`. # The following line activates a set of recommended lints for Flutter apps, # packages, and plugins designed to encourage good coding practices. include: package:flutter_lints/flutter.yaml linter: # The lint rules applied to this project can be customized in the # section below to disable rules from the `package:flutter_lints/flutter.yaml` # included above or to enable additional rules. A list of all available lints # and their documentation is published at # https://dart-lang.github.io/linter/lints/index.html. # # Instead of disabling a lint rule for the entire project in the # section below, it can also be suppressed for a single line of code # or a specific dart file by using the `// ignore: name_of_lint` and # `// ignore_for_file: name_of_lint` syntax on the line or in the file # producing the lint. rules: # avoid_print: false # Uncomment to disable the `avoid_print` rule # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule # Additional information about this file can be found at # https://dart.dev/guides/language/analysis-options ``` -------------------------------- ### Check DevTools Version with Dart CLI Source: https://docs.flutter.dev/tools/devtools/release-notes Run this command to verify the current version of DevTools installed with your Dart SDK. ```bash $ dart devtools --version ``` -------------------------------- ### Mix-and-Match State Management with TapboxC Source: https://docs.flutter.dev/ui/interactivity This example demonstrates a mix-and-match state management approach. The `TapboxC` widget manages its internal `_highlight` state for visual feedback on tap, while its `_active` state is managed by the `ParentWidget` and updated via a callback. ```dart import 'package:flutter/material.dart'; //---------------------------- ParentWidget ---------------------------- class ParentWidget extends StatefulWidget { const ParentWidget({super.key}); @override State createState() => _ParentWidgetState(); } class _ParentWidgetState extends State { bool _active = false; void _handleTapboxChanged(bool newValue) { setState(() { _active = newValue; }); } @override Widget build(BuildContext context) { return SizedBox( child: TapboxC(active: _active, onChanged: _handleTapboxChanged), ); } } //----------------------------- TapboxC ------------------------------ class TapboxC extends StatefulWidget { const TapboxC({super.key, this.active = false, required this.onChanged}); final bool active; final ValueChanged onChanged; @override State createState() => _TapboxCState(); } class _TapboxCState extends State { bool _highlight = false; void _handleTapDown(TapDownDetails details) { setState(() { _highlight = true; }); } void _handleTapUp(TapUpDetails details) { setState(() { _highlight = false; }); } void _handleTapCancel() { setState(() { _highlight = false; }); } void _handleTap() { widget.onChanged(!widget.active); } @override Widget build(BuildContext context) { // This example adds a green border on tap down. // On tap up, the square changes to the opposite state. return GestureDetector( onTapDown: _handleTapDown, // Handle the tap events in the order that onTapUp: _handleTapUp, // they occur: down, up, tap, cancel onTap: _handleTap, onTapCancel: _handleTapCancel, child: Container( width: 200, height: 200, decoration: BoxDecoration( color: widget.active ? Colors.lightGreen[700] : Colors.grey[600], border: _highlight ? Border.all(color: Colors.teal[700]!, width: 10) : null, ), child: Center( child: Text( widget.active ? 'Active' : 'Inactive', style: const TextStyle(fontSize: 32, color: Colors.white), ), ), ), ); } } ``` -------------------------------- ### Define the Entry Point in JavaScript and Dart Source: https://docs.flutter.dev/flutter-for/react-native-devs JavaScript allows flexible entry point definition. Dart requires a top-level `main()` function as the app's starting point. ```JavaScript // JavaScript function startHere() { // Can be used as entry point } ``` ```Dart /// Dart void main() {} ``` -------------------------------- ### Migrating DropdownButtonFormField from value to initialValue Source: https://docs.flutter.dev/release/breaking-changes/deprecate-dropdownbuttonformfield-value Replace the deprecated 'value' parameter with 'initialValue' to set the starting selection of the form field. ```dart DropdownButtonFormField( value: 'Yellow', ), ``` ```dart DropdownButtonFormField( initialValue: 'Yellow', ), ``` -------------------------------- ### Create Main and Detail Screens with Image Source: https://docs.flutter.dev/cookbook/navigation/hero-animations This snippet defines two basic screens, `MainScreen` and `DetailScreen`, both displaying the same image. Tapping the image on the main screen navigates to the detail screen, and tapping on the detail screen navigates back. ```dart import 'package:flutter/material.dart'; class MainScreen extends StatelessWidget { const MainScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Main Screen')), body: GestureDetector( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) { return const DetailScreen(); }, ), ); }, child: Image.network('https://picsum.photos/250?image=9'), ), ); } } class DetailScreen extends StatelessWidget { const DetailScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: GestureDetector( onTap: () { Navigator.pop(context); }, child: Center( child: Image.network('https://picsum.photos/250?image=9'), ), ), ); } } ``` -------------------------------- ### Run Flutter app for simulator testing Source: https://docs.flutter.dev/platform-integration/ios/app-extensions Starts the application in debug mode, which is required for testing extensions on the iOS simulator. ```bash $ flutter run ``` -------------------------------- ### Implement Platform View and Factory in Objective-C Source: https://docs.flutter.dev/platform-integration/ios/platform-views Provides the header and implementation files for creating a platform view factory and view in Objective-C. ```objectivec #import ​ @interface FLNativeViewFactory : NSObject - (instancetype)initWithMessenger:(NSObject*)messenger; @end ​ @interface FLNativeView : NSObject ​ - (instancetype)initWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id _Nullable)args binaryMessenger:(NSObject*)messenger; ​ - (UIView*)view; @end ``` ```objectivec #import "FLNativeView.h" ​ @implementation FLNativeViewFactory { NSObject* _messenger; } ​ - (instancetype)initWithMessenger:(NSObject*)messenger { self = [super init]; if (self) { _messenger = messenger; } return self; } ​ - (NSObject*)createWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id _Nullable)args { return [[FLNativeView alloc] initWithFrame:frame viewIdentifier:viewId arguments:args binaryMessenger:_messenger]; } ​ /// Implementing this method is only necessary when the `arguments` in `createWithFrame` is not `nil`. - (NSObject*)createArgsCodec { ``` -------------------------------- ### Complete lib/main.dart with Key for Integration Testing Source: https://docs.flutter.dev/testing/integration-tests The full `lib/main.dart` file after adding a `Key` to the `FloatingActionButton`, essential for targeting the button in integration tests. ```dart import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Counter App', home: MyHomePage(title: 'Counter App Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(widget.title)), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text('You have pushed the button this many times:'), Text( '$_counter', style: Theme.of(context).textTheme.headlineMedium, ), ], ), ), floatingActionButton: FloatingActionButton( // Provide a Key to this button. This allows finding this // specific button inside the test suite, and tapping it. key: const Key('increment'), onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } } ``` -------------------------------- ### Implement URL Launching with url_launcher in Flutter Source: https://docs.flutter.dev/packages-and-plugins/using-packages?q=sdk%3Aflutter+platform%3Alinux This Flutter example uses the 'url_launcher' package to open a specified URL in the device's default browser when a button is pressed. ```dart import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(home: DemoPage()); } } class DemoPage extends StatelessWidget { const DemoPage({super.key}); void launchURL() { launchUrl(Uri.parse('https://flutter.dev')); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: ElevatedButton( onPressed: launchURL, child: const Text('Show Flutter homepage'), ), ), ); } } ``` -------------------------------- ### Custom LoggingShortcutManager Source: https://docs.flutter.dev/ui/interactivity/actions-and-shortcuts Subclass ShortcutManager to customize shortcut handling behavior. This example logs each key event that the Shortcuts widget handles. ```dart class LoggingShortcutManager extends ShortcutManager { @override KeyEventResult handleKeypress(BuildContext context, KeyEvent event) { final KeyEventResult result = super.handleKeypress(context, event); if (result == KeyEventResult.handled) { print('Handled shortcut $event in $context'); } return result; } } ``` -------------------------------- ### Run Flutter Drive Integration Tests on Web Server (Headless) Source: https://docs.flutter.dev/testing/integration-tests Execute integration tests in a headless web server environment using Flutter Drive for automated testing without a visible browser UI. ```bash $ flutter drive \ --driver=test_driver/integration_test.dart \ --target=integration_test/app_test.dart \ -d web-server ``` -------------------------------- ### Set App Store Connect environment variables Source: https://docs.flutter.dev/deployment/macos Configures the required credentials for API access using issuer ID, key ID, and the private key file content. ```bash export APP_STORE_CONNECT_ISSUER_ID=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee export APP_STORE_CONNECT_KEY_IDENTIFIER=ABC1234567 export APP_STORE_CONNECT_PRIVATE_KEY=`cat /path/to/api/key/AuthKey_XXXYYYZZZ.p8` ``` -------------------------------- ### Create React Native App Source: https://docs.flutter.dev/flutter-for/react-native-devs Command-line command to scaffold a new React Native project with the specified project name. ```bash $ create-react-native-app ``` -------------------------------- ### Instantiate ArticleViewModel in MainApp for Testing Source: https://docs.flutter.dev/learn/pathway/tutorial/change-notifier This snippet updates the MainApp widget to instantiate ArticleViewModel. This setup allows the ViewModel's getRandomArticleSummary method to be called on creation, facilitating early testing of HTTP requests. ```dart class MainApp extends StatelessWidget { const MainApp({super.key}); @override Widget build(BuildContext context) { // Instantiate your `ArticleViewModel` to test its HTTP requests. final viewModel = ArticleViewModel(ArticleModel()); return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Wikipedia Flutter'), ), body: const Center( child: Text('Check console for article data'), ), ), ); } } ``` -------------------------------- ### Basic Flutter Widget Hierarchy Example Source: https://docs.flutter.dev/resources/architectural-overview This snippet demonstrates a simple Flutter widget tree, showing how `Container`, `Row`, `Image`, and `Text` widgets are nested to form a UI layout. ```dart Container( color: Colors.blue, child: Row( children: [ Image.network('https://www.example.com/1.png'), const Text('A'), ], ), ); ``` -------------------------------- ### RawGestureDetector: Before explicit supportedDevices for PanGestureRecognizer Source: https://docs.flutter.dev/release/breaking-changes/trackpad-gestures This example shows `RawGestureDetector` usage where the `PanGestureRecognizer` is instantiated without explicitly setting its `supportedDevices` property. ```dart void main() => runApp(Foo()); class Foo extends StatelessWidget { @override Widget build(BuildContext context) { return RawGestureDetector( gestures: { PanGestureRecognizer: GestureRecognizerFactoryWithHandlers( () => PanGestureRecognizer(), (recognizer) { recognizer ..onStart = (details) { debugPrint('onStart'); } ..onUpdate = (details) { debugPrint('onUpdate'); } ..onEnd = (details) { debugPrint('onEnd'); }; }, ), }, child: Container() ); } } ``` -------------------------------- ### Example 5: Centered Container with infinite size request Source: https://docs.flutter.dev/ui/layout/constraints A Container requesting infinite size, when placed inside a Center, will fill the screen because it cannot exceed the screen's bounds. ```dart Center( child: Container( width: double.infinity, height: double.infinity, color: red, ), ) ``` -------------------------------- ### Initialize FlutterEngine in UIKit with Swift Source: https://docs.flutter.dev/add-to-app/ios/add-flutter-screen Instantiate and run the FlutterEngine within the AppDelegate to pre-warm the engine during application launch. ```swift import UIKit import Flutter // The following library connects plugins with iOS platform code to this app. import FlutterPluginRegistrant ​ @UIApplicationMain class AppDelegate: FlutterAppDelegate { // More on the FlutterAppDelegate. lazy var flutterEngine = FlutterEngine(name: "my flutter engine") ​ override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Runs the default Dart entrypoint with a default Flutter route. flutterEngine.run(); // Connects plugins with iOS platform code to this app. GeneratedPluginRegistrant.register(with: self.flutterEngine); return super.application(application, didFinishLaunchingWithOptions: launchOptions); } } ``` -------------------------------- ### Poorly-Organized LICENSE File with Missing Blank Line Source: https://docs.flutter.dev/packages-and-plugins/developing-packages Example of incorrect LICENSE file formatting. A blank line must separate package names from license text, and separators should be on their own line. ```text package_1 -------------------------------------------------------------------------------- ``` -------------------------------- ### Display asynchronous data in a Flutter ListView Source: https://docs.flutter.dev/flutter-for/xamarin-forms-devs A complete example of a StatefulWidget that fetches JSON data on initialization and renders it in a scrollable list. ```dart import 'dart:convert'; ​ import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; ​ void main() { runApp(const SampleApp()); } ​ class SampleApp extends StatelessWidget { const SampleApp({super.key}); ​ @override Widget build(BuildContext context) { return const MaterialApp(title: 'Sample App', home: SampleAppPage()); } } ​ class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); ​ @override State createState() => _SampleAppPageState(); } ​ class _SampleAppPageState extends State { List> data = []; ​ @override void initState() { super.initState(); loadData(); } ​ Future loadData() async { final Uri dataURL = Uri.parse('https://jsonplaceholder.typicode.com/posts'); final http.Response response = await http.get(dataURL); setState(() { data = (jsonDecode(response.body) as List).cast>(); }); } ​ Widget getRow(int index) { return Padding( padding: const EdgeInsets.all(10), child: Text('Row ${data[index]['title']}'), ); } ​ @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: ListView.builder( itemCount: data.length, itemBuilder: (context, index) { return getRow(index); }, ), ); } } ``` -------------------------------- ### Add Flutter SDK PATH to bash Source: https://docs.flutter.dev/install/add-to-path Add the Flutter bin directory to PATH in bash by appending to ~/.bashrc. Replace with your Flutter installation path. ```bash $ echo 'export PATH="/bin:$PATH"' >> ~/.bashrc ``` ```bash $ echo 'export PATH="$HOME/develop/flutter/bin:$PATH"' >> ~/.bashrc ``` -------------------------------- ### Create a Hello World app in React Native Source: https://docs.flutter.dev/flutter-for/react-native-devs Uses a functional component returning a View and Text. Requires imports from the react and react-native packages. ```javascript // React Native import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; ​ const App = () => { return ( Hello world! ); }; ​ const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center' } }); ​ export default App; ``` -------------------------------- ### Configure system instructions for custom widget usage Source: https://docs.flutter.dev/ai/genui/get-started Use PromptBuilder to define system instructions that tell the AI agent when and how to use the custom widget. Reference the CatalogItem name in the instructions. ```dart final promptBuilder = PromptBuilder.chat( catalog: catalog, instructions: ''' You are an expert in creating funny riddles. Every time I give you a word, generate a RiddleCard that displays one new riddle related to that word. Each riddle should have both a question and an answer. ''', ); ​ // Pass promptBuilder.systemPrompt to your LLM Config ``` -------------------------------- ### Add Flutter SDK PATH to zsh Source: https://docs.flutter.dev/install/add-to-path Add the Flutter bin directory to PATH in zsh by appending to ~/.zshenv. Replace with your Flutter installation path. ```bash $ echo 'export PATH="/bin:$PATH"' >> ~/.zshenv ``` ```bash $ echo 'export PATH="$HOME/develop/flutter/bin:$PATH"' >> ~/.zshenv ``` -------------------------------- ### Initialize and configure buffer stream for real-time audio Source: https://docs.flutter.dev/cookbook/audio/soloud Set up a buffer stream for streaming audio data in real time with specified buffering type, sample rate, channels, and format. ```dart final stream = SoLoud.instance.setBufferStream( bufferingType: BufferingType.released, sampleRate: 24000, channels: Channels.mono, format: BufferType.s16le, // pcm16bits ); ``` -------------------------------- ### Fetch and parse JSON data Source: https://docs.flutter.dev/cookbook/networking/fetch-data Perform an asynchronous GET request and convert the response body into a custom Dart object if successful. ```dart Future fetchAlbum() async { final response = await http.get( Uri.parse('https://jsonplaceholder.typicode.com/albums/1'), headers: {'Accept': 'application/json'}, ); ​ if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. return Album.fromJson(jsonDecode(response.body) as Map); } else { // If the server did not return a 200 OK response, // then throw an exception. throw Exception('Failed to load album'); } } ``` -------------------------------- ### Create a minimal Flutter project Source: https://docs.flutter.dev/learn/pathway/tutorial/set-up-state-project Use the --empty flag with the flutter create command to generate a project without default boilerplate code. ```bash flutter create ``` ```bash --empty ``` -------------------------------- ### Request audio recording permissions Source: https://docs.flutter.dev/cookbook/audio/record Check for microphone permissions before starting a recording session; platform-specific configuration may also be required. ```dart final recorder = AudioRecorder(); if (await recorder.hasPermission()) { // Permission granted, proceed with recording. } else { // Permission denied. } ``` -------------------------------- ### Basic custom flutter_bootstrap.js script Source: https://docs.flutter.dev/platform-integration/web/initialization Minimal custom bootstrap script that includes required tokens ({{flutter_js}} and {{flutter_build_config}}) and calls _flutter.loader.load() to start the Flutter app. ```javascript {{flutter_js}} {{flutter_build_config}} ​ _flutter.loader.load(); ``` -------------------------------- ### Package.swift template for Flutter plugin Source: https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-plugin-authors Complete Package.swift template with platform configuration, library/target setup, and Flutter framework dependency. Update plugin_name, platforms, and resources as needed for your plugin. ```swift // swift-tools-version: 5.9 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( // TODO: Update your plugin name. name: "plugin_name", platforms: [ // TODO: Update the platforms your plugin supports. // If your plugin only supports iOS, remove `.macOS(...)`. // If your plugin only supports macOS, remove `.iOS(...)`. .iOS("13.0"), .macOS("10.15") ], products: [ // TODO: Update your library and target names. // If the plugin name contains "_", replace with "-" for the library name. .library(name: "plugin-name", targets: ["plugin_name"]) ], dependencies: [ .package(name: "FlutterFramework", path: "../FlutterFramework") ], targets: [ .target( // TODO: Update your target name. name: "plugin_name", dependencies: [ .product(name: "FlutterFramework", package: "FlutterFramework") ], resources: [ // TODO: If your plugin requires a privacy manifest // (e.g. if it uses any required reason APIs), update the PrivacyInfo.xcprivacy file // to describe your plugin's privacy impact, and then uncomment this line. // For more information, see: // https://developer.apple.com/documentation/bundleresources/privacy_manifest_files // .process("PrivacyInfo.xcprivacy"), // TODO: If you have other resources that need to be bundled with your plugin, refer to // the following instructions to add them: // https://developer.apple.com/documentation/xcode/bundling-resources-with-a-swift-package ] ) ] ) ``` ```swift let package = Package( // TODO: Update your plugin name. name: "plugin_name", platforms: [ .iOS("13.0"), .macOS("10.15") ], products: [ // TODO: Update your library and target names. // If the plugin name contains "_", replace with "-" for the library name .library(name: "plugin-name", targets: ["plugin_name"]) ], dependencies: [], targets: [ .target( // TODO: Update your target name. name: "plugin_name", dependencies: [], resources: [ // TODO: If your plugin requires a privacy manifest // (e.g. if it uses any required reason APIs), update the PrivacyInfo.xcprivacy file // to describe your plugin's privacy impact, and then uncomment this line. // For more information, see: // https://developer.apple.com/documentation/bundleresources/privacy_manifest_files // .process("PrivacyInfo.xcprivacy"), // TODO: If you have other resources that need to be bundled with your plugin, refer to // the following instructions to add them: // https://developer.apple.com/documentation/xcode/bundling-resources-with-a-swift-package ] ) ] ) ``` -------------------------------- ### Complete Authenticated Request with JSON Parsing Source: https://docs.flutter.dev/cookbook/networking/authenticated-requests Full example demonstrating authenticated HTTP request with JSON deserialization using pattern matching. Requires dart:async, dart:convert, dart:io, and the http package. ```dart import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; Future fetchAlbum() async { final response = await http.get( Uri.parse('https://jsonplaceholder.typicode.com/albums/1'), // Send authorization headers to the backend. headers: {HttpHeaders.authorizationHeader: 'Basic your_api_token_here'}, ); final responseJson = jsonDecode(response.body) as Map; return Album.fromJson(responseJson); } class Album { final int userId; final int id; final String title; const Album({required this.userId, required this.id, required this.title}); factory Album.fromJson(Map json) { return switch (json) { {'userId': int userId, 'id': int id, 'title': String title} => Album( userId: userId, id: id, title: title, ), _ => throw const FormatException('Failed to load album.'), }; } } ``` -------------------------------- ### Migrating RawMenuAnchor Close Order Handling Source: https://docs.flutter.dev/release/breaking-changes/raw-menu-anchor-close-order This example demonstrates the changes required when migrating `RawMenuAnchor` configurations to align with the new coordinated close order. The `menuController.closeChildren()` call is now handled automatically. ```dart RawMenuAnchor( controller: menuController, onCloseRequested: (hideOverlay) { if (!animationController.isForwardOrCompleted) { return; } // Descendant submenus must be closed before the parent menu. This is now // handled automatically, so this call is no longer necessary. menuController.closeChildren(); animationController.reverse().whenComplete(hideOverlay); }, onClose: () { // This might have executed before descendants called onClose(). _handleMenuClosed(); }, // ... ) ``` ```dart RawMenuAnchor( controller: menuController, onCloseRequested: (hideOverlay) { if (!animationController.isForwardOrCompleted) { return; } // menuController.closeChildren() is now called automatically. animationController.reverse().whenComplete(hideOverlay); }, onClose: () { // This now executes only after all descendant submenus have called onClose(). _handleMenuClosed(); }, // ... ) ``` -------------------------------- ### Flutter doctor verbose output example Source: https://docs.flutter.dev/resources/bug-reports Sample output from running `flutter doctor -v` command showing Flutter, Android, iOS, and IDE toolchain versions and configurations. Paste this into GitHub issues to help diagnose environment-related problems. ```text [✓] Flutter (Channel stable, 1.22.3, on Mac OS X 10.15.7 19H2, locale en-US) • Flutter version 1.22.3 at /Users/me/projects/flutter • Framework revision 8874f21e79 (5 days ago), 2020-10-29 14:14:35 -0700 • Engine revision a1440ca392 • Dart version 2.10.3 [✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2) • Android SDK at /Users/me/Library/Android/sdk • Platform android-30, build-tools 29.0.2 • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593) • All Android licenses accepted. [✓] Xcode - develop for iOS and macOS (Xcode 12.2) • Xcode at /Applications/Xcode.app/Contents/Developer • Xcode 12.2, Build version 12B5035g • CocoaPods version 1.9.3 [✓] Android Studio (version 4.0) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin version 50.0.1 • Dart plugin version 193.7547 • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593) [✓] VS Code (version 1.50.1) • VS Code at /Applications/Visual Studio Code.app/Contents • Flutter extension version 3.13.2 [✓] Connected device (1 available) • iPhone (mobile) • 00000000-0000000000000000 • ios • iOS 14.0 ``` -------------------------------- ### Implement onGenerateRoute with route prefix parsing Source: https://docs.flutter.dev/cookbook/effects/nested-nav Use onGenerateRoute to match exact routes for home and settings, and parse the setup flow prefix to extract the sub-route name. Pass the extracted sub-route to the SetupFlow widget for nested navigation handling. ```dart onGenerateRoute: (settings) { final Widget page; if (settings.name == routeHome) { page = const HomeScreen(); } else if (settings.name == routeSettings) { page = const SettingsScreen(); } else if (settings.name!.startsWith(routePrefixDeviceSetup)) { final subRoute = settings.name!.substring( routePrefixDeviceSetup.length, ); page = SetupFlow(setupPageRoute: subRoute); } else { throw Exception('Unknown route: ${settings.name}'); } return MaterialPageRoute( builder: (context) { return page; }, settings: settings, ); }, ``` -------------------------------- ### Create `test_driver` Directory Source: https://docs.flutter.dev/testing/integration-tests Create a new directory named `test_driver` within your project to store integration test driver files. ```bash $ mkdir test_driver ``` -------------------------------- ### Initialize Multi-View App with runWidget Source: https://docs.flutter.dev/platform-integration/web/embedding-flutter-web In multi-view mode, replace `runApp` with `runWidget` in your `main.dart` to initialize the application without relying on an `implicitView`. This example uses `MultiViewApp` to render `MyApp` into all available views. ```dart void main() { runWidget( MultiViewApp( viewBuilder: (BuildContext context) => const MyApp(), ), ); } ``` -------------------------------- ### Add Flutter SDK bin to PATH on ChromeOS Source: https://docs.flutter.dev/install/add-to-path Use this command to append the Flutter SDK's 'bin' directory to your 'PATH' environment variable in '~/.bash_profile'. Replace '' with your actual Flutter SDK installation path. ```bash $ echo 'export PATH=":$PATH"' >> ~/.bash_profile ``` -------------------------------- ### Create a Custom Widget by Composition in Flutter Source: https://docs.flutter.dev/flutter-for/android-devs This example shows how to build a `CustomButton` widget by composing an `ElevatedButton` and a `Text` widget, illustrating Flutter's widget composition pattern. ```dart class CustomButton extends StatelessWidget { final String label; const CustomButton(this.label, {super.key}); @override Widget build(BuildContext context) { return ElevatedButton(onPressed: () {}, child: Text(label)); } } ``` -------------------------------- ### Create a Scaffold with drawer in Flutter Source: https://docs.flutter.dev/cookbook/design/drawer Basic Scaffold setup with a drawer property. The Scaffold provides the Material Design structure and the drawer parameter accepts a Drawer widget. ```dart Scaffold( appBar: AppBar(title: const Text('AppBar without hamburger button')), drawer: // Add a Drawer here in the next step. ); ``` -------------------------------- ### Integrate english_words Package into a Flutter App Source: https://docs.flutter.dev/packages-and-plugins/using-packages?q=sdk%3Aflutter+platform%3Alinux This example demonstrates how to use the 'english_words' package to display a random word pair in a Flutter application. ```dart import 'package:english_words/english_words.dart'; import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(home: DemoPage()); } } class DemoPage extends StatelessWidget { const DemoPage({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Center(child: Text(generateWordPairs().first.asPascalCase)), ); } } ``` -------------------------------- ### Initialize GenUI with Google Generative AI Source: https://docs.flutter.dev/ai/genui/get-started Create instances of `SurfaceController`, `A2uiTransportAdapter`, `PromptBuilder`, `GenerativeModel`, and `Conversation` to integrate GenUI with Google Gemini AI for local testing. ```dart import 'package:genui/genui.dart'; import 'package:google_generative_ai/google_generative_ai.dart'; final catalog = Catalog(components: [ // ... ]); final catalogs = [catalog]; final surfaceController = SurfaceController(catalogs: catalogs); final transportAdapter = A2uiTransportAdapter(); transportAdapter.messageStream.listen(surfaceController.handleMessage); final promptBuilder = PromptBuilder.chat( catalog: catalog, instructions: 'You are a helpful assistant.', ); final model = GenerativeModel( model: 'gemini-2.5-flash', apiKey: 'YOUR_API_KEY', // Or set GEMINI_API_KEY environment variable. systemInstruction: Content.system(promptBuilder.systemPrompt), ); final conversation = Conversation( surfaceController: surfaceController, transportAdapter: transportAdapter, ); ``` -------------------------------- ### Initialize GamePage with Column layout Source: https://docs.flutter.dev/learn/pathway/tutorial/layout Replace the default container with a Padding and Column widget to start the layout. The spacing property defines the gap between children along the main axis. ```dart class GamePage extends StatelessWidget { GamePage({super.key}); // This manages game logic, and is out of scope for this lesson. final Game _game = Game(); ​ @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(8.0), child: Column( spacing: 5.0, children: [ // Add children next. ], ), ); } } ``` -------------------------------- ### Create the base Flutter app in main.dart Source: https://docs.flutter.dev/ui/layout/tutorial Initializes a basic Flutter application with a Scaffold and AppBar. Replace the contents of lib/main.dart with this code to begin the layout tutorial. ```dart import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const String appTitle = 'Flutter layout demo'; return MaterialApp( title: appTitle, home: Scaffold( appBar: AppBar(title: const Text(appTitle)), body: const Center( child: Text('Hello World'), ), ), ); } } ``` -------------------------------- ### Sample User JSON model Source: https://docs.flutter.dev/data-and-backend/serialization/json A basic JSON structure representing a user with name and email fields, used as a baseline for serialization examples. ```json { "name": "John Smith", "email": "john@example.com" } ``` -------------------------------- ### Poorly-Organized LICENSE File Without Package Names Source: https://docs.flutter.dev/packages-and-plugins/developing-packages Example of incorrect LICENSE file formatting. License text should always be preceded by package names to clarify which packages each license applies to. ```text -------------------------------------------------------------------------------- ``` -------------------------------- ### Build a GridView with two columns in Dart Source: https://docs.flutter.dev/cookbook/design/orientation This snippet shows how to create a basic `GridView` with a fixed number of columns. It serves as a starting point before adapting to orientation changes. ```dart return GridView.count( // A list with 2 columns crossAxisCount: 2, // ... ); ``` -------------------------------- ### Row with Flexible Widgets Source: https://docs.flutter.dev/ui/layout/constraints This example demonstrates using Flexible widgets within a Row. Flexible allows its child to be the same or smaller width than itself, unlike Expanded which forces an exact match. ```dart Row( children: [ Flexible( child: Container( color: red, child: const Text( 'This is a very long text that won\'t fit the line.', style: big, ), ), ), Flexible( child: Container( color: green, child: const Text('Goodbye!', style: big), ), ), ], ) ``` -------------------------------- ### Complete custom font implementation in Dart Source: https://docs.flutter.dev/cookbook/design/fonts Full example showing how to set a default app font in ThemeData and override it for specific widgets. ```dart import 'package:flutter/material.dart'; ​ void main() => runApp(const MyApp()); ​ class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Custom Fonts', // Set Raleway as the default app font. theme: ThemeData(fontFamily: 'Raleway'), home: const MyHomePage(), ); } } ​ class MyHomePage extends StatelessWidget { const MyHomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( // The AppBar uses the app-default Raleway font. appBar: AppBar(title: const Text('Custom Fonts')), body: const Center( // This Text widget uses the RobotoMono font. child: Text( 'Roboto Mono sample', style: TextStyle(fontFamily: 'RobotoMono'), ), ), ); } } ``` -------------------------------- ### Dictionary API JSON Response Structure Source: https://docs.flutter.dev/ai/best-practices/tool-calls Example of the JSON data returned by the Free Dictionary API when the LLM requests word details. ```json [ { "word": "tool", "phonetic": "/tuːl/", "phonetics": [ { "text": "/tuːl/", "audio": "https://api.dictionaryapi.dev/media/pronunciations/en/tool-uk.mp3", "sourceUrl": "https://commons.wikimedia.org/w/index.php?curid=94709459", "license": { "name": "BY-SA 4.0", "url": "https://creativecommons.org/licenses/by-sa/4.0" } } ], "meanings": [ { "partOfSpeech": "noun", "definitions": [ { "definition": "A mechanical device intended to make a task easier.", "synonyms": [], "antonyms": [], "example": "Hand me that tool, would you? I don't have the right tools to start fiddling around with the engine." }, ... ] ``` -------------------------------- ### Well-Organized LICENSE File with Shared License Source: https://docs.flutter.dev/packages-and-plugins/developing-packages Format a LICENSE file where multiple packages share the same license. List all package names before the license text, separated by a blank line. ```text package_1 -------------------------------------------------------------------------------- package_1 package_2 ``` -------------------------------- ### Generate API Documentation with dart doc Source: https://docs.flutter.dev/packages-and-plugins/developing-packages Run the dart doc tool to generate API documentation locally. Use the appropriate command path for your operating system. ```bash $FLUTTER_ROOT/bin/cache/dart-sdk/bin/dart doc # on macOS or Linux ``` ```bash %FLUTTER_ROOT%\bin\cache\dart-sdk\bin\dart doc # on Windows ``` -------------------------------- ### Display Flutter test command help Source: https://docs.flutter.dev/cookbook/testing/unit/introduction View all available options and usage information for the `flutter test` command. ```bash flutter test --help ``` -------------------------------- ### Specifying Package Dependencies in pubspec.yaml Source: https://docs.flutter.dev/packages-and-plugins/using-packages?q=sdk%3Aflutter+platform%3Alinux This snippet shows examples of specifying package dependencies using version ranges and exact versions in a `pubspec.yaml` file. Using version ranges is recommended to avoid potential conflicts. ```yaml dependencies: url_launcher: ^5.4.0 # Good, any version >= 5.4.0 but < 6.0.0 image_picker: '5.4.3' # Not so good, only version 5.4.3 works. ``` -------------------------------- ### Initiate Code Modification with Gemini CLI Source: https://docs.flutter.dev/ai/gemini-cli-extension To begin a guided development session for modifying existing code, use the /modify command. This command will prompt for your goals and generate a modification plan. ```bash /modify ``` -------------------------------- ### Create a new Flutter project with CLI Source: https://docs.flutter.dev/learn/pathway/tutorial/create-an-app Use the Flutter CLI to generate a new project with the minimal empty template. Run this command in your terminal from the desired parent directory. ```bash $ flutter create birdle --empty ``` -------------------------------- ### Add sentry_flutter package dependency Source: https://docs.flutter.dev/cookbook/maintenance/error-reporting Install the sentry_flutter package using flutter pub add command to enable error reporting to Sentry. ```shell $ flutter pub add sentry_flutter ``` -------------------------------- ### flutter emulators Source: https://docs.flutter.dev/reference/flutter-cli List, launch and create emulators. ```APIDOC ## COMMAND flutter emulators ### Description List, launch and create emulators. ### Usage `flutter emulators` ### Arguments N/A (subcommands like `list`, `launch`, `create` are implied but not detailed) ### Request Example N/A ### Response #### Success Response (0) - **Output** (string) - List of emulators or status of emulator operation. #### Response Example N/A ``` -------------------------------- ### Validate Linux toolchain with flutter doctor Source: https://docs.flutter.dev/platform-integration/linux/setup Run this command to check for issues with your development setup and verify that the Linux toolchain is correctly configured. ```bash $ flutter doctor -v ``` -------------------------------- ### Set up advanced regex-based proxy rules Source: https://docs.flutter.dev/platform-integration/web/web-dev-config-file Use regex for complex path matching and capture group replacements in proxy targets. ```yaml server: proxy: - target: "http://localhost:5000/" regex: "/users/(\d+)/$" # Path matches requests like /users/123/ - target: "http://localhost:4000/" regex: "^/api/(v\d+)/(.*)" # Matches requests like /api/v1/users replace: "/$2?apiVersion=$1" # Allows capture groups (optional)" ``` -------------------------------- ### Launch DevTools via Dart CLI Source: https://docs.flutter.dev/learn/pathway/tutorial/devtools Run this command in a separate terminal window while your app is in debug mode to start the DevTools server. ```shell $ dart devtools ``` -------------------------------- ### Full Flutter Isolate Example Application Source: https://docs.flutter.dev/flutter-for/uikit-devs This complete Flutter application demonstrates how to integrate Isolates for background processing and update the UI safely from the main thread. It includes necessary imports and widget structure. ```dart import 'dart:async'; import 'dart:convert'; import 'dart:isolate'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; void main() { runApp(const SampleApp()); } class SampleApp extends StatelessWidget { const SampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(title: 'Sample App', home: SampleAppPage()); } } class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); @override State createState() => _SampleAppPageState(); } class _SampleAppPageState extends State { List> data = []; @override void initState() { super.initState(); loadData(); } bool get showLoadingDialog => data.isEmpty; Future loadData() async { final ReceivePort receivePort = ReceivePort(); await Isolate.spawn(dataLoader, receivePort.sendPort); // The 'echo' isolate sends its SendPort as the first message. final SendPort sendPort = await receivePort.first as SendPort; final List> msg = await sendReceive( sendPort, 'https://jsonplaceholder.typicode.com/posts', ); setState(() { data = msg; }); } // The entry point for the isolate. static Future dataLoader(SendPort sendPort) async { // Open the ReceivePort for incoming messages. final ReceivePort port = ReceivePort(); // Notify any other isolates what port this isolate listens to. sendPort.send(port.sendPort); await for (final dynamic msg in port) { final String url = msg[0] as String; final SendPort replyTo = msg[1] as SendPort; final Uri dataURL = Uri.parse(url); ``` -------------------------------- ### Complete Flutter DELETE request example Source: https://docs.flutter.dev/cookbook/networking/delete-data Demonstrates fetching an album and then deleting it via an HTTP DELETE call. Note the use of Album.empty() to avoid null issues in FutureBuilder. ```dart import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; Future fetchAlbum() async { final response = await http.get( Uri.parse('https://jsonplaceholder.typicode.com/albums/1'), ); if (response.statusCode == 200) { // If the server did return a 200 OK response, then parse the JSON. return Album.fromJson(jsonDecode(response.body) as Map); } else { // If the server did not return a 200 OK response, then throw an exception. throw Exception('Failed to load album'); } } Future deleteAlbum(String id) async { final http.Response response = await http.delete( Uri.parse('https://jsonplaceholder.typicode.com/albums/$id'), headers: { 'Content-Type': 'application/json; charset=UTF-8', }, ); if (response.statusCode == 200) { // If the server did return a 200 OK response, // then return an empty Album. After deleting, // you'll get an empty JSON `{}` response. // Don't return `null`, otherwise `snapshot.hasData` // will always return false on `FutureBuilder`. return Album.empty(); } else { // If the server did not return a "200 OK response", // then throw an exception. throw Exception('Failed to delete album.'); } } class Album { int? id; String? title; Album({this.id, this.title}); Album.empty(); factory Album.fromJson(Map json) { return switch (json) { {'id': int id, 'title': String title} => Album(id: id, title: title), _ => throw const FormatException('Failed to load album.'), }; } } void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() { return _MyAppState(); } } class _MyAppState extends State { late Future _futureAlbum; @override void initState() { super.initState(); _futureAlbum = fetchAlbum(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Delete Data Example', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: Scaffold( appBar: AppBar(title: const Text('Delete Data Example')), body: Center( child: FutureBuilder( future: _futureAlbum, builder: (context, snapshot) { // If the connection is done, // check for response data or an error. if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasData) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(snapshot.data?.title ?? 'Deleted'), ElevatedButton( child: const Text('Delete Data'), onPressed: () { setState(() { _futureAlbum = deleteAlbum( snapshot.data!.id.toString(), ); }); }, ), ], ); } else if (snapshot.hasError) { return Text('${snapshot.error}'); } } // By default, show a loading spinner. return const CircularProgressIndicator(); }, ), ), ), ); } } ``` -------------------------------- ### Initialize Staggered Animation in initState Source: https://docs.flutter.dev/cookbook/effects/staggered-menu-animation Start the staggered animation when the menu becomes visible by creating animation intervals and forwarding the AnimationController in initState(). ```Dart @override void initState() { super.initState(); _createAnimationIntervals(); _staggeredController = AnimationController( vsync: this, duration: _animationDuration, )..forward(); } ``` -------------------------------- ### Initialize FlutterEngine in UIKit with Objective-C Source: https://docs.flutter.dev/add-to-app/ios/add-flutter-screen Define the FlutterEngine in the AppDelegate header and initialize it in the implementation file during app startup. ```objectivec @import UIKit; @import Flutter; ​ @interface AppDelegate : FlutterAppDelegate // More on the FlutterAppDelegate below. @property (nonatomic,strong) FlutterEngine *flutterEngine; @end ``` ```objectivec // The following library connects plugins with iOS platform code to this app. #import ​ #import "AppDelegate.h" ​ @implementation AppDelegate ​ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.flutterEngine = [[FlutterEngine alloc] initWithName:@"my flutter engine"]; // Runs the default Dart entrypoint with a default Flutter route. [self.flutterEngine run]; // Connects plugins with iOS platform code to this app. [GeneratedPluginRegistrant registerWithRegistry:self.flutterEngine]; return [super application:application didFinishLaunchingWithOptions:launchOptions]; } ​ @end ``` -------------------------------- ### Navigate to project directory and run Flutter app Source: https://docs.flutter.dev/learn/pathway/tutorial/create-an-app Change to the project root directory and use the Flutter CLI to run the app. The -d chrome flag launches the app in a Chrome browser instance. ```bash $ cd birdle ``` ```bash $ flutter run -d chrome ``` -------------------------------- ### Well-Organized LICENSE File with Single License Source: https://docs.flutter.dev/packages-and-plugins/developing-packages Format a LICENSE file with a single package license. Use 80 hyphens as a separator line when multiple licenses are present. ```text package_1 -------------------------------------------------------------------------------- package_2 ``` -------------------------------- ### HighlightTextEditingController with BuildContext parameter Source: https://docs.flutter.dev/release/breaking-changes/buildtextspan-buildcontext This example shows how a custom `TextEditingController` can access `Theme.of(context).accentColor` directly within `buildTextSpan` after the `BuildContext` parameter was introduced, removing the need to pass the color explicitly. ```dart class HighlightTextEditingController extends TextEditingController { @override TextSpan buildTextSpan({required BuildContext context, TextStyle? style, required bool withComposing}) { final Color color = Theme.of(context).accentColor; return super.buildTextSpan(context: context, style: TextStyle(color: color), withComposing: withComposing); } } ``` -------------------------------- ### Dynamically Load Deferred Dart Library with FutureBuilder Source: https://docs.flutter.dev/perf/deferred-components Import the deferred Dart library and use `FutureBuilder` to asynchronously load it with `loadLibrary()`. This example displays a loading indicator until the library is available, then renders the deferred widget. ```dart import 'package:flutter/material.dart'; import 'box.dart' deferred as box; class SomeWidget extends StatefulWidget { const SomeWidget({super.key}); @override State createState() => _SomeWidgetState(); } class _SomeWidgetState extends State { late Future _libraryFuture; @override void initState() { super.initState(); _libraryFuture = box.loadLibrary(); } @override Widget build(BuildContext context) { return FutureBuilder( future: _libraryFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } return box.DeferredBox(); } return const CircularProgressIndicator(); }, ); } } ``` -------------------------------- ### Launch FlutterActivity with default intent Source: https://docs.flutter.dev/add-to-app/android/add-flutter-screen Launch FlutterActivity using its default intent, which assumes a 'main()' Dart entrypoint and '/' initial route. This example shows how to trigger the launch from an OnClickListener. ```kotlin MyButton(onClick = { startActivity( FlutterActivity.createDefaultIntent(this) ) }) @Composable fun MyButton(onClick: () -> Unit) { Button(onClick = onClick) { Text("Launch Flutter!") } } ``` ```kotlin myButton.setOnClickListener { startActivity( FlutterActivity.createDefaultIntent(this) ) } ``` ```java myButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity( FlutterActivity.createDefaultIntent(currentActivity) ); } }); ``` -------------------------------- ### Complete Flutter app with asynchronous data loading and ListView display Source: https://docs.flutter.dev/flutter-for/uikit-devs Full example showing a StatefulWidget that loads JSON data asynchronously in initState() and displays it in a ListView.builder. Requires http and dart:convert imports. ```dart import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; void main() { runApp(const SampleApp()); } class SampleApp extends StatelessWidget { const SampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(title: 'Sample App', home: SampleAppPage()); } } class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); @override State createState() => _SampleAppPageState(); } class _SampleAppPageState extends State { List> data = []; @override void initState() { super.initState(); loadData(); } Future loadData() async { final Uri dataURL = Uri.parse('https://jsonplaceholder.typicode.com/posts'); final http.Response response = await http.get(dataURL); setState(() { data = (jsonDecode(response.body) as List).cast>(); }); } Widget getRow(int index) { return Padding( padding: const EdgeInsets.all(10), child: Text('Row ${data[index]['title']}'), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: ListView.builder( itemCount: data.length, itemBuilder: (context, index) { return getRow(index); }, ), ); } } ``` -------------------------------- ### Build app bundle for Android size estimation Source: https://docs.flutter.dev/perf/app-size Generate an upload package (.aab file) for Android to measure app size via Google Play Console. This is the first step before uploading to check download and install sizes. ```bash flutter build appbundle ``` -------------------------------- ### Running default and non-default flavors Source: https://docs.flutter.dev/tools/pubspec Run the default flavor without specifying --flavor, or use --flavor to run non-default flavors. ```console // Use this command to run the default flavor (production). flutter run // Use this command to run non-default flavors (staging). flutter run --flavor staging ``` -------------------------------- ### Text Truncation with Ellipsis in CSS Source: https://docs.flutter.dev/flutter-for/web-devs CSS example using webkit properties to limit text display to 2 lines with ellipsis overflow handling. ```css .grey-box { background-color: #e0e0e0; /* grey 300 */ width: 320px; height: 240px; font: 900 24px Roboto; display: flex; align-items: center; justify-content: center; } .red-box { background-color: #ef5350; /* red 400 */ padding: 16px; color: #ffffff; overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; } ``` -------------------------------- ### Configure localization tool in l10n.yaml Source: https://docs.flutter.dev/ui/internationalization Create this file in the project root to define input directories and output file names for the localization tool. ```yaml arb-dir: lib/l10n template-arb-file: app_en.arb output-localization-file: app_localizations.dart ``` -------------------------------- ### Letter Spacing in CSS Source: https://docs.flutter.dev/flutter-for/web-devs CSS example showing letter-spacing property applied to a red box containing text within a centered grey container. ```css .grey-box { background-color: #e0e0e0; /* grey 300 */ width: 320px; height: 240px; font: 900 24px Roboto; display: flex; align-items: center; justify-content: center; } .red-box { background-color: #ef5350; /* red 400 */ padding: 16px; color: #ffffff; letter-spacing: 4px; } ``` -------------------------------- ### LayoutBuilder setState Migration - Before and After Source: https://docs.flutter.dev/release/breaking-changes/layout-builder-optimization Counter example demonstrating the missing setState call in the before version and its correction in the after version. The builder function depends on _counter, so setState must wrap the counter increment to trigger widget rebuild. ```dart import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: Counter(), ); } } class Counter extends StatefulWidget { Counter({Key key}) : super(key: key); @override _CounterState createState() => _CounterState(); } class _CounterState extends State { int _counter = 0; @override Widget build(BuildContext context) { return Center(child: Container( child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return _ResizingBox( TextButton( onPressed: () { _counter++; }, child: Text('Increment Counter')), Text(_counter.toString()), ); }, ), )); } } class _ResizingBox extends StatefulWidget { _ResizingBox(this.child1, this.child2); final Widget child1; final Widget child2; @override State createState() => _ResizingBoxState(); } class _ResizingBoxState extends State<_ResizingBox> with SingleTickerProviderStateMixin { Animation animation; @override void initState() { super.initState(); animation = AnimationController( vsync: this, duration: const Duration(minutes: 1), ) ..forward() ..addListener(() { setState(() {}); }); } @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.min, children: [ SizedBox( width: 100 + animation.value * 100, child: widget.child1, ), SizedBox( width: 100 + animation.value * 100, child: widget.child2, ), ], ); } } ``` ```dart import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: Counter(), ); } } class Counter extends StatefulWidget { Counter({Key key}) : super(key: key); @override _CounterState createState() => _CounterState(); } class _CounterState extends State { int _counter = 0; @override Widget build(BuildContext context) { return Center(child: Container( child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return _ResizingBox( TextButton( onPressed: () { setState(() { _counter++; }); }, child: Text('Increment Counter')), Text(_counter.toString()), ); }, ), )); } } class _ResizingBox extends StatefulWidget { _ResizingBox(this.child1, this.child2); final Widget child1; final Widget child2; @override State createState() => _ResizingBoxState(); } class _ResizingBoxState extends State<_ResizingBox> with SingleTickerProviderStateMixin { Animation animation; @override void initState() { super.initState(); animation = AnimationController( vsync: this, duration: const Duration(minutes: 1), ) ..forward() ..addListener(() { setState(() {}); }); } @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.min, children: [ SizedBox( width: 100 + animation.value * 100, child: widget.child1, ), SizedBox( width: 100 + animation.value * 100, child: widget.child2, ), ], ); } } ``` -------------------------------- ### Create Flutter app with go_router Source: https://docs.flutter.dev/cookbook/navigation/set-up-app-links Initialize a new Flutter project and add the go_router package for handling deep link routing. ```bash $ flutter create deeplink_cookbook ``` ```bash $ flutter pub add go_router ``` -------------------------------- ### Configure Shanghai Jiao Tong University Mirror on macOS/Linux/ChromeOS Source: https://docs.flutter.dev/community/china Set environment variables to use the Shanghai Jiao Tong University mirror for Flutter SDK and pub packages on Unix-like systems. ```bash export PUB_HOSTED_URL=https://mirror.sjtu.edu.cn/dart-pub export FLUTTER_STORAGE_BASE_URL=https://mirror.sjtu.edu.cn ``` -------------------------------- ### Test Android App Links using ADB Source: https://docs.flutter.dev/cookbook/navigation/set-up-app-links Use this command to trigger an intent and verify that the app handles the specific URL correctly. Replace and with your actual values. ```bash adb shell 'am start -a android.intent.action.VIEW \ -c android.intent.category.BROWSABLE \ -d "http:///details"' \ ``` -------------------------------- ### Remove the Flutter SDK installation directory Source: https://docs.flutter.dev/install/uninstall Deletes the directory where the Flutter SDK was extracted. Use the command corresponding to your operating system's shell. ```powershell $ Remove-Item -Recurse -Force -Path (Join-Path $env:USERPROFILE "develop\flutter") ``` ```bash $ rm -rf ~/develop/flutter ``` -------------------------------- ### Open main.dart file Source: https://docs.flutter.dev/cookbook/design/fonts Command to open the main entry point file of the Flutter application. ```shell $ vi lib/main.dart ``` -------------------------------- ### Add google_mobile_ads Plugin Dependency Source: https://docs.flutter.dev/cookbook/plugins/google-mobile-ads Install the google_mobile_ads package using flutter pub add command. This adds the plugin to your pubspec.yaml and downloads dependencies. ```bash $ flutter pub add google_mobile_ads ``` -------------------------------- ### Add json_schema_builder dependency with dart pub Source: https://docs.flutter.dev/ai/genui/get-started Install the json_schema_builder package as a dependency using the Dart CLI. This package is required for defining widget schemas. ```bash $ dart pub add json_schema_builder ``` -------------------------------- ### Check build target obfuscation support Source: https://docs.flutter.dev/deployment/obfuscate Verify that your build target supports the `--obfuscate` and `--split-debug-info` options before attempting obfuscation. ```bash $ flutter build -h ``` -------------------------------- ### Build APK with splits-per-abi flag Source: https://docs.flutter.dev/release/breaking-changes/default-abi-filters-android Use this command to create separate APKs for each architecture, which automatically disables the default abiFilters configuration. ```bash flutter build apk --splits-per-abi ``` -------------------------------- ### Create a Flutter project with Kotlin Source: https://docs.flutter.dev/deployment/flavors Initializes a new Flutter project with Kotlin as the preferred language for Android development. ```console $ flutter create --android-language kotlin flavors_example ``` -------------------------------- ### Example 9: ConstrainedBox with parent overriding constraints Source: https://docs.flutter.dev/ui/layout/constraints The ConstrainedBox's constraints are ignored because its parent (the screen) forces it to be screen-sized, which then passes that constraint to its child Container. ```dart ConstrainedBox( constraints: const BoxConstraints( minWidth: 70, minHeight: 70, maxWidth: 150, maxHeight: 150, ), child: Container(color: red, width: 10, height: 10), ) ``` -------------------------------- ### Import extension for authenticated HTTP client Source: https://docs.flutter.dev/data-and-backend/google-apis Import the extension_google_sign_in_as_googleapis_auth package to access the authClient extension for setting up authenticated HTTP clients. ```dart import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart'; ``` -------------------------------- ### Example 3: Centered Container with fixed size Source: https://docs.flutter.dev/ui/layout/constraints The Center widget allows its child Container to be its desired 100x100 size, as long as it's not bigger than the screen. ```dart Center(child: Container(width: 100, height: 100, color: red)) ``` -------------------------------- ### Build Scaffold with Persistent App Bar in Flutter Source: https://docs.flutter.dev/cookbook/effects/nested-nav Return a Scaffold widget with a persistent AppBar from the SetupFlow widget's build() method. This creates the basic structure for the setup flow UI. ```dart @override Widget build(BuildContext context) { return Scaffold(appBar: _buildFlowAppBar(), body: const SizedBox()); } PreferredSizeWidget _buildFlowAppBar() { return AppBar(title: const Text('Bulb Setup')); } ``` -------------------------------- ### Integrate Actions with the Actions Widget in Dart Source: https://docs.flutter.dev/ui/interactivity/actions-and-shortcuts This example demonstrates how to use the Actions widget to associate an Intent type with a specific Action within the widget tree. ```dart @override Widget build(BuildContext context) { return Actions( actions: >{SelectAllIntent: SelectAllAction(model)}, child: child, ); } ``` -------------------------------- ### Increment Counter Variable in Dart Source: https://docs.flutter.dev/testing/native-debugging Dart code line that increments the _counter variable. Used as an example breakpoint location when testing the VS Code debugger. ```dart _counter++; ``` -------------------------------- ### Widget Causing Full Page Repaint Source: https://docs.flutter.dev/tools/devtools/legacy-inspector This example demonstrates a simple `CircularProgressIndicator` widget that, without a `RepaintBoundary`, can cause the entire page to repaint on every frame. ```dart class EverythingRepaintsPage extends StatelessWidget { const EverythingRepaintsPage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Repaint Example')), body: const Center(child: CircularProgressIndicator()), ); } } ``` -------------------------------- ### Enable Firebase Web Frameworks Preview Source: https://docs.flutter.dev/deployment/web Enables the web frameworks preview in the Firebase CLI, necessary for framework-aware deployments like Flutter Web. ```bash firebase experiments:enable webframeworks ``` -------------------------------- ### Create Commands in View Model Constructor Source: https://docs.flutter.dev/app-architecture/case-study/ui-layer Initialize Command0 and Command1 objects in the view model constructor, binding them to private async methods. Commands are created as late properties and executed immediately or on demand. Required setup includes injecting repository dependencies. ```dart class HomeViewModel extends ChangeNotifier { HomeViewModel({ required BookingRepository bookingRepository, required UserRepository userRepository, }) : _bookingRepository = bookingRepository, _userRepository = userRepository { // Load required data when this screen is built. load = Command0(_load)..execute(); deleteBooking = Command1(_deleteBooking); } ​ final BookingRepository _bookingRepository; final UserRepository _userRepository; ​ late Command0 load; late Command1 deleteBooking; ​ User? _user; User? get user => _user; ​ List _bookings = []; List get bookings => _bookings; ​ Future _load() async { // ... } ​ Future> _deleteBooking(int id) async { // ... } ​ // ... } ``` -------------------------------- ### Filter Network Requests in DevTools Source: https://docs.flutter.dev/tools/devtools/network Use these examples to filter network requests in the DevTools Network view by method, type, status, or URI. ```Network Filter Query my-endpoint m:get t:json s:200 ``` ```Network Filter Query https s:404 ``` -------------------------------- ### Add certificates to the keychain Source: https://docs.flutter.dev/deployment/macos Imports the previously fetched certificates into the initialized temporary keychain. ```bash keychain add-certificates ``` -------------------------------- ### Transition Widgets API Source: https://docs.flutter.dev/release/release-notes/release-notes-1.22.0 Sample code and documentation for various animation transition widgets. ```APIDOC ## Transitions ### Description Added sample code and documentation for SizeTransition, ScaleTransition, RelativePositionedTransition, and RotationTransition. ### Endpoint /framework/widgets/transitions.dart ### Request Example ```dart RotationTransition( turns: _animation, child: const Padding( padding: EdgeInsets.all(8.0), child: FlutterLogo(size: 150.0), ), ) ``` ``` -------------------------------- ### Example Widget Tree Output from debugDumpApp Source: https://docs.flutter.dev/testing/code-debugging This output shows a 'flattened' widget tree generated by debugDumpApp(). It includes both user-defined widgets and many internal framework widgets that are part of the Flutter build process. ```log flutter: WidgetsFlutterBinding - DEBUG MODE flutter: [root](renderObject: RenderView#06beb) flutter: └View-[GlobalObjectKey FlutterView#7971c] flutter: └_ViewScope flutter: └_MediaQueryFromView(state: _MediaQueryFromViewState#d790c) flutter: └MediaQuery(MediaQueryData(size: Size(800.0, 600.0), devicePixelRatio: 1.0, textScaleFactor: 1.0, platformBrightness: Brightness.dark, padding: EdgeInsets.zero, viewPadding: EdgeInsets.zero, viewInsets: EdgeInsets.zero, systemGestureInsets: EdgeInsets.zero, alwaysUse24HourFormat: false, accessibleNavigation: false, highContrast: false, disableAnimations: false, invertColors: false, boldText: false, navigationMode: traditional, gestureSettings: DeviceGestureSettings(touchSlop: null), displayFeatures: [])) flutter: └MaterialApp(state: _MaterialAppState#27fa9) flutter: └ScrollConfiguration(behavior: MaterialScrollBehavior) flutter: └HeroControllerScope flutter: └Focus(state: _FocusState#d7f97) flutter: └_FocusInheritedScope flutter: └Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#a6464) flutter: └WidgetsApp-[GlobalObjectKey _MaterialAppState#27fa9](state: _WidgetsAppState#b5b17) flutter: └RootRestorationScope(state: _RootRestorationScopeState#6b028) flutter: └UnmanagedRestorationScope flutter: └RestorationScope(dependencies: [UnmanagedRestorationScope], state: _RestorationScopeState#d1369) flutter: └UnmanagedRestorationScope flutter: └SharedAppData(state: _SharedAppDataState#95e82) flutter: └_SharedAppModel flutter: └Shortcuts(shortcuts: , state: _ShortcutsState#272dc) flutter: └Focus(debugLabel: "Shortcuts", dependencies: [_FocusInheritedScope], state: _FocusState#a3300) flutter: └_FocusInheritedScope flutter: └Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#db110) flutter: └DefaultTextEditingShortcuts flutter: └Shortcuts(shortcuts: , state: _ShortcutsState#1d796) flutter: └Focus(debugLabel: "Shortcuts", dependencies: [_FocusInheritedScope], state: _FocusState#0081b) flutter: └_FocusInheritedScope flutter: └Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#0d70e) flutter: └Shortcuts(shortcuts: , state: _ShortcutsState#56bac) flutter: └Focus(debugLabel: "Shortcuts", dependencies: [_FocusInheritedScope], state: _FocusState#3152e) flutter: └_FocusInheritedScope flutter: └Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#b7eaf) flutter: └Actions(dispatcher: null, actions: {DoNothingIntent: DoNothingAction#0fda1, DoNothingAndStopPropagationIntent: DoNothingAction#17f30, RequestFocusIntent: RequestFocusAction#10bd0, NextFocusIntent: NextFocusAction#60317, PreviousFocusIntent: PreviousFocusAction#2a933, DirectionalFocusIntent: DirectionalFocusAction#a6922, ScrollIntent: _OverridableContextAction#964fe(defaultAction: ScrollAction#ffb50), PrioritizedIntents: PrioritizedAction#be0e2, VoidCallbackIntent: VoidCallbackAction#805fa}, state: _ActionsState#bbd25) flutter: └_ActionsScope flutter: └FocusTraversalGroup(policy: ReadingOrderTraversalPolicy#f1e76, state: _FocusTraversalGroupState#0c200) ``` -------------------------------- ### RawGestureDetector: Configuring supportedDevices in Flutter 3.3.0 Source: https://docs.flutter.dev/release/breaking-changes/trackpad-gestures For Flutter 3.3.0, this example demonstrates how to use `RawGestureDetector` with a custom `PanGestureRecognizer` to explicitly define `supportedDevices` and exclude `PointerDeviceKind.trackpad`. ```dart // Example of code after the change. void main() => runApp(Foo()); class Foo extends StatelessWidget { @override Widget build(BuildContext context) { return RawGestureDetector( gestures: { PanGestureRecognizer: GestureRecognizerFactoryWithHandlers( () => PanGestureRecognizer( supportedDevices: { PointerDeviceKind.touch, PointerDeviceKind.mouse, PointerDeviceKind.stylus, PointerDeviceKind.invertedStylus, // Do not include PointerDeviceKind.trackpad } ), (recognizer) { recognizer ..onStart = (details) { debugPrint('onStart'); } ..onUpdate = (details) { debugPrint('onUpdate'); } ..onEnd = (details) { debugPrint('onEnd'); }; }, ), }, child: Container() ); } } ``` -------------------------------- ### Define Flutter app with extensions in snapcraft.yaml Source: https://docs.flutter.dev/deployment/linux Specify the application entry point and extensions to expose required libraries. The gnome extension provides GTK 3 libraries for better system integration and smaller snap footprint. ```yaml apps: super-cool-app: command: super_cool_app extensions: [gnome] ``` -------------------------------- ### Switch statement before migration Source: https://docs.flutter.dev/release/breaking-changes/target-platform-linux-windows Example switch statement on TargetPlatform before adding linux and windows cases. This code will trigger missing_enum_constant_in_switch analyzer warnings after the enum update. ```dart void dance(TargetPlatform platform) { switch (platform) { case TargetPlatform.android: // Do Android dance. break; case TargetPlatform.fuchsia: // Do Fuchsia dance. break; case TargetPlatform.iOS: // Do iOS dance. break; case TargetPlatform.macOS: // Do macOS dance. break; } } ``` -------------------------------- ### Deprecated `androidOverscrollIndicator` usage in Flutter Source: https://docs.flutter.dev/release/breaking-changes/3-13-deprecations The `androidOverscrollIndicator` property was deprecated in v2.13. These examples show its previous usage within `MaterialApp`'s `scrollBehavior` and `theme` properties. ```dart MaterialApp( scrollBehavior: MaterialScrollBehavior( androidOverscrollIndicator: AndroidOverscrollIndicator.glow, ), //... ); ``` ```dart MaterialApp( scrollBehavior: ScrollBehavior( androidOverscrollIndicator: AndroidOverscrollIndicator.glow, ), //... ); ``` ```dart MaterialApp( theme: Theme.light().copyWith( androidOverscrollIndicator: AndroidOverscrollIndicator.glow, ), //... ); ``` -------------------------------- ### Run code generation commands Source: https://docs.flutter.dev/data-and-backend/serialization/json Use build for a one-time generation or watch to automatically regenerate files when source files change. ```bash dart run build_runner build --delete-conflicting-outputs ``` ```bash dart run build_runner watch --delete-conflicting-outputs ``` -------------------------------- ### Displaying Static Text with StatelessWidget in Flutter Source: https://docs.flutter.dev/flutter-for/xamarin-forms-devs Use StatelessWidget for UI elements that do not change during runtime. This example shows a basic Text widget with a fixed style. ```dart const Text( 'I like Flutter!', style: TextStyle(fontWeight: FontWeight.bold), ); ``` -------------------------------- ### Configure Shanghai Jiao Tong University Mirror on Windows Source: https://docs.flutter.dev/community/china Set environment variables to use the Shanghai Jiao Tong University mirror for Flutter SDK and pub packages on Windows. ```powershell $env:PUB_HOSTED_URL="https://mirror.sjtu.edu.cn/dart-pub" $env:FLUTTER_STORAGE_BASE_URL="https://mirror.sjtu.edu.cn" ``` -------------------------------- ### Publish the package to App Store Connect Source: https://docs.flutter.dev/deployment/macos Uploads the signed .pkg file to App Store Connect for distribution. ```bash app-store-connect publish \ --path "$PACKAGE_NAME" ``` -------------------------------- ### Toggle Widgets Dynamically in Flutter Source: https://docs.flutter.dev/flutter-for/uikit-devs This example demonstrates how to dynamically show or hide widgets in Flutter using a boolean flag and `setState()`, similar to `addSubview()` in UIKit. ```dart class SampleApp extends StatelessWidget { // This widget is the root of your application. const SampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(title: 'Sample App', home: SampleAppPage()); } } class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); @override State createState() => _SampleAppPageState(); } class _SampleAppPageState extends State { // Default value for toggle. bool toggle = true; void _toggle() { setState(() { toggle = !toggle; }); } Widget _getToggleChild() { if (toggle) { return const Text('Toggle One'); } return CupertinoButton(onPressed: () {}, child: const Text('Toggle Two')); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: Center(child: _getToggleChild()), floatingActionButton: FloatingActionButton( onPressed: _toggle, tooltip: 'Update Text', child: const Icon(Icons.update), ), ); } } ``` -------------------------------- ### Implementing form validation in Flutter Source: https://docs.flutter.dev/flutter-for/android-devs Manage validation state by updating the errorText property of InputDecoration. This example uses a regex to validate email input on submission. ```dart import 'package:flutter/material.dart'; void main() { runApp(const SampleApp()); } class SampleApp extends StatelessWidget { const SampleApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Sample App', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: const SampleAppPage(), ); } } class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); @override State createState() => _SampleAppPageState(); } class _SampleAppPageState extends State { String? _errorText; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: Center( child: TextField( onSubmitted: (text) { setState(() { if (!isEmail(text)) { _errorText = 'Error: This is not an email'; } else { _errorText = null; } }); }, decoration: InputDecoration( hintText: 'This is a hint', errorText: _getErrorText(), ), ), ), ); } String? _getErrorText() { return _errorText; } bool isEmail(String em) { String emailRegexp = r'^(([^<>()[\\\]\\.,;:\s@\"]+(\\.[^<>()[\\\]\\.,;:\s@\"]+)*)|' r'(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|' r'(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$'; RegExp regExp = RegExp(emailRegexp); return regExp.hasMatch(em); } } ``` -------------------------------- ### Dart VM Service URI Output from Xcode Source: https://docs.flutter.dev/add-to-app/debugging Example output displayed in Xcode's Debug area showing the Dart VM service listening URI. Copy this URI to attach debuggers in other IDEs like VS Code. ```text 2023-07-12 14:55:39.966191-0500 Runner[58361:53017145] flutter: The Dart VM service is listening on http://127.0.0.1:50642/00wEOvfyff8=/ ``` -------------------------------- ### Initialize AnimationController with SingleTickerProviderStateMixin Source: https://docs.flutter.dev/cookbook/effects/staggered-menu-animation Set up an AnimationController in the initState method and dispose of it properly. The SingleTickerProviderStateMixin provides the vsync parameter required for smooth animations. ```dart class _MenuState extends State with SingleTickerProviderStateMixin { late AnimationController _staggeredController; @override void initState() { super.initState(); _staggeredController = AnimationController(vsync: this); } @override void dispose() { _staggeredController.dispose(); super.dispose(); } } ``` -------------------------------- ### Define arguments for named routes in Flutter Source: https://docs.flutter.dev/cookbook/navigation/navigate-with-arguments Create a class to encapsulate data passed as arguments to a named route. This example defines a class with a title and a message. ```dart // You can pass any object to the arguments parameter. // In this example, create a class that contains both // a customizable title and message. class ScreenArguments { final String title; final String message; ScreenArguments(this.title, this.message); } ``` -------------------------------- ### Add includes for Flutter and UPower Source: https://docs.flutter.dev/platform-integration/platform-channels Add necessary header files to my_application.cc after the existing flutter_linux include. ```c #include #include ``` -------------------------------- ### Implementing a grid with GridView.count Source: https://docs.flutter.dev/cookbook/lists/grid-lists Use the GridView.count constructor to specify a fixed number of items in the cross axis. This example generates 100 items in a 2-column grid. ```dart GridView.count( // Create a grid with 2 columns. // If you change the scrollDirection to horizontal, // this produces 2 rows. crossAxisCount: 2, // Generate 100 widgets that display their index in the list. children: List.generate(100, (index) { return Center( child: Text( 'Item $index', style: TextTheme.of(context).headlineSmall, ), ); }), ), ``` -------------------------------- ### Add Xcode Pre-action Script for Flutter Source: https://docs.flutter.dev/platform-integration/ios/app-extensions This script prepares the Flutter environment for the iOS extension build process. ```bash /bin/sh "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" prepare ``` -------------------------------- ### Create horizontal ListView in Dart Source: https://docs.flutter.dev/cookbook/lists/horizontal-list Use ListView with scrollDirection: Axis.horizontal to create a list that scrolls horizontally. The example displays colored containers from the Colors.primaries palette. ```dart ListView( scrollDirection: Axis.horizontal, children: [ for (final color in Colors.primaries) Container(width: 160, color: color), ], ), ``` -------------------------------- ### Instantiate SubscribeButton with ViewModel and Repository in Dart Source: https://docs.flutter.dev/app-architecture/design-patterns/optimistic-state Shows how to create an instance of `SubscribeButton`, providing it with a `SubscribeButtonViewModel` that is initialized with a `SubscriptionRepository`. ```dart SubscribeButton( viewModel: SubscribeButtonViewModel( subscriptionRepository: SubscriptionRepository(), ), ) ``` -------------------------------- ### Open the iOS Xcode workspace Source: https://docs.flutter.dev/platform-integration/ios/app-extensions Navigates into the project directory and opens the Xcode workspace to perform native configuration. ```bash $ cd example_app_with_extension && open ios/Runner.xcworkspace ``` -------------------------------- ### Add IOKit.ps Import to MainFlutterWindow.swift Source: https://docs.flutter.dev/platform-integration/platform-channels This import is required to access macOS IOKit battery APIs for power source information. Add it at the top of `MainFlutterWindow.swift`. ```swift import IOKit.ps ``` -------------------------------- ### Handle taps with GestureDetector Source: https://docs.flutter.dev/cookbook/gestures/handling-taps Wrap a widget in a GestureDetector and provide an onTap callback to respond to touch events. This example displays a SnackBar when the custom button is pressed. ```dart // The GestureDetector wraps the button. GestureDetector( // When the child is tapped, show a snackbar. onTap: () { const snackBar = SnackBar(content: Text('Tap')); ​ ScaffoldMessenger.of(context).showSnackBar(snackBar); }, // The custom button child: Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( color: Colors.lightBlue, borderRadius: BorderRadius.circular(8), ), child: const Text('My Button'), ), ) ``` -------------------------------- ### Initialize GoogleSignIn instance Source: https://docs.flutter.dev/data-and-backend/google-apis Create a static GoogleSignIn instance and call initialize() in initState() before interacting with authentication methods. ```dart final GoogleSignIn _googleSignIn = GoogleSignIn.instance; @override void initState() { super.initState(); _googleSignIn.initialize(); // ··· } ``` -------------------------------- ### Use Package Font in Flutter Text Widget Source: https://docs.flutter.dev/cookbook/design/package-fonts Example of applying a font from a package to a `Text` widget using the `fontFamily` property within a `TextStyle` in Dart. ```dart child: Text( 'Using the Raleway font from the awesome_package', style: TextStyle(fontFamily: 'Raleway'), ), ``` -------------------------------- ### Implement State class with setState for dynamic updates Source: https://docs.flutter.dev/flutter-for/react-native-devs Implement the State class with build() method and use setState() to notify the framework of state changes, triggering UI rebuilds. This example demonstrates toggling text visibility and managing a periodic timer. ```dart class _MyStatefulWidgetState extends State { bool showText = true; bool toggleState = true; Timer? t2; void toggleBlinkState() { setState(() { toggleState = !toggleState; }); if (!toggleState) { t2 = Timer.periodic(const Duration(milliseconds: 1000), (t) { toggleShowText(); }); } else { t2?.cancel(); } } void toggleShowText() { setState(() { showText = !showText; }); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( children: [ if (showText) const Text('This execution will be done before you can blink.'), Padding( padding: const EdgeInsets.only(top: 70), child: ElevatedButton( onPressed: toggleBlinkState, child: toggleState ? const Text('Blink') : const Text('Stop Blinking'), ), ), ], ), ), ); } } ``` -------------------------------- ### Lock device orientation to portraitUp in Dart Source: https://docs.flutter.dev/cookbook/design/orientation Call `SystemChrome.setPreferredOrientations()` in the `main()` method to restrict the app to specific device orientations. This example locks the app to `portraitUp` only. ```dart void main() { WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); runApp(const MyApp()); } ``` -------------------------------- ### Initialize SurfaceController, TransportAdapter, and Conversation in Dart Source: https://docs.flutter.dev/ai/genui/get-started Set up the core components in initState: create a SurfaceController with widget catalogs, initialize an A2uiTransportAdapter to handle messages, build a PromptBuilder with system instructions, and instantiate a Conversation to orchestrate agent interactions. Dispose of resources in the dispose method. ```dart class _MyHomePageState extends State { late final SurfaceController _surfaceController; late final A2uiTransportAdapter _transportAdapter; late final Conversation _conversation; @override void initState() { super.initState(); // Create a SurfaceController with a widget catalog. // The CoreCatalogItems contain basic widgets for text, markdown, and images. _surfaceController = SurfaceController(catalogs: [CoreCatalogItems.asCatalog()]); _transportAdapter = A2uiTransportAdapter(); _transportAdapter.messageStream.listen(_surfaceController.handleMessage); final catalog = CoreCatalogItems.asCatalog(); final promptBuilder = PromptBuilder.chat( catalog: catalog, instructions: ''' You are an expert in creating funny riddles. Every time I give you a word, you should generate UI that displays one new riddle related to that word. Each riddle should have both a question and an answer. ''', ); // ... initialize your LLM Client of choice using promptBuilder.systemPrompt // Create the Conversation to orchestrate everything. _conversation = Conversation( surfaceController: _surfaceController, transportAdapter: _transportAdapter, onSurfaceAdded: _onSurfaceAdded, // Added in the next step. onSurfaceDeleted: _onSurfaceDeleted, // Added in the next step. ); } @override void dispose() { _textController.dispose(); _conversation.dispose(); super.dispose(); } } ``` -------------------------------- ### Bind Image widget to URL Source: https://docs.flutter.dev/ai/genui/get-started Example JSON data structure for an Image component with a URL source. Used by the AI to generate image display elements. ```json { "component": "Image", "url": "https://example.com/image.png", "variant": "mediumFeature" } ``` -------------------------------- ### Visual Studio C++ workload ID Source: https://docs.flutter.dev/platform-integration/windows/setup The specific workload ID required when installing Visual Studio via the command line for Flutter desktop development. ```text Microsoft.VisualStudio.Workload.NativeDesktop ``` -------------------------------- ### Build iOS Framework with Output Path Source: https://docs.flutter.dev/add-to-app/ios/project-setup Generate iOS frameworks from a Flutter module to a specified output directory. Run this command every time you change code in your Flutter module. ```bash $ flutter build ios-framework --output=/path/to/MyApp/Flutter/ ``` -------------------------------- ### Create desktop entry file for Flutter snap Source: https://docs.flutter.dev/deployment/linux Define application metadata for desktop menu integration following XDG Desktop Entry Specification. File name and icon must match the app name in snapcraft.yaml and be placed in snap/gui/ directory. ```yaml [Desktop Entry] Name=Super Cool App Comment=Super Cool App that does everything Exec=super-cool-app Icon=${SNAP}/meta/gui/super-cool-app.png # Replace name with your app name. Terminal=false Type=Application Categories=Education; # Adjust accordingly your snap category. ``` -------------------------------- ### Create a basic Hello World app in Flutter Source: https://docs.flutter.dev/flutter-for/react-native-devs A minimal Flutter app using the Center and Text widgets. The Text widget requires an explicit textDirection when used outside of a Material context. ```dart // Flutter import 'package:flutter/material.dart'; ​ void main() { runApp( const Center( child: Text('Hello, world!', textDirection: TextDirection.ltr), ), ); } ``` -------------------------------- ### Generate an upload keystore using keytool Source: https://docs.flutter.dev/deployment/android Use these commands to create a keystore file for signing your Android app. The -storetype JKS flag is required for Java 9 or newer. ```bash keytool -genkey -v -keystore ~/upload-keystore.jks -keyalg RSA \ -keysize 2048 -validity 10000 -alias upload ``` ```powershell keytool -genkey -v -keystore $env:USERPROFILE\upload-keystore.jks ` -storetype JKS -keyalg RSA -keysize 2048 -validity 10000 ` -alias upload ``` -------------------------------- ### Flutter SDK in protected folder error Source: https://docs.flutter.dev/install/troubleshoot This error occurs when the Flutter SDK is installed in a directory requiring elevated privileges, such as `C:\Program Files\` on Windows. ```text The Flutter SDK is installed in a protected folder and may not function correctly. Please move the SDK to a location that is user-writable without Administration permissions and restart. ``` -------------------------------- ### Defining the root application structure Source: https://docs.flutter.dev/flutter-for/xamarin-forms-devs Demonstrates setting the initial UI in Xamarin.Forms via the MainPage property versus creating a root Widget in Flutter. ```csharp public class App : Application { public App() { MainPage = new ContentPage { Content = new Label { Text = "Hello World", HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center } }; } } ``` ```dart class MyApp extends StatelessWidget { /// This widget is the root of your application. const MyApp({super.key}); @override Widget build(BuildContext context) { return const Center( child: Text('Hello World!', textDirection: TextDirection.ltr), ); } } ``` -------------------------------- ### Update framework paths in project.pbxproj Source: https://docs.flutter.dev/add-to-app/ios/project-setup Modify hardcoded 'Release' paths to use the $(CONFIGURATION) variable and wrap them in quotes to support multiple build modes. ```text 312885572C1A441C009F74FF /* Flutter.xcframework */ = { isa = PBXFileReference; expectedSignature = "AppleDeveloperProgram:S8QB4VV633:FLUTTER.IO LLC"; lastKnownFileType = wrapper.xcframework; name = Flutter.xcframework; path = Flutter/Release/Flutter.xcframework; sourceTree = ""; }; 312885582C1A441C009F74FF /* App.xcframework */ = { isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = App.xcframework; path = Flutter/Release/App.xcframework; sourceTree = ""; }; ``` ```text 312885572C1A441C009F74FF /* Flutter.xcframework */ = { isa = PBXFileReference; expectedSignature = "AppleDeveloperProgram:S8QB4VV633:FLUTTER.IO LLC"; lastKnownFileType = wrapper.xcframework; name = Flutter.xcframework; path = "Flutter/$(CONFIGURATION)/Flutter.xcframework"; sourceTree = ""; }; 312885582C1A441C009F74FF /* App.xcframework */ = { isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = App.xcframework; path = "Flutter/$(CONFIGURATION)/App.xcframework"; sourceTree = ""; }; ``` -------------------------------- ### Add Flutter SDK PATH to tcsh Source: https://docs.flutter.dev/install/add-to-path Add the Flutter bin directory to PATH in tcsh by appending to ~/.tcshrc. Replace with your Flutter installation path. ```bash $ echo 'setenv PATH "/bin:$PATH"' >> ~/.tcshrc ``` ```bash $ echo 'setenv PATH "$HOME/develop/flutter/bin:$PATH"' >> ~/.tcshrc ``` -------------------------------- ### Update main.dart with global state and CupertinoApp Source: https://docs.flutter.dev/learn/pathway/tutorial/advanced-ui Initialize the global ContactGroupsModel and configure the root CupertinoApp with a dynamic theme. ```dart import 'package:flutter/cupertino.dart'; import 'package:rolodex/data/contact_group.dart'; final contactGroupsModel = ContactGroupsModel(); void main() { runApp(const RolodexApp()); } class RolodexApp extends StatelessWidget { const RolodexApp({super.key}); @override Widget build(BuildContext context) { return CupertinoApp( title: 'Rolodex', theme: const CupertinoThemeData( barBackgroundColor: CupertinoDynamicColor.withBrightness( color: Color(0xFFF9F9F9), darkColor: Color(0xFF1D1D1D), ), ), home: CupertinoPageScaffold(child: Center(child: Text('Hello Rolodex!'))), ); } } ``` -------------------------------- ### Add Flutter SDK PATH to csh Source: https://docs.flutter.dev/install/add-to-path Add the Flutter bin directory to PATH in csh by appending to ~/.cshrc. Replace with your Flutter installation path. ```bash $ echo 'setenv PATH "/bin:$PATH"' >> ~/.cshrc ``` ```bash $ echo 'setenv PATH "$HOME/develop/flutter/bin:$PATH"' >> ~/.cshrc ``` -------------------------------- ### Check PUB_HOSTED_URL on macOS/Linux Source: https://docs.flutter.dev/community/china Verify that the PUB_HOSTED_URL environment variable is unset or empty before publishing packages to pub.dev on macOS or Linux. ```bash $ echo $PUB_HOSTED_URL ``` -------------------------------- ### Configure localization delegates in MaterialApp Source: https://docs.flutter.dev/flutter-for/xamarin-forms-devs Define delegates and supported locales within the MaterialApp widget. This setup is required for the app to recognize and load localized resources. ```dart import 'package:flutter_localizations/flutter_localizations.dart'; class MyWidget extends StatelessWidget { const MyWidget({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( localizationsDelegates: >[ // Add app-specific localization delegate[s] here GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, ], supportedLocales: [ Locale('en', 'US'), // English Locale('he', 'IL'), // Hebrew // ... other locales the app supports ], ); } } ``` -------------------------------- ### Check Outdated Package Dependencies Source: https://docs.flutter.dev/install/upgrade Identify out-of-date package dependencies and get advice on how to update them. Provides information about available updates for packages listed in pubspec.yaml. ```bash $ flutter pub outdated ``` -------------------------------- ### Create a new Flutter app for deep linking Source: https://docs.flutter.dev/cookbook/navigation/set-up-universal-links Use the `flutter create` command to initialize a new Flutter project, specifying an app name like `deeplink_cookbook`. ```bash $ flutter create deeplink_cookbook ``` -------------------------------- ### Create the dogs table Source: https://docs.flutter.dev/cookbook/persistence/sqlite Use the onCreate callback within openDatabase to execute the SQL command that defines your table schema. ```dart final database = openDatabase( // Set the path to the database. Note: Using the `join` function from the // `path` package is best practice to ensure the path is correctly // constructed for each platform. join(await getDatabasesPath(), 'doggie_database.db'), // When the database is first created, create a table to store dogs. onCreate: (db, version) { // Run the CREATE TABLE statement on the database. return db.execute( 'CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)', ); }, // Set the version. This executes the onCreate function and provides a // path to perform database upgrades and downgrades. version: 1, ); ``` -------------------------------- ### Register Plugins with Flutter Engine in Objective-C Source: https://docs.flutter.dev/platform-integration/ios/app-extensions Call the plugin registration method after the Flutter engine has been started with [flutterEngine run]. This ensures all plugins are properly initialized. ```objc // Add this after [flutterEngine run] [GeneratedPluginRegistrant registerWithRegistry:flutterEngine]; ``` -------------------------------- ### Apply a vertical linear gradient Source: https://docs.flutter.dev/flutter-for/web-devs Create a vertical gradient by setting the start and end points to the same x-axis value. In Flutter, use LinearGradient within a BoxDecoration. ```css
Lorem ipsum
.grey-box { background-color: #e0e0e0; /* grey 300 */ width: 320px; height: 240px; font: 900 24px Roboto; display: flex; align-items: center; justify-content: center; } .red-box { padding: 16px; color: #ffffff; background: linear-gradient(180deg, #ef5350, rgba(0, 0, 0, 0) 80%); } ``` ```dart final container = Container( // grey box width: 320, height: 240, color: Colors.grey[300], child: Center( child: Container( // red box decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment(0.0, 0.6), colors: [ Color(0xffef5350), Color(0x00ef5350), ], ), ), padding: const EdgeInsets.all(16), child: Text( 'Lorem ipsum', style: bold24Roboto, ), ), ), ); ``` -------------------------------- ### Windows Build Linker Error for RunLoop Source: https://docs.flutter.dev/release/breaking-changes/windows-version-information This error indicates a problem with the `RunLoop` migration. If encountered, refer to the run loop migration guide for resolution. ```Linker Error flutter_window.obj : error LNK2019: unresolved external symbol "public: void __cdecl RunLoop::RegisterFlutterInstance(class flutter::FlutterEngine *)" (?RegisterFlutterInstance@RunLoop@@QEAAXPEAVFlutterEngine@flutter@@@Z) referenced in function "protected: virtual bool __cdecl FlutterWindow::OnCreate(void)" (?OnCreate@FlutterWindow@@MEAA_NXZ) ``` -------------------------------- ### Define Launch Theme in Android styles.xml Source: https://docs.flutter.dev/platform-integration/android/splash-screen This theme is applied during app initialization to display a splash screen. It sets the `windowBackground` to a `Drawable`. ```xml ``` -------------------------------- ### Add camera dependencies using Flutter CLI Source: https://docs.flutter.dev/cookbook/plugins/picture-using-camera Run this command to add the camera, path_provider, and path packages to your project's pubspec.yaml. ```shell $ flutter pub add camera path_provider path ``` -------------------------------- ### Implement Custom Locale Resolution in MaterialApp Source: https://docs.flutter.dev/ui/internationalization Provide a localeResolutionCallback to override the default matching logic. This example shows how to unconditionally accept the user's selected locale. ```dart MaterialApp( localeResolutionCallback: (locale, supportedLocales) { return locale; }, ); ``` -------------------------------- ### Row with overflowing Text child Source: https://docs.flutter.dev/ui/layout/constraints This example shows a Row where one of its Text children is too wide to fit. Since Row does not constrain its children, it results in an overflow warning. ```dart Row( children: [ Container( color: red, child: const Text( 'This is a very long text that ' 'won\'t fit the line.', style: big, ), ), Container( color: green, child: const Text('Goodbye!', style: big), ), ], ) ``` -------------------------------- ### Navigate using go_router package Source: https://docs.flutter.dev/ui/navigation When using a routing package like `go_router`, use its provided methods, such as `context.go()`, for declarative navigation and deep link handling. ```dart child: const Text('Open second screen'), onPressed: () => context.go('/second'), ``` -------------------------------- ### FittedBox with unbounded child Source: https://docs.flutter.dev/ui/layout/constraints This example illustrates FittedBox attempting to scale a child with infinite width. FittedBox requires bounded children; otherwise, it will not render and produce an error. ```dart FittedBox( child: Container(height: 20, width: double.infinity, color: Colors.red), ) ``` -------------------------------- ### Example 4: Aligned Container with fixed size Source: https://docs.flutter.dev/ui/layout/constraints Similar to Center, Align allows the Container to be its desired size, but positions it to the bottom-right of the available space instead of centering it. ```dart Align( alignment: Alignment.bottomRight, child: Container(width: 100, height: 100, color: red), ) ``` -------------------------------- ### flutter create Source: https://docs.flutter.dev/reference/flutter-cli Creates a new project. ```APIDOC ## COMMAND flutter create ### Description Creates a new project. ### Usage `flutter create ` ### Arguments - **** (string) - Required - The directory where the new project will be created. ### Request Example N/A ### Response #### Success Response (0) - **Output** (string) - Project creation status and instructions. #### Response Example N/A ``` -------------------------------- ### Async function in onPressed callback Source: https://docs.flutter.dev/testing/errors Example of an onPressed callback that invokes an asynchronous MethodChannel operation. Errors from such operations are not caught by FlutterError.onError and must be handled via PlatformDispatcher. ```dart OutlinedButton( child: const Text('Click me!'), onPressed: () async { const channel = MethodChannel('crashy-custom-channel'); await channel.invokeMethod('blah'); }, ) ``` -------------------------------- ### Build a release version of a Flutter desktop app Source: https://docs.flutter.dev/desktop Generates a production-ready release build for the specified desktop operating system. ```bash PS C:\> flutter build windows $ flutter build macos $ flutter build linux ``` -------------------------------- ### Update MainActivity to v2 Embedding Source: https://docs.flutter.dev/release/breaking-changes/plugin-api-migration Update the example app's MainActivity to extend FlutterActivity for v2 embedding support. The class can remain empty as plugins now auto-register. ```java package io.flutter.plugins.firebasecoreexample; import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.plugins.firebase.core.FirebaseCorePlugin; public class MainActivity extends FlutterActivity { // You can keep this empty class or remove it. Plugins on the new embedding // now automatically registers plugins. } ``` -------------------------------- ### Flutter test StateError for page transitions Source: https://docs.flutter.dev/release/breaking-changes/page-transition-replaced-by-ZoomPageTransitionBuilder Example of the 'Too many elements' error that may occur in tests due to multiple widgets being present during the new transition. ```text ══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════ The following StateError was thrown running a test: Bad state: Too many elements When the exception was thrown, this was the stack: #0 Iterable.single (dart:core/iterable.dart:656:24) #1 WidgetController.widget (package:flutter_test/src/controller.dart:69:30) #2 main. (file:///path/to/your/test.dart:1:2) ``` -------------------------------- ### Run and build Flutter flavors via CLI Source: https://docs.flutter.dev/deployment/flavors Commands to execute or compile specific build flavors using the --flavor flag for different environments. ```console $ flutter run --flavor staging ``` ```console $ flutter (run | build ) --flavor ``` ```console $ flutter build apk --flavor staging ``` -------------------------------- ### Run Flutter Unit Tests from Command Line Source: https://docs.flutter.dev/cookbook/testing/unit/mocking Execute a specific unit test file in a Flutter project using the `flutter test` command. ```bash $ flutter test test/fetch_album_test.dart ``` -------------------------------- ### Define a Flutter Root Widget with CupertinoApp Source: https://docs.flutter.dev/flutter-for/swiftui-devs Extend `StatelessWidget` to create the root widget for a Flutter app. This example uses `CupertinoApp` to provide an iOS-style design system. ```dart class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { // Returns a CupertinoApp that, by default, // has the look and feel of an iOS app. return const CupertinoApp(home: HomePage()); } } ``` -------------------------------- ### Apply Dark Mode Theme in Flutter Source: https://docs.flutter.dev/flutter-for/compose-devs This example demonstrates how to set the application-level theme to dark mode in Flutter by configuring the brightness property within ThemeData for a MaterialApp. ```dart const MaterialApp( theme: ThemeData( brightness: Brightness.dark, ), home: HomePage(), ); ``` -------------------------------- ### Flutter TodoList Widget for Interaction Testing Source: https://docs.flutter.dev/cookbook/testing/widget/tap-drag This `StatefulWidget` defines a basic todo application used as an example for testing user interactions. It includes a `TextField`, a `ListView`, and a `FloatingActionButton`. ```dart class TodoList extends StatefulWidget { const TodoList({super.key}); @override State createState() => _TodoListState(); } class _TodoListState extends State { static const _appTitle = 'Todo List'; final todos = []; final controller = TextEditingController(); @override Widget build(BuildContext context) { return MaterialApp( title: _appTitle, home: Scaffold( appBar: AppBar(title: const Text(_appTitle)), body: Column( children: [ TextField(controller: controller), Expanded( child: ListView.builder( itemCount: todos.length, itemBuilder: (context, index) { final todo = todos[index]; return Dismissible( key: Key('$todo$index'), onDismissed: (direction) => todos.removeAt(index), background: Container(color: Colors.red), child: ListTile(title: Text(todo)), ); }, ), ), ], ), floatingActionButton: FloatingActionButton( onPressed: () { setState(() { todos.add(controller.text); controller.clear(); }); }, child: const Icon(Icons.add), ), ), ); } } ``` -------------------------------- ### Check PUB_HOSTED_URL on Windows Source: https://docs.flutter.dev/community/china Verify that the PUB_HOSTED_URL environment variable is unset or empty before publishing packages to pub.dev on Windows. ```powershell $ echo $env:PUB_HOSTED_URL ``` -------------------------------- ### Run iOS and macOS unit tests via xcodebuild Source: https://docs.flutter.dev/testing/testing-plugins Run in the example/ios or example/macos directory. You may need to open Runner.xcworkspace in Xcode first to configure code signing. ```sh xcodebuild test -workspace Runner.xcworkspace -scheme Runner -configuration Debug ``` -------------------------------- ### Bind Text widget to static value Source: https://docs.flutter.dev/ai/genui/get-started Example JSON data structure for a Text component with static content. The AI generates this JSON to create UI elements. ```json { "component": "Text", "text": "Welcome to GenUI", "variant": "h1" } ``` -------------------------------- ### Add Flutter SDK PATH to fish Source: https://docs.flutter.dev/install/add-to-path Add the Flutter bin directory to PATH in fish using the fish_add_path command. Replace with your Flutter installation path. ```bash $ fish_add_path -g -p /bin ``` ```bash $ fish_add_path -g -p ~/develop/flutter/bin ``` -------------------------------- ### Configure Tsinghua University Mirror on macOS/Linux/ChromeOS Source: https://docs.flutter.dev/community/china Set environment variables to use the Tsinghua University TUNA Association mirror for Flutter SDK and pub packages on Unix-like systems. ```bash export PUB_HOSTED_URL=https://mirrors.tuna.tsinghua.edu.cn/dart-pub export FLUTTER_STORAGE_BASE_URL=https://mirrors.tuna.tsinghua.edu.cn ``` -------------------------------- ### TextField with custom Localizations widget (after migration) Source: https://docs.flutter.dev/release/breaking-changes/text-field-material-localizations Provides MaterialLocalizations via explicit Localizations widget with delegates. Use this when MaterialApp is not available or when you need custom localization setup. ```dart import 'package:flutter/material.dart'; void main() => runApp(Foo()); class Foo extends StatelessWidget { @override Widget build(BuildContext context) { return Localizations( locale: const Locale('en', 'US'), delegates: const >[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Material( child: TextField(), ), ), ), ); } } ``` -------------------------------- ### Create a CupertinoApp for iOS-style UI Source: https://docs.flutter.dev/cookbook/design/cupertino-sheets This snippet demonstrates how to set up a basic Flutter application using `CupertinoApp` as the root widget, which is suitable for apps following iOS design guidelines. ```dart class CupertinoSheetDemo extends StatelessWidget { const CupertinoSheetDemo({super.key}); @override Widget build(BuildContext context) { return const CupertinoApp( title: 'CupertinoSheet Demo', home: CupertinoSheetPage(), ); } } ``` -------------------------------- ### Flutter Doctor: cmdline-tools component is missing Source: https://docs.flutter.dev/install/troubleshoot This output from `flutter doctor` indicates that the Android command-line tools are not found. This issue prevents proper Android development setup. ```plaintext [!] Android toolchain - develop for Android devices (Android SDK version 33.0.2) • Android SDK at C:\Users\My PC\AppData\Local\Android\sdk X cmdline-tools component is missing ``` -------------------------------- ### Initialize AnimationController for Expandable FAB in Flutter Source: https://docs.flutter.dev/cookbook/effects/expandable-fab Initializes the `AnimationController` and `Animation` to control the expansion and collapse of child `ActionButton`s. This setup manages the animation's duration and curve. ```dart class _ExpandableFabState extends State with SingleTickerProviderStateMixin { late final AnimationController _controller; late final Animation _expandAnimation; bool _open = false; @override void initState() { super.initState(); _open = widget.initialOpen ?? false; _controller = AnimationController( value: _open ? 1.0 : 0.0, duration: const Duration(milliseconds: 250), vsync: this, ); _expandAnimation = CurvedAnimation( curve: Curves.fastOutSlowIn, reverseCurve: Curves.easeOutQuad, parent: _controller, ); } @override void dispose() { _controller.dispose(); super.dispose(); } void _toggle() { setState(() { _open = !_open; if (_open) { _controller.forward(); } else { _controller.reverse(); } }); } } ``` -------------------------------- ### Successful Android licenses acceptance output Source: https://docs.flutter.dev/platform-integration/android/setup Expected terminal output after successfully accepting all required Android SDK licenses. ```bash All SDK package licenses accepted. ``` -------------------------------- ### Upload iOS App Bundle to App Store Connect using altool Source: https://docs.flutter.dev/deployment/ios Use this command to upload a generated `.ipa` file to App Store Connect from the command line, requiring an API key and issuer ID for authentication. ```bash xcrun altool --upload-app --type ios -f build/ios/ipa/*.ipa --apiKey your_api_key --apiIssuer your_issuer_id ``` -------------------------------- ### Fetch API for Networking in React Native Source: https://docs.flutter.dev/flutter-for/react-native-devs Demonstrates how to use the Fetch API in React Native to make an HTTP GET request and update component state with the response. ```javascript // React Native const [ipAddress, setIpAddress] = useState('') const _getIPAddress = () => { fetch('https://httpbin.org/ip') .then(response => response.json()) .then(responseJson => { setIpAddress(responseJson.origin); }) .catch(error => { console.error(error); }); }; ``` -------------------------------- ### Retrieve Text Input from TextField in Flutter Source: https://docs.flutter.dev/flutter-for/uikit-devs Use a TextEditingController to get the current value of a TextField. Ensure the controller is disposed of when the widget is removed to prevent memory leaks. ```dart class _MyFormState extends State { // Create a text controller and use it to retrieve the current value. // of the TextField! final myController = TextEditingController(); @override void dispose() { // Clean up the controller when disposing of the Widget. myController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Retrieve Text Input')), body: Padding( padding: const EdgeInsets.all(16), child: TextField(controller: myController), ), floatingActionButton: FloatingActionButton( // When the user presses the button, show an alert dialog with the // text the user has typed into our text field. onPressed: () { showDialog( context: context, builder: (context) { return AlertDialog( // Retrieve the text the user has typed in using our // TextEditingController. content: Text(myController.text), ); }, ); }, tooltip: 'Show me the value!', child: const Icon(Icons.text_fields), ), ); } } ``` -------------------------------- ### Add Authorization Header to HTTP Request Source: https://docs.flutter.dev/cookbook/networking/authenticated-requests Use the http package to add an Authorization header to a GET request. The HttpHeaders.authorizationHeader constant provides the standard header name. ```dart final response = await http.get( Uri.parse('https://jsonplaceholder.typicode.com/albums/1'), // Send authorization headers to the backend. headers: {HttpHeaders.authorizationHeader: 'Basic your_api_token_here'}, ); ``` -------------------------------- ### Configure Flutter Mirror on macOS, Linux, or ChromeOS Source: https://docs.flutter.dev/community/china Use these commands to set the `PUB_HOSTED_URL` and `FLUTTER_STORAGE_BASE_URL` environment variables for Flutter on Unix-like systems. ```bash export PUB_HOSTED_URL=https://mirrors.tuna.tsinghua.edu.cn/dart-pub export FLUTTER_STORAGE_BASE_URL=https://mirrors.tuna.tsinghua.edu.cn/flutter ``` -------------------------------- ### Refresh Flutter Plugins in Module Source: https://docs.flutter.dev/add-to-app/ios/project-setup Run `flutter pub get` in your Flutter module directory after changing `pubspec.yaml` dependencies. This updates the list of plugins for the `podhelper.rb` script. ```bash flutter pub get ``` -------------------------------- ### Publish a Flutter Package to pub.dev Source: https://docs.flutter.dev/packages-and-plugins/developing-packages Execute this command to publish your package to pub.dev. Be aware that publishing is a permanent action. ```bash $ flutter pub publish ``` -------------------------------- ### Configure Drag Start Behavior for GestureDetector in Flutter Source: https://docs.flutter.dev/release/release-notes/release-notes-1.2.1 Set `dragStartBehavior` to `DragStartBehavior.down` on a `GestureDetector` to make `onStart` callbacks trigger at the touch down location, restoring previous behavior. ```dart GestureDectector( dragStartBehavior: DragStartBehavior.down, onVerticalDragDown: myDragDown onVerticalDragEnd: myDragEnd, onVerticalDragStart: myDragStart, onVerticalDragUpdate: myDragUpdate, onVerticalDragCancel: myDragCancel, onHorizontalDragDown: myDragDown onHorizontalDragEnd: myDragEnd, onHorizontalDragStart: myDragStart, onHorizontalDragUpdate: myDragUpdate, onHorizontalDragCancel: myDragCancel, // Other fields… ) ``` -------------------------------- ### Upload snap to Snap Store with release channel Source: https://docs.flutter.dev/deployment/linux Push the built snap file to the Snap Store, specifying the target release channel (stable, candidate, beta, or edge). ```bash $ snapcraft upload --release= .snap ``` -------------------------------- ### Apply a horizontal linear gradient Source: https://docs.flutter.dev/flutter-for/web-devs Create a horizontal gradient by setting the start and end points to the same y-axis value. Use Alignment values to control the direction and spread. ```css
Lorem ipsum
.grey-box { background-color: #e0e0e0; /* grey 300 */ width: 320px; height: 240px; font: 900 24px Roboto; display: flex; align-items: center; justify-content: center; } .red-box { padding: 16px; color: #ffffff; background: linear-gradient(90deg, #ef5350, rgba(0, 0, 0, 0) 80%); } ``` ```dart final container = Container( // grey box width: 320, height: 240, color: Colors.grey[300], child: Center( child: Container( // red box padding: const EdgeInsets.all(16), decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment(-1.0, 0.0), end: Alignment(0.6, 0.0), colors: [ Color(0xffef5350), Color(0x00ef5350), ], ), ), child: Text( 'Lorem ipsum', style: bold24Roboto, ), ), ), ); ``` -------------------------------- ### FittedBox in Center with overflowing Text Source: https://docs.flutter.dev/ui/layout/constraints This example demonstrates a FittedBox inside a Center with text too large for the screen. FittedBox scales the text to fit the screen's available size. ```dart const Center( child: FittedBox( child: Text( 'This is some very very very large text that is too big to fit a regular screen in a single line.', ), ), ) ``` -------------------------------- ### Example 8: Nested Containers with padding Source: https://docs.flutter.dev/ui/layout/constraints The red Container sizes itself to its child's size plus its own padding, making the red color visible around the green child. ```dart Center( child: Container( padding: const EdgeInsets.all(20), color: red, child: Container(color: green, width: 30, height: 30), ), ) ``` -------------------------------- ### Initial Tile Widget with Container Source: https://docs.flutter.dev/learn/pathway/tutorial/implicit-animations This snippet shows the initial implementation of the `Tile` widget using a `Container`, where property changes like background color update instantly without animation. ```dart class Tile extends StatelessWidget { const Tile(this.letter, this.hitType, {super.key}); final String letter; final HitType hitType; @override Widget build(BuildContext context) { return Container( height: 60, width: 60, decoration: BoxDecoration( border: Border.all(color: Colors.grey.shade300), color: switch (type) { HitType.hit => Colors.green, HitType.partial => Colors.yellow, HitType.miss => Colors.grey, _ => Colors.white, }, ), child: Center( child: Text( letter.toUpperCase(), style: Theme.of(context).textTheme.titleLarge, ), ), ); } } ``` -------------------------------- ### Use Actions.handler for Button Callbacks in Dart Source: https://docs.flutter.dev/ui/interactivity/actions-and-shortcuts This example demonstrates how to use Actions.handler to create an onPressed callback for a button, which automatically disables the button if no enabled action matches the intent. ```dart @override Widget build(BuildContext context) { return Actions( actions: >{SelectAllIntent: SelectAllAction(model)}, child: Builder( builder: (context) => TextButton( onPressed: Actions.handler( context, SelectAllIntent(controller: controller), ), child: const Text('SELECT ALL'), ), ), ); } ``` -------------------------------- ### Handle Surface lifecycle with SurfaceProducer callbacks Source: https://docs.flutter.dev/release/breaking-changes/android-surface-plugins Implement the SurfaceProducer.Callback to manage surface initialization and cleanup when the application is suspended or resumed. ```java surfaceProducer.setCallback( new TextureRegistry.SurfaceProducer.Callback() { @Override public void onSurfaceAvailable() { // Do surface initialization here, and draw the current frame. } ​ @Override public void onSurfaceDestroyed() { // Do surface cleanup here, and stop drawing frames. } } ); ``` -------------------------------- ### Create a custom Curve in Flutter Source: https://docs.flutter.dev/ui/animations/index Subclass the Curve class and override the transform method to define custom animation progress. This example uses a sine wave for a shaking effect. ```dart import 'dart:math'; ​ class ShakeCurve extends Curve { @override double transform(double t) => sin(t * pi * 2); } ``` -------------------------------- ### Configure iOS camera and microphone permissions Source: https://docs.flutter.dev/cookbook/plugins/picture-using-camera Add these keys to your ios/Runner/Info.plist file to request necessary hardware permissions from the user. ```xml NSCameraUsageDescription Explanation on why the camera access is needed. NSMicrophoneUsageDescription Explanation on why the microphone access is needed. ``` -------------------------------- ### Example Semantics Tree Output Source: https://docs.flutter.dev/testing/code-debugging This console output shows the structure of the semantics tree, including element properties like Rect, actions, flags, and label, after calling debugDumpSemanticsTree(). ```flutter flutter: SemanticsNode#0 flutter: │ Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) flutter: │ flutter: └─SemanticsNode#1 flutter: │ Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) flutter: │ textDirection: ltr flutter: │ flutter: └─SemanticsNode#2 flutter: │ Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) flutter: │ sortKey: OrdinalSortKey#824a2(order: 0.0) flutter: │ flutter: └─SemanticsNode#3 flutter: │ Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) flutter: │ flags: scopesRoute flutter: │ flutter: └─SemanticsNode#4 flutter: Rect.fromLTRB(278.0, 267.0, 522.0, 333.0) flutter: actions: tap flutter: flags: isButton, hasEnabledState, isEnabled flutter: label: flutter: "Clickable text here! flutter: Click Me!" flutter: textDirection: ltr flutter: flutter: Clicked! ``` -------------------------------- ### Configure Flutter plugin in snapcraft.yaml parts Source: https://docs.flutter.dev/deployment/linux Use the Flutter plugin to automatically download and configure the Flutter SDK. Specify the main entry point file for the application. ```yaml parts: super-cool-app: source: . plugin: flutter flutter-target: lib/main.dart # The main entry-point file of the application ``` -------------------------------- ### Deprecated `TestWindow` property access in Flutter tests Source: https://docs.flutter.dev/release/breaking-changes/3-13-deprecations Many properties of `TestWindow` were removed to prepare for multi-window support. This example shows how `textScaleFactorTestValue` was accessed via `tester.binding.window` before migration. ```dart testWidgets('My test', (WidgetTester tester) aysnc { // For all instances, replace window with platformDispatcher tester.binding.window.textScaleFactorTestValue = 42; addTearDown(tester.binding.window.clearTextScaleFactorTestValue); // ... }); ``` -------------------------------- ### Create and configure FragmentShader with uniforms Source: https://docs.flutter.dev/ui/design/graphics/fragment-shaders Create a FragmentShader instance from a FragmentProgram and set uniform values (configuration parameters) before use. Available uniforms depend on the shader definition. ```dart void updateShader(Canvas canvas, Rect rect, FragmentProgram program) { var shader = program.fragmentShader(); shader.setFloat(0, 42.0); canvas.drawRect(rect, Paint()..shader = shader); } ``` -------------------------------- ### Connect Adapter and Initialize Agent in initState Source: https://docs.flutter.dev/ai/genui/get-started Wire the transport adapter to the surface controller, create an A2uiAgentConnector pointing to the A2A server, initialize a Conversation with both controllers, and listen for remote agent messages. Replace the localhost URL with your actual A2A server endpoint. ```dart @override void initState() { super.initState(); // Connect Adapter -> Controller _transportAdapter.messageStream.listen(_surfaceController.handleMessage); _connector = A2uiAgentConnector( // TODO: Replace with your A2A server URL. url: Uri.parse('http://localhost:8080'), ); _uiAgent = Conversation( surfaceController: _surfaceController, transportAdapter: _transportAdapter, ); // Listen for messages from the remote agent. _connector.stream.listen(_surfaceController.handleMessage); } ``` -------------------------------- ### Customize AnimatedContainer curve in Dart Source: https://docs.flutter.dev/learn/pathway/tutorial/implicit-animations Apply the curve parameter to an AnimatedContainer to customize the speed profile of the transition. This example uses Curves.bounceIn to create a bouncing effect when properties change. ```dart class Tile extends StatelessWidget { const Tile(this.letter, this.hitType, {super.key}); ​ final String letter; final HitType hitType; @override Widget build(BuildContext context) { return AnimatedContainer( duration: Duration(milliseconds: 500), curve: Curves.bounceIn, // NEW height: 60, width: 60, decoration: BoxDecoration( border: Border.all(color: Colors.grey.shade300), color: switch (hitType) { HitType.hit => Colors.green, HitType.partial => Colors.yellow, HitType.miss => Colors.grey, _ => Colors.white, }, ), child: Center( child: Text( letter.toUpperCase(), style: Theme.of(context).textTheme.titleLarge, ), ), ); } } ``` -------------------------------- ### Serialize nested User and Address objects Source: https://docs.flutter.dev/data-and-backend/serialization/json Example demonstrating the problem: calling toJson() on a User with nested Address produces incorrect output with "Instance of 'address'". ```dart Address address = Address('My st.', 'New York'); User user = User('John', address); print(user.toJson()); ``` -------------------------------- ### HomeViewModel with a load action Source: https://docs.flutter.dev/app-architecture/design-patterns/command Demonstrates adding a 'load' action to the HomeViewModel, typically triggered by the view to fetch data. ```dart class HomeViewModel extends ChangeNotifier { User? get user => // ... // ··· void load() { // load user } // ··· } ``` -------------------------------- ### Dependency resolution output for url_launcher Source: https://docs.flutter.dev/testing/native-debugging?tab=from-vscode-to-xcode-ios Displays the list of platform-specific implementation packages and interface plugins added during the resolution process. Note the addition of platform-specific packages for Android, iOS, Linux, macOS, Web, and Windows. ```text Resolving dependencies... collection 1.17.1 (1.17.2 available) + flutter_web_plugins 0.0.0 from sdk flutter matcher 0.12.15 (0.12.16 available) material_color_utilities 0.2.0 (0.8.0 available) + plugin_platform_interface 2.1.4 source_span 1.9.1 (1.10.0 available) stream_channel 2.1.1 (2.1.2 available) test_api 0.5.1 (0.6.1 available) + url_launcher 6.1.11 + url_launcher_android 6.0.36 + url_launcher_ios 6.1.4 + url_launcher_linux 3.0.5 + url_launcher_macos 3.0.5 + url_launcher_platform_interface 2.1.3 + url_launcher_web 2.0.17 + url_launcher_windows 3.0.6 Changed 10 dependencies! ``` -------------------------------- ### Define widget schema with json_schema_builder Source: https://docs.flutter.dev/ai/genui/get-started Create a schema object that defines the data structure required for a custom widget. This example defines a RiddleCard schema with question and answer fields. ```dart import 'package:json_schema_builder/json_schema_builder.dart'; import 'package:flutter/material.dart'; import 'package:genui/genui.dart'; ​ final _schema = S.object( properties: { 'question': S.string(description: 'The question part of a riddle.'), 'answer': S.string(description: 'The answer part of a riddle.'), }, required: ['question', 'answer'], ); ``` -------------------------------- ### Define and Load Keystore Properties in Gradle Source: https://docs.flutter.dev/deployment/android This snippet shows how to load keystore properties from a `key.properties` file into a `keystoreProperties` object. Place this code before the `android` block in your Gradle build file. ```kotlin import java.util.Properties import java.io.FileInputStream plugins { ... } val keystoreProperties = Properties() val keystorePropertiesFile = rootProject.file("key.properties") if (keystorePropertiesFile.exists()) { keystoreProperties.load(FileInputStream(keystorePropertiesFile)) } android { ... } ``` ```groovy import java.util.Properties import java.io.FileInputStream plugins { ... } def keystoreProperties = new Properties() def keystorePropertiesFile = rootProject.file('key.properties') if (keystorePropertiesFile.exists()) { keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) } android { ... } ``` -------------------------------- ### Build iOS Frameworks for Flutter Module Source: https://docs.flutter.dev/add-to-app/ios/project-setup Run this command every time you change code in your Flutter module to generate the necessary iOS frameworks, including the Flutter engine and plugin frameworks, at the specified output path. ```bash flutter build ios-framework --output=/path/to/MyApp/Flutter/ ``` -------------------------------- ### Add test package as dev dependency Source: https://docs.flutter.dev/cookbook/testing/unit/introduction Install the test package as a dev dependency using flutter pub add. This provides core testing functionality for Dart packages. ```bash $ flutter pub add dev:test ``` -------------------------------- ### Initialize Flutter app with CupertinoApp Source: https://docs.flutter.dev/learn/pathway/tutorial/advanced-ui Replace the default `main.dart` content to use `CupertinoApp` for iOS-style UI, setting up a basic theme and scaffold. ```dart import 'package:flutter/cupertino.dart'; void main() { runApp(const RolodexApp()); } class RolodexApp extends StatelessWidget { const RolodexApp({super.key}); @override Widget build(BuildContext context) { return const CupertinoApp( title: 'Rolodex', theme: CupertinoThemeData( barBackgroundColor: CupertinoDynamicColor.withBrightness( color: Color(0xFFF9F9F9), darkColor: Color(0xFF1D1D1D), ), ), home: CupertinoPageScaffold( child: Center( child: Text('Hello Rolodex!'), ), ), ); } } ``` -------------------------------- ### Add desktop support to an existing Flutter project Source: https://docs.flutter.dev/desktop Injects the necessary native files and directories for desktop platforms into an existing Flutter project root. ```bash $ flutter create --platforms=windows,macos,linux . ``` -------------------------------- ### Configure Flutter Mirror on Windows Source: https://docs.flutter.dev/community/china Use these commands to set the `PUB_HOSTED_URL` and `FLUTTER_STORAGE_BASE_URL` environment variables for Flutter on Windows PowerShell. ```powershell $env:PUB_HOSTED_URL="https://mirrors.tuna.tsinghua.edu.cn/dart-pub" $env:FLUTTER_STORAGE_BASE_URL="https://mirrors.tuna.tsinghua.edu.cn/flutter" ``` -------------------------------- ### Implement url_launcher Plugin Source: https://docs.flutter.dev/packages-and-plugins/using-packages Add the plugin to pubspec.yaml and use launchUrl to open web links. This plugin requires platform-specific code and a project rebuild. ```yaml dependencies: flutter: sdk: flutter url_launcher: ^5.4.0 ``` ```dart import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; ​ void main() { runApp(const MyApp()); } ​ class MyApp extends StatelessWidget { const MyApp({super.key}); ​ @override Widget build(BuildContext context) { return const MaterialApp(home: DemoPage()); } } ​ class DemoPage extends StatelessWidget { const DemoPage({super.key}); ​ void launchURL() { launchUrl(Uri.parse('https://flutter.dev')); } ​ @override Widget build(BuildContext context) { return Scaffold( body: Center( child: ElevatedButton( onPressed: launchURL, child: const Text('Show Flutter homepage'), ), ), ); } } ``` -------------------------------- ### Dart VM Service URI Output Source: https://docs.flutter.dev/testing/native-debugging Console output displayed when a Flutter app starts in the debugger, showing the Dart VM service listening address and URI token. ```text flutter: The Dart VM service is listening on http://127.0.0.1:62080/KPHEj2qPD1E=/ ``` -------------------------------- ### Flutter CLI migration commands Source: https://docs.flutter.dev/release/breaking-changes/windows-dark-mode Commands to verify the SDK version, upgrade Flutter, regenerate Windows platform files, and verify the build. ```bash flutter --version ``` ```bash flutter upgrade ``` ```bash flutter create --platforms=windows . ``` ```bash flutter build windows ``` -------------------------------- ### Create FFI plugin with flutter create command Source: https://docs.flutter.dev/platform-integration/android/c-interop Creates a new FFI plugin named 'native_add' with support for multiple platforms. Include only the platforms you need to build for. ```bash $ flutter create --platforms=android,ios,macos,windows,linux --template=plugin_ffi native_add $ cd native_add ``` -------------------------------- ### Autofocus text field on visibility Source: https://docs.flutter.dev/cookbook/forms/focus Use the autofocus property to automatically focus a TextField when it becomes visible, allowing users to start typing immediately without manual interaction. ```dart TextField( autofocus: true, ); ``` -------------------------------- ### Example 6: Centered Container without explicit size or child Source: https://docs.flutter.dev/ui/layout/constraints When a Container has no child and no fixed size, and its parent (Center) allows it to be any size up to the screen, it defaults to filling the entire screen. ```dart Center(child: Container(color: red)) ``` -------------------------------- ### Initialize VideoPlayerController in Flutter Source: https://docs.flutter.dev/cookbook/plugins/play-video This snippet demonstrates how to create a `StatefulWidget` and initialize a `VideoPlayerController` from a network URL. It also shows how to dispose of the controller to free up resources. ```dart class VideoPlayerScreen extends StatefulWidget { const VideoPlayerScreen({super.key}); @override State createState() => _VideoPlayerScreenState(); } class _VideoPlayerScreenState extends State { late VideoPlayerController _controller; late Future _initializeVideoPlayerFuture; @override void initState() { super.initState(); // Create and store the VideoPlayerController. The VideoPlayerController // offers several different constructors to play videos from assets, files, // or the internet. _controller = VideoPlayerController.networkUrl( Uri.parse( 'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4', ), ); _initializeVideoPlayerFuture = _controller.initialize(); } @override void dispose() { // Ensure disposing of the VideoPlayerController to free up resources. _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { // Complete the code in the next step. return Container(); } } ``` -------------------------------- ### Flutter Logo App without Animation (Dart) Source: https://docs.flutter.dev/ui/animations/tutorial This snippet presents a basic Flutter application that displays a static Flutter logo. It serves as a foundational example before introducing animation logic. ```dart import 'package:flutter/material.dart'; void main() => runApp(const LogoApp()); class LogoApp extends StatefulWidget { const LogoApp({super.key}); @override State createState() => _LogoAppState(); } class _LogoAppState extends State { @override Widget build(BuildContext context) { return Center( child: Container( margin: const EdgeInsets.symmetric(vertical: 10), height: 300, width: 300, child: const FlutterLogo(), ), ); } } ``` -------------------------------- ### Review and sign Android SDK licenses Source: https://docs.flutter.dev/platform-integration/android/setup Run this command in your terminal to review and accept the Android SDK licenses required before developing Flutter apps for Android. ```bash $ flutter doctor --android-licenses ``` -------------------------------- ### Dart Memory Concepts Example Source: https://docs.flutter.dev/tools/devtools/memory This snippet illustrates Dart's memory management concepts, including object allocation, retaining paths, and when objects become unreachable for garbage collection. ```dart class Child{} class Parent { Child? child; } Parent parent1 = Parent(); void myFunction() { Child? child = Child(); // The `child` object was allocated in memory. // It's now retained from garbage collection // by one retaining path (root …-> myFunction -> child). Parent? parent2 = Parent()..child = child; parent1.child = child; // At this point the `child` object has three retaining paths: // root …-> myFunction -> child // root …-> myFunction -> parent2 -> child // root -> parent1 -> child child = null; parent1.child = null; parent2 = null; // At this point, the `child` instance is unreachable // and will eventually be garbage collected. … } ``` -------------------------------- ### File modification list for Windows environment Source: https://docs.flutter.dev/testing/native-debugging?tab=from-vscode-to-xcode-ios Shows the directory structure and last write times for native configuration files on Windows. This output confirms that the build configurations were updated successfully. ```text C:\dev\example\ios\Flutter\ Mode LastWriteTime Length Name ---- ------------- ------ ---- 8/1/2025 9:15 AM Debug.xcconfig 8/1/2025 9:15 AM Release.xcconfig C:\dev\example\linux\flutter\ Mode LastWriteTime Length Name ---- ------------- ------ ---- ``` -------------------------------- ### Initialize MethodChannel in FlutterWindow::OnCreate Source: https://docs.flutter.dev/platform-integration/platform-channels Sets up the MethodChannel with the specific channel name 'samples.flutter.dev/battery' during the Windows window creation. ```cpp bool FlutterWindow::OnCreate() { // ... RegisterPlugins(flutter_controller_->engine()); flutter::MethodChannel<> channel( flutter_controller_->engine()->messenger(), "samples.flutter.dev/battery", &flutter::StandardMethodCodec::GetInstance()); channel.SetMethodCallHandler( [](const flutter::MethodCall<>& call, std::unique_ptr> result) { // TODO }); SetChildContent(flutter_controller_->view()->GetNativeWindow()); return true; } ``` -------------------------------- ### Show Validation Errors in Flutter TextField Source: https://docs.flutter.dev/flutter-for/uikit-devs Dynamically update the `errorText` property of `InputDecoration` based on user input validation. The example demonstrates email validation and updates the error state. ```dart import 'package:flutter/material.dart'; void main() { runApp(const SampleApp()); } class SampleApp extends StatelessWidget { const SampleApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return const MaterialApp(title: 'Sample App', home: SampleAppPage()); } } class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); @override State createState() => _SampleAppPageState(); } class _SampleAppPageState extends State { String? _errorText; bool isEmail(String em) { String emailRegexp = r'^(([^<>()[\\]\\.,;:\s@\"]+(\.[^<>()[\\]\\.,;:\s@\"]+)*)|' r'(\".+\"))@((\\[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\\])|' r'(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'; RegExp regExp = RegExp(emailRegexp); return regExp.hasMatch(em); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: Center( child: TextField( onSubmitted: (text) { setState(() { if (!isEmail(text)) { _errorText = 'Error: This is not an email'; } else { _errorText = null; } }); }, decoration: InputDecoration( hintText: 'This is a hint', errorText: _errorText, ), ), ), ); } } ``` -------------------------------- ### Manage Local State with StatefulWidget in Flutter Source: https://docs.flutter.dev/flutter-for/compose-devs This example shows a basic counter app using a StatefulWidget in Flutter, where the _counter state is updated via setState() to trigger UI redraws. ```dart class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { int _counter = 0; @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('$_counter'), TextButton( onPressed: () => setState(() { _counter++; }), child: const Text('+'), ), ], ), ), ); } } ``` -------------------------------- ### Bundle license files Source: https://docs.flutter.dev/tools/pubspec Specify paths to additional license files that should be bundled with the application. ```yaml flutter: licenses: - [path_to_file] ``` -------------------------------- ### Set PUB_HOSTED_URL for Flutter mirrors Source: https://docs.flutter.dev/community/china Configures the environment to fetch Flutter packages from a mirror site. This is necessary for users in China to bypass connectivity issues. ```powershell $ $env:PUB_HOSTED_URL="https://pub.flutter-io.cn" ``` ```bash $ export PUB_HOSTED_URL="https://pub.flutter-io.cn" ``` ```bash $ export PUB_HOSTED_URL="https://pub.flutter-io.cn" ``` -------------------------------- ### Configure platforms in Package.swift Source: https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-plugin-authors Platform configuration block for Package.swift specifying minimum iOS and macOS versions. Remove unsupported platforms as needed for your plugin. ```swift platforms: [ // TODO: Update the platforms your plugin supports. // If your plugin only supports iOS, remove `.macOS(...)`. // If your plugin only supports macOS, remove `.iOS(...)`. .iOS("13.0"), .macOS("10.15") ], ``` -------------------------------- ### Encode Image to PNG bytes in Dart Source: https://docs.flutter.dev/release/release-notes/release-notes-0.0.21-1.0.0.md Use Image.toByteData() with the format parameter to encode a dart:ui Image into PNG bytes. Pass ui.ImageByteFormat.png to get the encoded byte data. ```dart image.toByteData(format: ui.ImageByteFormat.png); ``` -------------------------------- ### Import YouTubeApi from googleapis package Source: https://docs.flutter.dev/data-and-backend/google-apis Import the root API class for the desired Google API. Each API is provided as a separate Dart library in name_version format. ```dart /// Provides the `YouTubeApi` class. import 'package:googleapis/youtube/v3.dart'; ``` -------------------------------- ### Row with all children Expanded Source: https://docs.flutter.dev/ui/layout/constraints This example shows a Row where all children are wrapped in Expanded widgets. Each Expanded widget takes a size proportional to its flex parameter, overriding its child's preferred width. ```dart Row( children: [ Expanded( child: Container( color: red, child: const Text( 'This is a very long text that won\'t fit the line.', style: big, ), ), ), Expanded( child: Container( color: green, child: const Text('Goodbye!', style: big), ), ), ], ) ``` -------------------------------- ### Build Windows version of the Flutter app Source: https://docs.flutter.dev/testing/native-debugging?tab=from-vscode-to-xcode-ios Execute this command in PowerShell or the Command Prompt to prepare the Windows application for debugging. ```powershell C:\> flutter build windows --debug ``` ```text Building Windows application... 31.4s √ Built build\windows\runner\Debug\my_app.exe. ``` -------------------------------- ### Flutter CLI Command Reference Source: https://docs.flutter.dev/reference/flutter-cli A collection of specific commands for project maintenance, building, debugging, and environment configuration. ```bash flutter analyze -d ``` ```bash flutter assemble -o ``` ```bash flutter attach -d ``` ```bash flutter bash-completion ``` ```bash flutter build ``` ```bash flutter channel ``` ```bash flutter clean ``` ```bash flutter config --build-dir= ``` ```bash flutter create ``` ```bash flutter custom-devices list ``` ```bash flutter devices -d ``` ```bash flutter doctor ``` ```bash flutter downgrade ``` ```bash flutter drive ``` ```bash flutter emulators ``` ```bash flutter gen-l10n ``` ```bash flutter install -d ``` ```bash flutter logs ``` ```bash flutter precache ``` ```bash flutter pub ``` ```bash flutter run ``` ```bash flutter screenshot ``` ```bash flutter symbolize --input= ``` ```bash flutter test [] ``` ```bash flutter upgrade ``` -------------------------------- ### Example 7: Nested Containers, parent sized by child Source: https://docs.flutter.dev/ui/layout/constraints A red Container without an explicit size will size itself to its green child's 30x30 dimensions, making the red color invisible. ```dart Center( child: Container( color: red, child: Container(color: green, width: 30, height: 30), ), ) ``` -------------------------------- ### DatabaseService getAll method to fetch all ToDo items Source: https://docs.flutter.dev/app-architecture/design-patterns/sql Queries the database to retrieve all ToDo items and maps each database entry to a Todo instance. Returns a Result containing the list of todos or an error if the query fails. ```dart Future>> getAll() async { try { final entries = await _database!.query( _todoTableName, columns: [_idColumnName, _taskColumnName], ); final list = entries .map( (element) => Todo( id: element[_idColumnName] as int, task: element[_taskColumnName] as String, ), ) .toList(); return Result.ok(list); } on Exception catch (e) { return Result.error(e); } } ``` -------------------------------- ### Define a Custom Curve with ShakeCurve Source: https://docs.flutter.dev/ui/animations This example shows how to create a custom `Curve` by extending the `Curve` class. Custom curves allow for unique animation behaviors not available in the standard `Curves` class. ```dart import 'dart:math'; class ShakeCurve extends Curve { @override double transform(double t) => sin(t * pi * 2); } ``` -------------------------------- ### Define ButtonSegments for SegmentedButton in Flutter Source: https://docs.flutter.dev/release/breaking-changes/material-3-migration Use ButtonSegment to define individual items within a SegmentedButton widget. This example shows segments for different weather states using icons and enum values. ```dart segments: const >[ ButtonSegment( icon: Icon(Icons.cloud_outlined), value: Weather.cloudy, ), ButtonSegment( icon: Icon(Icons.beach_access_sharp), value: Weather.rainy, ), ButtonSegment( icon: Icon(Icons.brightness_5_sharp), value: Weather.sunny, ), ], ), ``` -------------------------------- ### Configure Release Signing in Android Gradle Source: https://docs.flutter.dev/deployment/android This snippet demonstrates how to add a release signing configuration within the `android` block. It uses the previously loaded `keystoreProperties` to set the key alias, passwords, and store file. ```kotlin android { // ... signingConfigs { create("release") { keyAlias = keystoreProperties["keyAlias"] as String keyPassword = keystoreProperties["keyPassword"] as String storeFile = keystoreProperties["storeFile"]?.let { file(it) } storePassword = keystoreProperties["storePassword"] as String } } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, // so `flutter run --release` works. signingConfig = signingConfigs.getByName("debug") signingConfig = signingConfigs.getByName("release") } } ... } ``` ```groovy android { // ... signingConfigs { release { keyAlias = keystoreProperties['keyAlias'] keyPassword = keystoreProperties['keyPassword'] storeFile = keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null storePassword = keystoreProperties['storePassword'] } } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, // so `flutter run --release` works. signingConfig = signingConfigs.debug signingConfig = signingConfigs.release } } ... } ``` -------------------------------- ### Manually add associated domains to iOS entitlements Source: https://docs.flutter.dev/cookbook/navigation/set-up-universal-links Edit the `ios/Runner/Runner.entitlements` XML file to manually add an associated domain entry, replacing `example.com` with your actual web domain. ```xml com.apple.developer.associated-domains applinks:example.com ``` -------------------------------- ### Migrate MaterialState to WidgetState in Dart Source: https://docs.flutter.dev/release/breaking-changes/material-state This example demonstrates the migration from MaterialState to WidgetState APIs, showing the 'before' and 'after' code for handling widget states, properties, mouse cursors, and border sides. ```dart MaterialState selected = MaterialState.selected; final MaterialStateProperty backgroundColor; class _MouseCursor extends MaterialStateMouseCursor{ const _MouseCursor(this.resolveCallback); final MaterialPropertyResolver resolveCallback; @override MouseCursor resolve(Set states) => resolveCallback(states) ?? MouseCursor.uncontrolled; } BorderSide side = MaterialStateBorderSide.resolveWith((Set states) { if (states.contains(MaterialState.selected)) { return const BorderSide(color: Colors.red); } return null; }); ``` ```dart WidgetState selected = WidgetState.selected; final WidgetStateProperty backgroundColor; class _MouseCursor extends WidgetStateMouseCursor{ const _MouseCursor(this.resolveCallback); final WidgetPropertyResolver resolveCallback; @override MouseCursor resolve(Set states) => resolveCallback(states) ?? MouseCursor.uncontrolled; } BorderSide side = WidgetStateBorderSide.resolveWith((Set states) { if (states.contains(WidgetState.selected)) { return const BorderSide(color: Colors.red); } return null; }); ``` -------------------------------- ### Execute Flutter Widget Test File Source: https://docs.flutter.dev/cookbook/testing/widget/scrolling Use this command in the project's root directory to run a specific Flutter widget test file. ```bash flutter test test/widget_test.dart ``` -------------------------------- ### Migrate BinaryMessages API to ServicesBinding in Dart Source: https://docs.flutter.dev/release/breaking-changes/1-22-deprecations The BinaryMessages class and its static methods were removed. Migrate to ServicesBinding.instance.defaultBinaryMessenger for equivalent functionality. The codeList contains 'before' and 'after' examples for various API calls. ```dart defaultBinaryMessenger ``` ```dart ServicesBinding.instance.defaultBinaryMessenger ``` ```dart BinaryMessages ``` ```dart BinaryMessenger ``` ```dart BinaryMessages.handlePlatformMessage ``` ```dart ServicesBinding.instance.defaultBinaryMessenger.handlePlatformMessage ``` ```dart BinaryMessages.send ``` ```dart ServicesBinding.instance.defaultBinaryMessenger.send ``` ```dart BinaryMessages.setMessageHandler ``` ```dart ServicesBinding.instance.defaultBinaryMessenger.setMessageHandler ``` ```dart BinaryMessages.setMockMessageHandler ``` ```dart ServicesBinding.instance.defaultBinaryMessenger.setMockMessageHandler ``` -------------------------------- ### Build Android app bundle for debugging Source: https://docs.flutter.dev/testing/native-debugging Command to generate Android platform dependencies and the corresponding terminal output indicating a successful build. ```bash flutter build appbundle --debug ``` ```text Running Gradle task 'bundleDebug'... 27.1s ✓ Built build/app/outputs/bundle/debug/app-debug.aab. ``` -------------------------------- ### Build Android APKs for Integration Testing Source: https://docs.flutter.dev/testing/integration-tests Commands to navigate to the Android directory and build debug and test APKs using Flutter and Gradle. ```bash // Go to the Android directory which contains the gradlew script $ pushd android // Build a debug APK for Flutter with gradlew // Note that a standard --release build will not include package:integration_test $ flutter build apk --debug // Build an Android test APK $ ./gradlew app:assembleAndroidTest // Build a debug APK by passing in an integration test $ ./gradlew app:assembleDebug -Ptarget=integration_test/_test.dart ``` -------------------------------- ### Handle I/O-bound operations with async/await Source: https://docs.flutter.dev/flutter-for/xamarin-forms-devs Declare functions as `async` and `await` long-running I/O tasks like network calls to prevent blocking the UI thread. This example fetches data from a URL. ```dart Future loadData() async { final Uri dataURL = Uri.parse('https://jsonplaceholder.typicode.com/posts'); final http.Response response = await http.get(dataURL); setState(() { data = (jsonDecode(response.body) as List).cast>(); }); } ``` -------------------------------- ### Migrate to SurfaceProducer API in Java Source: https://docs.flutter.dev/release/breaking-changes/android-surface-plugins Replace SurfaceTextureEntry creation and Surface instantiation with the new SurfaceProducer API. ```java TextureRegistry.SurfaceTextureEntry entry = textureRegistry.createSurfaceTexture(); TextureRegistry.SurfaceProducer producer = textureRegistry.createSurfaceProducer(); ``` ```java Surface surface = new Surface(entry.surfaceTexture()); Surface surface = producer.getSurface(); ``` -------------------------------- ### Updating UI Dynamically with StatefulWidget in Flutter Source: https://docs.flutter.dev/flutter-for/xamarin-forms-devs Employ StatefulWidget when UI elements need to change based on user interaction or data updates. This example demonstrates how to update text when a FloatingActionButton is pressed. ```dart import 'package:flutter/material.dart'; void main() { runApp(const SampleApp()); } class SampleApp extends StatelessWidget { /// This widget is the root of your application. const SampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(title: 'Sample App', home: SampleAppPage()); } } class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); @override State createState() => _SampleAppPageState(); } class _SampleAppPageState extends State { /// Default placeholder text String textToShow = 'I Like Flutter'; void _updateText() { setState(() { // Update the text textToShow = 'Flutter is Awesome!'; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: Center(child: Text(textToShow)), floatingActionButton: FloatingActionButton( onPressed: _updateText, tooltip: 'Update Text', child: const Icon(Icons.update), ), ); } } ``` -------------------------------- ### Create Reusable Widget in Flutter Source: https://docs.flutter.dev/flutter-for/react-native-devs This example defines a `StatelessWidget` named `CustomCard` with named, required parameters. It shows how to create a reusable UI widget and its usage within another widget in Flutter. ```dart /// Flutter class CustomCard extends StatelessWidget { const CustomCard({super.key, required this.index, required this.onPress}); final int index; final void Function() onPress; @override Widget build(BuildContext context) { return Card( child: Column( children: [ Text('Card $index'), TextButton(onPressed: onPress, child: const Text('Press')), ], ), ); } } class UseCard extends StatelessWidget { const UseCard({super.key, required this.index}); final int index; @override Widget build(BuildContext context) { /// Usage return CustomCard( index: index, onPress: () { print('Card $index'); }, ); } ``` -------------------------------- ### Generated plugin configuration files directory listing Source: https://docs.flutter.dev/testing/native-debugging Shows the files generated across different platform directories (macOS, Windows, and root) after adding a plugin like url_launcher. ```text 8/1/2025 9:15 AM generated_plugin_registrant.cc 8/1/2025 9:15 AM generated_plugins.cmake C:\dev\example\macos\Flutter\ Mode LastWriteTime Length Name ---- ------------- ------ ---- 8/1/2025 9:15 AM Flutter-Debug.xcconfig 8/1/2025 9:15 AM Flutter-Release.xcconfig 8/1/2025 9:15 AM GeneratedPluginRegistrant.swift C:\dev\example\ Mode LastWriteTime Length Name ---- ------------- ------ ---- 8/1/2025 9:15 AM pubspec.lock 8/1/2025 9:15 AM pubspec.yaml C:\dev\example\windows\flutter\ Mode LastWriteTime Length Name ---- ------------- ------ ---- 8/1/2025 9:15 AM generated_plugin_registrant.cc 8/1/2025 9:15 AM generated_plugins.cmake ``` -------------------------------- ### Accessing View Model Data in Widget Build Source: https://docs.flutter.dev/app-architecture/case-study/ui-layer Access properties from the view model within the build method to pass data to sub-widgets. This example shows providing booking data to a SliverList. ```dart @override Widget build(BuildContext context) { return Scaffold( // Some code was removed for brevity. body: SafeArea( child: ListenableBuilder( listenable: viewModel, builder: (context, _) { return CustomScrollView( slivers: [ SliverToBoxAdapter(...), SliverList.builder( itemCount: viewModel.bookings.length, itemBuilder: (_, index) => _Booking( key: ValueKey(viewModel.bookings[index].id), booking:viewModel.bookings[index], onTap: () => context.push(Routes.bookingWithId( viewModel.bookings[index].id)), onDismissed: (_) => viewModel.deleteBooking.execute( viewModel.bookings[index].id, ), ), ), ], ); }, ), ), ``` -------------------------------- ### Configure snap metadata in snapcraft.yaml Source: https://docs.flutter.dev/deployment/linux Define core snap properties including confinement level, base runtime, and quality grade. These settings control system resource access, runtime environment, and publication eligibility. ```yaml confinement: strict base: core22 grade: stable ``` -------------------------------- ### Create MaterialApp with Theme in Flutter Source: https://docs.flutter.dev/ai/genui/get-started Define the main application widget with MaterialApp configuration, including title, theme with primary color, and home screen. This is the root widget for the A2UI example application. ```dart class GenUIExampleApp extends StatelessWidget { const GenUIExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'A2UI Example', theme: ThemeData( primarySwatch: Colors.blue, ), home: const ChatScreen(), ); } } ``` -------------------------------- ### Add synchronization flag to data model in Dart Source: https://docs.flutter.dev/app-architecture/design-patterns/offline-first Uses a boolean flag to track whether local changes have been pushed to the server. This example uses the Freezed package for immutable data classes. ```dart @freezed abstract class UserProfile with _$UserProfile { const factory UserProfile({ required String name, required String photoUrl, @Default(false) bool synchronized, }) = _UserProfile; } ``` -------------------------------- ### Bash: Decode Base64 Encoded Play Store Upload Key Source: https://docs.flutter.dev/deployment/cd This command deserializes a base64-encoded upload key stored in an environment variable, writing it to a file on the CI system during the install phase. ```bash echo "$PLAY_STORE_UPLOAD_KEY" | base64 --decode > [path to your upload keystore] ``` -------------------------------- ### Flutter app entry point and root widget Source: https://docs.flutter.dev/learn/pathway/tutorial/create-an-app The main function is the entry point for any Dart program. It calls runApp() with the root widget (MainApp) to initialize the Flutter app and build the widget tree. ```dart void main() { runApp(const MainApp()); } ``` ```dart class MainApp extends StatelessWidget { const MainApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: Scaffold( body: Center( child: Text('Hello World!'), ), ), ); } } ``` -------------------------------- ### Add provider package dependency with Flutter CLI Source: https://docs.flutter.dev/data-and-backend/state-mgmt/simple Install the provider package as a dependency using the flutter pub add command. This must be done before importing and using the provider package in your project. ```bash $ flutter pub add provider ``` -------------------------------- ### Update Podfile for Flutter integration Source: https://docs.flutter.dev/add-to-app/ios/project-setup?tab=embed-using-cocoapods Modify the Podfile to include Flutter's helper script and install necessary pods for specific targets. Ensure the flutter_application_path correctly points to your Flutter module. ```ruby flutter_application_path = '../my_flutter' load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb') ``` ```ruby target 'MyApp' do install_all_flutter_pods(flutter_application_path) end ``` ```ruby post_install do |installer| flutter_post_install(installer) if defined?(flutter_post_install) end ``` -------------------------------- ### Open pubspec.yaml in terminal Source: https://docs.flutter.dev/cookbook/design/fonts Access the project configuration file using a command-line text editor. ```shell $ vi pubspec.yaml ``` -------------------------------- ### Create LLM Provider with Initial History Source: https://docs.flutter.dev/ai/ai-toolkit/feature-integration Initialize a new provider instance, such as FirebaseProvider, with an existing list of chat messages. ```dart class _HomePageState extends State { ... // create a new provider with the given history and the current settings LlmProvider _createProvider([List? history]) => FirebaseProvider( history: history, ... ); ... } ``` -------------------------------- ### Kotlin: Get battery level with version-specific handling Source: https://docs.flutter.dev/platform-integration/platform-channels Retrieve battery level using BatteryManager for API 21+ or IntentFilter for earlier versions. Returns battery percentage as an integer, or -1 if unavailable. ```kotlin private fun getBatteryLevel(): Int { val batteryLevel: Int if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) } else { val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1) } return batteryLevel } ``` -------------------------------- ### Run Flutter application on desktop platforms Source: https://docs.flutter.dev/desktop Launches the application on the specified desktop target. If the -d flag is omitted, Flutter lists all available devices. ```bash C:\> flutter run -d windows $ flutter run -d macos $ flutter run -d linux ``` -------------------------------- ### Aligning tabs to the start in a scrollable Flutter TabBar Source: https://docs.flutter.dev/release/breaking-changes/tab-alignment In Material 3, scrollable TabBars default to TabAlignment.startOffset. Set tabAlignment to TabAlignment.start to align tabs to the beginning without the 52.0 pixel offset. ```dart TabBar( isScrollable: true, tabs: List.generate( count, (int index) => Tab(text: 'Tab $index'), ).toList(), ); ``` ```dart TabBar( tabAlignment: TabAlignment.start, isScrollable: true, tabs: List.generate( count, (int index) => Tab(text: 'Tab $index'), ).toList(), ); ``` -------------------------------- ### Configure Flutter View Constraints (JavaScript) Source: https://docs.flutter.dev/platform-integration/web/embedding-flutter-web Define layout constraints for a Flutter web view using the `viewConstraints` property in `app.addView`. These constraints guide Flutter's rendering within the `hostElement`. ```javascript // Adding a view with initial data... let viewId = app.addView({ hostElement: someElement, viewConstraints: { maxWidth: 320, minHeight: 0, maxHeight: Infinity, } }); ``` -------------------------------- ### Migrate Layer.findAll to findAllAnnotations in Dart Source: https://docs.flutter.dev/release/breaking-changes/1-22-deprecations The Layer.findAll method was deprecated. Migrate to findAllAnnotations and access the result via AnnotationResult.annotations. The first code example shows the deprecated usage, and the second shows the updated usage. ```dart findAll(offset); ``` ```dart findAllAnnotations(offset).annotations; ``` -------------------------------- ### Implementing showAutocorrectionPromptRect for iOS Autocorrect in Dart Source: https://docs.flutter.dev/release/breaking-changes/add-showAutocorrectionPromptRect For iOS applications supporting autocorrect, implement showAutocorrectionPromptRect to update the autocorrection highlight range. This example shows how to manage the highlight based on text changes and focus. ```dart // Assume your `TextInputClient` is a `State` subclass, and it has a variable // `_currentPromptRectRange` that controls the autocorrection highlight. class CustomTextInputClient extends State<...> implements TextInputClient { @override void updateEditingValue(TextEditingValue value) { // When the text changes, the highlight needs to be dismissed. if (value.text != _value.text) { setState(() { _currentPromptRectRange = null; }); } } ​ void _handleFocusChanged() { // When this text input loses focus, the autocorrection highlight needs // to be dismissed. if (!_hasFocus) { setState(() { _currentPromptRectRange = null; }); } } ​ @override void showAutocorrectionPromptRect(int start, int end) { // Updates the range of the highlight, as iOS requested. // This method isn't called when iOS decides to // dismiss the highlight. setState(() { _currentPromptRectRange = TextRange(start: start, end: end); }); } } ``` -------------------------------- ### Implement a signature painter in Flutter using CustomPainter Source: https://docs.flutter.dev/flutter-for/xamarin-forms-devs Use the CustomPaint widget and a CustomPainter subclass to draw directly on the Skia canvas. This example captures touch offsets via GestureDetector to render a signature. ```dart import 'package:flutter/material.dart'; ​ void main() { runApp(const MaterialApp(home: DemoApp())); } ​ class DemoApp extends StatelessWidget { const DemoApp({super.key}); ​ @override Widget build(BuildContext context) => const Scaffold(body: Signature()); } ​ class Signature extends StatefulWidget { const Signature({super.key}); ​ @override SignatureState createState() => SignatureState(); } ​ class SignatureState extends State { List _points = []; ​ void _onPanUpdate(DragUpdateDetails details) { setState(() { final RenderBox referenceBox = context.findRenderObject() as RenderBox; final Offset localPosition = referenceBox.globalToLocal( details.globalPosition, ); _points = List.from(_points)..add(localPosition); }); } ​ @override Widget build(BuildContext context) { return GestureDetector( onPanUpdate: _onPanUpdate, onPanEnd: (details) => _points.add(null), child: CustomPaint( painter: SignaturePainter(_points), size: Size.infinite, ), ); } } ​ class SignaturePainter extends CustomPainter { const SignaturePainter(this.points); ​ final List points; ​ @override void paint(Canvas canvas, Size size) { final Paint paint = Paint() ..color = Colors.black ..strokeCap = StrokeCap.round ..strokeWidth = 5; for (int i = 0; i < points.length - 1; i++) { if (points[i] != null && points[i + 1] != null) { canvas.drawLine(points[i]!, points[i + 1]!, paint); } } } ​ @override bool shouldRepaint(SignaturePainter oldDelegate) => oldDelegate.points != points; } ``` -------------------------------- ### Add Google Generative AI and GenUI Dependencies Source: https://docs.flutter.dev/ai/genui/get-started Add the necessary packages to your `pubspec.yaml` file using the `dart pub add` command. ```bash $ dart pub add genui google_generative_ai ``` -------------------------------- ### HomeViewModel with multiple action states Source: https://docs.flutter.dev/app-architecture/design-patterns/command Demonstrates the complexity of managing separate 'running' and 'error' states for multiple actions like 'load' and 'edit' within a single view model. ```dart class HomeViewModel extends ChangeNotifier { User? get user => // ... bool get runningLoad => // ... Exception? get errorLoad => // ... bool get runningEdit => // ... Exception? get errorEdit => // ... void load() { // load user } void edit(String name) { // edit user } } ``` -------------------------------- ### Get battery level method in Android Source: https://docs.flutter.dev/platform-integration/platform-channels Retrieves battery level using BatteryManager API for Android 5.0+ (LOLLIPOP) or falls back to intent-based approach for older versions. Returns -1 if unavailable. ```java private int getBatteryLevel() { int batteryLevel = -1; if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE); batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY); } else { Intent intent = new ContextWrapper(getApplicationContext()). registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); } ​ return batteryLevel; } ``` -------------------------------- ### _flutter.loader.load() Source: https://docs.flutter.dev/platform-integration/web/initialization Initializes the Flutter web application with customizable configuration and provides callbacks for advanced control over the initialization process. ```APIDOC ## JS _flutter.loader.load() ### Description Initializes the Flutter web application. This function allows customization of the app's initialization behavior through optional arguments like `config` and `onEntrypointLoaded`. ### Method Function Call ### Endpoint `_flutter.loader.load()` ### Parameters #### Request Body (Arguments) - **config** (Object) - Optional - The Flutter configuration for your app. This object can contain various fields to customize rendering, asset loading, and debugging. - **assetBase** (String) - Optional - The base URL of the `assets` directory. Useful when Flutter loads from a different domain or subdirectory. - **canvasKitBaseUrl** (String) - Optional - The base URL from where `canvaskit.wasm` is downloaded. - **canvasKitVariant** (String) - Optional - The CanvasKit variant to download. Options: `auto` (default), `full`, `chromium`. - **canvasKitForceCpuOnly** (bool) - Optional - If `true`, forces CPU-only rendering in CanvasKit. - **canvasKitMaximumSurfaces** (double) - Optional - The maximum number of overlay surfaces for CanvasKit renderer. - **debugShowSemanticNodes** (bool) - Optional - If `true`, visibly renders the semantics tree onscreen for debugging. - **entrypointBaseUrl** (String) - Optional - The base URL of your Flutter app's entrypoint. Defaults to "/". - **hostElement** (HtmlElement) - Optional - The HTML Element into which Flutter renders the app. If not set, Flutter web takes over the whole page. - **renderer** (String) - Optional - Specifies the web renderer: `"canvaskit"` or `"skwasm"`. - **forceSingleThreadedSkwasm** (bool) - Optional - Forces the Skia WASM renderer to run in single-threaded mode for compatibility. Default is `false` for multi-threaded rendering. - **onEntrypointLoaded** (Function) - Optional - A callback function invoked when the engine is ready to be initialized. It receives an `engineInitializer` object as its only parameter. - **engineInitializer** (Object) - The object passed to `onEntrypointLoaded`. - **initializeEngine()** (Function) - A function on `engineInitializer` to set run-time configuration and start the Flutter web engine. Returns a `Promise` that resolves with an `app runner` object. - **app runner** (Object) - The object returned by `initializeEngine()`. - **runApp()** (Function) - A method on `app runner` that runs the Flutter app. Returns a `flutter app` object. - **flutter app** (Object) - The object returned by `runApp()`. - **addView()** (Function) - (Multi-view mode) Adds a view to the app. - **removeView()** (Function) - (Multi-view mode) Removes a view from the app. ### Request Example ```javascript _flutter.loader.load({ config: { renderer: 'skwasm', forceSingleThreadedSkwasm: true, }, }); ``` ### Response This function does not directly return a value but initiates the Flutter application loading process. The `onEntrypointLoaded` callback provides objects for further control. #### Response Example N/A (Asynchronous initialization) ``` -------------------------------- ### Upgrade cupertino_icons dependency in pubspec.yaml Source: https://docs.flutter.dev/release/breaking-changes/cupertino-icons-1.0.0 This snippet shows how to update the `cupertino_icons` package version in your `pubspec.yaml` file from an older version to 1.0.0. This change is necessary to get the new SF Symbols styled icons. ```yaml dependencies: ... // Other dependencies cupertino_icons: ^0.1.0 ``` ```yaml dependencies: ... // Other dependencies cupertino_icons: ^1.0.0 ``` -------------------------------- ### Generate Flutter iOS frameworks Source: https://docs.flutter.dev/add-to-app/ios/project-setup Run this command to generate the necessary xcframeworks and LLDB files for your iOS project. ```bash $ flutter build ios-framework --output=/path/to/MyApp/Flutter/ ``` -------------------------------- ### ButtonShapeWidget with animated text display Source: https://docs.flutter.dev/cookbook/effects/download-button Displays 'GET' or 'OPEN' text with opacity animation based on download state. The button shape transitions between CircleBorder (during download/fetch) and StadiumBorder (idle state) using AnimatedContainer. ```dart @immutable class ButtonShapeWidget extends StatelessWidget { const ButtonShapeWidget({ super.key, required this.isDownloading, required this.isDownloaded, required this.isFetching, required this.transitionDuration, }); final bool isDownloading; final bool isDownloaded; final bool isFetching; final Duration transitionDuration; @override Widget build(BuildContext context) { final ShapeDecoration shape; if (isDownloading || isFetching) { shape = const ShapeDecoration( shape: CircleBorder(), color: Colors.transparent, ); } else { shape = const ShapeDecoration( shape: StadiumBorder(), color: CupertinoColors.lightBackgroundGray, ); } return AnimatedContainer( duration: transitionDuration, curve: Curves.ease, width: double.infinity, decoration: shape, child: Padding( padding: const EdgeInsets.symmetric(vertical: 6), child: AnimatedOpacity( duration: transitionDuration, opacity: isDownloading || isFetching ? 0.0 : 1.0, curve: Curves.ease, child: Text( isDownloaded ? 'OPEN' : 'GET', textAlign: TextAlign.center, style: Theme.of(context).textTheme.labelLarge?.copyWith( fontWeight: FontWeight.bold, color: CupertinoColors.activeBlue, ), ), ), ), ); } } ``` -------------------------------- ### Run a Flutter web app Source: https://docs.flutter.dev/platform-integration/web/building Launch the application in Chrome using standard or WebAssembly build modes. ```bash $ flutter run -d chrome ``` ```bash $ flutter run -d chrome --wasm ``` -------------------------------- ### Configure app version in pubspec.yaml Source: https://docs.flutter.dev/deployment/windows Sets the build name and build number which determine the executable's file and product versions. ```yaml version: 1.0.0+1 ``` -------------------------------- ### Handle Zone Mismatch with Mutable ZoneValue Source: https://docs.flutter.dev/release/breaking-changes/zone-errors This example demonstrates how to use a mutable object within `zoneValues` to update a value after `WidgetsFlutterBinding.ensureInitialized()` has been called, addressing scenarios where `runApp`'s zone depends on plugin-obtained values. ```dart import 'dart:async'; import 'package:flutter/material.dart'; class Mutable { Mutable(this.value); T value; } void main() { var myValue = Mutable(0.0); Zone.current.fork( zoneValues: { 'myKey': myValue, } ).run(() { WidgetsFlutterBinding.ensureInitialized(); var newValue = ...; // obtain value from plugin myValue.value = newValue; // update value in Zone runApp(...); }); } ``` -------------------------------- ### ListView with PrimaryScrollController - Previous Behavior Source: https://docs.flutter.dev/release/breaking-changes/primary-scroll-controller-desktop Previously, this ListView would automatically attach to PrimaryScrollController on all platforms with primary defaulting to true. This example shows the old behavior that caused assertion errors on desktop with multiple ScrollViews. ```dart // Previously, this ListView would always result in primary being true, // and attached to the PrimaryScrollController on all platforms. Scaffold( body: ListView.builder( itemBuilder: (BuildContext context, int index) { return Text('Item $index'); } ), ); ``` -------------------------------- ### Configure CFUG Mirror on macOS/Linux/ChromeOS Source: https://docs.flutter.dev/community/china Set environment variables to use the China Flutter User Group mirror for Flutter SDK and pub packages on Unix-like systems. ```bash export PUB_HOSTED_URL=https://pub.flutter-io.cn export FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn ``` -------------------------------- ### Image asset folder structure with density variants Source: https://docs.flutter.dev/flutter-for/xamarin-forms-devs Organize image assets in folders with density multiplier suffixes. Place the base 1.0x image in the main folder and variants in subdirectories named with their respective multipliers (2.0x, 3.0x, etc.). ```text images/my_icon.png // Base: 1.0x image images/2.0x/my_icon.png // 2.0x image images/3.0x/my_icon.png // 3.0x image ``` -------------------------------- ### Implement Platform-Specific Bottom Navigation Bars in Flutter Source: https://docs.flutter.dev/platform-integration/platform-adaptations This example demonstrates using CupertinoTabBar for iOS and NavigationBar for Android within a Scaffold to create platform-adaptive bottom navigation, mapping navigation items to platform-specific icons. ```dart final Map _navigationItems = { 'Menu': Platform.isIOS ? Icon(CupertinoIcons.house_fill) : Icon(Icons.home), 'Order': Icon(Icons.adaptive.share), }; ... Scaffold( body: _currentWidget, bottomNavigationBar: Platform.isIOS ? CupertinoTabBar( currentIndex: _currentIndex, onTap: (index) { setState(() => _currentIndex = index); _loadScreen(); }, items: _navigationItems.entries .map( (entry) => BottomNavigationBarItem( icon: entry.value, label: entry.key, )) .toList(), ) : NavigationBar( selectedIndex: _currentIndex, onDestinationSelected: (index) { setState(() => _currentIndex = index); _loadScreen(); }, destinations: _navigationItems.entries .map((entry) => NavigationDestination( icon: entry.value, label: entry.key, )) .toList(), )); ``` -------------------------------- ### TextInputClient after migration with insertContent override Source: https://docs.flutter.dev/release/breaking-changes/insert-content-text-input-client Implement the `insertContent` method to support rich content insertion from the IME. This is the general approach for migration. ```dart class MyCustomTextInputClient implements TextInputClient { // ... @override void insertContent() { // ... } // ... } ``` -------------------------------- ### Arrange Widgets with Flutter Column and Container Source: https://docs.flutter.dev/flutter-for/react-native-devs This Flutter example illustrates how to arrange widgets in a column using the Column widget, with individual Container widgets for visual elements. Center is used to center the entire column. ```dart @override Widget build(BuildContext context) { return Center( child: Column( children: [ Container(color: Colors.red, width: 100, height: 100), Container(color: Colors.blue, width: 100, height: 100), Container(color: Colors.green, width: 100, height: 100), ], ), ); } ``` -------------------------------- ### Run Flutter orientation tests Source: https://docs.flutter.dev/cookbook/testing/widget/orientation Command to execute the widget tests defined in the project. ```bash flutter test test/widget_test.dart ``` -------------------------------- ### Flutter snapcraft.yaml configuration Source: https://docs.flutter.dev/deployment/linux Complete snapcraft.yaml file for a Flutter Linux app with metadata, confinement, base, grade, dbus slot, apps, and parts configuration. Place in /snap/snapcraft.yaml. ```yaml name: super-cool-app version: 0.1.0 summary: Super Cool App description: Super Cool App that does everything! confinement: strict base: core22 grade: stable slots: dbus-super-cool-app: # adjust accordingly to your app name interface: dbus bus: session name: org.bar.super_cool_app # adjust accordingly to your app name and apps: super-cool-app: command: super_cool_app extensions: [gnome] # gnome includes the libraries required by flutter plugs: - network slots: - dbus-super-cool-app parts: super-cool-app: source: . plugin: flutter flutter-target: lib/main.dart # The main entry-point file of the application ``` -------------------------------- ### Flutter CLI Commands for WebAssembly (Wasm) Source: https://docs.flutter.dev/platform-integration/web/wasm These commands demonstrate how to prepare, run, and build Flutter web applications with WebAssembly support using the Flutter command-line interface. ```bash $ flutter create . --platforms web ``` ```bash $ flutter run -d chrome --wasm ``` ```bash $ flutter build web --wasm ``` -------------------------------- ### Create analysis_options.yaml with flutter_lints Source: https://docs.flutter.dev/release/breaking-changes/flutter-lints-package Minimal configuration file to enable the latest recommended lints from package:flutter_lints. Place this file in the root directory next to pubspec.yaml. ```yaml include: package:flutter_lints/flutter.yaml ``` -------------------------------- ### Illustrate package import structure Source: https://docs.flutter.dev/tools/devtools/app-size This snippet shows a hypothetical package import hierarchy where package:a imports package:b and package:c, and both package:b and package:c import package:d. ```text package:a |__ package:b | |__ package:d |__ package:c |__ package:d ``` -------------------------------- ### Example Play Games Services IDs XML Source: https://docs.flutter.dev/cookbook/games/achievements-leaderboard This XML file contains the Play Games Services IDs for your game, including the app ID, package name, and IDs for achievements and leaderboards. It should be placed at android/app/src/main/res/values/games-ids.xml. ```xml 424242424242 dev.flutter.tictactoe sOmEiDsTrInG sOmEiDsTrInG ``` -------------------------------- ### User Profile View Model Missing Exception Handling Source: https://docs.flutter.dev/app-architecture/design-patterns/result This example demonstrates a common pitfall where a view model method loads data without a `try-catch` block, leading to application crashes if exceptions occur. ```dart class UserProfileViewModel extends ChangeNotifier { // ··· Future load() async { _userProfile = await userProfileRepository.getUserProfile(); notifyListeners(); } } ``` -------------------------------- ### DevTools connection output after app launch Source: https://docs.flutter.dev/tools/devtools/cli Terminal output showing the Dart VM Service URL and DevTools debugger URL after starting a Flutter app. The URL contains a unique security token for each run. ```bash A Dart VM Service on macOS is available at: http://127.0.0.1:51830/u37pq71Re0k=/ The Flutter DevTools debugger and profiler on macOS is available at: http://127.0.0.1:9100?uri=http://127.0.0.1:51830/u37pq71Re0k=/ ``` -------------------------------- ### Create Flutter App Source: https://docs.flutter.dev/flutter-for/react-native-devs Command-line command to scaffold a new Flutter project. Requires Flutter SDK to be in PATH and generates files for both Android and iOS platforms. ```bash $ flutter create ``` -------------------------------- ### Plugin platform support configuration for iOS and Android Source: https://docs.flutter.dev/packages-and-plugins/developing-packages Declare supported platforms in the pubspec.yaml file using the platforms map under flutter.plugin. This example shows iOS and Android support with their respective plugin classes and package names. ```yaml flutter: plugin: platforms: android: package: com.example.hello pluginClass: HelloPlugin ios: pluginClass: HelloPlugin ``` -------------------------------- ### Handle ListView Item Taps with GestureDetector in Flutter Source: https://docs.flutter.dev/flutter-for/xamarin-forms-devs Wraps each ListView item with GestureDetector to detect tap events. Use onTap callback to respond when a user taps a row; the example logs the tapped row index. ```dart import 'dart:developer' as developer; import 'package:flutter/material.dart'; void main() { runApp(const SampleApp()); } class SampleApp extends StatelessWidget { // This widget is the root of your application. const SampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(title: 'Sample App', home: SampleAppPage()); } } class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); @override State createState() => _SampleAppPageState(); } class _SampleAppPageState extends State { List _getListData() { return List.generate( 100, (index) => GestureDetector( onTap: () { developer.log('Row $index tapped'); }, child: Padding( padding: const EdgeInsets.all(10), child: Text('Row $index'), ), ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: ListView(children: _getListData()), ); } } ``` -------------------------------- ### Create a Flutter plugin with specific platform languages Source: https://docs.flutter.dev/packages-and-plugins/developing-packages Use the --template=plugin flag and specify preferred languages for Android (-a) and iOS (-i). ```bash $ flutter create --org com.example --template=plugin --platforms=android,ios,linux,macos,windows -a kotlin hello ``` ```bash $ flutter create --org com.example --template=plugin --platforms=android,ios,linux,macos,windows -a java hello ``` ```bash $ flutter create --org com.example --template=plugin --platforms=android,ios,linux,macos,windows -i objc hello ``` ```bash $ flutter create --org com.example --template=plugin --platforms=android,ios,linux,macos,windows -i swift hello ``` -------------------------------- ### Update Import Statements After Header Migration Source: https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-plugin-authors When migrating header files to a new directory structure, update your Objective-C import statements accordingly. This example shows how to reference a public header file after it has been moved to an `include` subdirectory. ```objc #import "PublicHeaderFile.h" #import "./include/plugin_name/PublicHeaderFile.h" ``` -------------------------------- ### Configure keystore references in key.properties Source: https://docs.flutter.dev/deployment/android Create this file in the android directory to store keystore credentials. Ensure the file is kept private and not checked into source control. ```properties storePassword= keyPassword= keyAlias=upload storeFile= ``` -------------------------------- ### Load resources using Bundle.module Source: https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-plugin-authors Use conditional compilation to load resources from the correct bundle depending on whether the plugin is built as a Swift Package. ```swift #if SWIFT_PACKAGE let settingsURL = Bundle.module.url(forResource: "image", withExtension: "jpg") #else let settingsURL = Bundle(for: Self.self).url(forResource: "image", withExtension: "jpg") #endif ``` -------------------------------- ### Pre-defined Actions: After Migration Source: https://docs.flutter.dev/release/breaking-changes/actions-api-revision This snippet demonstrates the updated approach for mapping pre-defined actions, using specific Intent classes and Type for actions. The `shortcuts` map now uses `ActivateIntent` directly. ```Dart class MyWidget extends StatelessWidget { // ... @override Widget build(BuildContext context) { return Shortcuts( shortcuts: { LogicalKeySet(LogicalKeyboardKey.enter): ActivateIntent, }, child: Actions( actions: >{ ActivateIntent: ActivateAction(), }, child: Container(), ) ); } } ``` -------------------------------- ### Invoke platform method to get battery level in Flutter Source: https://docs.flutter.dev/platform-integration/platform-channels Asynchronously calls the 'getBatteryLevel' method on the platform channel and handles potential PlatformException errors. The UI state is updated with the retrieved battery level or an error message. ```dart // Get battery level. String _batteryLevel = 'Unknown battery level.'; Future _getBatteryLevel() async { String batteryLevel; try { final result = await platform.invokeMethod('getBatteryLevel'); batteryLevel = 'Battery level at $result % .'; } on PlatformException catch (e) { batteryLevel = "Failed to get battery level: '${e.message}'."; } setState(() { _batteryLevel = batteryLevel; }); } ``` -------------------------------- ### Prevent Specific Key Input in Flutter TextField with Focus Source: https://docs.flutter.dev/ui/interactivity/focus This example demonstrates using the `Focus` widget's `onKeyEvent` to prevent a specific key (the letter 'a') from being processed by a child `TextField`. It returns `KeyEventResult.handled` for the 'a' key and `KeyEventResult.ignored` for others. ```dart @override Widget build(BuildContext context) { return Focus( onKeyEvent: (node, event) { return (event.logicalKey == LogicalKeyboardKey.keyA) ? KeyEventResult.handled : KeyEventResult.ignored; }, child: const TextField(), ); } ``` -------------------------------- ### Configure Initial Route with Cached FlutterEngine Source: https://docs.flutter.dev/add-to-app/android/add-flutter-screen Set up a cached FlutterEngine with a custom initial route before executing the Dart entrypoint. The initial route is configured via the navigation channel and takes effect when runApp() is first executed. Changing the route after runApp() has no effect; use a method channel for subsequent route changes. ```Kotlin class MyApplication : Application() { lateinit var flutterEngine : FlutterEngine override fun onCreate() { super.onCreate() // Instantiate a FlutterEngine. flutterEngine = FlutterEngine(this) // Configure an initial route. flutterEngine.navigationChannel.setInitialRoute("your/route/here"); // Start executing Dart code to pre-warm the FlutterEngine. flutterEngine.dartExecutor.executeDartEntrypoint( DartExecutor.DartEntrypoint.createDefault() ) // Cache the FlutterEngine to be used by FlutterActivity or FlutterFragment. FlutterEngineCache .getInstance() .put("my_engine_id", flutterEngine) } } ``` ```Java public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); // Instantiate a FlutterEngine. flutterEngine = new FlutterEngine(this); // Configure an initial route. flutterEngine.getNavigationChannel().setInitialRoute("your/route/here"); // Start executing Dart code to pre-warm the FlutterEngine. flutterEngine.getDartExecutor().executeDartEntrypoint( DartEntrypoint.createDefault() ); // Cache the FlutterEngine to be used by FlutterActivity or FlutterFragment. FlutterEngineCache .getInstance() .put("my_engine_id", flutterEngine); } } ``` -------------------------------- ### Link against system libraries in build.dart Source: https://docs.flutter.dev/platform-integration/bind-native-code This snippet demonstrates how to configure `build.dart` to link against system libraries. It uses `LookupInProcess` for Android, iOS, Linux, and macOS, and `DynamicLoadingSystem` for Windows, specifying the DLL name. ```Dart // hook/build.dart import 'package:hooks/hooks.dart'; import 'package:code_assets/code_assets.dart'; void main(List args) async { await build(args, (input, output) async { final targetOS = input.target.os; switch (targetOS) { case OS.android || OS.iOS || OS.linux || OS.macOS: output.assets.code.add( CodeAsset( package: 'host_name', name: 'src/third_party/unix.dart', linkMode: LookupInProcess(), ), ); case OS.windows: output.assets.code.add( CodeAsset( package: 'host_name', name: 'src/third_party/windows.dart', linkMode: DynamicLoadingSystem(Uri.file('ws2_32.dll')), ), ); default: throw Exception('Unsupported target os: $targetOS'); } }); } ``` -------------------------------- ### Static Field Initializer with Global Variable Source: https://docs.flutter.dev/tools/hot-reload Static fields and global variables are not reinitialized during hot reload; changes to their initializers require hot restart. This example shows a global table that won't update on hot reload. ```dart final sampleTable = [ Table( children: const [ TableRow(children: [Text('T1')]), ], ), Table( children: const [ TableRow(children: [Text('T2')]), ], ), Table( children: const [ TableRow(children: [Text('T3')]), ], ), Table( children: const [ TableRow(children: [Text('T4')]), ], ), ]; ``` ```dart final sampleTable = [ Table( children: const [ TableRow(children: [Text('T1')]), ], ), Table( children: const [ TableRow(children: [Text('T2')]), ], ), Table( children: const [ TableRow(children: [Text('T3')]), ], ), Table( children: const [ TableRow( children: [Text('T10')], // modified ), ], ), ]; ``` -------------------------------- ### Add Web Platform Support to Existing Plugin Source: https://docs.flutter.dev/packages-and-plugins/developing-packages Use this command to add web platform support to an existing Flutter plugin project. Run it from the plugin's root directory. ```bash flutter create --template=plugin --platforms=web . ``` -------------------------------- ### Migrate BuildContext, Element, StatefulElement methods to generics in Dart Source: https://docs.flutter.dev/release/breaking-changes/1-22-deprecations Update various BuildContext, Element, and StatefulElement methods to use generic type parameters for improved type safety. The codeList contains 'before' and 'after' examples for each method. ```dart inheritFromElement ``` ```dart dependOnInheritedElement ``` ```dart inheritFromWidgetOfExactType ``` ```dart dependOnInheritedWidgetOfExactType ``` ```dart ancestorInheritedElementForWidgetOfExactType ``` ```dart getElementForInheritedWidgetOfExactType ``` ```dart ancestorWidgetOfExactType ``` ```dart findAncestorWidgetOfExactType ``` ```dart ancestorStateOfType ``` ```dart findAncestorStateOfType ``` ```dart rootAncestorStateOfType ``` ```dart findRootAncestorStateOfType ``` ```dart ancestorRenderObjectOfType ``` ```dart findAncestorRenderObjectOfType ``` ```dart inheritFromElement ``` ```dart dependOnInheritedElement ``` ```dart inheritFromWidgetOfExactType ``` ```dart dependOnInheritedWidgetOfExactType ``` ```dart ancestorInheritedElementForWidgetOfExactType ``` ```dart getElementForInheritedWidgetOfExactType ``` ```dart ancestorWidgetOfExactType ``` ```dart findAncestorWidgetOfExactType ``` ```dart ancestorStateOfType ``` ```dart findAncestorStateOfType ``` ```dart rootAncestorStateOfType ``` ```dart findRootAncestorStateOfType ``` ```dart ancestorRenderObjectOfType ``` ```dart findAncestorRenderObjectOfType ``` ```dart inheritFromElement ``` ```dart dependOnInheritedElement ``` -------------------------------- ### Configure suggested prompts in LlmChatView Source: https://docs.flutter.dev/ai/ai-toolkit/feature-integration The suggestions parameter provides a list of predefined prompts shown to the user when no chat history is present. ```dart class ChatPage extends StatelessWidget { const ChatPage({super.key}); ​ @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text(App.title)), body: LlmChatView( suggestions: [ 'I\'m a Star Wars fan. What should I wear for Halloween?', 'I\'m allergic to peanuts. What candy should I avoid at Halloween?', 'What\'s the difference between a pumpkin and a squash?', ], provider: FirebaseProvider( model: FirebaseAI.geminiAI().generativeModel( model: 'gemini-2.5-flash', ), ), ), ); } ``` -------------------------------- ### Migrate BuildContext.ancestorStateOfType to generic method in Dart Source: https://docs.flutter.dev/release/breaking-changes/1-22-deprecations Update ancestorStateOfType to use generic type parameters for improved type safety and reduced boilerplate. The first code example shows the deprecated usage, and the second shows the updated usage. ```dart ComplexLayoutState state = context.ancestorStateOfType(const TypeMatcher()) as ComplexLayoutState; ``` ```dart ComplexLayoutState state = context.ancestorStateOfType(); ``` -------------------------------- ### Implement CPU-bound tasks using Flutter Isolates Source: https://docs.flutter.dev/flutter-for/xamarin-forms-devs Use `Isolate`s for computationally intensive work to avoid UI freezes. This example shows how to spawn an `Isolate` and communicate data back to the main thread using `SendPort` and `ReceivePort`. ```dart Future loadData() async { final ReceivePort receivePort = ReceivePort(); await Isolate.spawn(dataLoader, receivePort.sendPort); // The 'echo' isolate sends its SendPort as the first message final SendPort sendPort = await receivePort.first as SendPort; final List> msg = await sendReceive( sendPort, 'https://jsonplaceholder.typicode.com/posts', ); setState(() { data = msg; }); } // The entry point for the isolate static Future dataLoader(SendPort sendPort) async { // Open the ReceivePort for incoming messages. final ReceivePort port = ReceivePort(); // Notify any other isolates what port this isolate listens to. sendPort.send(port.sendPort); await for (final dynamic msg in port) { final String url = msg[0] as String; final SendPort replyTo = msg[1] as SendPort; final Uri dataURL = Uri.parse(url); final http.Response response = await http.get(dataURL); // Lots of JSON to parse replyTo.send(jsonDecode(response.body) as List>); } } Future>> sendReceive(SendPort port, String msg) { final ReceivePort response = ReceivePort(); port.send([msg, response.sendPort]); return response.first as Future>>; } ``` -------------------------------- ### Run Flutter Integration Test with Performance Profiling Source: https://docs.flutter.dev/cookbook/testing/integration/profiling Execute the Flutter integration test with the specified driver and target files, enabling profile mode for performance benchmarking. Remember to use `--no-dds` when running on mobile devices or emulators where DDS might not be accessible. ```bash flutter drive \ --driver=test_driver/perf_driver.dart \ --target=integration_test/scrolling_test.dart \ --profile ``` -------------------------------- ### Complete Flutter app with network request and progress indicator Source: https://docs.flutter.dev/flutter-for/uikit-devs Full StatefulWidget example that loads data on init, displays a CircularProgressIndicator while loading, and renders a ListView once data arrives. Demonstrates conditional rendering based on data state. ```dart import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; void main() { runApp(const SampleApp()); } class SampleApp extends StatelessWidget { const SampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(title: 'Sample App', home: SampleAppPage()); } } class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); @override State createState() => _SampleAppPageState(); } class _SampleAppPageState extends State { List> data = []; @override void initState() { super.initState(); loadData(); } bool get showLoadingDialog => data.isEmpty; Future loadData() async { final Uri dataURL = Uri.parse('https://jsonplaceholder.typicode.com/posts'); final http.Response response = await http.get(dataURL); setState(() { data = (jsonDecode(response.body) as List).cast>(); }); } Widget getBody() { if (showLoadingDialog) { return getProgressDialog(); } return getListView(); } Widget getProgressDialog() { return const Center(child: CircularProgressIndicator()); } ListView getListView() { return ListView.builder( itemCount: data.length, itemBuilder: (context, index) { return getRow(index); }, ); } Widget getRow(int i) { return Padding( padding: const EdgeInsets.all(10), child: Text("Row ${data[i]["title"]}"), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: getBody(), ); } } ``` -------------------------------- ### Run Prepare Flutter Framework Script Pre-Action Shell Command Source: https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers Shell script to execute during the Build pre-action phase in Xcode. This prepares the Flutter framework before building the app and must be configured for each flavor. ```shell "$FLUTTER_ROOT"/packages/flutter_tools/bin/macos_assemble.sh prepare ``` -------------------------------- ### Filter Android Architectures for Flutter Source: https://docs.flutter.dev/add-to-app/android/project-setup Configure `abiFilters` in your Android `build.gradle` file to limit supported architectures, preventing `libflutter.so` runtime crashes when integrating Flutter into an Android project. Examples are provided for both Kotlin DSL and Groovy DSL. ```kotlin android { //... defaultConfig { ndk { // Filter for architectures supported by Flutter abiFilters += listOf("armeabi-v7a", "arm64-v8a", "x86_64") } } } ``` ```groovy android { // ... defaultConfig { ndk { // Filter for architectures supported by Flutter abiFilters "armeabi-v7a", "arm64-v8a", "x86_64" } } } ``` -------------------------------- ### Package Management with Flutter Pub Source: https://docs.flutter.dev/reference/flutter-cli Commands for managing project dependencies, checking for outdated packages, and upgrading versions. ```bash $ flutter pub get $ flutter pub outdated $ flutter pub upgrade ``` -------------------------------- ### Calculate Animation Intervals for Staggered Items Source: https://docs.flutter.dev/cookbook/effects/staggered-menu-animation Use the Interval class to define start and end times (as percentages of total duration) for each list item and button animation. Calculate intervals in initState and store them for use in animation builders. ```dart class _MenuState extends State with SingleTickerProviderStateMixin { final List _itemSlideIntervals = []; late Interval _buttonInterval; @override void initState() { super.initState(); _createAnimationIntervals(); _staggeredController = AnimationController( vsync: this, duration: _animationDuration, ); } void _createAnimationIntervals() { for (var i = 0; i < _menuTitles.length; ++i) { final startTime = _initialDelayTime + (_staggerTime * i); final endTime = startTime + _itemSlideTime; _itemSlideIntervals.add( Interval( startTime.inMilliseconds / _animationDuration.inMilliseconds, endTime.inMilliseconds / _animationDuration.inMilliseconds, ), ); } final buttonStartTime = Duration(milliseconds: _menuTitles.length * 50) + _buttonDelayTime; final buttonEndTime = buttonStartTime + _buttonTime; _buttonInterval = Interval( buttonStartTime.inMilliseconds / _animationDuration.inMilliseconds, buttonEndTime.inMilliseconds / _animationDuration.inMilliseconds, ); } } ``` -------------------------------- ### Full Command implementation with async execution Source: https://docs.flutter.dev/app-architecture/design-patterns/command A complete Command class implementation that handles async actions, prevents duplicate execution when running is true, captures exceptions, and manages running, error, and completed states. ```dart class Command extends ChangeNotifier { Command(this._action); bool _running = false; bool get running => _running; Exception? _error; Exception? get error => _error; bool _completed = false; bool get completed => _completed; final Future Function() _action; Future execute() async { if (_running) { return; } _running = true; _completed = false; _error = null; notifyListeners(); try { await _action(); _completed = true; } on Exception catch (error) { _error = error; } finally { _running = false; notifyListeners(); } } void clear() { _running = false; _error = null; _completed = false; } } ``` -------------------------------- ### Formulas for migrating SpringDescription default constructor Source: https://docs.flutter.dev/release/breaking-changes/spring-description-underdamped Use these mathematical formulas to calculate new 'mass', 'stiffness', and 'damping' parameters for SpringDescription's default constructor to restore previous animation behavior. ```math new_m = 1 new_c = c * m new_k = (4 * (k / m) - (c / m)^2 + (c * m)^2) / 4 ``` -------------------------------- ### SubscriptionRepository with async subscribe() method Source: https://docs.flutter.dev/app-architecture/design-patterns/optimistic-state Adds an asynchronous subscribe() method that simulates a network request with a one-second delay and then throws an exception to demonstrate failure handling for optimistic state recovery. ```dart class SubscriptionRepository { /// Simulates a network request and then fails. Future subscribe() async { // Simulate a network request await Future.delayed(const Duration(seconds: 1)); // Fail after one second throw Exception('Failed to subscribe'); } } ``` -------------------------------- ### Example Project Directory Structure for Package Filtering Source: https://docs.flutter.dev/tools/devtools/legacy-inspector This directory structure illustrates how Flutter DevTools filters widgets in the Inspector Widget Tree. Widgets outside the main app package require explicit inclusion in 'Package directories' settings. ```text project_foo pkgs project_foo_app widgets_A widgets_B ``` -------------------------------- ### Create a basic ListView with ListTile Source: https://docs.flutter.dev/cookbook/lists/basic-list Use the standard ListView constructor for small lists. ListTile provides a pre-defined structure for icons and text. ```dart ListView( children: const [ ListTile(leading: Icon(Icons.map), title: Text('Map')), ListTile(leading: Icon(Icons.photo_album), title: Text('Album')), ListTile(leading: Icon(Icons.phone), title: Text('Phone')), ], ), ``` -------------------------------- ### Test Universal Link with Xcode CLI on Simulator Source: https://docs.flutter.dev/cookbook/navigation/set-up-universal-links Command to test a universal link on an iOS Simulator using Xcode's simctl tool. Replace with your actual domain. ```bash $ xcrun simctl openurl booted https:///details ``` -------------------------------- ### Implement SDFPainter with FragmentShader Source: https://docs.flutter.dev/ui/design/graphics/fragment-shaders This class demonstrates how to use `FragmentShader` to render a Signed Distance Field (SDF) effect onto a canvas, handling shader setup and image sampling. It manages shader uniforms and caches the SDF image for performance. ```dart class SDFPainter { SDFPainter(this.sdfShader, this.renderShader); FragmentShader sdfShader; FragmentShader renderShader; Image? _sdf; bool isDirty = false; double radius = 0.5; void paint(Canvas canvas, Size size) { if (_sdf == null || isDirty) { final recorder = PictureRecorder(); final subCanvas = Canvas(recorder); final paint = Paint()..shader = sdfShader; sdfShader.setFloat(0, size.width); sdfShader.setFloat(1, size.height); sdfShader.setFloat(2, radius); subCanvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint); final picture = recorder.endRecording(); _sdf = picture.toImageSync(size.width.toInt(), size.height.toInt()); isDirty = false; } renderShader.setFloat(0, size.width); renderShader.setFloat(1, size.height); renderShader.setImageSampler(0, _sdf!); canvas.drawRect( Rect.fromLTWH(0, 0, size.width, size.height), Paint()..shader = renderShader, ); } } ``` -------------------------------- ### Import font files using bash shell commands Source: https://docs.flutter.dev/cookbook/design/fonts Execute these commands to rename your project, create a fonts directory, and copy font assets into your project. ```bash $ mv /path/to/my_app /path/to/custom_fonts ``` ```bash $ cd /path/to/custom_fonts ``` ```bash $ mkdir fonts ``` ```bash $ cp ~/Downloads/*.ttf ./fonts ``` -------------------------------- ### Open Xcode workspace from command line Source: https://docs.flutter.dev/deployment/macos Run this command from the base directory of your application project to open the macOS-specific workspace. ```bash open macos/Runner.xcworkspace ``` -------------------------------- ### Old onReorder callback with manual index correction Source: https://docs.flutter.dev/release/breaking-changes/deprecate-onreorder-callback The deprecated onReorder callback requires manual adjustment of newIndex when oldIndex is before newIndex, because removing an item shortens the list by one element. This pattern was necessary to get correct reorder behavior. ```dart void handleReorder(int oldIndex, int newIndex) { if (oldIndex < newIndex) { // Removing the item at oldIndex will shorten the list by 1. newIndex -= 1; } // Handle the actual reorder behavior... } ReorderableListView( onReorder: handleReorder, ) ``` -------------------------------- ### Registering a Platform View Factory with Explicit Sizing Source: https://docs.flutter.dev/release/breaking-changes/platform-views-using-html-slots-web Set style.width and style.height on the root element to '100%' to fill allocated space and suppress warnings. ```dart ui.platformViewRegistry.registerViewFactory(viewType, (int viewId) { final html.Element htmlElement = html.DivElement() // ..other props ..style.width = '100%' ..style.height = '100%'; // ... return htmlElement; }); ``` -------------------------------- ### Configure GitHub Actions for Linux integration tests Source: https://docs.flutter.dev/testing/integration-tests Use the xvfb-run tool to provide a virtual X Window system for Flutter tests on Linux CI runners. This configuration is required for Flutter to launch and test Linux applications in headless environments. ```yaml - name: Run Integration Tests uses: username/xvfb-action@v1.1.2 with: run: flutter test integration_test -d linux -r github ``` -------------------------------- ### Flutter Progress Indicator with Network Data Loading Source: https://docs.flutter.dev/flutter-for/android-devs Complete example showing how to display a CircularProgressIndicator while loading data from a network endpoint, then render a ListView once data arrives. Uses setState() to trigger UI updates and separates build logic into helper methods. ```dart import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; void main() { runApp(const SampleApp()); } class SampleApp extends StatelessWidget { const SampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Sample App', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: const SampleAppPage(), ); } } class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); @override State createState() => _SampleAppPageState(); } class _SampleAppPageState extends State { List> widgets = []; @override void initState() { super.initState(); loadData(); } Widget getBody() { bool showLoadingDialog = widgets.isEmpty; if (showLoadingDialog) { return getProgressDialog(); } else { return getListView(); } } Widget getProgressDialog() { return const Center(child: CircularProgressIndicator()); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: getBody(), ); } ListView getListView() { return ListView.builder( itemCount: widgets.length, itemBuilder: (context, position) { return getRow(position); }, ); } Widget getRow(int i) { return Padding( padding: const EdgeInsets.all(10), child: Text("Row ${widgets[i]["title"]}"), ); } Future loadData() async { final dataURL = Uri.parse('https://jsonplaceholder.typicode.com/posts'); final response = await http.get(dataURL); setState(() { widgets = (jsonDecode(response.body) as List) .cast>(); }); } } ``` -------------------------------- ### Run Flutter Integration Tests on Android and iOS Devices Source: https://docs.flutter.dev/testing/integration-tests Use this command from the project root to execute integration tests on a connected Android or iOS device. ```bash $ flutter test integration_test/app_test.dart ``` -------------------------------- ### Flutter Isolate-based Data Loading and UI Update Source: https://docs.flutter.dev/flutter-for/android-devs This comprehensive example demonstrates how to fetch data from a network API using Dart isolates to prevent UI freezes. It includes methods for building a UI, initiating data loading, and handling isolate communication. ```Dart return const Center(child: CircularProgressIndicator()); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: getBody(), ); } ListView getListView() { return ListView.builder( itemCount: widgets.length, itemBuilder: (context, position) { return getRow(position); }, ); } Widget getRow(int i) { return Padding( padding: const EdgeInsets.all(10), child: Text("Row ${widgets[i]["title"]}"), ); } Future loadData() async { ReceivePort receivePort = ReceivePort(); await Isolate.spawn(dataLoader, receivePort.sendPort); // The 'echo' isolate sends its SendPort as the first message. SendPort sendPort = await receivePort.first as SendPort; final msg = await sendReceive( sendPort, 'https://jsonplaceholder.typicode.com/posts', ) as List; final posts = msg.cast>(); setState(() { widgets = posts; }); } // The entry point for the isolate. static Future dataLoader(SendPort sendPort) async { // Open the ReceivePort for incoming messages. ReceivePort port = ReceivePort(); // Notify any other isolates what port this isolate listens to. sendPort.send(port.sendPort); await for (var msg in port) { String dataUrl = msg[0] as String; SendPort replyTo = msg[1] as SendPort; http.Response response = await http.get(Uri.parse(dataUrl)); // Lots of JSON to parse replyTo.send(jsonDecode(response.body)); } } Future sendReceive(SendPort port, Object? msg) { ReceivePort response = ReceivePort(); port.send([msg, response.sendPort]); return response.first; } } ``` -------------------------------- ### Project Directory Structure for Widget Inspector Source: https://docs.flutter.dev/tools/devtools/inspector Use this directory structure to understand how adding parent paths to Package Directories affects widget visibility. Changes to these directories persist across inspector sessions for the app. ```text project_foo pkgs project_foo_app widgets_A widgets_B ``` -------------------------------- ### Generate Self-Signed .pfx Certificate for MSIX (OpenSSL) Source: https://docs.flutter.dev/platform-integration/windows/building Use these OpenSSL commands in sequence to generate a self-signed .pfx certificate, which is necessary for local testing and private deployment of MSIX packages. Ensure OpenSSL is installed and its `bin` directory is in your system's PATH. ```Shell openssl genrsa -out mykeyname.key 2048 ``` ```Shell openssl req -new -key mykeyname.key -out mycsrname.csr ``` ```Shell openssl x509 -in mycsrname.csr -out mycrtname.crt -req -signkey mykeyname.key -days 10000 ``` ```Shell openssl pkcs12 -export -out CERTIFICATE.pfx -inkey mykeyname.key -in mycrtname.crt ``` -------------------------------- ### HomeViewModel with User data Source: https://docs.flutter.dev/app-architecture/design-patterns/command Shows how a HomeViewModel exposes a User instance as part of its UI state. ```dart class HomeViewModel extends ChangeNotifier { User? get user => // ... // ··· } ``` -------------------------------- ### Set AlertDialog shape to original 2 pixel border radius Source: https://docs.flutter.dev/release/breaking-changes/dialog-border-radius Use the shape property with RoundedRectangleBorder to maintain the original 2.0 pixel border radius for AlertDialog. This example shows a complete Flutter app with a FloatingActionButton that displays an AlertDialog with the legacy border radius. ```dart import 'package:flutter/material.dart'; void main() => runApp(Foo()); class Foo extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton(onPressed: () { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( content: Text('Alert!'), shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(2))), ); }, ); }), ), ); } } ``` -------------------------------- ### Define Dog model with toMap() and toString() methods Source: https://docs.flutter.dev/cookbook/persistence/sqlite Create a Dog class with id, name, and age fields. The toMap() method converts the Dog instance to a Map for database storage, and toString() provides readable output for debugging. ```dart class Dog { final int id; final String name; final int age; Dog({required this.id, required this.name, required this.age}); // Convert a Dog into a Map. The keys must correspond to the names of the // columns in the database. Map toMap() { return {'id': id, 'name': name, 'age': age}; } // Implement toString to make it easier to see information about // each dog when using the print statement. @override String toString() { return 'Dog{id: $id, name: $name, age: $age}'; } } ``` -------------------------------- ### Import GoogleSignIn for authentication Source: https://docs.flutter.dev/data-and-backend/google-apis Import the GoogleSignIn class from the google_sign_in package to authenticate users with their Google identity. ```dart /// Provides the `GoogleSignIn` class. import 'package:google_sign_in/google_sign_in.dart'; ``` -------------------------------- ### Example Flutter Timeline Summary JSON Output Source: https://docs.flutter.dev/cookbook/testing/integration/profiling This JSON object illustrates the structure and content of a `TimelineSummary` file. It provides key performance metrics such as average and worst frame build/rasterizer times, missed frame budget counts, and raw frame timing data. ```json { "average_frame_build_time_millis": 4.2592592592592595, "worst_frame_build_time_millis": 21.0, "missed_frame_build_budget_count": 2, "average_frame_rasterizer_time_millis": 5.518518518518518, "worst_frame_rasterizer_time_millis": 51.0, "missed_frame_rasterizer_budget_count": 10, "frame_count": 54, "frame_build_times": [ 6874, 5019, 3638 ], "frame_rasterizer_times": [ 51955, 8468, 3129 ] } ``` -------------------------------- ### Run Integration Tests Locally Source: https://docs.flutter.dev/release/breaking-changes/plugin-api-migration Execute the integration tests from the command line using the `flutter test` command, specifying the test file path. ```bash flutter test integration_test/app_test.dart ``` -------------------------------- ### Calling Agentic Loop with Function Call Handler in Dart Source: https://docs.flutter.dev/ai/best-practices/tool-calls Usage example showing how to invoke the agentic loop extension method with a prompt and a callback that routes function calls to appropriate handlers. The callback uses a switch expression to dispatch the 'getWordMetadata' function call. ```dart await _clueSolverModel.generateContentWithFunctions( prompt: getSolverPrompt(clue, length, pattern), onFunctionCall: (functionCall) async => switch (functionCall.name) { 'getWordMetadata' => await _getWordMetadataFromApi( functionCall.args['word'] as String, ), _ => throw Exception('Unknown function call: ${functionCall.name}'), }, ); ``` -------------------------------- ### Run build_runner to generate mocks Source: https://docs.flutter.dev/cookbook/testing/unit/mocking Execute the build_runner command to generate the MockHttpClient class from the annotations. The generated code will be in fetch_album_test.mocks.dart. ```bash $ dart run build_runner build ``` -------------------------------- ### flutter pub Source: https://docs.flutter.dev/reference/flutter-cli Works with packages. Use instead of `dart pub`. ```APIDOC ## COMMAND flutter pub ### Description Works with packages. Use instead of `dart pub`. ### Usage `flutter pub ` ### Arguments - **** (string) - Required - A `pub` subcommand (e.g., `get`, `outdated`, `upgrade`). ### Request Example N/A ### Response #### Success Response (0) - **Output** (string) - Output from the specified `pub` command. #### Response Example N/A ``` -------------------------------- ### Build Flutter Module as Android Archive (AAR) Source: https://docs.flutter.dev/add-to-app/android/project-setup Run flutter build aar in the Flutter module directory to generate Android Archives (AARs) and POMs artifacts in a local Maven repository. This allows host app builds without requiring the Flutter SDK installed. ```bash cd some/path/flutter_module flutter build aar ``` -------------------------------- ### Implement MethodCallHandler logic for Windows Source: https://docs.flutter.dev/platform-integration/platform-channels Replaces the placeholder handler with logic to check for the 'getBatteryLevel' method and return the native battery status. ```cpp channel.SetMethodCallHandler( [](const flutter::MethodCall<>& call, std::unique_ptr> result) { // TODO }); ``` ```cpp channel.SetMethodCallHandler( [](const flutter::MethodCall<>& call, std::unique_ptr> result) { if (call.method_name() == "getBatteryLevel") { int battery_level = GetBatteryLevel(); if (battery_level != -1) { result->Success(battery_level); } else { result->Error("UNAVAILABLE", "Battery level not available."); } } else { result->NotImplemented(); } }); ``` -------------------------------- ### Complete Flutter App for Updating Data Source: https://docs.flutter.dev/cookbook/networking/update-data This comprehensive example shows a Flutter application that fetches an album, allows the user to update its title via a text field, and sends the updated data using an HTTP PUT request. It includes the `Album` model, API calls, and UI components. ```dart import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; Future fetchAlbum() async { final response = await http.get( Uri.parse('https://jsonplaceholder.typicode.com/albums/1'), ); if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. return Album.fromJson(jsonDecode(response.body) as Map); } else { // If the server did not return a 200 OK response, // then throw an exception. throw Exception('Failed to load album'); } } Future updateAlbum(String title) async { final response = await http.put( Uri.parse('https://jsonplaceholder.typicode.com/albums/1'), headers: { 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode({'title': title}), ); if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. return Album.fromJson(jsonDecode(response.body) as Map); } else { // If the server did not return a 200 OK response, // then throw an exception. throw Exception('Failed to update album.'); } } class Album { final int id; final String title; const Album({required this.id, required this.title}); factory Album.fromJson(Map json) { return switch (json) { {'id': int id, 'title': String title} => Album(id: id, title: title), _ => throw const FormatException('Failed to load album.'), }; } } void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() { return _MyAppState(); } } class _MyAppState extends State { final TextEditingController _controller = TextEditingController(); late Future _futureAlbum; @override void initState() { super.initState(); _futureAlbum = fetchAlbum(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Update Data Example', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: Scaffold( appBar: AppBar(title: const Text('Update Data Example')), body: Container( alignment: Alignment.center, padding: const EdgeInsets.all(8), child: FutureBuilder( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasData) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(snapshot.data!.title), TextField( controller: _controller, decoration: const InputDecoration( hintText: 'Enter Title', ), ), ElevatedButton( onPressed: () { setState(() { _futureAlbum = updateAlbum(_controller.text); }); }, child: const Text('Update Data'), ), ], ); } else if (snapshot.hasError) { return Text('${snapshot.error}'); } } return const CircularProgressIndicator(); }, ), ), ), ); } } ``` -------------------------------- ### Configure Path and Git Dependencies Source: https://docs.flutter.dev/packages-and-plugins/using-packages Use these formats in pubspec.yaml for packages not hosted on pub.dev. Relative paths are resolved from the directory containing the pubspec file. ```yaml dependencies: packageA: path: ../packageA/ ``` ```yaml dependencies: packageA: git: url: https://github.com/flutter/packageA.git ``` ```yaml dependencies: packageA: git: url: git@github.com:flutter/packageA.git ``` ```yaml dependencies: packageA: git: url: https://github.com/flutter/packages.git path: packages/packageA ``` -------------------------------- ### Shortcuts and Actions with SelectAllIntent Source: https://docs.flutter.dev/ui/interactivity/actions-and-shortcuts Map keyboard shortcuts to intents using Shortcuts widget, then bind intents to actions using Actions widget. Demonstrates Ctrl+A binding to SelectAllIntent with a custom SelectAllAction. ```dart @override Widget build(BuildContext context) { return Shortcuts( shortcuts: { LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.keyA): const SelectAllIntent(), }, child: Actions( dispatcher: LoggingActionDispatcher(), actions: >{ SelectAllIntent: SelectAllAction(model), }, child: Builder( builder: (context) => TextButton( onPressed: Actions.handler( context, const SelectAllIntent(), ), child: const Text('SELECT ALL'), ), ), ), ); } ``` -------------------------------- ### Gradle Plugin Block Before Kotlin Migration (Groovy DSL) Source: https://docs.flutter.dev/release/breaking-changes/migrate-to-built-in-kotlin/for-plugin-authors This snippet shows the legacy `apply` plugin syntax and `kotlinOptions` configuration in a Groovy `build.gradle` file before migrating to built-in Kotlin. ```groovy apply plugin: 'com.android.library' apply plugin: 'kotlin-android' // ... android { // ... kotlinOptions { jvmTarget = JavaVersion.VERSION_17.toString() } // ... } // ... ``` -------------------------------- ### Create and insert a Dog instance Source: https://docs.flutter.dev/cookbook/persistence/sqlite Instantiate a Dog object and call insertDog() to add it to the database. ```dart // Create a Dog and add it to the dogs table var fido = Dog(id: 0, name: 'Fido', age: 35); await insertDog(fido); ``` -------------------------------- ### Import necessary packages for Flutter MethodChannel Source: https://docs.flutter.dev/platform-integration/platform-channels Imports 'dart:async' for asynchronous operations, 'package:flutter/material.dart' for UI components, and 'package:flutter/services.dart' for platform services like MethodChannel. ```dart import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; ``` -------------------------------- ### Imperative Style UI Mutation in Java Source: https://docs.flutter.dev/flutter-for/declarative Shows the imperative approach where you retrieve a UI instance and mutate it directly using methods like setColor() and add(). This pattern requires replicating configuration in the constructor since the UI instance may not persist. ```java // Imperative style b.setColor(red) b.clearChildren() ViewC c3 = new ViewC(...) b.add(c3) ``` -------------------------------- ### Enable Network Access for macOS Source: https://docs.flutter.dev/ai/ai-toolkit Add the network client entitlement to your macOS `*.entitlements` file to allow network access for your application. ```xml ... com.apple.security.network.client ``` -------------------------------- ### Configure CFUG Mirror on Windows Source: https://docs.flutter.dev/community/china Set environment variables to use the China Flutter User Group mirror for Flutter SDK and pub packages on Windows. ```powershell $env:PUB_HOSTED_URL="https://pub.flutter-io.cn" $env:FLUTTER_STORAGE_BASE_URL="https://storage.flutter-io.cn" ``` -------------------------------- ### Pre-warming and Caching FlutterEngine for Faster Startup Source: https://docs.flutter.dev/add-to-app/android/add-flutter-fragment Initialize a FlutterEngine in advance, typically in the Application class, and cache it to avoid the warm-up delay when a FlutterFragment is first displayed. This reduces blank screen time for users. ```kotlin // Somewhere in your app, before your FlutterFragment is needed, // like in the Application class ... // Instantiate a FlutterEngine. val flutterEngine = FlutterEngine(context) // Start executing Dart code in the FlutterEngine. flutterEngine.getDartExecutor().executeDartEntrypoint( DartEntrypoint.createDefault() ) // Cache the pre-warmed FlutterEngine to be used later by FlutterFragment. FlutterEngineCache .getInstance() .put("my_engine_id", flutterEngine) ``` ```java // Somewhere in your app, before your FlutterFragment is needed, // like in the Application class ... // Instantiate a FlutterEngine. FlutterEngine flutterEngine = new FlutterEngine(context); // Start executing Dart code in the FlutterEngine. flutterEngine.getDartExecutor().executeDartEntrypoint( DartEntrypoint.createDefault() ); // Cache the pre-warmed FlutterEngine to be used later by FlutterFragment. FlutterEngineCache .getInstance() .put("my_engine_id", flutterEngine); ``` -------------------------------- ### DatabaseService open method for SQLite database initialization Source: https://docs.flutter.dev/app-architecture/design-patterns/sql Opens an existing SQLite database or creates a new one if it doesn't exist. Uses sqflite's databaseFactory and defines the table schema in the onCreate callback. The id column is set as primary key with autoincrement. ```dart Future open() async { _database = await databaseFactory.openDatabase( join(await databaseFactory.getDatabasesPath(), 'app_database.db'), options: OpenDatabaseOptions( onCreate: (db, version) { return db.execute( 'CREATE TABLE $_todoTableName($_idColumnName INTEGER PRIMARY KEY AUTOINCREMENT, $_taskColumnName TEXT)', ); }, version: 1, ), ); } ```