### Start the iOS Simulator Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/platform-integration/ios/setup.md Use this command to launch the iOS Simulator on your Mac. Ensure Xcode is installed. ```bash $ open -a Simulator ``` -------------------------------- ### Run and Test Flutter Example Apps Source: https://github.com/flutter/website/blob/main/examples/README.md Use these commands from the repository root to create, navigate into, analyze, test, and run a specific Flutter example project. Replace "$PROJECT" with the path to your desired example. ```bash flutter create --no-overwrite $PROJECT ``` ```bash cd $PROJECT ``` ```bash dart analyze ``` ```bash flutter test ``` ```bash flutter run ``` -------------------------------- ### Run a Cupertino API example from the Flutter repository Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/ui/design/cupertino/index.md This command-line snippet demonstrates how to navigate to the Flutter API examples directory and run a specific Cupertino widget example, such as `CupertinoSwitch`, from the repository. ```console cd path/to/flutter cd examples/api flutter run lib/cupertino/switch/cupertino_switch.0.dart ``` -------------------------------- ### Install snap package locally Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/deployment/linux.md Install a locally built snap file with the --dangerous flag to bypass store verification during testing. ```console $ sudo snap install ./super-cool-app_0.1.0_amd64.snap --dangerous ``` -------------------------------- ### Example: Add Flutter SDK from Home Directory to Zsh PATH Source: https://github.com/flutter/website/blob/main/sites/docs/src/_includes/docs/install/path/macos.md An example of adding the Flutter SDK to the PATH, assuming it's located in '$HOME/develop/flutter'. ```bash export PATH="$HOME/develop/flutter/bin:$PATH" ``` -------------------------------- ### Install Snapcraft CLI Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/deployment/linux.md Use this command to install the Snapcraft command-line tool on your system. ```console $ sudo snap install snapcraft --classic ``` -------------------------------- ### Example Output of Recently Modified Flutter Project Files Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/testing/native-debugging.md This output demonstrates the files and directories generated or updated in a Flutter project after installing a plugin like `url_launcher`, showing platform-specific configuration and code files. ```ps 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 ---- ------------- ------ ---- 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 ``` -------------------------------- ### Install Git on macOS using Xcode Command Line Tools Source: https://github.com/flutter/website/blob/main/sites/docs/src/_includes/docs/install/quick.md Execute `xcode-select --install` to prompt the installation of Xcode Command Line Tools, which includes Git, on macOS. This is important for iOS/macOS development. ```console $ xcode-select --install ``` -------------------------------- ### Install a Flutter app on a device with `flutter install` Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/reference/flutter-cli.md This command installs a Flutter application onto an attached device. ```bash flutter install -d ``` -------------------------------- ### Example Flutter Snapcraft YAML Configuration Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/deployment/linux.md This is a complete example of a `snapcraft.yaml` file for a Flutter project, defining application metadata, confinement, and build parts. ```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 ``` -------------------------------- ### Navigate to the Project Directory Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/reference/create-new-app.md After creating the app, use the `cd` command to navigate into the newly created project directory. ```bash $ cd my_app ``` -------------------------------- ### Example Crane Command for Digest Source: https://github.com/flutter/website/blob/main/cloud_build/firebase-ghcli/README.md An example command to get the digest for the Dart SDK version 3.12.1. ```bash crane digest docker.io/library/dart:3.12.1 ``` -------------------------------- ### Install Bundler Gem on CI Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/deployment/cd.md Command to install the Bundler gem, typically run during the setup phase of a CI task to manage dependencies. ```bash gem install bundler ``` -------------------------------- ### Remove Flutter SDK directory on Windows Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/install/uninstall.md Delete the Flutter installation directory on Windows using PowerShell. Replace the example path with your actual Flutter installation location. ```powershell $ Remove-Item -Recurse -Force -Path (Join-Path $env:USERPROFILE "develop\flutter") ``` -------------------------------- ### Example: Building an APK for a Staging Flavor Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/deployment/flavors.md This command demonstrates how to build an APK for the 'staging' product flavor using the Flutter CLI. ```console $ flutter build apk --flavor staging ``` -------------------------------- ### Full GenUI A2UI Flutter Application Example Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/ai/genui/get-started.md This complete example demonstrates the integration of GenUI with A2UI in a Flutter app, including UI setup, conversation flow, and agent communication. ```dart import 'package:flutter/material.dart'; import 'package:genui/genui.dart'; import 'package:genui_a2a/genui_a2a.dart'; import 'package:logging/logging.dart'; void main() { // Setup logging. Logger.root.level = Level.ALL; Logger.root.onRecord.listen((record) { print('${record.level.name}: ${record.time}: ${record.message}'); if (record.error != null) { print(record.error); } if (record.stackTrace != null) { print(record.stackTrace); } }); runApp(const GenUIExampleApp()); } 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(), ); } } class ChatScreen extends StatefulWidget { const ChatScreen({super.key}); @override State createState() => _ChatScreenState(); } class _ChatScreenState extends State { final TextEditingController _textController = TextEditingController(); final SurfaceController _surfaceController = SurfaceController(catalogs: [BasicCatalogItems.asCatalog()]); late final A2uiTransportAdapter _transportAdapter; late final Conversation _uiAgent; late final A2uiAgentConnector _connector; final List _messages = []; @override void initState() { super.initState(); // The Conversation wires transport -> controller internally. _transportAdapter = A2uiTransportAdapter(onSend: (message) async { // Implement sending to LLM if needed, or handled by connector }); _connector = A2uiAgentConnector( // TODO: Replace with your A2A server URL. url: Uri.parse('http://localhost:8080'), ); _uiAgent = Conversation( controller: _surfaceController, transport: _transportAdapter, ); // Listen for messages from the remote agent. _connector.stream.listen(_surfaceController.handleMessage); } @override void dispose() { _textController.dispose(); _uiAgent.dispose(); _transportAdapter.dispose(); _surfaceController.dispose(); _connector.dispose(); super.dispose(); } void _handleSubmitted(String text) async { if (text.isEmpty) return; _textController.clear(); final message = ChatMessage.user(text); setState(() { _messages.insert(0, message); }); final responseText = await _connector.connectAndSend(message); // Handling response depends on your app's logic } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('A2UI Example'), ), body: Column( children: [ Expanded( child: ListView.builder( padding: const EdgeInsets.all(8.0), reverse: true, itemBuilder: (_, int index) => _buildMessage(_messages[index]), itemCount: _messages.length, ), ), const Divider(height: 1.0), Container( decoration: BoxDecoration(color: Theme.of(context).cardColor), child: _buildTextComposer(), ), // Surface for the main AI-generated UI: SizedBox( height: 300, child: Surface( surfaceContext: _surfaceController.contextFor('main_surface'), ), ), ], ), ); } } ``` -------------------------------- ### Example Desktop Entry File for Flutter Snap Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/deployment/linux.md This `.desktop` file example defines metadata for the application's desktop entry, including its name, command to execute, and icon path. It should be placed in `/snap/gui/`. ```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. ``` -------------------------------- ### Remove Flutter SDK directory on macOS, Linux, and ChromeOS Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/install/uninstall.md Delete the Flutter installation directory on Unix-like systems using shell. Replace the example path with your actual Flutter installation location. ```console $ rm -rf ~/develop/flutter ``` -------------------------------- ### Create a starter Flutter package Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/packages-and-plugins/developing-packages.md Use the `--template=package` flag with `flutter create` to generate a basic package project structure. ```console $ flutter create --template=package hello ``` -------------------------------- ### Open Xcode workspace for example app Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/packages-and-plugins/swift-package-manager/for-plugin-authors.md Opens the example app's Xcode workspace to add the plugin as a local package. Replace 'ios' with 'macos' if working with macOS plugins. ```bash open example/ios/Runner.xcworkspace ``` -------------------------------- ### Complete Camera Integration Example Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/cookbook/plugins/picture-using-camera.md This comprehensive example demonstrates how to initialize the camera, capture an image, and display it within a Flutter application using the `camera` plugin. It includes setup, UI for preview and capture, and image display. ```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)), ); } } ``` -------------------------------- ### Flutter nested navigation hands-on example in DartPad Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/cookbook/effects/nested-nav.md This comprehensive example demonstrates a complete nested navigation flow for a device setup process in Flutter, including route generation, state management, and custom navigation logic. ```dart import 'package:flutter/material.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'; void main() { runApp( MaterialApp( theme: ThemeData( brightness: Brightness.dark, appBarTheme: const AppBarTheme(backgroundColor: Colors.blue), floatingActionButtonTheme: const FloatingActionButtonThemeData( backgroundColor: Colors.blue, ), ), 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, ); }, debugShowCheckedModeBanner: false, ), ); } @immutable class SetupFlow extends StatefulWidget { static SetupFlowState of(BuildContext context) { return context.findAncestorStateOfType()!; } const SetupFlow({super.key, required this.setupPageRoute}); final String setupPageRoute; @override SetupFlowState createState() => SetupFlowState(); } class SetupFlowState extends State { final _navigatorKey = GlobalKey(); @override void initState() { super.initState(); } void _onDiscoveryComplete() { _navigatorKey.currentState!.pushNamed(routeDeviceSetupSelectDevicePage); } void _onDeviceSelected(String deviceId) { _navigatorKey.currentState!.pushNamed(routeDeviceSetupConnectingPage); } void _onConnectionEstablished() { _navigatorKey.currentState!.pushNamed(routeDeviceSetupFinishedPage); } Future _onExitPressed() async { final isConfirmed = await _isExitDesired(); if (isConfirmed && mounted) { _exitSetup(); } } Future _isExitDesired() async { return await showDialog( context: context, builder: (context) { return AlertDialog( title: const Text('Are you sure?'), content: const Text( 'If you exit device setup, your progress will be lost.', ), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(true); }, child: const Text('Leave'), ), TextButton( onPressed: () { Navigator.of(context).pop(false); }, child: const Text('Stay'), ), ], ); }, ) ?? false; } void _exitSetup() { Navigator.of(context).pop(); } @override Widget build(BuildContext context) { return PopScope( canPop: false, onPopInvokedWithResult: (didPop, _) async { if (didPop) return; if (await _isExitDesired() && context.mounted) { _exitSetup(); } }, child: Scaffold( appBar: _buildFlowAppBar(), body: Navigator( key: _navigatorKey, initialRoute: widget.setupPageRoute, onGenerateRoute: _onGenerateRoute, ), ), ); } Route _onGenerateRoute(RouteSettings settings) { final page = switch (settings.name) { routeDeviceSetupStartPage => WaitingPage( message: 'Searching for nearby bulb...', onWaitComplete: _onDiscoveryComplete, ), routeDeviceSetupSelectDevicePage => SelectDevicePage( onDeviceSelected: _onDeviceSelected, ), routeDeviceSetupConnectingPage => WaitingPage( message: 'Connecting...', onWaitComplete: _onConnectionEstablished, ), routeDeviceSetupFinishedPage => FinishedPage(onFinishPressed: _exitSetup), ``` -------------------------------- ### Configure LXD with Default Settings Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/deployment/linux.md Run this command to initialize and configure LXD. The default answers are suitable for most use cases. ```console $ 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]: ``` -------------------------------- ### Exit code 69 pub get failure output Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/install/troubleshoot.md Example error output showing exit code 69 when pub get fails due to networking issues, including TLS errors and environment variables. ```plaintext 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 ``` -------------------------------- ### Xcode Cloud Post-Clone Script for Flutter iOS Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/deployment/cd.md This script runs after Xcode Cloud clones the Git repository. It sets up Flutter, installs iOS artifacts, gets Flutter dependencies, and installs CocoaPods dependencies for an iOS project. ```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 # Install CocoaPods dependencies. cd ios && pod install # run `pod install` in the `ios` directory. exit 0 ``` -------------------------------- ### Configure Set Instructions Source: https://github.com/flutter/website/blob/main/packages/excerpter/README.md Examples of using set instructions to modify the base path for source files, update the plaster template, or define global replacement rules. ```markdown ``` -------------------------------- ### Add Flutter SDK to PATH on ChromeOS Source: https://github.com/flutter/website/blob/main/sites/docs/src/_includes/docs/install/path/chromeos.md Add the Flutter SDK's 'bin' directory to your system's PATH. Replace '' with the absolute path to your Flutter SDK installation. The second example demonstrates a common installation location. ```console $ echo 'export PATH=":$PATH"' >> ~/.bash_profile ``` ```console $ echo 'export PATH="$HOME/develop/flutter/bin:$PATH"' >> ~/.bash_profile ``` -------------------------------- ### Console output after adding dependencies Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/testing/integration-tests/index.md Example console output after running the `flutter pub add` command to install testing dependencies. ```console Building flutter tool... Resolving dependencies... Got dependencies. Resolving dependencies... + file 7.0.0 + flutter_driver 0.0.0 from sdk flutter + fuchsia_remote_debug_protocol 0.0.0 from sdk flutter + integration_test 0.0.0 from sdk flutter ... test_api 0.6.1 (0.7.1 available) vm_service 13.0.0 (14.2.1 available) + webdriver 3.0.3 Changed 8 dependencies! 7 packages have newer versions incompatible with dependency constraints. Try `flutter pub outdated` for more information. ``` -------------------------------- ### List, launch, and create emulators with `flutter emulators` Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/reference/flutter-cli.md This command provides functionality to manage emulators, including listing, launching, and creating new ones. ```bash flutter emulators ``` -------------------------------- ### Android cmdline-tools missing error output Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/install/troubleshoot.md Example flutter doctor output indicating the cmdline-tools component is missing from the Android SDK installation. ```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 ``` -------------------------------- ### Initial DraggableCard Widget Setup (Dart) Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/cookbook/animation/physics-simulation.md Sets up the basic `DraggableCard` stateful widget and its parent `PhysicsCardDragDemo` for a physics simulation. This is the starting point for the animation. ```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)); } } ``` -------------------------------- ### Create, analyze, test, and run a Flutter app Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/reference/flutter-cli.md Demonstrates the basic workflow for developing a Flutter application using the `flutter` CLI, from project creation to running the app. ```console $ flutter create my_app $ cd my_app $ flutter analyze $ flutter test $ flutter run lib/main.dart ``` -------------------------------- ### Initialize Firebase Hosting for Project Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/deployment/web.md Run this command in your project directory to initialize Firebase Hosting, configuring it for your web application. ```console firebase init hosting ``` -------------------------------- ### Complete sqflite Example for Dog Database Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/cookbook/persistence/sqlite.md This comprehensive snippet demonstrates how to initialize an SQLite database, define a data model (`Dog`), and perform insert, query, update, and delete operations using the `sqflite` package in Flutter. It includes database setup, schema creation, and example usage. ```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}'; } } ``` -------------------------------- ### Add LayoutBuilder with SingleChildScrollView Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/cookbook/lists/spaced-items.md Initial setup for a scrollable list. This snippet demonstrates how to use `LayoutBuilder` to get parent constraints and wrap its child in a `SingleChildScrollView` to enable scrolling. ```dart LayoutBuilder( builder: (context, constraints) { return SingleChildScrollView(child: Placeholder()); }, ); ``` -------------------------------- ### Example: Extract Flutter SDK 3.29.3 on Linux Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/install/manual.md A concrete tar example for extracting Flutter SDK version 3.29.3 on Linux, assuming the archive is in ~/Downloads and the destination is ~/develop/. ```console $ tar -xf ~/Downloads/flutter_linux_3.29.3-stable.tar.xz -C ~/develop/ ``` -------------------------------- ### Build static menu widget in Flutter Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/cookbook/effects/staggered-menu-animation.md Create a stateful Menu widget that displays a list of menu titles and a Get Started button in a drawer. This is the foundation 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), ), ), ), ); } } ``` -------------------------------- ### Build Snap using Multipass Backend Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/deployment/linux.md Run this command from the project's root directory to build the snap using the default Multipass VM backend. Ensure `snapcraft.yaml` is complete before execution. ```console $ snapcraft ``` -------------------------------- ### Example: Extract Flutter SDK 3.29.3 on Windows Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/install/manual.md A concrete PowerShell example for extracting Flutter SDK version 3.29.3 on Windows, assuming the ZIP is in Downloads and the destination is develop. ```console $ Expand-Archive `n -Path $env:USERPROFILE\Downloads\flutter_windows_3.29.3-stable.zip `n -Destination $env:USERPROFILE\develop\ ``` -------------------------------- ### Build Get Started Button with Scale and Fade Animation Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/cookbook/effects/staggered-menu-animation.md Creates an animated button that scales up and fades in using an elasticOut curve with interval-based timing. The button uses a Stadium border and blue background. ```dart Widget _buildGetStartedButton() { return SizedBox( width: double.infinity, child: Padding( padding: const EdgeInsets.all(24), child: AnimatedBuilder( animation: _staggeredController, builder: (context, child) { final animationPercent = Curves.elasticOut.transform( _buttonInterval.transform(_staggeredController.value), ); final opacity = animationPercent.clamp(0.0, 1.0); final scale = (animationPercent * 0.5) + 0.5; return Opacity( opacity: opacity, child: Transform.scale(scale: scale, child: child), ); }, 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), ), ), ), ), ); } ``` -------------------------------- ### Create a new Flutter project Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/deployment/flavors-ios.md Use the Flutter CLI to create a new project. This is the starting point for setting up flavors. ```bash $ flutter create flavors_example ``` -------------------------------- ### Create FFI Package Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/packages-and-plugins/developing-packages.md Create a starter FFI package using the flutter create command with the --template=package_ffi flag. ```console $ flutter create --template=package_ffi hello ``` -------------------------------- ### Validate Flutter web setup with flutter devices Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/platform-integration/web/setup.md Run this command to verify that Flutter can find your installed web browser. You should see at least one connected device labeled Chrome (web) or Edge (web). ```console $ flutter devices Found 1 connected devices: Chrome (web) • chrome • web-javascript • Google Chrome ``` -------------------------------- ### Complete Flutter app with ListView.builder for long lists (Dart) Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/cookbook/lists/long-lists.md A complete Flutter application demonstrating how to create and display a long list of items using ListView.builder. This example includes the main function, a StatelessWidget, and the Scaffold setup. ```dart import 'package:flutter/material.dart'; void main() { runApp( MyApp( items: List.generate(10000, (i) => 'Item $i'), ), ); } class MyApp extends StatelessWidget { final List items; const MyApp({super.key, required this.items}); @override Widget build(BuildContext context) { const title = 'Long List'; return MaterialApp( title: title, home: Scaffold( appBar: AppBar(title: const Text(title)), body: ListView.builder( itemCount: items.length, prototypeItem: ListTile(title: Text(items.first)), itemBuilder: (context, index) { return ListTile(title: Text(items[index])); }, ), ), ); } } ``` -------------------------------- ### Clone Flutter main channel and verify installation Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/install/archive.md Clone the Flutter repository from the main branch and verify the SDK version. Run these commands in your terminal to set up Flutter from source. ```console $ git clone -b main https://github.com/flutter/flutter.git $ ./flutter/bin/flutter --version ``` -------------------------------- ### Flutter create output and next steps Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/testing/native-debugging.md Output from flutter create showing project initialization completion and instructions to run the application. ```console 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. ``` -------------------------------- ### Flutter Named Routes with MaterialApp and Navigator Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/cookbook/navigation/named-routes.md Complete example showing how to define named routes in MaterialApp and navigate between screens using route names. Uses initialRoute to set the starting screen and routes map to define available routes. ```dart import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( title: 'Named Routes Demo', // Start the app with the "/" named route. In this case, the app starts // on the FirstScreen widget. initialRoute: '/', routes: { // When navigating to the "/" route, build the FirstScreen widget. '/': (context) => const FirstScreen(), // When navigating to the "/second" route, build the SecondScreen widget. '/second': (context) => const SecondScreen(), }, ), ); } 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( // Within the `FirstScreen` widget onPressed: () { // Navigate to the second screen using a named route. Navigator.pushNamed(context, '/second'); }, child: const Text('Launch screen'), ), ), ); } } class SecondScreen extends StatelessWidget { const SecondScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Second Screen')), body: Center( child: ElevatedButton( // Within the SecondScreen widget onPressed: () { // Navigate back to the first screen by popping the current route // off the stack. Navigator.pop(context); }, child: const Text('Go back!'), ), ), ); } } ``` -------------------------------- ### Complete Drag and Drop Example in Flutter Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/cookbook/effects/drag-a-widget.md This comprehensive Flutter application demonstrates how to implement drag-and-drop functionality using `LongPressDraggable` for items and `DragTarget` for customer carts. It includes UI setup, state management for item assignment, and visual feedback during dragging. ```dart import 'package:flutter/material.dart'; void main() { runApp( const MaterialApp( home: ExampleDragAndDrop(), debugShowCheckedModeBanner: false, ), ); } const _urlPrefix = 'https://docs.flutter.dev/assets/images/exercise/effects/split-check'; const List _items = [ Item( name: 'Spinach Pizza', totalPriceCents: 1299, uid: '1', imageProvider: NetworkImage('$_urlPrefix/Food1.jpg'), ), Item( name: 'Veggie Delight', totalPriceCents: 799, uid: '2', imageProvider: NetworkImage('$_urlPrefix/Food2.jpg'), ), Item( name: 'Chicken Parmesan', totalPriceCents: 1499, uid: '3', imageProvider: NetworkImage('$_urlPrefix/Food3.jpg'), ), ]; @immutable class ExampleDragAndDrop extends StatefulWidget { const ExampleDragAndDrop({super.key}); @override State createState() => _ExampleDragAndDropState(); } class _ExampleDragAndDropState extends State with TickerProviderStateMixin { final List _people = [ Customer( name: 'Makayla', imageProvider: const NetworkImage('$_urlPrefix/Avatar1.jpg'), ), Customer( name: 'Nathan', imageProvider: const NetworkImage('$_urlPrefix/Avatar2.jpg'), ), Customer( name: 'Emilio', imageProvider: const NetworkImage('$_urlPrefix/Avatar3.jpg'), ), ]; final GlobalKey _draggableKey = GlobalKey(); void _itemDroppedOnCustomerCart({ required Item item, required Customer customer, }) { setState(() { customer.items.add(item); }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: const Color(0xFFF7F7F7), appBar: _buildAppBar(), body: _buildContent(), ); } PreferredSizeWidget _buildAppBar() { return AppBar( iconTheme: const IconThemeData(color: Color(0xFFF64209)), title: Text( 'Order Food', style: Theme.of(context).textTheme.headlineMedium?.copyWith( fontSize: 36, color: const Color(0xFFF64209), fontWeight: FontWeight.bold, ), ), backgroundColor: const Color(0xFFF7F7F7), elevation: 0, ); } Widget _buildContent() { return Stack( children: [ SafeArea( child: Column( children: [ Expanded(child: _buildMenuList()), _buildPeopleRow(), ], ), ), ], ); } Widget _buildMenuList() { return ListView.separated( padding: const EdgeInsets.all(16), itemCount: _items.length, separatorBuilder: (context, index) { return const SizedBox(height: 12); }, itemBuilder: (context, index) { final item = _items[index]; return _buildMenuItem(item: item); }, ); } Widget _buildMenuItem({required Item item}) { return LongPressDraggable( data: item, dragAnchorStrategy: pointerDragAnchorStrategy, feedback: DraggingListItem( dragKey: _draggableKey, photoProvider: item.imageProvider, ), child: MenuListItem( name: item.name, price: item.formattedTotalItemPrice, photoProvider: item.imageProvider, ), ); } Widget _buildPeopleRow() { return Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 20), child: Row(children: _people.map(_buildPersonWithDropZone).toList()), ); } Widget _buildPersonWithDropZone(Customer customer) { return Expanded( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 6), child: DragTarget( builder: (context, candidateItems, rejectedItems) { return CustomerCart( hasItems: customer.items.isNotEmpty, highlighted: candidateItems.isNotEmpty, customer: customer, ); }, onAcceptWithDetails: (details) { _itemDroppedOnCustomerCart(item: details.data, customer: customer); }, ), ), ); } } class CustomerCart extends StatelessWidget { const CustomerCart({ super.key, required this.customer, this.highlighted = false, this.hasItems = false, }); final Customer customer; final bool highlighted; final bool hasItems; @override ``` -------------------------------- ### Create project directory structure Source: https://github.com/flutter/website/blob/main/sites/docs/src/content/learn/pathway/tutorial/advanced-ui.md Create subdirectories within the `lib` folder to organize data models, screen widgets, and theme configurations. ```console $ mkdir lib/data lib/screens lib/theme ```