text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../app_model.dart'; // Uses full-screen breakpoints to reflow the widget tree class LoginPage extends StatelessWidget { const LoginPage({super.key}); @override Widget build(BuildContext context) { Size screenSize = MediaQuery.of(context).size; // Reflow from Row to Col when in Portrait mode bool useVerticalLayout = screenSize.width < screenSize.height; // Hide an optional element if the screen gets too small. bool hideDetailPanel = screenSize.shortestSide < 250; return Scaffold( body: Flex( direction: useVerticalLayout ? Axis.vertical : Axis.horizontal, children: [ if (!hideDetailPanel) ...[ Flexible(child: _LoginDetailPanel()), ], Flexible(child: _LoginForm()), ], ), ); } } class _LoginDetailPanel extends StatelessWidget { @override Widget build(BuildContext context) => Container( alignment: Alignment.center, color: Colors.grey.shade300, child: const Text( 'LOGIN VIEW\nBRANDING', style: TextStyle(fontSize: 64), textAlign: TextAlign.center, ), ); } class _LoginForm extends StatelessWidget { @override Widget build(BuildContext context) { // When login button is pressed, show the Dashboard page. void handleLoginPressed() => context.read<AppModel>().login(); // Example Form, pressing the login button will show the Dashboard page return Center( // Use a maxWidth so the form is responsive, but does get not too large on bigger screens child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 450), // Very small screens may require vertical scrolling of the form child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(16), child: Column( children: [ TextField(decoration: _getTextDecoration('Enter email...')), const SizedBox(height: 16), TextField( decoration: _getTextDecoration('Enter password...'), obscureText: true, ), const SizedBox(height: 16), OutlinedButton( onPressed: handleLoginPressed, child: Container( width: double.infinity, alignment: Alignment.center, padding: const EdgeInsets.all(16), child: const Text('Log In'), ), ), ], ), ), ), ), ); } } InputDecoration _getTextDecoration(String hint) => InputDecoration(border: const OutlineInputBorder(), hintText: hint);
website/examples/ui/layout/adaptive_app_demos/lib/pages/login_page.dart/0
{ "file_path": "website/examples/ui/layout/adaptive_app_demos/lib/pages/login_page.dart", "repo_id": "website", "token_count": 1233 }
1,350
# When adding the release notes for a new DevTools release, # make sure to add the version number as an entry in this list. # This step might be eliminated in the future. releases: - '2.33.0' - '2.32.0' - '2.31.0' - '2.30.0' - '2.29.0' - '2.28.5' - '2.28.4' - '2.28.3' - '2.27.0' - '2.26.1' - '2.25.0' - '2.24.0' - '2.23.1' - '2.22.2' - '2.21.1' - '2.20.0' - '2.19.0' - '2.18.0' - '2.17.0' - '2.16.0' - '2.15.0' - '2.14.0' - '2.13.1' - '2.12.2' - '2.12.1' - '2.11.2' - '2.10.0' - '2.9.2' - '2.9.1' - '2.8.0' - '2.7.0'
website/src/_data/devtools_releases.yml/0
{ "file_path": "website/src/_data/devtools_releases.yml", "repo_id": "website", "token_count": 355 }
1,351
{{site.alert.secondary}} 如果你正在中国的网络环境下配置 Flutter, 请参考 [在中国网络环境下使用 Flutter][] 文档. {{site.alert.end}} [在中国网络环境下使用 Flutter]: https://flutter.cn/community/china
website/src/_includes/docs/china-notice-cn.md/0
{ "file_path": "website/src/_includes/docs/china-notice-cn.md", "repo_id": "website", "token_count": 140 }
1,352
{% assign os=include.os %} {% assign terminal=include.terminal %} {%- if os=='macOS' -%} {% assign special = 'Command' %} {% else %} {% assign special = 'Control' %} {%- endif %} ### Use VS Code to install Flutter {:.no_toc} To install Flutter using these instructions, verify that you have installed [Visual Studio Code][] {{site.appmin.vscode}} or later and the [Flutter extension for VS Code][]. #### Prompt VS Code to install Flutter 1. Launch VS Code. 1. To open the **Command Palette**, press <kbd>{{special}}</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd>. 1. In the **Command Palette**, type `flutter`. 1. Select **Flutter: New Project**. 1. VS Code prompts you to locate the Flutter SDK on your computer. {:type="a"} 1. If you have the Flutter SDK installed, click **Locate SDK**. 1. If you do not have the Flutter SDK installed, click **Download SDK**. This option sends you the Flutter install page if you have not installed Git {% if os == "Windows" %}for Windows {% endif %}as directed in the [development tools prerequisites][]. 1. When prompted **Which Flutter template?**, ignore it. Press <kbd>Esc</kbd>. You can create a test project after checking your development setup. #### Download the Flutter SDK 1. When the **Select Folder for Flutter SDK** dialog displays, choose where you want to install Flutter. VS Code places you in your user profile to start. Choose a different location. {% if os == "Windows" -%} Consider `%USERPROFILE%` or `C:\dev`. {% include docs/install/admonitions/install-paths.md %} {% else -%} Consider `~/development/` {% endif %} 1. Click **Clone Flutter**. While downloading Flutter, VS Code displays this pop-up notification: ```terminal Downloading the Flutter SDK. This may take a few minutes. ``` This download takes a few minutes. If you suspect that the download has hung, click **Cancel** then start the installation again. 1. Once it finishes downloading Flutter, the **Output** panel displays. ```terminal Checking Dart SDK version... Downloading Dart SDK from the Flutter engine ... Expanding downloaded archive... ``` When successful, VS Code displays this pop-up notification: ```terminal Initializing the Flutter SDK. This may take a few minutes. ``` While initializing, the **Output** panel displays the following: ```terminal Building flutter tool... Running pub upgrade... Resolving dependencies... Got dependencies. Downloading Material fonts... Downloading Gradle Wrapper... Downloading package sky_engine... Downloading flutter_patched_sdk tools... Downloading flutter_patched_sdk_product tools... Downloading windows-x64 tools... Downloading windows-x64/font-subset tools... ``` This process also runs `flutter doctor -v`. At this point in the procedure, _ignore this output._ Flutter Doctor might show errors that don't apply to this quick start. When the Flutter install succeeds, VS Code displays this pop-up notification: ```terminal Do you want to add the Flutter SDK to PATH so it's accessible in external terminals? ``` {% if os=='Windows' %} 1. Click **Add SDK to PATH**. When successful, a notification displays: ```terminal The Flutter SDK was added to your PATH ``` {% endif %} 1. VS Code may display a Google Analytics notice. If you agree, click **OK**. 1. To enable `flutter` in all {{terminal}} windows: {:type="a"} 1. Close, then reopen all {{terminal}} windows. 1. Restart VS Code. [development tools prerequisites]: #development-tools [Visual Studio Code]: https://code.visualstudio.com/docs/setup/mac [Flutter extension for VS Code]: https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
website/src/_includes/docs/install/flutter/vscode.md/0
{ "file_path": "website/src/_includes/docs/install/flutter/vscode.md", "repo_id": "website", "token_count": 1200 }
1,353
{% assign target = include.target %} <details markdown="1"> <summary><strong>To verify your shell configuration, expand this section</strong></summary> Like most UNIX-like operating system, macOS can support multiple shells, like `bash`, `zsh`, and `sh`. As of the October 2019 release of macOS Catalina (macOS 10.15), Zsh or `zsh` is the default shell for macOS. #### Check and set `zsh` as default 1. To verify `zsh` was set as the default macOS shell, run the [Directory Services command line utility][dscl]. ```terminal $ dscl . -read ~/ UserShell ``` {{terminal}} should print the following as its response. ```terminal UserShell: /bin/zsh ``` You can skip the remaining steps. 1. If you need to install `zsh`, follow the procedure in [this Wiki][install-zsh]. 1. If you need to change your default shell to `zsh`, run the `chsh` command. ```terminal $ chsh -s `which zsh` ``` To learn more about macOS and `zsh`, check out [Use zsh as the default shell on your Mac][zsh-mac] in the macOS documentation. </details> [install-zsh]: https://github.com/ohmyzsh/ohmyzsh/wiki/Installing-ZSH [dscl]: https://ss64.com/mac/dscl.html
website/src/_includes/docs/install/reqs/macos/zsh-config.md/0
{ "file_path": "website/src/_includes/docs/install/reqs/macos/zsh-config.md", "repo_id": "website", "token_count": 405 }
1,354
## Other Resources To learn more about C interoperability, check out these videos: - [C interoperability with Dart FFI] - [How to Use Dart FFI to Build a Retro Audio Player] [C interoperability with Dart FFI]: {{site.yt.watch}}?v=2MMK7YoFgaA [How to Use Dart FFI to Build a Retro Audio Player]: {{site.yt.watch}}?v=05Wn2oM_nWw
website/src/_includes/docs/resource-links/ffi-video-resources.md/0
{ "file_path": "website/src/_includes/docs/resource-links/ffi-video-resources.md", "repo_id": "website", "token_count": 111 }
1,355
{% assign cache_bust = site.time|date:'?v=%s' %} {% assign page_url = page.url | regex_replace: '/index$|/index.html$|\.html$|/$' -%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>{% if page.title %}{{ page.title }} | {% endif %}{{ site.title }}</title> <link rel="icon" href="/assets/images/branding/flutter/icon/64.png"> <link rel="apple-touch-icon" href="/assets/images/branding/flutter/logo/flutter-logomark-320px.png"> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta name="theme-color" content="#ffffff"> {% unless page.strip_fonts == true -%} <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> {% endunless -%} {% if jekyll.environment == "production" -%} <meta name="google-site-verification" content="{{ site.google_site_verification }}"> <script> (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','{{ site.google_tag_manager_id }}'); </script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '{{ site.google_analytics_id }}', 'auto'); ga('send', 'pageview'); </script> {% endif -%} {% assign desc = page.description -%} {% unless desc and desc != '' -%} {% assign error = page.url | append: ' must have a description specified!' -%} {{ error | throw_error }} {% endunless %} {% assign og_image_path = page.image.path | default: layout.image.path | default: site.default_share_image -%} <meta name="description" content="{{desc}}"> <meta name="keywords" content="{% if page.tags %}{{page.tags}}, {% endif %}{{page.keywords}}"> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:site" content="@flutterdev"> <meta property="og:title" content="{{page.title}}"> <meta property="og:url" content="{{page_url | absolute_url}}"> <meta property="og:description" content="{{desc}}"> <meta property="og:image" content="{{og_image_path | absolute_url}}"> {% unless page.strip_fonts == true -%} <link href="https://fonts.googleapis.com/css2?family=Google+Sans:wght@400;500;700&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Google+Sans+Text:wght@400;500;700&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Google+Sans+Mono:wght@400;500;700&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" rel="stylesheet" /> {% endunless -%} {% include head-diff2html.html -%} <script> window.__CALLBACKS = []; </script> <link rel="stylesheet" href="{{ '/assets/css/main.css' | append: cache_bust }}"> {% for css in page.css -%} {% assign asset_path = '/assets/css/{{css}}' -%} <link rel="stylesheet" href="{{ asset_path | append: cache_bust }}"> {% endfor -%} </head> <body{% if page.body_class %} class="{{ page.body_class }}"{% endif %}> {% include cookie-notice.html %} {% if jekyll.environment == "production" %} <noscript> <iframe src="https://www.googletagmanager.com/ns.html?id={{ site.google_tag_manager_id }}" height="0" width="0" style="display:none;visibility:hidden"> </iframe> </noscript> {% endif %} <div id="overlay-under-drawer"></div> {% include header.html %} {% if page.show_banner -%} {% include banner.html %} {% endif -%} {{ content }} {% if page.show_footer %} {% include footer.html %} {% endif %} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js" integrity="sha512-3gJwYpMe3QewGELv8k/BX9vcqhryRdzRMxVfq6ngyWXwo03GFEzjsUm8Q7RZcHPHksttq7/GFoxjCVUjkjvPdw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.6.2/js/bootstrap.min.js" integrity="sha512-7rusk8kGPFynZWu26OKbTeI+QPoYchtxsmPeBqkHIEXJxeun4yJ4ISYe7C6sz9wdxeE1Gk3VxsIWgCZTc+vX3g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.11/clipboard.min.js" integrity="sha512-7O5pXpc0oCRrxk8RUfDYFgn0nO1t+jLuIOQdOMRp4APB7uZ4vSjspzp5y6YDtDs4VzUSTbWzBFZ/LKJhnyFOKw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/3.0.5/js.cookie.min.js" integrity="sha512-nlp9/l96/EpjYBx7EP7pGASVXNe80hGhYAUrjeXnu/fyF5Py0/RXav4BBNs7n5Hx1WFhOEOWSAVjGeC3oKxDVQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="{{ '/assets/js/vendor/code-prettify/prettify.js' | append: cache_bust }}"></script> <script src="{{ '/assets/js/vendor/code-prettify/lang-css.js' | append: cache_bust }}"></script> <script src="{{ '/assets/js/vendor/code-prettify/lang-dart.js' | append: cache_bust }}"></script> <script src="{{ '/assets/js/vendor/code-prettify/lang-yaml.js' | append: cache_bust }}"></script> <script src="{{ '/assets/js/tabs.js' | append: cache_bust }}"></script> <script src="{{ '/assets/js/archive.js' | append: cache_bust }}"></script> <script src="{{ '/assets/js/main.js' | append: cache_bust }}"></script> {% for script in page.js -%} <script src="{{ script.url | default: js }}" {% if script.defer %}defer{% endif %}></script> {% endfor %} </body> </html>
website/src/_layouts/base.html/0
{ "file_path": "website/src/_layouts/base.html", "repo_id": "website", "token_count": 2832 }
1,356
require_relative 'markdown_with_code_excerpts' require_relative 'code_excerpt_framer' module Jekyll module Converters # Kramdown plugin extension. # # Converts markdown code blocks preceded by a processing instruction (PI) of the form # <?code-excerpt?> into: # # - <code-example> elements suitable for use in Angular docs. # - diff2html elements # class DartSiteMarkdown < Converter priority :high include MarkdownWithCodeExcerptsConverterMixin def initialize(config = {}) super(config) @cec = MarkdownWithCodeExcerpts.new(config, DartSite::CodeExcerptFramer.new) end def convert(content) @cec.convert(content) end end end end
website/src/_plugins/markdown_converter.rb/0
{ "file_path": "website/src/_plugins/markdown_converter.rb", "repo_id": "website", "token_count": 283 }
1,357
.d2h-wrapper { margin: 30px 0; } .d2h-file-header { height: unset; }
website/src/_sass/components/_d2h.scss/0
{ "file_path": "website/src/_sass/components/_d2h.scss", "repo_id": "website", "token_count": 42 }
1,358
--- title: Add a Flutter View to an Android app short-title: Integrate via FlutterView description: Learn how to perform advanced integrations via Flutter Views. --- {{site.alert.warning}} Integrating via a [FlutterView]({{site.api}}/javadoc/io/flutter/embedding/android/FlutterView.html) is advanced usage and requires manually creating custom, application specific bindings. {{site.alert.end}} Integrating via a [FlutterView]({{site.api}}/javadoc/io/flutter/embedding/android/FlutterView.html) requires a bit more work than via FlutterActivity and FlutterFragment previously described. Fundamentally, the Flutter framework on the Dart side requires access to various activity-level events and lifecycles to function. Since the FlutterView (which is an [android.view.View]({{site.android-dev}}/reference/android/view/View.html)) can be added to any activity which is owned by the developer's application and since the FlutterView doesn't have access to activity level events, the developer must bridge those connections manually to the [FlutterEngine]({{site.api}}/javadoc/io/flutter/embedding/engine/FlutterEngine.html). How you choose to feed your application's activities' events to the FlutterView will be specific to your application. ## A sample <img src='/assets/images/docs/development/add-to-app/android/add-flutter-view/add-view-sample.gif' class="mw-100" alt="Add Flutter View sample video"> Unlike the guides for FlutterActivity and FlutterFragment, the FlutterView integration could be better demonstrated with a sample project. A sample project is at [https://github.com/flutter/samples/tree/main/add_to_app/android_view]({{site.repo.samples}}/tree/main/add_to_app/android_view) to document a simple FlutterView integration where FlutterViews are used for some of the cells in a RecycleView list of cards as seen in the gif above. ## General approach The general gist of the FlutterView-level integration is that you must recreate the various interactions between your Activity, the [FlutterView]({{site.api}}/javadoc/io/flutter/embedding/android/FlutterView.html) and the [FlutterEngine]({{site.api}}/javadoc/io/flutter/embedding/engine/FlutterEngine.html) present in the [FlutterActivityAndFragmentDelegate](https://cs.opensource.google/flutter/engine/+/master:shell/platform/android/io/flutter/embedding/android/FlutterActivityAndFragmentDelegate.java) in your own application's code. The connections made in the [FlutterActivityAndFragmentDelegate](https://cs.opensource.google/flutter/engine/+/master:shell/platform/android/io/flutter/embedding/android/FlutterActivityAndFragmentDelegate.java) are done automatically when using a [FlutterActivity]({{site.api}}/javadoc/io/flutter/embedding/android/FlutterActivity.html) or a [FlutterFragment]({{site.api}}/javadoc/io/flutter/embedding/android/FlutterFragment.html), but since the [FlutterView]({{site.api}}/javadoc/io/flutter/embedding/android/FlutterView.html) in this case is being added to an Activity or Fragment in your application, you must recreate the connections manually. Otherwise, the [FlutterView]({{site.api}}/javadoc/io/flutter/embedding/android/FlutterView.html) will not render anything or have other missing functionalities. A sample [FlutterViewEngine]({{site.repo.samples}}/blob/main/add_to_app/android_view/android_view/app/src/main/java/dev/flutter/example/androidView/FlutterViewEngine.kt) class shows one such possible implementation of an application-specific connection between an Activity, a [FlutterView]({{site.api}}/javadoc/io/flutter/embedding/android/FlutterView.html) and a [FlutterEngine]({{site.api}}/javadoc/io/flutter/embedding/engine/FlutterEngine.html). ### APIs to implement The absolute minimum implementation needed for Flutter to draw anything at all is to: - Call [attachToFlutterEngine]({{site.api}}/javadoc/io/flutter/embedding/android/FlutterView.html#attachToFlutterEngine-io.flutter.embedding.engine.FlutterEngine-) when the [FlutterView]({{site.api}}/javadoc/io/flutter/embedding/android/FlutterView.html) is added to a resumed Activity's view hierarchy and is visible; and - Call [appIsResumed]({{site.api}}/javadoc/io/flutter/embedding/engine/systemchannels/LifecycleChannel.html#appIsResumed--) on the [FlutterEngine]({{site.api}}/javadoc/io/flutter/embedding/engine/FlutterEngine.html)'s `lifecycleChannel` field when the Activity hosting the [FlutterView]({{site.api}}/javadoc/io/flutter/embedding/android/FlutterView.html) is visible. The reverse [detachFromFlutterEngine]({{site.api}}/javadoc/io/flutter/embedding/android/FlutterView.html#detachFromFlutterEngine--) and other lifecycle methods on the [LifecycleChannel]({{site.api}}/javadoc/io/flutter/embedding/engine/systemchannels/LifecycleChannel.html) class must also be called to not leak resources when the FlutterView or Activity is no longer visible. In addition, see the remaining implementation in the [FlutterViewEngine]({{site.repo.samples}}/blob/main/add_to_app/android_view/android_view/app/src/main/java/dev/flutter/example/androidView/FlutterViewEngine.kt) demo class or in the [FlutterActivityAndFragmentDelegate](https://cs.opensource.google/flutter/engine/+/master:shell/platform/android/io/flutter/embedding/android/FlutterActivityAndFragmentDelegate.java) to ensure a correct functioning of other features such as clipboards, system UI overlay, plugins etc.
website/src/add-to-app/android/add-flutter-view.md/0
{ "file_path": "website/src/add-to-app/android/add-flutter-view.md", "repo_id": "website", "token_count": 1640 }
1,359
<?xml version="1.0" encoding="utf-8"?> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 237.9 238"> <style type="text/css"> .st0{fill:none;} .st1{opacity:0.72;fill:#FFFFFF;} </style> <rect class="st0" width="237.9" height="237.9"/> <polygon class="st1" points="126.8,205.6 126.7,205.6 80.1,159 106.7,132.3 179.9,205.6 "/> <polygon class="st1" points="126.7,112.3 126.7,112.3 80,158.9 106.7,185.5 179.9,112.3 "/> <polygon class="st1" points="126.7,32.5 126.6,32.4 39.9,119 66.6,145.7 179.8,32.5 "/> </svg>
website/src/assets/images/branding/flutter/icon/mono.svg/0
{ "file_path": "website/src/assets/images/branding/flutter/icon/mono.svg", "repo_id": "website", "token_count": 283 }
1,360
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg width="1.9999179in" height="1.9999999in" version="1.1" viewBox="0 0 50.796725 50.798808" id="svg11" sodipodi:docname="windows.svg" inkscape:version="1.3.2 (091e20e, 2023-11-25)" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"> <defs id="defs11" /> <sodipodi:namedview id="namedview11" pagecolor="#ffffff" bordercolor="#000000" borderopacity="0.25" inkscape:showpageshadow="2" inkscape:pageopacity="0.0" inkscape:pagecheckerboard="0" inkscape:deskcolor="#d1d1d1" inkscape:zoom="0.865" inkscape:cx="246.24277" inkscape:cy="90.751445" inkscape:window-width="1392" inkscape:window-height="942" inkscape:window-x="0" inkscape:window-y="25" inkscape:window-maximized="0" inkscape:current-layer="svg11" inkscape:document-units="in" /> <g id="g1" transform="matrix(1.042091,0,0,1.042091,0,1.1497045e-4)" style="fill:#027dfd;fill-opacity:1"> <rect x="0" y="-0.00011032669" width="23.105" height="23.105" id="rect8" style="fill:#027dfd;fill-opacity:1" /> <rect x="25.639999" y="-0.00011032669" width="23.105" height="23.105" id="rect9" style="fill:#027dfd;fill-opacity:1" /> <rect x="0" y="25.64189" width="23.105" height="23.105" id="rect10" style="fill:#027dfd;fill-opacity:1" /> <rect x="25.639999" y="25.64189" width="23.105" height="23.105" id="rect11" style="fill:#027dfd;fill-opacity:1" /> </g> <g id="g4" transform="matrix(1.042091,0,0,1.042091,0,1.1497045e-4)" style="fill:#027dfd;fill-opacity:1"> <rect x="0" y="-0.00011032669" width="23.105" height="23.105" id="rect1" style="fill:#027dfd;fill-opacity:1" /> <rect x="25.639999" y="-0.00011032669" width="23.105" height="23.105" id="rect2" style="fill:#027dfd;fill-opacity:1" /> <rect x="0" y="25.64189" width="23.105" height="23.105" id="rect3" style="fill:#027dfd;fill-opacity:1" /> <rect x="25.639999" y="25.64189" width="23.105" height="23.105" id="rect4" style="fill:#027dfd;fill-opacity:1" /> </g> <rect x="0" y="-2.1218882e-12" width="24.077513" height="24.077513" id="rect5" style="fill:#027dfd;stroke-width:1.04209;fill-opacity:1" /> <rect x="26.719213" y="-2.1218882e-12" width="24.077513" height="24.077513" id="rect6" style="fill:#027dfd;stroke-width:1.04209;fill-opacity:1" /> <rect x="0" y="26.721298" width="24.077513" height="24.077513" id="rect7" style="fill:#027dfd;stroke-width:1.04209;fill-opacity:1" /> <rect x="26.719213" y="26.721298" width="24.077513" height="24.077513" id="rect12" style="fill:#027dfd;stroke-width:1.04209;fill-opacity:1" /> </svg>
website/src/assets/images/docs/brand-svg/windows.svg/0
{ "file_path": "website/src/assets/images/docs/brand-svg/windows.svg", "repo_id": "website", "token_count": 1835 }
1,361
--- title: Flutter Brand Guidelines description: > The guidelines governing the usage of the Flutter trademarks and assets. --- The "Flutter" name and logo are trademarks owned by Google. These Brand Guidelines describe the appropriate uses of the Flutter trademarks by members of the developer community who have obtained our consent to use the trademarks pursuant to the [Flutter Terms of Service](/tos). These guidelines will ensure that the Flutter trademarks are used in a manner that promotes Google's mission to provide a free and open source SDK for crafting high-quality native interfaces on iOS and Android in record time, and are not associated with objectionable material, as determined by Google. Use of the Flutter trademarks that is not expressly permitted by these guidelines is prohibited absent written permission from Google. The official Flutter assets and further guidelines on representing the brand can be found at [Representing the Flutter Brand]({{site.main-url}}/brand). ## General Rules That Govern the Use of the Flutter Trademarks You are free to use the Flutter trademarks: (i) in connection with your download and use of the Flutter SDK to build and develop apps, (ii) in training materials (e.g., video tutorials, online publications, etc.) that provide instructions or tips regarding how to use the Flutter SDK to build and develop apps, and (iii) to show your support for the use of the Flutter SDK by members of the developer community. These guidelines do not restrict your right to use the "Flutter" name in connection with descriptions of the Flutter SDK that would be considered "fair use." For example, you may use the "Flutter" name to make truthful factual statements (e.g., "built with the Flutter SDK") or to accurately describe a feature of the Flutter SDK. You may use the Flutter trademarks on your personal website, personal blog, or social media account to show your support for the Flutter SDK, provided you do not use the Flutter trademarks in a way that could confuse people into thinking that your site is an official Google site or that Google has sponsored or endorsed your site. In the case of websites or personal blogs, this means you should not use the Flutter trademarks as the primary element on the webpage (e.g., in the masthead of the webpage or the title of the blog). In the case of social media accounts, this means you should not use the Flutter trademarks in the background, in your profile image or in your social media username. ## Specific Rules for Proper Usage of the Flutter Trademarks In addition to the general rules discussed above, below are specific rules governing the proper use of the Flutter trademarks. **DO:** * Use the "Flutter" name as an adjective, never as a noun or verb, and never in the plural or possessive form. * Use a generic term following the "Flutter" name, for example, "the Flutter SDK" or "the Flutter UI toolkit." * Distinguish the "Flutter" name from the surrounding text in some way. Capitalize the first letter, capitalize or italicize the entire mark, place the mark in quotes, use a different type style or font for the mark. * Use the trademark symbol <sup>TM</sup> for the first or most prominent time the "Flutter" name appears in text on your website or blog. Make sure to always use the <sup>TM</sup> symbol, not the <sup>&reg;</sup> symbol. * Include the following text near the first or most prominent use of the Flutter marks on your website or blog: "Flutter and the related logo are trademarks of Google LLC. We are not endorsed by or affiliated with Google LLC." * Keep some distance between the Flutter trademarks and any other trademarks, logos, or icons that are displayed on the webpage. **DON'T:** * Don't alter, distort, or modify the Flutter trademarks in any way. This includes varying the spelling of the "Flutter" name, or displaying the Flutter logo with color variations or unapproved visual elements. * Don't combine the Google name with the "Flutter" name to form a unitary brand (e.g., don't use the phrases "Google Flutter" or "Google's Flutter"). You may use the Google name in full text to accurately describe the Flutter SDK (e.g., "The Flutter SDK by Google"). * Don't register the Flutter trademarks or any trademarks, logos, or domain names that are confusingly similar to them. * Don't incorporate the Flutter trademarks into your own product names, service names, trademarks, logos, or company names. * Don't display the Flutter trademarks in a manner that is misleading, unfair, defamatory, infringing, libelous, disparaging, obscene or otherwise objectionable to Google. * Don't use the Flutter trademarks on or in connection with the sale of any non-software goods or services (e.g., merchandise such as clothing, pens, and stickers). ## Community Use Exceptions To allow for the use of the Flutter trademarks by the Flutter community, below are specific exceptions to the rules described above: 1. Local Flutter user groups may: (i) use the "Flutter" name as part of their social media username in the following format: "Flutter + [name of country/city]" (e.g., "Flutter France"); and (ii) use the Flutter logo in the national colors of the country where the user group is based (e.g., for a user group based in France, the colors blue, white and red), provided the Flutter logo is otherwise unaltered. Such social media accounts should include a disclaimer that clarifies that it is not an official Google account. 2. You may use the Flutter trademarks as part of the name of a newsletter or related community content (e.g., Flutter training courses, Flutter community forums) whose purpose is to promote the use of the Flutter SDK by members of the developer community. Where the Flutter trademarks are displayed on a website as part of a community site name, you should use the trademark symbol <sup>TM</sup> after the most prominent appearance of the "Flutter" name and include the following text: "Flutter and the related logo are trademarks of Google LLC. We are not endorsed by or affiliated with Google LLC." Where the Flutter trademarks are displayed on a social media account as part of a community site name, you should include a disclaimer that clarifies that it is not an official Google account. 3. <b>[Unofficial Flutter Events]</b> You may use the Flutter trademarks as part of the name of a community event (e.g. conference), but please make sure to include the following disclaimer on the event website in a prominent and easy-to-see spot: "Flutter and the related logo are trademarks of Google LLC. [Title of event] is not affiliated with or otherwise sponsored by Google LLC."
website/src/brand/index.md/0
{ "file_path": "website/src/brand/index.md", "repo_id": "website", "token_count": 1663 }
1,362
--- title: Export fonts from a package description: How to export fonts from a package. --- <?code-excerpt path-base="cookbook/design/package_fonts"?> Rather than declaring a font as part of an app, you can declare a font as part of a separate package. This is a convenient way to share the same font across several different projects, or for coders publishing their packages to [pub.dev][]. This recipe uses the following steps: 1. Add a font to a package. 2. Add the package and font to the app. 3. Use the font. {{site.alert.note}} Check out the [google_fonts][] package for direct access to almost 1000 open-sourced font families. {{site.alert.end}} ## 1. Add a font to a package To export a font from a package, you need to import the font files into the `lib` folder of the package project. You can place font files directly in the `lib` folder or in a subdirectory, such as `lib/fonts`. In this example, assume you've got a Flutter library called `awesome_package` with fonts living in a `lib/fonts` folder. ``` awesome_package/ lib/ awesome_package.dart fonts/ Raleway-Regular.ttf Raleway-Italic.ttf ``` ## 2. Add the package and fonts to the app Now you can use the fonts in the package by updating the `pubspec.yaml` in the *app's* root directory. ### Add the package to the app To add the `awesome_package` package as a dependency, run `flutter pub add`: ```terminal $ flutter pub add awesome_package ``` ### Declare the font assets Now that you've imported the package, tell Flutter where to find the fonts from the `awesome_package`. To declare package fonts, prefix the path to the font with `packages/awesome_package`. This tells Flutter to look in the `lib` folder of the package for the font. ```yaml flutter: fonts: - family: Raleway fonts: - asset: packages/awesome_package/fonts/Raleway-Regular.ttf - asset: packages/awesome_package/fonts/Raleway-Italic.ttf style: italic ``` ## 3. Use the font Use a [`TextStyle`][] to change the appearance of text. To use package fonts, declare which font you'd like to use and which package the font belongs to. <?code-excerpt "lib/main.dart (TextStyle)"?> ```dart child: Text( 'Using the Raleway font from the awesome_package', style: TextStyle( fontFamily: 'Raleway', ), ), ``` ## Complete example ### Fonts The Raleway and RobotoMono fonts were downloaded from [Google Fonts][]. ### `pubspec.yaml` ```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 ``` ### `main.dart` <?code-excerpt "lib/main.dart"?> ```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: 'Package Fonts', home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( // The AppBar uses the app-default font. appBar: AppBar(title: const Text('Package Fonts')), body: const Center( // This Text widget uses the Raleway font. child: Text( 'Using the Raleway font from the awesome_package', style: TextStyle( fontFamily: 'Raleway', ), ), ), ); } } ``` ![Package Fonts Demo](/assets/images/docs/cookbook/package-fonts.png){:.site-mobile-screenshot} [Google Fonts]: https://fonts.google.com [google_fonts]: {{site.pub-pkg}}/google_fonts [pub.dev]: {{site.pub}} [`TextStyle`]: {{site.api}}/flutter/painting/TextStyle-class.html
website/src/cookbook/design/package-fonts.md/0
{ "file_path": "website/src/cookbook/design/package-fonts.md", "repo_id": "website", "token_count": 1457 }
1,363
--- title: Forms description: A catalog of Flutter form recipes. --- {% include docs/cookbook-group-index.md %}
website/src/cookbook/forms/index.md/0
{ "file_path": "website/src/cookbook/forms/index.md", "repo_id": "website", "token_count": 36 }
1,364
--- title: Navigate to a new screen and back description: How to navigate between routes. js: - defer: true url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js --- <?code-excerpt path-base="cookbook/navigation/navigation_basics"?> Most apps contain several screens for displaying different types of information. For example, an app might have a screen that displays products. When the user taps the image of a product, a new screen displays details about the product. {{site.alert.secondary}} **Terminology**: In Flutter, _screens_ and _pages_ are called _routes_. The remainder of this recipe refers to routes. {{site.alert.end}} In Android, a route is equivalent to an Activity. In iOS, a route is equivalent to a ViewController. In Flutter, a route is just a widget. This recipe uses the [`Navigator`][] to navigate to a new route. The next few sections show how to navigate between two routes, using these steps: 1. Create two routes. 2. Navigate to the second route using Navigator.push(). 3. Return to the first route using Navigator.pop(). ## 1. Create two routes First, create two routes to work with. Since this is a basic example, each route contains only a single button. Tapping the button on the first route navigates to the second route. Tapping the button on the second route returns to the first route. First, set up the visual structure: <?code-excerpt "lib/main_step1.dart (FirstSecondRoutes)"?> ```dart class FirstRoute extends StatelessWidget { const FirstRoute({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('First Route'), ), body: Center( child: ElevatedButton( child: const Text('Open route'), onPressed: () { // Navigate to second route when tapped. }, ), ), ); } } class SecondRoute extends StatelessWidget { const SecondRoute({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Second Route'), ), body: Center( child: ElevatedButton( onPressed: () { // Navigate back to first route when tapped. }, child: const Text('Go back!'), ), ), ); } } ``` ## 2. Navigate to the second route using Navigator.push() To switch to a new route, use the [`Navigator.push()`][] method. The `push()` method adds a `Route` to the stack of routes managed by the `Navigator`. Where does the `Route` come from? You can create your own, or use a [`MaterialPageRoute`][], which is useful because it transitions to the new route using a platform-specific animation. In the `build()` method of the `FirstRoute` widget, update the `onPressed()` callback: <?code-excerpt "lib/main_step2.dart (FirstRouteOnPressed)"?> ```dart // Within the `FirstRoute` widget onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => const SecondRoute()), ); } ``` ## 3. Return to the first route using Navigator.pop() How do you close the second route and return to the first? By using the [`Navigator.pop()`][] method. The `pop()` method removes the current `Route` from the stack of routes managed by the `Navigator`. To implement a return to the original route, update the `onPressed()` callback in the `SecondRoute` widget: <?code-excerpt "lib/main_step2.dart (SecondRouteOnPressed)"?> ```dart // Within the SecondRoute widget onPressed: () { Navigator.pop(context); } ``` ## Interactive example <?code-excerpt "lib/main.dart"?> ```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-interactive_example import 'package:flutter/material.dart'; void main() { runApp(const MaterialApp( title: 'Navigation Basics', home: FirstRoute(), )); } class FirstRoute extends StatelessWidget { const FirstRoute({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('First Route'), ), body: Center( child: ElevatedButton( child: const Text('Open route'), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => const SecondRoute()), ); }, ), ), ); } } class SecondRoute extends StatelessWidget { const SecondRoute({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Second Route'), ), body: Center( child: ElevatedButton( onPressed: () { Navigator.pop(context); }, child: const Text('Go back!'), ), ), ); } } ``` <noscript> <img src="/assets/images/docs/cookbook/navigation-basics.gif" alt="Navigation Basics Demo" class="site-mobile-screenshot" /> </noscript> ## Navigation with CupertinoPageRoute In the previous example you learned how to navigate between screens using the [`MaterialPageRoute`][] from [Material Components][]. However, in Flutter you are not limited to Material design language, instead, you also have access to [Cupertino][] (iOS-style) widgets. Implementing navigation with Cupertino widgets follows the same steps as when using [`MaterialPageRoute`][], but instead you use [`CupertinoPageRoute`][] which provides an iOS-style transition animation. In the following example, these widgets have been replaced: - [`MaterialApp`][] replaced by [`CupertinoApp`]. - [`Scaffold`][] replaced by [`CupertinoPageScaffold`][]. - [`ElevatedButton`][] replaced by [`CupertinoButton`][]. This way, the example follows the current iOS design language. {{site.alert.secondary}} You don't need to replace all Material widgets with Cupertino versions to use [`CupertinoPageRoute`][] since Flutter allows you to mix and match Material and Cupertino widgets depending on your needs. {{site.alert.end}} <?code-excerpt "lib/main_cupertino.dart"?> ```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-interactive_example import 'package:flutter/cupertino.dart'; void main() { runApp(const CupertinoApp( title: 'Navigation Basics', home: FirstRoute(), )); } class FirstRoute extends StatelessWidget { const FirstRoute({super.key}); @override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar( middle: Text('First Route'), ), child: Center( child: CupertinoButton( child: const Text('Open route'), onPressed: () { Navigator.push( context, CupertinoPageRoute(builder: (context) => const SecondRoute()), ); }, ), ), ); } } class SecondRoute extends StatelessWidget { const SecondRoute({super.key}); @override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar( middle: Text('Second Route'), ), child: Center( child: CupertinoButton( onPressed: () { Navigator.pop(context); }, child: const Text('Go back!'), ), ), ); } } ``` <noscript> <img src="/assets/images/docs/cookbook/navigation-basics-cupertino.gif" alt="Navigation Basics Cupertino Demo" class="site-mobile-screenshot" /> </noscript> [Cupertino]: {{site.docs}}/ui/widgets/cupertino [Material Components]: {{site.docs}}/ui/widgets/material [`CupertinoApp`]: {{site.api}}/flutter/cupertino/CupertinoApp-class.html [`CupertinoButton`]: {{site.api}}/flutter/cupertino/CupertinoButton-class.html [`CupertinoPageRoute`]: {{site.api}}/flutter/cupertino/CupertinoPageRoute-class.html [`CupertinoPageScaffold`]: {{site.api}}/flutter/cupertino/CupertinoPageScaffold-class.html [`ElevatedButton`]: {{site.api}}/flutter/material/ElevatedButton-class.html [`MaterialApp`]: {{site.api}}/flutter/material/MaterialApp-class.html [`MaterialPageRoute`]: {{site.api}}/flutter/material/MaterialPageRoute-class.html [`Navigator.pop()`]: {{site.api}}/flutter/widgets/Navigator/pop.html [`Navigator.push()`]: {{site.api}}/flutter/widgets/Navigator/push.html [`Navigator`]: {{site.api}}/flutter/widgets/Navigator-class.html [`Scaffold`]: {{site.api}}/flutter/material/Scaffold-class.html
website/src/cookbook/navigation/navigation-basics.md/0
{ "file_path": "website/src/cookbook/navigation/navigation-basics.md", "repo_id": "website", "token_count": 3107 }
1,365
--- title: Persist data with SQLite description: How to use SQLite to store and retrieve data. --- <?code-excerpt path-base="cookbook/persistence/sqlite/"?> {{site.alert.note}} This guide uses the [sqflite package][]. This package only supports apps that run on macOS, iOS, or Android. {{site.alert.end}} [sqflite package]: {{site.pub-pkg}}/sqflite If you are writing an app that needs to persist and query large amounts of data on the local device, consider using a database instead of a local file or key-value store. In general, databases provide faster inserts, updates, and queries compared to other local persistence solutions. Flutter apps can make use of the SQLite databases via the [`sqflite`][] plugin available on pub.dev. This recipe demonstrates the basics of using `sqflite` to insert, read, update, and remove data about various Dogs. If you are new to SQLite and SQL statements, review the [SQLite Tutorial][] to learn the basics before completing this recipe. This recipe uses the following steps: 1. Add the dependencies. 2. Define the `Dog` data model. 3. Open the database. 4. Create the `dogs` table. 5. Insert a `Dog` into the database. 6. Retrieve the list of dogs. 7. Update a `Dog` in the database. 7. Delete a `Dog` from the database. ## 1. Add the dependencies To work with SQLite databases, import the `sqflite` and `path` packages. * The `sqflite` package provides classes and functions to interact with a SQLite database. * The `path` package provides functions to define the location for storing the database on disk. To add the packages as a dependency, run `flutter pub add`: ```terminal $ flutter pub add sqflite path ``` Make sure to import the packages in the file you'll be working in. <?code-excerpt "lib/main.dart (imports)"?> ```dart import 'dart:async'; import 'package:flutter/widgets.dart'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; ``` ## 2. Define the Dog data model Before creating the table to store information on Dogs, take a few moments to define the data that needs to be stored. For this example, define a Dog class that contains three pieces of data: A unique `id`, the `name`, and the `age` of each dog. <?code-excerpt "lib/step2.dart"?> ```dart class Dog { final int id; final String name; final int age; const Dog({ required this.id, required this.name, required this.age, }); } ``` ## 3. Open the database Before reading and writing data to the database, open a connection to the database. This involves two steps: 1. Define the path to the database file using `getDatabasesPath()` from the `sqflite` package, combined with the `join` function from the `path` package. 2. Open the database with the `openDatabase()` function from `sqflite`. {{site.alert.note}} In order to use the keyword `await`, the code must be placed inside an `async` function. You should place all the following table functions inside `void main() async {}`. {{site.alert.end}} <?code-excerpt "lib/step3.dart (openDatabase)"?> ```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'), ); ``` ## 4. Create the `dogs` table Next, create a table to store information about various Dogs. For this example, create a table called `dogs` that defines the data that can be stored. Each `Dog` contains an `id`, `name`, and `age`. Therefore, these are represented as three columns in the `dogs` table. 1. The `id` is a Dart `int`, and is stored as an `INTEGER` SQLite Datatype. It is also good practice to use an `id` as the primary key for the table to improve query and update times. 2. The `name` is a Dart `String`, and is stored as a `TEXT` SQLite Datatype. 3. The `age` is also a Dart `int`, and is stored as an `INTEGER` Datatype. For more information about the available Datatypes that can be stored in a SQLite database, see the [official SQLite Datatypes documentation][]. <?code-excerpt "lib/main.dart (openDatabase)"?> ```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, ); ``` ## 5. Insert a Dog into the database Now that you have a database with a table suitable for storing information about various dogs, it's time to read and write data. First, insert a `Dog` into the `dogs` table. This involves two steps: 1. Convert the `Dog` into a `Map` 2. Use the [`insert()`][] method to store the `Map` in the `dogs` table. <?code-excerpt "lib/main.dart (Dog)"?> ```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<String, Object?> 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}'; } } ``` <?code-excerpt "lib/main.dart (insertDog)"?> ```dart // Define a function that inserts dogs into the database Future<void> 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, ); } ``` <?code-excerpt "lib/main.dart (fido)"?> ```dart // Create a Dog and add it to the dogs table var fido = Dog( id: 0, name: 'Fido', age: 35, ); await insertDog(fido); ``` ## 6. Retrieve the list of Dogs Now that a `Dog` is stored in the database, query the database for a specific dog or a list of all dogs. This involves two steps: 1. Run a `query` against the `dogs` table. This returns a `List<Map>`. 2. Convert the `List<Map>` into a `List<Dog>`. <?code-excerpt "lib/main.dart (dogs)"?> ```dart // A method that retrieves all the dogs from the dogs table. Future<List<Dog>> dogs() async { // Get a reference to the database. final db = await database; // Query the table for all the dogs. final List<Map<String, Object?>> 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), ]; } ``` <?code-excerpt "lib/main.dart (print)"?> ```dart // Now, use the method above to retrieve all the dogs. print(await dogs()); // Prints a list that include Fido. ``` ## 7. Update a `Dog` in the database After inserting information into the database, you might want to update that information at a later time. You can do this by using the [`update()`][] method from the `sqflite` library. This involves two steps: 1. Convert the Dog into a Map. 2. Use a `where` clause to ensure you update the correct Dog. <?code-excerpt "lib/main.dart (update)"?> ```dart Future<void> 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], ); } ``` <?code-excerpt "lib/main.dart (update2)"?> ```dart // 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. ``` {{site.alert.warning}} Always use `whereArgs` to pass arguments to a `where` statement. This helps safeguard against SQL injection attacks. Do not use string interpolation, such as `where: "id = ${dog.id}"`! {{site.alert.end}} ## 8. Delete a `Dog` from the database In addition to inserting and updating information about Dogs, you can also remove dogs from the database. To delete data, use the [`delete()`][] method from the `sqflite` library. In this section, create a function that takes an id and deletes the dog with a matching id from the database. To make this work, you must provide a `where` clause to limit the records being deleted. <?code-excerpt "lib/main.dart (deleteDog)"?> ```dart Future<void> 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], ); } ``` ## Example To run the example: 1. Create a new Flutter project. 2. Add the `sqflite` and `path` packages to your `pubspec.yaml`. 3. Paste the following code into a new file called `lib/db_test.dart`. 4. Run the code with `flutter run lib/db_test.dart`. <?code-excerpt "lib/main.dart"?> ```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<void> 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<List<Dog>> dogs() async { // Get a reference to the database. final db = await database; // Query the table for all the dogs. final List<Map<String, Object?>> 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<void> 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<void> 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<String, Object?> 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}'; } } ``` [`delete()`]: {{site.pub-api}}/sqflite_common/latest/sqlite_api/DatabaseExecutor/delete.html [`insert()`]: {{site.pub-api}}/sqflite_common/latest/sqlite_api/DatabaseExecutor/insert.html [`sqflite`]: {{site.pub-pkg}}/sqflite [SQLite Tutorial]: http://www.sqlitetutorial.net/ [official SQLite Datatypes documentation]: https://www.sqlite.org/datatype3.html [`update()`]: {{site.pub-api}}/sqflite_common/latest/sqlite_api/DatabaseExecutor/update.html
website/src/cookbook/persistence/sqlite.md/0
{ "file_path": "website/src/cookbook/persistence/sqlite.md", "repo_id": "website", "token_count": 4896 }
1,366
--- title: Tap, drag, and enter text description: How to test widgets for user interaction. --- <?code-excerpt path-base="cookbook/testing/widget/tap_drag/"?> {% assign api = site.api | append: '/flutter' -%} Many widgets not only display information, but also respond to user interaction. This includes buttons that can be tapped, and [`TextField`][] for entering text. To test these interactions, you need a way to simulate them in the test environment. For this purpose, use the [`WidgetTester`][] library. The `WidgetTester` provides methods for entering text, tapping, and dragging. * [`enterText()`][] * [`tap()`][] * [`drag()`][] In many cases, user interactions update the state of the app. In the test environment, Flutter doesn't automatically rebuild widgets when the state changes. To ensure that the widget tree is rebuilt after simulating a user interaction, call the [`pump()`][] or [`pumpAndSettle()`][] methods provided by the `WidgetTester`. This recipe uses the following steps: 1. Create a widget to test. 2. Enter text in the text field. 3. Ensure tapping a button adds the todo. 4. Ensure swipe-to-dismiss removes the todo. ### 1. Create a widget to test For this example, create a basic todo app that tests three features: 1. Entering text into a `TextField`. 2. Tapping a `FloatingActionButton` to add the text to a list of todos. 3. Swiping-to-dismiss to remove the item from the list. To keep the focus on testing, this recipe won't provide a detailed guide on how to build the todo app. To learn more about how this app is built, see the relevant recipes: * [Create and style a text field][] * [Handle taps][] * [Create a basic list][] * [Implement swipe to dismiss][] <?code-excerpt "test/main_test.dart (TodoList)"?> ```dart class TodoList extends StatefulWidget { const TodoList({super.key}); @override State<TodoList> createState() => _TodoListState(); } class _TodoListState extends State<TodoList> { static const _appTitle = 'Todo List'; final todos = <String>[]; 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), ), ), ); } } ``` ### 2. Enter text in the text field Now that you have a todo app, begin writing the test. Start by entering text into the `TextField`. Accomplish this task by: 1. Building the widget in the test environment. 2. Using the [`enterText()`][] method from the `WidgetTester`. <?code-excerpt "test/main_steps.dart (TestWidgetStep2)"?> ```dart 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'); }); ``` {{site.alert.note}} This recipe builds upon previous widget testing recipes. To learn the core concepts of widget testing, see the following recipes: * [Introduction to widget testing][] * [Finding widgets in a widget test][] {{site.alert.end}} ### 3. Ensure tapping a button adds the todo After entering text into the `TextField`, ensure that tapping the `FloatingActionButton` adds the item to the list. This involves three steps: 1. Tap the add button using the [`tap()`][] method. 2. Rebuild the widget after the state has changed using the [`pump()`][] method. 3. Ensure that the list item appears on screen. <?code-excerpt "test/main_steps.dart (TestWidgetStep3)"?> ```dart testWidgets('Add and remove a todo', (tester) async { // Enter text code... // Tap the add button. await tester.tap(find.byType(FloatingActionButton)); // Rebuild the widget after the state has changed. await tester.pump(); // Expect to find the item on screen. expect(find.text('hi'), findsOneWidget); }); ``` ### 4. Ensure swipe-to-dismiss removes the todo Finally, ensure that performing a swipe-to-dismiss action on the todo item removes it from the list. This involves three steps: 1. Use the [`drag()`][] method to perform a swipe-to-dismiss action. 2. Use the [`pumpAndSettle()`][] method to continually rebuild the widget tree until the dismiss animation is complete. 3. Ensure that the item no longer appears on screen. <?code-excerpt "test/main_steps.dart (TestWidgetStep4)"?> ```dart testWidgets('Add and remove a todo', (tester) async { // Enter text and add the item... // 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); }); ``` ### Complete example <?code-excerpt "test/main_test.dart"?> ```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<TodoList> createState() => _TodoListState(); } class _TodoListState extends State<TodoList> { static const _appTitle = 'Todo List'; final todos = <String>[]; 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), ), ), ); } } ``` [Create a basic list]: /cookbook/lists/basic-list [Create and style a text field]: /cookbook/forms/text-input [`drag()`]: {{api}}/flutter_test/WidgetController/drag.html [`enterText()`]: {{api}}/flutter_test/WidgetTester/enterText.html [Finding widgets in a widget test]: /cookbook/testing/widget/finders [Handle taps]: /cookbook/gestures/handling-taps [Implement swipe to dismiss]: /cookbook/gestures/dismissible [Introduction to widget testing]: /cookbook/testing/widget/introduction [`pump()`]: {{api}}/flutter_test/WidgetTester/pump.html [`pumpAndSettle()`]: {{api}}/flutter_test/WidgetTester/pumpAndSettle.html [`tap()`]: {{api}}/flutter_test/WidgetController/tap.html [`TextField`]: {{api}}/material/TextField-class.html [`WidgetTester`]: {{api}}/flutter_test/WidgetTester-class.html
website/src/cookbook/testing/widget/tap-drag.md/0
{ "file_path": "website/src/cookbook/testing/widget/tap-drag.md", "repo_id": "website", "token_count": 3469 }
1,367
--- title: Continuous delivery with Flutter description: > How to automate continuous building and releasing of your Flutter app. --- Follow continuous delivery best practices with Flutter to make sure your application is delivered to your beta testers and validated on a frequent basis without resorting to manual workflows. ## CI/CD Options There are a number of continuous integration (CI) and continuous delivery (CD) options available to help automate the delivery of your application. ### All-in-one options with built-in Flutter functionality * [Codemagic][] * [Bitrise][] * [Appcircle][] ### Integrating fastlane with existing workflows You can use fastlane with the following tooling: * [GitHub Actions][] * Example: [Github Action in Flutter Project][] * [Cirrus][] * [Travis][] * [GitLab][] * [CircleCI][] * [Building and deploying Flutter apps with Fastlane][] This guide shows how to set up fastlane and then integrate it with your existing testing and continuous integration (CI) workflows. For more information, see "Integrating fastlane with existing workflow". ## fastlane [fastlane][] is an open-source tool suite to automate releases and deployments for your app. ### Local setup It's recommended that you test the build and deployment process locally before migrating to a cloud-based system. You could also choose to perform continuous delivery from a local machine. 1. Install fastlane `gem install fastlane` or `brew install fastlane`. Visit the [fastlane docs][fastlane] for more info. 1. Create an environment variable named `FLUTTER_ROOT`, and set it to the root directory of your Flutter SDK. (This is required for the scripts that deploy for iOS.) 1. Create your Flutter project, and when ready, make sure that your project builds via * ![Android](/assets/images/docs/cd/android.png) `flutter build appbundle`; and * ![iOS](/assets/images/docs/cd/ios.png) `flutter build ipa`. 1. Initialize the fastlane projects for each platform. * ![Android](/assets/images/docs/cd/android.png) In your `[project]/android` directory, run `fastlane init`. * ![iOS](/assets/images/docs/cd/ios.png) In your `[project]/ios` directory, run `fastlane init`. 1. Edit the `Appfile`s to ensure they have adequate metadata for your app. * ![Android](/assets/images/docs/cd/android.png) Check that `package_name` in `[project]/android/fastlane/Appfile` matches your package name in AndroidManifest.xml. * ![iOS](/assets/images/docs/cd/ios.png) Check that `app_identifier` in `[project]/ios/fastlane/Appfile` also matches Info.plist's bundle identifier. Fill in `apple_id`, `itc_team_id`, `team_id` with your respective account info. 1. Set up your local login credentials for the stores. * ![Android](/assets/images/docs/cd/android.png) Follow the [Supply setup steps][] and ensure that `fastlane supply init` successfully syncs data from your Play Store console. _Treat the .json file like your password and do not check it into any public source control repositories._ * ![iOS](/assets/images/docs/cd/ios.png) Your iTunes Connect username is already in your `Appfile`'s `apple_id` field. Set the `FASTLANE_PASSWORD` shell environment variable with your iTunes Connect password. Otherwise, you'll be prompted when uploading to iTunes/TestFlight. 1. Set up code signing. * ![Android](/assets/images/docs/cd/android.png) Follow the [Android app signing steps][]. * ![iOS](/assets/images/docs/cd/ios.png) On iOS, create and sign using a distribution certificate instead of a development certificate when you're ready to test and deploy using TestFlight or App Store. * Create and download a distribution certificate in your [Apple Developer Account console][]. * `open [project]/ios/Runner.xcworkspace/` and select the distribution certificate in your target's settings pane. 1. Create a `Fastfile` script for each platform. * ![Android](/assets/images/docs/cd/android.png) On Android, follow the [fastlane Android beta deployment guide][]. Your edit could be as simple as adding a `lane` that calls `upload_to_play_store`. Set the `aab` argument to `../build/app/outputs/bundle/release/app-release.aab` to use the app bundle `flutter build` already built. * ![iOS](/assets/images/docs/cd/ios.png) On iOS, follow the [fastlane iOS beta deployment guide][]. You can specify the archive path to avoid rebuilding the project. For example: ```ruby build_app( skip_build_archive: true, archive_path: "../build/ios/archive/Runner.xcarchive", ) upload_to_testflight ``` You're now ready to perform deployments locally or migrate the deployment process to a continuous integration (CI) system. ### Running deployment locally 1. Build the release mode app. * ![Android](/assets/images/docs/cd/android.png) `flutter build appbundle`. * ![iOS](/assets/images/docs/cd/ios.png) `flutter build ipa`. 1. Run the Fastfile script on each platform. * ![Android](/assets/images/docs/cd/android.png) `cd android` then `fastlane [name of the lane you created]`. * ![iOS](/assets/images/docs/cd/ios.png) `cd ios` then `fastlane [name of the lane you created]`. ### Cloud build and deploy setup First, follow the local setup section described in 'Local setup' to make sure the process works before migrating onto a cloud system like Travis. The main thing to consider is that since cloud instances are ephemeral and untrusted, you won't be leaving your credentials like your Play Store service account JSON or your iTunes distribution certificate on the server. Continuous Integration (CI) systems generally support encrypted environment variables to store private data. You can pass these environment variables using `--dart-define MY_VAR=MY_VALUE` while building the app. **Take precaution not to re-echo those variable values back onto the console in your test scripts**. Those variables are also not available in pull requests until they're merged to ensure that malicious actors cannot create a pull request that prints these secrets out. Be careful with interactions with these secrets in pull requests that you accept and merge. 1. Make login credentials ephemeral. * ![Android](/assets/images/docs/cd/android.png) On Android: * Remove the `json_key_file` field from `Appfile` and store the string content of the JSON in your CI system's encrypted variable. Read the environment variable directly in your `Fastfile`. ``` upload_to_play_store( ... json_key_data: ENV['<variable name>'] ) ``` * Serialize your upload key (for example, using base64) and save it as an encrypted environment variable. You can deserialize it on your CI system during the install phase with ```bash echo "$PLAY_STORE_UPLOAD_KEY" | base64 --decode > [path to your upload keystore] ``` * ![iOS](/assets/images/docs/cd/ios.png) On iOS: * Move the local environment variable `FASTLANE_PASSWORD` to use encrypted environment variables on the CI system. * The CI system needs access to your distribution certificate. fastlane's [Match][] system is recommended to synchronize your certificates across machines. 2. It's recommended to use a Gemfile instead of using an indeterministic `gem install fastlane` on the CI system each time to ensure the fastlane dependencies are stable and reproducible between local and cloud machines. However, this step is optional. * In both your `[project]/android` and `[project]/ios` folders, create a `Gemfile` containing the following content: ``` source "https://rubygems.org" gem "fastlane" ``` * In both directories, run `bundle update` and check both `Gemfile` and `Gemfile.lock` into source control. * When running locally, use `bundle exec fastlane` instead of `fastlane`. 3. Create the CI test script such as `.travis.yml` or `.cirrus.yml` in your repository root. * See [fastlane CI documentation][] for CI specific setup. * Shard your script to run on both Linux and macOS platforms. * During the setup phase of the CI task, do the following: * Ensure Bundler is available using `gem install bundler`. * Run `bundle install` in `[project]/android` or `[project]/ios`. * Make sure the Flutter SDK is available and set in `PATH`. * For Android, ensure the Android SDK is available and the `ANDROID_SDK_ROOT` path is set. * For iOS, you might have to specify a dependency on Xcode (for example, `osx_image: xcode9.2`). * In the script phase of the CI task: * Run `flutter build appbundle` or `flutter build ios --release --no-codesign`, depending on the platform. * `cd android` or `cd ios` * `bundle exec fastlane [name of the lane]` ## Xcode Cloud [Xcode Cloud][] is a continuous integration and delivery service for building, testing, and distributing apps and frameworks for Apple platforms. ### Requirements * Xcode 13.4.1 or higher. * Be enrolled in the [Apple Developer Program][]. ### Custom build script Xcode Cloud recognizes [custom build scripts][] that can be used to perform additional tasks at a designated time. It also includes a set of [predefined environment variables][], such as `$CI_WORKSPACE`, which is the location of your cloned repository. {{site.alert.note}} The temporary build environment that Xcode Cloud uses includes tools that are part of macOS and Xcode&mdash;for example, Python&mdash;and additionally Homebrew to support installing third-party dependencies and tools. {{site.alert.end}} #### Post-clone script Leverage the post-clone custom build script that runs after Xcode Cloud clones your Git repository using the following instructions: Create a file at `ios/ci_scripts/ci_post_clone.sh` and add the content below. <?code-excerpt "deployment/xcode_cloud/ci_post_clone.sh"?> ```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 ``` This file should be added to your git repository and marked as executable. ```terminal $ git add --chmod=+x ios/ci_scripts/ci_post_clone.sh ``` ### Workflow configuration An [Xcode Cloud workflow][] defines the steps performed in the CI/CD process when your workflow is triggered. {{site.alert.note}} This requires that your project is already initialized with Git and linked to a remote repository. {{site.alert.end}} To create a new workflow in Xcode, use the following instructions: 1. Choose **Product > Xcode Cloud > Create Workflow** to open the **Create Workflow** sheet. 2. Select the product (app) that the workflow should be attached to, then click the **Next** button. 3. The next sheet displays an overview of the default workflow provided by Xcode, and can be customized by clicking the **Edit Workflow** button. #### Branch changes By default Xcode suggests the Branch Changes condition that starts a new build for every change to your Git repository's default branch. For your app's iOS variant, it's reasonable that you would want Xcode Cloud to trigger your workflow after you've made changes to your flutter packages, or modified either the Dart or iOS source files within the `lib\` and `ios\` directories. This can be achieved by using the following Files and Folders conditions: ![Xcode Workflow Branch Changes](/assets/images/docs/releaseguide/xcode_workflow_branch_changes.png){:width="100%"} ### Next build number Xcode Cloud defaults the build number for new workflows to `1` and increments it per successful build. If you're using an existing app with a higher build number, you'll need to configure Xcode Cloud to use the correct build number for its builds by simply specifying the `Next Build Number` in your iteration. Check out [Setting the next build number for Xcode Cloud builds][] for more information. [Android app signing steps]: /deployment/android#signing-the-app [Appcircle]: https://appcircle.io/blog/guide-to-automated-mobile-ci-cd-for-flutter-projects-with-appcircle/ [Apple Developer Account console]: {{site.apple-dev}}/account/ios/certificate/ [Bitrise]: https://devcenter.bitrise.io/en/getting-started/quick-start-guides/getting-started-with-flutter-apps [CI Options and Examples]: #reference-and-examples [Cirrus]: https://cirrus-ci.org [Cirrus script]: {{site.repo.flutter}}/blob/master/.cirrus.yml [Codemagic]: https://blog.codemagic.io/getting-started-with-codemagic/ [fastlane]: https://docs.fastlane.tools [fastlane Android beta deployment guide]: https://docs.fastlane.tools/getting-started/android/beta-deployment/ [fastlane CI documentation]: https://docs.fastlane.tools/best-practices/continuous-integration [fastlane iOS beta deployment guide]: https://docs.fastlane.tools/getting-started/ios/beta-deployment/ [Github Action in Flutter Project]: {{site.github}}/nabilnalakath/flutter-githubaction [GitHub Actions]: {{site.github}}/features/actions [GitLab]: https://docs.gitlab.com/ee/ci/README.html#doc-nav [CircleCI]: https://circleci.com [Building and deploying Flutter apps with Fastlane]: https://circleci.com/blog/deploy-flutter-android [Match]: https://docs.fastlane.tools/actions/match/ [Supply setup steps]: https://docs.fastlane.tools/getting-started/android/setup/#setting-up-supply [Travis]: https://travis-ci.org/ [Apple Developer Program]: {{site.apple-dev}}/programs [Xcode Cloud]: {{site.apple-dev}}/xcode-cloud [Xcode Cloud workflow]: {{site.apple-dev}}/documentation/xcode/xcode-cloud-workflow-reference [custom build scripts]: {{site.apple-dev}}/documentation/xcode/writing-custom-build-scripts [predefined environment variables]: {{site.apple-dev}}/documentation/xcode/environment-variable-reference [Setting the next build number for Xcode Cloud builds]: {{site.apple-dev}}/documentation/xcode/setting-the-next-build-number-for-xcode-cloud-builds#Set-the-next-build-number-to-a-custom-value
website/src/deployment/cd.md/0
{ "file_path": "website/src/deployment/cd.md", "repo_id": "website", "token_count": 4597 }
1,368
--- title: Flutter concurrency for Swift developers description: > Leverage your Swift concurrency knowledge while learning Flutter and Dart. --- <?code-excerpt path-base="resources/dart_swift_concurrency"?> Both Dart and Swift support concurrent programming. This guide should help you understand how concurrency works in Dart and how it compares to Swift. With this understanding, you can create high-performing iOS apps. When developing in the Apple ecosystem, some tasks might take a long time to complete. These tasks include fetching or processing large amounts of data. iOS developers typically use Grand Central Dispatch (GCD) to schedule tasks using a shared thread pool. With GCD, developers add tasks to dispatch queues and GCD decides on which thread to execute them. But, GCD spins up threads to handle remaining work items. This means you can end up with a large number of threads and the system can become over committed. With Swift, the structured concurrency model reduced the number of threads and context switches. Now, each core has only one thread. Dart has a single-threaded execution model, with support for `Isolates`, an event loop, and asynchronous code. An `Isolate` is Dart's implementation of a lightweight thread. Unless you spawn an `Isolate`, your Dart code runs in the main UI thread driven by an event loop. Flutter's event loop is equivalent to the iOS main loop—in other words, the Looper attached to the main thread. Dart's single-threaded model doesn't mean you are required to run everything as a blocking operation that causes the UI to freeze. Instead, use the asynchronous features that the Dart language provides, such as `async`/`await`. ### Asynchronous Programming An asynchronous operation allows other operations to execute before it completes. Both Dart and Swift support asynchronous functions using the `async` and `await` keywords. In both cases, `async` marks that a function performs asynchronous work, and `await` tells the system to await a result from function. This means that the Dart VM _could_ suspend the function, if necessary. For more details on asynchronous programming, check out [Concurrency in Dart]({{site.dart-site}}/guides/language/concurrency). ### Leveraging the main thread/isolate For Apple operating systems, the primary (also called the main) thread is where the application begins running. Rendering the user interface always happens on the main thread. One difference between Swift and Dart is that Swift might use different threads for different tasks, and Swift doesn't guarantee which thread is used. So, when dispatching UI updates in Swift, you might need to ensure that the work occurs on the main thread. Say you want to write a function that fetches the weather asynchronously and displays the results. In GCD, to manually dispatch a process to the main thread, you might do something like the following. First, define the `Weather` `enum`: ```swift // 1 second delay is used in mocked API call. extension UInt64 { static let oneSecond = UInt64(1_000_000_000) } enum Weather: String { case rainy, sunny } ``` Next, define the view model and mark it as an `ObservableObject` so that it can return a value of type `Weather?`. Use GCD create to a `DispatchQueue` to send the work to the pool of threads ```swift class ContentViewModel: ObservableObject { @Published private(set) var result: Weather? private let queue = DispatchQueue(label: "weather_io_queue") func load() { // Mimic 1 sec delay. queue.asyncAfter(deadline: .now() + 1) { [weak self] in DispatchQueue.main.async { self?.result = .sunny } } } } ``` Finally, display the results: ```swift struct ContentView: View { @StateObject var viewModel = ContentViewModel() var body: some View { Text(viewModel.result?.rawValue ?? "Loading") .onAppear { viewModel.load() } } } ``` More recently, Swift introduced _actors_ to support synchronization for shared, mutable state. To ensure that work is performed on the main thread, define a view model class that is marked as a `@MainActor`, with a `load()` function that internally calls an asynchronous function using `Task`. ```swift @MainActor class ContentViewModel: ObservableObject { @Published private(set) var result: Weather? func load() async { try? await Task.sleep(nanoseconds: .oneSecond) self.result = .sunny } } ``` Next, define the view model as a state object using `@StateObject`, with a `load()` function that can be called by the view model: ```swift struct ContentView: View { @StateObject var viewModel = ContentViewModel() var body: some View { Text(viewModel.result?.rawValue ?? "Loading...") .task { await viewModel.load() } } } ``` In Dart, all work runs on the main isolate by default. To implement the same example in Dart, first, create the `Weather` `enum`: <?code-excerpt "lib/async_weather.dart (Weather)"?> ```dart enum Weather { rainy, windy, sunny, } ``` Then, define a simple view model (similar to what was created in SwiftUI), to fetch the weather. In Dart, a `Future` object represents a value to be provided in the future. A `Future` is similar to Swift's `ObservableObject`. In this example, a function within the view model returns a `Future<Weather>` object: <?code-excerpt "lib/async_weather.dart (HomePageViewModel)"?> ```dart @immutable class HomePageViewModel { const HomePageViewModel(); Future<Weather> load() async { await Future.delayed(const Duration(seconds: 1)); return Weather.sunny; } } ``` The `load()` function in this example shares similarities with the Swift code. The Dart function is marked as `async` because it uses the `await` keyword. Additionally, a Dart function marked as `async` automatically returns a `Future`. In other words, you don't have to create a `Future` instance manually inside functions marked as `async`. For the last step, display the weather value. In Flutter, [`FutureBuilder`]({{site.api}}/flutter/widgets/FutureBuilder-class.html) and [`StreamBuilder`]({{site.api}}/flutter/widgets/StreamBuilder-class.html) widgets are used to display the results of a Future in the UI. The following example uses a `FutureBuilder`: <?code-excerpt "lib/async_weather.dart (HomePageWidget)"?> ```dart class HomePage extends StatelessWidget { const HomePage({super.key}); final HomePageViewModel viewModel = const HomePageViewModel(); @override Widget build(BuildContext context) { return CupertinoPageScaffold( // Feed a FutureBuilder to your widget tree. child: FutureBuilder<Weather>( // Specify the Future that you want to track. future: viewModel.load(), builder: (context, snapshot) { // A snapshot is of type `AsyncSnapshot` and contains the // state of the Future. By looking if the snapshot contains // an error or if the data is null, you can decide what to // show to the user. if (snapshot.hasData) { return Center( child: Text( snapshot.data.toString(), ), ); } else { return const Center( child: CupertinoActivityIndicator(), ); } }, ), ); } } ``` For the complete example, check out the [async_weather][] file on GitHub. [async_weather]: {{site.repo.this}}/examples/resources/lib/async_weather.dart ### Leveraging a background thread/isolate Flutter apps can run on a variety of multi-core hardware, including devices running macOS and iOS. To improve the performance of these applications, you must sometimes run tasks on different cores concurrently. This is especially important to avoid blocking UI rendering with long-running operations. In Swift, you can leverage GCD to run tasks on global queues with different quality of service class (qos) properties. This indicates the task's priority. ```swift func parse(string: String, completion: @escaping ([String:Any]) -> Void) { // Mimic 1 sec delay. DispatchQueue(label: "data_processing_queue", qos: .userInitiated) .asyncAfter(deadline: .now() + 1) { let result: [String:Any] = ["foo": 123] completion(result) } } } ``` In Dart, you can offload computation to a worker isolate, often called a background worker. A common scenario spawns a simple worker isolate and returns the results in a message when the worker exits. As of Dart 2.19, you can use `Isolate.run()` to spawn an isolate and run computations: ```dart void main() async { // Read some data. final jsonData = await Isolate.run(() => jsonDecode(jsonString) as Map<String, dynamic>);` // Use that data. print('Number of JSON keys: ${jsonData.length}'); } ``` In Flutter, you can also use the `compute` function to spin up an isolate to run a callback function: ```dart final jsonData = await compute(getNumberOfKeys, jsonString); ``` In this case, the callback function is a top-level function as shown below: ```dart Map<String, dynamic> getNumberOfKeys(String jsonString) { return jsonDecode(jsonString); } ``` You can find more information on Dart at [Learning Dart as a Swift developer][], and more information on Flutter at [Flutter for SwiftUI developers][] or [Flutter for UIKit developers][]. [Learning Dart as a Swift developer]: {{site.dart-site}}/guides/language/coming-from/swift-to-dart [Flutter for SwiftUI developers]: /get-started/flutter-for/swiftui-devs [Flutter for UIKit developers]: /get-started/flutter-for/uikit-devs
website/src/get-started/flutter-for/dart-swift-concurrency.md/0
{ "file_path": "website/src/get-started/flutter-for/dart-swift-concurrency.md", "repo_id": "website", "token_count": 3087 }
1,369
## Configuring Android app support {{site.alert.note}} Flutter relies on a full installation of Android Studio to supply its Android platform dependencies. However, you can write your Flutter apps in a number of editors; a later step discusses that. {{site.alert.end}} ### Install Android Studio 1. Download and install [Android Studio]({{site.android-dev}}/studio/install#chrome-os). 1. Start Android Studio, and go through the 'Android Studio Setup Wizard'. This installs the latest Android SDK, platform tools and build tooling that are required by Flutter when developing for Android. 1. From the welcome dialog, choose **More Actions -> SDK Manager**. From the SDK Tools tab, select **Android SDK Command-line Tools (latest)** to install additional necessary tooling. 1. Accept Android licenses. ```terminal $ flutter doctor --android-licenses ``` ### Deploy to your Chromebook To deploy apps directly to your Chromebook, you need to do the following: 1. [Enable ADB][] in Settings. Note that this requires you to reboot your device once. 1. In the Terminal, run `flutter devices`. If prompted, authorize access to the Android container. Verify that `flutter devices` lists your ChromeOS device as a recognized device. ### Set up your Android device To prepare to run and test your Flutter app on an attached device, you need an Android device running Android 5.0 (API level 21) or higher. 1. Enable **Developer options** and **USB debugging** on your device. Detailed instructions are available in the [Android documentation]({{site.android-dev}}/studio/debug/dev-options). 1. Using a USB cable, plug your phone into your computer. On your Chromebook, you might see a notification for "USB device detected". Click on "Connect to Linux". If prompted on your Android device, authorize your computer to access your device. 1. In the terminal, run the `flutter devices` command to verify that Flutter recognizes your connected Android device. By default, Flutter uses the version of the Android SDK where your `adb` tool is based. If you want Flutter to use a different installation of the Android SDK, you must set the `ANDROID_SDK_ROOT` environment variable to that installation directory. [Enable ADB]: https://support.google.com/chromebook/answer/9770692
website/src/get-started/install/_deprecated/_android-setup-chromeos.md/0
{ "file_path": "website/src/get-started/install/_deprecated/_android-setup-chromeos.md", "repo_id": "website", "token_count": 627 }
1,370
--- title: Install help description: This page describes some common installation issues new Flutter users have run into and offers suggestions to resolve them. --- This page describes some common installation issues new Flutter users have encountered and offers suggestions on how to resolve them. If you are still experiencing problems, consider reaching out to any of the resources listed under [community support channels][]. To add a topic to this page or make a correction, you can file an issue or a pull request using the buttons at the top of the page. ## Get the Flutter SDK ### Unable to find the `flutter` command __What does this issue look like?__ When you try to run the `flutter` command, the console fails to find it. The error usually looks as follows: ``` 'flutter' is not recognized as an internal or external command operable program or batch file ``` Error messages on macOS and Linux could look slightly different from the one on Windows. __Explanation and suggestions__ Did you add Flutter to the `PATH` environment variable for your platform? On Windows, follow these [instructions for adding a command to your path][windows path]. If you've already [set up VS Code][] for Flutter development, you can use the Flutter extension's **Locate SDK** prompt to identify the location of your `flutter` folder. See also: [Configuring PATH and Environment Variables - Dart Code][config path] ### Flutter in special folders __What does this issue look like?__ Running your Flutter project produces an error like the following: ``` 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. ``` __Explanation and suggestions__ On Windows, this usually happens when Flutter is installed in a directory like `C:\Program Files\` that requires elevated privileges. Try relocating Flutter to a different folder, such as `C:\src\flutter`. ## Android setup ### Having multiple versions of Java installed __What does this issue look like?__ The command `flutter doctor --android-licenses` fails. Running `flutter doctor –verbose` gives an error message like the following: ``` java.lang.UnsupportedClassVersionError: com/android/prefs/AndroidLocationsProvider has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0 ``` __Explanation and suggestions__ The error occurs when an older version of the Java Development Kit (JDK) is installed on your computer. If you don't need multiple versions of Java, uninstall existing JDKs from your computer. Flutter automatically uses the JDK included in Android Studio. If you do need another version of Java, try the workaround described in [this GitHub issue][java binary path] until a long-term solution is implemented. For more information, check out the [Android Java Gradle migration guide][] or [flutter doctor --android-licenses not working due to java.lang.UnsupportedClassVersionError - Stack Overflow][so java version]. ### `cmdline-tools` component is missing __What does this issue look like?__ The `flutter doctor` command complains that the `cmdline-tools` are missing from the Android toolchain. For example: ``` [!] 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 ``` __Explanation and suggestions__ The easiest way to get the cmdline-tools is through the SDK Manager in Android Studio. To do this, use the following instructions: 1. Open the SDK Manager from Android Studio, by selecting **Tools > SDK Manager** from the menu bar. 2. Select the latest Android SDK (or a specific version that your app requires), Android SDK Command-line Tools, and Android SDK Build-Tools. 3. Click **Apply** to install the selected artifacts. ![Android Studio SDK Manager](/assets/images/docs/get-started/install_android_tools.png) If you're not using Android Studio, you can download the tools using the [sdkmanager][] command-line tool. ## Other problems ### Exit code 69 __What does this issue look like?__ Running a `flutter` command produces an "exit code: 69" error, as shown in the following example: ``` 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 ``` __Explanation and suggestions__ This issue is related to networking. Try the following instructions to troubleshoot: * Check your internet connection. Make sure that you are connected to the internet and that your connection is stable. * Restart your devices, including your computer and networking equipment. * Use a VPN to help to bypass any restrictions that might prevent you from connecting to the network. * If you have tried all of these steps and are still getting the error, print out verbose logs with the `flutter doctor -v` command and ask for help in one of the [community support channels][]. ## Community support The Flutter community is helpful and welcoming. If none of the above suggestions solves your installation issue, consider asking for support from one of the following channels: * [/r/flutterhelp](https://www.reddit.com/r/flutterhelp/) on Reddit * [/r/flutterdev](https://discord.gg/rflutterdev) on Discord, particularly the `install-and-setup` channel on this server. * [StackOverflow][], in particular, questions tagged with [#flutter][] or [#dart][]. To be respectful of everyone's time, search the archive for a similar issue before posting a new one. [StackOverflow]: {{site.so}} [#dart]: {{site.so}}/questions/tagged/dart [#flutter]: {{site.so}}/questions/tagged/flutter [Android Java Gradle migration guide]: /release/breaking-changes/android-java-gradle-migration-guide [community support channels]: #community-support [java binary path]: {{site.repo.flutter}}/issues/106416#issuecomment-1522198064 [so java version]: {{site.so}}/questions/75328050/ [set up VS Code]: /get-started/editor [config path]: https://dartcode.org/docs/configuring-path-and-environment-variables/ [sdkmanager]: {{site.android-dev}}/studio/command-line/sdkmanager [windows path]: https://www.wikihow.com/Change-the-PATH-Environment-Variable-on-Windows
website/src/get-started/install/help.md/0
{ "file_path": "website/src/get-started/install/help.md", "repo_id": "website", "token_count": 1846 }
1,371
--- title: Test drive description: How to create a templated Flutter app and use hot reload. prev: title: Install Flutter path: /get-started/install next: title: Write your first Flutter app path: /get-started/codelab toc: false --- {% case os %} {% when 'Windows' -%} {% assign path='C:\dev\' %} {% assign terminal='PowerShell' %} {% assign prompt1='D:>' %} {% assign prompt2=path | append: '>' %} {% assign dirdl='%CSIDL_DEFAULT_DOWNLOADS%\' %} {% when "macOS" -%} {% assign path='~/development/' %} {% assign terminal='the Terminal' %} {% assign prompt1='$' %} {% assign prompt2='$' %} {% assign dirdl='~/Downloads/' %} {% else -%} {% assign path='/usr/bin/' %} {% assign terminal='a shell' %} {% assign prompt1='$' %} {% assign prompt2='$' %} {% assign dirdl='~/Downloads/' %} {% endcase -%} ## What you'll learn 1. How to create a new Flutter app from a sample template. 1. How to run the new Flutter app. 1. How to use "hot reload" after you make changes to the app. ## Guide depends on your IDE These tasks depend on which integrated development environment (IDE) you use. * **Option 1** explains how to code with Visual Studio Code and its Flutter extension. * **Option 2** explains how to code with Android Studio or IntelliJ IDEA with its Flutter plugin. Flutter supports IntelliJ IDEA Community, Educational, and Ultimate editions. * **Option 3** explains how to code with an editor of your choice and use the terminal to compile and debug your code. ## Choose your IDE Select your preferred IDE for Flutter apps. {% comment %} Nav tabs {% endcomment -%} <ul class="nav nav-tabs" id="editor-setup" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="vscode-tab" href="#vscode" role="tab" aria-controls="vscode" aria-selected="true">Visual Studio Code</a> </li> <li class="nav-item"> <a class="nav-link" id="androidstudio-tab" href="#androidstudio" role="tab" aria-controls="androidstudio" aria-selected="false">Android Studio and IntelliJ</a> </li> <li class="nav-item"> <a class="nav-link" id="terminal-tab" href="#terminal" role="tab" aria-controls="terminal" aria-selected="false">Terminal & editor</a> </li> </ul> {% comment %} Tab panes {% endcomment -%} <div class="tab-content"> {% include docs/install/test-drive/vscode.md %} {% include docs/install/test-drive/androidstudio.md %} {% include docs/install/test-drive/terminal.md %} </div>
website/src/get-started/test-drive/index.md/0
{ "file_path": "website/src/get-started/test-drive/index.md", "repo_id": "website", "token_count": 881 }
1,372
--- title: Performance description: Evaluating the performance of your app from several angles. --- <iframe width="560" height="315" src="{{site.yt.embed}}/PKGguGUwSYE" title="Learn tips to boost Flutter's performance" {{site.yt.set}}></iframe> [Flutter performance basics]({{site.yt.watch}}?v=PKGguGUwSYE) {{site.alert.note}} If your app has a performance issue and you are trying to debug it, check out the DevTool's page on [Using the Performance view][]. {{site.alert.end}} [Using the Performance view]: /tools/devtools/performance What is performance? Why is performance important? How do I improve performance? Our goal is to answer those three questions (mainly the third one), and anything related to them. This document should serve as the single entry point or the root node of a tree of resources that addresses any questions that you have about performance. The answers to the first two questions are mostly philosophical, and not as helpful to many developers who visit this page with specific performance issues that need to be solved. Therefore, the answers to those questions are in the [appendix](/perf/appendix). To improve performance, you first need metrics: some measurable numbers to verify the problems and improvements. In the [metrics](/perf/metrics) page, you'll see which metrics are currently used, and which tools and APIs are available to get the metrics. There is a list of [Frequently asked questions](/perf/faq), so you can find out if the questions you have or the problems you're having were already answered or encountered, and whether there are existing solutions. (Alternatively, you can check the Flutter GitHub issue database using the [performance][performance] label.) Finally, the performance issues are divided into four categories. They correspond to the four labels that are used in the Flutter GitHub issue database: "[perf: speed][speed]", "[perf: memory][memory]", "[perf: app size][size]", "[perf: energy][energy]". The rest of the content is organized using those four categories. {% comment %} Let's put "speed" (rendering) first as it's the most popular performance issue category. {% endcomment -%} ## Speed Are your animations janky (not smooth)? Learn how to evaluate and fix rendering issues. [Improving rendering performance](/perf/rendering-performance) {% comment %} Do your apps take a long time to open? We'll also cover the startup speed issue in some future pages. {% endcomment -%} {% comment %} TODO(<https://github.com/flutter/website/issues/8249>): Reintroduce this article and add this link back. ## Memory [Using memory wisely](/perf/memory) {% endcomment -%} ## App size How to measure your app's size. The smaller the size, the quicker it is to download. [Measuring your app's size][] {% comment %} TODO(<https://github.com/flutter/website/issues/8249>): Reintroduce this article and add this link back. ## Energy How to ensure a longer battery life when running your app. [Preserving your battery](/perf/power) {% endcomment -%} [Measuring your app's size]: /perf/app-size [speed]: {{site.repo.flutter}}/issues?q=is%3Aopen+label%3A%22perf%3A+speed%22+sort%3Aupdated-asc+ [energy]: {{site.repo.flutter}}/issues?q=is%3Aopen+label%3A%22perf%3A+energy%22+sort%3Aupdated-asc+ [memory]: {{site.repo.flutter}}/issues?q=is%3Aopen+label%3A%22perf%3A+memory%22+sort%3Aupdated-asc+ [size]: {{site.repo.flutter}}/issues?q=is%3Aopen+label%3A%22perf%3A+app+size%22+sort%3Aupdated-asc+ [performance]: {{site.repo.flutter}}/issues?q=+label%3A%22severe%3A+performance%22
website/src/perf/index.md/0
{ "file_path": "website/src/perf/index.md", "repo_id": "website", "token_count": 1076 }
1,373
--- title: Add Android devtools for Flutter from Web on macOS start description: Configure your Mac to develop Flutter mobile apps for Android. short-title: Starting from Web on macOS --- To add Android as a Flutter app target for macOS, follow this procedure. ## Install Android Studio 1. Allocate a minimum of 7.5 GB of storage for Android Studio. Consider allocating 10 GB of storage for an optimal configuration. 1. Install [Android Studio][] {{site.appmin.android_studio}} to debug and compile Java or Kotlin code for Android. Flutter requires the full version of Android Studio. {% include docs/install/compiler/android.md target='macos' devos='macOS' attempt="first" -%} {% include docs/install/flutter-doctor.md target='Android' devos='macOS' config='macOSAndroidWeb' %} [Android Studio]: https://developer.android.com/studio/install#mac
website/src/platform-integration/android/install-android/install-android-from-web-on-macos.md/0
{ "file_path": "website/src/platform-integration/android/install-android/install-android-from-web-on-macos.md", "repo_id": "website", "token_count": 257 }
1,374
--- title: Adding an iOS App Clip target description: How to add an iOS App Clip target to your Flutter project. --- {{site.alert.important}} Targeting iOS 16 increases the uncompressed IPA payload size limit to 15MB. Depending on the size of your app, you might hit the limit. ([#71098][]). {{site.alert.end}} This guide describes how to manually add another Flutter-rendering iOS App Clip target to your existing Flutter project or [add-to-app][] project. [#71098]: {{site.repo.flutter}}/issues/71098 [add-to-app]: /add-to-app {{site.alert.warning}} This is an advanced guide and is best intended for audience with a working knowledge of iOS development. {{site.alert.end}} To see a working sample, see the [App Clip sample][] on GitHub. [App Clip sample]: {{site.repo.samples}}/tree/main/ios_app_clip ## Step 1 - Open project Open your iOS Xcode project, such as `ios/Runner.xcworkspace` for full-Flutter apps. ## Step 2 - Add an App Clip target **2.1** Click on your project in the Project Navigator to show the project settings. Press **+** at the bottom of the target list to add a new target. {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/add-target.png" %} **2.2** Select the **App Clip** type for your new target. {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/add-app-clip.png" %} **2.3** Enter your new target detail in the dialog. Select **Storyboard** for Interface. Select the same language as your original target for **Language**. (In other words, to simplify the setup, don't create a Swift App Clip target for an Objective-C main target, and vice versa.) {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/app-clip-details.png" %} **2.4** In the following dialog, activate the new scheme for the new target. {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/activate-scheme.png" %} **2.5** Back in the project settings, open the **Build Phases** tab. Drag **Embedded App Clips** to above **Thin Binary**. {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/embedded-app-clips.png" %} <a id="step-3"></a> ## Step 3 - Remove unneeded files **3.1** In the Project Navigator, in the newly created App Clip group, delete everything except `Info.plist` and `<app clip target>.entitlements`. {{site.alert.tip}} For add-to-app users, it's up to the reader to decide how much of this template to keep to invoke `FlutterViewController` or `FlutterEngine` APIs from this code later. {{site.alert.end}} {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/clean-files.png" %} Move files to trash. **3.2** If you don't use the `SceneDelegate.swift` file, remove the reference to it in the `Info.plist`. Open the `Info.plist` file in the App Clip group. Delete the entire dictionary entry for **Application Scene Manifest**. {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/scene-manifest.png" %} ## Step 4 - Share build configurations This step isn't necessary for add-to-app projects since add-to-app projects have their custom build configurations and versions. **4.1** Back in the project settings, select the project entry now rather than any targets. In the **Info** tab, under the **Configurations** expandable group, expand the **Debug**, **Profile**, and **Release** entries. For each, select the same value from the drop-down menu for the App Clip target as the entry selected for the normal app target. This gives your App Clip target access to Flutter's required build settings. Set **iOS Deployment Target** to at least **16.0** to take advantage of the 15MB size limit. {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/configuration.png" %} **4.2** In the App Clip group's `Info.plist` file, set: * `Build version string (short)` to `$(FLUTTER_BUILD_NAME)` * `Bundle version` to `$(FLUTTER_BUILD_NUMBER)` ## Step 5 - Share code and assets ### Option 1 - Share everything Assuming the intent is to show the same Flutter UI in the standard app as in the App Clip, share the same code and assets. For each of the following: `Main.storyboard`, `Assets.xcassets`, `LaunchScreen.storyboard`, `GeneratedPluginRegistrant.m`, and `AppDelegate.swift` (and `Supporting Files/main.m` if using Objective-C), select the file, then in the first tab of the inspector, also include the App Clip target in the `Target Membership` checkbox group. {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/add-target-membership.png" %} ### Option 2 - Customize Flutter launch for App Clip In this case, do not delete everything listed in [Step 3](#step-3). Instead, use the scaffolding and the [iOS add-to-app APIs][] to perform a custom launch of Flutter. For example to show a [custom Flutter route][]. [custom Flutter route]: /add-to-app/ios/add-flutter-screen#route [iOS add-to-app APIs]: /add-to-app/ios/add-flutter-screen ## Step 6 - Add App Clip associated domains This is a standard step for App Clip development. See the [official Apple documentation][]. [official Apple documentation]: {{site.apple-dev}}/documentation/app_clips/creating_an_app_clip_with_xcode#3604097 **6.1** Open the `<app clip target>.entitlements` file. Add an `Associated Domains` Array type. Add a row to the array with `appclips:<your bundle id>`. {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/app-clip-entitlements.png" %} **6.2** The same associated domains entitlement needs to be added to your main app, as well. Copy the `<app clip target>.entitlements` file from your App Clip group to your main app group and rename it to the same name as your main target such as `Runner.entitlements`. Open the file and delete the `Parent Application Identifiers` entry for the main app's entitlement file (leave that entry for the App Clip's entitlement file). {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/main-app-entitlements.png" %} **6.3** Back in the project settings, select the main app's target, open the **Build Settings** tab. Set the **Code Signing Entitlements** setting to the relative path of the second entitlements file created for the main app. {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/main-app-entitlements-setting.png" %} ## Step 7 - Integrate Flutter These steps are not necessary for add-to-app. **7.1** For the Swift target, set the `Objective-C Bridging Header` build setting to `Runner/Runner-Bridging-Header.h` In other words, the same as the main app target's build settings. {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/bridge-header.png" %} **7.2** Now open the **Build Phases** tab. Press the **+** sign and select **New Run Script Phase**. {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/new-build-phase.png" %} Drag that new phase to below the **Dependencies** phase. Expand the new phase and add this line to the script content: ```bash /bin/sh "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build ``` Uncheck **Based on dependency analysis**. In other words, the same as the main app target's build phases. {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/xcode-backend-build.png" %} This ensures that your Flutter Dart code is compiled when running the App Clip target. **7.3** Press the **+** sign and select **New Run Script Phase** again. Leave it as the last phase. This time, add: ```bash /bin/sh "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed_and_thin ``` Uncheck **Based on dependency analysis**. In other words, the same as the main app target's build phases. {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/xcode-backend-embed.png" %} This ensures that your Flutter app and engine are embedded into the App Clip bundle. ## Step 8 - Integrate plugins **8.1** Open the `Podfile` for your Flutter project or add-to-app host project. For full-Flutter apps, replace the following section: ```ruby target 'Runner' do use_frameworks! use_modular_headers! flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) end ``` with: ```ruby use_frameworks! use_modular_headers! flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) target 'Runner' target '<name of your App Clip target>' ``` At the top of the file, also uncomment `platform :ios, '12.0'` and set the version to the lowest of the two target's iOS Deployment Target. For add-to-app, add to: ```ruby target 'MyApp' do install_all_flutter_pods(flutter_application_path) end ``` with: ```ruby target 'MyApp' do install_all_flutter_pods(flutter_application_path) end target '<name of your App Clip target>' install_all_flutter_pods(flutter_application_path) end ``` **8.2** From the command line, enter your Flutter project directory and then install the pod: ```terminal cd ios pod install ``` ## Run You can now run your App Clip target from Xcode by selecting your App Clip target from the scheme drop-down, selecting an iOS 16 or higher device and pressing run. {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/run-select.png" %} To test launching an App Clip from the beginning, also consult Apple's doc on [Testing Your App Clip's Launch Experience][testing]. [testing]: {{site.apple-dev}}/documentation/app_clips/testing_your_app_clip_s_launch_experience ## Debugging, hot reload Unfortunately `flutter attach` cannot auto-discover the Flutter session in an App Clip due to networking permission restrictions. In order to debug your App Clip and use functionalities like hot reload, you must look for the Observatory URI from the console output in Xcode after running. {% include docs/app-figure.md image="development/platform-integration/ios-app-clip/observatory-uri.png" %} You must then copy and paste it back into the `flutter attach` command to connect. For example: ```terminal flutter attach --debug-uri <copied URI> ```
website/src/platform-integration/ios/ios-app-clip.md/0
{ "file_path": "website/src/platform-integration/ios/ios-app-clip.md", "repo_id": "website", "token_count": 3228 }
1,375
--- title: Add macOS devtools to Flutter from web start description: Configure your system to develop Flutter mobile apps on macOS. short-title: Starting from web --- To add macOS as a Flutter app target for macOS, follow this procedure. ## Install Xcode 1. Allocate a minimum of 26 GB of storage for Xcode. Consider allocating 42 GB of storage for an optimal configuration. 1. Install [Xcode][] {{site.appnow.xcode}} to debug and compile native Swift or ObjectiveC code. {% include docs/install/compiler/xcode.md target='macOS' devos='macOS' attempt="first" -%} {% include docs/install/flutter-doctor.md target='macOS' devos='macOS' config='macOSDesktopWeb' %} [Xcode]: {{site.apple-dev}}/xcode/
website/src/platform-integration/macos/install-macos/install-macos-from-web.md/0
{ "file_path": "website/src/platform-integration/macos/install-macos/install-macos-from-web.md", "repo_id": "website", "token_count": 233 }
1,376
--- title: Web renderers description: How to choose a web renderer for running and building a web app. --- When running and building apps for the web, you can choose between two different renderers. This page describes both renderers and how to choose the best one for your needs. The two renderers are: **HTML renderer** : This renderer, which has a smaller download size than the CanvasKit renderer, uses a combination of HTML elements, CSS, Canvas elements, and SVG elements. **CanvasKit renderer** : This renderer is fully consistent with Flutter mobile and desktop, has faster performance with higher widget density, but adds about 1.5MB in download size. [CanvasKit][canvaskit] uses WebGL to render Skia paint commands. ## Command line options The `--web-renderer` command line option takes one of three values, `auto`, `html`, or `canvaskit`. * `auto` (default) - automatically chooses which renderer to use. This option chooses the HTML renderer when the app is running in a mobile browser, and CanvasKit renderer when the app is running in a desktop browser. * `html` - always use the HTML renderer * `canvaskit` - always use the CanvasKit renderer This flag can be used with the `run` or `build` subcommands. For example: ```terminal flutter run -d chrome --web-renderer html ``` ```terminal flutter build web --web-renderer canvaskit ``` This flag is ignored when a non-browser (mobile or desktop) device target is selected. ## Runtime configuration To override the web renderer at runtime: * Build the app with the `auto` option. * Prepare a configuration object with the `renderer` property set to `"canvaskit"` or `"html"`. * Pass that object to the `engineInitializer.initializeEngine(configuration);` method in the [Flutter Web app initialization][web-app-init] script. ```html <body> <script> let useHtml = true; window.addEventListener('load', function(ev) { _flutter.loader.loadEntrypoint({ serviceWorker: { serviceWorkerVersion: serviceWorkerVersion, }, onEntrypointLoaded: function(engineInitializer) { let config = { renderer: useHtml ? "html" : "canvaskit", }; engineInitializer.initializeEngine(config).then(function(appRunner) { appRunner.runApp(); }); } }); }); </script> </body> ``` The web renderer can't be changed after the Flutter engine startup process begins in `main.dart.js`. {{site.alert.note}} As of **Flutter 3.7.0**, setting a `window.flutterWebRenderer` (an approach used in previous releases) displays a **deprecation notice** in the JS console. For more information, check out [Customizing web app initialization][web-app-init]. {{site.alert.end}} ## Choosing which option to use Choose the `auto` option (default) if you are optimizing for download size on mobile browsers and optimizing for performance on desktop browsers. Choose the `html` option if you are optimizing download size over performance on both desktop and mobile browsers. Choose the `canvaskit` option if you are prioritizing performance and pixel-perfect consistency on both desktop and mobile browsers. ## Examples Run in Chrome using the default renderer option (`auto`): ``` flutter run -d chrome ``` Build your app in release mode, using the default (auto) option: ``` flutter build web --release ``` Build your app in release mode, using just the CanvasKit renderer: ``` flutter build web --web-renderer canvaskit --release ``` Run your app in profile mode using the HTML renderer: ``` flutter run -d chrome --web-renderer html --profile ``` [canvaskit]: https://skia.org/docs/user/modules/canvaskit/ [file an issue]: {{site.repo.flutter}}/issues/new?title=[web]:+%3Cdescribe+issue+here%3E&labels=%E2%98%B8+platform-web&body=Describe+your+issue+and+include+the+command+you%27re+running,+flutter_web%20version,+browser+version [web-app-init]: /platform-integration/web/initialization
website/src/platform-integration/web/renderers.md/0
{ "file_path": "website/src/platform-integration/web/renderers.md", "repo_id": "website", "token_count": 1224 }
1,377
{% assign id = include.os | downcase -%} {% assign channels = 'stable beta' | split: ' ' -%} <div id="{{id}}" class="tab-pane {%- if id == 'windows' %} active {% endif %}" role="tabpanel" aria-labelledby="{{id}}-tab" markdown="1"> {% for channel in channels -%} ## {{channel | capitalize }} channel ({{include.os}}) Select from the following scrollable list: <div class="scrollable-table"> <table id="downloads-{{id}}-{{channel}}" class="table table-striped"> <thead><tr><th>Flutter version</th><th>Architecture</th><th>Ref</th><th class="date">Release Date</th><th>Dart version</th><th>Provenance</th></tr></thead> <tr class="loading"><td colspan="6">Loading...</td></tr> </table> </div> {% endfor -%} </div>
website/src/release/_release_os.md/0
{ "file_path": "website/src/release/_release_os.md", "repo_id": "website", "token_count": 270 }
1,378
--- title: Android 14 nonlinear font scaling enabled description: >- Android 14's new nonlinear font scaling feature is enabled in Flutter after v3.14. --- ## Summary Android 14 introduced nonlinear font scaling up to 200%. It may change how your app looks when the user changes the accessibility text scaling in system preferences. ## Background The [Android 14 nonlinear font scaling][] feature prevents excessive accessibility font scaling by scaling larger text at a lesser rate when the user increases the text scaling value in system preferences. ## Migration guide As the [Android 14 feature overview][Android 14 nonlinear font scaling] suggests, test your UI with the maximum font size enabled (`200%`). This should verify that your app can apply the font sizes correctly and can accommodate larger font sizes without impacting usability. To adopt nonlinear font scaling in your app and custom widgets, consider migrating from `textScaleFactor` to `TextScaler`. To learn how to migrate to `TextScaler`, check out the [Deprecate `textScaleFactor` in favor of `TextScaler`][] migration guide. **Temporarily Opting Out** To opt-out of nonlinear text scaling on Android 14 until you migrate your app, add a modified `MediaQuery` at the top of your app's widget tree: ```dart runApp( Builder(builder: (context) { final mediaQueryData = MediaQuery.of(context); final mediaQueryDataWithLinearTextScaling = mediaQueryData .copyWith(textScaler: TextScaler.linear(mediaQueryData.textScaler.textScaleFactor)); return MediaQuery(data: mediaQueryDataWithLinearTextScaling, child: realWidgetTree); }), ); ``` This uses the deprecated `textScaleFactor` API. It will stop working once that API is removed from the Flutter API. ## Timeline Landed in version: 3.14.0-11.0.pre<br> In stable release: 3.16 ## References API documentation: * [`TextScaler`][] Relevant issues: * [New font scaling system (Issue 116231)][] Relevant PRs: * [Implementing TextScaler for nonlinear text scaling][] See also: * [Deprecate `textScaleFactor` in favor of `TextScaler`][] [Android 14 nonlinear font scaling]: {{site.android-dev}}/about/versions/14/features#non-linear-font-scaling [Deprecate `textScaleFactor` in favor of `TextScaler`]: /release/breaking-changes/deprecate-textscalefactor [`TextScaler`]: {{site.api}}/flutter/painting/TextScaler-class.html [New font scaling system (Issue 116231)]: {{site.repo.flutter}}/issues/116231 [Implementing TextScaler for nonlinear text scaling]: {{site.repo.engine}}/pull/44907
website/src/release/breaking-changes/android-14-nonlinear-text-scaling-migration.md/0
{ "file_path": "website/src/release/breaking-changes/android-14-nonlinear-text-scaling-migration.md", "repo_id": "website", "token_count": 734 }
1,379
--- title: Default drag scrolling devices description: > ScrollBehaviors will now configure what PointerDeviceKinds can drag Scrollables. --- ## Summary `ScrollBehavior`s now allow or disallow drag scrolling from specified `PointerDeviceKind`s. `ScrollBehavior.dragDevices`, by default, allows scrolling widgets to be dragged by all `PointerDeviceKind`s except for `PointerDeviceKind.mouse`. ## Context Prior to this change, all `PointerDeviceKind`s could drag a `Scrollable` widget. This did not match developer expectations when interacting with Flutter applications using mouse input devices. This also made it difficult to execute other mouse gestures, like selecting text that was contained in a `Scrollable` widget. Now, the inherited `ScrollBehavior` manages which devices can drag scrolling widgets as specified by `ScrollBehavior.dragDevices`. This set of `PointerDeviceKind`s are allowed to drag. ## Description of change This change fixed the unexpected ability to scroll by dragging with a mouse. If you have relied on the previous behavior in your application, there are several ways to control and configure this feature. - Extend `ScrollBehavior`, `MaterialScrollBehavior`, or `CupertinoScrollBehavior` to modify the default behavior, overriding `ScrollBehavior.dragDevices`. - With your own `ScrollBehavior`, you can apply it app-wide by setting `MaterialApp.scrollBehavior` or `CupertinoApp.scrollBehavior`. - Or, if you wish to only apply it to specific widgets, add a `ScrollConfiguration` above the widget in question with your custom `ScrollBehavior`. Your scrollable widgets then inherit and reflect this behavior. - Instead of creating your own `ScrollBehavior`, another option for changing the default behavior is to copy the existing `ScrollBehavior`, and set different `dragDevices`. - Create a `ScrollConfiguration` in your widget tree, and provide a modified copy of the existing `ScrollBehavior` in the current context using `copyWith`. To accommodate the new configuration of drag devices in `ScrollBehavior`, `GestureDetector.kind` has been deprecated along with all subclassed instances of the parameter. A flutter fix is available to migrate existing code for all gesture detectors from `kind` to `supportedDevices`. The previous parameter `kind` only allowed one `PointerDeviceKind` to be used to filter gestures. The introduction of `supportedDevices` makes it possible for more than one valid `PointerDeviceKind`. ## Migration guide ### Setting a custom `ScrollBehavior` for your application Code before migration: ```dart MaterialApp( // ... ); ``` Code after migration: ```dart class MyCustomScrollBehavior extends MaterialScrollBehavior { // Override behavior methods and getters like dragDevices @override Set<PointerDeviceKind> get dragDevices => { PointerDeviceKind.touch, PointerDeviceKind.mouse, // etc. }; } // Set ScrollBehavior for an entire application. MaterialApp( scrollBehavior: MyCustomScrollBehavior(), // ... ); ``` ### Setting a custom `ScrollBehavior` for a specific widget Code before migration: ```dart final ScrollController controller = ScrollController(); ListView.builder( controller: controller, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); } ); ``` Code after migration: ```dart class MyCustomScrollBehavior extends MaterialScrollBehavior { // Override behavior methods and getters like dragDevices @override Set<PointerDeviceKind> get dragDevices => { PointerDeviceKind.touch, PointerDeviceKind.mouse, // etc. }; } // ScrollBehavior can be set for a specific widget. final ScrollController controller = ScrollController(); ScrollConfiguration( behavior: MyCustomScrollBehavior(), child: ListView.builder( controller: controller, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); } ), ); ``` ### Copy and modify existing `ScrollBehavior` Code before migration: ```dart final ScrollController controller = ScrollController(); ListView.builder( controller: controller, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); } ); ``` Code after migration: ```dart // ScrollBehavior can be copied and adjusted. final ScrollController controller = ScrollController(); ScrollConfiguration( behavior: ScrollConfiguration.of(context).copyWith(dragDevices: { PointerDeviceKind.touch, PointerDeviceKind.mouse, }), child: ListView.builder( controller: controller, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); } ), ); ``` ### Migrate `GestureDetector`s from `kind` to `supportedDevices` Code before migration: ```dart VerticalDragGestureRecognizer( kind: PointerDeviceKind.touch, ); ``` Code after migration: ```dart VerticalDragGestureRecognizer( supportedDevices: <PointerDeviceKind>{ PointerDeviceKind.touch }, ); ``` ## Timeline Landed in version: 2.3.0-12.0.pre<br> In stable release: 2.5 ## References API documentation: * [`ScrollConfiguration`][] * [`ScrollBehavior`][] * [`MaterialScrollBehavior`][] * [`CupertinoScrollBehavior`][] * [`PointerDeviceKind`][] * [`GestureDetector`][] Relevant issue: * [Issue #71322][] Relevant PRs: * [Reject mouse drags by default in scrollables][] * [Deprecate GestureDetector.kind in favor of new supportedDevices][] [`ScrollConfiguration`]: {{site.api}}/flutter/widgets/ScrollConfiguration-class.html [`ScrollBehavior`]: {{site.api}}/flutter/widgets/ScrollBehavior-class.html [`MaterialScrollBehavior`]: {{site.api}}/flutter/material/MaterialScrollBehavior-class.html [`CupertinoScrollBehavior`]: {{site.api}}/flutter/cupertino/CupertinoScrollBehavior-class.html [`PointerDeviceKind`]: {{site.api}}/flutter/dart-ui/PointerDeviceKind-class.html [`GestureDetector`]: {{site.api}}/flutter/widgets/GestureDetector-class.html [Issue #71322]: {{site.repo.flutter}}/issues/71322 [Reject mouse drags by default in scrollables]: {{site.repo.flutter}}/pull/81569 [Deprecate GestureDetector.kind in favor of new supportedDevices]: {{site.repo.flutter}}/pull/81858
website/src/release/breaking-changes/default-scroll-behavior-drag.md/0
{ "file_path": "website/src/release/breaking-changes/default-scroll-behavior-drag.md", "repo_id": "website", "token_count": 1815 }
1,380
--- title: GestureRecognizer cleanup description: > OneSequenceGestureRecognizer subclasses should override `addAllowedPointer` to take a `PointerDownEvent` --- ## Summary `OneSequenceGestureRecognizer.addAllowedPointer()` was changed to take a `PointerDownEvent`, like its superclass. Previously, it accepted the more general `PointerEvent` type, which was incorrect. ## Context The framework only ever passes `PointerDownEvent` objects to `addAllowedPointer()`. Declaring `OneSequenceGestureRecognizer.addAllowedPointer()` to take the more general type was confusing, and caused `OneSequenceGestureRecognizer` subclasses to have to cast their argument to the right class. ## Description of change The previous declaration forced `OneSequenceGestureRecognizer` descendants to override `addAllowedPointer()` like so: ```dart class CustomGestureRecognizer extends ScaleGestureRecognizer { @override void addAllowedPointer(PointerEvent event) { // insert custom handling of event here... super.addAllowedPointer(event); } } ``` The new method declaration will cause this code to fail with the following error message: ```nocode super.addAllowedPointer(event); The argument type 'PointerEvent' can't be assigned to the parameter type 'PointerDownEvent'. #argument_type_not_assignable ``` ## Migration guide Code before migration: ```dart class CustomGestureRecognizer extends ScaleGestureRecognizer { @override void addAllowedPointer(PointerEvent event) { // insert custom handling of event here... super.addAllowedPointer(event); } } ``` Code after migration: ```dart class CustomGestureRecognizer extends ScaleGestureRecognizer { @override void addAllowedPointer(PointerDownEvent event) { // insert custom handling of event here... super.addAllowedPointer(event); } } ``` ## Timeline Landed in version: 2.3.0-13.0.pre<br> In stable release: 2.5 ## References API documentation: * [`OneSequenceGestureRecognizer`][] Relevant PR: * [Fix addAllowedPointer() overrides][] [`OneSequenceGestureRecognizer`]: {{site.api}}/flutter/gestures/OneSequenceGestureRecognizer-class.html [Fix addAllowedPointer() overrides]: {{site.repo.flutter}}/pull/82834
website/src/release/breaking-changes/gesture-recognizer-add-allowed-pointer.md/0
{ "file_path": "website/src/release/breaking-changes/gesture-recognizer-add-allowed-pointer.md", "repo_id": "website", "token_count": 739 }
1,381
--- title: Updated default text styles for menus description: >- The default text styles for menus are updated to match the Material 3 specification. --- ## Summary The default text styles used for menus are updated to match the Material 3 specification. ## Context The default text style for `MenuItemButton` (a widget used in a `MenuBar`, and in a menu created with `MenuAnchor`), and `DropdownMenuEntry` (in the `DropdownMenu`) is updated to match the Material 3 specification. Likewise, the default text style for the `DropdownMenu`s `TextField` is updated to match the Material 3 specification. ## Description of change The default text style for `MenuItemButton` (a widget used in a `MenuBar`, and in a menu created with `MenuAnchor`), and `DropdownMenuEntry` (in the `DropdownMenu`) is updated from `TextTheme.bodyLarge` to `TextTheme.labelLarge` for Material 3. The default text style for the `DropdownMenu`s `TextField` is updated from `TextTheme.labelLarge` to `TextTheme.bodyLarge` for Material 3. ## Migration guide A `MenuItemButton` for Material 3 uses `TextTheme.labelLarge` as the default text style. To use the previous default text style, set the `TextTheme.bodyLarge` text style in the `MenuItemButton.style` or `MenuButtonThemeData.style` properties. Code before migration: ```dart MenuItemButton( child: Text(MenuEntry.about.label), onPressed: () => _activate(MenuEntry.about), ), ``` ```dart menuButtonTheme: MenuButtonThemeData( style: MenuItemButton.styleFrom( /// ... ), ), ``` Code after migration: ```dart MenuItemButton( style: MenuItemButton.styleFrom( textStyle: Theme.of(context).textTheme.bodyLarge, ), child: Text(MenuEntry.about.label), onPressed: () => _activate(MenuEntry.about), ), ``` ```dart menuButtonTheme: MenuButtonThemeData( style: MenuItemButton.styleFrom( textStyle: Theme.of(context).textTheme.bodyLarge, ), ), ``` A `DropdownMenu`'s `TextField` for Material 3 uses `TextTheme.bodyLarge` as the default text style. To use the previous default text style, set the `TextTheme.labelLarge` text style in the `DropdownMenu.textStyle` or `DropdownMenuThemeData.textStyle` properties. Code before migration: ```dart DropdownMenu<ColorLabel>( initialSelection: ColorLabel.green, controller: colorController, label: const Text('Color'), dropdownMenuEntries: colorEntries, onSelected: (ColorLabel? color) { setState(() { selectedColor = color; }); }, ), ``` ```dart dropdownMenuTheme: DropdownMenuThemeData( /// ... ), ``` Code after migration: ```dart DropdownMenu<ColorLabel>( textStyle: Theme.of(context).textTheme.labelLarge, initialSelection: ColorLabel.green, controller: colorController, label: const Text('Color'), dropdownMenuEntries: colorEntries, onSelected: (ColorLabel? color) { setState(() { selectedColor = color; }); }, ), ``` ```dart dropdownMenuTheme: DropdownMenuThemeData( textStyle: TextStyle( fontStyle: FontStyle.italic, fontWeight: FontWeight.bold, ), ), ``` A `DropdownMenu`'s `DropdownMenuEntry` for Material 3 uses `TextTheme.labelLarge` as the default text style. To use the previous default text style, set the `TextTheme.bodyLarge` text style in the `DropdownMenuEntry.style` or `MenuButtonThemeData.style` properties. Code before migration: ```dart DropdownMenuEntry<ColorLabel>( value: color, label: color.label, ), ``` ```dart menuButtonTheme: MenuButtonThemeData( style: MenuItemButton.styleFrom( /// ... ), ), ``` Code after migration: ```dart DropdownMenuEntry<ColorLabel>( style: MenuItemButton.styleFrom( textStyle: Theme.of(context).textTheme.bodyLarge, ), value: color, label: color.label, ), ``` ```dart menuButtonTheme: MenuButtonThemeData( style: MenuItemButton.styleFrom( textStyle: Theme.of(context).textTheme.bodyLarge, ), ), ``` ## Timeline Landed in version: 3.14.0-11.0.pre<br> In stable release: 3.16 ## References API documentation: * [`MenuBar`][] * [`MenuAnchor`][] * [`MenuItemButton`][] * [`MenuButtonTheme`][] * [`DropdownMenu`][] * [`DropdownMenuEntry`][] * [`DropdownMenuTheme`][] * [`TextTheme`][] Relevant PRs: * [Update default menu text styles for Material 3][] [`MenuBar`]: {{site.api}}/flutter/material/MenuBar-class.html [`MenuAnchor`]: {{site.api}}/flutter/material/MenuAnchor-class.html [`MenuItemButton`]: {{site.api}}/flutter/material/MenuItemButton-class.html [`MenuButtonTheme`]: {{site.api}}/flutter/material/MenuButtonTheme-class.html [`DropdownMenu`]: {{site.api}}/flutter/material/DropdownMenu-class.html [`DropdownMenuEntry`]: {{site.api}}/flutter/material/DropdownMenuEntry-class.html [`DropdownMenuTheme`]: {{site.api}}/flutter/material/DropdownMenuTheme-class.html [`TextTheme`]: {{site.api}}/flutter/material/TextTheme-class.html [Update default menu text styles for Material 3]: {{site.repo.flutter}}/pull/131930
website/src/release/breaking-changes/menus-text-style.md/0
{ "file_path": "website/src/release/breaking-changes/menus-text-style.md", "repo_id": "website", "token_count": 1649 }
1,382
--- title: Default `PrimaryScrollController` on Desktop description: > The `PrimaryScrollController` will no longer attach to vertical `ScrollView`s automatically on Desktop. --- ## Summary The `PrimaryScrollController` API has been updated to no longer automatically attach to vertical `ScrollView`s on desktop platforms. ## Context Prior to this change, `ScrollView.primary` would default to true if a `ScrollView` had an `Axis.vertical` scroll direction and a `ScrollController` had not already been provided. This allowed for common UI patterns, like the scroll-to-top function on iOS to work out of the box for Flutter apps. On desktop however, this default would often cause the following assertion error: ```nocode ScrollController attached to multiple ScrollViews. ``` While it is common for a mobile application to display one `ScrollView` at a time, desktop UI patterns are more likely to display multiple `ScrollView`s side-by-side. The prior implementation of `PrimaryScrollController` conflicted with this pattern, resulting in an often unhelpful error message. To remedy this, the `PrimaryScrollController` has been updated with additional parameters as well as better error messaging across multiple widgets that depend on it. ## Description of change The previous implementation of `ScrollView` resulted in `primary` being true by default for all vertical `ScrollView`s that did not already have a `ScrollController`, on all platforms. This default behavior was not always clear, particularly because it is separate from the `PrimaryScrollController` itself. ```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'); } ), ); ``` The implementation changes `ScrollView.primary` to be nullable, with the fallback decision-making being relocated to the `PrimaryScrollController`. When `primary` is null, and no `ScrollController` has been provided, the `ScrollView` will look up the `PrimaryScrollController` and instead call `shouldInherit` to determine if the given `ScrollView` should use the `PrimaryScrollController`. The new members of the `PrimaryScrollController` class, `automaticallyInheritForPlatforms` and `scrollDirection`, are evaluated in `shouldInherit`, allowing users clarity and control over the `PrimaryScrollController`'s behavior. By default, backwards compatibility is maintained for mobile platforms. `PrimaryScrollController.shouldInherit` returns true for vertical `ScrollView`s. On desktop, this returns false by default. ```dart // Only on mobile platforms will this attach to the PrimaryScrollController by // default. Scaffold( body: ListView.builder( itemBuilder: (BuildContext context, int index) { return Text('Item $index'); } ), ); ``` To change the default, users can set `ScrollView.primary` true or false to explicitly manage the `PrimaryScrollController` for an individual `ScrollView`. For behavior across multiple `ScrollView`s, the `PrimaryScrollController` is now configurable by setting the specific platform, as well as the scroll direction that is preferred for inheritance. Widgets that use the `PrimaryScrollController`, such as `NestedScrollView`, `Scrollbar`, and `DropdownMenuButton` will experience no change to existing functionality. Features like the iOS scroll-to-top will also continue to work as expected without any migration. `ScrollAction`s, and `ScrollIntent`s on desktop are the only classes affected by this change, requiring migration. By default, the `PrimaryScrollController` is used to execute fallback keyboard scrolling `Shortcuts` if the current `Focus` is contained within a `Scrollable`. Since displaying more than one `ScrollView` side-by-side is common on desktop platforms, it isn't possible for Flutter to decide "Which `ScrollView` should be primary in this view and receive the keyboard scroll action?" If more than one `ScrollView` was present previous to this change, the same assertion (`ScrollController attached to multiple ScrollViews.`) would be thrown. Now, on desktop platforms, users need to specify `primary: true` to designate which `ScrollView` is the fallback to receive unhandled keyboard `Shortcuts`. ## Migration guide Code before migration: ```dart // These side-by-side ListViews would throw errors from Scrollbars and // ScrollActions previously due to the PrimaryScrollController. Scaffold( body: LayoutBuilder( builder: (context, constraints) { return Row( children: [ SizedBox( height: constraints.maxHeight, width: constraints.maxWidth / 2, child: ListView.builder( itemBuilder: (BuildContext context, int index) { return Text('List 1 - Item $index'); } ), ), SizedBox( height: constraints.maxHeight, width: constraints.maxWidth / 2, child: ListView.builder( itemBuilder: (BuildContext context, int index) { return Text('List 2 - Item $index'); } ), ), ] ); }, ), ); ``` Code after migration: ```dart // These side-by-side ListViews will no longer throw errors, but for // default ScrollActions, one will need to be designated as primary. Scaffold( body: LayoutBuilder( builder: (context, constraints) { return Row( children: [ SizedBox( height: constraints.maxHeight, width: constraints.maxWidth / 2, child: ListView.builder( // This ScrollView will use the PrimaryScrollController primary: true, itemBuilder: (BuildContext context, int index) { return Text('List 1 - Item $index'); } ), ), SizedBox( height: constraints.maxHeight, width: constraints.maxWidth / 2, child: ListView.builder( itemBuilder: (BuildContext context, int index) { return Text('List 2 - Item $index'); } ), ), ] ); }, ), ); ``` ## Timeline Landed in version: 3.3.0-0.0.pre In stable release: 3.3 ## References API documentation: * [`PrimaryScrollController`][] * [`ScrollView`][] * [`ScrollAction`][] * [`ScrollIntent`][] * [`Scrollbar`][] Design document: * [Updating PrimaryScrollController][] Relevant issues: * [Issue #100264][] Relevant PRs: * [Updating PrimaryScrollController for Desktop][] [`PrimaryScrollController`]: {{site.api}}/flutter/widgets/PrimaryScrollController-class.html [`ScrollView`]: {{site.api}}/flutter/widgets/ScrollView-class.html [`ScrollAction`]: {{site.api}}/flutter/widgets/ScrollAction-class.html [`ScrollIntent`]: {{site.api}}/flutter/widgets/ScrollIntent-class.html [`Scrollbar`]: {{site.api}}/flutter/material/Scrollbar-class.html [Updating PrimaryScrollController]: https://docs.google.com/document/d/12OQx7h8UQzzAi0Kxh-saDC2dg7h2fghCCzwJ0ysPmZE/edit?usp=sharing&resourcekey=0-ATO-1Er3HO2HITm59I0IdA [Issue #100264]: {{site.repo.flutter}}/issues/100264 [Updating PrimaryScrollController for Desktop]: {{site.repo.flutter}}/pull/102099
website/src/release/breaking-changes/primary-scroll-controller-desktop.md/0
{ "file_path": "website/src/release/breaking-changes/primary-scroll-controller-desktop.md", "repo_id": "website", "token_count": 2413 }
1,383
--- title: Customizing tabs alignment using the new TabBar.tabAlignment property description: Introducing the TabBar.tabAlignment property. --- ## Summary Using `TabBar.tabAlignment` to customize the alignment of tabs in a `TabBar`. ## Context The `TabBar.tabAlignment` property sets where a Material 3 `TabBar` places tabs. The `TabAlignment` enum has the following values: * `TabAlignment.start`: Aligns the tabs to the start of the scrollable `TabBar`. * `TabAlignment.startOffset`: Aligns the tabs to the start of the scrollable `TabBar` with an offset of `52.0` pixels. * `TabAlignment.center`: Aligns the tabs to the center of the `TabBar`. * `TabAlignment.fill`: Aligns the tabs to the start and stretches the tabs to fill the fixed `TabBar`. The scrollable `TabBar` supports the following alignments: * `TabAlignment.start` * `TabAlignment.startOffset` * `TabAlignment.center` The fixed `TabBar` supports the following alignments: * `TabAlignment.fill` * `TabAlignment.center` When you set `ThemeData.useMaterial3` to `true`, a scrollable `TabBar` aligns tabs as `TabAlignment.startOffset` by default. To change this alignment, set the `TabBar.tabAlignment` property for widget level customization. Or, set the `TabBarThemeData.tabAlignment` property for app level customization. ## Description of change When you set `TabBar.isScrollable` and `ThemeData.useMaterial3` to `true`, the tabs in a scrollable `TabBar` defaults to `TabAlignment.startOffset`. This aligns the tabs to the start of the scrollable `TabBar` with an offset of `52.0` pixels. This changes the previous behavior. The tabs were aligned to the start of the scrollable `TabBar` when more tabs needed to display than the width allowed. ## Migration guide A Material 3 scrollable `TabBar` uses `TabAlignment.startOffset` as the default tab alignment. This aligns the tabs to the start of the scrollable `TabBar` with an offset of `52.0` pixels. To align the tabs to the start of the scrollable `TabBar`, set `TabBar.tabAlignment` to `TabAlignment.start`. This change also removed the `52.0` pixel offset. The following code snippets show how to use `TabBar.tabAlignment` to align tabs to the start of the scrollable `TabBar`: Code before migration: ```dart TabBar( isScrollable: true, tabs: List<Tab>.generate( count, (int index) => Tab(text: 'Tab $index'), ).toList(), ); ``` Code after migration: ```dart TabBar( tabAlignment: TabAlignment.start, isScrollable: true, tabs: List<Tab>.generate( count, (int index) => Tab(text: 'Tab $index'), ).toList(), ); ``` ## Timeline Landed in version: 3.13.0-17.0.pre<br> In stable release: 3.16 ## References API documentation: * [`TabBar`][] * [`TabBar.tabAlignment`][] * [`TabAlignment`][] Relevant PRs: * [Introduce `TabBar.tabAlignment`][] * [Fix Material 3 Scrollable `TabBar`][] [`TabBar`]: {{site.api}}/flutter/material/TabBar-class.html [`TabBar.tabAlignment`]: {{site.api}}/flutter/material/TabBar/tabAlignment.html [`TabAlignment`]: {{site.api}}/flutter/material/TabAlignment.html [Introduce `TabBar.tabAlignment`]: {{site.repo.flutter}}/pull/125036 [Fix Material 3 Scrollable `TabBar`]: {{site.repo.flutter}}/pull/131409
website/src/release/breaking-changes/tab-alignment.md/0
{ "file_path": "website/src/release/breaking-changes/tab-alignment.md", "repo_id": "website", "token_count": 1048 }
1,384
--- title: Migrate a Windows project to support dark title bars description: How to update a Windows project to support dark title bars --- Projects created before Flutter 3.7 have light title bars even when the Windows theme is dark mode. Projects created before Flutter 3.7 need to be migrated to support dark title bars. ## Migration steps Your project can be updated using these steps: 1. Verify you are on Flutter version 3.7 or newer using `flutter --version` 2. If needed, use `flutter upgrade` to update to the latest version of the Flutter SDK 3. Backup your project, possibly using git or some other version control system 4. Delete the following files: 1. `windows/runner/CMakeLists.txt` 2. `windows/runner/win32_window.cpp` 3. `windows/runner/win32_window.h` 5. Run `flutter create --platforms=windows .` 6. Review the changes to the following files: 1. `windows/runner/CMakeLists.txt` 2. `windows/runner/win32_window.cpp` 3. `windows/runner/win32_window.h` 7. Verify your app builds using `flutter build windows` {{site.alert.note}} Follow the [run loop migration guide][] if the build fails with the following error message: ``` 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) ``` {{site.alert.end}} ## Example [PR 862][] shows the migration work for the [Flutter Gallery][] app. [run loop migration guide]: /release/breaking-changes/windows-run-loop [PR 862]: {{site.repo.gallery-archive}}/pull/862/files [Flutter Gallery]: {{site.gallery-archive}}
website/src/release/breaking-changes/windows-dark-mode.md/0
{ "file_path": "website/src/release/breaking-changes/windows-dark-mode.md", "repo_id": "website", "token_count": 543 }
1,385
--- title: Flutter 1.2.1 release notes short-title: 1.2.1 release notes description: Release notes for Flutter 1.2.1. --- Our #1 priority since the Flutter v1.0 release has been to continue to address high priority issues reported both by Flutter developers and the Flutter team itself. This includes committing 672 pull requests in the Flutter engine and framework since December (we've been busy!). We've called out the new features and breaking changes that we think are noteworthy below. The biggest ones came from our Framework and Tool tags, but we also found and fixed a couple of Severe issues as well. ## Framework To more fully round-out Flutter's animation support, this release adds several more of the standard easing functions: [#25788](https://github.com/flutter/flutter/pull/25788) Add Robert Penner's easing functions To integrate more fully with Android, this release adds support for [Android App Bundles][], a new packaging format that helps in reducing app size and enables new features like dynamic delivery for Android apps: [#24440](https://github.com/flutter/flutter/pull/24440) Adding support for android app bundle To integrate more fully with iOS, this release adds several new features and fixes for iOS, including a new CupertinoTheme: [#25183](https://github.com/flutter/flutter/pull/25183) Add navigatorKey to CupertinoTabView [#25593](https://github.com/flutter/flutter/pull/25593) Let CupertinoTabScaffold handle keyboard insets too [#24876](https://github.com/flutter/flutter/pull/24876) Adds a fade in and out, rounds corners, fixes offset and fixes height of cursor on iOS [#23759](https://github.com/flutter/flutter/pull/23759) Adds CupertinoTheme In addition to the iOS Cupertino theme support, this release continues to enhance the Material theme as well: [#24169](https://github.com/flutter/flutter/pull/24169) [Material] Theme-able elevation on dialogs [#25339](https://github.com/flutter/flutter/pull/25339) [Material] Theme-able TextStyles for AlertDialog To integrate more fully with desktop form-factors like Android tablets and ChromeOS as well as desktop web and desktop OS support, this release builds more support for keyboard and mouse as first class input devices: [#7758](https://github.com/flutter/engine/pull/7758) Recommended implementation of combining characters implementation [#27853](https://github.com/flutter/flutter/pull/27853) Hook up character events and unmodified code points to Android raw key event handling [#27620](https://github.com/flutter/flutter/pull/27620) Add a keyboard key code generator [#27627](https://github.com/flutter/flutter/pull/27627) Adding support for logical and physical key events [#6961](https://github.com/flutter/engine/pull/6961) Add hover event support to the engine [#24830](https://github.com/flutter/flutter/pull/24830) Implement hover support for mouse pointers As widgets are the core way to interact with users in Flutter, this release continues to add features and fixes to the Flutter widget set with particular attention paid to the [SliverAppBar](https://api.flutter.dev/flutter/material/SliverAppBar-class.html): [#26021](https://github.com/flutter/flutter/pull/26021) Fix SliverAppBar title opacity and test all cases [#26101](https://github.com/flutter/flutter/pull/26101) Fix a floating snapping SliverAppBar crash [#25091](https://github.com/flutter/flutter/pull/25091) Add animations to SliverAppBar doc [#24736](https://github.com/flutter/flutter/pull/24736) Provide some more locations for the FAB [#25585](https://github.com/flutter/flutter/pull/25585) Expose font fallback API in TextStyle, Roll engine 54a3577c0139..215ca1560088 [#24457](https://github.com/flutter/flutter/pull/24457) Revise Android and iOS gestures on Material TextField [#24554](https://github.com/flutter/flutter/pull/24554) Adds force press gesture detector and recognizer [#23919](https://github.com/flutter/flutter/pull/23919) Allow detection of taps on TabBar [#25384](https://github.com/flutter/flutter/pull/25384) Adds support for floating cursor [#24976](https://github.com/flutter/flutter/pull/24976) Support TextField multi-line hint text [#26332](https://github.com/flutter/flutter/pull/26332) Strut: fine tuned control over text minimum line heights, allows forcing the line height to be a specified height And finally, as Flutter usage continues to grow world-wide, we continue to enhance support for localizations across several languages, including Ukrainian, Polish, Swahili and Galician in this release. [#25394](https://github.com/flutter/flutter/pull/25394) Update localizations [#27506](https://github.com/flutter/flutter/pull/27506) Added support for Swahili (material_sw.arb) [#27352](https://github.com/flutter/flutter/pull/24876) Including Galician language ## Plug-Ins As in the framework and engine itself, we're continuing to focus on plugin quality as well: [flutter/engine#7317](https://github.com/flutter/engine/pull/7317) Fix stale GrContext for iOS platform views [flutter/engine#7558](https://github.com/flutter/engine/pull/7558) Fix lost touch events for iOS platform views [flutter/plugins#1157](https://github.com/flutter/plugins/pull/1157) [google_maps_flutter] Fix camera positioning issue on iOS [flutter/plugins#1176](https://github.com/flutter/plugins/pull/1176) [firebase_auth] Fix Firebase phone auth on Android [flutter/plugins#1037](https://github.com/flutter/plugins/pull/1037) [camera] Save photo orientation on iOS [flutter/plugins#1129](https://github.com/flutter/plugins/pull/1129) [android_alarm_manager] Fix "background start not allowed" issues, queue events that are received too early [flutter/plugins#1051 ](https://github.com/flutter/plugins/pull/1051)[image_picker] Fix crash on iOS when the picker is tapped multiple times The webview_flutter plugin got a communication channel between Dart and JavaScript: [flutter/plugins#1116](https://github.com/flutter/plugins/pull/1116) Add WebView JavaScript channels (Dart side) [flutter/plugins#1130](https://github.com/flutter/plugins/pull/1130) WebView JavasScript channels Android implementation [flutter/plugins#1139](https://github.com/flutter/plugins/pull/1139) WebView JavaScript channels - iOS implementation [lutter/plugins1021](https://github.com/flutter/plugins/pull/1021) javascript evaluation ios/android We've made progress building the In App Purchase plugin (which is still pre-release): [#1057](https://github.com/flutter/plugins/pull/1057) [IAP] Check if the payment processor is available [#1084](https://github.com/flutter/plugins/pull/1084) [IAP] Fetch SkuDetails from Google Play [#1068](https://github.com/flutter/plugins/pull/1068) IAP productlist ios [#1172](https://github.com/flutter/plugins/pull/1172) [In_app_purchase] add payment objc translators ## Dart The release contains a new Dart SDK which provides support for a new set literals syntax and increases AOT performance 10-20% by reducing the overhead of calling constructors or static methods: [#37](https://github.com/dart-lang/language/issues/37) Set Literal [#33274](https://github.com/dart-lang/sdk/issues/33274) Add support for "naked" instructions: global object pool, pc-relative static calls, faster indirect calls, potential code sharing ## Tool We've added a number of new tools and new features to existing tools in this release. This release continues to improve error messages across a range of tools: [#26107](https://github.com/flutter/flutter/pull/26107) Better error messages for flutter tool --dynamic flag [#26084](https://github.com/flutter/flutter/pull/26084) Improve message when saving compilation training data [#25863](https://github.com/flutter/flutter/pull/25863) Friendlier messages when using dynamic patching This release also adds support for Java 1.8: [#25470](https://github.com/flutter/flutter/pull/25470) Support Java 1.8 ## Severe In this release, we've found and fixed a few severe issues from the previous release, including two crashes and one performance degradation. Crashes [#7314](https://github.com/flutter/flutter/issues/7314) Flutter crash on startup (metabug) Performance [#25381](https://github.com/flutter/flutter/pull/25381) Add cull opacity perf test to device lab ## Breaking Changes In an effort to continue to improve Flutter since 1.0 to meet customer needs, we have had to make a few breaking changes: ### [#8769](https://github.com/flutter/flutter/pull/8769) Rename ListItem to ListTile, document ListTile fixed height geometry Many developers were confused by the fact that ListItem was fixed height. We've renamed it to ListTile, to indicate that (like other tiles) its height is fixed, and the documentation has been updated to clearly say that about ListTile. You'll need to rename instances of the ListItem class to ListTile in your code. ### [#7518](https://github.com/flutter/engine/pull/7518) Update default flutter_assets path for iOS embedding Flutter assets for iOS applications are now found in Frameworks/App.framework/flutter_assets instead of flutter_assets. The flutter command line tool should take care of this difference, but if you are writing an AddToApp application for iOS that shares assets with Flutter, you'll need to be aware of this change. ### [#27697](https://github.com/flutter/flutter/pull/27697) Cupertino TextField Cursor Fix CupertinoTextField's cursorColor default now matches the app's theme. If this is undesirable, developers can use the cupertinoOverrideTheme property of ThemeData to provide a Cupertino-specific override using a CupertinoThemeData object, e.g: ``` Widget build(BuildContext context) { // Set theme data for override in the CupertinoThemeData's constructor Theme.of(context).cupertinoOverrideTheme = CupertinoThemeData( brightness: Brightness.dark, primaryColor: Color(0xFF42A5F5) ); return Text( 'Example', style: Theme.of(context).textTheme.title, ); } ``` ### [#23424](https://github.com/flutter/flutter/pull/23424) Teach drag start behaviors to DragGestureRecognizer By default, a drag gesture detector's onStart callback will be called with the location of where a drag gesture is detected (i.e. after dragging a certain number of pixels) instead of at the touch down location. To use the old functionality with a given drag gesture recognizer, the dragStartBehavior variable of the recognizer should be set DragStartBehavior.down, e.g., include the bolded line below when declaring your GestureDecorator: ``` 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… ``` ### [#26238](https://github.com/flutter/flutter/pull/26238) Remove long-deprecated TwoLevelList Removed the long-deprecated TwoLevelList widget; use ListView with ExpansionTile instead. See [this example](https://github.com/flutter/flutter/blob/v1.2.1/examples/catalog/lib/expansion_tile_sample.dart) for a sample that uses ExpansionTile. ###[#7442](https://github.com/flutter/engine/pull/7442) Move Picture.toImage rasterization to the GPU thread Picture.toImage now returns a `Future<Image>` instead. This permits image rasterization to occur on the GPU thread, improving performance in many cases and ensuring correct results. At a minimum, you'll need to declare methods invoking on Picture instances as async, and use await, like this: ``` `void usePictureImage(Picture p) async { var image = await p.toImage(); // Do something with the pixels in image…. } ``` However, your application may well be performing other asynchronous actions, and you should consider how you want to handle image processing in that light. For more on Dart's support for asynchronous programming and the Future class, see [https://www.dartlang.org/tutorials/language/futures.](https://www.dartlang.org/tutorials/language/futures) ### [#7567](https://github.com/flutter/engine/pull/7567) Rename FlutterResult in embedder.h In the Embedder API, the FlutterResult type has been renamed to FlutterEngineResult to better explain its purpose. You'll need to rename any instances of the former to the latter. ### [#7414](https://github.com/flutter/engine/pull/7414) Strut implementation Rename dart:ui ParagraphStyle.lineHeight to ParagraphStyle.height. The ParagraphStyle.lineHeight property previously did not do anything and was renamed to stay consistent with TextStyle.height. You'll need to rename any instances of the former to the latter. ## Regressions Soon after our 1.2 release, we found two regressions: * [#28640](https://github.com/flutter/flutter/issues/28640) NoSuchMethodError: android.view.MotionEvent.isFromSource [flutter/flutter#24830](https://github.com/flutter/flutter/pull/24830) ("Implement hover support for mouse pointers.") is using an Android API that doesn't exist on older devices. This can cause a crash on Android 4.1 (Jellybean) and 4.1 (Jellybean MR1). * [#28484](https://github.com/flutter/flutter/issues/28484) Widget rendering strange since Flutter update This can cause rendering issues when loading certain images on physical iOS devices. To get a fix for these regressions, once beta 1.3 lands in March, you can switch to the beta channel and perform a "flutter upgrade" at the command line. At the time of this writing, that will update you to at least version 1.3.8, which includes [flutter/engine#8006](https://github.com/flutter/engine/pull/8006) ("Guard against using Android API not defined in API level 16 & 17") and the Skia commit that fixes the rendering issue. For the crashing issue, the two affected versions of Android are more than ten years old and represent at most 2.5% of Android users, few of which are likely to be installing new Android applications, whether they're Flutter or not. Even so, we hate to leave known regressions in a stable release, but after much internal debate, we decided it was the best way to proceed for Flutter developers and their app users. Our ideal fix for any serious issue is to create a "hotfix" release by taking an existing release and "cherry picking" the fixes that we'd like to apply. The ability to hotfix an existing stable release is something that we implemented for 1.2 but have not quite gotten to production quality. The consequence of this is that if we had created a new stable "1.2.1-a" release with the fix for the regressions, we'd have stranded all of our users at that branch; updating to future branches would've required users to remove and reinstall Flutter from scratch, which was clearly unacceptable. We are working hard to validate our ability to hotfix in 1.3+ so that we don't have this problem again. Another option would have been to bring 1.3 to a stable release. Our current policy is to only bring out a new stable release once per quarter to reduce churn for Flutter developers. As of this writing, the pre-stable 1.3 release contains 104 framework commits (and even more engine, Dart, and Skia commits), any of which is a risk to how your current apps are running. To reduce that risk, we leave releases in beta for a month, let developers test them, and only promote releases to the stable channel when we're confident in them. That's how we maintain stability in the quarterly releases. Our next stable release is currently planned for May, 2019, which is the first stable release that will include the fix for this regression. If you are affected by [#28640](https://github.com/flutter/flutter/issues/28640) and feel like the workaround to use the pre-release 1.3 is not an option for you, please let us know by on [flutter/flutter#29235](https://github.com/flutter/flutter/issues/29235) itself. Similarly, if you are affected by [#28484](https://github.com/flutter/flutter/issues/28484), et us know on [flutter/flutter/#29360](https://github.com/flutter/flutter/issues/29360). If we find that there's a lot of feedback from the Flutter community that we made the wrong decision here, we'll use your feedback to reevaluate. Flutter is, after all, a community effort, and your opinions matter. ## Tooling Releases In addition to Flutter framework changes in the 1.2 release, we've made a number of tooling releases in the same timeframe, which you can read about here: * Dart & Flutter support for Visual Studio Code: versions [2.21](https://dartcode.org/releases/v2-21/), [2.22](https://dartcode.org/releases/v2-22/), [2.23](https://dartcode.org/releases/v2-23/) and [2.24](https://dartcode.org/releases/v2-24/). * Dart & Flutter support for IntelliJ & Android Studio: [January, 2019](https://groups.google.com/forum/#!searchin/flutter-dev/nilay%7Csort:date/flutter-dev/VCfGRhDsHgs/JcYKxkxHBAAJ) and [February, 2019](https://groups.google.com/forum/#!searchin/flutter-dev/nilay%7Csort:date/flutter-dev/VCfGRhDsHgs/JcYKxkxHBAAJ) releases. * Dart DevTools [alpha release](/tools/devtools). ## Full Issue List You can see [the full list of PRs committed in this release](/release/release-notes/changelogs/changelog-1.2.1). [Android App Bundles]: https://developer.android.com/guide/app-bundle/
website/src/release/release-notes/release-notes-1.2.1.md/0
{ "file_path": "website/src/release/release-notes/release-notes-1.2.1.md", "repo_id": "website", "token_count": 4944 }
1,386
--- title: Videos description: > Available videos on various aspects of developing in Flutter. --- These Flutter videos, produced both internally at Google and by the Flutter community, might help if you are a visual learner. Note that many people make Flutter videos. This page shows some that we like, but there are many others, including some in different languages. --- ## Series ### Flutter Forward Even if you couldn't make it to Nairobi for the in-person event, you can enjoy the content created for Flutter Forward! <iframe width="560" height="315" src="{{site.yt.embed}}/zKQYGKAe5W8?start=2778" title="Watch the livestream from Flutter Forward in Nairobi Kenya from 2023" {{site.yt.set}}></iframe> Flutter Forward livestream<br> [Flutter Forward playlist][] [Flutter Forward playlist]: {{site.yt.playlist}}PLjxrf2q8roU3LvrdR8Hv_phLrTj0xmjnD ### Get ready for Flutter Forward Flutter Forward is happening on Jan 25th, in Nairobi, Kenya. Before the event, the Flutter team provided 17 days of Flutter featuring new content and activities leading up to the event. This playlist contains these and other pre-event videos relating to Flutter Forward. <iframe width="560" height="315" src="{{site.yt.embed}}/hpgkrUPRBjc?start=6" title="Watch the videos to prepare you for Flutter Forward 2023" {{site.yt.set}}></iframe> 17 Days of Flutter!<br> [Get ready for Flutter Forward playlist][] [Get ready for Flutter Forward playlist]: {{site.yt.playlist}}PLjxrf2q8roU3PUEaM4yYXqvFMEwOluBNl ### Learning to Fly {{site.alert.note}} Season 2 of Learning to Fly has been released as part of the 17 Days of Flutter, leading up to the 3.7 release! [Season 2][] centers around creating a platform game, DoodleDash, using the Flame engine. {{site.alert.end}} [Season 2]: {{site.yt.watch}}?v=ILTx1Wa33Z0 Follow along with Khanh's journey as she learns Flutter. From ideation down to the moments of confusion, learn alongside her as she asks important questions like: "What is the best way to build out a theme? How to approach using fonts?" And more! <iframe width="560" height="315" src="{{site.yt.embed}}/CkcvVZZEsJE" title="Learn how to build your first Flutter app" {{site.yt.set}}></iframe> Building my first Flutter app | Learning to Fly<br> [Learning to Fly playlist][] [Learning to Fly playlist]: {{site.yt.playlist}}PLjxrf2q8roU3X18pAQWLyCJaa79RpqWnn Here are some of the series offered on the [flutterdev YouTube channel][]. For more information, check out _all_ of the [Flutter channel's playlists][]. [Flutter channel's playlists]: {{site.social.youtube}}/playlists [flutterdev YouTube channel]: {{site.social.youtube}} ### Decoding Flutter This series focuses on tips, tricks, best practices, and general advice on getting the most out of Flutter. In the comments section for this series, you can submit suggestions future episodes. <iframe width="560" height="315" src="{{site.yt.embed}}/QIW35-vcA2o" title="Watch this series on best practices for Flutter: Decoding Flutter" {{site.yt.set}}></iframe> Introducing Decoding Flutter [Decoding Flutter playlist][] [Decoding Flutter playlist]: {{site.yt.playlist}}PLjxrf2q8roU1fRV40Ec8200rX6OuQkmnl ### Flutter widget of the week Do you have 60 seconds? Each one-minute video highlights a Flutter widget. <iframe width="560" height="315" src="{{site.yt.embed}}/b_sQ9bMltGU" title="Watch this series on different Flutter Widgets: Widget of the Week" {{site.yt.set}}></iframe> Introducing widget of the week<br> [Flutter widget of the week playlist][] [Flutter widget of the week playlist]: {{site.yt.playlist}}PLjxrf2q8roU23XGwz3Km7sQZFTdB996iG ### Flutter package of the week If you have another minute (or two), each of these videos highlights a Flutter package. <iframe width="560" height="315" src="{{site.yt.embed}}/QFcFEpFmNJ8" title="Watch this series on different Flutter Packages: Package of the Week" {{site.yt.set}}></iframe> `flutter_slidable` package [Flutter package of the week playlist][] [Flutter package of the week playlist]: {{site.yt.playlist}}PLjxrf2q8roU1quF6ny8oFHJ2gBdrYN_AK ### The Boring Flutter show This series features Flutter programmers coding, unscripted and in real time. Mistakes, solutions (some of them correct), and snazzy intro music included. <iframe width="560" height="315" src="{{site.yt.embed}}/vqPG1tU6-c0" title="Watch this live Flutter coding series: The Boring Show" {{site.yt.set}}></iframe> Introducing the Boring Flutter show<br> [The Boring Flutter show playlist][] [The Boring Flutter show playlist]: {{site.yt.playlist}}PLjxrf2q8roU3ahJVrSgAnPjzkpGmL9Czl ### Flutter at Google I/O 2022 Google I/O 2022 is over, but you can still catch the great Flutter content! <iframe width="560" height="315" src="{{site.yt.embed}}/w_ezWG1yKQQ" title="Watch highlights about Flutter from Google I/O 2022" {{site.yt.set}}></iframe> [Flutter at Google I/O playlist][] [Flutter at Google I/O playlist]: {{site.yt.playlist}}PLjxrf2q8roU1kHjuHoFGBLCxjy4h2WOcP ### Flutter Engage 2021 [Flutter Engage 2021][] was a day-long event that officially launched Flutter 2. [Flutter Engage 2021]: https://events.flutter.dev/ Check out the Flutter Engage 2021 highlights reel. <iframe width="560" height="315" src="{{site.yt.embed}}/IdrCyS7EF8M" title="Watch highlights about Flutter from Flutter Engage 2021" {{site.yt.set}}></iframe> Watch recordings of the sessions on the Flutter YouTube channel. <iframe width="560" height="315" src="{{site.yt.embed}}/zSbsIiluixw" title="Watch the Flutter sessions from Flutter Engage 2021" {{site.yt.set}}></iframe> Keynote<br> [Flutter Engage 2021 playlist][] Watch recordings of the sessions offered by the Flutter community. <iframe width="560" height="315" src="{{site.yt.embed}}/-_de6IfY2RU" title="Watch the Flutter community sessions from Flutter Engage 2021" {{site.yt.set}}></iframe> [Flutter Engage community talks playlist][] [Flutter Engage 2021 playlist]: {{site.yt.playlist}}PLjxrf2q8roU21cXt24HLm-ZODXmr4Jw0C [Flutter Engage community talks playlist]: {{site.yt.playlist}}PLjxrf2q8roU1ln3WoiGTUvLr7ZrPPFvXv ### Flutter in focus Five-to-ten minute tutorials (more or less) on using Flutter. <iframe width="560" height="315" src="{{site.yt.embed}}/wgTBLj7rMPM" title="Watch this series on Flutter tutorials: Flutter in Focus" {{site.yt.set}}></iframe> Introducing Flutter in focus<br> [Flutter in focus playlist][] [Flutter in focus playlist]: {{site.yt.playlist}}PLjxrf2q8roU2HdJQDjJzOeO6J3FoFLWr2 ## Conference talks Here are a some Flutter talks given at various conferences. <iframe width="560" height="315" src="{{site.yt.embed}}/d_m5csmrf7I" title="Watch this series on Flutter talks given at other conferences" {{site.yt.set}}></iframe> [Conference talks playlist][] [Conference talks playlist]: {{site.yt.playlist}}PLjxrf2q8roU1UJ0OEpANodVMVm1GeE7Ti ## Flutter developer stories Videos showing how various customers, such as Abbey Road Studio, Hamilton, and Alibaba, have used Flutter to create beautiful compelling apps with millions of downloads. <iframe width="560" height="315" src="{{site.yt.embed}}/_ACWeGGBP4E" title="Watch this series on Flutter developer stories" {{site.yt.set}}></iframe> [Flutter developer stories playlist][] [Flutter developer stories playlist]: {{site.yt.playlist}}PLjxrf2q8roU33POuWi4bK0zvDpAHK6759
website/src/resources/videos.md/0
{ "file_path": "website/src/resources/videos.md", "repo_id": "website", "token_count": 2409 }
1,387
--- title: Testing plugins description: Learn how to test your plugin package. --- All of the [usual types of Flutter tests][] apply to plugin packages as well, but because plugins contain native code they often also require other kinds of tests to test all of their functionality. [usual types of Flutter tests]: /testing/overview {{site.alert.note}} To learn how to test your plugin code, read on. To learn how to avoid crashes from a plugin when testing your Flutter app, check out [Plugins in Flutter tests][]. {{site.alert.end}} [Plugins in Flutter tests]: /testing/plugins-in-tests ## Types of plugin tests To see examples of each of these types of tests, you can [create a new plugin from the plugin template][plugin-tests] and look in the indicated directories. * <strong>Dart [unit tests][] and [widget tests][]</strong>. These tests allow you to test the Dart portion of your plugin just as you would test the Dart code of a non-plugin package. However, the plugin's native code [won't be loaded][], so any calls to platform channels need to be [mocked in tests][]. See the `test` directory for an example. * <strong>Dart [integration tests][]</strong>. Since integration tests run in the context of a Flutter application (the example app), they can test both the Dart and native code, as well as the interaction between them. They are also useful for unit testing web implementation code that needs to run in a browser. These are often the most important tests for a plugin. However, Dart integration tests can't interact with native UI, such as native dialogs or the contents of platform views. See the `example/integration_test` directory for an example. * <strong>Native unit tests.</strong> Just as Dart unit tests can test the Dart portions of a plugin in isolation, native unit tests can test the native parts in isolation. Each platform has its own native unit test system, and the tests are written in the same native languages as the code it is testing. Native unit tests can be especially valuable if you need to mock out APIs wrapped by your plugin code, which isn't possible in a Dart integration test. You can set up and use any native test frameworks you are familiar with for each platform, but the following are already configured in the plugin template: * <strong>Android</strong>: [JUnit][] tests can be found in `android/src/test/`. * <strong>iOS</strong> and <strong>macOS</strong>: [XCTest][] tests can be found in `example/ios/RunnerTests/` and `example/macos/RunnerTests/` respectively. These are in the example directory, not the top-level package directory, because they are run via the example app's project. * <strong>Linux</strong> and <strong>Windows</strong>: [GoogleTest][] tests can be found in `linux/test/` and `windows/test/`, respectively. Other types of tests, which aren't currently pre-configured in the template, are <strong>native UI tests</strong>. Running your application under a native UI testing framework, such as [Espresso][] or [XCUITest][], enables tests that interact with both native and Flutter UI elements, so can be useful if your plugin can't be tested without native UI interactions. [Espresso]: {{site.repo.packages}}/tree/main/packages/espresso [GoogleTest]: {{site.github}}/google/googletest [integration tests]: /cookbook/testing/integration/introduction [JUnit]: {{site.github}}/junit-team/junit4/wiki/Getting-started [mocked in tests]: /testing/plugins-in-tests#mock-the-platform-channel [plugin-tests]: /packages-and-plugins/developing-packages#step-1-create-the-package-1 [unit tests]: /cookbook/testing/unit/introduction [widget tests]: /cookbook/testing/widget/introduction [won't be loaded]: /testing/plugins-in-tests [XCTest]: {{site.apple-dev}}/documentation/xctest [XCUITest]: {{site.apple-dev}}/library/archive/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/09-ui_testing.html ## Running tests ### Dart unit tests These can be run like any other Flutter unit tests, either from your preferred Flutter IDE, or using `flutter test`. ### Integration tests For information on running this type of test, check out the [integration test documentation][]. The commands must be run in the `example` directory. [integration test documentation]: /cookbook/testing/integration/introduction#5-run-the-integration-test ### Native unit tests For all platforms, you need to build the example application at least once before running the unit tests, to ensure that all of the platform-specific build files have been created. <strong>Android JUnit</strong><br> If you have the example opened as an Android project in Android Studio, you can run the unit tests using the [Android Studio test UI][]. To run the tests from the command line, use the following command in the `example/android` directory: ```sh ./gradlew testDebugUnitTest ``` <strong>iOS and macOS XCTest</strong><br> If you have the example app opened in Xcode, you can run the unit tests using the [Xcode Test UI][]. To run the tests from the command line, use the following command in the `example/ios` (for iOS) or `example/macos` (for macOS) directory: ```sh xcodebuild test -workspace Runner.xcworkspace -scheme Runner -configuration Debug ``` For iOS tests, you might need to first open `Runner.xcworkspace` in Xcode to configure code signing. <strong>Linux GoogleTest</strong><br> To run the tests from the command line, use the following command in the example directory, replacing "my_plugin" with your plugin project name: ```sh build/linux/plugins/x64/debug/my_plugin/my_plugin_test ``` If you built the example app in release mode rather than debug, replace "debug" with "release". <strong>Windows GoogleTest</strong><br> If you have the example app opened in Visual Studio, you can run the unit tests using the [Visual Studio test UI][]. To run the tests from the command line, use the following command in the example directory, replacing "my_plugin" with your plugin project name: ```sh build/windows/plugins/my_plugin/Debug/my_plugin_test.exe ``` If you built the example app in release mode rather than debug, replace "Debug" with "Release". ## What types of tests to add The [general advice for testing Flutter projects][general advice] applies to plugins as well. Some extra considerations for plugin testing: * Since only integration tests can test the communication between Dart and the native languages, try to have at least one integration test of each platform channel call. * If some flows can't be tested using integration tests—for example if they require interacting with native UI or mocking device state—consider writing "end to end" tests of the two halves using unit tests: * Native unit tests that set up the necessary mocks, then call into the method channel entry point with a synthesized call and validate the method response. * Dart unit tests that mock the platform channel, then call the plugin's public API and validate the results. [Android Studio test UI]: {{site.android-dev}}/studio/test/test-in-android-studio [general advice]: /testing/overview [Visual Studio test UI]: https://learn.microsoft.com/en-us/visualstudio/test/getting-started-with-unit-testing?view=vs-2022&tabs=dotnet%2Cmstest#run-unit-tests [Xcode Test UI]: {{site.apple-dev}}/library/archive/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/05-running_tests.html
website/src/testing/testing-plugins.md/0
{ "file_path": "website/src/testing/testing-plugins.md", "repo_id": "website", "token_count": 2078 }
1,388
## CPU profiler Start recording a CPU profile by clicking **Record**. When you are done recording, click **Stop**. At this point, CPU profiling data is pulled from the VM and displayed in the profiler views (Call tree, Bottom up, Method table, and Flame chart). To load all available CPU samples without manually recording and stopping, you can click **Load all CPU samples**, which pulls all CPU samples that the VM has recorded and stored in its ring buffer, and then displays those CPU samples in the profiler views. ### Bottom up This table provides a bottom-up representation of a CPU profile. This means that each top-level method, or root, in the bottom up table is actually the top method in the call stack for one or more CPU samples. In other words, each top-level method in a bottom up table is a leaf node from the top down table (the call tree). In this table, a method can be expanded to show its _callers_. This view is useful for identifying expensive _methods_ in a CPU profile. When a root node in this table has a high _self_ time, that means that many CPU samples in this profile ended with that method on top of the call stack. ![Screenshot of the Bottom up view](/assets/images/docs/tools/devtools/bottom-up-view.png) See the [Guidelines](#guidelines) section below to learn how to enable the blue and green vertical lines seen in this image. Tooltips can help you understand the values in each column: <dl markdown="1"> <dt markdown="1">**Total time** </dt> <dd markdown="1">For top-level methods in the bottom-up tree (stack frames that were at the top of at least one CPU sample), this is the time the method spent executing its own code, as well as the code for any methods that it called. </dd> <dt markdown="1">**Self time** </dt> <dd markdown="1">For top-level methods in the bottom-up tree (stack frames that were at the top of at least one CPU sample), this is the time the method spent executing only its own code.<br><br> For children methods in the bottom-up tree (the callers), this is the self time of the top-level method (the callee) when called through the child method (the caller). </dd> </dl> **Table element** (self time) ![Screenshot of a bottom up table](/assets/images/docs/tools/devtools/table-element.png) ### Call tree This table provides a top-down representation of a CPU profile. This means that each top-level method in the call tree is a root of one or more CPU samples. In this table, a method can be expanded to show its _callees_. This view is useful for identifying expensive _paths_ in a CPU profile. When a root node in this table has a high _total_ time, that means that many CPU samples in this profile started with that method on the bottom of the call stack. ![Screenshot of a call tree table](/assets/images/docs/tools/devtools/call-tree.png) See the [Guidelines](#guidelines) section below to learn how to enable the blue and green vertical lines seen in this image. Tooltips can help you understand the values in each column: <dl markdown="1"> <dt markdown="1">**Total time** </dt> <dd>Time that a method spent executing its own code as well as the code for any methods it called. </dd> <dt markdown="1">**Self time** </dt> <dd>Time the method spent executing only its own code. </dd> </dl> ### Method table The method table provides CPU statistics for each method contained in a CPU profile. In the table on the left, all available methods are listed with their **total** and **self** time. **Total** time is the combined time that a method spent **anywhere** on the call stack, or in other words, the time a method spent executing its own code and any code for methods that it called. **Self** time is the combined time that a method spent on top of the call stack, or in other words, the time a method spent executing only its own code. ![Screenshot of a call tree table](/assets/images/docs/tools/devtools/method-table.png) Selecting a method from the table on the left shows the call graph for that method. The call graph shows a method's callers and callees and their respective caller / callee percentages. ### Flame chart The flame chart view is a graphical representation of the [Call tree](#call-tree). This is a top-down view of a CPU profile, so in this chart, the top-most method calls the one below it. The width of each flame chart element represents the amount of time that a method spent on the call stack. Like the Call tree, this view is useful for identifying expensive paths in a CPU profile. ![Screenshot of a flame chart](/assets/images/docs/tools/devtools/cpu-flame-chart.png) The help menu, which can be opened by clicking the `?` icon next to the search bar, provides information about how to navigate and zoom within the chart and a color-coded legend. ![Screenshot of flame chart help](/assets/images/docs/tools/devtools/flame-chart-help.png){:width="70%"} ### CPU sampling rate DevTools sets a default rate at which the VM collects CPU samples: 1 sample / 250 μs (microseconds). This is selected by default on the CPU profiler page as "Cpu sampling rate: medium". This rate can be modified using the selector at the top of the page. ![Screenshot of cpu sampling rate menu](/assets/images/docs/tools/devtools/cpu-sampling-rate-menu.png){:width="70%"} The **low**, **medium**, and **high** sampling rates are 1,000 Hz, 4,000 Hz, and 20,000 Hz, respectively. It's important to know the trade-offs of modifying this setting. A profile that was recorded with a **higher** sampling rate yields a more fine-grained CPU profile with more samples. This might affect performance of your app since the VM is being interrupted more often to collect samples. This also causes the VM's CPU sample buffer to overflow more quickly. The VM has limited space where it can store CPU sample information. At a higher sampling rate, the space fills up and begins to overflow sooner than it would have if a lower sampling rate was used. This means that you might not have access to CPU samples from the beginning of the recorded profile, depending on whether the buffer overflows during the time of recording. A profile that was recorded with a lower sampling rate yields a more coarse-grained CPU profile with fewer samples. This affects your app's performance less, but you might have access to less information about what the CPU was doing during the time of the profile. The VM's sample buffer also fills more slowly, so you can see CPU samples for a longer period of app run time. This means that you have a better chance of viewing CPU samples from the beginning of the recorded profile. ### Filtering When viewing a CPU profile, you can filter the data by library, method name, or [`UserTag`][]. ![Screenshot of filter by tag menu](/assets/images/docs/tools/devtools/filter-by-tag.png) [`UserTag`]: {{site.api}}/flutter/dart-developer/UserTag-class.html ## Guidelines When looking at a call tree or bottom up view, sometimes the trees can be very deep. To help with viewing parent-child relationships in a deep tree, enable the **Display guidelines** option. This adds vertical guidelines between parent and child in the tree. ![Screenshot of display options](/assets/images/docs/tools/devtools/display-options.png)
website/src/tools/devtools/_profiler.md/0
{ "file_path": "website/src/tools/devtools/_profiler.md", "repo_id": "website", "token_count": 1952 }
1,389
--- short-title: 2.12.1 release notes description: Release notes for Dart and Flutter DevTools version 2.12.1. toc: false --- {% include_relative release-notes-2.12.1-src.md %}
website/src/tools/devtools/release-notes/release-notes-2.12.1.md/0
{ "file_path": "website/src/tools/devtools/release-notes/release-notes-2.12.1.md", "repo_id": "website", "token_count": 61 }
1,390
--- short-title: 2.19.0 release notes description: Release notes for Dart and Flutter DevTools version 2.19.0. toc: false --- {% include_relative release-notes-2.19.0-src.md %}
website/src/tools/devtools/release-notes/release-notes-2.19.0.md/0
{ "file_path": "website/src/tools/devtools/release-notes/release-notes-2.19.0.md", "repo_id": "website", "token_count": 61 }
1,391
--- short-title: 2.27.0 release notes description: Release notes for Dart and Flutter DevTools version 2.27.0. toc: false --- {% include_relative release-notes-2.27.0-src.md %}
website/src/tools/devtools/release-notes/release-notes-2.27.0.md/0
{ "file_path": "website/src/tools/devtools/release-notes/release-notes-2.27.0.md", "repo_id": "website", "token_count": 61 }
1,392
--- short-title: 2.31.0 release notes description: Release notes for Dart and Flutter DevTools version 2.31.0. toc: false --- {% include_relative release-notes-2.31.0-src.md %}
website/src/tools/devtools/release-notes/release-notes-2.31.0.md/0
{ "file_path": "website/src/tools/devtools/release-notes/release-notes-2.31.0.md", "repo_id": "website", "token_count": 61 }
1,393
--- title: Code formatting description: > Flutter's code formatter formats your code following recommended style guidelines. --- While your code might follow any preferred style&mdash;in our experience&mdash;teams of developers might find it more productive to: * Have a single, shared style, and * Enforce this style through automatic formatting. The alternative is often tiring formatting debates during code reviews, where time might be better spent on code behavior rather than code style. ## Automatically formatting code in VS Code Install the `Flutter` extension (see [Editor setup](/get-started/editor)) to get automatic formatting of code in VS Code. To automatically format the code in the current source code window, right-click in the code window and select `Format Document`. You can add a keyboard shortcut to this VS Code **Preferences**. To automatically format code whenever you save a file, set the `editor.formatOnSave` setting to `true`. ## Automatically formatting code in Android Studio and IntelliJ Install the `Dart` plugin (see [Editor setup](/get-started/editor)) to get automatic formatting of code in Android Studio and IntelliJ. To format your code in the current source code window: * In macOS, press <kbd>Cmd</kbd> + <kbd>Option</kbd> + <kbd>L</kbd>. * In Windows and Linux, press <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>L</kbd>. Android Studio and IntelliJ also provide a checkbox named **Format code on save** on the Flutter page in **Preferences** on macOS or **Settings** on Windows and Linux. This option corrects formatting in the current file when you save it. ## Automatically formatting code with the `dart` command To correct code formatting in the command line interface (CLI), run the `dart format` command: ```terminal $ dart format path1 path2 [...] ``` ## Using trailing commas Flutter code often involves building fairly deep tree-shaped data structures, for example in a `build` method. To get good automatic formatting, we recommend you adopt the optional *trailing commas*. The guideline for adding a trailing comma is simple: Always add a trailing comma at the end of a parameter list in functions, methods, and constructors where you care about keeping the formatting you crafted. This helps the automatic formatter to insert an appropriate amount of line breaks for Flutter-style code. Here is an example of automatically formatted code *with* trailing commas: ![Automatically formatted code with trailing commas](/assets/images/docs/tools/android-studio/trailing-comma-with.png){:width="100%"} And the same code automatically formatted code *without* trailing commas: ![Automatically formatted code without trailing commas](/assets/images/docs/tools/android-studio/trailing-comma-without.png){:width="100%"}
website/src/tools/formatting.md/0
{ "file_path": "website/src/tools/formatting.md", "repo_id": "website", "token_count": 729 }
1,394
--- title: Adding assets and images description: How to use images (and other assets) in your Flutter app. short-title: Assets and images --- <?code-excerpt path-base="ui/assets_and_images/lib"?> Flutter apps can include both code and _assets_ (sometimes called resources). An asset is a file that is bundled and deployed with your app, and is accessible at runtime. Common types of assets include static data (for example, JSON files), configuration files, icons, and images (JPEG, WebP, GIF, animated WebP/GIF, PNG, BMP, and WBMP). ## Specifying assets Flutter uses the [`pubspec.yaml`][] file, located at the root of your project, to identify assets required by an app. Here is an example: ```yaml flutter: assets: - assets/my_icon.png - assets/background.png ``` To include all assets under a directory, specify the directory name with the `/` character at the end: ```yaml flutter: assets: - directory/ - directory/subdirectory/ ``` {{site.alert.note}} Only files located directly in the directory are included. [Resolution-aware asset image variants](#resolution-aware) are the only exception. To add files located in subdirectories, create an entry per directory. {{site.alert.end}} ### Asset bundling The `assets` subsection of the `flutter` section specifies files that should be included with the app. Each asset is identified by an explicit path (relative to the `pubspec.yaml` file) where the asset file is located. The order in which the assets are declared doesn't matter. The actual directory name used (`assets` in first example or `directory` in the above example) doesn't matter. During a build, Flutter places assets into a special archive called the _asset bundle_ that apps read from at runtime. ## Loading assets Your app can access its assets through an [`AssetBundle`][] object. The two main methods on an asset bundle allow you to load a string/text asset (`loadString()`) or an image/binary asset (`load()`) out of the bundle, given a logical key. The logical key maps to the path to the asset specified in the `pubspec.yaml` file at build time. ### Loading text assets Each Flutter app has a [`rootBundle`][] object for easy access to the main asset bundle. It is possible to load assets directly using the `rootBundle` global static from `package:flutter/services.dart`. However, it's recommended to obtain the `AssetBundle` for the current `BuildContext` using [`DefaultAssetBundle`][], rather than the default asset bundle that was built with the app; this approach enables a parent widget to substitute a different `AssetBundle` at run time, which can be useful for localization or testing scenarios. Typically, you'll use `DefaultAssetBundle.of()` to indirectly load an asset, for example a JSON file, from the app's runtime `rootBundle`. {% comment %} Need example here to show obtaining the AssetBundle for the current BuildContext using DefaultAssetBundle.of {% endcomment %} Outside of a `Widget` context, or when a handle to an `AssetBundle` is not available, you can use `rootBundle` to directly load such assets. For example: <?code-excerpt "main.dart (RootBundle)"?> ```dart import 'package:flutter/services.dart' show rootBundle; Future<String> loadAsset() async { return await rootBundle.loadString('assets/config.json'); } ``` ### Loading images To load an image, use the [`AssetImage`][] class in a widget's `build()` method. For example, your app can load the background image from the asset declarations in the previous example: <?code-excerpt "main.dart (BackgroundImage)"?> ```dart return const Image(image: AssetImage('assets/background.png')); ``` ### Resolution-aware image assets {#resolution-aware} Flutter can load resolution-appropriate images for the current [device pixel ratio][]. [`AssetImage`][] will map a logical requested asset onto one that most closely matches the current [device pixel ratio][]. For this mapping to work, assets should be arranged according to a particular directory structure: ```text .../image.png .../Mx/image.png .../Nx/image.png ...etc. ``` Where _M_ and _N_ are numeric identifiers that correspond to the nominal resolution of the images contained within. In other words, they specify the device pixel ratio that the images are intended for. In this example, `image.png` is considered the *main asset*, while `Mx/image.png` and `Nx/image.png` are considered to be *variants*. The main asset is assumed to correspond to a resolution of 1.0. For example, consider the following asset layout for an image named `my_icon.png`: ```text .../my_icon.png (mdpi baseline) .../1.5x/my_icon.png (hdpi) .../2.0x/my_icon.png (xhdpi) .../3.0x/my_icon.png (xxhdpi) .../4.0x/my_icon.png (xxxhdpi) ``` On devices with a device pixel ratio of 1.8, the asset `.../2.0x/my_icon.png` is chosen. For a device pixel ratio of 2.7, the asset `.../3.0x/my_icon.png` is chosen. If the width and height of the rendered image are not specified on the `Image` widget, the nominal resolution is used to scale the asset so that it occupies the same amount of screen space as the main asset would have, just with a higher resolution. That is, if `.../my_icon.png` is 72px by 72px, then `.../3.0x/my_icon.png` should be 216px by 216px; but they both render into 72px by 72px (in logical pixels), if width and height are not specified. {{site.alert.note}} [Device pixel ratio][] depends on [MediaQueryData.size][], which requires having either [MaterialApp][] or [CupertinoApp][] as an ancestor of your [`AssetImage`][]. {{site.alert.end}} #### Bundling of resolution-aware image assets {#resolution-aware-bundling} You only need to specify the main asset or its parent directory in the `assets` section of `pubspec.yaml`. Flutter bundles the variants for you. Each entry should correspond to a real file, with the exception of the main asset entry. If the main asset entry doesn't correspond to a real file, then the asset with the lowest resolution is used as the fallback for devices with device pixel ratios below that resolution. The entry should still be included in the `pubspec.yaml` manifest, however. Anything using the default asset bundle inherits resolution awareness when loading images. (If you work with some of the lower level classes, like [`ImageStream`][] or [`ImageCache`][], you'll also notice parameters related to scale.) ### Asset images in package dependencies {#from-packages} To load an image from a [package][] dependency, the `package` argument must be provided to [`AssetImage`][]. For instance, suppose your application depends on a package called `my_icons`, which has the following directory structure: ```text .../pubspec.yaml .../icons/heart.png .../icons/1.5x/heart.png .../icons/2.0x/heart.png ...etc. ``` To load the image, use: <?code-excerpt "main.dart (PackageImage)"?> ```dart return const AssetImage('icons/heart.png', package: 'my_icons'); ``` Assets used by the package itself should also be fetched using the `package` argument as above. #### Bundling of package assets If the desired asset is specified in the `pubspec.yaml` file of the package, it's bundled automatically with the application. In particular, assets used by the package itself must be specified in its `pubspec.yaml`. A package can also choose to have assets in its `lib/` folder that are not specified in its `pubspec.yaml` file. In this case, for those images to be bundled, the application has to specify which ones to include in its `pubspec.yaml`. For instance, a package named `fancy_backgrounds` could have the following files: ```text .../lib/backgrounds/background1.png .../lib/backgrounds/background2.png .../lib/backgrounds/background3.png ``` To include, say, the first image, the `pubspec.yaml` of the application should specify it in the `assets` section: ```yaml flutter: assets: - packages/fancy_backgrounds/backgrounds/background1.png ``` The `lib/` is implied, so it should not be included in the asset path. If you are developing a package, to load an asset within the package, specify it in the `pubspec.yaml` of the package: ```yaml flutter: assets: - assets/images/ ``` To load the image within your package, use: ```dart return const AssetImage('packages/fancy_backgrounds/backgrounds/background1.png'); ``` ## Sharing assets with the underlying platform Flutter assets are readily available to platform code using the `AssetManager` on Android and `NSBundle` on iOS. ### Loading Flutter assets in Android On Android the assets are available through the [`AssetManager`][] API. The lookup key used in, for instance [`openFd`][], is obtained from `lookupKeyForAsset` on [`PluginRegistry.Registrar`][] or `getLookupKeyForAsset` on [`FlutterView`][]. `PluginRegistry.Registrar` is available when developing a plugin while `FlutterView` would be the choice when developing an app including a platform view. As an example, suppose you have specified the following in your pubspec.yaml ```yaml flutter: assets: - icons/heart.png ``` This reflects the following structure in your Flutter app. ```text .../pubspec.yaml .../icons/heart.png ...etc. ``` To access `icons/heart.png` from your Java plugin code, do the following: ```java AssetManager assetManager = registrar.context().getAssets(); String key = registrar.lookupKeyForAsset("icons/heart.png"); AssetFileDescriptor fd = assetManager.openFd(key); ``` ### Loading Flutter assets in iOS On iOS the assets are available through the [`mainBundle`][]. The lookup key used in, for instance [`pathForResource:ofType:`][], is obtained from `lookupKeyForAsset` or `lookupKeyForAsset:fromPackage:` on [`FlutterPluginRegistrar`][], or `lookupKeyForAsset:` or `lookupKeyForAsset:fromPackage:` on [`FlutterViewController`][]. `FlutterPluginRegistrar` is available when developing a plugin while `FlutterViewController` would be the choice when developing an app including a platform view. As an example, suppose you have the Flutter setting from above. To access `icons/heart.png` from your Objective-C plugin code you would do the following: ```objective-c NSString* key = [registrar lookupKeyForAsset:@"icons/heart.png"]; NSString* path = [[NSBundle mainBundle] pathForResource:key ofType:nil]; ``` To access `icons/heart.png` from your Swift app you would do the following: ```swift let key = controller.lookupKey(forAsset: "icons/heart.png") let mainBundle = Bundle.main let path = mainBundle.path(forResource: key, ofType: nil) ``` For a more complete example, see the implementation of the Flutter [`video_player` plugin][] on pub.dev. The [`ios_platform_images`][] plugin on pub.dev wraps up this logic in a convenient category. You fetch an image as follows: **Objective-C:** ```objective-c [UIImage flutterImageWithName:@"icons/heart.png"]; ``` **Swift:** ```swift UIImage.flutterImageNamed("icons/heart.png") ``` ### Loading iOS images in Flutter When implementing Flutter by [adding it to an existing iOS app][add-to-app], you might have images hosted in iOS that you want to use in Flutter. To accomplish that, use the [`ios_platform_images`][] plugin available on pub.dev. ## Platform assets There are other occasions to work with assets in the platform projects directly. Below are two common cases where assets are used before the Flutter framework is loaded and running. ### Updating the app icon Updating a Flutter application's launch icon works the same way as updating launch icons in native Android or iOS applications. ![Launch icon](/assets/images/docs/assets-and-images/icon.png) #### Android In your Flutter project's root directory, navigate to `.../android/app/src/main/res`. The various bitmap resource folders such as `mipmap-hdpi` already contain placeholder images named `ic_launcher.png`. Replace them with your desired assets respecting the recommended icon size per screen density as indicated by the [Android Developer Guide][]. ![Android icon location](/assets/images/docs/assets-and-images/android-icon-path.png) {{site.alert.note}} If you rename the `.png` files, you must also update the corresponding name in your `AndroidManifest.xml`'s `<application>` tag's `android:icon` attribute. {{site.alert.end}} #### iOS In your Flutter project's root directory, navigate to `.../ios/Runner`. The `Assets.xcassets/AppIcon.appiconset` directory already contains placeholder images. Replace them with the appropriately sized images as indicated by their filename as dictated by the Apple [Human Interface Guidelines][]. Keep the original file names. ![iOS icon location](/assets/images/docs/assets-and-images/ios-icon-path.png) ### Updating the launch screen <p align="center"> <img src="/assets/images/docs/assets-and-images/launch-screen.png" alt="Launch screen" /> </p> Flutter also uses native platform mechanisms to draw transitional launch screens to your Flutter app while the Flutter framework loads. This launch screen persists until Flutter renders the first frame of your application. {{site.alert.note}} This implies that if you don't call [`runApp()`][] in the `main()` function of your app (or more specifically, if you don't call [`FlutterView.render()`][] in response to [`PlatformDispatcher.onDrawFrame`][]), the launch screen persists forever. {{site.alert.end}} [`FlutterView.render()`]: {{site.api}}/flutter/dart-ui/FlutterView/render.html [`PlatformDispatcher.onDrawFrame`]: {{site.api}}/flutter/dart-ui/PlatformDispatcher/onDrawFrame.html #### Android To add a launch screen (also known as "splash screen") to your Flutter application, navigate to `.../android/app/src/main`. In `res/drawable/launch_background.xml`, use this [layer list drawable][] XML to customize the look of your launch screen. The existing template provides an example of adding an image to the middle of a white splash screen in commented code. You can uncomment it or use other [drawables][] to achieve the intended effect. For more details, see [Adding a splash screen to your Android app][]. #### iOS To add an image to the center of your "splash screen", navigate to `.../ios/Runner`. In `Assets.xcassets/LaunchImage.imageset`, drop in images named `LaunchImage.png`, `[email protected]`, `[email protected]`. If you use different filenames, update the `Contents.json` file in the same directory. You can also fully customize your launch screen storyboard in Xcode by opening `.../ios/Runner.xcworkspace`. Navigate to `Runner/Runner` in the Project Navigator and drop in images by opening `Assets.xcassets` or do any customization using the Interface Builder in `LaunchScreen.storyboard`. ![Adding launch icons in Xcode](/assets/images/docs/assets-and-images/ios-launchscreen-xcode.png){:width="100%"} For more details, see [Adding a splash screen to your iOS app][]. [add-to-app]: /add-to-app/ios [Adding a splash screen to your Android app]: /platform-integration/android/splash-screen [Adding a splash screen to your iOS app]: /platform-integration/ios/splash-screen [`AssetBundle`]: {{site.api}}/flutter/services/AssetBundle-class.html [`AssetImage`]: {{site.api}}/flutter/painting/AssetImage-class.html [`DefaultAssetBundle`]: {{site.api}}/flutter/widgets/DefaultAssetBundle-class.html [`ImageCache`]: {{site.api}}/flutter/painting/ImageCache-class.html [`ImageStream`]: {{site.api}}/flutter/painting/ImageStream-class.html [Android Developer Guide]: {{site.android-dev}}/training/multiscreen/screendensities [`AssetManager`]: {{site.android-dev}}/reference/android/content/res/AssetManager [device pixel ratio]: {{site.api}}/flutter/dart-ui/FlutterView/devicePixelRatio.html [Device pixel ratio]: {{site.api}}/flutter/dart-ui/FlutterView/devicePixelRatio.html [drawables]: {{site.android-dev}}/guide/topics/resources/drawable-resource [`FlutterPluginRegistrar`]: {{site.api}}/ios-embedder/protocol_flutter_plugin_registrar-p.html [`FlutterView`]: {{site.api}}/javadoc/io/flutter/view/FlutterView.html [`FlutterViewController`]: {{site.api}}/ios-embedder/interface_flutter_view_controller.html [Human Interface Guidelines]: {{site.apple-dev}}/design/human-interface-guidelines/app-icons [`ios_platform_images`]: {{site.pub}}/packages/ios_platform_images [layer list drawable]: {{site.android-dev}}/guide/topics/resources/drawable-resource#LayerList [`mainBundle`]: {{site.apple-dev}}/documentation/foundation/nsbundle/1410786-mainbundle [`openFd`]: {{site.android-dev}}/reference/android/content/res/AssetManager#openFd(java.lang.String) [package]: /packages-and-plugins/using-packages [`pathForResource:ofType:`]: {{site.apple-dev}}/documentation/foundation/nsbundle/1410989-pathforresource [`PluginRegistry.Registrar`]: {{site.api}}/javadoc/io/flutter/plugin/common/PluginRegistry.Registrar.html [`pubspec.yaml`]: {{site.dart-site}}/tools/pub/pubspec [`rootBundle`]: {{site.api}}/flutter/services/rootBundle.html [`runApp()`]: {{site.api}}/flutter/widgets/runApp.html [`video_player` plugin]: {{site.pub}}/packages/video_player [MediaQueryData.size]: {{site.api}}/flutter/widgets/MediaQueryData/size.html [MaterialApp]: {{site.api}}/flutter/material/MaterialApp-class.html [CupertinoApp]: {{site.api}}/flutter/cupertino/CupertinoApp-class.html
website/src/ui/assets/assets-and-images.md/0
{ "file_path": "website/src/ui/assets/assets-and-images.md", "repo_id": "website", "token_count": 5182 }
1,395
--- title: Layouts in Flutter short-title: Layout description: Learn how Flutter's layout mechanism works and how to build a layout. diff2html: true --- {% assign api = site.api | append: '/flutter' -%} {% capture examples -%} {{site.repo.this}}/tree/{{site.branch}}/examples {%- endcapture -%} <?code-excerpt path-base=""?> <style>dl, dd { margin-bottom: 0; }</style> {{site.alert.secondary}} <h4>What's the point?</h4> * Widgets are classes used to build UIs. * Widgets are used for both layout and UI elements. * Compose simple widgets to build complex widgets. {{site.alert.end}} The core of Flutter's layout mechanism is widgets. In Flutter, almost everything is a widget&mdash;even layout models are widgets. The images, icons, and text that you see in a Flutter app are all widgets. But things you don't see are also widgets, such as the rows, columns, and grids that arrange, constrain, and align the visible widgets. You create a layout by composing widgets to build more complex widgets. For example, the first screenshot below shows 3 icons with a label under each one: <div class="row mb-4"> <div class="col-12 text-center"> <img src='/assets/images/docs/ui/layout/lakes-icons.png' class="border mt-1 mb-1 mw-100" alt="Sample layout"> <img src='/assets/images/docs/ui/layout/lakes-icons-visual.png' class="border mt-1 mb-1 mw-100" alt="Sample layout with visual debugging"> </div> </div> The second screenshot displays the visual layout, showing a row of 3 columns where each column contains an icon and a label. {{site.alert.note}} Most of the screenshots in this tutorial are displayed with `debugPaintSizeEnabled` set to `true` so you can see the visual layout. For more information, see [Debugging layout issues visually][], a section in [Using the Flutter inspector][]. {{site.alert.end}} Here's a diagram of the widget tree for this UI: <img src='/assets/images/docs/ui/layout/sample-flutter-layout.png' class="mw-100" alt="Node tree"> {:.text-center} Most of this should look as you might expect, but you might be wondering about the containers (shown in pink). [`Container`][] is a widget class that allows you to customize its child widget. Use a `Container` when you want to add padding, margins, borders, or background color, to name some of its capabilities. In this example, each [`Text`][] widget is placed in a `Container` to add margins. The entire [`Row`][] is also placed in a `Container` to add padding around the row. The rest of the UI in this example is controlled by properties. Set an [`Icon`][]'s color using its `color` property. Use the `Text.style` property to set the font, its color, weight, and so on. Columns and rows have properties that allow you to specify how their children are aligned vertically or horizontally, and how much space the children should occupy. ## Lay out a widget How do you lay out a single widget in Flutter? This section shows you how to create and display a simple widget. It also shows the entire code for a simple Hello World app. In Flutter, it takes only a few steps to put text, an icon, or an image on the screen. ### 1. Select a layout widget Choose from a variety of [layout widgets][] based on how you want to align or constrain the visible widget, as these characteristics are typically passed on to the contained widget. This example uses [`Center`][] which centers its content horizontally and vertically. ### 2. Create a visible widget For example, create a [`Text`][] widget: <?code-excerpt "layout/base/lib/main.dart (text)" replace="/child: //g"?> ```dart Text('Hello World'), ``` Create an [`Image`][] widget: <?code-excerpt "layout/lakes/step5/lib/main.dart (Image-asset)" remove="/width|height/"?> ```dart return Image.asset( image, fit: BoxFit.cover, ); ``` Create an [`Icon`][] widget: <?code-excerpt "layout/lakes/step5/lib/main.dart (Icon)"?> ```dart Icon( Icons.star, color: Colors.red[500], ), ``` ### 3. Add the visible widget to the layout widget <?code-excerpt path-base="layout/base"?> All layout widgets have either of the following: * A `child` property if they take a single child&mdash;for example, `Center` or `Container` * A `children` property if they take a list of widgets&mdash;for example, `Row`, `Column`, `ListView`, or `Stack`. Add the `Text` widget to the `Center` widget: <?code-excerpt "lib/main.dart (centered-text)" replace="/body: //g"?> ```dart const Center( child: Text('Hello World'), ), ``` ### 4. Add the layout widget to the page A Flutter app is itself a widget, and most widgets have a [`build()`][] method. Instantiating and returning a widget in the app's `build()` method displays the widget. #### Material apps For a `Material` app, you can use a [`Scaffold`][] widget; it provides a default banner, background color, and has API for adding drawers, snack bars, and bottom sheets. Then you can add the `Center` widget directly to the `body` property for the home page. <?code-excerpt path-base="layout/base"?> <?code-excerpt "lib/main.dart (MyApp)" title?> ```dart 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'), ), ), ); } } ``` {{site.alert.note}} The [Material library][] implements widgets that follow [Material Design][] principles. When designing your UI, you can exclusively use widgets from the standard [widgets library][], or you can use widgets from the Material library. You can mix widgets from both libraries, you can customize existing widgets, or you can build your own set of custom widgets. {{site.alert.end}} #### Cupertino apps To create a `Cupertino` app, use `CupertinoApp` and [`CupertinoPageScaffold`][] widgets. Unlike `Material`, it doesn't provide a default banner or background color. You need to set these yourself. * To set default colors, pass in a configured [`CupertinoThemeData`][] to your app's `theme` property. * To add an iOS-styled navigation bar to the top of your app, add a [`CupertinoNavigationBar`][] widget to the `navigationBar` property of your scaffold. You can use the colors that [`CupertinoColors`][] provides to configure your widgets to match iOS design. * To lay out the body of your app, set the `child` property of your scaffold with the desired widget as its value, like `Center` or `Column`. To learn what other UI components you can add, check out the [Cupertino library][]. <?code-excerpt "lib/cupertino.dart (MyApp)" title?> ```dart class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const CupertinoApp( title: 'Flutter layout demo', theme: CupertinoThemeData( brightness: Brightness.light, primaryColor: CupertinoColors.systemBlue, ), home: CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( backgroundColor: CupertinoColors.systemGrey, middle: Text('Flutter layout demo'), ), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Hello World'), ], ), ), ), ); } } ``` {{site.alert.note}} The [Cupertino library][] implements widgets that follow [Apple's Human Interface Guidelines for iOS][]. When designing your UI, you can use widgets from the standard [widgets library][], or the Cupertino library. You can mix widgets from both libraries, you can customize existing widgets, or you can build your own set of custom widgets. {{site.alert.end}} [`CupertinoColors`]: {{api}}/cupertino/CupertinoColors-class.html [`CupertinoThemeData`]: {{api}}/cupertino/CupertinoThemeData-class.html [`CupertinoNavigationBar`]: {{api}}/cupertino/CupertinoNavigationBar-class.html [Apple's Human Interface Guidelines for iOS]: {{site.apple-dev}}/design/human-interface-guidelines/designing-for-ios #### Non-Material apps For a non-Material app, you can add the `Center` widget to the app's `build()` method: <?code-excerpt path-base="layout/non_material"?> <?code-excerpt "lib/main.dart (MyApp)" title?> ```dart class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return Container( decoration: const BoxDecoration(color: Colors.white), child: const Center( child: Text( 'Hello World', textDirection: TextDirection.ltr, style: TextStyle( fontSize: 32, color: Colors.black87, ), ), ), ); } } ``` By default, a non-Material app doesn't include an `AppBar`, title, or background color. If you want these features in a non-Material app, you have to build them yourself. This app changes the background color to white and the text to dark grey to mimic a Material app. <div class="row"> <div class="col-md-6" markdown="1"> That's it! When you run the app, you should see _Hello World_. App source code: * [Material app]({{examples}}/layout/base) * [Non-Material app]({{examples}}/layout/non_material) </div> <div class="col-md-6"> {% include docs/app-figure.md img-class="site-mobile-screenshot border w-75" image="ui/layout/hello-world.png" alt="Hello World" %} </div> </div> <hr> ## Lay out multiple widgets vertically and horizontally <?code-excerpt path-base=""?> One of the most common layout patterns is to arrange widgets vertically or horizontally. You can use a `Row` widget to arrange widgets horizontally, and a `Column` widget to arrange widgets vertically. {{site.alert.secondary}} <h4>What's the point?</h4> * `Row` and `Column` are two of the most commonly used layout patterns. * `Row` and `Column` each take a list of child widgets. * A child widget can itself be a `Row`, `Column`, or other complex widget. * You can specify how a `Row` or `Column` aligns its children, both vertically and horizontally. * You can stretch or constrain specific child widgets. * You can specify how child widgets use the `Row`'s or `Column`'s available space. {{site.alert.end}} To create a row or column in Flutter, you add a list of children widgets to a [`Row`][] or [`Column`][] widget. In turn, each child can itself be a row or column, and so on. The following example shows how it is possible to nest rows or columns inside of rows or columns. This layout is organized as a `Row`. The row contains two children: a column on the left, and an image on the right: <img src='/assets/images/docs/ui/layout/pavlova-diagram.png' class="mw-100" alt="Screenshot with callouts showing the row containing two children"> The left column's widget tree nests rows and columns. <img src='/assets/images/docs/ui/layout/pavlova-left-column-diagram.png' class="mw-100" alt="Diagram showing a left column broken down to its sub-rows and sub-columns"> You'll implement some of Pavlova's layout code in [Nesting rows and columns](#nesting-rows-and-columns). {{site.alert.note}} `Row` and `Column` are basic primitive widgets for horizontal and vertical layouts&mdash;these low-level widgets allow for maximum customization. Flutter also offers specialized, higher level widgets that might be sufficient for your needs. For example, instead of `Row` you might prefer [`ListTile`][], an easy-to-use widget with properties for leading and trailing icons, and up to 3 lines of text. Instead of Column, you might prefer [`ListView`][], a column-like layout that automatically scrolls if its content is too long to fit the available space. For more information, see [Common layout widgets][]. {{site.alert.end}} ### Aligning widgets You control how a row or column aligns its children using the `mainAxisAlignment` and `crossAxisAlignment` properties. For a row, the main axis runs horizontally and the cross axis runs vertically. For a column, the main axis runs vertically and the cross axis runs horizontally. <div class="mb-2 text-center"> <img src='/assets/images/docs/ui/layout/row-diagram.png' class="mb-2 mw-100" alt="Diagram showing the main axis and cross axis for a row"> <img src='/assets/images/docs/ui/layout/column-diagram.png' class="mb-2 mr-2 ml-2 mw-100" alt="Diagram showing the main axis and cross axis for a column"> </div> The [`MainAxisAlignment`][] and [`CrossAxisAlignment`][] enums offer a variety of constants for controlling alignment. {{site.alert.note}} When you add images to your project, you need to update the `pubspec.yaml` file to access them&mdash;this example uses `Image.asset` to display the images. For more information, see this example's [`pubspec.yaml` file][] or [Adding assets and images][]. You don't need to do this if you're referencing online images using `Image.network`. {{site.alert.end}} In the following example, each of the 3 images is 100 pixels wide. The render box (in this case, the entire screen) is more than 300 pixels wide, so setting the main axis alignment to `spaceEvenly` divides the free horizontal space evenly between, before, and after each image. <div class="row"> <div class="col-lg-8"> <?code-excerpt "layout/row_column/lib/main.dart (Row)" replace="/Row/[!$&!]/g"?> {% prettify dart context="html" %} [!Row!]( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Image.asset('images/pic1.jpg'), Image.asset('images/pic2.jpg'), Image.asset('images/pic3.jpg'), ], ); {% endprettify %} </div> <div class="col-lg-4" markdown="1"> <img src='/assets/images/docs/ui/layout/row-spaceevenly-visual.png' class="mw-100" alt="Row with 3 evenly spaced images"> **App source:** [row_column]({{examples}}/layout/row_column) </div> </div> Columns work the same way as rows. The following example shows a column of 3 images, each is 100 pixels high. The height of the render box (in this case, the entire screen) is more than 300 pixels, so setting the main axis alignment to `spaceEvenly` divides the free vertical space evenly between, above, and below each image. <div class="row"> <div class="col-lg-8" markdown="1"> <?code-excerpt "layout/row_column/lib/main.dart (Column)" replace="/Column/[!$&!]/g"?> {% prettify dart context="html" %} [!Column!]( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Image.asset('images/pic1.jpg'), Image.asset('images/pic2.jpg'), Image.asset('images/pic3.jpg'), ], ); {% endprettify %} **App source:** [row_column]({{examples}}/layout/row_column) </div> <div class="col-lg-4 text-center"> <img src='/assets/images/docs/ui/layout/column-visual.png' class="mb-4" height="250px" alt="Column showing 3 images spaced evenly"> </div> </div> ### Sizing widgets When a layout is too large to fit a device, a yellow and black striped pattern appears along the affected edge. Here is an [example][sizing] of a row that is too wide: <img src='/assets/images/docs/ui/layout/layout-too-large.png' class="mw-100" alt="Overly-wide row"> {:.text-center} Widgets can be sized to fit within a row or column by using the [`Expanded`][] widget. To fix the previous example where the row of images is too wide for its render box, wrap each image with an `Expanded` widget. <div class="row"> <div class="col-lg-8"> <?code-excerpt "layout/sizing/lib/main.dart (expanded-images)" replace="/Expanded/[!$&!]/g"?> {% prettify dart context="html" %} Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ [!Expanded!]( child: Image.asset('images/pic1.jpg'), ), [!Expanded!]( child: Image.asset('images/pic2.jpg'), ), [!Expanded!]( child: Image.asset('images/pic3.jpg'), ), ], ); {% endprettify %} </div> <div class="col-lg-4" markdown="1"> <img src='/assets/images/docs/ui/layout/row-expanded-2-visual.png' class="mw-100" alt="Row of 3 images that are too wide, but each is constrained to take only 1/3 of the space"> **App source:** [sizing]({{examples}}/layout/sizing) </div> </div> Perhaps you want a widget to occupy twice as much space as its siblings. For this, use the `Expanded` widget `flex` property, an integer that determines the flex factor for a widget. The default flex factor is 1. The following code sets the flex factor of the middle image to 2: <div class="row"> <div class="col-lg-8"> <?code-excerpt "layout/sizing/lib/main.dart (expanded-images-with-flex)" replace="/flex.*/[!$&!]/g"?> {% prettify dart context="html" %} Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Image.asset('images/pic1.jpg'), ), Expanded( [!flex: 2,!] child: Image.asset('images/pic2.jpg'), ), Expanded( child: Image.asset('images/pic3.jpg'), ), ], ); {% endprettify %} </div> <div class="col-lg-4" markdown="1"> <img src='/assets/images/docs/ui/layout/row-expanded-visual.png' class="mw-100" alt="Row of 3 images with the middle image twice as wide as the others"> **App source:** [sizing]({{examples}}/layout/sizing) </div> </div> [sizing]: {{examples}}/layout/sizing ### Packing widgets By default, a row or column occupies as much space along its main axis as possible, but if you want to pack the children closely together, set its `mainAxisSize` to `MainAxisSize.min`. The following example uses this property to pack the star icons together. <div class="row"> <div class="col-lg-8"> <?code-excerpt "layout/pavlova/lib/main.dart (stars)" replace="/mainAxisSize.*/[!$&!]/g; /\w+ \w+ = //g; /;//g"?> {% prettify dart context="html" %} Row( [!mainAxisSize: MainAxisSize.min,!] children: [ Icon(Icons.star, color: Colors.green[500]), Icon(Icons.star, color: Colors.green[500]), Icon(Icons.star, color: Colors.green[500]), const Icon(Icons.star, color: Colors.black), const Icon(Icons.star, color: Colors.black), ], ) {% endprettify %} </div> <div class="col-lg-4" markdown="1"> <img src='/assets/images/docs/ui/layout/packed.png' class="border mw-100" alt="Row of 5 stars, packed together in the middle of the row"> **App source:** [pavlova]({{examples}}/layout/pavlova) </div> </div> ### Nesting rows and columns The layout framework allows you to nest rows and columns inside of rows and columns as deeply as you need. Let's look at the code for the outlined section of the following layout: <img src='/assets/images/docs/ui/layout/pavlova-large-annotated.png' class="border mw-100" alt="Screenshot of the pavlova app, with the ratings and icon rows outlined in red"> {:.text-center} The outlined section is implemented as two rows. The ratings row contains five stars and the number of reviews. The icons row contains three columns of icons and text. The widget tree for the ratings row: <img src='/assets/images/docs/ui/layout/widget-tree-pavlova-rating-row.png' class="mw-100" alt="Ratings row widget tree"> {:.text-center} The `ratings` variable creates a row containing a smaller row of 5 star icons, and text: <?code-excerpt "layout/pavlova/lib/main.dart (ratings)" replace="/ratings/[!$&!]/g"?> ```dart final stars = Row( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.star, color: Colors.green[500]), Icon(Icons.star, color: Colors.green[500]), Icon(Icons.star, color: Colors.green[500]), const Icon(Icons.star, color: Colors.black), const Icon(Icons.star, color: Colors.black), ], ); final [!ratings!] = Container( padding: const EdgeInsets.all(20), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ stars, const Text( '170 Reviews', style: TextStyle( color: Colors.black, fontWeight: FontWeight.w800, fontFamily: 'Roboto', letterSpacing: 0.5, fontSize: 20, ), ), ], ), ); ``` {{site.alert.tip}} To minimize the visual confusion that can result from heavily nested layout code, implement pieces of the UI in variables and functions. {{site.alert.end}} The icons row, below the ratings row, contains 3 columns; each column contains an icon and two lines of text, as you can see in its widget tree: <img src='/assets/images/docs/ui/layout/widget-tree-pavlova-icon-row.png' class="mw-100" alt="Icon widget tree"> {:.text-center} The `iconList` variable defines the icons row: <?code-excerpt "layout/pavlova/lib/main.dart (iconList)" replace="/iconList/[!$&!]/g"?> ```dart const descTextStyle = TextStyle( color: Colors.black, fontWeight: FontWeight.w800, fontFamily: 'Roboto', letterSpacing: 0.5, fontSize: 18, height: 2, ); // DefaultTextStyle.merge() allows you to create a default text // style that is inherited by its child and all subsequent children. final [!iconList!] = DefaultTextStyle.merge( style: descTextStyle, child: Container( padding: const EdgeInsets.all(20), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Column( children: [ Icon(Icons.kitchen, color: Colors.green[500]), const Text('PREP:'), const Text('25 min'), ], ), Column( children: [ Icon(Icons.timer, color: Colors.green[500]), const Text('COOK:'), const Text('1 hr'), ], ), Column( children: [ Icon(Icons.restaurant, color: Colors.green[500]), const Text('FEEDS:'), const Text('4-6'), ], ), ], ), ), ); ``` The `leftColumn` variable contains the ratings and icons rows, as well as the title and text that describes the Pavlova: <?code-excerpt "layout/pavlova/lib/main.dart (leftColumn)" replace="/leftColumn/[!$&!]/g"?> ```dart final [!leftColumn!] = Container( padding: const EdgeInsets.fromLTRB(20, 30, 20, 20), child: Column( children: [ titleText, subTitle, ratings, iconList, ], ), ); ``` The left column is placed in a `SizedBox` to constrain its width. Finally, the UI is constructed with the entire row (containing the left column and the image) inside a `Card`. The [Pavlova image][] is from [Pixabay][]. You can embed an image from the net using `Image.network()` but, for this example, the image is saved to an images directory in the project, added to the [pubspec file][], and accessed using `Images.asset()`. For more information, see [Adding assets and images][]. <?code-excerpt "layout/pavlova/lib/main.dart (body)"?> ```dart body: Center( child: Container( margin: const EdgeInsets.fromLTRB(0, 40, 0, 30), height: 600, child: Card( child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( width: 440, child: leftColumn, ), mainImage, ], ), ), ), ), ``` {{site.alert.tip}} The Pavlova example runs best horizontally on a wide device, such as a tablet. If you are running this example in the iOS simulator, you can select a different device using the **Hardware > Device** menu. For this example, we recommend the iPad Pro. You can change its orientation to landscape mode using **Hardware > Rotate**. You can also change the size of the simulator window (without changing the number of logical pixels) using **Window > Scale**. {{site.alert.end}} **App source:** [pavlova]({{examples}}/layout/pavlova) [Pavlova image]: https://pixabay.com/en/photos/pavlova [Pixabay]: https://pixabay.com/en/photos/pavlova <hr> ## Common layout widgets Flutter has a rich library of layout widgets. Here are a few of those most commonly used. The intent is to get you up and running as quickly as possible, rather than overwhelm you with a complete list. For information on other available widgets, refer to the [Widget catalog][], or use the Search box in the [API reference docs][]. Also, the widget pages in the API docs often make suggestions about similar widgets that might better suit your needs. The following widgets fall into two categories: standard widgets from the [widgets library][], and specialized widgets from the [Material library][]. Any app can use the widgets library but only Material apps can use the Material Components library. ### Standard widgets * [`Container`](#container): Adds padding, margins, borders, background color, or other decorations to a widget. * [`GridView`](#gridview): Lays widgets out as a scrollable grid. * [`ListView`](#listview): Lays widgets out as a scrollable list. * [`Stack`](#stack): Overlaps a widget on top of another. ### Material widgets * [`Card`](#card): Organizes related info into a box with rounded corners and a drop shadow. * [`ListTile`](#listtile): Organizes up to 3 lines of text, and optional leading and trailing icons, into a row. ### Container Many layouts make liberal use of [`Container`][]s to separate widgets using padding, or to add borders or margins. You can change the device's background by placing the entire layout into a `Container` and changing its background color or image. <div class="row"> <div class="col-lg-6" markdown="1"> <h4>Summary (Container)</h4> * Add padding, margins, borders * Change background color or image * Contains a single child widget, but that child can be a Row, Column, or even the root of a widget tree </div> <div class="col-lg-6 text-center"> <img src='/assets/images/docs/ui/layout/margin-padding-border.png' class="mb-4 mw-100" width="230px" alt="Diagram showing: margin, border, padding, and content"> </div> </div> #### Examples (Container) This layout consists of a column with two rows, each containing 2 images. A [`Container`][] is used to change the background color of the column to a lighter grey. <div class="row"> <div class="col-lg-7"> <?code-excerpt "layout/container/lib/main.dart (column)" replace="/\bContainer/[!$&!]/g;"?> {% prettify dart context="html" %} Widget _buildImageColumn() { return [!Container!]( decoration: const BoxDecoration( color: Colors.black26, ), child: Column( children: [ _buildImageRow(1), _buildImageRow(3), ], ), ); } {% endprettify %} </div> <div class="col-lg-5 text-center"> <img src='/assets/images/docs/ui/layout/container.png' class="mb-4 mw-100" width="230px" alt="Screenshot showing 2 rows, each containing 2 images"> </div> </div> A `Container` is also used to add a rounded border and margins to each image: <?code-excerpt "layout/container/lib/main.dart (row)" replace="/\bContainer/[!$&!]/g;"?> ```dart Widget _buildDecoratedImage(int imageIndex) => Expanded( child: [!Container!]( decoration: BoxDecoration( border: Border.all(width: 10, color: Colors.black38), borderRadius: const BorderRadius.all(Radius.circular(8)), ), margin: const EdgeInsets.all(4), child: Image.asset('images/pic$imageIndex.jpg'), ), ); Widget _buildImageRow(int imageIndex) => Row( children: [ _buildDecoratedImage(imageIndex), _buildDecoratedImage(imageIndex + 1), ], ); ``` You can find more `Container` examples in the [tutorial][]. **App source:** [container]({{examples}}/layout/container) <hr> ### GridView Use [`GridView`][] to lay widgets out as a two-dimensional list. `GridView` provides two pre-fabricated lists, or you can build your own custom grid. When a `GridView` detects that its contents are too long to fit the render box, it automatically scrolls. #### Summary (GridView) * Lays widgets out in a grid * Detects when the column content exceeds the render box and automatically provides scrolling * Build your own custom grid, or use one of the provided grids: * `GridView.count` allows you to specify the number of columns * `GridView.extent` allows you to specify the maximum pixel width of a tile {% comment %} * Use `MediaQuery.of(context).orientation` to create a grid that changes its layout depending on whether the device is in landscape or portrait mode. {% endcomment %} {{site.alert.note}} When displaying a two-dimensional list where it's important which row and column a cell occupies (for example, it's the entry in the "calorie" column for the "avocado" row), use [`Table`][] or [`DataTable`][]. {{site.alert.end}} #### Examples (GridView) <div class="row"> <div class="col-lg-6" markdown="1"> <img src='/assets/images/docs/ui/layout/gridview-extent.png' class="mw-100" alt="A 3-column grid of photos"> {:.text-center} Uses `GridView.extent` to create a grid with tiles a maximum 150 pixels wide. **App source:** [grid_and_list]({{examples}}/layout/grid_and_list) </div> <div class="col-lg-6" markdown="1"> <img src='/assets/images/docs/ui/layout/gridview-count-flutter-gallery.png' class="mw-100" alt="A 2 column grid with footers"> {:.text-center} Uses `GridView.count` to create a grid that's 2 tiles wide in portrait mode, and 3 tiles wide in landscape mode. The titles are created by setting the `footer` property for each [`GridTile`][]. **Dart code:** [`grid_list_demo.dart`]({{examples}}/layout/gallery/lib/grid_list_demo.dart) </div> </div> <?code-excerpt "layout/grid_and_list/lib/main.dart (grid)" replace="/\GridView/[!$&!]/g;"?> ```dart Widget _buildGrid() => [!GridView!].extent( maxCrossAxisExtent: 150, padding: const EdgeInsets.all(4), mainAxisSpacing: 4, crossAxisSpacing: 4, children: _buildGridTileList(30)); // The images are saved with names pic0.jpg, pic1.jpg...pic29.jpg. // The List.generate() constructor allows an easy way to create // a list when objects have a predictable naming pattern. List<Container> _buildGridTileList(int count) => List.generate( count, (i) => Container(child: Image.asset('images/pic$i.jpg'))); ``` <hr> ### ListView [`ListView`][], a column-like widget, automatically provides scrolling when its content is too long for its render box. #### Summary (ListView) * A specialized [`Column`][] for organizing a list of boxes * Can be laid out horizontally or vertically * Detects when its content won't fit and provides scrolling * Less configurable than `Column`, but easier to use and supports scrolling #### Examples (ListView) <div class="row"> <div class="col-lg-6" markdown="1"> <img src='/assets/images/docs/ui/layout/listview.png' class="border mw-100" alt="ListView containing movie theaters and restaurants"> {:.text-center} Uses `ListView` to display a list of businesses using `ListTile`s. A `Divider` separates the theaters from the restaurants. **App source:** [grid_and_list]({{examples}}/layout/grid_and_list) </div> <div class="col-lg-6" markdown="1"> <img src='/assets/images/docs/ui/layout/listview-color-gallery.png' class="border mw-100" alt="ListView containing shades of blue"> {:.text-center} Uses `ListView` to display the [`Colors`][] from the [Material 2 Design palette][] for a particular color family. **Dart code:** [`colors_demo.dart`]({{examples}}/layout/gallery/lib/colors_demo.dart) </div> </div> <?code-excerpt "layout/grid_and_list/lib/main.dart (list)" replace="/\ListView/[!$&!]/g;"?> ```dart Widget _buildList() { return [!ListView!]( children: [ _tile('CineArts at the Empire', '85 W Portal Ave', Icons.theaters), _tile('The Castro Theater', '429 Castro St', Icons.theaters), _tile('Alamo Drafthouse Cinema', '2550 Mission St', Icons.theaters), _tile('Roxie Theater', '3117 16th St', Icons.theaters), _tile('United Artists Stonestown Twin', '501 Buckingham Way', Icons.theaters), _tile('AMC Metreon 16', '135 4th St #3000', Icons.theaters), const Divider(), _tile('K\'s Kitchen', '757 Monterey Blvd', Icons.restaurant), _tile('Emmy\'s Restaurant', '1923 Ocean Ave', Icons.restaurant), _tile('Chaiya Thai Restaurant', '272 Claremont Blvd', Icons.restaurant), _tile('La Ciccia', '291 30th St', Icons.restaurant), ], ); } ListTile _tile(String title, String subtitle, IconData icon) { return ListTile( title: Text(title, style: const TextStyle( fontWeight: FontWeight.w500, fontSize: 20, )), subtitle: Text(subtitle), leading: Icon( icon, color: Colors.blue[500], ), ); } ``` <hr> ### Stack Use [`Stack`][] to arrange widgets on top of a base widget&mdash;often an image. The widgets can completely or partially overlap the base widget. #### Summary (Stack) * Use for widgets that overlap another widget * The first widget in the list of children is the base widget; subsequent children are overlaid on top of that base widget * A `Stack`'s content can't scroll * You can choose to clip children that exceed the render box #### Examples (Stack) <div class="row"> <div class="col-lg-7" markdown="1"> <img src='/assets/images/docs/ui/layout/stack.png' class="mw-100" width="200px" alt="Circular avatar image with a label"> {:.text-center} Uses `Stack` to overlay a `Container` (that displays its `Text` on a translucent black background) on top of a `CircleAvatar`. The `Stack` offsets the text using the `alignment` property and `Alignment`s. **App source:** [card_and_stack]({{examples}}/layout/card_and_stack) </div> <div class="col-lg-5" markdown="1"> <img src='/assets/images/docs/ui/layout/stack-flutter-gallery.png' class="mw-100" alt="An image with a icon overlaid on top"> {:.text-center} Uses `Stack` to overlay an icon on top of an image. **Dart code:** [`bottom_navigation_demo.dart`]({{examples}}/layout/gallery/lib/bottom_navigation_demo.dart) </div> </div> <?code-excerpt "layout/card_and_stack/lib/main.dart (Stack)" replace="/\bStack/[!$&!]/g;"?> ```dart Widget _buildStack() { return [!Stack!]( alignment: const Alignment(0.6, 0.6), children: [ const CircleAvatar( backgroundImage: AssetImage('images/pic.jpg'), radius: 100, ), Container( decoration: const BoxDecoration( color: Colors.black45, ), child: const Text( 'Mia B', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white, ), ), ), ], ); } ``` <hr> ### Card A [`Card`][], from the [Material library][], contains related nuggets of information and can be composed from almost any widget, but is often used with [`ListTile`][]. `Card` has a single child, but its child can be a column, row, list, grid, or other widget that supports multiple children. By default, a `Card` shrinks its size to 0 by 0 pixels. You can use [`SizedBox`][] to constrain the size of a card. In Flutter, a `Card` features slightly rounded corners and a drop shadow, giving it a 3D effect. Changing a `Card`'s `elevation` property allows you to control the drop shadow effect. Setting the elevation to 24, for example, visually lifts the `Card` further from the surface and causes the shadow to become more dispersed. For a list of supported elevation values, see [Elevation][] in the [Material guidelines][Material Design]. Specifying an unsupported value disables the drop shadow entirely. #### Summary (Card) * Implements a [Material card][] * Used for presenting related nuggets of information * Accepts a single child, but that child can be a `Row`, `Column`, or other widget that holds a list of children * Displayed with rounded corners and a drop shadow * A `Card`'s content can't scroll * From the [Material library][] #### Examples (Card) <div class="row"> <div class="col-lg-6" markdown="1"> <img src='/assets/images/docs/ui/layout/card.png' class="mw-100" alt="Card containing 3 ListTiles"> {:.text-center} A `Card` containing 3 ListTiles and sized by wrapping it with a `SizedBox`. A `Divider` separates the first and second `ListTiles`. **App source:** [card_and_stack]({{examples}}/layout/card_and_stack) </div> <div class="col-lg-6" markdown="1"> <img src='/assets/images/docs/ui/layout/card-flutter-gallery.png' class="mw-100" alt="Tappable card containing an image and multiple forms of text"> {:.text-center} A `Card` containing an image and text. **Dart code:** [`cards_demo.dart`]({{examples}}/layout/gallery/lib/cards_demo.dart) </div> </div> <?code-excerpt "layout/card_and_stack/lib/main.dart (Card)" replace="/\bCard/[!$&!]/g;"?> ```dart Widget _buildCard() { return SizedBox( height: 210, child: [!Card!]( child: Column( children: [ ListTile( title: const Text( '1625 Main Street', style: TextStyle(fontWeight: FontWeight.w500), ), subtitle: const Text('My City, CA 99984'), leading: Icon( Icons.restaurant_menu, color: Colors.blue[500], ), ), const Divider(), ListTile( title: const Text( '(408) 555-1212', style: TextStyle(fontWeight: FontWeight.w500), ), leading: Icon( Icons.contact_phone, color: Colors.blue[500], ), ), ListTile( title: const Text('[email protected]'), leading: Icon( Icons.contact_mail, color: Colors.blue[500], ), ), ], ), ), ); } ``` <hr> ### ListTile Use [`ListTile`][], a specialized row widget from the [Material library][], for an easy way to create a row containing up to 3 lines of text and optional leading and trailing icons. `ListTile` is most commonly used in [`Card`][] or [`ListView`][], but can be used elsewhere. #### Summary (ListTile) * A specialized row that contains up to 3 lines of text and optional icons * Less configurable than `Row`, but easier to use * From the [Material library][] #### Examples (ListTile) <div class="row"> <div class="col-lg-6" markdown="1"> <img src='/assets/images/docs/ui/layout/card.png' class="mw-100" alt="Card containing 3 ListTiles"> {:.text-center} A `Card` containing 3 `ListTile`s. **App source:** [card_and_stack]({{examples}}/layout/card_and_stack) </div> <div class="col-lg-6" markdown="1"> <img src='/assets/images/docs/ui/layout/listtile-flutter-gallery.png' class="border mw-100" height="200px" alt="4 ListTiles, each containing a leading avatar"> {:.text-center} Uses `ListTile` with leading widgets. **Dart code:** [`list_demo.dart`]({{examples}}/layout/gallery/lib/list_demo.dart) </div> </div> <hr> ## Constraints To fully understand Flutter's layout system, you need to learn how Flutter positions and sizes the components in a layout. For more information, see [Understanding constraints][]. ## Videos The following videos, part of the [Flutter in Focus][] series, explain `Stateless` and `Stateful` widgets. <iframe width="560" height="315" src="{{site.yt.embed}}/wE7khGHVkYY?rel=0" title="Learn how to create stateless widgets" {{site.yt.set}}></iframe> <iframe width="560" height="315" src="{{site.yt.embed}}/AqCMFXEmf3w?rel=0" title="Learn the best times to use stateful widgets" {{site.yt.set}}></iframe> [Flutter in Focus playlist]({{site.yt.playlist}}PLjxrf2q8roU2HdJQDjJzOeO6J3FoFLWr2) --- Each episode of the [Widget of the Week series]({{site.yt.playlist}}PLjxrf2q8roU23XGwz3Km7sQZFTdB996iG) focuses on a widget. Several of them includes layout widgets. <iframe width="560" height="315" src="{{site.yt.embed}}/b_sQ9bMltGU?rel=0" title="Watch the Widget of the Week playlist" {{site.yt.set}}></iframe> [Flutter Widget of the Week playlist]({{site.yt.playlist}}PLjxrf2q8roU23XGwz3Km7sQZFTdB996iG) ## Other resources The following resources might help when writing layout code. * [Layout tutorial][] : Learn how to build a layout. * [Widget catalog][] : Describes many of the widgets available in Flutter. * [HTML/CSS Analogs in Flutter][] : For those familiar with web programming, this page maps HTML/CSS functionality to Flutter features. * [API reference docs][] : Reference documentation for all of the Flutter libraries. * [Adding assets and images][] : Explains how to add images and other assets to your app's package. * [Zero to One with Flutter][] : One person's experience writing his first Flutter app. [Cupertino library]: {{api}}/cupertino/cupertino-library.html [`CupertinoPageScaffold`]: {{api}}/cupertino/CupertinoPageScaffold-class.html [Adding assets and images]: /ui/assets/assets-and-images [API reference docs]: {{api}} [`build()`]: {{api}}/widgets/StatelessWidget/build.html [`Card`]: {{api}}/material/Card-class.html [`Center`]: {{api}}/widgets/Center-class.html [`Column`]: {{api}}/widgets/Column-class.html [Common layout widgets]: #common-layout-widgets [`Colors`]: {{api}}/material/Colors-class.html [`Container`]: {{api}}/widgets/Container-class.html [`CrossAxisAlignment`]: {{api}}/rendering/CrossAxisAlignment.html [`DataTable`]: {{api}}/material/DataTable-class.html [Elevation]: {{site.material}}/styles/elevation [`Expanded`]: {{api}}/widgets/Expanded-class.html [Flutter in Focus]: {{site.yt.watch}}?v=wgTBLj7rMPM&list=PLjxrf2q8roU2HdJQDjJzOeO6J3FoFLWr2 [`GridView`]: {{api}}/widgets/GridView-class.html [`GridTile`]: {{api}}/material/GridTile-class.html [HTML/CSS Analogs in Flutter]: /get-started/flutter-for/web-devs [`Icon`]: {{api}}/material/Icons-class.html [`Image`]: {{api}}/widgets/Image-class.html [Layout tutorial]: /ui/layout/tutorial [layout widgets]: /ui/widgets/layout [`ListTile`]: {{api}}/material/ListTile-class.html [`ListView`]: {{api}}/widgets/ListView-class.html [`MainAxisAlignment`]: {{api}}/rendering/MainAxisAlignment.html [Material card]: {{site.material}}/components/cards [Material Design]: {{site.material}}/styles [Material 2 Design palette]: {{site.material2}}/design/color/the-color-system.html#tools-for-picking-colors [Material library]: {{api}}/material/material-library.html [pubspec file]: {{examples}}/layout/pavlova/pubspec.yaml [`pubspec.yaml` file]: {{examples}}/layout/row_column/pubspec.yaml [`Row`]: {{api}}/widgets/Row-class.html [`Scaffold`]: {{api}}/material/Scaffold-class.html [`SizedBox`]: {{api}}/widgets/SizedBox-class.html [`Stack`]: {{api}}/widgets/Stack-class.html [`Table`]: {{api}}/widgets/Table-class.html [`Text`]: {{api}}/widgets/Text-class.html [tutorial]: /ui/layout/tutorial [widgets library]: {{api}}/widgets/widgets-library.html [Widget catalog]: /ui/widgets [Debugging layout issues visually]: /tools/devtools/inspector#debugging-layout-issues-visually [Understanding constraints]: /ui/layout/constraints [Using the Flutter inspector]: /tools/devtools/inspector [Zero to One with Flutter]: {{site.medium}}/@mravn/zero-to-one-with-flutter-43b13fd7b354
website/src/ui/layout/index.md/0
{ "file_path": "website/src/ui/layout/index.md", "repo_id": "website", "token_count": 15349 }
1,396
--- title: Cupertino (iOS-style) widgets short-title: Cupertino description: > A catalog of Flutter's widgets implementing the Cupertino design language. --- {% include docs/catalogpage.html category="Cupertino (iOS-style widgets)" %}
website/src/ui/widgets/cupertino.md/0
{ "file_path": "website/src/ui/widgets/cupertino.md", "repo_id": "website", "token_count": 70 }
1,397
// Copyright 2024 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:args/command_runner.dart'; import '../utils.dart'; final class CheckAllCommand extends Command<int> { @override String get description => 'Run all code related tests and validation.'; @override String get name => 'check-all'; @override Future<int> run() async { const verificationTasks = [ ['format-dart', '--check'], ['analyze-dart'], ['test-dart'], ['refresh-excerpts', '--fail-on-update'], ]; var seenFailure = false; for (final task in verificationTasks) { groupStart(task.first); final process = await Process.start( Platform.resolvedExecutable, ['run', 'flutter_site', ...task], ); await stdout.addStream(process.stdout); await stderr.addStream(process.stderr); final processExitCode = await process.exitCode; if (processExitCode != 0) { seenFailure = true; } groupEnd(); } return seenFailure ? 1 : 0; } }
website/tool/flutter_site/lib/src/commands/check_all.dart/0
{ "file_path": "website/tool/flutter_site/lib/src/commands/check_all.dart", "repo_id": "website", "token_count": 445 }
1,398
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
codelabs/animated-responsive-layout/step_04/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "codelabs/animated-responsive-layout/step_04/macos/Runner/Configs/Debug.xcconfig", "repo_id": "codelabs", "token_count": 32 }
0
#include "Generated.xcconfig"
codelabs/animated-responsive-layout/step_06/ios/Flutter/Debug.xcconfig/0
{ "file_path": "codelabs/animated-responsive-layout/step_06/ios/Flutter/Debug.xcconfig", "repo_id": "codelabs", "token_count": 12 }
1
#include "Generated.xcconfig"
codelabs/animated-responsive-layout/step_07/ios/Flutter/Release.xcconfig/0
{ "file_path": "codelabs/animated-responsive-layout/step_07/ios/Flutter/Release.xcconfig", "repo_id": "codelabs", "token_count": 12 }
2
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
codelabs/animated-responsive-layout/step_07/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "codelabs/animated-responsive-layout/step_07/macos/Runner/Configs/Release.xcconfig", "repo_id": "codelabs", "token_count": 32 }
3
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
codelabs/boring_to_beautiful/final/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "codelabs/boring_to_beautiful/final/macos/Runner/Configs/Release.xcconfig", "repo_id": "codelabs", "token_count": 32 }
4
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
codelabs/boring_to_beautiful/step_02/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "codelabs/boring_to_beautiful/step_02/macos/Runner/Configs/Release.xcconfig", "repo_id": "codelabs", "token_count": 32 }
5
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
codelabs/boring_to_beautiful/step_04/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "codelabs/boring_to_beautiful/step_04/macos/Runner/Configs/Release.xcconfig", "repo_id": "codelabs", "token_count": 32 }
6
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
codelabs/boring_to_beautiful/step_06/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "codelabs/boring_to_beautiful/step_06/macos/Runner/Configs/Release.xcconfig", "repo_id": "codelabs", "token_count": 32 }
7
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
codelabs/brick_breaker/step_05/android/gradle.properties/0
{ "file_path": "codelabs/brick_breaker/step_05/android/gradle.properties", "repo_id": "codelabs", "token_count": 30 }
8
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
codelabs/brick_breaker/step_05/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "codelabs/brick_breaker/step_05/macos/Runner/Configs/Release.xcconfig", "repo_id": "codelabs", "token_count": 32 }
9
name: Dart Patterns and Records steps: - name: step_03 steps: - name: Remove generated code rmdir: step_03 - name: Create project flutter: create --empty patterns_codelab - name: Strip DEVELOPMENT_TEAM strip-lines-containing: DEVELOPMENT_TEAM = path: patterns_codelab/ios/Runner.xcodeproj/project.pbxproj - name: Configure analysis_options.yaml path: patterns_codelab/analysis_options.yaml replace-contents: | include: ../../analysis_options.yaml analyzer: errors: unused_field: ignore language: strict-casts: false strict-inference: false linter: rules: - prefer_final_in_for_each - name: Remove README rm: patterns_codelab/README.md - name: Add .vscode directory mkdir: patterns_codelab/.vscode - name: Add .vscode/launch.json path: patterns_codelab/.vscode/launch.json replace-contents: | { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "patterns_codelab", "request": "launch", "type": "dart" } ] } - name: Patch lib/main.dart path: patterns_codelab/lib/main.dart patch-u: | --- b/dart-patterns-and-records/step_03/lib/main.dart +++ a/dart-patterns-and-records/step_03/lib/main.dart @@ -1,3 +1,7 @@ +// Copyright 2023 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + import 'package:flutter/material.dart'; void main() { - name: Replace pubspec.yaml path: patterns_codelab/pubspec.yaml replace-contents: | name: patterns_codelab description: A new Flutter project. publish_to: 'none' version: 0.1.0 environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^3.0.1 flutter: uses-material-design: true - name: Build web app path: patterns_codelab flutter: build web - name: Copy step_03 copydir: from: patterns_codelab to: step_03 - name: Flutter clean path: patterns_codelab flutter: clean - name: step_04 steps: - name: Remove generated code rmdir: step_04 - name: Add lib/data.dart path: patterns_codelab/lib/data.dart replace-contents: | // Copyright 2023 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; class Document { final Map<String, Object?> _json; Document() : _json = jsonDecode(documentJson); } const documentJson = ''' { "metadata": { "title": "My Document", "modified": "2023-05-10" }, "blocks": [ { "type": "h1", "text": "Chapter 1" }, { "type": "p", "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit." }, { "type": "checkbox", "checked": false, "text": "Learn Dart 3" } ] } '''; - name: Replace lib/main.dart path: patterns_codelab/lib/main.dart replace-contents: | // Copyright 2023 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'data.dart'; void main() { runApp(const DocumentApp()); } class DocumentApp extends StatelessWidget { const DocumentApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: DocumentScreen( document: Document(), ), ); } } class DocumentScreen extends StatelessWidget { final Document document; const DocumentScreen({ required this.document, super.key, }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Title goes here'), ), body: const Column( children: [ Center( child: Text('Body goes here'), ), ], ), ); } } - name: Build web app path: patterns_codelab flutter: build web - name: Copy step_04 copydir: from: patterns_codelab to: step_04 - name: Flutter clean path: patterns_codelab flutter: clean - name: step_05 steps: - name: Remove generated code rmdir: step_05 - name: Update lib/data.dart path: patterns_codelab/lib/data.dart patch-u: | --- b/dart-patterns-and-records/step_05/lib/data.dart +++ a/dart-patterns-and-records/step_05/lib/data.dart @@ -7,6 +7,13 @@ import 'dart:convert'; class Document { final Map<String, Object?> _json; Document() : _json = jsonDecode(documentJson); + + (String, {DateTime modified}) get metadata { + const title = 'My Document'; + final now = DateTime.now(); + + return (title, modified: now); + } } const documentJson = ''' - name: Update lib/main.dart path: patterns_codelab/lib/main.dart patch-u: | --- b/dart-patterns-and-records/step_05/lib/main.dart +++ a/dart-patterns-and-records/step_05/lib/main.dart @@ -34,14 +34,18 @@ class DocumentScreen extends StatelessWidget { @override Widget build(BuildContext context) { + final metadataRecord = document.metadata; + return Scaffold( appBar: AppBar( - title: const Text('Title goes here'), + title: Text(metadataRecord.$1), ), - body: const Column( + body: Column( children: [ Center( - child: Text('Body goes here'), + child: Text( + 'Last modified ${metadataRecord.modified}', + ), ), ], ), - name: Build web app path: patterns_codelab flutter: build web - name: Copy step_05 copydir: from: patterns_codelab to: step_05 - name: Flutter clean path: patterns_codelab flutter: clean - name: step_06_a steps: - name: Remove generated code rmdir: step_06_a - name: Update lib/main.dart path: patterns_codelab/lib/main.dart patch-u: | --- b/dart-patterns-and-records/step_06_a/lib/main.dart +++ a/dart-patterns-and-records/step_06_a/lib/main.dart @@ -34,17 +34,17 @@ class DocumentScreen extends StatelessWidget { @override Widget build(BuildContext context) { - final metadataRecord = document.metadata; + final (title, modified: modified) = document.metadata; return Scaffold( appBar: AppBar( - title: Text(metadataRecord.$1), + title: Text(title), ), body: Column( children: [ Center( child: Text( - 'Last modified ${metadataRecord.modified}', + 'Last modified $modified', ), ), ], - name: Build web app path: patterns_codelab flutter: build web - name: Copy step_06_a copydir: from: patterns_codelab to: step_06_a - name: Flutter clean path: patterns_codelab flutter: clean - name: step_06_b steps: - name: Remove generated code rmdir: step_06_b - name: Update lib/main.dart path: patterns_codelab/lib/main.dart patch-u: | --- b/dart-patterns-and-records/step_06_b/lib/main.dart +++ a/dart-patterns-and-records/step_06_b/lib/main.dart @@ -34,7 +34,7 @@ class DocumentScreen extends StatelessWidget { @override Widget build(BuildContext context) { - final (title, modified: modified) = document.metadata; + final (title, :modified) = document.metadata; return Scaffold( appBar: AppBar( - name: Build web app path: patterns_codelab flutter: build web - name: Copy step_06_b copydir: from: patterns_codelab to: step_06_b - name: Flutter clean path: patterns_codelab flutter: clean - name: step_07_a steps: - name: Remove generated code rmdir: step_07_a - name: Update lib/data.dart path: patterns_codelab/lib/data.dart patch-u: | --- b/dart-patterns-and-records/step_07_a/lib/data.dart +++ a/dart-patterns-and-records/step_07_a/lib/data.dart @@ -9,10 +9,16 @@ class Document { Document() : _json = jsonDecode(documentJson); (String, {DateTime modified}) get metadata { - const title = 'My Document'; - final now = DateTime.now(); - - return (title, modified: now); + if (_json.containsKey('metadata')) { + final metadataJson = _json['metadata']; + if (metadataJson is Map) { + final title = metadataJson['title'] as String; + final localModified = + DateTime.parse(metadataJson['modified'] as String); + return (title, modified: localModified); + } + } + throw const FormatException('Unexpected JSON'); } } - name: Build web app path: patterns_codelab flutter: build web - name: Copy step_07_a copydir: from: patterns_codelab to: step_07_a - name: Flutter clean path: patterns_codelab flutter: clean - name: step_07_b steps: - name: Remove generated code rmdir: step_07_b - name: Update lib/data.dart path: patterns_codelab/lib/data.dart patch-u: | --- b/dart-patterns-and-records/step_07_b/lib/data.dart +++ a/dart-patterns-and-records/step_07_b/lib/data.dart @@ -9,16 +9,17 @@ class Document { Document() : _json = jsonDecode(documentJson); (String, {DateTime modified}) get metadata { - if (_json.containsKey('metadata')) { - final metadataJson = _json['metadata']; - if (metadataJson is Map) { - final title = metadataJson['title'] as String; - final localModified = - DateTime.parse(metadataJson['modified'] as String); - return (title, modified: localModified); - } + if (_json + case { + 'metadata': { + 'title': String title, + 'modified': String localModified, + } + }) { + return (title, modified: DateTime.parse(localModified)); + } else { + throw const FormatException('Unexpected JSON'); } - throw const FormatException('Unexpected JSON'); } } - name: Build web app path: patterns_codelab flutter: build web - name: Copy step_07_b copydir: from: patterns_codelab to: step_07_b - name: Flutter clean path: patterns_codelab flutter: clean - name: step_08 steps: - name: Remove generated code rmdir: step_08 - name: Update lib/data.dart path: patterns_codelab/lib/data.dart patch-u: | --- b/dart-patterns-and-records/step_08/lib/data.dart +++ a/dart-patterns-and-records/step_08/lib/data.dart @@ -21,6 +21,14 @@ class Document { throw const FormatException('Unexpected JSON'); } } + + List<Block> getBlocks() { + if (_json case {'blocks': List blocksJson}) { + return [for (final blockJson in blocksJson) Block.fromJson(blockJson)]; + } else { + throw const FormatException('Unexpected JSON format'); + } + } } const documentJson = ''' @@ -46,3 +56,17 @@ const documentJson = ''' ] } '''; + +class Block { + final String type; + final String text; + Block(this.type, this.text); + + factory Block.fromJson(Map<String, dynamic> json) { + if (json case {'type': final type, 'text': final text}) { + return Block(type, text); + } else { + throw const FormatException('Unexpected JSON format'); + } + } +} - name: Build web app path: patterns_codelab flutter: build web - name: Copy step_08 copydir: from: patterns_codelab to: step_08 - name: Flutter clean path: patterns_codelab flutter: clean - name: step_09 steps: - name: Remove generated code rmdir: step_09 - name: Update lib/main.dart path: patterns_codelab/lib/main.dart patch-u: | --- b/dart-patterns-and-records/step_09/lib/main.dart +++ a/dart-patterns-and-records/step_09/lib/main.dart @@ -35,6 +35,7 @@ class DocumentScreen extends StatelessWidget { @override Widget build(BuildContext context) { final (title, :modified) = document.metadata; + final blocks = document.getBlocks(); return Scaffold( appBar: AppBar( @@ -42,9 +43,13 @@ class DocumentScreen extends StatelessWidget { ), body: Column( children: [ - Center( - child: Text( - 'Last modified $modified', + Text('Last modified: $modified'), + Expanded( + child: ListView.builder( + itemCount: blocks.length, + itemBuilder: (context, index) { + return BlockWidget(block: blocks[index]); + }, ), ), ], @@ -52,3 +57,33 @@ class DocumentScreen extends StatelessWidget { ); } } + +class BlockWidget extends StatelessWidget { + final Block block; + + const BlockWidget({ + required this.block, + super.key, + }); + + @override + Widget build(BuildContext context) { + TextStyle? textStyle; + switch (block.type) { + case 'h1': + textStyle = Theme.of(context).textTheme.displayMedium; + case 'p' || 'checkbox': + textStyle = Theme.of(context).textTheme.bodyMedium; + case _: + textStyle = Theme.of(context).textTheme.bodySmall; + } + + return Container( + margin: const EdgeInsets.all(8), + child: Text( + block.text, + style: textStyle, + ), + ); + } +} - name: Build web app path: patterns_codelab flutter: build web - name: Copy step_09 copydir: from: patterns_codelab to: step_09 - name: Flutter clean path: patterns_codelab flutter: clean - name: step_10 steps: - name: Remove generated code rmdir: step_10 - name: Update lib/main.dart path: patterns_codelab/lib/main.dart patch-u: | --- b/dart-patterns-and-records/step_10/lib/main.dart +++ a/dart-patterns-and-records/step_10/lib/main.dart @@ -69,14 +69,11 @@ class BlockWidget extends StatelessWidget { @override Widget build(BuildContext context) { TextStyle? textStyle; - switch (block.type) { - case 'h1': - textStyle = Theme.of(context).textTheme.displayMedium; - case 'p' || 'checkbox': - textStyle = Theme.of(context).textTheme.bodyMedium; - case _: - textStyle = Theme.of(context).textTheme.bodySmall; - } + textStyle = switch (block.type) { + 'h1' => Theme.of(context).textTheme.displayMedium, + 'p' || 'checkbox' => Theme.of(context).textTheme.bodyMedium, + _ => Theme.of(context).textTheme.bodySmall + }; return Container( margin: const EdgeInsets.all(8), - name: Build web app path: patterns_codelab flutter: build web - name: Copy step_10 copydir: from: patterns_codelab to: step_10 - name: Flutter clean path: patterns_codelab flutter: clean - name: step_11_a steps: - name: Remove generated code rmdir: step_11_a - name: Update lib/main.dart path: patterns_codelab/lib/main.dart patch-u: | --- b/dart-patterns-and-records/step_11_a/lib/main.dart +++ a/dart-patterns-and-records/step_11_a/lib/main.dart @@ -10,6 +10,19 @@ void main() { runApp(const DocumentApp()); } +String formatDate(DateTime dateTime) { + final today = DateTime.now(); + final difference = dateTime.difference(today); + + return switch (difference) { + Duration(inDays: 0) => 'today', + Duration(inDays: 1) => 'tomorrow', + Duration(inDays: -1) => 'yesterday', + Duration(inDays: final days, isNegative: true) => '${days.abs()} days ago', + Duration(inDays: final days) => '$days days from now', + }; +} + class DocumentApp extends StatelessWidget { const DocumentApp({super.key}); - name: Build web app path: patterns_codelab flutter: build web - name: Copy step_11_a copydir: from: patterns_codelab to: step_11_a - name: Flutter clean path: patterns_codelab flutter: clean - name: step_11_b steps: - name: Remove generated code rmdir: step_11_b - name: Update lib/main.dart path: patterns_codelab/lib/main.dart patch-u: | --- b/dart-patterns-and-records/step_11_b/lib/main.dart +++ a/dart-patterns-and-records/step_11_b/lib/main.dart @@ -18,6 +18,9 @@ String formatDate(DateTime dateTime) { Duration(inDays: 0) => 'today', Duration(inDays: 1) => 'tomorrow', Duration(inDays: -1) => 'yesterday', + Duration(inDays: final days) when days > 7 => '${days ~/ 7} weeks from now', + Duration(inDays: final days) when days < -7 => + '${days.abs() ~/ 7} weeks ago', Duration(inDays: final days, isNegative: true) => '${days.abs()} days ago', Duration(inDays: final days) => '$days days from now', }; @@ -48,6 +51,7 @@ class DocumentScreen extends StatelessWidget { @override Widget build(BuildContext context) { final (title, :modified) = document.metadata; + final formattedModifiedDate = formatDate(modified); final blocks = document.getBlocks(); return Scaffold( @@ -56,7 +60,7 @@ class DocumentScreen extends StatelessWidget { ), body: Column( children: [ - Text('Last modified: $modified'), + Text('Last modified: $formattedModifiedDate'), Expanded( child: ListView.builder( itemCount: blocks.length, - name: Build web app path: patterns_codelab flutter: build web - name: Copy step_11_b copydir: from: patterns_codelab to: step_11_b - name: Flutter clean path: patterns_codelab flutter: clean - name: step_12 steps: - name: Remove generated code rmdir: step_12 - name: Update lib/data.dart path: patterns_codelab/lib/data.dart patch-u: | --- b/dart-patterns-and-records/step_12/lib/data.dart +++ a/dart-patterns-and-records/step_12/lib/data.dart @@ -55,16 +55,32 @@ const documentJson = ''' } '''; -class Block { - final String type; - final String text; - Block(this.type, this.text); +sealed class Block { + Block(); - factory Block.fromJson(Map<String, dynamic> json) { - if (json case {'type': final type, 'text': final text}) { - return Block(type, text); - } else { - throw const FormatException('Unexpected JSON format'); - } + factory Block.fromJson(Map<String, Object?> json) { + return switch (json) { + {'type': 'h1', 'text': String text} => HeaderBlock(text), + {'type': 'p', 'text': String text} => ParagraphBlock(text), + {'type': 'checkbox', 'text': String text, 'checked': bool checked} => + CheckboxBlock(text, checked), + _ => throw const FormatException('Unexpected JSON format'), + }; } } + +class HeaderBlock extends Block { + final String text; + HeaderBlock(this.text); +} + +class ParagraphBlock extends Block { + final String text; + ParagraphBlock(this.text); +} + +class CheckboxBlock extends Block { + final String text; + final bool isChecked; + CheckboxBlock(this.text, this.isChecked); +} - name: Update lib/main.dart path: patterns_codelab/lib/main.dart patch-u: | --- b/dart-patterns-and-records/step_12/lib/main.dart +++ a/dart-patterns-and-records/step_12/lib/main.dart @@ -85,19 +85,21 @@ class BlockWidget extends StatelessWidget { @override Widget build(BuildContext context) { - TextStyle? textStyle; - textStyle = switch (block.type) { - 'h1' => Theme.of(context).textTheme.displayMedium, - 'p' || 'checkbox' => Theme.of(context).textTheme.bodyMedium, - _ => Theme.of(context).textTheme.bodySmall - }; - return Container( margin: const EdgeInsets.all(8), - child: Text( - block.text, - style: textStyle, - ), + child: switch (block) { + HeaderBlock(:final text) => Text( + text, + style: Theme.of(context).textTheme.displayMedium, + ), + ParagraphBlock(:final text) => Text(text), + CheckboxBlock(:final text, :final isChecked) => Row( + children: [ + Checkbox(value: isChecked, onChanged: (_) {}), + Text(text), + ], + ), + }, ); } } - name: Build web app path: patterns_codelab flutter: build web - name: Copy step_12 copydir: from: patterns_codelab to: step_12 - name: Flutter clean path: patterns_codelab flutter: clean - name: Cleanup rmdir: patterns_codelab
codelabs/dart-patterns-and-records/codelab_rebuild.yaml/0
{ "file_path": "codelabs/dart-patterns-and-records/codelab_rebuild.yaml", "repo_id": "codelabs", "token_count": 14325 }
10
#include "Generated.xcconfig"
codelabs/dart-patterns-and-records/step_06_b/ios/Flutter/Debug.xcconfig/0
{ "file_path": "codelabs/dart-patterns-and-records/step_06_b/ios/Flutter/Debug.xcconfig", "repo_id": "codelabs", "token_count": 12 }
11
#include "ephemeral/Flutter-Generated.xcconfig"
codelabs/dart-patterns-and-records/step_07_a/macos/Flutter/Flutter-Release.xcconfig/0
{ "file_path": "codelabs/dart-patterns-and-records/step_07_a/macos/Flutter/Flutter-Release.xcconfig", "repo_id": "codelabs", "token_count": 19 }
12
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
codelabs/dart-patterns-and-records/step_07_b/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "codelabs/dart-patterns-and-records/step_07_b/macos/Runner/Configs/Debug.xcconfig", "repo_id": "codelabs", "token_count": 32 }
13
#include "Generated.xcconfig"
codelabs/dart-patterns-and-records/step_12/ios/Flutter/Debug.xcconfig/0
{ "file_path": "codelabs/dart-patterns-and-records/step_12/ios/Flutter/Debug.xcconfig", "repo_id": "codelabs", "token_count": 12 }
14
#include "ephemeral/Flutter-Generated.xcconfig"
codelabs/deeplink_cookbook/macos/Flutter/Flutter-Release.xcconfig/0
{ "file_path": "codelabs/deeplink_cookbook/macos/Flutter/Flutter-Release.xcconfig", "repo_id": "codelabs", "token_count": 19 }
15
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
codelabs/ffigen_codelab/step_03/example/android/gradle.properties/0
{ "file_path": "codelabs/ffigen_codelab/step_03/example/android/gradle.properties", "repo_id": "codelabs", "token_count": 30 }
16
{ "indexes": [], "fieldOverrides": [] }
codelabs/firebase-auth-flutterfire-ui/complete/firestore.indexes.json/0
{ "file_path": "codelabs/firebase-auth-flutterfire-ui/complete/firestore.indexes.json", "repo_id": "codelabs", "token_count": 21 }
17
{"signIn":{"allowDuplicateEmails":false},"usageMode":"DEFAULT"}
codelabs/firebase-emulator-suite/complete/emulators_data/auth_export/config.json/0
{ "file_path": "codelabs/firebase-emulator-suite/complete/emulators_data/auth_export/config.json", "repo_id": "codelabs", "token_count": 20 }
18
// File generated by FlutterFire CLI. // ignore_for_file: lines_longer_than_80_chars import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; import 'package:flutter/foundation.dart' show defaultTargetPlatform, kIsWeb, TargetPlatform; /// Default [FirebaseOptions] for use with your Firebase apps. /// /// Example: /// ```dart /// import 'firebase_options.dart'; /// // ... /// await Firebase.initializeApp( /// options: DefaultFirebaseOptions.currentPlatform, /// ); /// ``` class DefaultFirebaseOptions { static FirebaseOptions get currentPlatform { if (kIsWeb) { return web; } switch (defaultTargetPlatform) { case TargetPlatform.android: return android; case TargetPlatform.iOS: return ios; case TargetPlatform.macOS: return macos; default: throw UnsupportedError( 'DefaultFirebaseOptions are not supported for this platform.'); } } static const FirebaseOptions web = FirebaseOptions( apiKey: 'AIzaSyBqTAGMEPyYPrraQColhTWE3gpBCHwBHaY', appId: '1:249605288217:web:f8441e30c5cc335b089588', messagingSenderId: '249605288217', projectId: 'flutter-firebase-codelab-d6b79', authDomain: 'flutter-firebase-codelab-d6b79.firebaseapp.com', storageBucket: 'flutter-firebase-codelab-d6b79.appspot.com', ); static const FirebaseOptions android = FirebaseOptions( apiKey: 'AIzaSyDOhizxfIPR8Qs4_isZnE_AnteC0zOxod4', appId: '1:249605288217:android:27c0f0a1ef464773089588', messagingSenderId: '249605288217', projectId: 'flutter-firebase-codelab-d6b79', storageBucket: 'flutter-firebase-codelab-d6b79.appspot.com', ); static const FirebaseOptions ios = FirebaseOptions( apiKey: 'AIzaSyCvSrqVklmfWxE_SM8HNHvxqOLZTQCsUtk', appId: '1:249605288217:ios:ef9f4946a0d08a35089588', messagingSenderId: '249605288217', projectId: 'flutter-firebase-codelab-d6b79', storageBucket: 'flutter-firebase-codelab-d6b79.appspot.com', iosClientId: '249605288217-9sn136tgsd0vg7nae831gahubpoph3ih.apps.googleusercontent.com', iosBundleId: 'com.example.complete', ); static const FirebaseOptions macos = FirebaseOptions( apiKey: 'AIzaSyCvSrqVklmfWxE_SM8HNHvxqOLZTQCsUtk', appId: '1:249605288217:ios:ef9f4946a0d08a35089588', messagingSenderId: '249605288217', projectId: 'flutter-firebase-codelab-d6b79', storageBucket: 'flutter-firebase-codelab-d6b79.appspot.com', iosClientId: '249605288217-9sn136tgsd0vg7nae831gahubpoph3ih.apps.googleusercontent.com', iosBundleId: 'com.example.complete', ); }
codelabs/firebase-emulator-suite/complete/lib/firebase_options.dart/0
{ "file_path": "codelabs/firebase-emulator-suite/complete/lib/firebase_options.dart", "repo_id": "codelabs", "token_count": 1118 }
19
#import "GeneratedPluginRegistrant.h"
codelabs/firebase-get-to-know-flutter/step_09/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "codelabs/firebase-get-to-know-flutter/step_09/ios/Runner/Runner-Bridging-Header.h", "repo_id": "codelabs", "token_count": 13 }
20
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
codelabs/firebase-get-to-know-flutter/step_09/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "codelabs/firebase-get-to-know-flutter/step_09/macos/Runner/Configs/Debug.xcconfig", "repo_id": "codelabs", "token_count": 32 }
21
#include "include/window_to_front/window_to_front_plugin_c_api.h" #include <flutter/plugin_registrar_windows.h> #include "window_to_front_plugin.h" void WindowToFrontPluginCApiRegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar) { window_to_front::WindowToFrontPlugin::RegisterWithRegistrar( flutter::PluginRegistrarManager::GetInstance() ->GetRegistrar<flutter::PluginRegistrarWindows>(registrar)); }
codelabs/github-client/window_to_front/windows/window_to_front_plugin_c_api.cpp/0
{ "file_path": "codelabs/github-client/window_to_front/windows/window_to_front_plugin_c_api.cpp", "repo_id": "codelabs", "token_count": 158 }
22
#import "GeneratedPluginRegistrant.h"
codelabs/google-maps-in-flutter/step_3/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "codelabs/google-maps-in-flutter/step_3/ios/Runner/Runner-Bridging-Header.h", "repo_id": "codelabs", "token_count": 13 }
23
#include "Generated.xcconfig"
codelabs/haiku_generator/step0/ios/Flutter/Release.xcconfig/0
{ "file_path": "codelabs/haiku_generator/step0/ios/Flutter/Release.xcconfig", "repo_id": "codelabs", "token_count": 12 }
24
#include "Generated.xcconfig"
codelabs/haiku_generator/step2/ios/Flutter/Release.xcconfig/0
{ "file_path": "codelabs/haiku_generator/step2/ios/Flutter/Release.xcconfig", "repo_id": "codelabs", "token_count": 12 }
25
import 'package:flutter/material.dart'; // New: Add this import import 'package:home_widget/home_widget.dart'; import 'article_screen.dart'; import 'news_data.dart'; // New: Add these constants // TO DO: Replace with your App Group ID const String appGroupId = '<YOUR APP GROUP>'; const String iOSWidgetName = 'NewsWidgets'; const String androidWidgetName = 'NewsWidget'; class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } // New: add this function void updateHeadline(NewsArticle newHeadline) { // Save the headline data to the widget HomeWidget.saveWidgetData<String>('headline_title', newHeadline.title); HomeWidget.saveWidgetData<String>( 'headline_description', newHeadline.description); HomeWidget.updateWidget( iOSName: iOSWidgetName, androidName: androidWidgetName, ); } class _MyHomePageState extends State<MyHomePage> { // New: Add initState @override void initState() { super.initState(); // Set the group ID HomeWidget.setAppGroupId(appGroupId); // Mock read in some data and update the headline final newHeadline = getNewsStories()[0]; updateHeadline(newHeadline); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Top Stories'), centerTitle: false, titleTextStyle: const TextStyle( fontSize: 30, fontWeight: FontWeight.bold, color: Colors.black)), body: ListView.separated( separatorBuilder: (context, idx) { return const Divider(); }, itemCount: getNewsStories().length, itemBuilder: (context, idx) { final article = getNewsStories()[idx]; return ListTile( key: Key('$idx ${article.hashCode}'), title: Text(article.title), subtitle: Text(article.description), onTap: () { Navigator.of(context).push( MaterialPageRoute<ArticleScreen>( builder: (context) { return ArticleScreen(article: article); }, ), ); }, ); }, )); } }
codelabs/homescreen_codelab/step_04/lib/home_screen.dart/0
{ "file_path": "codelabs/homescreen_codelab/step_04/lib/home_screen.dart", "repo_id": "codelabs", "token_count": 1011 }
26
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
codelabs/namer/step_05_a_pair/android/gradle.properties/0
{ "file_path": "codelabs/namer/step_05_a_pair/android/gradle.properties", "repo_id": "codelabs", "token_count": 30 }
27
#include "Generated.xcconfig"
codelabs/namer/step_05_c_card_padding/ios/Flutter/Release.xcconfig/0
{ "file_path": "codelabs/namer/step_05_c_card_padding/ios/Flutter/Release.xcconfig", "repo_id": "codelabs", "token_count": 12 }
28
#include "ephemeral/Flutter-Generated.xcconfig"
codelabs/namer/step_05_c_card_padding/macos/Flutter/Flutter-Release.xcconfig/0
{ "file_path": "codelabs/namer/step_05_c_card_padding/macos/Flutter/Flutter-Release.xcconfig", "repo_id": "codelabs", "token_count": 19 }
29
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
codelabs/namer/step_05_d_theme/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "codelabs/namer/step_05_d_theme/macos/Runner/Configs/Release.xcconfig", "repo_id": "codelabs", "token_count": 32 }
30
#include "Generated.xcconfig"
codelabs/namer/step_05_h_center_horizontal/ios/Flutter/Debug.xcconfig/0
{ "file_path": "codelabs/namer/step_05_h_center_horizontal/ios/Flutter/Debug.xcconfig", "repo_id": "codelabs", "token_count": 12 }
31
#include "ephemeral/Flutter-Generated.xcconfig"
codelabs/namer/step_05_h_center_horizontal/macos/Flutter/Flutter-Debug.xcconfig/0
{ "file_path": "codelabs/namer/step_05_h_center_horizontal/macos/Flutter/Flutter-Debug.xcconfig", "repo_id": "codelabs", "token_count": 19 }
32
#import "GeneratedPluginRegistrant.h"
codelabs/namer/step_05_i_optional_changes/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "codelabs/namer/step_05_i_optional_changes/ios/Runner/Runner-Bridging-Header.h", "repo_id": "codelabs", "token_count": 13 }
33
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
codelabs/namer/step_05_i_optional_changes/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "codelabs/namer/step_05_i_optional_changes/macos/Runner/Configs/Debug.xcconfig", "repo_id": "codelabs", "token_count": 32 }
34
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
codelabs/namer/step_07_e_add_layout_builder/android/gradle.properties/0
{ "file_path": "codelabs/namer/step_07_e_add_layout_builder/android/gradle.properties", "repo_id": "codelabs", "token_count": 30 }
35
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
codelabs/next-gen-ui/step_03_a/android/gradle.properties/0
{ "file_path": "codelabs/next-gen-ui/step_03_a/android/gradle.properties", "repo_id": "codelabs", "token_count": 30 }
36
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
codelabs/next-gen-ui/step_04_c/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "codelabs/next-gen-ui/step_04_c/macos/Runner/Configs/Release.xcconfig", "repo_id": "codelabs", "token_count": 32 }
37
#import "GeneratedPluginRegistrant.h"
codelabs/next-gen-ui/step_04_d/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "codelabs/next-gen-ui/step_04_d/ios/Runner/Runner-Bridging-Header.h", "repo_id": "codelabs", "token_count": 13 }
38
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
codelabs/next-gen-ui/step_05_a/android/gradle.properties/0
{ "file_path": "codelabs/next-gen-ui/step_05_a/android/gradle.properties", "repo_id": "codelabs", "token_count": 30 }
39
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
codelabs/testing_codelab/step_06/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "codelabs/testing_codelab/step_06/macos/Runner/Configs/Debug.xcconfig", "repo_id": "codelabs", "token_count": 32 }
40
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
codelabs/testing_codelab/step_08/android/gradle.properties/0
{ "file_path": "codelabs/testing_codelab/step_08/android/gradle.properties", "repo_id": "codelabs", "token_count": 30 }
41
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
codelabs/testing_codelab/step_08/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "codelabs/testing_codelab/step_08/macos/Runner/Configs/Release.xcconfig", "repo_id": "codelabs", "token_count": 32 }
42
org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true
codelabs/tfagents-flutter/finished/frontend/android/gradle.properties/0
{ "file_path": "codelabs/tfagents-flutter/finished/frontend/android/gradle.properties", "repo_id": "codelabs", "token_count": 31 }
43
org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true
codelabs/tfagents-flutter/step1/frontend/android/gradle.properties/0
{ "file_path": "codelabs/tfagents-flutter/step1/frontend/android/gradle.properties", "repo_id": "codelabs", "token_count": 31 }
44
#import "GeneratedPluginRegistrant.h"
codelabs/tfagents-flutter/step5/frontend/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "codelabs/tfagents-flutter/step5/frontend/ios/Runner/Runner-Bridging-Header.h", "repo_id": "codelabs", "token_count": 13 }
45
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
codelabs/tfagents-flutter/step5/frontend/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "codelabs/tfagents-flutter/step5/frontend/macos/Runner/Configs/Debug.xcconfig", "repo_id": "codelabs", "token_count": 32 }
46
#include "Generated.xcconfig"
codelabs/tfagents-flutter/step6/frontend/ios/Flutter/Debug.xcconfig/0
{ "file_path": "codelabs/tfagents-flutter/step6/frontend/ios/Flutter/Debug.xcconfig", "repo_id": "codelabs", "token_count": 12 }
47
#include "ephemeral/Flutter-Generated.xcconfig"
codelabs/tfagents-flutter/step6/frontend/macos/Flutter/Flutter-Debug.xcconfig/0
{ "file_path": "codelabs/tfagents-flutter/step6/frontend/macos/Flutter/Flutter-Debug.xcconfig", "repo_id": "codelabs", "token_count": 19 }
48
#include "Generated.xcconfig"
codelabs/tfrs-flutter/step0/frontend/ios/Flutter/Debug.xcconfig/0
{ "file_path": "codelabs/tfrs-flutter/step0/frontend/ios/Flutter/Debug.xcconfig", "repo_id": "codelabs", "token_count": 12 }
49
#include "ephemeral/Flutter-Generated.xcconfig"
codelabs/tfrs-flutter/step0/frontend/macos/Flutter/Flutter-Release.xcconfig/0
{ "file_path": "codelabs/tfrs-flutter/step0/frontend/macos/Flutter/Flutter-Release.xcconfig", "repo_id": "codelabs", "token_count": 19 }
50