text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
/* * Copyright 2018 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.run.bazelTest; import com.intellij.util.xmlb.XmlSerializer; import org.jdom.Element; import org.junit.Test; import java.util.Set; import java.util.TreeSet; import static org.junit.Assert.*; public class BazelTestFieldsTest { @Test public void shouldReadFieldsFromXml() { final Element elt = new Element("test"); addOption(elt, "testName", "Test number one"); addOption(elt, "entryFile", "/tmp/test/dir/lib/main.dart"); addOption(elt, "bazelTarget", "//path/to/flutter/app:hello"); addOption(elt, "additionalArgs", "--no-watch --some-other-args 75"); final BazelTestFields fields = BazelTestFields.readFrom(elt); assertEquals("Test number one", fields.getTestName()); assertEquals("/tmp/test/dir/lib/main.dart", fields.getEntryFile()); assertEquals("//path/to/flutter/app:hello", fields.getBazelTarget()); assertEquals("--no-watch --some-other-args 75", fields.getAdditionalArgs()); } @Test public void shouldUpgradeFieldsFromOldXml() { final Element elt = new Element("test"); addOption(elt, "launchingScript", "path/to/bazel-run.sh"); // obsolete addOption(elt, "entryFile", "/tmp/test/dir/lib/main.dart"); // obsolete addOption(elt, "bazelTarget", "//path/to/flutter/app:hello"); final BazelTestFields fields = BazelTestFields.readFrom(elt); XmlSerializer.deserializeInto(fields, elt); assertNull(fields.getTestName()); assertEquals("/tmp/test/dir/lib/main.dart", fields.getEntryFile()); assertEquals("//path/to/flutter/app:hello", fields.getBazelTarget()); assertNull(fields.getAdditionalArgs()); } @Test public void roundTripShouldPreserveFields() { final BazelTestFields before = new BazelTestFields( "Test number two", "/tmp/foo/lib/main_two.dart", "//path/to/flutter/app:hello2", "--no-watch --other-args" ); final Element elt = new Element("test"); before.writeTo(elt); // Verify that we no longer write workingDirectory. assertArrayEquals( new String[]{"additionalArgs", "bazelTarget", "entryFile", "testName"}, getOptionNames(elt).toArray()); final BazelTestFields after = BazelTestFields.readFrom(elt); assertEquals("Test number two", after.getTestName()); assertEquals("/tmp/foo/lib/main_two.dart", after.getEntryFile()); assertEquals("//path/to/flutter/app:hello2", after.getBazelTarget()); assertEquals("--no-watch --other-args", after.getAdditionalArgs()); } private void addOption(Element elt, String name, String value) { final Element child = new Element("option"); child.setAttribute("name", name); child.setAttribute("value", value); elt.addContent(child); } private Set<String> getOptionNames(Element elt) { final Set<String> result = new TreeSet<>(); for (Element child : elt.getChildren()) { result.add(child.getAttributeValue("name")); } return result; } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/bazelTest/BazelTestFieldsTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/bazelTest/BazelTestFieldsTest.java", "repo_id": "flutter-intellij", "token_count": 1114 }
522
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.testing; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.fixtures.impl.TempDirTestFixtureImpl; import org.junit.rules.ExternalResource; import static org.junit.Assert.assertNotNull; /** * Represents a temporary directory to be used in a JUnit 4 test. * * <p>To set up, use JUnit 4's @Rule or @ClassRule attribute. */ public class TestDir extends ExternalResource { final TempDirTestFixtureImpl fixture = new TempDirTestFixtureImpl(); @Override protected void before() throws Exception { fixture.setUp(); } @Override protected void after() { try { if (ApplicationManager.getApplication() != null) { fixture.tearDown(); } } catch (Exception e) { e.printStackTrace(); } } /** * Creates a subdirectory of the temp directory if it doesn't already exist. * * @param path relative to the temp directory. * @return The corresponding VirtualFile. */ public VirtualFile ensureDir(String path) throws Exception { return fixture.findOrCreateDir(path); } /** * Sets the contents of a file in the temp directory. * * <p>Creates it if it doesn't exist. * * @return The corresponding VirtualFile. */ public VirtualFile writeFile(String path, String text) throws Exception { return Testing.computeInWriteAction(() -> fixture.createFile(path, text)); } /** * Deletes a file in the temp directory. * * @param path relative to the temp directory. */ public void deleteFile(String path) throws Exception { Testing.runInWriteAction(() -> { final VirtualFile target = fixture.getFile(path); assertNotNull("attempted to delete nonexistent file: " + path, target); target.delete(this); }); } /** * Given a path relative to the temp directory, returns the absolute path. */ public String pathAt(String path) { return fixture.getTempDirPath() + "/" + path; } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/testing/TestDir.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/testing/TestDir.java", "repo_id": "flutter-intellij", "token_count": 703 }
523
/* * Copyright (c) 2017, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service; import com.google.gson.JsonObject; public interface RemoteServiceCompleter { /** * Should be called when a service request completes successfully. * * @param result the result of the request */ void result(JsonObject result); /** * Should be called when a service request completes with an error. * * @param code the error code generated by the request * @param message the description of the error * @param data [optional] the description of the error */ void error(int code, String message, JsonObject data); }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/RemoteServiceCompleter.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/RemoteServiceCompleter.java", "repo_id": "flutter-intellij", "token_count": 326 }
524
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonArray; import com.google.gson.JsonObject; /** * A {@link Context} is a data structure which holds the captured variables for some closure. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class Context extends Obj { public Context(JsonObject json) { super(json); } /** * The number of variables in this context. */ public int getLength() { return getAsInt("length"); } /** * The enclosing context for this context. * * Can return <code>null</code>. */ public ContextRef getParent() { JsonObject obj = (JsonObject) json.get("parent"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new ContextRef(obj); } /** * The variables in this context object. */ public ElementList<ContextElement> getVariables() { return new ElementList<ContextElement>(json.get("variables").getAsJsonArray()) { @Override protected ContextElement basicGet(JsonArray array, int index) { return new ContextElement(array.get(index).getAsJsonObject()); } }; } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Context.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Context.java", "repo_id": "flutter-intellij", "token_count": 644 }
525
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonObject; /** * An {@link FieldRef} is a reference to a {@link Field}. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class FieldRef extends ObjRef { public FieldRef(JsonObject json) { super(json); } /** * The declared type of this field. * * The value will always be of one of the kinds: Type, TypeRef, TypeParameter, BoundedType. */ public InstanceRef getDeclaredType() { return new InstanceRef((JsonObject) json.get("declaredType")); } /** * The location of this field in the source code. * * Note: this may not agree with the location of `owner` if this is a field from a mixin * application, patched class, etc. * * Can return <code>null</code>. */ public SourceLocation getLocation() { JsonObject obj = (JsonObject) json.get("location"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new SourceLocation(obj); } /** * The name of this field. */ public String getName() { return getAsString("name"); } /** * The owner of this field, which can be either a Library or a Class. * * Note: the location of `owner` may not agree with `location` if this is a field from a mixin * application, patched class, etc. */ public ObjRef getOwner() { return new ObjRef((JsonObject) json.get("owner")); } /** * Is this field const? */ public boolean isConst() { return getAsBoolean("const"); } /** * Is this field final? */ public boolean isFinal() { return getAsBoolean("final"); } /** * Is this field static? */ public boolean isStatic() { return getAsBoolean("static"); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/FieldRef.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/FieldRef.java", "repo_id": "flutter-intellij", "token_count": 852 }
526
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonObject; /** * {@link IsolateGroupRef} is a reference to an {@link IsolateGroup} object. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class IsolateGroupRef extends Response { public IsolateGroupRef(JsonObject json) { super(json); } /** * The id which is passed to the getIsolateGroup RPC to load this isolate group. */ public String getId() { return getAsString("id"); } /** * Specifies whether the isolate group was spawned by the VM or embedder for internal use. If * `false`, this isolate group is likely running user code. */ public boolean getIsSystemIsolateGroup() { return getAsBoolean("isSystemIsolateGroup"); } /** * A name identifying this isolate group. Not guaranteed to be unique. */ public String getName() { return getAsString("name"); } /** * A numeric id for this isolate group, represented as a string. Unique. */ public String getNumber() { return getAsString("number"); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/IsolateGroupRef.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/IsolateGroupRef.java", "repo_id": "flutter-intellij", "token_count": 518 }
527
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonObject; /** * The {@link SourceLocation} class is used to designate a position or range in some script. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class SourceLocation extends Response { public SourceLocation(JsonObject json) { super(json); } /** * The column associated with this location. Only provided for non-synthetic token positions. * * Can return <code>null</code>. */ public int getColumn() { return getAsInt("column"); } /** * The last token of the location if this is a range. * * Can return <code>null</code>. */ public int getEndTokenPos() { return getAsInt("endTokenPos"); } /** * The line associated with this location. Only provided for non-synthetic token positions. * * Can return <code>null</code>. */ public int getLine() { return getAsInt("line"); } /** * The script containing the source location. */ public ScriptRef getScript() { return new ScriptRef((JsonObject) json.get("script")); } /** * The first token of the location. */ public int getTokenPos() { return getAsInt("tokenPos"); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/SourceLocation.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/SourceLocation.java", "repo_id": "flutter-intellij", "token_count": 584 }
528
/* * Copyright 2020 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ repositories { mavenCentral() maven { url=uri("https://oss.sonatype.org/content/repositories/snapshots/") } } plugins { id("java") id("kotlin") id("org.jetbrains.intellij") } val ide: String by project val flutterPluginVersion: String by project val javaVersion: String by project val dartVersion: String by project val baseVersion: String by project val smaliPlugin: String by project val langPlugin: String by project val ideVersion: String by project group = "io.flutter" version = flutterPluginVersion tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().all { kotlinOptions { jvmTarget = javaVersion } } java { sourceCompatibility = JavaVersion.toVersion(javaVersion) targetCompatibility = JavaVersion.toVersion(javaVersion) } intellij { // This adds nullability assertions, but also compiles forms. instrumentCode.set(true) updateSinceUntilBuild.set(false) downloadSources.set(false) version.set(ideVersion) val pluginList = mutableListOf("java", "Dart:$dartVersion", "properties", "junit", "gradle", "Groovy", "org.jetbrains.android") if (ideVersion != "2023.2") { pluginList.add(smaliPlugin) } pluginList.add(langPlugin) plugins.set(pluginList) if (ide == "android-studio") { type.set("AI") } } dependencies { compileOnly(project(":flutter-idea")) testImplementation(project(":flutter-idea")) compileOnly(fileTree(mapOf("dir" to "${project.rootDir}/artifacts/android-studio/lib", "include" to listOf("*.jar")))) testImplementation(fileTree(mapOf("dir" to "${project.rootDir}/artifacts/android-studio/lib", "include" to listOf("*.jar")))) compileOnly(fileTree(mapOf("dir" to "${project.rootDir}/artifacts/android-studio/plugins", "include" to listOf("**/*.jar"), "exclude" to listOf("**/kotlin-compiler.jar", "**/kotlin-plugin.jar")))) testImplementation(fileTree(mapOf("dir" to "${project.rootDir}/artifacts/android-studio/plugins", "include" to listOf("**/*.jar"), "exclude" to listOf("**/kotlin-compiler.jar", "**/kotlin-plugin.jar")))) } sourceSets { main { java.srcDirs(listOf( "src", "third_party/vmServiceDrivers" //"resources" )) // Add kotlin.srcDirs if we start using Kotlin in the main plugin. //resources.srcDirs(listOf( //"src", //project(":flutter-idea").sourceSets.main.get().resources //"resources", //)) } } tasks { buildSearchableOptions { enabled = false } instrumentCode { compilerVersion.set("$baseVersion") } instrumentTestCode { compilerVersion.set("$baseVersion") } }
flutter-intellij/flutter-studio/build.gradle.kts/0
{ "file_path": "flutter-intellij/flutter-studio/build.gradle.kts", "repo_id": "flutter-intellij", "token_count": 1145 }
529
/* * Copyright 2019 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.editor; import com.android.tools.idea.ui.resourcechooser.colorpicker2.ColorPickerBuilder; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.BalloonBuilder; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.ui.awt.RelativePoint; import kotlin.Unit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.*; import javax.swing.*; public class AndroidStudioColorPickerProvider implements ColorPickerProvider { private Balloon popup; @Override public void show( Color initialColor, JComponent component, Point offset, Balloon.Position position, ColorPickerProvider.ColorListener colorListener, Runnable onCancel, Runnable onOk ) { if (popup != null) { popup.dispose(); } popup = null; final JComponent colorPanel = new ColorPickerBuilder() .setOriginalColor(initialColor != null ? initialColor : new Color(255, 255, 255)) .addSaturationBrightnessComponent() .addColorAdjustPanel() .addColorValuePanel().withFocus() .addOperationPanel( (okColor) -> { onOk.run(); return Unit.INSTANCE; }, (cancelColor) -> { onCancel.run(); return Unit.INSTANCE; } ).withFocus() .setFocusCycleRoot(true) .focusWhenDisplay(true) .addKeyAction( KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { onCancel.run(); } }) .addKeyAction( KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { onOk.run(); } } ) .addColorPickerListener((c, o) -> colorListener.colorChanged(c, null)) .build(); final BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().createBalloonBuilder(colorPanel); balloonBuilder.setFadeoutTime(0); balloonBuilder.setAnimationCycle(0); balloonBuilder.setHideOnClickOutside(true); balloonBuilder.setHideOnKeyOutside(false); balloonBuilder.setHideOnAction(false); balloonBuilder.setCloseButtonEnabled(false); balloonBuilder.setBlockClicksThroughBalloon(true); balloonBuilder.setRequestFocus(true); balloonBuilder.setShadow(true); balloonBuilder.setFillColor(colorPanel.getBackground()); popup = balloonBuilder.createBalloon(); popup.show(new RelativePoint(component, offset), position); } @Override public void dispose() { if (popup != null) { popup.dispose(); } popup = null; } }
flutter-intellij/flutter-studio/src/io/flutter/editor/AndroidStudioColorPickerProvider.java/0
{ "file_path": "flutter-intellij/flutter-studio/src/io/flutter/editor/AndroidStudioColorPickerProvider.java", "repo_id": "flutter-intellij", "token_count": 1143 }
530
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package com.android.tools.idea.tests.gui.framework.fixture; import javax.swing.JMenuItem; import org.fest.swing.core.Robot; import org.fest.swing.fixture.JMenuItemFixture; import org.jetbrains.annotations.NotNull; @SuppressWarnings("UnusedReturnValue") public class MenuItemFixture extends JMenuItemFixture { public MenuItemFixture(@NotNull Robot robot, @NotNull JMenuItem target) { super(robot, target); } /** * This is a replacement for AbstractComponentFixture.click(). The original method does not invoke the click() method of the driver * subclass used by JMenuItemFixture. Probably has something to do with type erasure. Ensuring the proper argument type, as is done * here, invokes the correct method. Et viola! Mac menus work. */ @NotNull public JMenuItemFixture clickit() { JMenuItem target = target(); driver().click(target); return myself(); } }
flutter-intellij/flutter-studio/testSrc/com/android/tools/idea/tests/gui/framework/fixture/MenuItemFixture.java/0
{ "file_path": "flutter-intellij/flutter-studio/testSrc/com/android/tools/idea/tests/gui/framework/fixture/MenuItemFixture.java", "repo_id": "flutter-intellij", "token_count": 326 }
531
#!/bin/bash # This should execute as a presubmit. # Fail on any error. set -e # Display commands being run. Only do this while debugging and be careful # that no confidential information is displayed. # set -x # Code under repo is checked out to ${KOKORO_ARTIFACTS_DIR}/github. # The final directory name in this path is determined by the scm name specified # in the job configuration. cd ${KOKORO_ARTIFACTS_DIR}/github/flutter-intellij-kokoro if [[ $KOKORO_JOB_NAME =~ .*presubmit ]]; then ./tool/kokoro/test.sh else echo "The build branch should not be reached in a test run." ./tool/kokoro/build.sh fi
flutter-intellij/kokoro/macos_external/kokoro_test.sh/0
{ "file_path": "flutter-intellij/kokoro/macos_external/kokoro_test.sh", "repo_id": "flutter-intellij", "token_count": 203 }
532
{ "flutter": { "version": "3.1.0", "channel": "beta" }, "widgets": [ { "name": "AboutDialog", "parent": "StatelessWidget", "library": "material", "description": "An about box. This is a dialog box with the application's icon, name, version number, and copyright, plus a button to show licenses for software used by the application." }, { "name": "AboutListTile", "parent": "StatelessWidget", "library": "material", "description": "A [ListTile] that shows an about box." }, { "name": "AbsorbPointer", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that absorbs pointers during hit testing." }, { "name": "ActionChip", "parent": "StatelessWidget", "library": "material", "description": "A material design action chip." }, { "name": "ActionListener", "parent": "StatefulWidget", "library": "widgets", "description": "A helper widget for making sure that listeners on an action are removed properly." }, { "name": "Actions", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that establishes an [ActionDispatcher] and a map of [Intent] to [Action] to be used by its descendants when invoking an [Action]." }, { "name": "AlertDialog", "parent": "StatelessWidget", "library": "material", "description": "A material design alert dialog." }, { "name": "Align", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that aligns its child within itself and optionally sizes itself based on the child's size." }, { "name": "AlignTransition", "parent": "AnimatedWidget", "library": "widgets", "description": "Animated version of an [Align] that animates its [Align.alignment] property." }, { "name": "AndroidView", "parent": "StatefulWidget", "library": "widgets", "description": "Embeds an Android view in the Widget hierarchy." }, { "name": "AndroidViewSurface", "parent": "PlatformViewSurface", "library": "widgets", "description": "Integrates an Android view with Flutter's compositor, touch, and semantics subsystems." }, { "name": "AnimatedAlign", "parent": "ImplicitlyAnimatedWidget", "library": "widgets", "description": "Animated version of [Align] which automatically transitions the child's position over a given duration whenever the given [alignment] changes." }, { "name": "AnimatedBuilder", "parent": "AnimatedWidget", "library": "widgets", "description": "A general-purpose widget for building animations." }, { "name": "AnimatedContainer", "parent": "ImplicitlyAnimatedWidget", "library": "widgets", "description": "Animated version of [Container] that gradually changes its values over a period of time." }, { "name": "AnimatedCrossFade", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that cross-fades between two given children and animates itself between their sizes." }, { "name": "AnimatedDefaultTextStyle", "parent": "ImplicitlyAnimatedWidget", "library": "widgets", "description": "Animated version of [DefaultTextStyle] which automatically transitions the default text style (the text style to apply to descendant [Text] widgets without explicit style) over a given duration whenever the given style changes." }, { "name": "AnimatedIcon", "parent": "StatelessWidget", "library": "material", "description": "Shows an animated icon at a given animation [progress]." }, { "name": "AnimatedList", "parent": "StatefulWidget", "library": "widgets", "description": "A scrolling container that animates items when they are inserted or removed." }, { "name": "AnimatedModalBarrier", "parent": "AnimatedWidget", "library": "widgets", "description": "A widget that prevents the user from interacting with widgets behind itself, and can be configured with an animated color value." }, { "name": "AnimatedOpacity", "parent": "ImplicitlyAnimatedWidget", "library": "widgets", "description": "Animated version of [Opacity] which automatically transitions the child's opacity over a given duration whenever the given opacity changes." }, { "name": "AnimatedPadding", "parent": "ImplicitlyAnimatedWidget", "library": "widgets", "description": "Animated version of [Padding] which automatically transitions the indentation over a given duration whenever the given inset changes." }, { "name": "AnimatedPhysicalModel", "parent": "ImplicitlyAnimatedWidget", "library": "widgets", "description": "Animated version of [PhysicalModel]." }, { "name": "AnimatedPositioned", "parent": "ImplicitlyAnimatedWidget", "library": "widgets", "description": "Animated version of [Positioned] which automatically transitions the child's position over a given duration whenever the given position changes." }, { "name": "AnimatedPositionedDirectional", "parent": "ImplicitlyAnimatedWidget", "library": "widgets", "description": "Animated version of [PositionedDirectional] which automatically transitions the child's position over a given duration whenever the given position changes." }, { "name": "AnimatedRotation", "parent": "ImplicitlyAnimatedWidget", "library": "widgets", "description": "Animated version of [Transform.rotate] which automatically transitions the child's rotation over a given duration whenever the given rotation changes." }, { "name": "AnimatedScale", "parent": "ImplicitlyAnimatedWidget", "library": "widgets", "description": "Animated version of [Transform.scale] which automatically transitions the child's scale over a given duration whenever the given scale changes." }, { "name": "AnimatedSize", "parent": "StatefulWidget", "library": "widgets", "description": "Animated widget that automatically transitions its size over a given duration whenever the given child's size changes." }, { "name": "AnimatedSlide", "parent": "ImplicitlyAnimatedWidget", "library": "widgets", "description": "Widget which automatically transitions the child's offset relative to its normal position whenever the given offset changes." }, { "name": "AnimatedSwitcher", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that by default does a cross-fade between a new widget and the widget previously set on the [AnimatedSwitcher] as a child." }, { "name": "AnimatedTheme", "parent": "ImplicitlyAnimatedWidget", "library": "material", "description": "Animated version of [Theme] which automatically transitions the colors, etc, over a given duration whenever the given theme changes." }, { "name": "AnimatedWidget", "parent": "StatefulWidget", "library": "widgets", "abstract": true, "description": "A widget that rebuilds when the given [Listenable] changes value." }, { "name": "AnnotatedRegion", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "Annotates a region of the layer tree with a value." }, { "name": "AppBar", "parent": "StatefulWidget", "library": "material", "description": "A material design app bar." }, { "name": "AspectRatio", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that attempts to size the child to a specific aspect ratio." }, { "name": "Autocomplete", "parent": "StatelessWidget", "library": "material", "description": "{@macro flutter.widgets.RawAutocomplete.RawAutocomplete}" }, { "name": "AutocompleteHighlightedOption", "parent": "InheritedNotifier", "library": "widgets", "description": "An inherited widget used to indicate which autocomplete option should be highlighted for keyboard navigation." }, { "name": "AutofillGroup", "parent": "StatefulWidget", "library": "widgets", "description": "An [AutofillScope] widget that groups [AutofillClient]s together." }, { "name": "AutomaticKeepAlive", "parent": "StatefulWidget", "library": "widgets", "description": "Allows subtrees to request to be kept alive in lazy lists." }, { "name": "BackButton", "parent": "StatelessWidget", "library": "material", "description": "A material design back button." }, { "name": "BackButtonIcon", "parent": "StatelessWidget", "library": "material", "description": "A \"back\" icon that's appropriate for the current [TargetPlatform]." }, { "name": "BackButtonListener", "parent": "StatefulWidget", "library": "widgets", "description": "A convenience widget that registers a callback for when the back button is pressed." }, { "name": "BackdropFilter", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that applies a filter to the existing painted content and then paints [child]." }, { "name": "Banner", "parent": "StatelessWidget", "library": "widgets", "description": "Displays a diagonal message above the corner of another widget." }, { "name": "Baseline", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that positions its child according to the child's baseline." }, { "name": "BlockSemantics", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that drops the semantics of all widget that were painted before it in the same semantic container." }, { "name": "BottomAppBar", "parent": "StatefulWidget", "library": "material", "description": "A container that is typically used with [Scaffold.bottomNavigationBar], and can have a notch along the top that makes room for an overlapping [FloatingActionButton]." }, { "name": "BottomNavigationBar", "parent": "StatefulWidget", "library": "material", "description": "A material widget that's displayed at the bottom of an app for selecting among a small number of views, typically between three and five." }, { "name": "BottomNavigationBarTheme", "parent": "InheritedWidget", "library": "material", "description": "Applies a bottom navigation bar theme to descendant [BottomNavigationBar] widgets." }, { "name": "BottomSheet", "parent": "StatefulWidget", "library": "material", "description": "A material design bottom sheet." }, { "name": "BoxScrollView", "parent": "ScrollView", "library": "widgets", "abstract": true, "description": "A [ScrollView] that uses a single child layout model." }, { "name": "Builder", "parent": "StatelessWidget", "library": "widgets", "description": "A stateless utility widget whose [build] method uses its [builder] callback to create the widget's child." }, { "name": "ButtonBar", "parent": "StatelessWidget", "library": "material", "description": "An end-aligned row of buttons, laying out into a column if there is not enough horizontal space." }, { "name": "ButtonBarTheme", "parent": "InheritedWidget", "library": "material", "description": "Applies a button bar theme to descendant [ButtonBar] widgets." }, { "name": "ButtonStyleButton", "parent": "StatefulWidget", "library": "material", "abstract": true, "description": "The base [StatefulWidget] class for buttons whose style is defined by a [ButtonStyle] object." }, { "name": "ButtonTheme", "parent": "InheritedTheme", "library": "material", "description": "Used with [ButtonThemeData] to configure the color and geometry of buttons." }, { "name": "CalendarDatePicker", "parent": "StatefulWidget", "library": "material", "description": "Displays a grid of days for a given month and allows the user to select a date." }, { "name": "CallbackShortcuts", "parent": "StatelessWidget", "library": "widgets", "description": "A widget that provides an uncomplicated mechanism for binding a key combination to a specific callback." }, { "name": "Card", "parent": "StatelessWidget", "library": "material", "description": "A material design card: a panel with slightly rounded corners and an elevation shadow." }, { "name": "Center", "parent": "Align", "library": "widgets", "description": "A widget that centers its child within itself." }, { "name": "Checkbox", "parent": "StatefulWidget", "library": "material", "description": "A material design checkbox." }, { "name": "CheckboxListTile", "parent": "StatelessWidget", "library": "material", "description": "A [ListTile] with a [Checkbox]. In other words, a checkbox with a label." }, { "name": "CheckboxTheme", "parent": "InheritedWidget", "library": "material", "description": "Applies a checkbox theme to descendant [Checkbox] widgets." }, { "name": "CheckedModeBanner", "parent": "StatelessWidget", "library": "widgets", "description": "Displays a [Banner] saying \"DEBUG\" when running in debug mode. [MaterialApp] builds one of these by default. Does nothing in release mode." }, { "name": "CheckedPopupMenuItem", "parent": "PopupMenuItem", "library": "material", "description": "An item with a checkmark in a material design popup menu." }, { "name": "Chip", "parent": "StatelessWidget", "library": "material", "description": "A material design chip." }, { "name": "ChipTheme", "parent": "InheritedTheme", "library": "material", "description": "Applies a chip theme to descendant [RawChip]-based widgets, like [Chip], [InputChip], [ChoiceChip], [FilterChip], and [ActionChip]." }, { "name": "ChoiceChip", "parent": "StatelessWidget", "library": "material", "description": "A material design choice chip." }, { "name": "CircleAvatar", "parent": "StatelessWidget", "library": "material", "description": "A circle that represents a user." }, { "name": "CircularProgressIndicator", "parent": "ProgressIndicator", "library": "material", "description": "A material design circular progress indicator, which spins to indicate that the application is busy." }, { "name": "ClipOval", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that clips its child using an oval." }, { "name": "ClipPath", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that clips its child using a path." }, { "name": "ClipRRect", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that clips its child using a rounded rectangle." }, { "name": "ClipRect", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that clips its child using a rectangle." }, { "name": "CloseButton", "parent": "StatelessWidget", "library": "material", "description": "A material design close button." }, { "name": "ColorFiltered", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "Applies a [ColorFilter] to its child." }, { "name": "ColoredBox", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that paints its area with a specified [Color] and then draws its child on top of that color." }, { "name": "Column", "parent": "Flex", "library": "widgets", "description": "A widget that displays its children in a vertical array." }, { "name": "CompositedTransformFollower", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that follows a [CompositedTransformTarget]." }, { "name": "CompositedTransformTarget", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that can be targeted by a [CompositedTransformFollower]." }, { "name": "ConstrainedBox", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that imposes additional constraints on its child." }, { "name": "ConstrainedLayoutBuilder", "parent": "RenderObjectWidget", "library": "widgets", "abstract": true, "description": "An abstract superclass for widgets that defer their building until layout." }, { "name": "ConstraintsTransformBox", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A container widget that applies an arbitrary transform to its constraints, and sizes its child using the resulting [BoxConstraints], treating any overflow as error." }, { "name": "Container", "parent": "StatelessWidget", "library": "widgets", "description": "A convenience widget that combines common painting, positioning, and sizing widgets." }, { "name": "CupertinoActionSheet", "parent": "StatelessWidget", "library": "cupertino", "description": "An iOS-style action sheet." }, { "name": "CupertinoActionSheetAction", "parent": "StatelessWidget", "library": "cupertino", "description": "A button typically used in a [CupertinoActionSheet]." }, { "name": "CupertinoActivityIndicator", "parent": "StatefulWidget", "library": "cupertino", "description": "An iOS-style activity indicator that spins clockwise." }, { "name": "CupertinoAlertDialog", "parent": "StatelessWidget", "library": "cupertino", "description": "An iOS-style alert dialog." }, { "name": "CupertinoApp", "parent": "StatefulWidget", "library": "cupertino", "description": "An application that uses Cupertino design." }, { "name": "CupertinoButton", "parent": "StatefulWidget", "library": "cupertino", "description": "An iOS-style button." }, { "name": "CupertinoContextMenu", "parent": "StatefulWidget", "library": "cupertino", "description": "A full-screen modal route that opens when the [child] is long-pressed." }, { "name": "CupertinoContextMenuAction", "parent": "StatefulWidget", "library": "cupertino", "description": "A button in a _ContextMenuSheet." }, { "name": "CupertinoDatePicker", "parent": "StatefulWidget", "library": "cupertino", "description": "A date picker widget in iOS style." }, { "name": "CupertinoDialogAction", "parent": "StatelessWidget", "library": "cupertino", "description": "A button typically used in a [CupertinoAlertDialog]." }, { "name": "CupertinoFormRow", "parent": "StatelessWidget", "library": "cupertino", "description": "An iOS-style form row." }, { "name": "CupertinoFormSection", "parent": "StatelessWidget", "library": "cupertino", "description": "An iOS-style form section." }, { "name": "CupertinoFullscreenDialogTransition", "parent": "StatelessWidget", "library": "cupertino", "description": "An iOS-style transition used for summoning fullscreen dialogs." }, { "name": "CupertinoNavigationBar", "parent": "StatefulWidget", "library": "cupertino", "description": "An iOS-styled navigation bar." }, { "name": "CupertinoNavigationBarBackButton", "parent": "StatelessWidget", "library": "cupertino", "description": "A nav bar back button typically used in [CupertinoNavigationBar]." }, { "name": "CupertinoPageScaffold", "parent": "StatefulWidget", "library": "cupertino", "description": "Implements a single iOS application page's layout." }, { "name": "CupertinoPageTransition", "parent": "StatelessWidget", "library": "cupertino", "description": "Provides an iOS-style page transition animation." }, { "name": "CupertinoPicker", "parent": "StatefulWidget", "library": "cupertino", "description": "An iOS-styled picker." }, { "name": "CupertinoPickerDefaultSelectionOverlay", "parent": "StatelessWidget", "library": "cupertino", "description": "A default selection overlay for [CupertinoPicker]s." }, { "name": "CupertinoPopupSurface", "parent": "StatelessWidget", "library": "cupertino", "description": "Rounded rectangle surface that looks like an iOS popup surface, e.g., alert dialog and action sheet." }, { "name": "CupertinoScrollbar", "parent": "RawScrollbar", "library": "cupertino", "description": "An iOS style scrollbar." }, { "name": "CupertinoSearchTextField", "parent": "StatefulWidget", "library": "cupertino", "description": "A [CupertinoTextField] that mimics the look and behavior of UIKit's `UISearchTextField`." }, { "name": "CupertinoSegmentedControl", "parent": "StatefulWidget", "library": "cupertino", "description": "An iOS-style segmented control." }, { "name": "CupertinoSlider", "parent": "StatefulWidget", "library": "cupertino", "description": "An iOS-style slider." }, { "name": "CupertinoSlidingSegmentedControl", "parent": "StatefulWidget", "library": "cupertino", "description": "An iOS 13 style segmented control." }, { "name": "CupertinoSliverNavigationBar", "parent": "StatefulWidget", "library": "cupertino", "description": "An iOS-styled navigation bar with iOS-11-style large titles using slivers." }, { "name": "CupertinoSliverRefreshControl", "parent": "StatefulWidget", "library": "cupertino", "description": "A sliver widget implementing the iOS-style pull to refresh content control." }, { "name": "CupertinoSwitch", "parent": "StatefulWidget", "library": "cupertino", "description": "An iOS-style switch." }, { "name": "CupertinoTabBar", "parent": "StatelessWidget", "library": "cupertino", "description": "An iOS-styled bottom navigation tab bar." }, { "name": "CupertinoTabScaffold", "parent": "StatefulWidget", "library": "cupertino", "description": "Implements a tabbed iOS application's root layout and behavior structure." }, { "name": "CupertinoTabView", "parent": "StatefulWidget", "library": "cupertino", "description": "A single tab view with its own [Navigator] state and history." }, { "name": "CupertinoTextField", "parent": "StatefulWidget", "library": "cupertino", "description": "An iOS-style text field." }, { "name": "CupertinoTextFormFieldRow", "parent": "FormField", "library": "cupertino", "description": "Creates a [CupertinoFormRow] containing a [FormField] that wraps a [CupertinoTextField]." }, { "name": "CupertinoTextSelectionToolbar", "parent": "StatelessWidget", "library": "cupertino", "description": "An iOS-style text selection toolbar." }, { "name": "CupertinoTextSelectionToolbarButton", "parent": "StatelessWidget", "library": "cupertino", "description": "A button in the style of the iOS text selection toolbar buttons." }, { "name": "CupertinoTheme", "parent": "StatelessWidget", "library": "cupertino", "description": "Applies a visual styling theme to descendant Cupertino widgets." }, { "name": "CupertinoTimerPicker", "parent": "StatefulWidget", "library": "cupertino", "description": "A countdown timer picker in iOS style." }, { "name": "CupertinoUserInterfaceLevel", "parent": "InheritedWidget", "library": "cupertino", "description": "Establishes a subtree in which [CupertinoUserInterfaceLevel.of] resolves to the given data." }, { "name": "CustomMultiChildLayout", "parent": "MultiChildRenderObjectWidget", "library": "widgets", "description": "A widget that uses a delegate to size and position multiple children." }, { "name": "CustomPaint", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that provides a canvas on which to draw during the paint phase." }, { "name": "CustomScrollView", "parent": "ScrollView", "library": "widgets", "description": "A [ScrollView] that creates custom scroll effects using slivers." }, { "name": "CustomSingleChildLayout", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that defers the layout of its single child to a delegate." }, { "name": "DataTable", "parent": "StatelessWidget", "library": "material", "description": "A material design data table." }, { "name": "DataTableTheme", "parent": "InheritedWidget", "library": "material", "description": "Applies a data table theme to descendant [DataTable] widgets." }, { "name": "DatePickerDialog", "parent": "StatefulWidget", "library": "material", "description": "A Material-style date picker dialog." }, { "name": "DateRangePickerDialog", "parent": "StatefulWidget", "library": "material", "description": "A Material-style date range picker dialog." }, { "name": "DecoratedBox", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that paints a [Decoration] either before or after its child paints." }, { "name": "DecoratedBoxTransition", "parent": "AnimatedWidget", "library": "widgets", "description": "Animated version of a [DecoratedBox] that animates the different properties of its [Decoration]." }, { "name": "DefaultAssetBundle", "parent": "InheritedWidget", "library": "widgets", "description": "A widget that determines the default asset bundle for its descendants." }, { "name": "DefaultSelectionStyle", "parent": "InheritedTheme", "library": "widgets", "description": "The selection style to apply to descendant [EditableText] widgets which don't have an explicit style." }, { "name": "DefaultTabController", "parent": "StatefulWidget", "library": "material", "description": "The [TabController] for descendant widgets that don't specify one explicitly." }, { "name": "DefaultTextEditingShortcuts", "parent": "Shortcuts", "library": "widgets", "description": "A [Shortcuts] widget with the shortcuts used for the default text editing behavior." }, { "name": "DefaultTextHeightBehavior", "parent": "InheritedTheme", "library": "widgets", "description": "The [TextHeightBehavior] that will apply to descendant [Text] and [EditableText] widgets which have not explicitly set [Text.textHeightBehavior]." }, { "name": "DefaultTextStyle", "parent": "InheritedTheme", "library": "widgets", "description": "The text style to apply to descendant [Text] widgets which don't have an explicit style." }, { "name": "DefaultTextStyleTransition", "parent": "AnimatedWidget", "library": "widgets", "description": "Animated version of a [DefaultTextStyle] that animates the different properties of its [TextStyle]." }, { "name": "Dialog", "parent": "StatelessWidget", "library": "material", "description": "A material design dialog." }, { "name": "Directionality", "parent": "InheritedWidget", "library": "widgets", "description": "A widget that determines the ambient directionality of text and text-direction-sensitive render objects." }, { "name": "Dismissible", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that can be dismissed by dragging in the indicated [direction]." }, { "name": "DisplayFeatureSubScreen", "parent": "StatelessWidget", "library": "widgets", "description": "Positions [child] such that it avoids overlapping any [DisplayFeature] that splits the screen into sub-screens." }, { "name": "Divider", "parent": "StatelessWidget", "library": "material", "description": "A thin horizontal line, with padding on either side." }, { "name": "DividerTheme", "parent": "InheritedTheme", "library": "material", "description": "An inherited widget that defines the configuration for [Divider]s, [VerticalDivider]s, dividers between [ListTile]s, and dividers between rows in [DataTable]s in this widget's subtree." }, { "name": "DragTarget", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that receives data when a [Draggable] widget is dropped." }, { "name": "Draggable", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that can be dragged from to a [DragTarget]." }, { "name": "DraggableScrollableActuator", "parent": "StatelessWidget", "library": "widgets", "description": "A widget that can notify a descendent [DraggableScrollableSheet] that it should reset its position to the initial state." }, { "name": "DraggableScrollableSheet", "parent": "StatefulWidget", "library": "widgets", "description": "A container for a [Scrollable] that responds to drag gestures by resizing the scrollable until a limit is reached, and then scrolling." }, { "name": "Drawer", "parent": "StatelessWidget", "library": "material", "description": "A material design panel that slides in horizontally from the edge of a [Scaffold] to show navigation links in an application." }, { "name": "DrawerController", "parent": "StatefulWidget", "library": "material", "description": "Provides interactive behavior for [Drawer] widgets." }, { "name": "DrawerHeader", "parent": "StatelessWidget", "library": "material", "description": "The top-most region of a material design drawer. The header's [child] widget, if any, is placed inside a [Container] whose [decoration] can be passed as an argument, inset by the given [padding]." }, { "name": "DrawerTheme", "parent": "InheritedTheme", "library": "material", "description": "An inherited widget that defines visual properties for [Drawer]s in this widget's subtree." }, { "name": "DropdownButton", "parent": "StatefulWidget", "library": "material", "description": "A material design button for selecting from a list of items." }, { "name": "DropdownButtonFormField", "parent": "FormField", "library": "material", "description": "A [FormField] that contains a [DropdownButton]." }, { "name": "DropdownButtonHideUnderline", "parent": "InheritedWidget", "library": "material", "description": "An inherited widget that causes any descendant [DropdownButton] widgets to not include their regular underline." }, { "name": "DropdownMenuItem", "parent": "_DropdownMenuItemContainer", "library": "material", "description": "An item in a menu created by a [DropdownButton]." }, { "name": "DualTransitionBuilder", "parent": "StatefulWidget", "library": "widgets", "description": "A transition builder that animates its [child] based on the [AnimationStatus] of the provided [animation]." }, { "name": "EditableText", "parent": "StatefulWidget", "library": "widgets", "description": "A basic text input field." }, { "name": "ElevatedButton", "parent": "ButtonStyleButton", "library": "material", "description": "A Material Design \"elevated button\"." }, { "name": "ElevatedButtonTheme", "parent": "InheritedTheme", "library": "material", "description": "Overrides the default [ButtonStyle] of its [ElevatedButton] descendants." }, { "name": "ErrorWidget", "parent": "LeafRenderObjectWidget", "library": "widgets", "description": "A widget that renders an exception's message." }, { "name": "ExcludeFocus", "parent": "StatelessWidget", "library": "widgets", "description": "A widget that controls whether or not the descendants of this widget are focusable." }, { "name": "ExcludeFocusTraversal", "parent": "StatelessWidget", "library": "widgets", "description": "A widget that controls whether or not the descendants of this widget are traversable." }, { "name": "ExcludeSemantics", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that drops all the semantics of its descendants." }, { "name": "ExpandIcon", "parent": "StatefulWidget", "library": "material", "description": "A widget representing a rotating expand/collapse button. The icon rotates 180 degrees when pressed, then reverts the animation on a second press. The underlying icon is [Icons.expand_more]." }, { "name": "Expanded", "parent": "Flexible", "library": "widgets", "description": "A widget that expands a child of a [Row], [Column], or [Flex] so that the child fills the available space." }, { "name": "ExpansionPanelList", "parent": "StatefulWidget", "library": "material", "description": "A material expansion panel list that lays out its children and animates expansions." }, { "name": "ExpansionTile", "parent": "StatefulWidget", "library": "material", "description": "A single-line [ListTile] with an expansion arrow icon that expands or collapses the tile to reveal or hide the [children]." }, { "name": "ExpansionTileTheme", "parent": "InheritedTheme", "library": "material", "description": "Overrides the default [ExpansionTileTheme] of its [ExpansionTile] descendants." }, { "name": "FadeInImage", "parent": "StatefulWidget", "library": "widgets", "description": "An image that shows a [placeholder] image while the target [image] is loading, then fades in the new image when it loads." }, { "name": "FadeTransition", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "Animates the opacity of a widget." }, { "name": "FilterChip", "parent": "StatelessWidget", "library": "material", "description": "A material design filter chip." }, { "name": "FittedBox", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "Scales and positions its child within itself according to [fit]." }, { "name": "Flex", "parent": "MultiChildRenderObjectWidget", "library": "widgets", "description": "A widget that displays its children in a one-dimensional array." }, { "name": "Flexible", "parent": "ParentDataWidget", "library": "widgets", "description": "A widget that controls how a child of a [Row], [Column], or [Flex] flexes." }, { "name": "FlexibleSpaceBar", "parent": "StatefulWidget", "library": "material", "description": "The part of a material design [AppBar] that expands, collapses, and stretches." }, { "name": "FlexibleSpaceBarSettings", "parent": "InheritedWidget", "library": "material", "description": "Provides sizing and opacity information to a [FlexibleSpaceBar]." }, { "name": "FloatingActionButton", "parent": "StatelessWidget", "library": "material", "description": "A material design floating action button." }, { "name": "Flow", "parent": "MultiChildRenderObjectWidget", "library": "widgets", "description": "A widget that sizes and positions children efficiently, according to the logic in a [FlowDelegate]." }, { "name": "FlutterLogo", "parent": "StatelessWidget", "library": "material", "description": "The Flutter logo, in widget form. This widget respects the [IconTheme]. For guidelines on using the Flutter logo, visit https://flutter.dev/brand." }, { "name": "Focus", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that manages a [FocusNode] to allow keyboard focus to be given to this widget and its descendants." }, { "name": "FocusScope", "parent": "Focus", "library": "widgets", "description": "A [FocusScope] is similar to a [Focus], but also serves as a scope for its descendants, restricting focus traversal to the scoped controls." }, { "name": "FocusTrap", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "The [FocusTrap] widget removes focus when a mouse primary pointer makes contact with another region of the screen." }, { "name": "FocusTrapArea", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "Declares a widget subtree which is part of the provided [focusNode]'s focus area without attaching focus to that region." }, { "name": "FocusTraversalGroup", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that describes the inherited focus policy for focus traversal for its descendants, grouping them into a separate traversal group." }, { "name": "FocusTraversalOrder", "parent": "InheritedWidget", "library": "widgets", "description": "An inherited widget that describes the order in which its child subtree should be traversed." }, { "name": "FocusableActionDetector", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that combines the functionality of [Actions], [Shortcuts], [MouseRegion] and a [Focus] widget to create a detector that defines actions and key bindings, and provides callbacks for handling focus and hover highlights." }, { "name": "Form", "parent": "StatefulWidget", "library": "widgets", "description": "An optional container for grouping together multiple form field widgets (e.g. [TextField] widgets)." }, { "name": "FormField", "parent": "StatefulWidget", "library": "widgets", "description": "A single form field." }, { "name": "FractionalTranslation", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "Applies a translation transformation before painting its child." }, { "name": "FractionallySizedBox", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that sizes its child to a fraction of the total available space. For more details about the layout algorithm, see [RenderFractionallySizedOverflowBox]." }, { "name": "FutureBuilder", "parent": "StatefulWidget", "library": "widgets", "description": "Widget that builds itself based on the latest snapshot of interaction with a [Future]." }, { "name": "GestureDetector", "parent": "StatelessWidget", "library": "widgets", "description": "A widget that detects gestures." }, { "name": "GlowingOverscrollIndicator", "parent": "StatefulWidget", "library": "widgets", "description": "A visual indication that a scroll view has overscrolled." }, { "name": "GridPaper", "parent": "StatelessWidget", "library": "widgets", "description": "A widget that draws a rectilinear grid of lines one pixel wide." }, { "name": "GridTile", "parent": "StatelessWidget", "library": "material", "description": "A tile in a material design grid list." }, { "name": "GridTileBar", "parent": "StatelessWidget", "library": "material", "description": "A header used in a material design [GridTile]." }, { "name": "GridView", "parent": "BoxScrollView", "library": "widgets", "description": "A scrollable, 2D array of widgets." }, { "name": "Hero", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that marks its child as being a candidate for [hero animations](https://flutter.dev/docs/development/ui/animations/hero-animations)." }, { "name": "HeroControllerScope", "parent": "InheritedWidget", "library": "widgets", "description": "An inherited widget to host a hero controller." }, { "name": "HeroMode", "parent": "StatelessWidget", "library": "widgets", "description": "Enables or disables [Hero]es in the widget subtree." }, { "name": "HtmlElementView", "parent": "StatelessWidget", "library": "widgets", "description": "Embeds an HTML element in the Widget hierarchy in Flutter Web." }, { "name": "Icon", "parent": "StatelessWidget", "library": "widgets", "description": "A graphical icon widget drawn with a glyph from a font described in an [IconData] such as material's predefined [IconData]s in [Icons]." }, { "name": "IconButton", "parent": "StatelessWidget", "library": "material", "description": "A material design icon button." }, { "name": "IconTheme", "parent": "InheritedTheme", "library": "widgets", "description": "Controls the default color, opacity, and size of icons in a widget subtree." }, { "name": "IgnorePointer", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that is invisible during hit testing." }, { "name": "Image", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that displays an image." }, { "name": "ImageFiltered", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "Applies an [ImageFilter] to its child." }, { "name": "ImageIcon", "parent": "StatelessWidget", "library": "widgets", "description": "An icon that comes from an [ImageProvider], e.g. an [AssetImage]." }, { "name": "ImplicitlyAnimatedWidget", "parent": "StatefulWidget", "library": "widgets", "abstract": true, "description": "An abstract class for building widgets that animate changes to their properties." }, { "name": "IndexedSemantics", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that annotates the child semantics with an index." }, { "name": "IndexedStack", "parent": "Stack", "library": "widgets", "description": "A [Stack] that shows a single child from a list of children." }, { "name": "InheritedModel", "parent": "InheritedWidget", "library": "widgets", "abstract": true, "description": "An [InheritedWidget] that's intended to be used as the base class for models whose dependents may only depend on one part or \"aspect\" of the overall model." }, { "name": "InheritedNotifier", "parent": "InheritedWidget", "library": "widgets", "abstract": true, "description": "An inherited widget for a [Listenable] [notifier], which updates its dependencies when the [notifier] is triggered." }, { "name": "InheritedTheme", "parent": "InheritedWidget", "library": "widgets", "abstract": true, "description": "An [InheritedWidget] that defines visual properties like colors and text styles, which the [child]'s subtree depends on." }, { "name": "InheritedWidget", "parent": "ProxyWidget", "library": "widgets", "abstract": true, "description": "Base class for widgets that efficiently propagate information down the tree." }, { "name": "Ink", "parent": "StatefulWidget", "library": "material", "description": "A convenience widget for drawing images and other decorations on [Material] widgets, so that [InkWell] and [InkResponse] splashes will render over them." }, { "name": "InkResponse", "parent": "StatelessWidget", "library": "material", "description": "An area of a [Material] that responds to touch. Has a configurable shape and can be configured to clip splashes that extend outside its bounds or not." }, { "name": "InkWell", "parent": "InkResponse", "library": "material", "description": "A rectangular area of a [Material] that responds to touch." }, { "name": "InputChip", "parent": "StatelessWidget", "library": "material", "description": "A material design input chip." }, { "name": "InputDatePickerFormField", "parent": "StatefulWidget", "library": "material", "description": "A [TextFormField] configured to accept and validate a date entered by a user." }, { "name": "InputDecorator", "parent": "StatefulWidget", "library": "material", "description": "Defines the appearance of a Material Design text field." }, { "name": "InteractiveViewer", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that enables pan and zoom interactions with its child." }, { "name": "IntrinsicHeight", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that sizes its child to the child's intrinsic height." }, { "name": "IntrinsicWidth", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that sizes its child to the child's maximum intrinsic width." }, { "name": "KeepAlive", "parent": "ParentDataWidget", "library": "widgets", "description": "Mark a child as needing to stay alive even when it's in a lazy list that would otherwise remove it." }, { "name": "KeyboardListener", "parent": "StatelessWidget", "library": "widgets", "description": "A widget that calls a callback whenever the user presses or releases a key on a keyboard." }, { "name": "KeyedSubtree", "parent": "StatelessWidget", "library": "widgets", "description": "A widget that builds its child." }, { "name": "LayoutBuilder", "parent": "ConstrainedLayoutBuilder", "library": "widgets", "description": "Builds a widget tree that can depend on the parent widget's size." }, { "name": "LayoutId", "parent": "ParentDataWidget", "library": "widgets", "description": "Metadata for identifying children in a [CustomMultiChildLayout]." }, { "name": "LeafRenderObjectWidget", "parent": "RenderObjectWidget", "library": "widgets", "abstract": true, "description": "A superclass for RenderObjectWidgets that configure RenderObject subclasses that have no children." }, { "name": "LicensePage", "parent": "StatefulWidget", "library": "material", "description": "A page that shows licenses for software used by the application." }, { "name": "LimitedBox", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A box that limits its size only when it's unconstrained." }, { "name": "LinearProgressIndicator", "parent": "ProgressIndicator", "library": "material", "description": "A material design linear progress indicator, also known as a progress bar." }, { "name": "ListBody", "parent": "MultiChildRenderObjectWidget", "library": "widgets", "description": "A widget that arranges its children sequentially along a given axis, forcing them to the dimension of the parent in the other axis." }, { "name": "ListTile", "parent": "StatelessWidget", "library": "material", "description": "A single fixed-height row that typically contains some text as well as a leading or trailing icon." }, { "name": "ListTileTheme", "parent": "InheritedTheme", "library": "material", "description": "An inherited widget that defines color and style parameters for [ListTile]s in this widget's subtree." }, { "name": "ListView", "parent": "BoxScrollView", "library": "widgets", "description": "A scrollable list of widgets arranged linearly." }, { "name": "ListWheelScrollView", "parent": "StatefulWidget", "library": "widgets", "description": "A box in which children on a wheel can be scrolled." }, { "name": "ListWheelViewport", "parent": "RenderObjectWidget", "library": "widgets", "description": "A viewport showing a subset of children on a wheel." }, { "name": "Listener", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that calls callbacks in response to common pointer events." }, { "name": "Localizations", "parent": "StatefulWidget", "library": "widgets", "description": "Defines the [Locale] for its `child` and the localized resources that the child depends on." }, { "name": "LongPressDraggable", "parent": "Draggable", "library": "widgets", "description": "Makes its child draggable starting from long press." }, { "name": "Material", "parent": "StatefulWidget", "library": "material", "description": "A piece of material." }, { "name": "MaterialApp", "parent": "StatefulWidget", "library": "material", "description": "An application that uses material design." }, { "name": "MaterialBanner", "parent": "StatefulWidget", "library": "material", "description": "A Material Design banner." }, { "name": "MaterialBannerTheme", "parent": "InheritedTheme", "library": "material", "description": "An inherited widget that defines the configuration for [MaterialBanner]s in this widget's subtree." }, { "name": "MaterialButton", "parent": "StatelessWidget", "library": "material", "description": "A utility class for building Material buttons that depend on the ambient [ButtonTheme] and [Theme]." }, { "name": "MediaQuery", "parent": "InheritedWidget", "library": "widgets", "description": "Establishes a subtree in which media queries resolve to the given data." }, { "name": "MergeSemantics", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that merges the semantics of its descendants." }, { "name": "MergeableMaterial", "parent": "StatefulWidget", "library": "material", "description": "Displays a list of [MergeableMaterialItem] children. The list contains [MaterialSlice] items whose boundaries are either \"merged\" with adjacent items or separated by a [MaterialGap]. The [children] are distributed along the given [mainAxis] in the same way as the children of a [ListBody]. When the list of children changes, gaps are automatically animated open or closed as needed." }, { "name": "MetaData", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "Holds opaque meta data in the render tree." }, { "name": "ModalBarrier", "parent": "StatelessWidget", "library": "widgets", "description": "A widget that prevents the user from interacting with widgets behind itself." }, { "name": "MouseRegion", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that tracks the movement of mice." }, { "name": "MultiChildRenderObjectWidget", "parent": "RenderObjectWidget", "library": "widgets", "abstract": true, "description": "A superclass for [RenderObjectWidget]s that configure [RenderObject] subclasses that have a single list of children. (This superclass only provides the storage for that child list, it doesn't actually provide the updating logic.)" }, { "name": "NavigationBar", "parent": "StatelessWidget", "library": "material", "description": "Material 3 Navigation Bar component." }, { "name": "NavigationBarTheme", "parent": "InheritedTheme", "library": "material", "description": "An inherited widget that defines visual properties for [NavigationBar]s and [NavigationDestination]s in this widget's subtree." }, { "name": "NavigationDestination", "parent": "StatelessWidget", "library": "material", "description": "Destination Widget for displaying Icons + labels in the Material 3 Navigation Bars through [NavigationBar.destinations]." }, { "name": "NavigationIndicator", "parent": "StatelessWidget", "library": "material", "description": "Selection Indicator for the Material 3 [NavigationBar] and [NavigationRail] components." }, { "name": "NavigationRail", "parent": "StatefulWidget", "library": "material", "description": "A material widget that is meant to be displayed at the left or right of an app to navigate between a small number of views, typically between three and five." }, { "name": "NavigationRailTheme", "parent": "InheritedTheme", "library": "material", "description": "An inherited widget that defines visual properties for [NavigationRail]s and [NavigationRailDestination]s in this widget's subtree." }, { "name": "NavigationToolbar", "parent": "StatelessWidget", "library": "widgets", "description": "[NavigationToolbar] is a layout helper to position 3 widgets or groups of widgets along a horizontal axis that's sensible for an application's navigation bar such as in Material Design and in iOS." }, { "name": "Navigator", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that manages a set of child widgets with a stack discipline." }, { "name": "NestedScrollView", "parent": "StatefulWidget", "library": "widgets", "description": "A scrolling view inside of which can be nested other scrolling views, with their scroll positions being intrinsically linked." }, { "name": "NestedScrollViewViewport", "parent": "Viewport", "library": "widgets", "description": "The [Viewport] variant used by [NestedScrollView]." }, { "name": "NotificationListener", "parent": "ProxyWidget", "library": "widgets", "description": "A widget that listens for [Notification]s bubbling up the tree." }, { "name": "ObstructingPreferredSizeWidget", "parent": "Object", "library": "cupertino", "abstract": true, "description": "Widget that has a preferred size and reports whether it fully obstructs widgets behind it." }, { "name": "Offstage", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that lays the child out as if it was in the tree, but without painting anything, without making the child available for hit testing, and without taking any room in the parent." }, { "name": "Opacity", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that makes its child partially transparent." }, { "name": "OrientationBuilder", "parent": "StatelessWidget", "library": "widgets", "description": "Builds a widget tree that can depend on the parent widget's orientation (distinct from the device orientation)." }, { "name": "OutlinedButton", "parent": "ButtonStyleButton", "library": "material", "description": "A Material Design \"Outlined Button\"; essentially a [TextButton] with an outlined border." }, { "name": "OutlinedButtonTheme", "parent": "InheritedTheme", "library": "material", "description": "Overrides the default [ButtonStyle] of its [OutlinedButton] descendants." }, { "name": "OverflowBar", "parent": "MultiChildRenderObjectWidget", "library": "widgets", "description": "A widget that lays out its [children] in a row unless they \"overflow\" the available horizontal space, in which case it lays them out in a column instead." }, { "name": "OverflowBox", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that imposes different constraints on its child than it gets from its parent, possibly allowing the child to overflow the parent." }, { "name": "Overlay", "parent": "StatefulWidget", "library": "widgets", "description": "A stack of entries that can be managed independently." }, { "name": "Padding", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that insets its child by the given padding." }, { "name": "PageStorage", "parent": "StatelessWidget", "library": "widgets", "description": "Establish a subtree in which widgets can opt into persisting states after being destroyed." }, { "name": "PageView", "parent": "StatefulWidget", "library": "widgets", "description": "A scrollable list that works page by page." }, { "name": "PaginatedDataTable", "parent": "StatefulWidget", "library": "material", "description": "A material design data table that shows data using multiple pages." }, { "name": "ParentDataWidget", "parent": "ProxyWidget", "library": "widgets", "abstract": true, "description": "Base class for widgets that hook [ParentData] information to children of [RenderObjectWidget]s." }, { "name": "PerformanceOverlay", "parent": "LeafRenderObjectWidget", "library": "widgets", "description": "Displays performance statistics." }, { "name": "PhysicalModel", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget representing a physical layer that clips its children to a shape." }, { "name": "PhysicalShape", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget representing a physical layer that clips its children to a path." }, { "name": "Placeholder", "parent": "StatelessWidget", "library": "widgets", "description": "A widget that draws a box that represents where other widgets will one day be added." }, { "name": "PlatformMenuBar", "parent": "StatefulWidget", "library": "widgets", "description": "A menu bar that uses the platform's native APIs to construct and render a menu described by a [PlatformMenu]/[PlatformMenuItem] hierarchy." }, { "name": "PlatformViewLink", "parent": "StatefulWidget", "library": "widgets", "description": "Links a platform view with the Flutter framework." }, { "name": "PlatformViewSurface", "parent": "LeafRenderObjectWidget", "library": "widgets", "description": "Integrates a platform view with Flutter's compositor, touch, and semantics subsystems." }, { "name": "PopupMenuButton", "parent": "StatefulWidget", "library": "material", "description": "Displays a menu when pressed and calls [onSelected] when the menu is dismissed because an item was selected. The value passed to [onSelected] is the value of the selected menu item." }, { "name": "PopupMenuDivider", "parent": "PopupMenuEntry", "library": "material", "description": "A horizontal divider in a material design popup menu." }, { "name": "PopupMenuEntry", "parent": "StatefulWidget", "library": "material", "abstract": true, "description": "A base class for entries in a material design popup menu." }, { "name": "PopupMenuItem", "parent": "PopupMenuEntry", "library": "material", "description": "An item in a material design popup menu." }, { "name": "PopupMenuTheme", "parent": "InheritedTheme", "library": "material", "description": "An inherited widget that defines the configuration for popup menus in this widget's subtree." }, { "name": "Positioned", "parent": "ParentDataWidget", "library": "widgets", "description": "A widget that controls where a child of a [Stack] is positioned." }, { "name": "PositionedDirectional", "parent": "StatelessWidget", "library": "widgets", "description": "A widget that controls where a child of a [Stack] is positioned without committing to a specific [TextDirection]." }, { "name": "PositionedTransition", "parent": "AnimatedWidget", "library": "widgets", "description": "Animated version of [Positioned] which takes a specific [Animation<RelativeRect>] to transition the child's position from a start position to an end position over the lifetime of the animation." }, { "name": "PreferredSize", "parent": "StatelessWidget", "library": "widgets", "description": "A widget with a preferred size." }, { "name": "PreferredSizeWidget", "parent": "Object", "library": "widgets", "abstract": true, "description": "An interface for widgets that can return the size this widget would prefer if it were otherwise unconstrained." }, { "name": "PrimaryScrollController", "parent": "InheritedWidget", "library": "widgets", "description": "Associates a [ScrollController] with a subtree." }, { "name": "ProgressIndicator", "parent": "StatefulWidget", "library": "material", "abstract": true, "description": "A base class for material design progress indicators." }, { "name": "ProgressIndicatorTheme", "parent": "InheritedTheme", "library": "material", "description": "An inherited widget that defines the configuration for [ProgressIndicator]s in this widget's subtree." }, { "name": "ProxyWidget", "parent": "Widget", "library": "widgets", "abstract": true, "description": "A widget that has a child widget provided to it, instead of building a new widget." }, { "name": "Radio", "parent": "StatefulWidget", "library": "material", "description": "A material design radio button." }, { "name": "RadioListTile", "parent": "StatelessWidget", "library": "material", "description": "A [ListTile] with a [Radio]. In other words, a radio button with a label." }, { "name": "RadioTheme", "parent": "InheritedWidget", "library": "material", "description": "Applies a radio theme to descendant [Radio] widgets." }, { "name": "RangeSlider", "parent": "StatefulWidget", "library": "material", "description": "A Material Design range slider." }, { "name": "RawAutocomplete", "parent": "StatefulWidget", "library": "widgets", "description": "{@template flutter.widgets.RawAutocomplete.RawAutocomplete} A widget for helping the user make a selection by entering some text and choosing from among a list of options." }, { "name": "RawChip", "parent": "StatefulWidget", "library": "material", "description": "A raw material design chip." }, { "name": "RawGestureDetector", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that detects gestures described by the given gesture factories." }, { "name": "RawImage", "parent": "LeafRenderObjectWidget", "library": "widgets", "description": "A widget that displays a [dart:ui.Image] directly." }, { "name": "RawKeyboardListener", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that calls a callback whenever the user presses or releases a key on a keyboard." }, { "name": "RawMaterialButton", "parent": "StatefulWidget", "library": "material", "categories": [ "Material", "Button" ], "description": "Creates a button based on [Semantics], [Material], and [InkWell] widgets." }, { "name": "RawScrollbar", "parent": "StatefulWidget", "library": "widgets", "description": "An extendable base class for building scrollbars that fade in and out." }, { "name": "RefreshIndicator", "parent": "StatefulWidget", "library": "material", "description": "A widget that supports the Material \"swipe to refresh\" idiom." }, { "name": "RefreshProgressIndicator", "parent": "CircularProgressIndicator", "library": "material", "description": "An indicator for the progress of refreshing the contents of a widget." }, { "name": "RelativePositionedTransition", "parent": "AnimatedWidget", "library": "widgets", "description": "Animated version of [Positioned] which transitions the child's position based on the value of [rect] relative to a bounding box with the specified [size]." }, { "name": "RenderObjectToWidgetAdapter", "parent": "RenderObjectWidget", "library": "widgets", "description": "A bridge from a [RenderObject] to an [Element] tree." }, { "name": "RenderObjectWidget", "parent": "Widget", "library": "widgets", "abstract": true, "description": "RenderObjectWidgets provide the configuration for [RenderObjectElement]s, which wrap [RenderObject]s, which provide the actual rendering of the application." }, { "name": "ReorderableDelayedDragStartListener", "parent": "ReorderableDragStartListener", "library": "widgets", "description": "A wrapper widget that will recognize the start of a drag operation by looking for a long press event. Once it is recognized, it will start a drag operation on the wrapped item in the reorderable list." }, { "name": "ReorderableDragStartListener", "parent": "StatelessWidget", "library": "widgets", "description": "A wrapper widget that will recognize the start of a drag on the wrapped widget by a [PointerDownEvent], and immediately initiate dragging the wrapped item to a new location in a reorderable list." }, { "name": "ReorderableList", "parent": "StatefulWidget", "library": "widgets", "description": "A scrolling container that allows the user to interactively reorder the list items." }, { "name": "ReorderableListView", "parent": "StatefulWidget", "library": "material", "description": "A list whose items the user can interactively reorder by dragging." }, { "name": "RepaintBoundary", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that creates a separate display list for its child." }, { "name": "RestorationScope", "parent": "StatefulWidget", "library": "widgets", "description": "Creates a new scope for restoration IDs used by descendant widgets to claim [RestorationBucket]s." }, { "name": "RichText", "parent": "MultiChildRenderObjectWidget", "library": "widgets", "description": "A paragraph of rich text." }, { "name": "RootRestorationScope", "parent": "StatefulWidget", "library": "widgets", "description": "Inserts a child bucket of [RestorationManager.rootBucket] into the widget tree and makes it available to descendants via [RestorationScope.of]." }, { "name": "RotatedBox", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that rotates its child by a integral number of quarter turns." }, { "name": "RotationTransition", "parent": "AnimatedWidget", "library": "widgets", "description": "Animates the rotation of a widget." }, { "name": "Router", "parent": "StatefulWidget", "library": "widgets", "description": "The dispatcher for opening and closing pages of an application." }, { "name": "Row", "parent": "Flex", "library": "widgets", "description": "A widget that displays its children in a horizontal array." }, { "name": "SafeArea", "parent": "StatelessWidget", "library": "widgets", "description": "A widget that insets its child by sufficient padding to avoid intrusions by the operating system." }, { "name": "Scaffold", "parent": "StatefulWidget", "library": "material", "description": "Implements the basic material design visual layout structure." }, { "name": "ScaffoldMessenger", "parent": "StatefulWidget", "library": "material", "description": "Manages [SnackBar]s and [MaterialBanner]s for descendant [Scaffold]s." }, { "name": "ScaleTransition", "parent": "AnimatedWidget", "library": "widgets", "description": "Animates the scale of a transformed widget." }, { "name": "ScrollConfiguration", "parent": "InheritedWidget", "library": "widgets", "description": "Controls how [Scrollable] widgets behave in a subtree." }, { "name": "ScrollNotificationObserver", "parent": "StatefulWidget", "library": "widgets", "description": "Notifies its listeners when a descendant scrolls." }, { "name": "ScrollView", "parent": "StatelessWidget", "library": "widgets", "abstract": true, "description": "A widget that scrolls." }, { "name": "Scrollable", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that scrolls." }, { "name": "Scrollbar", "parent": "StatelessWidget", "library": "material", "description": "A Material Design scrollbar." }, { "name": "ScrollbarTheme", "parent": "InheritedWidget", "library": "material", "description": "Applies a scrollbar theme to descendant [Scrollbar] widgets." }, { "name": "SelectableText", "parent": "StatefulWidget", "library": "material", "description": "A run of selectable text with a single style." }, { "name": "Semantics", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that annotates the widget tree with a description of the meaning of the widgets." }, { "name": "SemanticsDebugger", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that visualizes the semantics for the child." }, { "name": "ShaderMask", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that applies a mask generated by a [Shader] to its child." }, { "name": "SharedAppData", "parent": "StatefulWidget", "library": "widgets", "description": "Enables sharing key/value data with its `child` and all of the child's descendants." }, { "name": "Shortcuts", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that creates key bindings to specific actions for its descendants." }, { "name": "ShrinkWrappingViewport", "parent": "MultiChildRenderObjectWidget", "library": "widgets", "description": "A widget that is bigger on the inside and shrink wraps its children in the main axis." }, { "name": "SimpleDialog", "parent": "StatelessWidget", "library": "material", "description": "A simple material design dialog." }, { "name": "SimpleDialogOption", "parent": "StatelessWidget", "library": "material", "description": "An option used in a [SimpleDialog]." }, { "name": "SingleChildRenderObjectWidget", "parent": "RenderObjectWidget", "library": "widgets", "abstract": true, "description": "A superclass for [RenderObjectWidget]s that configure [RenderObject] subclasses that have a single child slot. (This superclass only provides the storage for that child, it doesn't actually provide the updating logic.)" }, { "name": "SingleChildScrollView", "parent": "StatelessWidget", "library": "widgets", "description": "A box in which a single widget can be scrolled." }, { "name": "SizeChangedLayoutNotifier", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that automatically dispatches a [SizeChangedLayoutNotification] when the layout dimensions of its child change." }, { "name": "SizeTransition", "parent": "AnimatedWidget", "library": "widgets", "description": "Animates its own size and clips and aligns its child." }, { "name": "SizedBox", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A box with a specified size." }, { "name": "SizedOverflowBox", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that is a specific size but passes its original constraints through to its child, which may then overflow." }, { "name": "SlideTransition", "parent": "AnimatedWidget", "library": "widgets", "description": "Animates the position of a widget relative to its normal position." }, { "name": "Slider", "parent": "StatefulWidget", "library": "material", "description": "A Material Design slider." }, { "name": "SliderTheme", "parent": "InheritedTheme", "library": "material", "description": "Applies a slider theme to descendant [Slider] widgets." }, { "name": "SliverAnimatedList", "parent": "StatefulWidget", "library": "widgets", "description": "A sliver that animates items when they are inserted or removed." }, { "name": "SliverAnimatedOpacity", "parent": "ImplicitlyAnimatedWidget", "library": "widgets", "description": "Animated version of [SliverOpacity] which automatically transitions the sliver child's opacity over a given duration whenever the given opacity changes." }, { "name": "SliverAppBar", "parent": "StatefulWidget", "library": "material", "description": "A material design app bar that integrates with a [CustomScrollView]." }, { "name": "SliverFadeTransition", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "Animates the opacity of a sliver widget." }, { "name": "SliverFillRemaining", "parent": "StatelessWidget", "library": "widgets", "description": "A sliver that contains a single box child that fills the remaining space in the viewport." }, { "name": "SliverFillViewport", "parent": "StatelessWidget", "library": "widgets", "description": "A sliver that contains multiple box children that each fills the viewport." }, { "name": "SliverFixedExtentList", "parent": "SliverMultiBoxAdaptorWidget", "library": "widgets", "description": "A sliver that places multiple box children with the same main axis extent in a linear array." }, { "name": "SliverGrid", "parent": "SliverMultiBoxAdaptorWidget", "library": "widgets", "description": "A sliver that places multiple box children in a two dimensional arrangement." }, { "name": "SliverIgnorePointer", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A sliver widget that is invisible during hit testing." }, { "name": "SliverLayoutBuilder", "parent": "ConstrainedLayoutBuilder", "library": "widgets", "description": "Builds a sliver widget tree that can depend on its own [SliverConstraints]." }, { "name": "SliverList", "parent": "SliverMultiBoxAdaptorWidget", "library": "widgets", "description": "A sliver that places multiple box children in a linear array along the main axis." }, { "name": "SliverMultiBoxAdaptorWidget", "parent": "SliverWithKeepAliveWidget", "library": "widgets", "abstract": true, "description": "A base class for sliver that have multiple box children." }, { "name": "SliverOffstage", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A sliver that lays its sliver child out as if it was in the tree, but without painting anything, without making the sliver child available for hit testing, and without taking any room in the parent." }, { "name": "SliverOpacity", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A sliver widget that makes its sliver child partially transparent." }, { "name": "SliverOverlapAbsorber", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A sliver that wraps another, forcing its layout extent to be treated as overlap." }, { "name": "SliverOverlapInjector", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A sliver that has a sliver geometry based on the values stored in a [SliverOverlapAbsorberHandle]." }, { "name": "SliverPadding", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A sliver that applies padding on each side of another sliver." }, { "name": "SliverPersistentHeader", "parent": "StatelessWidget", "library": "widgets", "description": "A sliver whose size varies when the sliver is scrolled to the edge of the viewport opposite the sliver's [GrowthDirection]." }, { "name": "SliverPrototypeExtentList", "parent": "SliverMultiBoxAdaptorWidget", "library": "widgets", "description": "A sliver that places its box children in a linear array and constrains them to have the same extent as a prototype item along the main axis." }, { "name": "SliverReorderableList", "parent": "StatefulWidget", "library": "widgets", "description": "A sliver list that allows the user to interactively reorder the list items." }, { "name": "SliverSafeArea", "parent": "StatelessWidget", "library": "widgets", "description": "A sliver that insets another sliver by sufficient padding to avoid intrusions by the operating system." }, { "name": "SliverToBoxAdapter", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A sliver that contains a single box widget." }, { "name": "SliverVisibility", "parent": "StatelessWidget", "library": "widgets", "description": "Whether to show or hide a sliver child." }, { "name": "SliverWithKeepAliveWidget", "parent": "RenderObjectWidget", "library": "widgets", "abstract": true, "description": "A base class for sliver that have [KeepAlive] children." }, { "name": "SnackBar", "parent": "StatefulWidget", "library": "material", "description": "A lightweight message with an optional action which briefly displays at the bottom of the screen." }, { "name": "SnackBarAction", "parent": "StatefulWidget", "library": "material", "description": "A button for a [SnackBar], known as an \"action\"." }, { "name": "Spacer", "parent": "StatelessWidget", "library": "widgets", "description": "Spacer creates an adjustable, empty spacer that can be used to tune the spacing between widgets in a [Flex] container, like [Row] or [Column]." }, { "name": "Stack", "parent": "MultiChildRenderObjectWidget", "library": "widgets", "description": "A widget that positions its children relative to the edges of its box." }, { "name": "StatefulBuilder", "parent": "StatefulWidget", "library": "widgets", "description": "A platonic widget that both has state and calls a closure to obtain its child widget." }, { "name": "StatefulWidget", "parent": "Widget", "library": "widgets", "abstract": true, "description": "A widget that has mutable state." }, { "name": "StatelessWidget", "parent": "Widget", "library": "widgets", "abstract": true, "description": "A widget that does not require mutable state." }, { "name": "StatusTransitionWidget", "parent": "StatefulWidget", "library": "widgets", "abstract": true, "description": "A widget that rebuilds when the given animation changes status." }, { "name": "Stepper", "parent": "StatefulWidget", "library": "material", "description": "A material stepper widget that displays progress through a sequence of steps. Steppers are particularly useful in the case of forms where one step requires the completion of another one, or where multiple steps need to be completed in order to submit the whole form." }, { "name": "StreamBuilder", "parent": "StreamBuilderBase", "library": "widgets", "description": "Widget that builds itself based on the latest snapshot of interaction with a [Stream]." }, { "name": "StreamBuilderBase", "parent": "StatefulWidget", "library": "widgets", "abstract": true, "description": "Base class for widgets that build themselves based on interaction with a specified [Stream]." }, { "name": "StretchingOverscrollIndicator", "parent": "StatefulWidget", "library": "widgets", "description": "A Material Design visual indication that a scroll view has overscrolled." }, { "name": "Switch", "parent": "StatelessWidget", "library": "material", "description": "A material design switch." }, { "name": "SwitchListTile", "parent": "StatelessWidget", "library": "material", "description": "A [ListTile] with a [Switch]. In other words, a switch with a label." }, { "name": "SwitchTheme", "parent": "InheritedWidget", "library": "material", "description": "Applies a switch theme to descendant [Switch] widgets." }, { "name": "Tab", "parent": "StatelessWidget", "library": "material", "description": "A material design [TabBar] tab." }, { "name": "TabBar", "parent": "StatefulWidget", "library": "material", "description": "A material design widget that displays a horizontal row of tabs." }, { "name": "TabBarView", "parent": "StatefulWidget", "library": "material", "description": "A page view that displays the widget which corresponds to the currently selected tab." }, { "name": "TabPageSelector", "parent": "StatelessWidget", "library": "material", "description": "Uses [TabPageSelectorIndicator] to display a row of small circular indicators, one per tab." }, { "name": "TabPageSelectorIndicator", "parent": "StatelessWidget", "library": "material", "description": "Displays a single circle with the specified size, border style, border color and background colors." }, { "name": "Table", "parent": "RenderObjectWidget", "library": "widgets", "description": "A widget that uses the table layout algorithm for its children." }, { "name": "TableCell", "parent": "ParentDataWidget", "library": "widgets", "description": "A widget that controls how a child of a [Table] is aligned." }, { "name": "TableRowInkWell", "parent": "InkResponse", "library": "material", "description": "A rectangular area of a Material that responds to touch but clips its ink splashes to the current table row of the nearest table." }, { "name": "Text", "parent": "StatelessWidget", "library": "widgets", "description": "A run of text with a single style." }, { "name": "TextButton", "parent": "ButtonStyleButton", "library": "material", "description": "A Material Design \"Text Button\"." }, { "name": "TextButtonTheme", "parent": "InheritedTheme", "library": "material", "description": "Overrides the default [ButtonStyle] of its [TextButton] descendants." }, { "name": "TextField", "parent": "StatefulWidget", "library": "material", "description": "A material design text field." }, { "name": "TextFormField", "parent": "FormField", "library": "material", "description": "A [FormField] that contains a [TextField]." }, { "name": "TextSelectionGestureDetector", "parent": "StatefulWidget", "library": "widgets", "description": "A gesture detector to respond to non-exclusive event chains for a text field." }, { "name": "TextSelectionTheme", "parent": "InheritedTheme", "library": "material", "description": "An inherited widget that defines the appearance of text selection in this widget's subtree." }, { "name": "TextSelectionToolbar", "parent": "StatelessWidget", "library": "material", "description": "A fully-functional Material-style text selection toolbar." }, { "name": "TextSelectionToolbarTextButton", "parent": "StatelessWidget", "library": "material", "description": "A button styled like a Material native Android text selection menu button." }, { "name": "Texture", "parent": "LeafRenderObjectWidget", "library": "widgets", "description": "A rectangle upon which a backend texture is mapped." }, { "name": "Theme", "parent": "StatelessWidget", "library": "material", "description": "Applies a theme to descendant widgets." }, { "name": "TickerMode", "parent": "StatefulWidget", "library": "widgets", "description": "Enables or disables tickers (and thus animation controllers) in the widget subtree." }, { "name": "TimePickerDialog", "parent": "StatefulWidget", "library": "material", "description": "A material design time picker designed to appear inside a popup dialog." }, { "name": "TimePickerTheme", "parent": "InheritedTheme", "library": "material", "description": "An inherited widget that defines the configuration for time pickers displayed using [showTimePicker] in this widget's subtree." }, { "name": "Title", "parent": "StatelessWidget", "library": "widgets", "description": "A widget that describes this app in the operating system." }, { "name": "ToggleButtons", "parent": "StatelessWidget", "library": "material", "description": "A set of toggle buttons." }, { "name": "ToggleButtonsTheme", "parent": "InheritedTheme", "library": "material", "description": "An inherited widget that defines color and border parameters for [ToggleButtons] in this widget's subtree." }, { "name": "Tooltip", "parent": "StatefulWidget", "library": "material", "description": "A material design tooltip." }, { "name": "TooltipTheme", "parent": "InheritedTheme", "library": "material", "description": "An inherited widget that defines the configuration for [Tooltip]s in this widget's subtree." }, { "name": "TooltipVisibility", "parent": "StatelessWidget", "library": "material", "description": "Overrides the visibility of descendant [Tooltip] widgets." }, { "name": "Transform", "parent": "SingleChildRenderObjectWidget", "library": "widgets", "description": "A widget that applies a transformation before painting its child." }, { "name": "TweenAnimationBuilder", "parent": "ImplicitlyAnimatedWidget", "library": "widgets", "description": "[Widget] builder that animates a property of a [Widget] to a target value whenever the target value changes." }, { "name": "UiKitView", "parent": "StatefulWidget", "library": "widgets", "description": "Embeds an iOS view in the Widget hierarchy." }, { "name": "UnconstrainedBox", "parent": "StatelessWidget", "library": "widgets", "description": "A widget that imposes no constraints on its child, allowing it to render at its \"natural\" size." }, { "name": "UniqueWidget", "parent": "StatefulWidget", "library": "widgets", "abstract": true, "description": "Base class for stateful widgets that have exactly one inflated instance in the tree." }, { "name": "UnmanagedRestorationScope", "parent": "InheritedWidget", "library": "widgets", "description": "Inserts a provided [RestorationBucket] into the widget tree and makes it available to descendants via [RestorationScope.of]." }, { "name": "UserAccountsDrawerHeader", "parent": "StatefulWidget", "library": "material", "description": "A material design [Drawer] header that identifies the app's user." }, { "name": "ValueListenableBuilder", "parent": "StatefulWidget", "library": "widgets", "description": "A widget whose content stays synced with a [ValueListenable]." }, { "name": "VerticalDivider", "parent": "StatelessWidget", "library": "material", "description": "A thin vertical line, with padding on either side." }, { "name": "Viewport", "parent": "MultiChildRenderObjectWidget", "library": "widgets", "description": "A widget that is bigger on the inside." }, { "name": "Visibility", "parent": "StatelessWidget", "library": "widgets", "description": "Whether to show or hide a child." }, { "name": "WidgetInspector", "parent": "StatefulWidget", "library": "widgets", "description": "A widget that enables inspecting the child widget's structure." }, { "name": "WidgetToRenderBoxAdapter", "parent": "LeafRenderObjectWidget", "library": "widgets", "description": "An adapter for placing a specific [RenderBox] in the widget tree." }, { "name": "WidgetsApp", "parent": "StatefulWidget", "library": "widgets", "description": "A convenience widget that wraps a number of widgets that are commonly required for an application." }, { "name": "WillPopScope", "parent": "StatefulWidget", "library": "widgets", "description": "Registers a callback to veto attempts by the user to dismiss the enclosing [ModalRoute]." }, { "name": "Wrap", "parent": "MultiChildRenderObjectWidget", "library": "widgets", "description": "A widget that displays its children in multiple horizontal or vertical runs." }, { "name": "YearPicker", "parent": "StatefulWidget", "library": "material", "description": "A scrollable grid of years to allow picking a year." } ] }
flutter-intellij/resources/flutter/catalog/widgets.json/0
{ "file_path": "flutter-intellij/resources/flutter/catalog/widgets.json", "repo_id": "flutter-intellij", "token_count": 35251 }
533
#!/bin/bash source ./tool/kokoro/setup.sh setup echo "kokoro build start" ./bin/plugin make --channel=dev echo "kokoro build finished" echo "kokoro deploy start" ./bin/plugin deploy --channel=dev echo "kokoro deploy finished"
flutter-intellij/tool/kokoro/deploy.sh/0
{ "file_path": "flutter-intellij/tool/kokoro/deploy.sh", "repo_id": "flutter-intellij", "token_count": 77 }
534
<?xml version="1.0" encoding="UTF-8"?> <module type="WEB_MODULE" version="4"> <component name="NewModuleRootManager" inherit-compiler-output="true"> <exclude-output /> <content url="file://$MODULE_DIR$"> <sourceFolder url="file://$MODULE_DIR$/bin" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/lib" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" /> <excludeFolder url="file://$MODULE_DIR$/.dart_tool" /> <excludeFolder url="file://$MODULE_DIR$/.pub" /> <excludeFolder url="file://$MODULE_DIR$/build" /> </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="Dart SDK" level="project" /> <orderEntry type="library" name="Dart Packages" level="project" /> </component> </module>
flutter-intellij/tool/plugin/plugin.iml/0
{ "file_path": "flutter-intellij/tool/plugin/plugin.iml", "repo_id": "flutter-intellij", "token_count": 335 }
535
# Below is a list of Flutter team members' GitHub handles who are # test owners of this repository. # # These owners are mainly team leaders and their sub-teams. Please feel # free to claim ownership by adding your handle to corresponding tests. # # This file will be used as a reference when new flaky bugs are filed and # the TL will be assigned and the sub-team will be labeled by default # for further triage. ## Linux Android DeviceLab tests /dev/devicelab/bin/tasks/analyzer_benchmark.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/android_choreographer_do_frame_test.dart @reidbaker @flutter/engine /dev/devicelab/bin/tasks/android_defines_test.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/android_lifecycles_test.dart @reidbaker @flutter/engine /dev/devicelab/bin/tasks/android_obfuscate_test.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/android_picture_cache_complexity_scoring_perf__timeline_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/android_stack_size_test.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/android_view_scroll_perf__timeline_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/animated_complex_image_filtered_perf__e2e_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/animated_complex_opacity_perf__e2e_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/animated_image_gc_perf.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/animated_placeholder_perf__e2e_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/backdrop_filter_perf__e2e_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/basic_material_app_android__compile.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/clipper_cache_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/codegen_integration.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/color_filter_and_fade_perf__e2e_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/color_filter_cache_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/color_filter_with_unstable_child_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/complex_layout_android__compile.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/complex_layout_android__scroll_smoothness.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/complex_layout_scroll_perf__devtools_memory.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/complex_layout_semantics_perf.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/cubic_bezier_perf__e2e_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/cubic_bezier_perf_sksl_warmup__e2e_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/cull_opacity_perf__e2e_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/devtools_profile_start_test.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/engine_dependency_proxy_test.dart @godofredoc @flutter/engine /dev/devicelab/bin/tasks/fast_scroll_heavy_gridview__memory.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flutter_engine_group_performance.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flutter_gallery__back_button_memory.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flutter_gallery__image_cache_memory.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flutter_gallery__memory_nav.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flutter_gallery__start_up.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flutter_gallery__start_up_delayed.dart @dnfield @flutter/engine /dev/devicelab/bin/tasks/flutter_gallery__transition_perf.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flutter_gallery__transition_perf_e2e.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flutter_gallery__transition_perf_hybrid.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flutter_gallery__transition_perf_with_semantics.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flutter_gallery_android__compile.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/flutter_gallery_sksl_warmup__transition_perf.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flutter_gallery_sksl_warmup__transition_perf_e2e.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flutter_gallery_v2_chrome_run_test.dart @yjbanov @flutter/web /dev/devicelab/bin/tasks/flutter_gallery_v2_web_compile_test.dart @yjbanov @flutter/web /dev/devicelab/bin/tasks/flutter_test_performance.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/frame_policy_delay_test_android.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/fullscreen_textfield_perf.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/fullscreen_textfield_perf__e2e_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/gradient_consistent_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/gradient_dynamic_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/gradient_static_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/gradle_java8_compile_test.dart @reidbaker @flutter/tool /dev/devicelab/bin/tasks/hot_mode_dev_cycle_linux__benchmark.dart @christopherfujino @flutter/tool /dev/devicelab/bin/tasks/image_list_jit_reported_duration.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/image_list_reported_duration.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/large_image_changer_perf_android.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/linux_chrome_dev_mode.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/list_text_layout_impeller_perf__e2e_summary.dart @dnfield @flutter/engine /dev/devicelab/bin/tasks/list_text_layout_perf__e2e_summary.dart @dnfield @flutter/engine /dev/devicelab/bin/tasks/multi_widget_construction_perf__e2e_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/new_gallery__crane_perf.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/old_gallery__transition_perf.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/opacity_peephole_col_of_alpha_savelayer_rows_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/opacity_peephole_col_of_rows_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/opacity_peephole_fade_transition_text_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/opacity_peephole_grid_of_alpha_savelayers_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/opacity_peephole_grid_of_opacity_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/opacity_peephole_one_rect_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/opacity_peephole_opacity_of_grid_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/picture_cache_perf__e2e_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/platform_channels_benchmarks.dart @gaaclarke @flutter/engine /dev/devicelab/bin/tasks/platform_views_scroll_perf__timeline_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/platform_views_scroll_perf_impeller__timeline_summary.dart @bdero @flutter/engine /dev/devicelab/bin/tasks/plugin_dependencies_test.dart @stuartmorgan @flutter/tool /dev/devicelab/bin/tasks/raster_cache_use_memory_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/routing_test.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/shader_mask_cache_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/spell_check_test_ios.dart @camsim99 @flutter/android /dev/devicelab/bin/tasks/spell_check_test.dart @camsim99 @flutter/android /dev/devicelab/bin/tasks/textfield_perf__e2e_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/very_long_picture_scrolling_perf__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/web_size__compile_test.dart @yjbanov @flutter/web /dev/devicelab/bin/tasks/wide_gamut_ios.dart @gaaclarke @flutter/engine /dev/devicelab/bin/tasks/animated_advanced_blend_perf__timeline_summary.dart @gaaclarke @flutter/engine /dev/devicelab/bin/tasks/animated_advanced_blend_perf_ios__timeline_summary.dart @gaaclarke @flutter/engine /dev/devicelab/bin/tasks/animated_advanced_blend_perf_opengles__timeline_summary.dart @gaaclarke @flutter/engine /dev/devicelab/bin/tasks/animated_blur_backdrop_filter_perf__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/animated_blur_backdrop_filter_perf_opengles__timeline_summary.dart @gaaclarke @flutter/engine /dev/devicelab/bin/tasks/slider_perf_android.dart @tahatesser @flutter/framework /dev/devicelab/bin/tasks/draw_vertices_perf_opengles__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/draw_atlas_perf_opengles__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/draw_vertices_perf__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/draw_atlas_perf__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/static_path_tessellation_perf__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/dynamic_path_tessellation_perf__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/complex_layout_scroll_perf_impeller__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/complex_layout_scroll_perf_impeller_gles__timeline_summary.dart @jonahwilliams @flutter/engine ## Windows Android DeviceLab tests /dev/devicelab/bin/tasks/basic_material_app_win__compile.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/channels_integration_test_win.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/complex_layout_win__compile.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/flavors_test_win.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/flutter_gallery_win__compile.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/hot_mode_dev_cycle_win__benchmark.dart @andrewkolos @flutter/tool /dev/devicelab/bin/tasks/windows_chrome_dev_mode.dart @yjbanov @flutter/web ## Mac Android DeviceLab tests /dev/devicelab/bin/tasks/android_semantics_integration_test.dart @HansMuller @flutter/framework /dev/devicelab/bin/tasks/backdrop_filter_perf__timeline_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/channels_integration_test.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/color_filter_and_fade_perf__timeline_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/complex_layout__start_up.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/complex_layout_scroll_perf__memory.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/complex_layout_scroll_perf__timeline_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/cubic_bezier_perf__timeline_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/cubic_bezier_perf_sksl_warmup__timeline_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/cull_opacity_perf__timeline_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/drive_perf_debug_warning.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/embedded_android_views_integration_test.dart @stuartmorgan @flutter/plugin /dev/devicelab/bin/tasks/external_textures_integration_test.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/fading_child_animation_perf__timeline_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/fast_scroll_large_images__memory.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flavors_test.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/flutter_view__start_up.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/fullscreen_textfield_perf__timeline_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/hello_world__memory.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/hello_world_android__compile.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/hello_world_impeller.dart @gaaclarke @flutter/engine /dev/devicelab/bin/tasks/home_scroll_perf__timeline_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/hot_mode_dev_cycle__benchmark.dart @eliasyishak @flutter/tool /dev/devicelab/bin/tasks/hybrid_android_views_integration_test.dart @stuartmorgan @flutter/plugin /dev/devicelab/bin/tasks/imagefiltered_transform_animation_perf__timeline_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/integration_test_test.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/integration_ui_driver.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/integration_ui_frame_number.dart @dnfield @flutter/engine /dev/devicelab/bin/tasks/integration_ui_keyboard_resize.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/integration_ui_screenshot.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/integration_ui_textfield.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/microbenchmarks.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/new_gallery__transition_perf.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/new_gallery_impeller__transition_perf.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/new_gallery_impeller_old_zoom__transition_perf.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/new_gallery_opengles_impeller__transition_perf.dart @gaaclarke @flutter/engine /dev/devicelab/bin/tasks/picture_cache_perf__timeline_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/platform_channel_sample_test.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/platform_interaction_test.dart @stuartmorgan @flutter/plugin /dev/devicelab/bin/tasks/platform_view__start_up.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/run_release_test.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/service_extensions_test.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/textfield_perf__timeline_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/tiles_scroll_perf__timeline_summary.dart @zanderso @flutter/engine ## Mac iOS DeviceLab tests /dev/devicelab/bin/tasks/animated_complex_opacity_perf_ios__e2e_summary.dart @hellohuanlin @flutter/engine /dev/devicelab/bin/tasks/animation_with_microtasks_perf_ios__timeline_summary.dart @dnfield @flutter/engine /dev/devicelab/bin/tasks/backdrop_filter_perf_ios__timeline_summary.dart @hellohuanlin @flutter/engine /dev/devicelab/bin/tasks/basic_material_app_ios__compile.dart @jmagman @flutter/tool /dev/devicelab/bin/tasks/channels_integration_test_ios.dart @jmagman @flutter/engine /dev/devicelab/bin/tasks/codegen_integration_mac.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/color_filter_and_fade_perf_ios__e2e_summary.dart @hellohuanlin @flutter/engine /dev/devicelab/bin/tasks/complex_layout_ios__start_up.dart @vashworth @flutter/engine /dev/devicelab/bin/tasks/complex_layout_scroll_perf_bad_ios__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/complex_layout_scroll_perf_ios__timeline_summary.dart @hellohuanlin @flutter/engine /dev/devicelab/bin/tasks/cubic_bezier_perf_ios_sksl_warmup__timeline_summary.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/external_textures_integration_test_ios.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flavors_test_ios.dart @jmagman @flutter/tool /dev/devicelab/bin/tasks/flutter_gallery__transition_perf_e2e_ios.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flutter_gallery_ios__compile.dart @jmagman @flutter/engine /dev/devicelab/bin/tasks/flutter_gallery_ios__start_up.dart @vashworth @flutter/engine /dev/devicelab/bin/tasks/flutter_gallery_ios_sksl_warmup__transition_perf.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/flutter_view_ios__start_up.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/fullscreen_textfield_perf_ios__e2e_summary.dart @vashworth @flutter/engine /dev/devicelab/bin/tasks/hello_world_ios__compile.dart @jmagman @flutter/engine /dev/devicelab/bin/tasks/hot_mode_dev_cycle_ios__benchmark.dart @vashworth @flutter/tool # TODO(vashworth): Remove once https://github.com/flutter/flutter/issues/142305 is fixed. /dev/devicelab/bin/tasks/hot_mode_dev_cycle_ios__benchmark_no_dds.dart @vashworth @flutter/tool /dev/devicelab/bin/tasks/imagefiltered_transform_animation_perf_ios__timeline_summary.dart @hellohuanlin @flutter/engine /dev/devicelab/bin/tasks/integration_test_test_ios.dart @jmagman @flutter/engine /dev/devicelab/bin/tasks/integration_ui_ios_driver.dart @vashworth @flutter/tool /dev/devicelab/bin/tasks/integration_ui_ios_frame_number.dart @dnfield @flutter/engine /dev/devicelab/bin/tasks/integration_ui_ios_keyboard_resize.dart @vashworth @flutter/engine /dev/devicelab/bin/tasks/integration_ui_ios_screenshot.dart @vashworth @flutter/tool /dev/devicelab/bin/tasks/integration_ui_ios_textfield.dart @vashworth @flutter/tool /dev/devicelab/bin/tasks/ios_app_with_extensions_test.dart @jmagman @flutter/tool /dev/devicelab/bin/tasks/ios_defines_test.dart @jmagman @flutter/tool /dev/devicelab/bin/tasks/ios_picture_cache_complexity_scoring_perf__timeline_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/ios_platform_view_tests.dart @stuartmorgan @flutter/plugin /dev/devicelab/bin/tasks/large_image_changer_perf_ios.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/microbenchmarks_ios.dart @vashworth @flutter/engine /dev/devicelab/bin/tasks/native_assets_android.dart @dacoharkes @flutter/android /dev/devicelab/bin/tasks/native_assets_ios.dart @dacoharkes @flutter/ios /dev/devicelab/bin/tasks/native_platform_view_ui_tests_ios.dart @hellohuanlin @flutter/ios /dev/devicelab/bin/tasks/new_gallery_ios__transition_perf.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/new_gallery_skia_ios__transition_perf.dart @zanderso @flutter/engine /dev/devicelab/bin/tasks/platform_channel_sample_test_ios.dart @hellohuanlin @flutter/engine /dev/devicelab/bin/tasks/platform_channel_sample_test_swift.dart @hellohuanlin @flutter/engine /dev/devicelab/bin/tasks/platform_channels_benchmarks_ios.dart @gaaclarke @flutter/engine /dev/devicelab/bin/tasks/platform_interaction_test_ios.dart @hellohuanlin @flutter/engine /dev/devicelab/bin/tasks/platform_view_ios__start_up.dart @stuartmorgan @flutter/plugin /dev/devicelab/bin/tasks/platform_views_scroll_perf_ad_banners__timeline_summary.dart @hellohuanlin @flutter/engine /dev/devicelab/bin/tasks/platform_views_scroll_perf_ios__timeline_summary.dart @hellohuanlin @flutter/engine /dev/devicelab/bin/tasks/platform_views_scroll_perf_non_intersecting_impeller_ios__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/post_backdrop_filter_perf_ios__timeline_summary.dart @hellohuanlin @flutter/engine /dev/devicelab/bin/tasks/route_test_ios.dart @jmagman @flutter/tool /dev/devicelab/bin/tasks/simple_animation_perf_ios.dart @hellohuanlin @flutter/engine /dev/devicelab/bin/tasks/tiles_scroll_perf_ios__timeline_summary.dart @hellohuanlin @flutter/engine /dev/devicelab/bin/tasks/very_long_picture_scrolling_perf_ios__e2e_summary.dart @flar @flutter/engine /dev/devicelab/bin/tasks/animated_blur_backdrop_filter_perf_ios__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/draw_points_perf_ios__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/draw_vertices_perf_ios__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/draw_atlas_perf_ios__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/static_path_tessellation_perf_ios__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/dynamic_path_tessellation_perf_ios__timeline_summary.dart @jonahwilliams @flutter/engine ## Host only DeviceLab tests /dev/devicelab/bin/tasks/animated_complex_opacity_perf_macos__e2e_summary.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/basic_material_app_macos__compile.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/build_aar_module_test.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/build_ios_framework_module_test.dart @jmagman @flutter/tool /dev/devicelab/bin/tasks/channels_integration_test_macos.dart @gaaclarke @flutter/desktop /dev/devicelab/bin/tasks/complex_layout_macos__compile.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/complex_layout_macos__start_up.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/complex_layout_scroll_perf_macos__timeline_summary.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/complex_layout_win_desktop__compile.dart @yaakovschectman @flutter/desktop /dev/devicelab/bin/tasks/complex_layout_win_desktop__start_up.dart @yaakovschectman @flutter/desktop /dev/devicelab/bin/tasks/dart_plugin_registry_test.dart @stuartmorgan @flutter/plugin /dev/devicelab/bin/tasks/entrypoint_dart_registrant.dart @aaclarke @flutter/plugin /dev/devicelab/bin/tasks/flavors_test_macos.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/flutter_gallery_macos__compile.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/flutter_gallery_macos__start_up.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/flutter_gallery_win_desktop__compile.dart @yaakovschectman @flutter/desktop /dev/devicelab/bin/tasks/flutter_gallery_win_desktop__start_up.dart @yaakovschectman @flutter/desktop /dev/devicelab/bin/tasks/flutter_tool_startup.dart @jensjoha @flutter/tool /dev/devicelab/bin/tasks/flutter_tool_startup__linux.dart @jensjoha @flutter/tool /dev/devicelab/bin/tasks/flutter_tool_startup__macos.dart @jensjoha @flutter/tool /dev/devicelab/bin/tasks/flutter_tool_startup__windows.dart @jensjoha @flutter/tool /dev/devicelab/bin/tasks/flutter_view_macos__start_up.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/flutter_view_win_desktop__start_up.dart @yaakovschectman @flutter/desktop /dev/devicelab/bin/tasks/gradle_desugar_classes_test.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/gradle_plugin_bundle_test.dart @stuartmorgan @flutter/plugin /dev/devicelab/bin/tasks/gradle_plugin_fat_apk_test.dart @stuartmorgan @flutter/plugin /dev/devicelab/bin/tasks/gradle_plugin_light_apk_test.dart @stuartmorgan @flutter/plugin /dev/devicelab/bin/tasks/hello_world_macos__compile.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/hello_world_win_desktop__compile.dart @yaakovschectman @flutter/desktop /dev/devicelab/bin/tasks/hot_mode_dev_cycle_ios_simulator.dart @vashworth @flutter/tool /dev/devicelab/bin/tasks/hot_mode_dev_cycle_macos_target__benchmark.dart @cbracken @flutter/tool /dev/devicelab/bin/tasks/hot_mode_dev_cycle_win_target__benchmark.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/integration_ui_test_test_macos.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/macos_chrome_dev_mode.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/module_custom_host_app_name_test.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/module_host_with_custom_build_test.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/module_test.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/module_test_ios.dart @jmagman @flutter/tool /dev/devicelab/bin/tasks/native_assets_ios_simulator.dart @dacoharkes @flutter/ios /dev/devicelab/bin/tasks/native_ui_tests_macos.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/platform_channel_sample_test_macos.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/platform_channel_sample_test_windows.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/platform_view_macos__start_up.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/platform_view_win_desktop__start_up.dart @yaakovschectman @flutter/desktop /dev/devicelab/bin/tasks/plugin_lint_mac.dart @stuartmorgan @flutter/plugin /dev/devicelab/bin/tasks/plugin_test.dart @stuartmorgan @flutter/plugin /dev/devicelab/bin/tasks/plugin_test_ios.dart @stuartmorgan @flutter/ios /dev/devicelab/bin/tasks/plugin_test_linux.dart @stuartmorgan @flutter/desktop /dev/devicelab/bin/tasks/plugin_test_macos.dart @cbracken @flutter/desktop /dev/devicelab/bin/tasks/plugin_test_windows.dart @loic-sharma @flutter/desktop /dev/devicelab/bin/tasks/run_debug_test_android.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/run_debug_test_android.dart @zanderso @flutter/tool /dev/devicelab/bin/tasks/run_debug_test_linux.dart @loic-sharma @flutter/tool /dev/devicelab/bin/tasks/run_debug_test_macos.dart @cbracken @flutter/tool /dev/devicelab/bin/tasks/run_debug_test_windows.dart @loic-sharma @flutter/tool /dev/devicelab/bin/tasks/run_release_test_linux.dart @loic-sharma @flutter/tool /dev/devicelab/bin/tasks/run_release_test_macos.dart @cbracken @flutter/tool /dev/devicelab/bin/tasks/run_release_test_windows.dart @loic-sharma @flutter/tool /dev/devicelab/bin/tasks/technical_debt__cost.dart @HansMuller @flutter/framework /dev/devicelab/bin/tasks/web_benchmarks_canvaskit.dart @yjbanov @flutter/web /dev/devicelab/bin/tasks/web_benchmarks_html.dart @yjbanov @flutter/web /dev/devicelab/bin/tasks/web_benchmarks_skwasm.dart @jacksongardner @flutter/web /dev/devicelab/bin/tasks/windows_home_scroll_perf__timeline_summary.dart @jonahwilliams @flutter/engine /dev/devicelab/bin/tasks/windows_startup_test.dart @loic-sharma @flutter/desktop ## Host only framework tests # Linux docs_deploy_beta # Linux docs_deploy_stable # Linux docs_publish /dev/bots/docs.sh @HansMuller @flutter/framework # Linux packages_autoroller /dev/conductor/core @christopherfujino @flutter/tool # Linux web_e2e_test /dev/integration_tests/web_e2e_tests @yjbanov @flutter/web # Linux web_smoke_test /examples/hello_world/test_driver/smoke_web_engine.dart @yjbanov @flutter/web # Linux android views /dev/integration_tests/android_views @gmackall @flutter/android # Linux deferred components /dev/integration_tests/deferred_components_test @gmackall @flutter/android ## Firebase tests /dev/integration_tests/abstract_method_smoke_test @reidbaker @flutter/android /dev/integration_tests/android_embedding_v2_smoke_test @reidbaker @flutter/android /dev/integration_tests/release_smoke_test @reidbaker @flutter/android ## Shards tests # TODO(keyonghan): add files/paths for below framework host only testss. # https://github.com/flutter/flutter/issues/82068 # # analyze @HansMuller @flutter/framework # build_tests @eliasyishak @flutter/tool # ci_yaml flutter roller @caseyhillers @flutter/infra # coverage @godofredoc @flutter/infra # customer_testing @HansMuller @flutter/framework # docs @HansMuller @flutter/framework # flutter_packaging @godofredoc @flutter/infra # flutter_plugins @stuartmorgan @flutter/plugin # framework_tests @HansMuller @flutter/framework # fuchsia_precache @christopherfujino @flutter/tool # realm_checker @jacksongardner @flutter/tool # skp_generator @Hixie # test_ownership @keyonghan # tool_host_cross_arch_tests @andrewkolos @flutter/tool # tool_integration_tests @christopherfujino @flutter/tool # tool_tests @andrewkolos @flutter/tool # verify_binaries_codesigned @xilaizhang @flutter/releases # web_canvaskit_tests @yjbanov @flutter/web # web_integration_tests @yjbanov @flutter/web # web_long_running_tests @yjbanov @flutter/web # web_tests @yjbanov @flutter/web # web_tool_tests @eliasyishak @flutter/tool
flutter/TESTOWNERS/0
{ "file_path": "flutter/TESTOWNERS", "repo_id": "flutter", "token_count": 11136 }
536
2ba8188ed97d8b05670845e5b5954e2fe0f54784
flutter/bin/internal/libimobiledevice.version/0
{ "file_path": "flutter/bin/internal/libimobiledevice.version", "repo_id": "flutter", "token_count": 27 }
537
// Copyright 2014 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 'use_cases.dart'; class DialogUseCase extends UseCase { @override String get name => 'Dialog'; @override String get route => '/dialog'; @override Widget build(BuildContext context) => const _MainWidget(); } class _MainWidget extends StatelessWidget { const _MainWidget(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: const Text('Dialog'), ), body: Center( child: TextButton( onPressed: () => showDialog<String>( context: context, builder: (BuildContext context) => Dialog( child: Padding( padding: const EdgeInsets.all(8.0), child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text('This is a typical dialog.'), const SizedBox(height: 15), Row( children: <Widget>[ TextButton( onPressed: () { Navigator.pop(context); }, child: const Text('OK'), ), TextButton( onPressed: () { Navigator.pop(context); }, child: const Text('Cancel'), ), ], ), ], ), ), ), ), child: const Text('Show Dialog'), ), ), ); } }
flutter/dev/a11y_assessments/lib/use_cases/dialog.dart/0
{ "file_path": "flutter/dev/a11y_assessments/lib/use_cases/dialog.dart", "repo_id": "flutter", "token_count": 1098 }
538
#include "ephemeral/Flutter-Generated.xcconfig"
flutter/dev/a11y_assessments/macos/Flutter/Flutter-Debug.xcconfig/0
{ "file_path": "flutter/dev/a11y_assessments/macos/Flutter/Flutter-Debug.xcconfig", "repo_id": "flutter", "token_count": 19 }
539
// Copyright 2014 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:a11y_assessments/use_cases/dialog.dart'; import 'package:flutter_test/flutter_test.dart'; import 'test_utils.dart'; void main() { testWidgets('dialog can run', (WidgetTester tester) async { await pumpsUseCase(tester, DialogUseCase()); expect(find.text('Show Dialog'), findsOneWidget); Future<void> invokeDialog() async { await tester.tap(find.text('Show Dialog')); await tester.pumpAndSettle(); expect(find.text('This is a typical dialog.'), findsOneWidget); } await invokeDialog(); await tester.tap(find.text('OK')); await tester.pumpAndSettle(); expect(find.text('This is a typical dialog.'), findsNothing); await invokeDialog(); await tester.tap(find.text('Cancel')); await tester.pumpAndSettle(); expect(find.text('This is a typical dialog.'), findsNothing); }); }
flutter/dev/a11y_assessments/test/dialog_test.dart/0
{ "file_path": "flutter/dev/a11y_assessments/test/dialog_test.dart", "repo_id": "flutter", "token_count": 358 }
540
This is a fake package for use by automated testing. For example, the `flutter_tools` package uses this to test `flutter test`.
flutter/dev/automated_tests/README.md/0
{ "file_path": "flutter/dev/automated_tests/README.md", "repo_id": "flutter", "token_count": 33 }
541
// Copyright 2014 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 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Rendering Error', (WidgetTester tester) async { // This should fail with user created widget = Row. await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( appBar: AppBar( title: const Text('RenderFlex OverFlow'), ), body: const SizedBox( width: 400.0, child: Row( children: <Widget>[ Icon(Icons.message), Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('Title'), Text( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed ' 'do eiusmod tempor incididunt ut labore et dolore magna ' 'aliqua. Ut enim ad minim veniam, quis nostrud ' 'exercitation ullamco laboris nisi ut aliquip ex ea ' 'commodo consequat.' ), ], ), ], ), ), ), ) ); }); }
flutter/dev/automated_tests/flutter_test/print_correct_local_widget_test.dart/0
{ "file_path": "flutter/dev/automated_tests/flutter_test/print_correct_local_widget_test.dart", "repo_id": "flutter", "token_count": 783 }
542
// Copyright 2014 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. // this is a test to make sure our tests consider syntax errors to be failures // see //flutter/dev/bots/test.dart The challenge: demand satisfaction If they apologize, no need for further action.
flutter/dev/automated_tests/test_smoke_test/syntax_error_test.broken_dart/0
{ "file_path": "flutter/dev/automated_tests/test_smoke_test/syntax_error_test.broken_dart", "repo_id": "flutter", "token_count": 92 }
543
{ "images":[ { "idiom":"iphone", "size":"29x29", "scale":"1x", "filename":"[email protected]" }, { "idiom":"iphone", "size":"29x29", "scale":"2x", "filename":"[email protected]" }, { "idiom":"iphone", "size":"29x29", "scale":"3x", "filename":"[email protected]" }, { "idiom":"iphone", "size":"40x40", "scale":"1x", "filename":"[email protected]" }, { "idiom":"iphone", "size":"40x40", "scale":"2x", "filename":"[email protected]" }, { "idiom":"iphone", "size":"40x40", "scale":"3x", "filename":"[email protected]" }, { "idiom":"iphone", "size":"60x60", "scale":"1x", "filename":"[email protected]" }, { "idiom":"iphone", "size":"60x60", "scale":"2x", "filename":"[email protected]" }, { "idiom":"iphone", "size":"60x60", "scale":"3x", "filename":"[email protected]" }, { "idiom":"ipad", "size":"29x29", "scale":"1x", "filename":"[email protected]" }, { "idiom":"ipad", "size":"29x29", "scale":"2x", "filename":"[email protected]" }, { "idiom":"ipad", "size":"40x40", "scale":"1x", "filename":"[email protected]" }, { "idiom":"ipad", "size":"40x40", "scale":"2x", "filename":"[email protected]" }, { "idiom":"ipad", "size":"76x76", "scale":"1x", "filename":"[email protected]" }, { "idiom":"ipad", "size":"76x76", "scale":"2x", "filename":"[email protected]" }, { "idiom":"ipad", "size":"76x76", "scale":"3x", "filename":"[email protected]" }, { "idiom":"ipad", "size":"83.5x83.5", "scale":"2x", "filename":"[email protected]" } ], "info":{ "version":1, "author":"makeappicon" } }
flutter/dev/benchmarks/complex_layout/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json/0
{ "file_path": "flutter/dev/benchmarks/complex_layout/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json", "repo_id": "flutter", "token_count": 1799 }
544
// Copyright 2014 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:ui' as ui; import 'package:flutter/material.dart'; // This tests whether the Opacity layer raster cache works with color filters. // See https://github.com/flutter/flutter/issues/51975. class ColorFilterAndFadePage extends StatefulWidget { const ColorFilterAndFadePage({super.key}); @override State<ColorFilterAndFadePage> createState() => _ColorFilterAndFadePageState(); } class _ColorFilterAndFadePageState extends State<ColorFilterAndFadePage> with TickerProviderStateMixin { @override Widget build(BuildContext context) { final Widget shadowWidget = _ShadowWidget( width: 24, height: 24, useColorFilter: _useColorFilter, shadow: const ui.Shadow( color: Colors.black45, offset: Offset(0.0, 2.0), blurRadius: 4.0, ), ); final Widget row = Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ shadowWidget, const SizedBox(width: 12), shadowWidget, const SizedBox(width: 12), shadowWidget, const SizedBox(width: 12), shadowWidget, const SizedBox(width: 12), shadowWidget, const SizedBox(width: 12), ], ); final Widget column = Column(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ row, const SizedBox(height: 12), row, const SizedBox(height: 12), row, const SizedBox(height: 12), row, const SizedBox(height: 12), ], ); final Widget fadeTransition = FadeTransition( opacity: _opacityAnimation, // This RepaintBoundary is necessary to not let the opacity change // invalidate the layer raster cache below. This is necessary with // or without the color filter. child: RepaintBoundary( child: column, ), ); return Scaffold( backgroundColor: Colors.lightBlue, body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ fadeTransition, Container(height: 20), const Text('Use Color Filter:'), Checkbox( value: _useColorFilter, onChanged: (bool? value) { setState(() { _useColorFilter = value ?? false; }); }, ), ], ), ), ); } // Create a looping fade-in fade-out animation for opacity. void _initAnimation() { _controller = AnimationController(duration: const Duration(seconds: 3), vsync: this); _opacityAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(_controller); _opacityAnimation.addStatusListener((AnimationStatus status) { if (status == AnimationStatus.completed) { _controller.reverse(); } else if (status == AnimationStatus.dismissed) { _controller.forward(); } }); _controller.forward(); } @override void initState() { super.initState(); _initAnimation(); } @override void dispose() { _controller.dispose(); super.dispose(); } late AnimationController _controller; late Animation<double> _opacityAnimation; bool _useColorFilter = true; } class _ShadowWidget extends StatelessWidget { const _ShadowWidget({ required this.width, required this.height, required this.useColorFilter, required this.shadow, }); final double width; final double height; final bool useColorFilter; final Shadow shadow; @override Widget build(BuildContext context) { return SizedBox( width: width, height: height, child: CustomPaint( painter: _ShadowPainter( useColorFilter: useColorFilter, shadow: shadow, ), size: Size(width, height), isComplex: true, ), ); } } class _ShadowPainter extends CustomPainter { const _ShadowPainter({required this.useColorFilter, required this.shadow}); final bool useColorFilter; final Shadow shadow; @override void paint(Canvas canvas, Size size) { final Rect rect = Offset.zero & size; final Paint paint = Paint(); if (useColorFilter) { paint.colorFilter = ColorFilter.mode(shadow.color, BlendMode.srcIn); } canvas.saveLayer(null, paint); canvas.translate(shadow.offset.dx, shadow.offset.dy); canvas.drawRect(rect, Paint()); canvas.drawRect(rect, Paint()..maskFilter = MaskFilter.blur(BlurStyle.normal, shadow.blurSigma)); canvas.restore(); canvas.drawRect(rect, Paint()..color = useColorFilter ? Colors.white : Colors.black); } @override bool shouldRepaint(_ShadowPainter oldDelegate) => oldDelegate.useColorFilter != useColorFilter; }
flutter/dev/benchmarks/macrobenchmarks/lib/src/color_filter_and_fade.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/color_filter_and_fade.dart", "repo_id": "flutter", "token_count": 2033 }
545
// Copyright 2014 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:math'; import 'package:flutter/material.dart'; import '../common.dart'; // Various tests to verify that the opacity layer propagates the opacity to various // combinations of children that can apply it themselves. // See https://github.com/flutter/flutter/issues/75697 class OpacityPeepholePage extends StatelessWidget { const OpacityPeepholePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Opacity Peephole tests')), body: ListView( key: const Key(kOpacityScrollableName), children: <Widget>[ for (final OpacityPeepholeCase variant in allOpacityPeepholeCases) ElevatedButton( key: Key(variant.route), child: Text(variant.name), onPressed: () { Navigator.pushNamed(context, variant.route); }, ), ], ), ); } } typedef ValueBuilder = Widget Function(double v); typedef AnimationBuilder = Widget Function(Animation<double> animation); double _opacity(double v) => v * 0.5 + 0.25; int _red(double v) => (v * 255).round(); int _green(double v) => _red(1 - v); int _blue(double v) => 0; class OpacityPeepholeCase { OpacityPeepholeCase.forValue({required String route, required String name, required ValueBuilder builder}) : this.forAnimation( route: route, name: name, builder: (Animation<double> animation) => AnimatedBuilder( animation: animation, builder: (BuildContext context, Widget? child) => builder(animation.value), ), ); OpacityPeepholeCase.forAnimation({required this.route, required this.name, required AnimationBuilder builder}) : animationBuilder = builder; final String route; final String name; final AnimationBuilder animationBuilder; Widget buildPage(BuildContext context) { return VariantPage(variant: this); } } List<OpacityPeepholeCase> allOpacityPeepholeCases = <OpacityPeepholeCase>[ // Tests that Opacity can hand down value to a simple child OpacityPeepholeCase.forValue( route: kOpacityPeepholeOneRectRouteName, name: 'One Big Rectangle', builder: (double v) { return Opacity( opacity: _opacity(v), child: Container( width: 300, height: 400, color: Color.fromARGB(255, _red(v), _green(v), _blue(v)), ), ); } ), // Tests that a column of Opacity widgets can individually hand their values down to simple children OpacityPeepholeCase.forValue( route: kOpacityPeepholeColumnOfOpacityRouteName, name: 'Column of Opacity', builder: (double v) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ for (int i = 0; i < 10; i++, v = 1 - v) Opacity( opacity: _opacity(v), child: Padding( padding: const EdgeInsets.all(5), child: Container( width: 300, height: 30, color: Color.fromARGB(255, _red(v), _green(v), _blue(v)), ), ), ), ], ); }, ), // Tests that an Opacity can hand value down to a cached child OpacityPeepholeCase.forValue( route: kOpacityPeepholeOpacityOfCachedChildRouteName, name: 'Opacity of Cached Child', builder: (double v) { // ChildV starts as a constant so the same color pattern always appears and the child will be cached double childV = 0; return Opacity( opacity: _opacity(v), child: RepaintBoundary( child: SizedBox( width: 300, height: 400, child: Stack( children: <Widget>[ for (double i = 0; i < 100; i += 10, childV = 1 - childV) Positioned.fromRelativeRect( rect: RelativeRect.fromLTRB(i, i, i, i), child: Container( color: Color.fromARGB(255, _red(childV), _green(childV), _blue(childV)), ), ), ], ), ), ), ); } ), // Tests that an Opacity can hand a value down to a Column of simple non-overlapping children OpacityPeepholeCase.forValue( route: kOpacityPeepholeOpacityOfColumnRouteName, name: 'Opacity of Column', builder: (double v) { return Opacity( opacity: _opacity(v), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ for (int i = 0; i < 10; i++, v = 1 - v) Padding( padding: const EdgeInsets.all(5), // RepaintBoundary here to avoid combining children into 1 big Picture child: RepaintBoundary( child: Container( width: 300, height: 30, color: Color.fromARGB(255, _red(v), _green(v), _blue(v)), ), ), ), ], ), ); }, ), // Tests that an entire grid of Opacity objects can hand their values down to their simple children OpacityPeepholeCase.forValue( route: kOpacityPeepholeGridOfOpacityRouteName, name: 'Grid of Opacity', builder: (double v) { double rowV = v; double colV = rowV; return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ for (int i = 0; i < 10; i++, rowV = 1 - rowV, colV = rowV) Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ for (int j = 0; j < 7; j++, colV = 1 - colV) Opacity( opacity: _opacity(colV), child: Padding( padding: const EdgeInsets.all(5), child: Container( width: 30, height: 30, color: Color.fromARGB(255, _red(colV), _green(colV), _blue(colV)), ), ), ), ], ), ], ); }, ), // tests if an Opacity can hand its value down to a 2D grid of simple non-overlapping children. // The success of this case would depend on the sophistication of the non-overlapping tests. OpacityPeepholeCase.forValue( route: kOpacityPeepholeOpacityOfGridRouteName, name: 'Opacity of Grid', builder: (double v) { double rowV = v; double colV = rowV; return Opacity( opacity: _opacity(v), child: SizedBox( width: 300, height: 400, child: Stack( children: <Widget>[ for (int i = 0; i < 10; i++, rowV = 1 - rowV, colV = rowV) for (int j = 0; j < 7; j++, colV = 1 - colV) Positioned.fromRect( rect: Rect.fromLTWH(j * 40 + 5, i * 40 + 5, 30, 30), // RepaintBoundary here to avoid combining the 70 children into a single Picture child: RepaintBoundary( child: Container( color: Color.fromARGB(255, _red(colV), _green(colV), _blue(colV)), ), ), ), ], ), ), ); }, ), // tests if an Opacity can hand its value down to a Column of non-overlapping rows of non-overlapping simple children. // This test only requires linear non-overlapping tests to succeed. OpacityPeepholeCase.forValue( route: kOpacityPeepholeOpacityOfColOfRowsRouteName, name: 'Opacity of Column of Rows', builder: (double v) { double rowV = v; double colV = v; return Opacity( opacity: _opacity(v), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ for (int i = 0; i < 10; i++, rowV = 1 - rowV, colV = rowV) Padding( padding: const EdgeInsets.only(top: 5, bottom: 5), // RepaintBoundary here to separate each row into a separate layer child child: RepaintBoundary( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ for (int j = 0; j < 7; j++, colV = 1 - colV) Padding( padding: const EdgeInsets.only(left: 5, right: 5), // RepaintBoundary here to prevent the row children combining into a single Picture child: RepaintBoundary( child: Container( width: 30, height: 30, color: Color.fromARGB(255, _red(colV), _green(colV), _blue(colV)), ), ), ), ], ), ), ), ], ), ); }, ), OpacityPeepholeCase.forAnimation( route: kOpacityPeepholeFadeTransitionTextRouteName, name: 'FadeTransition text', builder: (Animation<double> animation) { return FadeTransition( opacity: Tween<double>(begin: 0.25, end: 0.75).animate(animation), child: const SizedBox( width: 300, height: 400, child: Center( child: Text('Hello, World', style: TextStyle(fontSize: 48), ), ), ), ); }, ), OpacityPeepholeCase.forValue( route: kOpacityPeepholeGridOfRectsWithAlphaRouteName, name: 'Grid of Rectangles with alpha', builder: (double v) { return Opacity( opacity: _opacity(v), child: SizedBox.expand( child: CustomPaint( painter: RectGridPainter((Canvas canvas, Size size) { const int numRows = 10; const int numCols = 7; const double rectWidth = 30; const double rectHeight = 30; final double hGap = (size.width - numCols * rectWidth) / (numCols + 1); final double vGap = (size.height - numRows * rectHeight) / (numRows + 1); final double gap = min(hGap, vGap); final double xOffset = (size.width - (numCols * (rectWidth + gap) - gap)) * 0.5; final double yOffset = (size.height - (numRows * (rectHeight + gap) - gap)) * 0.5; final Paint rectPaint = Paint(); for (int r = 0; r < numRows; r++, v = 1 - v) { final double y = yOffset + r * (rectHeight + gap); double cv = v; for (int c = 0; c < numCols; c++, cv = 1 - cv) { final double x = xOffset + c * (rectWidth + gap); rectPaint.color = Color.fromRGBO(_red(cv), _green(cv), _blue(cv), _opacity(cv)); final Rect rect = Rect.fromLTWH(x, y, rectWidth, rectHeight); canvas.drawRect(rect, rectPaint); } } }), ), ), ); }, ), OpacityPeepholeCase.forValue( route: kOpacityPeepholeGridOfAlphaSaveLayerRectsRouteName, name: 'Grid of alpha SaveLayers of Rectangles', builder: (double v) { return Opacity( opacity: _opacity(v), child: SizedBox.expand( child: CustomPaint( painter: RectGridPainter((Canvas canvas, Size size) { const int numRows = 10; const int numCols = 7; const double rectWidth = 30; const double rectHeight = 30; final double hGap = (size.width - numCols * rectWidth) / (numCols + 1); final double vGap = (size.height - numRows * rectHeight) / (numRows + 1); final double gap = min(hGap, vGap); final double xOffset = (size.width - (numCols * (rectWidth + gap) - gap)) * 0.5; final double yOffset = (size.height - (numRows * (rectHeight + gap) - gap)) * 0.5; final Paint rectPaint = Paint(); final Paint layerPaint = Paint(); for (int r = 0; r < numRows; r++, v = 1 - v) { final double y = yOffset + r * (rectHeight + gap); double cv = v; for (int c = 0; c < numCols; c++, cv = 1 - cv) { final double x = xOffset + c * (rectWidth + gap); rectPaint.color = Color.fromRGBO(_red(cv), _green(cv), _blue(cv), 1.0); layerPaint.color = Color.fromRGBO(255, 255, 255, _opacity(cv)); final Rect rect = Rect.fromLTWH(x, y, rectWidth, rectHeight); canvas.saveLayer(null, layerPaint); canvas.drawRect(rect, rectPaint); canvas.restore(); } } }), ), ), ); }, ), OpacityPeepholeCase.forValue( route: kOpacityPeepholeColumnOfAlphaSaveLayerRowsOfRectsRouteName, name: 'Grid with alpha SaveLayer on Rows', builder: (double v) { return Opacity( opacity: _opacity(v), child: SizedBox.expand( child: CustomPaint( painter: RectGridPainter((Canvas canvas, Size size) { const int numRows = 10; const int numCols = 7; const double rectWidth = 30; const double rectHeight = 30; final double hGap = (size.width - numCols * rectWidth) / (numCols + 1); final double vGap = (size.height - numRows * rectHeight) / (numRows + 1); final double gap = min(hGap, vGap); final double xOffset = (size.width - (numCols * (rectWidth + gap) - gap)) * 0.5; final double yOffset = (size.height - (numRows * (rectHeight + gap) - gap)) * 0.5; final Paint rectPaint = Paint(); final Paint layerPaint = Paint(); for (int r = 0; r < numRows; r++, v = 1 - v) { final double y = yOffset + r * (rectHeight + gap); layerPaint.color = Color.fromRGBO(255, 255, 255, _opacity(v)); canvas.saveLayer(null, layerPaint); double cv = v; for (int c = 0; c < numCols; c++, cv = 1 - cv) { final double x = xOffset + c * (rectWidth + gap); rectPaint.color = Color.fromRGBO(_red(cv), _green(cv), _blue(cv), 1.0); final Rect rect = Rect.fromLTWH(x, y, rectWidth, rectHeight); canvas.drawRect(rect, rectPaint); } canvas.restore(); } }), ), ), ); }, ), ]; class RectGridPainter extends CustomPainter { RectGridPainter(this.painter); final void Function(Canvas canvas, Size size) painter; @override void paint(Canvas canvas, Size size) => painter(canvas, size); @override bool shouldRepaint(CustomPainter oldDelegate) => true; } Map<String, WidgetBuilder> opacityPeepholeRoutes = <String, WidgetBuilder>{ for (OpacityPeepholeCase variant in allOpacityPeepholeCases) variant.route: variant.buildPage, }; class VariantPage extends StatefulWidget { const VariantPage({super.key, required this.variant}); final OpacityPeepholeCase variant; @override State<VariantPage> createState() => VariantPageState(); } class VariantPageState extends State<VariantPage> with SingleTickerProviderStateMixin { late AnimationController _controller; @override void initState() { super.initState(); _controller = AnimationController(vsync: this, duration: const Duration(seconds: 4)); _controller.repeat(reverse: true); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.variant.name), ), body: Center( child: widget.variant.animationBuilder(_controller), ), ); } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/opacity_peephole.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/opacity_peephole.dart", "repo_id": "flutter", "token_count": 8016 }
546
// Copyright 2014 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:ui'; import 'recorder.dart'; /// Repeatedly paints a grid of rectangles where each rectangle is drawn in its /// own [Picture]. /// /// Measures the performance of updating many layers. For example, the HTML /// rendering backend attempts to reuse the DOM nodes created for engine layers. /// /// See also `bench_draw_rect.dart`, which draws nearly identical UI but puts all /// rectangles into the same picture. class BenchUpdateManyChildLayers extends SceneBuilderRecorder { BenchUpdateManyChildLayers() : super(name: benchmarkName); static const String benchmarkName = 'bench_update_many_child_layers'; /// Number of rows in the grid. static const int kRows = 32; /// Number of columns in the grid. static const int kColumns = 32; /// Counter used to offset the rendered rects to make them wobble. /// /// The wobbling is there so a human could visually verify that the benchmark /// is correctly pumping frames. double wobbleCounter = 0; late List<Picture> _pictures; late Size viewSize; late Size cellSize; late Size rectSize; @override Future<void> setUpAll() async { _pictures = <Picture>[]; viewSize = view.physicalSize; cellSize = Size( viewSize.width / kColumns, viewSize.height / kRows, ); rectSize = cellSize * 0.8; final Paint paint = Paint()..color = const Color.fromARGB(255, 255, 0, 0); for (int i = 0; i < kRows * kColumns; i++) { final PictureRecorder pictureRecorder = PictureRecorder(); final Canvas canvas = Canvas(pictureRecorder); canvas.drawRect(Offset.zero & rectSize, paint); _pictures.add(pictureRecorder.endRecording()); } } OffsetEngineLayer? _rootLayer; final Map<int, OffsetEngineLayer> _layers = <int, OffsetEngineLayer>{}; @override void onDrawFrame(SceneBuilder sceneBuilder) { _rootLayer = sceneBuilder.pushOffset(0, 0, oldLayer: _rootLayer); for (int row = 0; row < kRows; row++) { for (int col = 0; col < kColumns; col++) { final int layerId = 1000000 * row + col; final OffsetEngineLayer? oldLayer = _layers[layerId]; final double wobbleOffsetX = col * cellSize.width + (wobbleCounter - 5).abs(); final double offsetY = row * cellSize.height; // Retain every other layer, so we exercise the update path 50% of the // time and the retain path the other 50%. final bool shouldRetain = oldLayer != null && (row + col).isEven; if (shouldRetain) { sceneBuilder.addRetained(oldLayer); } else { _layers[layerId] = sceneBuilder.pushOffset( wobbleOffsetX, offsetY, oldLayer: oldLayer, ); sceneBuilder.addPicture(Offset.zero, _pictures[row * kColumns + col]); sceneBuilder.pop(); } } } sceneBuilder.pop(); wobbleCounter += 1; wobbleCounter = wobbleCounter % 10; } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_child_layers.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_child_layers.dart", "repo_id": "flutter", "token_count": 1089 }
547
// Copyright 2014 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:ui_web' as ui_web; import 'package:flutter/material.dart'; import 'package:web/web.dart' as web; import 'recorder.dart'; const String benchmarkViewType = 'benchmark_element'; void _registerFactory() { ui_web.platformViewRegistry.registerViewFactory(benchmarkViewType, (int viewId) { final web.HTMLElement htmlElement = web.document.createElement('div') as web.HTMLDivElement; htmlElement.id = '${benchmarkViewType}_$viewId'; htmlElement.innerText = 'Google'; htmlElement.style ..setProperty('width', '100%') ..setProperty('height', '100%') ..setProperty('color', 'black') ..setProperty('backgroundColor', 'rgba(0, 255, 0, .5)') ..setProperty('textAlign', 'center') ..setProperty('border', '1px solid black'); return htmlElement; }); } /// Creates an infinite list of Link widgets and scrolls it. class BenchPlatformViewInfiniteScroll extends WidgetRecorder { BenchPlatformViewInfiniteScroll.forward() : initialOffset = 0.0, finalOffset = 30000.0, super(name: benchmarkName) { _registerFactory(); } BenchPlatformViewInfiniteScroll.backward() : initialOffset = 30000.0, finalOffset = 0.0, super(name: benchmarkNameBackward) { _registerFactory(); } static const String benchmarkName = 'bench_platform_view_infinite_scroll'; static const String benchmarkNameBackward = 'bench_platform_view_infinite_scroll_backward'; final double initialOffset; final double finalOffset; @override Widget createWidget() => MaterialApp( title: 'Infinite Platform View Scroll Benchmark', home: _InfiniteScrollPlatformViews(initialOffset, finalOffset), ); } class _InfiniteScrollPlatformViews extends StatefulWidget { const _InfiniteScrollPlatformViews(this.initialOffset, this.finalOffset); final double initialOffset; final double finalOffset; @override State<_InfiniteScrollPlatformViews> createState() => _InfiniteScrollPlatformViewsState(); } class _InfiniteScrollPlatformViewsState extends State<_InfiniteScrollPlatformViews> { static const Duration stepDuration = Duration(seconds: 20); late ScrollController scrollController; late double offset; @override void initState() { super.initState(); offset = widget.initialOffset; scrollController = ScrollController( initialScrollOffset: offset, ); // Without the timer the animation doesn't begin. Timer.run(() async { await scrollController.animateTo( widget.finalOffset, curve: Curves.linear, duration: stepDuration, ); }); } @override void dispose() { scrollController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return ListView.builder( controller: scrollController, itemExtent: 100.0, itemBuilder: (BuildContext context, int index) { return const SizedBox( height: 100.0, child: HtmlElementView(viewType: benchmarkViewType), ); }, ); } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_platform_view_infinite_scroll.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_platform_view_infinite_scroll.dart", "repo_id": "flutter", "token_count": 1125 }
548
# microbenchmarks To run these benchmarks on a device, first run `flutter logs' in one window to see the device logs, then, in a different window, run any of these: ``` flutter run --release lib/gestures/velocity_tracker_bench.dart flutter run --release lib/gestures/gesture_detector_bench.dart flutter run --release lib/stocks/animation_bench.dart flutter run --release lib/stocks/build_bench.dart flutter run --release lib/stocks/layout_bench.dart ``` The results should be in the device logs. ### Avoid changing names of the benchmarks Each microbenchmark is identified by a name, for example, "catmullrom_transform_iteration". Changing the name of an existing microbenchmarks will effectively remove the old benchmark and create a new one, losing the historical data associated with the old benchmark in the process.
flutter/dev/benchmarks/microbenchmarks/README.md/0
{ "file_path": "flutter/dev/benchmarks/microbenchmarks/README.md", "repo_id": "flutter", "token_count": 227 }
549
// Copyright 2014 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/services.dart' show PlatformAssetBundle; import 'package:flutter/widgets.dart'; import '../common.dart'; const int _kBatchSize = 100; const int _kNumIterations = 100; void main() async { assert(false, "Don't run benchmarks in debug mode! Use 'flutter run --release'."); final BenchmarkResultPrinter printer = BenchmarkResultPrinter(); WidgetsFlutterBinding.ensureInitialized(); final Stopwatch watch = Stopwatch(); final PlatformAssetBundle bundle = PlatformAssetBundle(); final List<double> values = <double>[]; for (int j = 0; j < _kNumIterations; ++j) { double tally = 0; watch.reset(); watch.start(); for (int i = 0; i < _kBatchSize; i += 1) { // We don't load images like this. PlatformAssetBundle is used for // other assets (like Rive animations). We are using an image because it's // conveniently sized and available for the test. tally += (await bundle.load('packages/flutter_gallery_assets/places/india_pondicherry_salt_farm.png')).lengthInBytes; } watch.stop(); values.add(watch.elapsedMicroseconds.toDouble() / _kBatchSize); if (tally < 0.0) { print("This shouldn't happen."); } } printer.addResultStatistics( description: 'PlatformAssetBundle.load 1MB', values: values, unit: 'us per iteration', name: 'PlatformAssetBundle_load_1MB', ); printer.printToStdout(); }
flutter/dev/benchmarks/microbenchmarks/lib/foundation/platform_asset_bundle.dart/0
{ "file_path": "flutter/dev/benchmarks/microbenchmarks/lib/foundation/platform_asset_bundle.dart", "repo_id": "flutter", "token_count": 533 }
550
// Copyright 2014 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 'package:flutter_test/flutter_test.dart'; import 'package:stocks/main.dart' as stocks; import 'package:stocks/stock_data.dart' as stock_data; import '../common.dart'; const Duration kBenchmarkTime = Duration(seconds: 15); Future<List<double>> runBuildBenchmark() async { assert(false, "Don't run benchmarks in debug mode! Use 'flutter run --release'."); stock_data.StockData.actuallyFetchData = false; // We control the framePolicy below to prevent us from scheduling frames in // the engine, so that the engine does not interfere with our timings. final LiveTestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized() as LiveTestWidgetsFlutterBinding; final Stopwatch watch = Stopwatch(); int iterations = 0; final List<double> values = <double>[]; await benchmarkWidgets((WidgetTester tester) async { stocks.main(); await tester.pump(); // Start startup animation await tester.pump(const Duration(seconds: 1)); // Complete startup animation await tester.tapAt(const Offset(20.0, 40.0)); // Open drawer await tester.pump(); // Start drawer animation await tester.pump(const Duration(seconds: 1)); // Complete drawer animation final Element appState = tester.element(find.byType(stocks.StocksApp)); binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.benchmark; Duration elapsed = Duration.zero; while (elapsed < kBenchmarkTime) { watch.reset(); watch.start(); appState.markNeedsBuild(); // We don't use tester.pump() because we're trying to drive it in an // artificially high load to find out how much CPU each frame takes. // This differs from normal benchmarks which might look at how many // frames are missed, etc. // We use Timer.run to ensure there's a microtask flush in between // the two calls below. await tester.pumpBenchmark(Duration(milliseconds: iterations * 16)); watch.stop(); iterations += 1; elapsed += Duration(microseconds: watch.elapsedMicroseconds); values.add(watch.elapsedMicroseconds.toDouble()); } }); return values; } Future<void> main() async { final BenchmarkResultPrinter printer = BenchmarkResultPrinter(); printer.addResultStatistics( description: 'Stock build', values: await runBuildBenchmark(), unit: 'µs per iteration', name: 'stock_build_iteration', ); printer.printToStdout(); }
flutter/dev/benchmarks/microbenchmarks/lib/stocks/build_bench.dart/0
{ "file_path": "flutter/dev/benchmarks/microbenchmarks/lib/stocks/build_bench.dart", "repo_id": "flutter", "token_count": 832 }
551
// Copyright 2014 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 "AppDelegate.h" @import Flutter; #import "GeneratedPluginRegistrant.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey, id> *)launchOptions { [GeneratedPluginRegistrant registerWithRegistry:self]; NSObject<FlutterPluginRegistrar>* registrar = [self registrarForPlugin:@"Echo"]; FlutterBasicMessageChannel* reset = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.echo.reset" binaryMessenger:registrar.messenger codec:FlutterStandardMessageCodec.sharedInstance]; [reset setMessageHandler:^(id _Nullable message, FlutterReply _Nonnull callback) { // noop }]; FlutterBasicMessageChannel* basicStandard = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.echo.basic.standard" binaryMessenger:registrar.messenger codec:FlutterStandardMessageCodec.sharedInstance]; [basicStandard setMessageHandler:^(id _Nullable message, FlutterReply _Nonnull callback) { callback(message); }]; FlutterBasicMessageChannel* basicBinary = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.echo.basic.binary" binaryMessenger:registrar.messenger codec:FlutterBinaryCodec.sharedInstance]; [basicBinary setMessageHandler:^(id _Nullable message, FlutterReply _Nonnull callback) { callback(message); }]; NSObject<FlutterTaskQueue>* taskQueue = [registrar.messenger makeBackgroundTaskQueue]; FlutterBasicMessageChannel* background = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.echo.background.standard" binaryMessenger:registrar.messenger codec:FlutterStandardMessageCodec.sharedInstance taskQueue:taskQueue]; [background setMessageHandler:^(id _Nullable message, FlutterReply _Nonnull callback) { callback(message); }]; return YES; } @end
flutter/dev/benchmarks/platform_channels_benchmarks/ios/Runner/AppDelegate.m/0
{ "file_path": "flutter/dev/benchmarks/platform_channels_benchmarks/ios/Runner/AppDelegate.m", "repo_id": "flutter", "token_count": 596 }
552
// Copyright 2014 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 <Flutter/Flutter.h> NS_ASSUME_NONNULL_BEGIN @interface DummyPlatformView : NSObject <FlutterPlatformView> - (instancetype)initWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id _Nullable)args binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger; - (UIView*)view; @end @interface DummyPlatformViewFactory : NSObject <FlutterPlatformViewFactory> - (instancetype)initWithMessenger:(NSObject<FlutterBinaryMessenger>*)messenger; @end NS_ASSUME_NONNULL_END
flutter/dev/benchmarks/platform_views_layout_hybrid_composition/ios/Runner/DummyPlatformView.h/0
{ "file_path": "flutter/dev/benchmarks/platform_views_layout_hybrid_composition/ios/Runner/DummyPlatformView.h", "repo_id": "flutter", "token_count": 262 }
553
// Copyright 2014 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:math' as math; import 'package:flutter/material.dart'; class StockArrowPainter extends CustomPainter { StockArrowPainter({ required this.color, required this.percentChange, }); final Color color; final double percentChange; @override void paint(Canvas canvas, Size size) { final Paint paint = Paint()..color = color; paint.strokeWidth = 1.0; const double padding = 2.0; assert(padding > paint.strokeWidth / 2.0); // make sure the circle remains inside the box final double r = (size.shortestSide - padding) / 2.0; // radius of the circle final double centerX = padding + r; final double centerY = padding + r; // Draw the arrow. const double w = 8.0; double h = 5.0; double arrowY; if (percentChange < 0.0) { h = -h; arrowY = centerX + 1.0; } else { arrowY = centerX - 1.0; } final Path path = Path(); path.moveTo(centerX, arrowY - h); // top of the arrow path.lineTo(centerX + w, arrowY + h); path.lineTo(centerX - w, arrowY + h); path.close(); paint.style = PaintingStyle.fill; canvas.drawPath(path, paint); // Draw a circle that circumscribes the arrow. paint.style = PaintingStyle.stroke; canvas.drawCircle(Offset(centerX, centerY), r, paint); } @override bool shouldRepaint(StockArrowPainter oldDelegate) { return oldDelegate.color != color || oldDelegate.percentChange != percentChange; } } class StockArrow extends StatelessWidget { const StockArrow({ super.key, required this.percentChange }); final double percentChange; int _colorIndexForPercentChange(double percentChange) { const double maxPercent = 10.0; final double normalizedPercentChange = math.min(percentChange.abs(), maxPercent) / maxPercent; return 100 + (normalizedPercentChange * 8.0).floor() * 100; } Color _colorForPercentChange(double percentChange) { if (percentChange > 0) { return Colors.green[_colorIndexForPercentChange(percentChange)]!; } return Colors.red[_colorIndexForPercentChange(percentChange)]!; } @override Widget build(BuildContext context) { return Container( width: 40.0, height: 40.0, margin: const EdgeInsets.symmetric(horizontal: 5.0), child: CustomPaint( painter: StockArrowPainter( // TODO(jackson): This should change colors with the theme color: _colorForPercentChange(percentChange), percentChange: percentChange, ), ), ); } }
flutter/dev/benchmarks/test_apps/stocks/lib/stock_arrow.dart/0
{ "file_path": "flutter/dev/benchmarks/test_apps/stocks/lib/stock_arrow.dart", "repo_id": "flutter", "token_count": 960 }
554
# Flutter's Build Infrastructure This directory exists to support building Flutter on our build infrastructure. Flutter build results are available at: * https://flutter-dashboard.appspot.com/#/build - Aggregate dashboard of the separate CI systems used by Flutter. * https://cirrus-ci.com/github/flutter/flutter/master - Testing is done on PRs and submitted changes on GitHub. Flutter infra requires special permissions to retrigger builds on the [build dashboard](https://flutter-dashboard.appspot.com/#/build). File an [infra ticket](https://github.com/flutter/flutter/wiki/Infra-Ticket-Queue) to request permission. The [Cirrus](https://cirrus-ci.org)-based bots run the [`test.dart`](test.dart) script for each PR and submission. This does testing for the tools, for the framework, and (for submitted changes only) rebuilds and updates the main branch API docs [staging site](https://main-api.flutter.dev/). For tagged dev and beta builds, it also builds and deploys the gallery app to the app stores. It is configured by the [.cirrus.yml](/.cirrus.yml). The build dashboard includes post-commit testing run on physical devices. See [//dev/devicelab](../devicelab/README.md) for more information. ## LUCI (Layered Universal Continuous Integration) A [set of infra scripts](https://flutter.googlesource.com/recipes/) run on Windows, Linux, and Mac machines. The configuration for how many machines and what kind are managed internally by Google. File an [infra ticket](https://github.com/flutter/flutter/wiki/Infra-Ticket-Queue) to request new machine types to be added. Both of these technologies are highly specific to the [LUCI](https://github.com/luci) project, which is the successor to Chromium's infra and the foundation to Flutter's infrastructure. ### Prerequisites To work on this infrastructure you will need: - [depot_tools](https://commondatastorage.googleapis.com/chrome-infra-docs/flat/depot_tools/docs/html/depot_tools_tutorial.html#_setting_up) - Python package installer: `sudo apt-get install python-pip` - Python coverage package (only needed for `training_simulation`): `sudo pip install coverage` To run `prepare_package.dart` locally: - Make sure the `depot_tools` is in your `PATH`. If you're on Windows, you also need an environment variable called `DEPOT_TOOLS` with the path to `depot_tools` as value. - Run `gsutil.py config` (or `python3 %DEPOT_TOOLS%\gsutil.py` on Windows) to authenticate with your auth token. - Create a local temp directory. `cd` into it. - Run `dart [path to your normal Flutter repo]/dev/bots/prepare_package.dart --temp_dir=. --revision=[revision to package] --branch=[branch to deploy to] --publish`. - If you're running into `gsutil` permission issues, check with @Hixie to make sure you have the right push permissions. ### Editing a recipe Flutter has several recipes depending on the test. The recipes share common actions through `recipe_modules`. Searching the builder config in [infra](https://flutter.googlesource.com/infra/+/refs/heads/main) will indicate the recipe used for a test. Recipes are just Python with some limitations on what can be imported. They are [documented](https://github.com/luci/recipes-py/blob/master/doc/user_guide.md) by the [luci/recipes-py GitHub project](https://github.com/luci/recipes-py). The typical cycle for editing a recipe is: 1. Check out the recipes project using `git clone https://flutter.googlesource.com/recipes`. 2. Make your edits (probably to files in `//recipes/recipes`). 3. Update the tests. Run `recipes.py test train` to update the existing expected output to match the new output. Verify completely new test cases by altering the `GenTests` method of the recipe. The recipe is required to have 100% test coverage. 4. Run `led get-builder 'luci.flutter.staging:BUILDER_NAME' | led edit -pa git_ref='refs/pull/<PR number>/head' | led edit -pa git_url='https://github.com/flutter/<repo>' | led edit-recipe-bundle | led launch`, where `BUILDER_NAME` is the builder name (e.g. `Linux Engine`), and `git_ref`/`git_url` is the ref/url of the intended changes to build. * If `led` fails, ensure that your `depot_tools` checkout is up to date. 5. To submit a CL, you need a local branch first (`git checkout -b [some branch name]`). 6. Upload the patch (`git commit`, `git cl upload`), and open the outputted URL to the CL. 7. Use "Find owners" to get reviewers for the CL ### Android Tools The Android SDK and NDK used by Flutter's Chrome infra bots are stored in Google Cloud. During the build, a bot runs the `download_android_tools.py` script that downloads the required version of the Android SDK into `dev/bots/android_tools`. To check which components are currently installed, download the current SDK stored in Google Cloud using the `download_android_tools.py` script, then `dev/bots/android_tools/sdk/tools/bin/sdkmanager --list`. If you find that some components need to be updated or installed, follow the steps below: #### How to update Android SDK on Google Cloud Storage 1. Run Android SDK Manager and update packages `$ dev/bots/android_tools/sdk/tools/android update sdk` Use `android.bat` on Windows. 2. Use the UI to choose the packages you want to install and/or update. 3. Run `dev/bots/android_tools/sdk/tools/bin/sdkmanager --update`. On Windows, run `sdkmanager.bat` instead. If the process fails with an error saying that it is unable to move files (Windows makes files and directories read-only when another process is holding them open), make a copy of the `dev/bots/android_tools/sdk/tools` directory, run the `sdkmanager.bat` from the copy, and use the `--sdk_root` option pointing at `dev/bots/android_tools/sdk`. 4. Run `dev/bots/android_tools/sdk/tools/bin/sdkmanager --licenses` and accept the licenses for the newly installed components. It also helps to run this command a second time and make sure that it prints "All SDK package licenses accepted". 5. Run upload_android_tools.py -t sdk `$ dev/bots/upload_android_tools.py -t sdk` #### How to update Android NDK on Google Cloud Storage 1. Download a new NDK binary (e.g. android-ndk-r10e-linux-x86_64.bin) 2. cd dev/bots/android_tools `$ cd dev/bots/android_tools` 3. Remove the old ndk directory `$ rm -rf ndk` 4. Run the new NDK binary file `$ ./android-ndk-r10e-linux-x86_64.bin` 5. Rename the extracted directory to ndk `$ mv android-ndk-r10e ndk` 6. Run upload_android_tools.py -t ndk `$ cd ../..` `$ dev/bots/upload_android_tools.py -t ndk` ## Flutter codelabs build test The Flutter codelabs exercise Material Components in the form of a demo application. The code for the codelabs is similar to, but distinct from, the code for the Shrine demo app in Flutter Gallery. The Flutter codelabs build test ensures that the final version of the [Material Components for Flutter Codelabs](https://github.com/material-components/material-components-flutter-codelabs) can be built. This test serves as a smoke test for the Flutter framework and should not fail. If it does, please address any issues in your PR and rerun the test. If you feel that the test failing is not a direct result of changes made in your PR or that breaking this test is absolutely necessary, escalate this issue by [submitting an issue](https://github.com/material-components/material-components-flutter-codelabs/issues/new?title=%5BURGENT%5D%20Flutter%20Framework%20breaking%20PR) to the MDC-Flutter Team. ## Unpublishing published archives Flutter downloadable archives are built for each release by our continuous integration systems using the [`prepare_package.dart`](prepare_package.dart) script, but if something goes very wrong, and a release is published that wasn't intended to be published, the [`unpublish_package.dart`](unpublish_package.dart) script may be used to remove the package or packages from the channels in which they were published. For example To remove a published package corresponding to the git hash `d444a455de87a2e40b7f576dc12ffd9ab82fd491`, first do a dry run of the script to see what it will do: ``` $ dart ./unpublish_package.dart --temp_dir=/tmp/foo --revision d444a455de87a2e40b7f576dc12ffd9ab82fd491 ``` And once you've verified the output of the dry run to be sure it is what you want to do, run: ``` $ dart ./unpublish_package.dart --confirm --temp_dir=/tmp/foo --revision d444a455de87a2e40b7f576dc12ffd9ab82fd491 ``` and it will perform the actions. You will of course need to have access to the cloud storage server and have `gsutil` installed to perform this operation. Only runs on Linux or macOS systems. See `dart ./unpublish_package.dart --help` for more details. Once the package is unpublished, it will not be available from the website for download, and will not be rebuilt (even though there is a tagged revision in the repo still) unless someone forces the packaging build to run again at that revision to rebuild the package.
flutter/dev/bots/README.md/0
{ "file_path": "flutter/dev/bots/README.md", "repo_id": "flutter", "token_count": 2702 }
555
// Copyright 2014 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'; import 'dart:io' show stderr; import 'dart:typed_data'; import 'package:convert/convert.dart'; import 'package:crypto/crypto.dart'; import 'package:file/file.dart'; import 'package:http/http.dart' as http; import 'package:path/path.dart' as path; import 'package:platform/platform.dart' show LocalPlatform, Platform; import 'package:pool/pool.dart'; import 'package:process/process.dart'; import 'common.dart'; import 'process_runner.dart'; typedef HttpReader = Future<Uint8List> Function(Uri url, {Map<String, String> headers}); /// Creates a pre-populated Flutter archive from a git repo. class ArchiveCreator { /// [tempDir] is the directory to use for creating the archive. The script /// will place several GiB of data there, so it should have available space. /// /// The processManager argument is used to inject a mock of [ProcessManager] for /// testing purposes. /// /// If subprocessOutput is true, then output from processes invoked during /// archive creation is echoed to stderr and stdout. factory ArchiveCreator( Directory tempDir, Directory outputDir, String revision, Branch branch, { required FileSystem fs, HttpReader? httpReader, Platform platform = const LocalPlatform(), ProcessManager? processManager, bool strict = true, bool subprocessOutput = true, }) { final Directory flutterRoot = fs.directory(path.join(tempDir.path, 'flutter')); final ProcessRunner processRunner = ProcessRunner( processManager: processManager, subprocessOutput: subprocessOutput, platform: platform, )..environment['PUB_CACHE'] = path.join( tempDir.path, '.pub-cache', ); final String flutterExecutable = path.join( flutterRoot.absolute.path, 'bin', 'flutter', ); final String dartExecutable = path.join( flutterRoot.absolute.path, 'bin', 'cache', 'dart-sdk', 'bin', 'dart', ); return ArchiveCreator._( tempDir: tempDir, platform: platform, flutterRoot: flutterRoot, fs: fs, outputDir: outputDir, revision: revision, branch: branch, strict: strict, processRunner: processRunner, httpReader: httpReader ?? http.readBytes, flutterExecutable: flutterExecutable, dartExecutable: dartExecutable, ); } ArchiveCreator._({ required this.branch, required String dartExecutable, required this.fs, required String flutterExecutable, required this.flutterRoot, required this.httpReader, required this.outputDir, required this.platform, required ProcessRunner processRunner, required this.revision, required this.strict, required this.tempDir, }) : assert(revision.length == 40), _processRunner = processRunner, _flutter = flutterExecutable, _dart = dartExecutable; /// The platform to use for the environment and determining which /// platform we're running on. final Platform platform; /// The branch to build the archive for. The branch must contain [revision]. final Branch branch; /// The git revision hash to build the archive for. This revision has /// to be available in the [branch], although it doesn't have to be /// at HEAD, since we clone the branch and then reset to this revision /// to create the archive. final String revision; /// The flutter root directory in the [tempDir]. final Directory flutterRoot; /// The temporary directory used to build the archive in. final Directory tempDir; /// The directory to write the output file to. final Directory outputDir; final FileSystem fs; /// True if the creator should be strict about checking requirements or not. /// /// In strict mode, will insist that the [revision] be a tagged revision. final bool strict; final Uri _minGitUri = Uri.parse(mingitForWindowsUrl); final ProcessRunner _processRunner; /// Used to tell the [ArchiveCreator] which function to use for reading /// bytes from a URL. Used in tests to inject a fake reader. Defaults to /// [http.readBytes]. final HttpReader httpReader; final Map<String, String> _version = <String, String>{}; late String _flutter; late String _dart; late final Future<String> _dartArch = (() async { // Parse 'arch' out of a string like '... "os_arch"\n'. return (await _runDart(<String>['--version'])) .trim().split(' ').last.replaceAll('"', '').split('_')[1]; })(); /// Returns a default archive name when given a Git revision. /// Used when an output filename is not given. Future<String> get _archiveName async { final String os = platform.operatingSystem.toLowerCase(); // Include the intended host architecture in the file name for non-x64. final String arch = await _dartArch == 'x64' ? '' : '${await _dartArch}_'; // We don't use .tar.xz on Mac because although it can unpack them // on the command line (with tar), the "Archive Utility" that runs // when you double-click on them just does some crazy behavior (it // converts it to a compressed cpio archive, and when you double // click on that, it converts it back to .tar.xz, without ever // unpacking it!) So, we use .zip for Mac, and the files are about // 220MB larger than they need to be. :-( final String suffix = platform.isLinux ? 'tar.xz' : 'zip'; final String package = '${os}_$arch${_version[frameworkVersionTag]}'; return 'flutter_$package-${branch.name}.$suffix'; } /// Checks out the flutter repo and prepares it for other operations. /// /// Returns the version for this release as obtained from the git tags, and /// the dart version as obtained from `flutter --version`. Future<Map<String, String>> initializeRepo() async { await _checkoutFlutter(); if (_version.isEmpty) { _version.addAll(await _getVersion()); } return _version; } /// Performs all of the steps needed to create an archive. Future<File> createArchive() async { assert(_version.isNotEmpty, 'Must run initializeRepo before createArchive'); final File outputFile = fs.file(path.join( outputDir.absolute.path, await _archiveName, )); await _installMinGitIfNeeded(); await _populateCaches(); await _validate(); await _archiveFiles(outputFile); return outputFile; } /// Validates the integrity of the release package. /// /// Currently only checks that macOS binaries are codesigned. Will throw a /// [PreparePackageException] if the test fails. Future<void> _validate() async { // Only validate in strict mode, which means `--publish` if (!strict || !platform.isMacOS) { return; } // Validate that the dart binary is codesigned try { // TODO(fujino): Use the conductor https://github.com/flutter/flutter/issues/81701 await _processRunner.runProcess( <String>[ 'codesign', '-vvvv', '--check-notarization', _dart, ], workingDirectory: flutterRoot, ); } on PreparePackageException catch (e) { throw PreparePackageException( 'The binary $_dart was not codesigned!\n${e.message}', ); } } /// Returns the version map of this release, according the to tags in the /// repo and the output of `flutter --version --machine`. /// /// This looks for the tag attached to [revision] and, if it doesn't find one, /// git will give an error. /// /// If [strict] is true, the exact [revision] must be tagged to return the /// version. If [strict] is not true, will look backwards in time starting at /// [revision] to find the most recent version tag. /// /// The version found as a git tag is added to the information given by /// `flutter --version --machine` with the `frameworkVersionFromGit` tag, and /// returned. Future<Map<String, String>> _getVersion() async { String gitVersion; if (strict) { try { gitVersion = await _runGit(<String>['describe', '--tags', '--exact-match', revision]); } on PreparePackageException catch (exception) { throw PreparePackageException( 'Git error when checking for a version tag attached to revision $revision.\n' 'Perhaps there is no tag at that revision?:\n' '$exception' ); } } else { gitVersion = await _runGit(<String>['describe', '--tags', '--abbrev=0', revision]); } // Run flutter command twice, once to make sure the flutter command is built // and ready (and thus won't output any junk on stdout the second time), and // once to capture theJSON output. The second run should be fast. await _runFlutter(<String>['--version', '--machine']); final String versionJson = await _runFlutter(<String>['--version', '--machine']); final Map<String, String> versionMap = <String, String>{}; final Map<String, dynamic> result = json.decode(versionJson) as Map<String, dynamic>; result.forEach((String key, dynamic value) => versionMap[key] = value.toString()); versionMap[frameworkVersionTag] = gitVersion; versionMap[dartTargetArchTag] = await _dartArch; return versionMap; } /// Clone the Flutter repo and make sure that the git environment is sane /// for when the user will unpack it. Future<void> _checkoutFlutter() async { // We want the user to start out the in the specified branch instead of a // detached head. To do that, we need to make sure the branch points at the // desired revision. await _runGit(<String>['clone', '-b', branch.name, gobMirror], workingDirectory: tempDir); await _runGit(<String>['reset', '--hard', revision]); // Make the origin point to github instead of the chromium mirror. await _runGit(<String>['remote', 'set-url', 'origin', githubRepo]); // Minify `.git` footprint (saving about ~100 MB as of Oct 2022) await _runGit(<String>['gc', '--prune=now', '--aggressive']); } /// Retrieve the MinGit executable from storage and unpack it. Future<void> _installMinGitIfNeeded() async { if (!platform.isWindows) { return; } final Uint8List data = await httpReader(_minGitUri); final File gitFile = fs.file(path.join(tempDir.absolute.path, 'mingit.zip')); await gitFile.writeAsBytes(data, flush: true); final Directory minGitPath = fs.directory(path.join(flutterRoot.absolute.path, 'bin', 'mingit')); await minGitPath.create(recursive: true); await _unzipArchive(gitFile, workingDirectory: minGitPath); } /// Downloads an archive of every package that is present in the temporary /// pub-cache from pub.dev. Stores the archives in /// $flutterRoot/.pub-preload-cache. /// /// These archives will be installed in the user-level cache on first /// following flutter command that accesses the cache. /// /// Precondition: all packages currently in the PUB_CACHE of [_processRunner] /// are installed from pub.dev. Future<void> _downloadPubPackageArchives() async { final Pool pool = Pool(10); // Number of simultaneous downloads. final http.Client client = http.Client(); final Directory preloadCache = fs.directory(path.join(flutterRoot.path, '.pub-preload-cache')); preloadCache.createSync(recursive: true); /// Fetch a single package. Future<void> fetchPackageArchive(String name, String version) async { await pool.withResource(() async { stderr.write('Fetching package archive for $name-$version.\n'); int retries = 7; while (true) { retries-=1; try { final Uri packageListingUrl = Uri.parse('https://pub.dev/api/packages/$name'); // Fetch the package listing to obtain the package download url. final http.Response packageListingResponse = await client.get(packageListingUrl); if (packageListingResponse.statusCode != 200) { throw Exception('Downloading $packageListingUrl failed. Status code ${packageListingResponse.statusCode}.'); } final dynamic decodedPackageListing = json.decode(packageListingResponse.body); if (decodedPackageListing is! Map) { throw const FormatException('Package listing should be a map'); } final dynamic versions = decodedPackageListing['versions']; if (versions is! List) { throw const FormatException('.versions should be a list'); } final Map<String, dynamic> versionDescription = versions.firstWhere( (dynamic description) { if (description is! Map) { throw const FormatException('.versions elements should be maps'); } return description['version'] == version; }, orElse: () => throw FormatException('Could not find $name-$version in package listing') ) as Map<String, dynamic>; final dynamic downloadUrl = versionDescription['archive_url']; if (downloadUrl is! String) { throw const FormatException('archive_url should be a string'); } final dynamic archiveSha256 = versionDescription['archive_sha256']; if (archiveSha256 is! String) { throw const FormatException('archive_sha256 should be a string'); } final http.Request request = http.Request('get', Uri.parse(downloadUrl)); final http.StreamedResponse response = await client.send(request); if (response.statusCode != 200) { throw Exception('Downloading ${request.url} failed. Status code ${response.statusCode}.'); } final File archiveFile = fs.file( path.join(preloadCache.path, '$name-$version.tar.gz'), ); await response.stream.pipe(archiveFile.openWrite()); final Stream<List<int>> archiveStream = archiveFile.openRead(); final Digest r = await sha256.bind(archiveStream).first; if (hex.encode(r.bytes) != archiveSha256) { throw Exception('Hash mismatch of downloaded archive'); } } on Exception catch (e) { stderr.write('Failed downloading $name-$version. $e\n'); if (retries > 0) { stderr.write('Retrying download of $name-$version...'); // Retry. continue; } else { rethrow; } } break; } }); } final Map<String, dynamic> cacheDescription = json.decode(await _runFlutter(<String>['pub', 'cache', 'list'])) as Map<String, dynamic>; final Map<String, dynamic> packages = cacheDescription['packages'] as Map<String, dynamic>; final List<Future<void>> downloads = <Future<void>>[]; for (final MapEntry<String, dynamic> package in packages.entries) { final String name = package.key; final Map<String, dynamic> versions = package.value as Map<String, dynamic>; for (final String version in versions.keys) { downloads.add(fetchPackageArchive(name, version)); } } await Future.wait(downloads); client.close(); } /// Prepare the archive repo so that it has all of the caches warmed up and /// is configured for the user to begin working. Future<void> _populateCaches() async { await _runFlutter(<String>['doctor']); await _runFlutter(<String>['update-packages']); await _runFlutter(<String>['precache']); await _runFlutter(<String>['ide-config']); // Create each of the templates, since they will call 'pub get' on // themselves when created, and this will warm the cache with their // dependencies too. for (final String template in <String>['app', 'package', 'plugin']) { final String createName = path.join(tempDir.path, 'create_$template'); await _runFlutter( <String>['create', '--template=$template', createName], // Run it outside the cloned Flutter repo to not nest git repos, since // they'll be git repos themselves too. workingDirectory: tempDir, ); } await _downloadPubPackageArchives(); // Yes, we could just skip all .packages files when constructing // the archive, but some are checked in, and we don't want to skip // those. await _runGit(<String>[ 'clean', '-f', // Do not -X as it could lead to entire bin/cache getting cleaned '-x', '--', '**/.packages', ]); /// Remove package_config files and any contents in .dart_tool await _runGit(<String>[ 'clean', '-f', '-x', '--', '**/.dart_tool/', ]); // Ensure the above commands do not clean out the cache final Directory flutterCache = fs.directory(path.join(flutterRoot.absolute.path, 'bin', 'cache')); if (!flutterCache.existsSync()) { throw Exception('The flutter cache was not found at ${flutterCache.path}!'); } /// Remove git subfolder from .pub-cache, this contains the flutter goldens /// and new flutter_gallery. final Directory gitCache = fs.directory(path.join(flutterRoot.absolute.path, '.pub-cache', 'git')); if (gitCache.existsSync()) { gitCache.deleteSync(recursive: true); } } /// Write the archive to the given output file. Future<void> _archiveFiles(File outputFile) async { if (outputFile.path.toLowerCase().endsWith('.zip')) { await _createZipArchive(outputFile, flutterRoot); } else if (outputFile.path.toLowerCase().endsWith('.tar.xz')) { await _createTarArchive(outputFile, flutterRoot); } } Future<String> _runDart(List<String> args, {Directory? workingDirectory}) { return _processRunner.runProcess( <String>[_dart, ...args], workingDirectory: workingDirectory ?? flutterRoot, ); } Future<String> _runFlutter(List<String> args, {Directory? workingDirectory}) { return _processRunner.runProcess( <String>[_flutter, ...args], workingDirectory: workingDirectory ?? flutterRoot, ); } Future<String> _runGit(List<String> args, {Directory? workingDirectory}) { return _processRunner.runProcess( <String>['git', ...args], workingDirectory: workingDirectory ?? flutterRoot, ); } /// Unpacks the given zip file into the currentDirectory (if set), or the /// same directory as the archive. Future<String> _unzipArchive(File archive, {Directory? workingDirectory}) { workingDirectory ??= fs.directory(path.dirname(archive.absolute.path)); List<String> commandLine; if (platform.isWindows) { commandLine = <String>[ '7za', 'x', archive.absolute.path, ]; } else { commandLine = <String>[ 'unzip', archive.absolute.path, ]; } return _processRunner.runProcess(commandLine, workingDirectory: workingDirectory); } /// Create a zip archive from the directory source. Future<String> _createZipArchive(File output, Directory source) async { List<String> commandLine; if (platform.isWindows) { // Unhide the .git folder, https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/attrib. await _processRunner.runProcess( <String>['attrib', '-h', '.git'], workingDirectory: fs.directory(source.absolute.path), ); commandLine = <String>[ '7za', 'a', '-tzip', '-mx=9', output.absolute.path, path.basename(source.path), ]; } else { commandLine = <String>[ 'zip', '-r', '-9', '--symlinks', output.absolute.path, path.basename(source.path), ]; } return _processRunner.runProcess( commandLine, workingDirectory: fs.directory(path.dirname(source.absolute.path)), ); } /// Create a tar archive from the directory source. Future<String> _createTarArchive(File output, Directory source) { return _processRunner.runProcess(<String>[ 'tar', 'cJf', output.absolute.path, // Print out input files as they get added, to debug hangs '--verbose', path.basename(source.absolute.path), ], workingDirectory: fs.directory(path.dirname(source.absolute.path))); } }
flutter/dev/bots/prepare_package/archive_creator.dart/0
{ "file_path": "flutter/dev/bots/prepare_package/archive_creator.dart", "repo_id": "flutter", "token_count": 7364 }
556
// Copyright 2014 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 '../../foo/stopwatch_external_lib.dart' as externallib; typedef ExternalStopwatchConstructor = externallib.MyStopwatch Function(); class StopwatchAtHome extends Stopwatch { StopwatchAtHome(); StopwatchAtHome.create(): this(); Stopwatch get stopwatch => this; } void testNoStopwatches(Stopwatch stopwatch) { stopwatch.runtimeType; // OK for now, but we probably want to catch public APIs that take a Stopwatch? final Stopwatch localVariable = Stopwatch(); // Bad: introducing Stopwatch from dart:core. Stopwatch().runtimeType; // Bad: introducing Stopwatch from dart:core. (localVariable..runtimeType) // OK: not directly introducing Stopwatch. .runtimeType; StopwatchAtHome().runtimeType; // Bad: introducing a Stopwatch subclass. Stopwatch anotherStopwatch = stopwatch; // OK: not directly introducing Stopwatch. StopwatchAtHome Function() constructor = StopwatchAtHome.new; // Bad: introducing a Stopwatch constructor. assert(() { anotherStopwatch = constructor()..runtimeType; constructor = StopwatchAtHome.create; // Bad: introducing a Stopwatch constructor. anotherStopwatch = constructor()..runtimeType; return true; }()); anotherStopwatch.runtimeType; externallib.MyStopwatch.create(); // Bad: introducing an external Stopwatch constructor. ExternalStopwatchConstructor? externalConstructor; assert(() { externalConstructor = externallib.MyStopwatch.new; // Bad: introducing an external Stopwatch constructor. return true; }()); externalConstructor?.call(); externallib.stopwatch.runtimeType; // Bad: introducing an external Stopwatch. externallib.createMyStopwatch().runtimeType; // Bad: calling an external function that returns a Stopwatch. externallib.createStopwatch().runtimeType; // Bad: calling an external function that returns a Stopwatch. externalConstructor = externallib.createMyStopwatch; // Bad: introducing the tear-off form of an external function that returns a Stopwatch. constructor.call().stopwatch; // OK: existing instance. } void testStopwatchIgnore(Stopwatch stopwatch) { Stopwatch().runtimeType; // flutter_ignore: stopwatch (see analyze.dart) Stopwatch().runtimeType; // flutter_ignore: some_other_ignores, stopwatch (see analyze.dart) }
flutter/dev/bots/test/analyze-test-input/root/packages/flutter/lib/stopwatch.dart/0
{ "file_path": "flutter/dev/bots/test/analyze-test-input/root/packages/flutter/lib/stopwatch.dart", "repo_id": "flutter", "token_count": 843 }
557
// Copyright 2014 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:io'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:path/path.dart' as path; import '../check_code_samples.dart'; import '../utils.dart'; import 'common.dart'; void main() { late SampleChecker checker; late FileSystem fs; late Directory examples; late Directory packages; late Directory dartUIPath; late Directory flutterRoot; String getRelativePath(File file, [Directory? from]) { from ??= flutterRoot; return path.relative(file.absolute.path, from: flutterRoot.absolute.path); } void writeLink({required File source, required File example, String? alternateLink}) { final String link = alternateLink ?? ' ** See code in ${getRelativePath(example)} **'; source ..createSync(recursive: true) ..writeAsStringSync(''' /// Class documentation /// /// {@tool dartpad} /// Example description /// ///$link /// {@end-tool} '''); } void buildTestFiles({bool missingLinks = false, bool missingTests = false, bool malformedLinks = false}) { final Directory examplesLib = examples.childDirectory('lib').childDirectory('layer')..createSync(recursive: true); final File fooExample = examplesLib.childFile('foo_example.0.dart') ..createSync(recursive: true) ..writeAsStringSync('// Example for foo'); final File barExample = examplesLib.childFile('bar_example.0.dart') ..createSync(recursive: true) ..writeAsStringSync('// Example for bar'); final File curvesExample = examples.childDirectory('lib').childDirectory('animation').childDirectory('curves').childFile('curve2_d.0.dart') ..createSync(recursive: true) ..writeAsStringSync('// Missing a test, but OK'); if (missingLinks) { examplesLib.childFile('missing_example.0.dart') ..createSync(recursive: true) ..writeAsStringSync('// Example that is not linked'); } final Directory examplesTests = examples.childDirectory('test').childDirectory('layer') ..createSync(recursive: true); examplesTests.childFile('foo_example.0_test.dart') ..createSync(recursive: true) ..writeAsStringSync('// test for foo example'); if (!missingTests) { examplesTests.childFile('bar_example.0_test.dart') ..createSync(recursive: true) ..writeAsStringSync('// test for bar example'); } if (missingLinks) { examplesTests.childFile('missing_example.0_test.dart') ..createSync(recursive: true) ..writeAsStringSync('// test for foo example'); } final Directory flutterPackage = packages.childDirectory('flutter').childDirectory('lib').childDirectory('src') ..createSync(recursive: true); if (malformedLinks) { writeLink(source: flutterPackage.childDirectory('layer').childFile('foo.dart'), example: fooExample, alternateLink: '*See Code *'); writeLink(source: flutterPackage.childDirectory('layer').childFile('bar.dart'), example: barExample, alternateLink: ' ** See code examples/api/lib/layer/bar_example.0.dart **'); writeLink(source: flutterPackage.childDirectory('animation').childFile('curves.dart'), example: curvesExample, alternateLink: '* see code in examples/api/lib/animation/curves/curve2_d.0.dart *'); } else { writeLink(source: flutterPackage.childDirectory('layer').childFile('foo.dart'), example: fooExample); writeLink(source: flutterPackage.childDirectory('layer').childFile('bar.dart'), example: barExample); writeLink(source: flutterPackage.childDirectory('animation').childFile('curves.dart'), example: curvesExample); } } setUp(() { fs = MemoryFileSystem(style: Platform.isWindows ? FileSystemStyle.windows : FileSystemStyle.posix); // Get the root prefix of the current directory so that on Windows we get a // correct root prefix. flutterRoot = fs.directory(path.join(path.rootPrefix(fs.currentDirectory.absolute.path), 'flutter sdk'))..createSync(recursive: true); fs.currentDirectory = flutterRoot; examples = flutterRoot.childDirectory('examples').childDirectory('api')..createSync(recursive: true); packages = flutterRoot.childDirectory('packages')..createSync(recursive: true); dartUIPath = flutterRoot .childDirectory('bin') .childDirectory('cache') .childDirectory('pkg') .childDirectory('sky_engine') .childDirectory('lib') ..createSync(recursive: true); checker = SampleChecker( examples: examples, packages: packages, dartUIPath: dartUIPath, flutterRoot: flutterRoot, filesystem: fs, ); }); test('check_code_samples.dart - checkCodeSamples catches missing links', () async { buildTestFiles(missingLinks: true); bool? success; final String result = await capture( () async { success = checker.checkCodeSamples(); }, shouldHaveErrors: true, ); final String lines = <String>[ '╔═╡ERROR #1╞════════════════════════════════════════════════════════════════════', '║ The following examples are not linked from any source file API doc comments:', '║ examples/api/lib/layer/missing_example.0.dart', '║ Either link them to a source file API doc comment, or remove them.', '╚═══════════════════════════════════════════════════════════════════════════════', ].map((String line) { return line.replaceAll('/', Platform.isWindows ? r'\' : '/'); }).join('\n'); expect(result, equals('$lines\n')); expect(success, equals(false)); }); test('check_code_samples.dart - checkCodeSamples catches malformed links', () async { buildTestFiles(malformedLinks: true); bool? success; final String result = await capture( () async { success = checker.checkCodeSamples(); }, shouldHaveErrors: true, ); final bool isWindows = Platform.isWindows; final String lines = <String>[ '╔═╡ERROR #1╞════════════════════════════════════════════════════════════════════', '║ The following examples are not linked from any source file API doc comments:', if (!isWindows) '║ examples/api/lib/animation/curves/curve2_d.0.dart', if (!isWindows) '║ examples/api/lib/layer/foo_example.0.dart', if (!isWindows) '║ examples/api/lib/layer/bar_example.0.dart', if (isWindows) r'║ examples\api\lib\animation\curves\curve2_d.0.dart', if (isWindows) r'║ examples\api\lib\layer\foo_example.0.dart', if (isWindows) r'║ examples\api\lib\layer\bar_example.0.dart', '║ Either link them to a source file API doc comment, or remove them.', '╚═══════════════════════════════════════════════════════════════════════════════', '╔═╡ERROR #2╞════════════════════════════════════════════════════════════════════', '║ The following malformed links were found in API doc comments:', if (!isWindows) '║ /flutter sdk/packages/flutter/lib/src/animation/curves.dart:6: ///* see code in examples/api/lib/animation/curves/curve2_d.0.dart *', if (!isWindows) '║ /flutter sdk/packages/flutter/lib/src/layer/foo.dart:6: ///*See Code *', if (!isWindows) '║ /flutter sdk/packages/flutter/lib/src/layer/bar.dart:6: /// ** See code examples/api/lib/layer/bar_example.0.dart **', if (isWindows) r'║ C:\flutter sdk\packages\flutter\lib\src\animation\curves.dart:6: ///* see code in examples/api/lib/animation/curves/curve2_d.0.dart *', if (isWindows) r'║ C:\flutter sdk\packages\flutter\lib\src\layer\foo.dart:6: ///*See Code *', if (isWindows) r'║ C:\flutter sdk\packages\flutter\lib\src\layer\bar.dart:6: /// ** See code examples/api/lib/layer/bar_example.0.dart **', '║ Correct the formatting of these links so that they match the exact pattern:', r"║ r'\*\* See code in (?<path>.+) \*\*'", '╚═══════════════════════════════════════════════════════════════════════════════', ].join('\n'); expect(result, equals('$lines\n')); expect(success, equals(false)); }); test('check_code_samples.dart - checkCodeSamples catches missing tests', () async { buildTestFiles(missingTests: true); bool? success; final String result = await capture( () async { success = checker.checkCodeSamples(); }, shouldHaveErrors: true, ); final String lines = <String>[ '╔═╡ERROR #1╞════════════════════════════════════════════════════════════════════', '║ The following example test files are missing:', '║ examples/api/test/layer/bar_example.0_test.dart', '╚═══════════════════════════════════════════════════════════════════════════════', ].map((String line) { return line.replaceAll('/', Platform.isWindows ? r'\' : '/'); }).join('\n'); expect(result, equals('$lines\n')); expect(success, equals(false)); }); test('check_code_samples.dart - checkCodeSamples succeeds', () async { buildTestFiles(); bool? success; final String result = await capture( () async { success = checker.checkCodeSamples(); }, ); expect(result, isEmpty); expect(success, equals(true)); }); } typedef AsyncVoidCallback = Future<void> Function(); Future<String> capture(AsyncVoidCallback callback, {bool shouldHaveErrors = false}) async { final StringBuffer buffer = StringBuffer(); final PrintCallback oldPrint = print; try { print = (Object? line) { buffer.writeln(line); }; await callback(); expect( hasError, shouldHaveErrors, reason: buffer.isEmpty ? '(No output to report.)' : hasError ? 'Unexpected errors:\n$buffer' : 'Unexpected success:\n$buffer', ); } finally { print = oldPrint; resetErrorStatus(); } if (stdout.supportsAnsiEscapes) { // Remove ANSI escapes when this test is running on a terminal. return buffer.toString().replaceAll(RegExp(r'(\x9B|\x1B\[)[0-?]{1,3}[ -/]*[@-~]'), ''); } else { return buffer.toString(); } }
flutter/dev/bots/test/check_code_samples_test.dart/0
{ "file_path": "flutter/dev/bots/test/check_code_samples_test.dart", "repo_id": "flutter", "token_count": 3907 }
558
// Copyright 2014 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. // See: https://github.com/flutter/flutter/wiki/Release-process import 'dart:io' as io; import 'package:args/command_runner.dart'; import 'package:conductor_core/conductor_core.dart'; import 'package:file/file.dart'; import 'package:file/local.dart'; import 'package:platform/platform.dart'; import 'package:process/process.dart'; const String readmeUrl = 'https://github.com/flutter/flutter/tree/master/dev/conductor/README.md'; Future<void> main(List<String> args) async { const FileSystem fileSystem = LocalFileSystem(); const ProcessManager processManager = LocalProcessManager(); const Platform platform = LocalPlatform(); final Stdio stdio = VerboseStdio( stdout: io.stdout, stderr: io.stderr, stdin: io.stdin, ); final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: _localFlutterRoot.parent, platform: platform, processManager: processManager, stdio: stdio, ); final CommandRunner<void> runner = CommandRunner<void>( 'conductor', 'A tool for coordinating Flutter releases. For more documentation on ' 'usage, please see $readmeUrl.', usageLineLength: 80, ); final String conductorVersion = (await const Git(processManager).getOutput( <String>['rev-parse'], 'Get the revision of the current Flutter SDK', workingDirectory: _localFlutterRoot.path, )).trim(); <Command<void>>[ StatusCommand( checkouts: checkouts, ), StartCommand( checkouts: checkouts, conductorVersion: conductorVersion, ), CleanCommand( checkouts: checkouts, ), CandidatesCommand( checkouts: checkouts, flutterRoot: _localFlutterRoot, ), NextCommand( checkouts: checkouts, ), ].forEach(runner.addCommand); if (!assertsEnabled()) { stdio.printError('The conductor tool must be run with --enable-asserts.'); io.exit(1); } try { await runner.run(args); } on Exception catch (e, stacktrace) { stdio.printError('$e\n\n$stacktrace'); io.exit(1); } } Directory get _localFlutterRoot { String filePath; const FileSystem fileSystem = LocalFileSystem(); const Platform platform = LocalPlatform(); filePath = platform.script.toFilePath(); final String checkoutsDirname = fileSystem.path.normalize( fileSystem.path.join( fileSystem.path.dirname(filePath), // flutter/dev/conductor/core/bin '..', // flutter/dev/conductor/core '..', // flutter/dev/conductor '..', // flutter/dev '..', // flutter ), ); return fileSystem.directory(checkoutsDirname); }
flutter/dev/conductor/core/bin/cli.dart/0
{ "file_path": "flutter/dev/conductor/core/bin/cli.dart", "repo_id": "flutter", "token_count": 970 }
559
// Copyright 2014 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. // // Generated code. Do not modify. // source: conductor_state.proto // // @dart = 2.12 // ignore_for_file: annotate_overrides, camel_case_types // ignore_for_file: constant_identifier_names, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_final_fields // ignore_for_file: unnecessary_import, unnecessary_this, unused_import import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; class ReleasePhase extends $pb.ProtobufEnum { static const ReleasePhase APPLY_ENGINE_CHERRYPICKS = ReleasePhase._(0, _omitEnumNames ? '' : 'APPLY_ENGINE_CHERRYPICKS'); static const ReleasePhase VERIFY_ENGINE_CI = ReleasePhase._(1, _omitEnumNames ? '' : 'VERIFY_ENGINE_CI'); static const ReleasePhase APPLY_FRAMEWORK_CHERRYPICKS = ReleasePhase._(2, _omitEnumNames ? '' : 'APPLY_FRAMEWORK_CHERRYPICKS'); static const ReleasePhase PUBLISH_VERSION = ReleasePhase._(3, _omitEnumNames ? '' : 'PUBLISH_VERSION'); static const ReleasePhase VERIFY_RELEASE = ReleasePhase._(5, _omitEnumNames ? '' : 'VERIFY_RELEASE'); static const ReleasePhase RELEASE_COMPLETED = ReleasePhase._(6, _omitEnumNames ? '' : 'RELEASE_COMPLETED'); static const $core.List<ReleasePhase> values = <ReleasePhase>[ APPLY_ENGINE_CHERRYPICKS, VERIFY_ENGINE_CI, APPLY_FRAMEWORK_CHERRYPICKS, PUBLISH_VERSION, VERIFY_RELEASE, RELEASE_COMPLETED, ]; static final $core.Map<$core.int, ReleasePhase> _byValue = $pb.ProtobufEnum.initByValue(values); static ReleasePhase? valueOf($core.int value) => _byValue[value]; const ReleasePhase._($core.int v, $core.String n) : super(v, n); } class CherrypickState extends $pb.ProtobufEnum { static const CherrypickState PENDING = CherrypickState._(0, _omitEnumNames ? '' : 'PENDING'); static const CherrypickState PENDING_WITH_CONFLICT = CherrypickState._(1, _omitEnumNames ? '' : 'PENDING_WITH_CONFLICT'); static const CherrypickState COMPLETED = CherrypickState._(2, _omitEnumNames ? '' : 'COMPLETED'); static const CherrypickState ABANDONED = CherrypickState._(3, _omitEnumNames ? '' : 'ABANDONED'); static const $core.List<CherrypickState> values = <CherrypickState>[ PENDING, PENDING_WITH_CONFLICT, COMPLETED, ABANDONED, ]; static final $core.Map<$core.int, CherrypickState> _byValue = $pb.ProtobufEnum.initByValue(values); static CherrypickState? valueOf($core.int value) => _byValue[value]; const CherrypickState._($core.int v, $core.String n) : super(v, n); } class ReleaseType extends $pb.ProtobufEnum { static const ReleaseType STABLE_INITIAL = ReleaseType._(0, _omitEnumNames ? '' : 'STABLE_INITIAL'); static const ReleaseType STABLE_HOTFIX = ReleaseType._(1, _omitEnumNames ? '' : 'STABLE_HOTFIX'); static const ReleaseType BETA_INITIAL = ReleaseType._(2, _omitEnumNames ? '' : 'BETA_INITIAL'); static const ReleaseType BETA_HOTFIX = ReleaseType._(3, _omitEnumNames ? '' : 'BETA_HOTFIX'); static const $core.List<ReleaseType> values = <ReleaseType>[ STABLE_INITIAL, STABLE_HOTFIX, BETA_INITIAL, BETA_HOTFIX, ]; static final $core.Map<$core.int, ReleaseType> _byValue = $pb.ProtobufEnum.initByValue(values); static ReleaseType? valueOf($core.int value) => _byValue[value]; const ReleaseType._($core.int v, $core.String n) : super(v, n); } const _omitEnumNames = $core.bool.fromEnvironment('protobuf.omit_enum_names');
flutter/dev/conductor/core/lib/src/proto/conductor_state.pbenum.dart/0
{ "file_path": "flutter/dev/conductor/core/lib/src/proto/conductor_state.pbenum.dart", "repo_id": "flutter", "token_count": 1305 }
560
// Copyright 2014 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:args/command_runner.dart'; import 'package:conductor_core/src/git.dart'; import 'package:conductor_core/src/globals.dart'; import 'package:conductor_core/src/next.dart'; import 'package:conductor_core/src/proto/conductor_state.pb.dart' as pb; import 'package:conductor_core/src/proto/conductor_state.pbenum.dart' show ReleasePhase; import 'package:conductor_core/src/repository.dart'; import 'package:conductor_core/src/state.dart'; import 'package:conductor_core/src/stdio.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:platform/platform.dart'; import './common.dart'; void main() { const String flutterRoot = '/flutter'; const String checkoutsParentDirectory = '$flutterRoot/dev/conductor'; const String candidateBranch = 'flutter-1.2-candidate.3'; const String workingBranch = 'cherrypicks-$candidateBranch'; const String remoteUrl = 'https://github.com/org/repo.git'; const String revision1 = 'd3af60d18e01fcb36e0c0fa06c8502e4935ed095'; const String revision2 = 'f99555c1e1392bf2a8135056b9446680c2af4ddf'; const String revision3 = 'ffffffffffffffffffffffffffffffffffffffff'; const String revision4 = '280e23318a0d8341415c66aa32581352a421d974'; const String releaseVersion = '1.2.0-3.0.pre'; const String releaseChannel = 'beta'; const String stateFile = '/state-file.json'; final String localPathSeparator = const LocalPlatform().pathSeparator; final String localOperatingSystem = const LocalPlatform().operatingSystem; group('next command', () { late MemoryFileSystem fileSystem; late TestStdio stdio; setUp(() { stdio = TestStdio(); fileSystem = MemoryFileSystem.test(); }); CommandRunner<void> createRunner({ required Checkouts checkouts, }) { final NextCommand command = NextCommand( checkouts: checkouts, ); return CommandRunner<void>('codesign-test', '')..addCommand(command); } test('throws if no state file found', () async { final FakeProcessManager processManager = FakeProcessManager.list( <FakeCommand>[], ); final FakePlatform platform = FakePlatform( environment: <String, String>{ 'HOME': <String>['path', 'to', 'home'].join(localPathSeparator), }, operatingSystem: localOperatingSystem, pathSeparator: localPathSeparator, ); final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: fileSystem.directory(checkoutsParentDirectory)..createSync(recursive: true), platform: platform, processManager: processManager, stdio: stdio, ); final CommandRunner<void> runner = createRunner(checkouts: checkouts); expect( () async => runner.run(<String>[ 'next', '--$kStateOption', stateFile, ]), throwsExceptionWith('No persistent state file found at $stateFile'), ); }); group('APPLY_ENGINE_CHERRYPICKS to VERIFY_ENGINE_CI', () { test('confirms to stdout when all engine cherrypicks were auto-applied', () async { stdio.stdin.add('n'); final File ciYaml = fileSystem.file('$checkoutsParentDirectory/engine/.ci.yaml') ..createSync(recursive: true); _initializeCiYamlFile(ciYaml); final FakeProcessManager processManager = FakeProcessManager.empty(); final FakePlatform platform = FakePlatform( environment: <String, String>{ 'HOME': <String>['path', 'to', 'home'].join(localPathSeparator), }, operatingSystem: localOperatingSystem, pathSeparator: localPathSeparator, ); final pb.ConductorState state = (pb.ConductorState.create() ..releaseChannel = releaseChannel ..engine = (pb.Repository.create() ..candidateBranch = candidateBranch ..cherrypicks.add(pb.Cherrypick.create() ..trunkRevision ='abc123' ..state = pb.CherrypickState.COMPLETED ) ..checkoutPath = fileSystem.path.join(checkoutsParentDirectory, 'engine') ..workingBranch = workingBranch ..upstream = (pb.Remote.create() ..name = 'upstream' ..url = remoteUrl ) ..mirror = (pb.Remote.create() ..name = 'mirror' ..url = remoteUrl ) ) ..currentPhase = ReleasePhase.APPLY_ENGINE_CHERRYPICKS ); writeStateToFile( fileSystem.file(stateFile), state, <String>[], ); final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: fileSystem.directory(checkoutsParentDirectory)..createSync(recursive: true), platform: platform, processManager: processManager, stdio: stdio, ); final CommandRunner<void> runner = createRunner(checkouts: checkouts); await runner.run(<String>[ 'next', '--$kStateOption', stateFile, ]); expect(processManager, hasNoRemainingExpectations); expect( stdio.stdout, contains('All engine cherrypicks have been auto-applied by the conductor'), ); }); test('updates lastPhase if user responds yes', () async { const String remoteUrl = 'https://github.com/org/repo.git'; const String releaseChannel = 'beta'; stdio.stdin.add('y'); final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['git', 'fetch', 'upstream'], ), FakeCommand( command: const <String>['git', 'checkout', workingBranch], onRun: (_) { final File file = fileSystem.file('$checkoutsParentDirectory/engine/.ci.yaml') ..createSync(recursive: true); _initializeCiYamlFile(file); }, ), const FakeCommand(command: <String>['git', 'push', 'mirror', 'HEAD:refs/heads/$workingBranch']), ]); final FakePlatform platform = FakePlatform( environment: <String, String>{ 'HOME': <String>['path', 'to', 'home'].join(localPathSeparator), }, operatingSystem: localOperatingSystem, pathSeparator: localPathSeparator, ); final pb.ConductorState state = (pb.ConductorState.create() ..currentPhase = ReleasePhase.APPLY_ENGINE_CHERRYPICKS ..engine = (pb.Repository.create() ..candidateBranch = candidateBranch ..checkoutPath = fileSystem.path.join(checkoutsParentDirectory, 'engine') ..cherrypicks.add( pb.Cherrypick.create() ..trunkRevision = revision2 ..state = pb.CherrypickState.PENDING ) ..workingBranch = workingBranch ..upstream = (pb.Remote.create() ..name = 'upstream' ..url = remoteUrl ) ..mirror = (pb.Remote.create() ..name = 'mirror' ..url = remoteUrl ) ) ..releaseChannel = releaseChannel ..releaseVersion = releaseVersion ); writeStateToFile( fileSystem.file(stateFile), state, <String>[], ); // engine dir is expected to already exist fileSystem.directory(checkoutsParentDirectory).childDirectory('engine').createSync(recursive: true); final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: fileSystem.directory(checkoutsParentDirectory), platform: platform, processManager: processManager, stdio: stdio, ); final CommandRunner<void> runner = createRunner(checkouts: checkouts); await runner.run(<String>[ 'next', '--$kStateOption', stateFile, ]); final pb.ConductorState finalState = readStateFromFile( fileSystem.file(stateFile), ); expect(processManager, hasNoRemainingExpectations); expect( stdio.stdout, contains('You must now open a pull request at https://github.com/flutter/engine/compare/flutter-1.2-candidate.3...org:cherrypicks-flutter-1.2-candidate.3?expand=1')); expect(stdio.stdout, contains( 'Are you ready to push your engine branch to the repository $remoteUrl? (y/n) ')); expect(finalState.currentPhase, ReleasePhase.VERIFY_ENGINE_CI); expect(stdio.error, isEmpty); }); }); group('VERIFY_ENGINE_CI to APPLY_FRAMEWORK_CHERRYPICKS', () { late pb.ConductorState state; late FakeProcessManager processManager; late FakePlatform platform; setUp(() { state = (pb.ConductorState.create() ..releaseChannel = releaseChannel ..engine = (pb.Repository.create() ..cherrypicks.add( pb.Cherrypick.create() ..trunkRevision = 'abc123' ..state = pb.CherrypickState.PENDING ) ) ..currentPhase = ReleasePhase.VERIFY_ENGINE_CI ); processManager = FakeProcessManager.empty(); platform = FakePlatform( environment: <String, String>{ 'HOME': <String>['path', 'to', 'home'].join(localPathSeparator), }, operatingSystem: localOperatingSystem, pathSeparator: localPathSeparator, ); }); test('does not update currentPhase if user responds no', () async { stdio.stdin.add('n'); writeStateToFile( fileSystem.file(stateFile), state, <String>[], ); final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: fileSystem.directory(checkoutsParentDirectory)..createSync(recursive: true), platform: platform, processManager: processManager, stdio: stdio, ); final CommandRunner<void> runner = createRunner(checkouts: checkouts); await runner.run(<String>[ 'next', '--$kStateOption', stateFile, ]); final pb.ConductorState finalState = readStateFromFile( fileSystem.file(stateFile), ); expect(processManager, hasNoRemainingExpectations); expect(stdio.stdout, contains('Has CI passed for the engine PR?')); expect(finalState.currentPhase, ReleasePhase.VERIFY_ENGINE_CI); expect(stdio.error.contains('Aborting command.'), true); }); test('updates currentPhase if user responds yes', () async { stdio.stdin.add('y'); final FakePlatform platform = FakePlatform( environment: <String, String>{ 'HOME': <String>['path', 'to', 'home'].join(localPathSeparator), }, operatingSystem: localOperatingSystem, pathSeparator: localPathSeparator, ); writeStateToFile( fileSystem.file(stateFile), state, <String>[], ); final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: fileSystem.directory(checkoutsParentDirectory)..createSync(recursive: true), platform: platform, processManager: processManager, stdio: stdio, ); final CommandRunner<void> runner = createRunner(checkouts: checkouts); await runner.run(<String>[ 'next', '--$kStateOption', stateFile, ]); final pb.ConductorState finalState = readStateFromFile( fileSystem.file(stateFile), ); expect(processManager, hasNoRemainingExpectations); expect(stdio.stdout, contains('Has CI passed for the engine PR?')); expect(finalState.currentPhase, ReleasePhase.APPLY_FRAMEWORK_CHERRYPICKS); }); }); group('APPLY_FRAMEWORK_CHERRYPICKS to PUBLISH_VERSION', () { const String mirrorRemoteUrl = 'https://github.com/org/repo.git'; const String upstreamRemoteUrl = 'https://github.com/mirror/repo.git'; const String engineUpstreamRemoteUrl = 'https://github.com/mirror/engine.git'; const String frameworkCheckoutPath = '$checkoutsParentDirectory/framework'; const String engineCheckoutPath = '$checkoutsParentDirectory/engine'; const String oldEngineVersion = '000000001'; const String frameworkCherrypick = '431ae69b4dd2dd48f7ba0153671e0311014c958b'; late FakeProcessManager processManager; late FakePlatform platform; late pb.ConductorState state; setUp(() { processManager = FakeProcessManager.empty(); platform = FakePlatform( environment: <String, String>{ 'HOME': <String>['path', 'to', 'home'].join(localPathSeparator), }, operatingSystem: localOperatingSystem, pathSeparator: localPathSeparator, ); state = (pb.ConductorState.create() ..releaseChannel = releaseChannel ..releaseVersion = releaseVersion ..framework = (pb.Repository.create() ..candidateBranch = candidateBranch ..checkoutPath = frameworkCheckoutPath ..cherrypicks.add( pb.Cherrypick.create() ..trunkRevision = frameworkCherrypick ..state = pb.CherrypickState.PENDING ) ..mirror = (pb.Remote.create() ..name = 'mirror' ..url = mirrorRemoteUrl ) ..upstream = (pb.Remote.create() ..name = 'upstream' ..url = upstreamRemoteUrl ) ..workingBranch = workingBranch ) ..engine = (pb.Repository.create() ..candidateBranch = candidateBranch ..checkoutPath = engineCheckoutPath ..dartRevision = 'cdef0123' ..workingBranch = workingBranch ..upstream = (pb.Remote.create() ..name = 'upstream' ..url = engineUpstreamRemoteUrl ) ) ..currentPhase = ReleasePhase.APPLY_FRAMEWORK_CHERRYPICKS ); // create engine repo fileSystem.directory(engineCheckoutPath).createSync(recursive: true); // create framework repo final Directory frameworkDir = fileSystem.directory(frameworkCheckoutPath); final File engineRevisionFile = frameworkDir .childDirectory('bin') .childDirectory('internal') .childFile('engine.version'); engineRevisionFile.createSync(recursive: true); engineRevisionFile.writeAsStringSync(oldEngineVersion, flush: true); }); test('with no dart, engine or framework cherrypicks, updates engine revision if version mismatch', () async { stdio.stdin.add('n'); processManager.addCommands(<FakeCommand>[ const FakeCommand(command: <String>['git', 'fetch', 'upstream']), // we want merged upstream commit, not local working commit const FakeCommand(command: <String>['git', 'checkout', 'upstream/$candidateBranch']), const FakeCommand( command: <String>['git', 'rev-parse', 'HEAD'], stdout: revision1, ), const FakeCommand(command: <String>['git', 'fetch', 'upstream']), FakeCommand( command: const <String>['git', 'checkout', workingBranch], onRun: (_) { final File file = fileSystem.file('$checkoutsParentDirectory/framework/.ci.yaml') ..createSync(); _initializeCiYamlFile(file); }, ), const FakeCommand( command: <String>['git', 'status', '--porcelain'], stdout: 'MM bin/internal/release-candidate-branch.version', ), const FakeCommand(command: <String>['git', 'add', '--all']), const FakeCommand(command: <String>[ 'git', 'commit', '--message', 'Create candidate branch version $candidateBranch for $releaseChannel', ]), const FakeCommand( command: <String>['git', 'rev-parse', 'HEAD'], stdout: revision3, ), const FakeCommand( command: <String>['git', 'status', '--porcelain'], stdout: 'MM bin/internal/engine.version', ), const FakeCommand(command: <String>['git', 'add', '--all']), const FakeCommand(command: <String>[ 'git', 'commit', '--message', 'Update Engine revision to $revision1 for $releaseChannel release $releaseVersion', ]), const FakeCommand( command: <String>['git', 'rev-parse', 'HEAD'], stdout: revision4, ), ]); final pb.ConductorState state = (pb.ConductorState.create() ..releaseChannel = releaseChannel ..releaseVersion = releaseVersion ..currentPhase = ReleasePhase.APPLY_FRAMEWORK_CHERRYPICKS ..framework = (pb.Repository.create() ..candidateBranch = candidateBranch ..checkoutPath = frameworkCheckoutPath ..mirror = (pb.Remote.create() ..name = 'mirror' ..url = mirrorRemoteUrl ) ..upstream = (pb.Remote.create() ..name = 'upstream' ..url = upstreamRemoteUrl ) ..workingBranch = workingBranch ) ..engine = (pb.Repository.create() ..candidateBranch = candidateBranch ..checkoutPath = engineCheckoutPath ..upstream = (pb.Remote.create() ..name = 'upstream' ..url = engineUpstreamRemoteUrl ) ..currentGitHead = revision1 ) ); writeStateToFile( fileSystem.file(stateFile), state, <String>[], ); final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: fileSystem.directory(checkoutsParentDirectory)..createSync(recursive: true), platform: platform, processManager: processManager, stdio: stdio, ); final CommandRunner<void> runner = createRunner(checkouts: checkouts); await runner.run(<String>[ 'next', '--$kStateOption', stateFile, ]); expect(processManager, hasNoRemainingExpectations); expect(stdio.stdout, contains('release-candidate-branch.version containing $candidateBranch')); expect(stdio.stdout, contains('Updating engine revision from $oldEngineVersion to $revision1')); expect(stdio.stdout, contains('Are you ready to push your framework branch')); }); test('with no engine cherrypicks but a dart revision update, updates engine revision', () async { stdio.stdin.add('n'); processManager.addCommands(<FakeCommand>[ const FakeCommand(command: <String>['git', 'fetch', 'upstream']), // we want merged upstream commit, not local working commit const FakeCommand(command: <String>['git', 'checkout', 'upstream/$candidateBranch']), const FakeCommand( command: <String>['git', 'rev-parse', 'HEAD'], stdout: revision1, ), const FakeCommand(command: <String>['git', 'fetch', 'upstream']), FakeCommand( command: const <String>['git', 'checkout', workingBranch], onRun: (_) { final File file = fileSystem.file('$checkoutsParentDirectory/framework/.ci.yaml') ..createSync(); _initializeCiYamlFile(file); }, ), const FakeCommand( command: <String>['git', 'status', '--porcelain'], stdout: 'MM bin/internal/release-candidate-branch.version', ), const FakeCommand(command: <String>['git', 'add', '--all']), const FakeCommand(command: <String>[ 'git', 'commit', '--message', 'Create candidate branch version $candidateBranch for $releaseChannel', ]), const FakeCommand( command: <String>['git', 'rev-parse', 'HEAD'], stdout: revision3, ), const FakeCommand( command: <String>['git', 'status', '--porcelain'], stdout: 'MM bin/internal/engine.version', ), const FakeCommand(command: <String>['git', 'add', '--all']), const FakeCommand(command: <String>[ 'git', 'commit', '--message', 'Update Engine revision to $revision1 for $releaseChannel release $releaseVersion', ]), const FakeCommand( command: <String>['git', 'rev-parse', 'HEAD'], stdout: revision4, ), ]); final pb.ConductorState state = (pb.ConductorState.create() ..releaseChannel = releaseChannel ..releaseVersion = releaseVersion ..currentPhase = ReleasePhase.APPLY_FRAMEWORK_CHERRYPICKS ..framework = (pb.Repository.create() ..candidateBranch = candidateBranch ..checkoutPath = frameworkCheckoutPath ..mirror = (pb.Remote.create() ..name = 'mirror' ..url = mirrorRemoteUrl ) ..upstream = (pb.Remote.create() ..name = 'upstream' ..url = upstreamRemoteUrl ) ..workingBranch = workingBranch ) ..engine = (pb.Repository.create() ..candidateBranch = candidateBranch ..checkoutPath = engineCheckoutPath ..upstream = (pb.Remote.create() ..name = 'upstream' ..url = engineUpstreamRemoteUrl ) ..dartRevision = 'abc123' ) ); writeStateToFile( fileSystem.file(stateFile), state, <String>[], ); final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: fileSystem.directory(checkoutsParentDirectory)..createSync(recursive: true), platform: platform, processManager: processManager, stdio: stdio, ); final CommandRunner<void> runner = createRunner(checkouts: checkouts); await runner.run(<String>[ 'next', '--$kStateOption', stateFile, ]); expect(processManager, hasNoRemainingExpectations); expect(stdio.stdout, contains('release-candidate-branch.version containing $candidateBranch')); expect(stdio.stdout, contains('Updating engine revision from $oldEngineVersion to $revision1')); expect(stdio.stdout, contains('Are you ready to push your framework branch')); }); test('does not update state.currentPhase if user responds no', () async { stdio.stdin.add('n'); processManager.addCommands(<FakeCommand>[ const FakeCommand(command: <String>['git', 'fetch', 'upstream']), // we want merged upstream commit, not local working commit FakeCommand( command: const <String>['git', 'checkout', 'upstream/$candidateBranch'], onRun: (_) { final File file = fileSystem.file('$checkoutsParentDirectory/framework/.ci.yaml') ..createSync(); _initializeCiYamlFile(file); }, ), const FakeCommand( command: <String>['git', 'rev-parse', 'HEAD'], stdout: revision1, ), const FakeCommand(command: <String>['git', 'fetch', 'upstream']), const FakeCommand(command: <String>['git', 'checkout', workingBranch]), const FakeCommand( command: <String>['git', 'status', '--porcelain'], stdout: 'MM bin/internal/release-candidate-branch.version', ), const FakeCommand(command: <String>['git', 'add', '--all']), const FakeCommand(command: <String>[ 'git', 'commit', '--message', 'Create candidate branch version $candidateBranch for $releaseChannel', ]), const FakeCommand( command: <String>['git', 'rev-parse', 'HEAD'], stdout: revision3, ), const FakeCommand( command: <String>['git', 'status', '--porcelain'], stdout: 'MM bin/internal/engine.version', ), const FakeCommand(command: <String>['git', 'add', '--all']), const FakeCommand(command: <String>[ 'git', 'commit', '--message', 'Update Engine revision to $revision1 for $releaseChannel release $releaseVersion', ]), const FakeCommand( command: <String>['git', 'rev-parse', 'HEAD'], stdout: revision4, ), ]); writeStateToFile( fileSystem.file(stateFile), state, <String>[], ); final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: fileSystem.directory(checkoutsParentDirectory)..createSync(recursive: true), platform: platform, processManager: processManager, stdio: stdio, ); final CommandRunner<void> runner = createRunner(checkouts: checkouts); await runner.run(<String>[ 'next', '--$kStateOption', stateFile, ]); final pb.ConductorState finalState = readStateFromFile( fileSystem.file(stateFile), ); expect(stdio.stdout, contains('Are you ready to push your framework branch to the repository $mirrorRemoteUrl? (y/n) ')); expect(stdio.error, contains('Aborting command.')); expect(finalState.currentPhase, ReleasePhase.APPLY_FRAMEWORK_CHERRYPICKS); }); test('updates state.currentPhase if user responds yes', () async { stdio.stdin.add('y'); processManager.addCommands(<FakeCommand>[ // Engine repo const FakeCommand(command: <String>['git', 'fetch', 'upstream']), // we want merged upstream commit, not local working commit const FakeCommand(command: <String>['git', 'checkout', 'upstream/$candidateBranch']), const FakeCommand( command: <String>['git', 'rev-parse', 'HEAD'], stdout: revision1, ), // Framework repo const FakeCommand(command: <String>['git', 'fetch', 'upstream']), FakeCommand( command: const <String>['git', 'checkout', workingBranch], onRun: (_) { final File file = fileSystem.file('$checkoutsParentDirectory/framework/.ci.yaml') ..createSync(); _initializeCiYamlFile(file); }, ), const FakeCommand( command: <String>['git', 'status', '--porcelain'], stdout: 'MM bin/internal/release-candidate-branch.version', ), const FakeCommand(command: <String>['git', 'add', '--all']), const FakeCommand(command: <String>[ 'git', 'commit', '--message', 'Create candidate branch version $candidateBranch for $releaseChannel', ]), const FakeCommand( command: <String>['git', 'rev-parse', 'HEAD'], stdout: revision3, ), const FakeCommand( command: <String>['git', 'status', '--porcelain'], stdout: 'MM bin/internal/engine.version', ), const FakeCommand(command: <String>['git', 'add', '--all']), const FakeCommand(command: <String>[ 'git', 'commit', '--message', 'Update Engine revision to $revision1 for $releaseChannel release $releaseVersion', ]), const FakeCommand( command: <String>['git', 'rev-parse', 'HEAD'], stdout: revision4, ), const FakeCommand( command: <String>['git', 'push', 'mirror', 'HEAD:refs/heads/$workingBranch'], ), ]); writeStateToFile( fileSystem.file(stateFile), state, <String>[], ); final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: fileSystem.directory(checkoutsParentDirectory)..createSync(recursive: true), platform: platform, processManager: processManager, stdio: stdio, ); final CommandRunner<void> runner = createRunner(checkouts: checkouts); await runner.run(<String>[ 'next', '--$kStateOption', stateFile, ]); final pb.ConductorState finalState = readStateFromFile( fileSystem.file(stateFile), ); expect(finalState.currentPhase, ReleasePhase.PUBLISH_VERSION); expect( stdio.stdout, contains('Rolling new engine hash $revision1 to framework checkout...'), ); expect( stdio.stdout, contains('There was 1 cherrypick that was not auto-applied'), ); expect( stdio.stdout, contains('Are you ready to push your framework branch to the repository $mirrorRemoteUrl? (y/n)'), ); expect( stdio.stdout, contains('Executed command: `git push mirror HEAD:refs/heads/$workingBranch`'), ); expect(stdio.error, isEmpty); }); }); group('PUBLISH_VERSION to VERIFY_RELEASE', () { const String releaseVersion = '1.2.0-3.0.pre'; late pb.ConductorState state; setUp(() { state = (pb.ConductorState.create() ..releaseChannel = releaseChannel ..currentPhase = ReleasePhase.PUBLISH_VERSION ..framework = (pb.Repository.create() ..candidateBranch = candidateBranch ..upstream = (pb.Remote.create() ..url = FrameworkRepository.defaultUpstream ) ) ..engine = (pb.Repository.create() ..candidateBranch = candidateBranch ..upstream = (pb.Remote.create() ..url = EngineRepository.defaultUpstream ) ) ..releaseVersion = releaseVersion ); }); test('gives push command and updates state.currentPhase', () async { stdio.stdin.add('y'); final FakeProcessManager processManager = FakeProcessManager.empty(); final FakePlatform platform = FakePlatform( environment: <String, String>{ 'HOME': <String>['path', 'to', 'home'].join(localPathSeparator), }, operatingSystem: localOperatingSystem, pathSeparator: localPathSeparator, ); writeStateToFile( fileSystem.file(stateFile), state, <String>[], ); final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: fileSystem.directory(checkoutsParentDirectory)..createSync(recursive: true), platform: platform, processManager: processManager, stdio: stdio, ); final CommandRunner<void> runner = createRunner(checkouts: checkouts); await runner.run(<String>[ 'next', '--$kStateOption', stateFile, ]); final pb.ConductorState finalState = readStateFromFile( fileSystem.file(stateFile), ); expect(processManager, hasNoRemainingExpectations); expect(finalState.currentPhase, ReleasePhase.VERIFY_RELEASE); expect(stdio.stdout, contains('Run the following command, and ask a Googler')); expect(stdio.stdout, contains(':tag $releaseVersion')); expect(stdio.stdout, contains(':git_branch ${state.framework.candidateBranch}')); expect(stdio.stdout, contains(':release_channel ${state.releaseChannel}')); expect(finalState.logs, stdio.logs); }); }); test('throws exception if state.currentPhase is RELEASE_COMPLETED', () async { final FakeProcessManager processManager = FakeProcessManager.empty(); final FakePlatform platform = FakePlatform( environment: <String, String>{ 'HOME': <String>['path', 'to', 'home'].join(localPathSeparator), }, operatingSystem: localOperatingSystem, pathSeparator: localPathSeparator, ); final pb.ConductorState state = pb.ConductorState.create() ..currentPhase = ReleasePhase.RELEASE_COMPLETED; writeStateToFile( fileSystem.file(stateFile), state, <String>[], ); final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: fileSystem.directory(checkoutsParentDirectory)..createSync(recursive: true), platform: platform, processManager: processManager, stdio: stdio, ); final CommandRunner<void> runner = createRunner(checkouts: checkouts); expect( () async => runner.run(<String>[ 'next', '--$kStateOption', stateFile, ]), throwsExceptionWith('This release is finished.'), ); }); }, onPlatform: <String, dynamic>{ 'windows': const Skip('Flutter Conductor only supported on macos/linux'), }); group('prompt', () { test('can be overridden for different frontend implementations', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final Stdio stdio = _UnimplementedStdio.instance; final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: fileSystem.directory('/'), platform: FakePlatform(), processManager: FakeProcessManager.empty(), stdio: stdio, ); final _TestNextContext context = _TestNextContext( checkouts: checkouts, stateFile: fileSystem.file('/statefile.json'), ); final bool response = await context.prompt( 'A prompt that will immediately be agreed to', ); expect(response, true); }); test('throws if user inputs character that is not "y" or "n"', () { final FileSystem fileSystem = MemoryFileSystem.test(); final TestStdio stdio = TestStdio( stdin: <String>['x'], verbose: true, ); final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: fileSystem.directory('/'), platform: FakePlatform(), processManager: FakeProcessManager.empty(), stdio: stdio, ); final NextContext context = NextContext( autoAccept: false, force: false, checkouts: checkouts, stateFile: fileSystem.file('/statefile.json'), ); expect( () => context.prompt('Asking a question?'), throwsExceptionWith('Unknown user input (expected "y" or "n")'), ); }); }); group('.pushWorkingBranch()', () { late MemoryFileSystem fileSystem; late TestStdio stdio; late Platform platform; setUp(() { stdio = TestStdio(); fileSystem = MemoryFileSystem.test(); platform = FakePlatform(); }); test('catches GitException if the push was rejected and instead throws a helpful ConductorException', () async { const String gitPushErrorMessage = ''' To github.com:user/engine.git ! [rejected] HEAD -> cherrypicks-flutter-2.8-candidate.3 (non-fast-forward) error: failed to push some refs to 'github.com:user/engine.git' hint: Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. '''; final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: fileSystem.directory(checkoutsParentDirectory)..createSync(recursive: true), platform: platform, processManager: FakeProcessManager.empty(), stdio: stdio, ); final Repository testRepository = _TestRepository.fromCheckouts(checkouts); final pb.Repository testPbRepository = pb.Repository(); (checkouts.processManager as FakeProcessManager).addCommands(<FakeCommand>[ FakeCommand( command: <String>['git', 'clone', '--origin', 'upstream', '--', testRepository.upstreamRemote.url, '/flutter/dev/conductor/flutter_conductor_checkouts/test-repo/test-repo'], ), const FakeCommand( command: <String>['git', 'rev-parse', 'HEAD'], stdout: revision1, ), FakeCommand( command: const <String>['git', 'push', '', 'HEAD:refs/heads/'], exception: GitException(gitPushErrorMessage, <String>['git', 'push', '--force', '', 'HEAD:refs/heads/']), ), ]); final NextContext nextContext = NextContext( autoAccept: false, checkouts: checkouts, force: false, stateFile: fileSystem.file(stateFile), ); expect( () => nextContext.pushWorkingBranch(testRepository, testPbRepository), throwsA(isA<ConductorException>().having( (ConductorException exception) => exception.message, 'has correct message', contains('Re-run this command with --force to overwrite the remote branch'), )), ); }); }); } /// A [Stdio] that will throw an exception if any of its methods are called. class _UnimplementedStdio extends Fake implements Stdio { _UnimplementedStdio(); static final _UnimplementedStdio instance = _UnimplementedStdio(); } class _TestRepository extends Repository { _TestRepository.fromCheckouts(Checkouts checkouts, [String name = 'test-repo']) : super( fileSystem: checkouts.fileSystem, parentDirectory: checkouts.directory.childDirectory(name), platform: checkouts.platform, processManager: checkouts.processManager, name: name, requiredLocalBranches: <String>[], stdio: checkouts.stdio, upstreamRemote: const Remote(name: RemoteName.upstream, url: '[email protected]:upstream/repo.git'), ); @override Future<_TestRepository> cloneRepository(String? cloneName) async { throw Exception('Unimplemented!'); } } class _TestNextContext extends NextContext { const _TestNextContext({ required super.stateFile, required super.checkouts, }) : super(autoAccept: false, force: false); @override Future<bool> prompt(String message) { // always say yes return Future<bool>.value(true); } } void _initializeCiYamlFile( File file, { List<String>? enabledBranches, }) { enabledBranches ??= <String>['master', 'beta', 'stable']; file.createSync(recursive: true); final StringBuffer buffer = StringBuffer('enabled_branches:\n'); for (final String branch in enabledBranches) { buffer.writeln(' - $branch'); } buffer.writeln(''' platform_properties: linux: properties: caches: ["name":"openjdk","path":"java"] targets: - name: Linux analyze recipe: flutter/flutter timeout: 60 properties: tags: > ["framework","hostonly"] validation: analyze validation_name: Analyze scheduler: luci '''); file.writeAsStringSync(buffer.toString()); }
flutter/dev/conductor/core/test/next_test.dart/0
{ "file_path": "flutter/dev/conductor/core/test/next_test.dart", "repo_id": "flutter", "token_count": 17553 }
561
// Copyright 2014 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'; import 'dart:io'; import 'package:args/args.dart'; import 'package:flutter_devicelab/framework/ab.dart'; import 'package:flutter_devicelab/framework/runner.dart'; import 'package:flutter_devicelab/framework/task_result.dart'; import 'package:flutter_devicelab/framework/utils.dart'; /// Runs tasks. /// /// The tasks are chosen depending on the command-line options. Future<void> main(List<String> rawArgs) async { // This is populated by a callback in the ArgParser. final List<String> taskNames = <String>[]; final ArgParser argParser = createArgParser(taskNames); ArgResults args; try { args = argParser.parse(rawArgs); // populates taskNames as a side-effect } on FormatException catch (error) { stderr.writeln('${error.message}\n'); stderr.writeln('Usage:\n'); stderr.writeln(argParser.usage); exit(1); } /// Suppresses standard output, prints only standard error output. final bool silent = (args['silent'] as bool?) ?? false; /// The build of the local engine to use. /// /// Required for A/B test mode. final String? localEngine = args['local-engine'] as String?; /// The build of the local engine to use as the host platform. /// /// Required if [localEngine] is set. final String? localEngineHost = args['local-engine-host'] as String?; /// The build of the local Web SDK to use. /// /// Required for A/B test mode. final String? localWebSdk = args['local-web-sdk'] as String?; /// The path to the engine "src/" directory. final String? localEngineSrcPath = args['local-engine-src-path'] as String?; /// The device-id to run test on. final String? deviceId = args['device-id'] as String?; /// Whether to exit on first test failure. final bool exitOnFirstTestFailure = (args['exit'] as bool?) ?? false; /// Whether to tell tasks to clean up after themselves. final bool terminateStrayDartProcesses = (args['terminate-stray-dart-processes'] as bool?) ?? false; /// The git branch being tested on. final String? gitBranch = args['git-branch'] as String?; /// Name of the LUCI builder this test is currently running on. /// /// This is only passed on CI runs for Cocoon to be able to uniquely identify /// this test run. final String? luciBuilder = args['luci-builder'] as String?; /// Path to write test results to. final String? resultsPath = args['results-file'] as String?; /// Use an emulator for this test if it is an android test. final bool useEmulator = (args['use-emulator'] as bool?) ?? false; if (args.wasParsed('list')) { for (int i = 0; i < taskNames.length; i++) { print('${(i + 1).toString().padLeft(3)} - ${taskNames[i]}'); } exit(0); } if (taskNames.isEmpty) { stderr.writeln('Failed to find tasks to run based on supplied options.'); exit(1); } if (args.wasParsed('ab')) { final int runsPerTest = int.parse(args['ab'] as String); final String resultsFile = args['ab-result-file'] as String? ?? 'ABresults#.json'; if (taskNames.length > 1) { stderr.writeln('When running in A/B test mode exactly one task must be passed but got ${taskNames.join(', ')}.\n'); stderr.writeln(argParser.usage); exit(1); } if (localEngine == null && localWebSdk == null) { stderr.writeln('When running in A/B test mode --local-engine or --local-web-sdk is required.\n'); stderr.writeln(argParser.usage); exit(1); } if (localEngineHost == null) { stderr.writeln('When running in A/B test mode --local-engine-host is required.\n'); stderr.writeln(argParser.usage); exit(1); } await _runABTest( runsPerTest: runsPerTest, silent: silent, localEngine: localEngine, localEngineHost: localEngineHost, localWebSdk: localWebSdk, localEngineSrcPath: localEngineSrcPath, deviceId: deviceId, resultsFile: resultsFile, taskName: taskNames.single, ); } else { await runTasks(taskNames, silent: silent, localEngine: localEngine, localEngineHost: localEngineHost, localEngineSrcPath: localEngineSrcPath, deviceId: deviceId, exitOnFirstTestFailure: exitOnFirstTestFailure, terminateStrayDartProcesses: terminateStrayDartProcesses, gitBranch: gitBranch, luciBuilder: luciBuilder, resultsPath: resultsPath, useEmulator: useEmulator, ); } } Future<void> _runABTest({ required int runsPerTest, required bool silent, required String? localEngine, required String localEngineHost, required String? localWebSdk, required String? localEngineSrcPath, required String? deviceId, required String resultsFile, required String taskName, }) async { print('$taskName A/B test. Will run $runsPerTest times.'); assert(localEngine != null || localWebSdk != null); final ABTest abTest = ABTest( localEngine: (localEngine ?? localWebSdk)!, localEngineHost: localEngineHost, taskName: taskName, ); for (int i = 1; i <= runsPerTest; i++) { section('Run #$i'); print('Running with the default engine (A)'); final TaskResult defaultEngineResult = await runTask( taskName, silent: silent, deviceId: deviceId, ); print('Default engine result:'); print(const JsonEncoder.withIndent(' ').convert(defaultEngineResult)); if (!defaultEngineResult.succeeded) { stderr.writeln('Task failed on the default engine.'); exit(1); } abTest.addAResult(defaultEngineResult); print('Running with the local engine (B)'); final TaskResult localEngineResult = await runTask( taskName, silent: silent, localEngine: localEngine, localEngineHost: localEngineHost, localWebSdk: localWebSdk, localEngineSrcPath: localEngineSrcPath, deviceId: deviceId, ); print('Task localEngineResult:'); print(const JsonEncoder.withIndent(' ').convert(localEngineResult)); if (!localEngineResult.succeeded) { stderr.writeln('Task failed on the local engine.'); exit(1); } abTest.addBResult(localEngineResult); if (!silent && i < runsPerTest) { section('A/B results so far'); print(abTest.printSummary()); } } abTest.finalize(); final File jsonFile = _uniqueFile(resultsFile); jsonFile.writeAsStringSync(const JsonEncoder.withIndent(' ').convert(abTest.jsonMap)); if (!silent) { section('Raw results'); print(abTest.rawResults()); } section('Final A/B results'); print(abTest.printSummary()); print(''); print('Results saved to ${jsonFile.path}'); } File _uniqueFile(String filenameTemplate) { final List<String> parts = filenameTemplate.split('#'); if (parts.length != 2) { return File(filenameTemplate); } File file = File(parts[0] + parts[1]); int i = 1; while (file.existsSync()) { file = File(parts[0] + i.toString() + parts[1]); i++; } return file; } ArgParser createArgParser(List<String> taskNames) { return ArgParser() ..addMultiOption( 'task', abbr: 't', help: 'Name of a Dart file in bin/tasks.\n' ' Example: complex_layout__start_up\n' '\n' 'This option may be repeated to specify multiple tasks.', callback: (List<String> tasks) { taskNames.addAll(tasks); }, ) ..addOption( 'device-id', abbr: 'd', help: 'Target device id (prefixes are allowed, names are not supported).\n' 'The option will be ignored if the test target does not run on a\n' 'mobile device. This still respects the device operating system\n' 'settings in the test case, and will results in error if no device\n' 'with given ID/ID prefix is found.', ) ..addOption( 'ab', help: 'Runs an A/B test comparing the default engine with the local\n' 'engine build for one task. This option does not support running\n' 'multiple tasks. The value is the number of times to run the task.\n' 'The task is expected to be a benchmark that reports score keys.\n' 'The A/B test collects the metrics collected by the test and\n' 'produces a report containing averages, noise, and the speed-up\n' 'between the two engines. --local-engine is required when running\n' 'an A/B test.', callback: (String? value) { if (value != null && int.tryParse(value) == null) { throw ArgParserException('Option --ab must be a number, but was "$value".'); } }, ) ..addOption( 'ab-result-file', help: 'The filename in which to place the json encoded results of an A/B test.\n' 'The filename may contain a single # character to be replaced by a sequence\n' 'number if the name already exists.', ) ..addFlag( 'exit', help: 'Exit on the first test failure. Currently flakes are intentionally (though ' 'incorrectly) not considered to be failures.', ) ..addOption( 'git-branch', help: '[Flutter infrastructure] Git branch of the current commit. LUCI\n' 'checkouts run in detached HEAD state, so the branch must be passed.', ) ..addOption( 'local-engine', help: 'Name of a build output within the engine out directory, if you\n' 'are building Flutter locally. Use this to select a specific\n' 'version of the engine if you have built multiple engine targets.\n' 'This path is relative to --local-engine-src-path/out. This option\n' 'is required when running an A/B test (see the --ab option).', ) ..addOption( 'local-engine-host', help: 'Name of a build output within the engine out directory, if you\n' 'are building Flutter locally. Use this to select a specific\n' 'version of the engine to use as the host platform if you have built ' 'multiple engine targets.\n' 'This path is relative to --local-engine-src-path/out. This option\n' 'is required when running an A/B test (see the --ab option).', ) ..addOption( 'local-web-sdk', help: 'Name of a build output within the engine out directory, if you\n' 'are building Flutter locally. Use this to select a specific\n' 'version of the engine if you have built multiple engine targets.\n' 'This path is relative to --local-engine-src-path/out. This option\n' 'is required when running an A/B test (see the --ab option).', ) ..addFlag( 'list', abbr: 'l', help: "Don't actually run the tasks, but list out the tasks that would\n" 'have been run, in the order they would have run.', ) ..addOption( 'local-engine-src-path', help: 'Path to your engine src directory, if you are building Flutter\n' 'locally. Defaults to \$FLUTTER_ENGINE if set, or tries to guess at\n' 'the location based on the value of the --flutter-root option.', ) ..addOption('luci-builder', help: '[Flutter infrastructure] Name of the LUCI builder being run on.') ..addOption( 'results-file', help: '[Flutter infrastructure] File path for test results. If passed with\n' 'task, will write test results to the file.' ) ..addOption( 'service-account-token-file', help: '[Flutter infrastructure] Authentication for uploading results.', ) ..addFlag( 'silent', help: 'Reduce verbosity slightly.', ) ..addFlag( 'terminate-stray-dart-processes', defaultsTo: true, help: 'Whether to send a SIGKILL signal to any Dart processes that are still ' 'running when a task is completed. If any Dart processes are terminated ' 'in this way, the test is considered to have failed.', ) ..addFlag( 'use-emulator', help: 'If this is an android test, use an emulator to run the test instead of ' 'a physical device.' ) ..addMultiOption( 'test', hide: true, callback: (List<String> value) { if (value.isNotEmpty) { throw const FormatException( 'Invalid option --test. Did you mean --task (-t)?', ); } }, ); }
flutter/dev/devicelab/bin/run.dart/0
{ "file_path": "flutter/dev/devicelab/bin/run.dart", "repo_id": "flutter", "token_count": 4706 }
562
// Copyright 2014 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_devicelab/framework/devices.dart'; import 'package:flutter_devicelab/framework/framework.dart'; import 'package:flutter_devicelab/framework/task_result.dart'; import 'package:flutter_devicelab/tasks/gallery.dart'; Future<void> main() async { deviceOperatingSystem = DeviceOperatingSystem.android; await task(() async { final TaskResult withoutSemantics = await createGalleryTransitionTest()(); final TaskResult withSemantics = await createGalleryTransitionTest(semanticsEnabled: true)(); final bool withSemanticsDataMissing = withSemantics.benchmarkScoreKeys == null || withSemantics.benchmarkScoreKeys!.isEmpty; final bool withoutSemanticsDataMissing = withoutSemantics.benchmarkScoreKeys == null || withoutSemantics.benchmarkScoreKeys!.isEmpty; if (withSemanticsDataMissing || withoutSemanticsDataMissing) { String message = 'Lack of data'; if (withSemanticsDataMissing) { message += ' for test with semantics'; if (withoutSemanticsDataMissing) { message += ' and without semantics'; } } else { message += 'for test without semantics'; } return TaskResult.failure(message); } final List<String> benchmarkScoreKeys = <String>[]; final Map<String, dynamic> data = <String, dynamic>{}; for (final String key in withSemantics.benchmarkScoreKeys!) { final String deltaKey = 'delta_$key'; data[deltaKey] = (withSemantics.data![key] as num) - (withoutSemantics.data![key] as num); data['semantics_$key'] = withSemantics.data![key]; data[key] = withoutSemantics.data![key]; benchmarkScoreKeys.add(deltaKey); } return TaskResult.success(data, benchmarkScoreKeys: benchmarkScoreKeys); }); }
flutter/dev/devicelab/bin/tasks/flutter_gallery__transition_perf_with_semantics.dart/0
{ "file_path": "flutter/dev/devicelab/bin/tasks/flutter_gallery__transition_perf_with_semantics.dart", "repo_id": "flutter", "token_count": 636 }
563
// Copyright 2014 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' show Completer, StreamSubscription; import 'dart:io' show Directory, Process; import 'package:flutter_devicelab/framework/devices.dart' show Device, DeviceOperatingSystem, deviceOperatingSystem, devices; import 'package:flutter_devicelab/framework/framework.dart' show task; import 'package:flutter_devicelab/framework/task_result.dart' show TaskResult; import 'package:flutter_devicelab/framework/utils.dart' show dir, flutter, flutterDirectory, inDirectory, startFlutter; import 'package:path/path.dart' as path; Future<TaskResult> run() async { deviceOperatingSystem = DeviceOperatingSystem.android; final Device device = await devices.workingDevice; await device.unlock(); final Directory appDir = dir(path.join(flutterDirectory.path, 'examples/hello_world')); bool isUsingValidationLayers = false; bool hasValidationErrors = false; int impellerBackendCount = 0; final Completer<void> didReceiveBackendMessage = Completer<void>(); await inDirectory(appDir, () async { await flutter('packages', options: <String>['get']); final StreamSubscription<String> adb = device.logcat.listen( (String data) { if (data.contains('Using the Impeller rendering backend')) { // Sometimes more than one of these will be printed out if there is a // fallback. if (!didReceiveBackendMessage.isCompleted) { didReceiveBackendMessage.complete(); } impellerBackendCount += 1; } if (data.contains( 'Using the Impeller rendering backend (Vulkan with Validation Layers)')) { isUsingValidationLayers = true; } // "ImpellerValidationBreak" comes from the engine: // https://github.com/flutter/engine/blob/4160ebacdae2081d6f3160432f5f0dd87dbebec1/impeller/base/validation.cc#L40 if (data.contains('ImpellerValidationBreak')) { hasValidationErrors = true; } }, ); final Process process = await startFlutter( 'run', options: <String>[ '--enable-impeller', '-d', device.deviceId, ], ); await didReceiveBackendMessage.future; // Since we are waiting for the lack of errors, there is no determinate // amount of time we can wait. await Future<void>.delayed(const Duration(seconds: 30)); process.stdin.write('q'); await adb.cancel(); }); if (!isUsingValidationLayers || impellerBackendCount != 1) { return TaskResult.failure('Not using Vulkan validation layers.'); } if (hasValidationErrors){ return TaskResult.failure('Impeller validation errors detected.'); } return TaskResult.success(null); } Future<void> main() async { await task(run); }
flutter/dev/devicelab/bin/tasks/hello_world_impeller.dart/0
{ "file_path": "flutter/dev/devicelab/bin/tasks/hello_world_impeller.dart", "repo_id": "flutter", "token_count": 1066 }
564
// Copyright 2014 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:io'; import 'package:flutter_devicelab/framework/framework.dart'; import 'package:flutter_devicelab/framework/task_result.dart'; import 'package:flutter_devicelab/framework/utils.dart'; import 'package:path/path.dart' as path; Future<void> main() async { await task(() async { section('Copy test Flutter App with watchOS Companion'); final Directory tempDir = Directory.systemTemp .createTempSync('flutter_ios_app_with_extensions_test.'); final Directory projectDir = Directory(path.join(tempDir.path, 'app_with_extensions')); try { mkdir(projectDir); recursiveCopy( Directory(path.join(flutterDirectory.path, 'dev', 'integration_tests', 'ios_app_with_extensions')), projectDir, ); section('Create release build'); // This attempts to build the companion watchOS app. However, the watchOS // SDK is not available in CI and therefore the build will fail. // Check to make sure that the tool attempts to build the companion watchOS app. // See https://github.com/flutter/flutter/pull/94190. await inDirectory(projectDir, () async { final String buildOutput = await evalFlutter( 'build', options: <String>['ios', '--no-codesign', '--release', '--verbose'], ); if (!buildOutput.contains('-destination generic/platform=watchOS')) { print(buildOutput); throw TaskResult.failure('Did not try to get watch build settings'); } }); return TaskResult.success(null); } catch (e) { return TaskResult.failure(e.toString()); } finally { rmTree(tempDir); } }); }
flutter/dev/devicelab/bin/tasks/ios_app_with_extensions_test.dart/0
{ "file_path": "flutter/dev/devicelab/bin/tasks/ios_app_with_extensions_test.dart", "repo_id": "flutter", "token_count": 686 }
565
// Copyright 2014 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_devicelab/framework/devices.dart'; import 'package:flutter_devicelab/framework/framework.dart'; import 'package:flutter_devicelab/framework/task_result.dart'; import 'package:flutter_devicelab/tasks/build_test_task.dart'; /// Smoke test of a successful task. Future<void> main(List<String> args) async { deviceOperatingSystem = DeviceOperatingSystem.fake; await task(FakeBuildTestTask(args).call); } class FakeBuildTestTask extends BuildTestTask { FakeBuildTestTask(super.args) : super(runFlutterClean: false) { deviceOperatingSystem = DeviceOperatingSystem.fake; } @override // In prod, tasks always run some unit of work and the test framework assumes // there will be some work done when managing the isolate. To fake this, add a delay. Future<void> build() => Future<void>.delayed(const Duration(milliseconds: 500)); @override Future<TaskResult> test() async { await Future<void>.delayed(const Duration(milliseconds: 500)); return TaskResult.success(<String, String>{'benchmark': 'data'}); } }
flutter/dev/devicelab/bin/tasks/smoke_test_build_test.dart/0
{ "file_path": "flutter/dev/devicelab/bin/tasks/smoke_test_build_test.dart", "repo_id": "flutter", "token_count": 373 }
566
// Copyright 2014 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:convert'; import 'dart:io'; import 'dart:math' as math; import 'package:path/path.dart' as path; import 'package:retry/retry.dart'; import 'utils.dart'; const String DeviceIdEnvName = 'FLUTTER_DEVICELAB_DEVICEID'; class DeviceException implements Exception { const DeviceException(this.message); final String message; @override String toString() => '$DeviceException: $message'; } /// Gets the artifact path relative to the current directory. String getArtifactPath() { return path.normalize( path.join( path.current, '../../bin/cache/artifacts', ) ); } /// Return the item is in idList if find a match, otherwise return null String? _findMatchId(List<String> idList, String idPattern) { String? candidate; idPattern = idPattern.toLowerCase(); for (final String id in idList) { if (id.toLowerCase() == idPattern) { return id; } if (id.toLowerCase().startsWith(idPattern)) { candidate ??= id; } } return candidate; } /// The root of the API for controlling devices. DeviceDiscovery get devices => DeviceDiscovery(); /// Device operating system the test is configured to test. enum DeviceOperatingSystem { android, androidArm, androidArm64, fake, fuchsia, ios, linux, macos, windows, } /// Device OS to test on. DeviceOperatingSystem deviceOperatingSystem = DeviceOperatingSystem.android; /// Discovers available devices and chooses one to work with. abstract class DeviceDiscovery { factory DeviceDiscovery() { switch (deviceOperatingSystem) { case DeviceOperatingSystem.android: return AndroidDeviceDiscovery(); case DeviceOperatingSystem.androidArm: return AndroidDeviceDiscovery(cpu: AndroidCPU.arm); case DeviceOperatingSystem.androidArm64: return AndroidDeviceDiscovery(cpu: AndroidCPU.arm64); case DeviceOperatingSystem.ios: return IosDeviceDiscovery(); case DeviceOperatingSystem.fuchsia: return FuchsiaDeviceDiscovery(); case DeviceOperatingSystem.linux: return LinuxDeviceDiscovery(); case DeviceOperatingSystem.macos: return MacosDeviceDiscovery(); case DeviceOperatingSystem.windows: return WindowsDeviceDiscovery(); case DeviceOperatingSystem.fake: print('Looking for fake devices! You should not see this in release builds.'); return FakeDeviceDiscovery(); } } /// Selects a device to work with, load-balancing between devices if more than /// one are available. /// /// Calling this method does not guarantee that the same device will be /// returned. For such behavior see [workingDevice]. Future<void> chooseWorkingDevice(); /// Selects a device to work with by device ID. Future<void> chooseWorkingDeviceById(String deviceId); /// A device to work with. /// /// Returns the same device when called repeatedly (unlike /// [chooseWorkingDevice]). This is useful when you need to perform multiple /// operations on one. Future<Device> get workingDevice; /// Lists all available devices' IDs. Future<List<String>> discoverDevices(); /// Checks the health of the available devices. Future<Map<String, HealthCheckResult>> checkDevices(); /// Prepares the system to run tasks. Future<void> performPreflightTasks(); } /// A proxy for one specific device. abstract class Device { // Const constructor so subclasses may be const. const Device(); /// A unique device identifier. String get deviceId; /// Whether the device is awake. Future<bool> isAwake(); /// Whether the device is asleep. Future<bool> isAsleep(); /// Wake up the device if it is not awake. Future<void> wakeUp(); /// Send the device to sleep mode. Future<void> sendToSleep(); /// Emulates pressing the home button. Future<void> home(); /// Emulates pressing the power button, toggling the device's on/off state. Future<void> togglePower(); /// Unlocks the device. /// /// Assumes the device doesn't have a secure unlock pattern. Future<void> unlock(); /// Attempt to reboot the phone, if possible. Future<void> reboot(); /// Emulate a tap on the touch screen. Future<void> tap(int x, int y); /// Read memory statistics for a process. Future<Map<String, dynamic>> getMemoryStats(String packageName); /// Stream the system log from the device. /// /// Flutter applications' `print` statements end up in this log /// with some prefix. Stream<String> get logcat; /// Clears the device logs. /// /// This is important because benchmarks tests rely on the logs produced by /// the flutter run command. /// /// On Android, those logs may contain logs from previous test. Future<void> clearLogs(); /// Whether this device supports calls to [startLoggingToSink] /// and [stopLoggingToSink]. bool get canStreamLogs => false; /// Starts logging to an [IOSink]. /// /// If `clear` is set to true, the log will be cleared before starting. This /// is not supported on all platforms. Future<void> startLoggingToSink(IOSink sink, {bool clear = true}) { throw UnimplementedError(); } /// Stops logging that was started by [startLoggingToSink]. Future<void> stopLoggingToSink() { throw UnimplementedError(); } /// Stop a process. Future<void> stop(String packageName); /// Wait for the device to become ready. Future<void> awaitDevice(); Future<void> uninstallApp() async { await flutter('install', options: <String>[ '--uninstall-only', '-d', deviceId]); await Future<void>.delayed(const Duration(seconds: 2)); await awaitDevice(); } @override String toString() { return 'device: $deviceId'; } } enum AndroidCPU { arm, arm64, } class AndroidDeviceDiscovery implements DeviceDiscovery { factory AndroidDeviceDiscovery({AndroidCPU? cpu}) { return _instance ??= AndroidDeviceDiscovery._(cpu); } AndroidDeviceDiscovery._(this.cpu); final AndroidCPU? cpu; // Parses information about a device. Example: // // 015d172c98400a03 device usb:340787200X product:nakasi model:Nexus_7 device:grouper static final RegExp _kDeviceRegex = RegExp(r'^(\S+)\s+(\S+)(.*)'); static AndroidDeviceDiscovery? _instance; AndroidDevice? _workingDevice; @override Future<AndroidDevice> get workingDevice async { if (_workingDevice == null) { if (Platform.environment.containsKey(DeviceIdEnvName)) { final String deviceId = Platform.environment[DeviceIdEnvName]!; await chooseWorkingDeviceById(deviceId); return _workingDevice!; } await chooseWorkingDevice(); } return _workingDevice!; } Future<bool> _matchesCPURequirement(AndroidDevice device) async { switch (cpu) { case null: return true; case AndroidCPU.arm64: return device.isArm64(); case AndroidCPU.arm: return device.isArm(); } } /// Picks a random Android device out of connected devices and sets it as /// [workingDevice]. @override Future<void> chooseWorkingDevice() async { final List<AndroidDevice> allDevices = (await discoverDevices()) .map<AndroidDevice>((String id) => AndroidDevice(deviceId: id)) .toList(); if (allDevices.isEmpty) { throw const DeviceException('No Android devices detected'); } if (cpu != null) { for (final AndroidDevice device in allDevices) { if (await _matchesCPURequirement(device)) { _workingDevice = device; break; } } } else { // TODO(yjbanov): filter out and warn about those with low battery level _workingDevice = allDevices[math.Random().nextInt(allDevices.length)]; } if (_workingDevice == null) { throw const DeviceException('Cannot find a suitable Android device'); } print('Device chosen: $_workingDevice'); } @override Future<void> chooseWorkingDeviceById(String deviceId) async { final String? matchedId = _findMatchId(await discoverDevices(), deviceId); if (matchedId != null) { _workingDevice = AndroidDevice(deviceId: matchedId); if (cpu != null) { if (!await _matchesCPURequirement(_workingDevice!)) { throw DeviceException('The selected device $matchedId does not match the cpu requirement'); } } print('Choose device by ID: $matchedId'); return; } throw DeviceException( 'Device with ID $deviceId is not found for operating system: ' '$deviceOperatingSystem' ); } @override Future<List<String>> discoverDevices() async { final List<String> output = (await eval(adbPath, <String>['devices', '-l'])) .trim().split('\n'); final List<String> results = <String>[]; for (final String line in output) { // Skip lines like: * daemon started successfully * if (line.startsWith('* daemon ')) { continue; } if (line.startsWith('List of devices')) { continue; } if (_kDeviceRegex.hasMatch(line)) { final Match match = _kDeviceRegex.firstMatch(line)!; final String deviceID = match[1]!; final String deviceState = match[2]!; if (!const <String>['unauthorized', 'offline'].contains(deviceState)) { results.add(deviceID); } } else { throw FormatException('Failed to parse device from adb output: "$line"'); } } return results; } @override Future<Map<String, HealthCheckResult>> checkDevices() async { final Map<String, HealthCheckResult> results = <String, HealthCheckResult>{}; for (final String deviceId in await discoverDevices()) { try { final AndroidDevice device = AndroidDevice(deviceId: deviceId); // Just a smoke test that we can read wakefulness state // TODO(yjbanov): check battery level await device._getWakefulness(); results['android-device-$deviceId'] = HealthCheckResult.success(); } on Exception catch (e, s) { results['android-device-$deviceId'] = HealthCheckResult.error(e, s); } } return results; } @override Future<void> performPreflightTasks() async { // Kills the `adb` server causing it to start a new instance upon next // command. // // Restarting `adb` helps with keeping device connections alive. When `adb` // runs non-stop for too long it loses connections to devices. There may be // a better method, but so far that's the best one I've found. await exec(adbPath, <String>['kill-server']); } } class LinuxDeviceDiscovery implements DeviceDiscovery { factory LinuxDeviceDiscovery() { return _instance ??= LinuxDeviceDiscovery._(); } LinuxDeviceDiscovery._(); static LinuxDeviceDiscovery? _instance; static const LinuxDevice _device = LinuxDevice(); @override Future<Map<String, HealthCheckResult>> checkDevices() async { return <String, HealthCheckResult>{}; } @override Future<void> chooseWorkingDevice() async { } @override Future<void> chooseWorkingDeviceById(String deviceId) async { } @override Future<List<String>> discoverDevices() async { return <String>['linux']; } @override Future<void> performPreflightTasks() async { } @override Future<Device> get workingDevice async => _device; } class MacosDeviceDiscovery implements DeviceDiscovery { factory MacosDeviceDiscovery() { return _instance ??= MacosDeviceDiscovery._(); } MacosDeviceDiscovery._(); static MacosDeviceDiscovery? _instance; static const MacosDevice _device = MacosDevice(); @override Future<Map<String, HealthCheckResult>> checkDevices() async { return <String, HealthCheckResult>{}; } @override Future<void> chooseWorkingDevice() async { } @override Future<void> chooseWorkingDeviceById(String deviceId) async { } @override Future<List<String>> discoverDevices() async { return <String>['macos']; } @override Future<void> performPreflightTasks() async { } @override Future<Device> get workingDevice async => _device; } class WindowsDeviceDiscovery implements DeviceDiscovery { factory WindowsDeviceDiscovery() { return _instance ??= WindowsDeviceDiscovery._(); } WindowsDeviceDiscovery._(); static WindowsDeviceDiscovery? _instance; static const WindowsDevice _device = WindowsDevice(); @override Future<Map<String, HealthCheckResult>> checkDevices() async { return <String, HealthCheckResult>{}; } @override Future<void> chooseWorkingDevice() async { } @override Future<void> chooseWorkingDeviceById(String deviceId) async { } @override Future<List<String>> discoverDevices() async { return <String>['windows']; } @override Future<void> performPreflightTasks() async { } @override Future<Device> get workingDevice async => _device; } class FuchsiaDeviceDiscovery implements DeviceDiscovery { factory FuchsiaDeviceDiscovery() { return _instance ??= FuchsiaDeviceDiscovery._(); } FuchsiaDeviceDiscovery._(); static FuchsiaDeviceDiscovery? _instance; FuchsiaDevice? _workingDevice; String get _ffx { final String ffx = path.join(getArtifactPath(), 'fuchsia', 'tools','x64', 'ffx'); if (!File(ffx).existsSync()) { throw FileSystemException("Couldn't find ffx at location $ffx"); } return ffx; } @override Future<FuchsiaDevice> get workingDevice async { if (_workingDevice == null) { if (Platform.environment.containsKey(DeviceIdEnvName)) { final String deviceId = Platform.environment[DeviceIdEnvName]!; await chooseWorkingDeviceById(deviceId); return _workingDevice!; } await chooseWorkingDevice(); } return _workingDevice!; } /// Picks the first connected Fuchsia device. @override Future<void> chooseWorkingDevice() async { final List<FuchsiaDevice> allDevices = (await discoverDevices()) .map<FuchsiaDevice>((String id) => FuchsiaDevice(deviceId: id)) .toList(); if (allDevices.isEmpty) { throw const DeviceException('No Fuchsia devices detected'); } _workingDevice = allDevices.first; print('Device chosen: $_workingDevice'); } @override Future<void> chooseWorkingDeviceById(String deviceId) async { final String? matchedId = _findMatchId(await discoverDevices(), deviceId); if (matchedId != null) { _workingDevice = FuchsiaDevice(deviceId: matchedId); print('Choose device by ID: $matchedId'); return; } throw DeviceException( 'Device with ID $deviceId is not found for operating system: ' '$deviceOperatingSystem' ); } @override Future<List<String>> discoverDevices() async { final List<String> output = (await eval(_ffx, <String>['target', 'list', '-f', 's'])) .trim() .split('\n'); final List<String> devices = <String>[]; for (final String line in output) { final List<String> parts = line.split(' '); assert(parts.length == 2); devices.add(parts.last); // The device id. } return devices; } @override Future<Map<String, HealthCheckResult>> checkDevices() async { final Map<String, HealthCheckResult> results = <String, HealthCheckResult>{}; for (final String deviceId in await discoverDevices()) { try { final int resolveResult = await exec( _ffx, <String>[ 'target', 'list', '-f', 'a', deviceId, ] ); if (resolveResult == 0) { results['fuchsia-device-$deviceId'] = HealthCheckResult.success(); } else { results['fuchsia-device-$deviceId'] = HealthCheckResult.failure('Cannot resolve device $deviceId'); } } on Exception catch (error, stacktrace) { results['fuchsia-device-$deviceId'] = HealthCheckResult.error(error, stacktrace); } } return results; } @override Future<void> performPreflightTasks() async {} } class AndroidDevice extends Device { AndroidDevice({required this.deviceId}) { _updateDeviceInfo(); } @override final String deviceId; String deviceInfo = ''; int apiLevel = 0; /// Whether the device is awake. @override Future<bool> isAwake() async { return await _getWakefulness() == 'Awake'; } /// Whether the device is asleep. @override Future<bool> isAsleep() async { return await _getWakefulness() == 'Asleep'; } /// Wake up the device if it is not awake using [togglePower]. @override Future<void> wakeUp() async { if (!(await isAwake())) { await togglePower(); } } /// Send the device to sleep mode if it is not asleep using [togglePower]. @override Future<void> sendToSleep() async { if (!(await isAsleep())) { await togglePower(); } } /// Sends `KEYCODE_HOME` (3), which causes the device to go to the home screen. @override Future<void> home() async { await shellExec('input', const <String>['keyevent', '3']); } /// Sends `KEYCODE_POWER` (26), which causes the device to toggle its mode /// between awake and asleep. @override Future<void> togglePower() async { await shellExec('input', const <String>['keyevent', '26']); } /// Unlocks the device by sending `KEYCODE_MENU` (82). /// /// This only works when the device doesn't have a secure unlock pattern. @override Future<void> unlock() async { await wakeUp(); await shellExec('input', const <String>['keyevent', '82']); } @override Future<void> tap(int x, int y) async { await shellExec('input', <String>['tap', '$x', '$y']); } /// Retrieves device's wakefulness state. /// /// See: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/PowerManagerInternal.java Future<String> _getWakefulness() async { final String powerInfo = await shellEval('dumpsys', <String>['power']); // A motoG4 phone returns `mWakefulness=Awake`. // A Samsung phone returns `getWakefullnessLocked()=Awake`. final RegExp wakefulnessRegexp = RegExp(r'.*(mWakefulness=|getWakefulnessLocked\(\)=).*'); final String wakefulness = grep(wakefulnessRegexp, from: powerInfo).single.split('=')[1].trim(); return wakefulness; } Future<bool> isArm64() async { final String cpuInfo = await shellEval('getprop', const <String>['ro.product.cpu.abi']); return cpuInfo.contains('arm64'); } Future<bool> isArm() async { final String cpuInfo = await shellEval('getprop', const <String>['ro.product.cpu.abi']); return cpuInfo.contains('armeabi'); } Future<void> _updateDeviceInfo() async { String info; try { info = await shellEval( 'getprop', <String>[ 'ro.bootimage.build.fingerprint', ';', 'getprop', 'ro.build.version.release', ';', 'getprop', 'ro.build.version.sdk', ], silent: true, ); } on IOException { info = ''; } final List<String> list = info.split('\n'); if (list.length == 3) { apiLevel = int.parse(list[2]); deviceInfo = 'fingerprint: ${list[0]} os: ${list[1]} api-level: $apiLevel'; } else { apiLevel = 0; deviceInfo = ''; } } /// Executes [command] on `adb shell`. Future<void> shellExec(String command, List<String> arguments, { Map<String, String>? environment, bool silent = false }) async { await adb(<String>['shell', command, ...arguments], environment: environment, silent: silent); } /// Executes [command] on `adb shell` and returns its standard output as a [String]. Future<String> shellEval(String command, List<String> arguments, { Map<String, String>? environment, bool silent = false }) { return adb(<String>['shell', command, ...arguments], environment: environment, silent: silent); } /// Runs `adb` with the given [arguments], selecting this device. Future<String> adb( List<String> arguments, { Map<String, String>? environment, bool silent = false, }) { return eval( adbPath, <String>['-s', deviceId, ...arguments], environment: environment, printStdout: !silent, printStderr: !silent, ); } @override Future<Map<String, dynamic>> getMemoryStats(String packageName) async { final String meminfo = await shellEval('dumpsys', <String>['meminfo', packageName]); final Match? match = RegExp(r'TOTAL\s+(\d+)').firstMatch(meminfo); assert(match != null, 'could not parse dumpsys meminfo output'); return <String, dynamic>{ 'total_kb': int.parse(match!.group(1)!), }; } @override bool get canStreamLogs => true; bool _abortedLogging = false; Process? _loggingProcess; @override Future<void> startLoggingToSink(IOSink sink, {bool clear = true}) async { if (clear) { await adb(<String>['logcat', '--clear'], silent: true); } _loggingProcess = await startProcess( adbPath, // Catch the whole log. <String>['-s', deviceId, 'logcat'], ); _loggingProcess!.stdout .transform<String>(const Utf8Decoder(allowMalformed: true)) .listen((String line) { sink.write(line); }); _loggingProcess!.stderr .transform<String>(const Utf8Decoder(allowMalformed: true)) .listen((String line) { sink.write(line); }); unawaited(_loggingProcess!.exitCode.then<void>((int exitCode) { if (!_abortedLogging) { sink.writeln('adb logcat failed with exit code $exitCode.\n'); } })); } @override Future<void> stopLoggingToSink() async { if (_loggingProcess != null) { _abortedLogging = true; _loggingProcess!.kill(); await _loggingProcess!.exitCode; } } @override Future<void> clearLogs() { return adb(<String>['logcat', '-c']); } @override Stream<String> get logcat { final Completer<void> stdoutDone = Completer<void>(); final Completer<void> stderrDone = Completer<void>(); final Completer<void> processDone = Completer<void>(); final Completer<void> abort = Completer<void>(); bool aborted = false; late final StreamController<String> stream; stream = StreamController<String>( onListen: () async { await clearLogs(); final Process process = await startProcess( adbPath, // Make logcat less chatty by filtering down to just ActivityManager // (to let us know when app starts), flutter (needed by tests to see // log output), and fatal messages (hopefully catches tombstones). // For local testing, this can just be: // <String>['-s', deviceId, 'logcat'] // to view the whole log, or just run logcat alongside this. <String>['-s', deviceId, 'logcat', 'ActivityManager:I', 'flutter:V', '*:F'], ); process.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String line) { print('adb logcat: $line'); if (!stream.isClosed) { stream.sink.add(line); } }, onDone: () { stdoutDone.complete(); }); process.stderr .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String line) { print('adb logcat stderr: $line'); }, onDone: () { stderrDone.complete(); }); unawaited(process.exitCode.then<void>((int exitCode) { print('adb logcat process terminated with exit code $exitCode'); if (!aborted) { stream.addError(BuildFailedError('adb logcat failed with exit code $exitCode.\n')); processDone.complete(); } })); await Future.any<dynamic>(<Future<dynamic>>[ Future.wait<void>(<Future<void>>[ stdoutDone.future, stderrDone.future, processDone.future, ]), abort.future, ]); aborted = true; print('terminating adb logcat'); process.kill(); print('closing logcat stream'); await stream.close(); }, onCancel: () { if (!aborted) { print('adb logcat aborted'); aborted = true; abort.complete(); } }, ); return stream.stream; } @override Future<void> stop(String packageName) async { return shellExec('am', <String>['force-stop', packageName]); } @override String toString() { return '$deviceId $deviceInfo'; } @override Future<void> reboot() { return adb(<String>['reboot']); } @override Future<void> awaitDevice() async { print('Waiting for device.'); final String waitOut = await adb(<String>['wait-for-device']); print(waitOut); const RetryOptions retryOptions = RetryOptions(delayFactor: Duration(seconds: 1), maxAttempts: 10, maxDelay: Duration(minutes: 1)); await retryOptions.retry(() async { final String adbShellOut = await adb(<String>['shell', 'getprop sys.boot_completed']); if (adbShellOut != '1') { print('Device not ready.'); print(adbShellOut); throw const DeviceException('Phone not ready.'); } }, retryIf: (Exception e) => e is DeviceException); print('Done waiting for device.'); } } class IosDeviceDiscovery implements DeviceDiscovery { factory IosDeviceDiscovery() { return _instance ??= IosDeviceDiscovery._(); } IosDeviceDiscovery._(); static IosDeviceDiscovery? _instance; IosDevice? _workingDevice; @override Future<IosDevice> get workingDevice async { if (_workingDevice == null) { if (Platform.environment.containsKey(DeviceIdEnvName)) { final String deviceId = Platform.environment[DeviceIdEnvName]!; await chooseWorkingDeviceById(deviceId); return _workingDevice!; } await chooseWorkingDevice(); } return _workingDevice!; } /// Picks a random iOS device out of connected devices and sets it as /// [workingDevice]. @override Future<void> chooseWorkingDevice() async { final List<IosDevice> allDevices = (await discoverDevices()) .map<IosDevice>((String id) => IosDevice(deviceId: id)) .toList(); if (allDevices.isEmpty) { throw const DeviceException('No iOS devices detected'); } // TODO(yjbanov): filter out and warn about those with low battery level _workingDevice = allDevices[math.Random().nextInt(allDevices.length)]; print('Device chosen: $_workingDevice'); } @override Future<void> chooseWorkingDeviceById(String deviceId) async { final String? matchedId = _findMatchId(await discoverDevices(), deviceId); if (matchedId != null) { _workingDevice = IosDevice(deviceId: matchedId); print('Choose device by ID: $matchedId'); return; } throw DeviceException( 'Device with ID $deviceId is not found for operating system: ' '$deviceOperatingSystem' ); } @override Future<List<String>> discoverDevices() async { final List<dynamic> results = json.decode(await eval( path.join(flutterDirectory.path, 'bin', 'flutter'), <String>['devices', '--machine', '--suppress-analytics', '--device-timeout', '5'], )) as List<dynamic>; // [ // { // "name": "Flutter's iPhone", // "id": "00008020-00017DA80CC1002E", // "isSupported": true, // "targetPlatform": "ios", // "emulator": false, // "sdk": "iOS 13.2", // "capabilities": { // "hotReload": true, // "hotRestart": true, // "screenshot": true, // "fastStart": false, // "flutterExit": true, // "hardwareRendering": false, // "startPaused": false // } // } // ] final List<String> deviceIds = <String>[]; for (final dynamic result in results) { final Map<String, dynamic> device = result as Map<String, dynamic>; if (device['targetPlatform'] == 'ios' && device['id'] != null && device['emulator'] != true && device['isSupported'] == true) { deviceIds.add(device['id'] as String); } } if (deviceIds.isEmpty) { throw const DeviceException('No connected physical iOS devices found.'); } return deviceIds; } @override Future<Map<String, HealthCheckResult>> checkDevices() async { final Map<String, HealthCheckResult> results = <String, HealthCheckResult>{}; for (final String deviceId in await discoverDevices()) { // TODO(ianh): do a more meaningful connectivity check than just recording the ID results['ios-device-$deviceId'] = HealthCheckResult.success(); } return results; } @override Future<void> performPreflightTasks() async { // Currently we do not have preflight tasks for iOS. } } /// iOS device. class IosDevice extends Device { IosDevice({ required this.deviceId }); @override final String deviceId; String get idevicesyslogPath { return path.join(flutterDirectory.path, 'bin', 'cache', 'artifacts', 'libimobiledevice', 'idevicesyslog'); } String get dyldLibraryPath { final List<String> dylibsPaths = <String>[ path.join(flutterDirectory.path, 'bin', 'cache', 'artifacts', 'libimobiledevice'), path.join(flutterDirectory.path, 'bin', 'cache', 'artifacts', 'openssl'), path.join(flutterDirectory.path, 'bin', 'cache', 'artifacts', 'usbmuxd'), path.join(flutterDirectory.path, 'bin', 'cache', 'artifacts', 'libplist'), ]; return dylibsPaths.join(':'); } @override bool get canStreamLogs => true; bool _abortedLogging = false; Process? _loggingProcess; @override Future<void> startLoggingToSink(IOSink sink, {bool clear = true}) async { // Clear is not supported. _loggingProcess = await startProcess( idevicesyslogPath, <String>['-u', deviceId, '--quiet'], environment: <String, String>{ 'DYLD_LIBRARY_PATH': dyldLibraryPath, }, ); _loggingProcess!.stdout .transform<String>(const Utf8Decoder(allowMalformed: true)) .listen((String line) { sink.write(line); }); _loggingProcess!.stderr .transform<String>(const Utf8Decoder(allowMalformed: true)) .listen((String line) { sink.write(line); }); unawaited(_loggingProcess!.exitCode.then<void>((int exitCode) { if (!_abortedLogging) { sink.writeln('idevicesyslog failed with exit code $exitCode.\n'); } })); } @override Future<void> stopLoggingToSink() async { if (_loggingProcess != null) { _abortedLogging = true; _loggingProcess!.kill(); await _loggingProcess!.exitCode; } } // The methods below are stubs for now. They will need to be expanded. // We currently do not have a way to lock/unlock iOS devices. So we assume the // devices are already unlocked. For now we'll just keep them at minimum // screen brightness so they don't drain battery too fast. @override Future<bool> isAwake() async => true; @override Future<bool> isAsleep() async => false; @override Future<void> wakeUp() async {} @override Future<void> sendToSleep() async {} @override Future<void> home() async {} @override Future<void> togglePower() async {} @override Future<void> unlock() async {} @override Future<void> tap(int x, int y) async { throw UnimplementedError(); } @override Future<Map<String, dynamic>> getMemoryStats(String packageName) async { throw UnimplementedError(); } @override Stream<String> get logcat { throw UnimplementedError(); } @override Future<void> clearLogs() async {} @override Future<void> stop(String packageName) async {} @override Future<void> reboot() { return Process.run('idevicediagnostics', <String>['restart', '-u', deviceId]); } @override Future<void> awaitDevice() async {} } class LinuxDevice extends Device { const LinuxDevice(); @override String get deviceId => 'linux'; @override Future<Map<String, dynamic>> getMemoryStats(String packageName) async { return <String, dynamic>{}; } @override Future<void> home() async { } @override Future<bool> isAsleep() async { return false; } @override Future<bool> isAwake() async { return true; } @override Stream<String> get logcat => const Stream<String>.empty(); @override Future<void> clearLogs() async {} @override Future<void> reboot() async { } @override Future<void> sendToSleep() async { } @override Future<void> stop(String packageName) async { } @override Future<void> tap(int x, int y) async { } @override Future<void> togglePower() async { } @override Future<void> unlock() async { } @override Future<void> wakeUp() async { } @override Future<void> awaitDevice() async {} } class MacosDevice extends Device { const MacosDevice(); @override String get deviceId => 'macos'; @override Future<Map<String, dynamic>> getMemoryStats(String packageName) async { return <String, dynamic>{}; } @override Future<void> home() async { } @override Future<bool> isAsleep() async { return false; } @override Future<bool> isAwake() async { return true; } @override Stream<String> get logcat => const Stream<String>.empty(); @override Future<void> clearLogs() async {} @override Future<void> reboot() async { } @override Future<void> sendToSleep() async { } @override Future<void> stop(String packageName) async { } @override Future<void> tap(int x, int y) async { } @override Future<void> togglePower() async { } @override Future<void> unlock() async { } @override Future<void> wakeUp() async { } @override Future<void> awaitDevice() async {} } class WindowsDevice extends Device { const WindowsDevice(); @override String get deviceId => 'windows'; @override Future<Map<String, dynamic>> getMemoryStats(String packageName) async { return <String, dynamic>{}; } @override Future<void> home() async { } @override Future<bool> isAsleep() async { return false; } @override Future<bool> isAwake() async { return true; } @override Stream<String> get logcat => const Stream<String>.empty(); @override Future<void> clearLogs() async {} @override Future<void> reboot() async { } @override Future<void> sendToSleep() async { } @override Future<void> stop(String packageName) async { } @override Future<void> tap(int x, int y) async { } @override Future<void> togglePower() async { } @override Future<void> unlock() async { } @override Future<void> wakeUp() async { } @override Future<void> awaitDevice() async {} } /// Fuchsia device. class FuchsiaDevice extends Device { const FuchsiaDevice({ required this.deviceId }); @override final String deviceId; // TODO(egarciad): Implement these for Fuchsia. @override Future<bool> isAwake() async => true; @override Future<bool> isAsleep() async => false; @override Future<void> wakeUp() async {} @override Future<void> sendToSleep() async {} @override Future<void> home() async {} @override Future<void> togglePower() async {} @override Future<void> unlock() async {} @override Future<void> tap(int x, int y) async {} @override Future<void> stop(String packageName) async {} @override Future<Map<String, dynamic>> getMemoryStats(String packageName) async { throw UnimplementedError(); } @override Stream<String> get logcat { throw UnimplementedError(); } @override Future<void> clearLogs() async {} @override Future<void> reboot() async { // Unsupported. } @override Future<void> awaitDevice() async {} } /// Path to the `adb` executable. String get adbPath { final String? androidHome = Platform.environment['ANDROID_HOME'] ?? Platform.environment['ANDROID_SDK_ROOT']; if (androidHome == null) { throw const DeviceException( 'The ANDROID_HOME environment variable is ' 'missing. The variable must point to the Android ' 'SDK directory containing platform-tools.' ); } final String adbPath = path.join(androidHome, 'platform-tools/adb'); if (!canRun(adbPath)) { throw DeviceException('adb not found at: $adbPath'); } return path.absolute(adbPath); } class FakeDevice extends Device { const FakeDevice({ required this.deviceId }); @override final String deviceId; @override Future<bool> isAwake() async => true; @override Future<bool> isAsleep() async => false; @override Future<void> wakeUp() async {} @override Future<void> sendToSleep() async {} @override Future<void> home() async {} @override Future<void> togglePower() async {} @override Future<void> unlock() async {} @override Future<void> tap(int x, int y) async { throw UnimplementedError(); } @override Future<Map<String, dynamic>> getMemoryStats(String packageName) async { throw UnimplementedError(); } @override Stream<String> get logcat { throw UnimplementedError(); } @override Future<void> clearLogs() async {} @override Future<void> stop(String packageName) async {} @override Future<void> reboot() async { // Unsupported. } @override Future<void> awaitDevice() async {} } class FakeDeviceDiscovery implements DeviceDiscovery { factory FakeDeviceDiscovery() { return _instance ??= FakeDeviceDiscovery._(); } FakeDeviceDiscovery._(); static FakeDeviceDiscovery? _instance; FakeDevice? _workingDevice; @override Future<FakeDevice> get workingDevice async { if (_workingDevice == null) { if (Platform.environment.containsKey(DeviceIdEnvName)) { final String deviceId = Platform.environment[DeviceIdEnvName]!; await chooseWorkingDeviceById(deviceId); return _workingDevice!; } await chooseWorkingDevice(); } return _workingDevice!; } /// The Fake is only available for by ID device discovery. @override Future<void> chooseWorkingDevice() async { throw const DeviceException('No fake devices detected'); } @override Future<void> chooseWorkingDeviceById(String deviceId) async { final String? matchedId = _findMatchId(await discoverDevices(), deviceId); if (matchedId != null) { _workingDevice = FakeDevice(deviceId: matchedId); print('Choose device by ID: $matchedId'); return; } throw DeviceException( 'Device with ID $deviceId is not found for operating system: ' '$deviceOperatingSystem' ); } @override Future<List<String>> discoverDevices() async { return <String>['FAKE_SUCCESS', 'THIS_IS_A_FAKE']; } @override Future<Map<String, HealthCheckResult>> checkDevices() async { final Map<String, HealthCheckResult> results = <String, HealthCheckResult>{}; for (final String deviceId in await discoverDevices()) { results['fake-device-$deviceId'] = HealthCheckResult.success(); } return results; } @override Future<void> performPreflightTasks() async { } }
flutter/dev/devicelab/lib/framework/devices.dart/0
{ "file_path": "flutter/dev/devicelab/lib/framework/devices.dart", "repo_id": "flutter", "token_count": 14151 }
567
// Copyright 2014 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:io'; import 'package:args/args.dart'; import '../framework/devices.dart'; import '../framework/task_result.dart'; import '../framework/utils.dart'; /// [Task] for defining build-test separation. /// /// Using this [Task] allows DeviceLab capacity to only be spent on the [test]. abstract class BuildTestTask { BuildTestTask(this.args, {this.workingDirectory, this.runFlutterClean = true,}) { final ArgResults argResults = argParser.parse(args); applicationBinaryPath = argResults[kApplicationBinaryPathOption] as String?; buildOnly = argResults[kBuildOnlyFlag] as bool; testOnly = argResults[kTestOnlyFlag] as bool; } static const String kApplicationBinaryPathOption = 'application-binary-path'; static const String kBuildOnlyFlag = 'build'; static const String kTestOnlyFlag = 'test'; final ArgParser argParser = ArgParser() ..addOption(kApplicationBinaryPathOption) ..addFlag(kBuildOnlyFlag) ..addFlag(kTestOnlyFlag); /// Args passed from the test runner via "--task-arg". final List<String> args; /// If true, skip [test]. bool buildOnly = false; /// If true, skip [build]. bool testOnly = false; /// Whether to run `flutter clean` before building the application under test. final bool runFlutterClean; /// Path to a built application to use in [test]. /// /// If not given, will default to child's expected location. String? applicationBinaryPath; /// Where the test artifacts are stored, such as performance results. final Directory? workingDirectory; /// Run Flutter build to create [applicationBinaryPath]. Future<void> build() async { await inDirectory<void>(workingDirectory, () async { if (runFlutterClean) { section('FLUTTER CLEAN'); await flutter('clean'); } section('BUILDING APPLICATION'); await flutter('build', options: getBuildArgs(deviceOperatingSystem)); copyArtifacts(); }); } /// Run Flutter drive test from [getTestArgs] against the application under test on the device. /// /// This assumes that [applicationBinaryPath] exists. Future<TaskResult> test() async { final Device device = await devices.workingDevice; await device.unlock(); await inDirectory<void>(workingDirectory, () async { section('DRIVE START'); await flutter('drive', options: getTestArgs(deviceOperatingSystem, device.deviceId)); }); return parseTaskResult(); } /// Args passed to flutter build to build the application under test. List<String> getBuildArgs(DeviceOperatingSystem deviceOperatingSystem) => throw UnimplementedError('getBuildArgs is not implemented'); /// Args passed to flutter drive to test the built application. List<String> getTestArgs(DeviceOperatingSystem deviceOperatingSystem, String deviceId) => throw UnimplementedError('getTestArgs is not implemented'); /// Copy artifacts to [applicationBinaryPath] if specified. /// /// This is needed when running from CI, so that LUCI recipes know where to locate and upload artifacts to GCS. void copyArtifacts() => throw UnimplementedError('copyArtifacts is not implemented'); /// Logic to construct [TaskResult] from this test's results. Future<TaskResult> parseTaskResult() => throw UnimplementedError('parseTaskResult is not implemented'); /// Path to the built application under test. /// /// Tasks can override to support default values. Otherwise, it will default /// to needing to be passed as an argument in the test runner. String? getApplicationBinaryPath() => applicationBinaryPath; /// Run this task. /// /// Throws [Exception] when unnecessary arguments are passed. Future<TaskResult> call() async { if (buildOnly && testOnly) { throw Exception('Both build and test should not be passed. Pass only one.'); } if (!testOnly) { await build(); } if (buildOnly) { return TaskResult.buildOnly(); } return test(); } }
flutter/dev/devicelab/lib/tasks/build_test_task.dart/0
{ "file_path": "flutter/dev/devicelab/lib/tasks/build_test_task.dart", "repo_id": "flutter", "token_count": 1211 }
568
name: flutter_devicelab description: Flutter continuous integration performance and correctness tests. homepage: https://github.com/flutter/flutter environment: sdk: '>=3.2.0-0 <4.0.0' dependencies: archive: 3.3.2 args: 2.4.2 file: 7.0.0 http: 0.13.6 logging: 1.2.0 meta: 1.12.0 metrics_center: 1.0.13 path: 1.9.0 platform: 3.1.4 process: 5.0.2 pubspec_parse: 1.2.3 shelf: 1.4.1 shelf_static: 1.1.2 stack_trace: 1.11.1 vm_service: 14.2.0 web: 0.5.1 webkit_inspection_protocol: 1.2.1 xml: 6.5.0 standard_message_codec: 0.0.1+4 _discoveryapis_commons: 1.0.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" checked_yaml: 2.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" convert: 3.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" crypto: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" gcloud: 0.8.12 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" googleapis: 12.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" googleapis_auth: 1.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" http_parser: 4.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" json_annotation: 4.8.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" mime: 1.0.5 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" petitparser: 6.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" pub_semver: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" retry: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" stream_channel: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" typed_data: 1.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" yaml: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" dev_dependencies: test: 1.25.2 _fe_analyzer_shared: 67.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" analyzer: 6.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" coverage: 1.7.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" frontend_server_client: 3.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" glob: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" http_multi_server: 3.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" io: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" js: 0.7.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" node_preamble: 2.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" package_config: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" pool: 1.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" shelf_packages_handler: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" shelf_web_socket: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" source_map_stack_trace: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" source_maps: 0.10.12 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" test_api: 0.7.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" test_core: 0.6.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" watcher: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" web_socket_channel: 2.4.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" # PUBSPEC CHECKSUM: 956f
flutter/dev/devicelab/pubspec.yaml/0
{ "file_path": "flutter/dev/devicelab/pubspec.yaml", "repo_id": "flutter", "token_count": 1817 }
569
<link rel="search" type="application/opensearchdescription+xml" title="Flutter API" href="/opensearch.xml"/>
flutter/dev/docs/opensearch.html/0
{ "file_path": "flutter/dev/docs/opensearch.html", "repo_id": "flutter", "token_count": 32 }
570
# Android custom host app Android host app for a Flutter module created using ``` $ flutter create -t module hello ``` and placed in a sibling folder to (a clone of) the host app. Used by the `module_custom_host_app_name_test.dart` device lab test.
flutter/dev/integration_tests/android_custom_host_app/README.md/0
{ "file_path": "flutter/dev/integration_tests/android_custom_host_app/README.md", "repo_id": "flutter", "token_count": 74 }
571
<!-- Copyright 2014 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. --> <!-- Modify this file to customize your launch splash screen --> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@android:color/white" /> <!-- You can insert your own image assets here --> <!-- <item> <bitmap android:gravity="center" android:src="@mipmap/launch_image" /> </item> --> </layer-list>
flutter/dev/integration_tests/android_embedding_v2_smoke_test/android/app/src/main/res/drawable/launch_background.xml/0
{ "file_path": "flutter/dev/integration_tests/android_embedding_v2_smoke_test/android/app/src/main/res/drawable/launch_background.xml", "repo_id": "flutter", "token_count": 193 }
572
// Copyright 2014 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. /// The name of the route containing the test suite. const String headingsRoute = 'headings'; /// The string supplied to the [ValueKey] for the app bar title widget. const String appBarTitleKeyValue = 'Headings#AppBarTitle'; /// The string supplied to the [ValueKey] for the body text widget. const String bodyTextKeyValue = 'Headings#BodyText';
flutter/dev/integration_tests/android_semantics_testing/lib/src/tests/headings_constants.dart/0
{ "file_path": "flutter/dev/integration_tests/android_semantics_testing/lib/src/tests/headings_constants.dart", "repo_id": "flutter", "token_count": 134 }
573
// Copyright 2014 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. package io.flutter.integration.android_verified_input; import androidx.annotation.NonNull; import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.plugin.common.MethodChannel; import io.flutter.embedding.engine.dart.DartExecutor; public class MainActivity extends FlutterActivity { public static MethodChannel mMethodChannel; @Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { DartExecutor executor = flutterEngine.getDartExecutor(); // Configuring AdView to call adservices APIs flutterEngine .getPlatformViewsController() .getRegistry() .registerViewFactory("verified-input-view", new VerifiedInputViewFactory()); mMethodChannel = new MethodChannel(executor, "verified_input_test"); } }
flutter/dev/integration_tests/android_verified_input/android/app/src/main/java/io/flutter/integration/android_verified_input/MainActivity.java/0
{ "file_path": "flutter/dev/integration_tests/android_verified_input/android/app/src/main/java/io/flutter/integration/android_verified_input/MainActivity.java", "repo_id": "flutter", "token_count": 303 }
574
// Copyright 2014 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 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_driver/driver_extension.dart'; class FutureDataHandler { final Completer<DataHandler> handlerCompleter = Completer<DataHandler>(); Future<String> handleMessage(String? message) async { final DataHandler handler = await handlerCompleter.future; return handler(message); } } FutureDataHandler driverDataHandler = FutureDataHandler(); MethodChannel channel = const MethodChannel('verified_input_test'); Future<dynamic> onMethodChannelCall(MethodCall call) { switch (call.method) { // Android side is notifying us of the result of verifying the input // event. case 'notify_verified_input': final bool result = call.arguments as bool; // FlutterDriver handler, note that this captures the notification // value delivered via the method channel. Future<String> handler(String? message) async { switch (message) { case 'input_was_verified': return '$result'; } return 'unknown message: "$message"'; } // Install the handler now. driverDataHandler.handlerCompleter.complete(handler); } return Future<dynamic>.value(); } void main() { enableFlutterDriverExtension(handler: driverDataHandler.handleMessage); channel.setMethodCallHandler(onMethodChannelCall); runApp(MaterialApp(home: _Home())); } class _Home extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Verified Input Integration Test'), centerTitle: true, backgroundColor: Colors.black45, ), body: Container( padding: const EdgeInsets.all(30.0), color: Colors.black26, child: const AndroidView( key: Key('PlatformView'), viewType: 'verified-input-view', ) )); } }
flutter/dev/integration_tests/android_verified_input/lib/main.dart/0
{ "file_path": "flutter/dev/integration_tests/android_verified_input/lib/main.dart", "repo_id": "flutter", "token_count": 774 }
575
{ "info" : { "version" : 1, "author" : "xcode" } }
flutter/dev/integration_tests/channels/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json/0
{ "file_path": "flutter/dev/integration_tests/channels/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json", "repo_id": "flutter", "token_count": 36 }
576
org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError android.useAndroidX=true android.enableJetifier=true android.enableR8=true android.experimental.enableNewResourceShrinker=true
flutter/dev/integration_tests/deferred_components_test/android/gradle.properties/0
{ "file_path": "flutter/dev/integration_tests/deferred_components_test/android/gradle.properties", "repo_id": "flutter", "token_count": 76 }
577
// Copyright 2014 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 "AppDelegate.h" @interface AppDelegate () @property (atomic) uint64_t textureId; @property (atomic) int framesProduced; @property (atomic) int framesConsumed; @property (atomic) int lastFrameConsumed; @property (atomic) double startTime; @property (atomic) double endTime; @property (atomic) double frameRate; @property (atomic) double frameStartTime; @property (atomic) NSTimer* timer; - (void)tick:(NSTimer*)timer; @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { FlutterViewController* flutterController = (FlutterViewController*)self.window.rootViewController; FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:@"texture" binaryMessenger:flutterController]; [channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { if ([@"start" isEqualToString:call.method]) { _framesProduced = 0; _framesConsumed = 0; _frameRate = 1.0 / [(NSNumber*) call.arguments intValue]; _timer = [NSTimer scheduledTimerWithTimeInterval:_frameRate target:self selector:@selector(tick:) userInfo:nil repeats:YES]; _startTime = [[NSDate date] timeIntervalSince1970]; result(nil); } else if ([@"stop" isEqualToString:call.method]) { [_timer invalidate]; _endTime = [[NSDate date] timeIntervalSince1970]; result(nil); } else if ([@"getProducedFrameRate" isEqualToString:call.method]) { result(@(_framesProduced / (_endTime - _startTime))); } else if ([@"getConsumedFrameRate" isEqualToString:call.method]) { result(@(_framesConsumed / (_endTime - _startTime))); } else { result(FlutterMethodNotImplemented); } }]; _textureId = [flutterController registerTexture:self]; return [super application:application didFinishLaunchingWithOptions:launchOptions]; } - (void)tick:(NSTimer*)timer { FlutterViewController* flutterController = (FlutterViewController*)self.window.rootViewController; [flutterController textureFrameAvailable:_textureId]; _frameStartTime = [[NSDate date] timeIntervalSince1970]; // We just pretend to be producing a frame. _framesProduced++; } - (CVPixelBufferRef)copyPixelBuffer { double now = [[NSDate date] timeIntervalSince1970]; if (now < _frameStartTime || _frameStartTime + _frameRate < now || _framesProduced == _lastFrameConsumed) return nil; _framesConsumed++; _lastFrameConsumed = _framesProduced; // We just pretend to be handing over the produced frame to the consumer. return nil; } @end
flutter/dev/integration_tests/external_textures/ios/Runner/AppDelegate.m/0
{ "file_path": "flutter/dev/integration_tests/external_textures/ios/Runner/AppDelegate.m", "repo_id": "flutter", "token_count": 1182 }
578
// Copyright 2014 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 'logic.dart'; class Calculator extends StatefulWidget { const Calculator({super.key}); @override State<Calculator> createState() => CalculatorState(); } class CalculatorState extends State<Calculator> { /// As the user taps keys we update the current `_expression` and we also /// keep a stack of previous expressions so we can return to earlier states /// when the user hits the DEL key. final List<CalcExpression> _expressionStack = <CalcExpression>[]; CalcExpression _expression = CalcExpression.empty(); // Make `expression` the current expression and push the previous current // expression onto the stack. void pushExpression(CalcExpression expression) { _expressionStack.add(_expression); _expression = expression; } /// Pop the top expression off of the stack and make it the current expression. void popCalcExpression() { if (_expressionStack.isNotEmpty) { _expression = _expressionStack.removeLast(); } else { _expression = CalcExpression.empty(); } } /// Set `resultExpression` to the current expression and clear the stack. void setResult(CalcExpression resultExpression) { _expressionStack.clear(); _expression = resultExpression; } void handleNumberTap(int n) { final CalcExpression? expression = _expression.appendDigit(n); if (expression != null) { setState(() { pushExpression(expression); }); } } void handlePointTap() { final CalcExpression? expression = _expression.appendPoint(); if (expression != null) { setState(() { pushExpression(expression); }); } } void handlePlusTap() { final CalcExpression? expression = _expression.appendOperation(Operation.Addition); if (expression != null) { setState(() { pushExpression(expression); }); } } void handleMinusTap() { final CalcExpression? expression = _expression.appendMinus(); if (expression != null) { setState(() { pushExpression(expression); }); } } void handleMultTap() { final CalcExpression? expression = _expression.appendOperation(Operation.Multiplication); if (expression != null) { setState(() { pushExpression(expression); }); } } void handleDivTap() { final CalcExpression? expression = _expression.appendOperation(Operation.Division); if (expression != null) { setState(() { pushExpression(expression); }); } } void handleEqualsTap() { final CalcExpression? resultExpression = _expression.computeResult(); if (resultExpression != null) { setState(() { setResult(resultExpression); }); } } void handleDelTap() { setState(() { popCalcExpression(); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).canvasColor, elevation: 0.0, ), body: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ // Give the key-pad 3/5 of the vertical space and the display 2/5. Expanded( flex: 2, child: CalcDisplay(content: _expression.toString()), ), const Divider(height: 1.0), Expanded( flex: 3, child: KeyPad(calcState: this), ), ], ), ); } } class CalcDisplay extends StatelessWidget { const CalcDisplay({ super.key, this.content}); final String? content; @override Widget build(BuildContext context) { return Center( child: Text( content!, style: const TextStyle(fontSize: 24.0), ), ); } } class KeyPad extends StatelessWidget { const KeyPad({ super.key, this.calcState }); final CalculatorState? calcState; @override Widget build(BuildContext context) { final ThemeData themeData = ThemeData( primarySwatch: Colors.purple, brightness: Brightness.dark, platform: Theme.of(context).platform, ); return Theme( data: themeData, child: Material( child: Row( children: <Widget>[ Expanded( // We set flex equal to the number of columns so that the main keypad // and the op keypad have sizes proportional to their number of // columns. flex: 3, child: Column( children: <Widget>[ KeyRow(<Widget>[ NumberKey(7, calcState), NumberKey(8, calcState), NumberKey(9, calcState), ]), KeyRow(<Widget>[ NumberKey(4, calcState), NumberKey(5, calcState), NumberKey(6, calcState), ]), KeyRow(<Widget>[ NumberKey(1, calcState), NumberKey(2, calcState), NumberKey(3, calcState), ]), KeyRow(<Widget>[ CalcKey('.', calcState!.handlePointTap), NumberKey(0, calcState), CalcKey('=', calcState!.handleEqualsTap), ]), ], ), ), Expanded( child: Material( color: themeData.colorScheme.surface, child: Column( children: <Widget>[ CalcKey('\u232B', calcState!.handleDelTap), CalcKey('\u00F7', calcState!.handleDivTap), CalcKey('\u00D7', calcState!.handleMultTap), CalcKey('-', calcState!.handleMinusTap), CalcKey('+', calcState!.handlePlusTap), ], ), ), ), ], ), ), ); } } class KeyRow extends StatelessWidget { const KeyRow(this.keys, {super.key}); final List<Widget> keys; @override Widget build(BuildContext context) { return Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: keys, ), ); } } class CalcKey extends StatelessWidget { const CalcKey(this.text, this.onTap, {super.key}); final String text; final GestureTapCallback onTap; @override Widget build(BuildContext context) { final Orientation orientation = MediaQuery.of(context).orientation; return Expanded( child: InkResponse( onTap: onTap, child: Center( child: Text( text, style: TextStyle( // This line is used as a sentinel in the hot reload tests: hot_mode_test.dart // in the devicelab. fontSize: (orientation == Orientation.portrait) ? 32.0 : 24.0 ), ), ), ), ); } } class NumberKey extends CalcKey { NumberKey(int value, CalculatorState? calcState, {Key? key}) : super('$value', () { calcState!.handleNumberTap(value); }, key: key); }
flutter/dev/integration_tests/flutter_gallery/lib/demo/calculator/home.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/calculator/home.dart", "repo_id": "flutter", "token_count": 3230 }
579
# Fortnightly A Flutter sample app based on the Material study Fortnightly (a hypothetical, online newspaper.) It showcases print-quality, custom typography, Material Theming, and text-heavy UI design and layout. For info on the Fortnightly Material Study, see: https://material.io/design/material-studies/fortnightly.html ## Goals for this sample * Help you understand how to customize and layout text. * Provide you with example code for * Text * A short app bar (the menu button top left.) * Avatar images ## Widgets / APIs * BeveledRectangleBorder * BoxConstraints on Container * CircleAvatar * ExactAssetImage * Fonts * SafeArea * Stack * SingleChildScrollView * Text * TextStyle * TextTheme ## Notice * Theming is passed as a parameter in the constructor of `MaterialApp` (`theme:`). * `SafeArea` adds padding around notches and virtual home buttons on screens that have them (like iPhone X+). Here, it protects the `ShortAppBar` from overlapping with the status bar (time) and makes sure the bottom of the newspaper article has padding beneath it if necessary. * The entire newspaper article is wrapped in a `SingleChildScrollView` widget which ensures that the entire article can be viewed no matter what the screen's size or orientation is. * The `Text` widget with text ' ¬ ' has a `TextStyle` that changes one parameter of an inherited `TextStyle` using `.apply()``. * The `Text` widget with text 'Connor Eghan' has a `TextStyle` created explicitly instead of inheriting from theming. * You can break up long strings in your source files by putting them on multiple lines. * Fonts are imported with multiple files expressing their weights (Bold, Light, Medium, Regular) but are accessed with a `FontWeight` value like `FontWeight.w800` for Merriweather-Bold.ttf. ## Questions/issues If you have a general question about developing in Flutter, the best places to go are: * [The FlutterDev Google Group](https://groups.google.com/forum/#!forum/flutter-dev) * [The Flutter Gitter channel](https://gitter.im/flutter/flutter) * [StackOverflow](https://stackoverflow.com/questions/tagged/flutter)
flutter/dev/integration_tests/flutter_gallery/lib/demo/fortnightly/README.md/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/fortnightly/README.md", "repo_id": "flutter", "token_count": 588 }
580
// Copyright 2014 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 '../../gallery/demo.dart'; class ExpansionTileListDemo extends StatelessWidget { const ExpansionTileListDemo({super.key}); static const String routeName = '/material/expansion-tile-list'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Expand/collapse list control'), actions: <Widget>[MaterialDemoDocumentationButton(routeName)], ), body: Scrollbar( child: ListView( primary: true, children: <Widget>[ const ListTile(title: Text('Top')), ExpansionTile( title: const Text('Sublist'), backgroundColor: Theme.of(context).colorScheme.secondary.withOpacity(0.025), children: const <Widget>[ ListTile(title: Text('One')), ListTile(title: Text('Two')), // https://en.wikipedia.org/wiki/Free_Four ListTile(title: Text('Free')), ListTile(title: Text('Four')), ], ), const ListTile(title: Text('Bottom')), ], ), ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/material/expansion_tile_list_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/expansion_tile_list_demo.dart", "repo_id": "flutter", "token_count": 594 }
581
// Copyright 2014 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 '../../gallery/demo.dart'; const String _checkboxText = 'Checkboxes allow the user to select multiple options from a set. ' "A normal checkbox's value is true or false and a tristate checkbox's " 'value can also be null.'; const String _checkboxCode = 'selectioncontrols_checkbox'; const String _radioText = 'Radio buttons allow the user to select one option from a set. Use radio ' 'buttons for exclusive selection if you think that the user needs to see ' 'all available options side-by-side.'; const String _radioCode = 'selectioncontrols_radio'; const String _switchText = 'On/off switches toggle the state of a single settings option. The option ' 'that the switch controls, as well as the state it’s in, should be made ' 'clear from the corresponding inline label.'; const String _switchCode = 'selectioncontrols_switch'; class SelectionControlsDemo extends StatefulWidget { const SelectionControlsDemo({super.key}); static const String routeName = '/material/selection-controls'; @override State<SelectionControlsDemo> createState() => _SelectionControlsDemoState(); } class _SelectionControlsDemoState extends State<SelectionControlsDemo> { @override Widget build(BuildContext context) { final List<ComponentDemoTabData> demos = <ComponentDemoTabData>[ ComponentDemoTabData( tabName: 'CHECKBOX', description: _checkboxText, demoWidget: buildCheckbox(), exampleCodeTag: _checkboxCode, documentationUrl: 'https://api.flutter.dev/flutter/material/Checkbox-class.html', ), ComponentDemoTabData( tabName: 'RADIO', description: _radioText, demoWidget: buildRadio(), exampleCodeTag: _radioCode, documentationUrl: 'https://api.flutter.dev/flutter/material/Radio-class.html', ), ComponentDemoTabData( tabName: 'SWITCH', description: _switchText, demoWidget: buildSwitch(), exampleCodeTag: _switchCode, documentationUrl: 'https://api.flutter.dev/flutter/material/Switch-class.html', ), ]; return TabbedComponentDemoScaffold( title: 'Selection controls', demos: demos, ); } bool? checkboxValueA = true; bool? checkboxValueB = false; bool? checkboxValueC; int? radioValue = 0; bool switchValue = false; void handleRadioValueChanged(int? value) { setState(() { radioValue = value; }); } Widget buildCheckbox() { return Align( alignment: const Alignment(0.0, -0.2), child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Semantics( label: 'Checkbox A', child: Checkbox( value: checkboxValueA, onChanged: (bool? value) { setState(() { checkboxValueA = value; }); }, ), ), Semantics( label: 'Checkbox B', child: Checkbox( value: checkboxValueB, onChanged: (bool? value) { setState(() { checkboxValueB = value; }); }, ), ), Semantics( label: 'Checkbox C', child: Checkbox( value: checkboxValueC, tristate: true, onChanged: (bool? value) { setState(() { checkboxValueC = value; }); }, ), ), ], ), const Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ // Disabled checkboxes Checkbox(value: true, onChanged: null), Checkbox(value: false, onChanged: null), Checkbox(value: null, tristate: true, onChanged: null), ], ), ], ), ); } Widget buildRadio() { return Align( alignment: const Alignment(0.0, -0.2), child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Radio<int>( value: 0, groupValue: radioValue, onChanged: handleRadioValueChanged, ), Radio<int>( value: 1, groupValue: radioValue, onChanged: handleRadioValueChanged, ), Radio<int>( value: 2, groupValue: radioValue, onChanged: handleRadioValueChanged, ), ], ), // Disabled radio buttons const Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Radio<int>( value: 0, groupValue: 0, onChanged: null, ), Radio<int>( value: 1, groupValue: 0, onChanged: null, ), Radio<int>( value: 2, groupValue: 0, onChanged: null, ), ], ), ], ), ); } Widget buildSwitch() { return Align( alignment: const Alignment(0.0, -0.2), child: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Switch.adaptive( value: switchValue, onChanged: (bool value) { setState(() { switchValue = value; }); }, ), // Disabled switches const Switch.adaptive(value: true, onChanged: null), const Switch.adaptive(value: false, onChanged: null), ], ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/material/selection_controls_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/selection_controls_demo.dart", "repo_id": "flutter", "token_count": 3158 }
582
// Copyright 2014 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. enum Category { all, accessories, clothing, home, } class Product { const Product({ required this.category, required this.id, required this.isFeatured, required this.name, required this.price, }); final Category category; final int id; final bool isFeatured; final String name; final int price; String get assetName => '$id-0.jpg'; String get assetPackage => 'shrine_images'; @override String toString() => '$name (id=$id)'; }
flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/model/product.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/model/product.dart", "repo_id": "flutter", "token_count": 205 }
583
// Copyright 2014 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. // Demos for which timeline data will be collected using // FlutterDriver.traceAction(). // // Warning: The number of tests executed with timeline collection enabled // significantly impacts heap size of the running app. When run with // --trace-startup, as we do in this test, the VM stores trace events in an // endless buffer instead of a ring buffer. // // These names must match GalleryItem titles from kAllGalleryDemos // in dev/integration_tests/flutter_gallery/lib/gallery/demos.dart const List<String> kProfiledDemos = <String>[ 'Shrine@Studies', 'Contact profile@Studies', 'Animation@Studies', 'Bottom navigation@Material', 'Buttons@Material', 'Cards@Material', 'Chips@Material', 'Dialogs@Material', 'Pickers@Material', ]; // There are 3 places where the Gallery demos are traversed. // 1- In widget tests such as dev/integration_tests/flutter_gallery/test/smoke_test.dart // 2- In driver tests such as dev/integration_tests/flutter_gallery/test_driver/transitions_perf_test.dart // 3- In on-device instrumentation tests such as dev/integration_tests/flutter_gallery/test/live_smoketest.dart // // If you change navigation behavior in the Gallery or in the framework, make // sure all 3 are covered. // Demos that will be backed out of within FlutterDriver.runUnsynchronized(); // // These names must match GalleryItem titles from kAllGalleryDemos // in dev/integration_tests/flutter_gallery/lib/gallery/demos.dart const List<String> kUnsynchronizedDemos = <String>[ 'Progress indicators@Material', 'Activity Indicator@Cupertino', 'Video@Media', ];
flutter/dev/integration_tests/flutter_gallery/lib/demo_lists.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo_lists.dart", "repo_id": "flutter", "token_count": 503 }
584
// Copyright 2014 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 'gallery/home.dart'; import 'main.dart' as other_main; // This main chain-calls main.dart's main. This file is used for publishing // the gallery and removes the 'PREVIEW' banner. void main() { GalleryHome.showPreviewBanner = false; other_main.main(); }
flutter/dev/integration_tests/flutter_gallery/lib/main_publish.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/main_publish.dart", "repo_id": "flutter", "token_count": 127 }
585
// Copyright 2014 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 'package:flutter_gallery/gallery/app.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); if (binding is LiveTestWidgetsFlutterBinding) { binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; } testWidgets('Flutter gallery button example code displays', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/6147 await tester.pumpWidget(const GalleryApp(testMode: true)); await tester.pump(); // see https://github.com/flutter/flutter/issues/1865 await tester.pump(); // triggers a frame await Scrollable.ensureVisible(tester.element(find.text('Material')), alignment: 0.5); await tester.pumpAndSettle(); await tester.tap(find.text('Material')); await tester.pumpAndSettle(); // Launch the buttons demo and then prove that showing the example // code dialog does not crash. await tester.tap(find.text('Buttons')); await tester.pumpAndSettle(); await tester.tap(find.byTooltip('Show example code')); await tester.pump(); // start animation await tester.pump(const Duration(seconds: 1)); // end animation expect(find.text('Example code'), findsOneWidget); }); }
flutter/dev/integration_tests/flutter_gallery/test/example_code_display_test.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/test/example_code_display_test.dart", "repo_id": "flutter", "token_count": 493 }
586
// Copyright 2014 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/cupertino.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_gallery/demo_lists.dart'; import 'package:flutter_gallery/gallery/app.dart' show GalleryApp; import 'package:flutter_gallery/gallery/demos.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'run_demos.dart'; // All of the gallery demos, identified as "title@category". // // These names are reported by the test app, see _handleMessages() // in transitions_perf.dart. List<String> _allDemos = kAllGalleryDemos.map( (GalleryDemo demo) => '${demo.title}@${demo.category.name}', ).toList(); void main([List<String> args = const <String>[]]) { final bool withSemantics = args.contains('--with_semantics'); final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; group('flutter gallery transitions on e2e', () { testWidgets('find.bySemanticsLabel', (WidgetTester tester) async { runApp(const GalleryApp(testMode: true)); await tester.pumpAndSettle(); final int id = tester.getSemantics(find.bySemanticsLabel('Material')).id; expect(id, greaterThan(-1)); }, skip: !withSemantics); testWidgets( 'all demos', (WidgetTester tester) async { runApp(const GalleryApp(testMode: true)); await tester.pumpAndSettle(); // Collect timeline data for just a limited set of demos to avoid OOMs. await binding.watchPerformance(() async { await runDemos(kProfiledDemos, tester); }); // Execute the remaining tests. final Set<String> unprofiledDemos = Set<String>.from(_allDemos) ..removeAll(kProfiledDemos); await runDemos(unprofiledDemos.toList(), tester); }, semanticsEnabled: withSemantics, ); }); }
flutter/dev/integration_tests/flutter_gallery/test_driver/transitions_perf_e2e.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/test_driver/transitions_perf_e2e.dart", "repo_id": "flutter", "token_count": 755 }
587
// Copyright 2014 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. package io.flutter.integration.platformviews; import android.annotation.TargetApi; import android.os.Build; import android.view.MotionEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static android.view.MotionEvent.PointerCoords; import static android.view.MotionEvent.PointerProperties; @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public class MotionEventCodec { public static HashMap<String, Object> encode(MotionEvent event) { ArrayList<HashMap<String,Object>> pointerProperties = new ArrayList<>(); ArrayList<HashMap<String,Object>> pointerCoords = new ArrayList<>(); for (int i = 0; i < event.getPointerCount(); i++) { MotionEvent.PointerProperties properties = new MotionEvent.PointerProperties(); event.getPointerProperties(i, properties); pointerProperties.add(encodePointerProperties(properties)); MotionEvent.PointerCoords coords = new MotionEvent.PointerCoords(); event.getPointerCoords(i, coords); pointerCoords.add(encodePointerCoords(coords)); } HashMap<String, Object> eventMap = new HashMap<>(); eventMap.put("downTime", event.getDownTime()); eventMap.put("eventTime", event.getEventTime()); eventMap.put("action", event.getAction()); eventMap.put("pointerCount", event.getPointerCount()); eventMap.put("pointerProperties", pointerProperties); eventMap.put("pointerCoords", pointerCoords); eventMap.put("metaState", event.getMetaState()); eventMap.put("buttonState", event.getButtonState()); eventMap.put("xPrecision", event.getXPrecision()); eventMap.put("yPrecision", event.getYPrecision()); eventMap.put("deviceId", event.getDeviceId()); eventMap.put("edgeFlags", event.getEdgeFlags()); eventMap.put("source", event.getSource()); eventMap.put("flags", event.getFlags()); return eventMap; } private static HashMap<String, Object> encodePointerProperties(PointerProperties properties) { HashMap<String, Object> map = new HashMap<>(); map.put("id", properties.id); map.put("toolType", properties.toolType); return map; } private static HashMap<String, Object> encodePointerCoords(PointerCoords coords) { HashMap<String, Object> map = new HashMap<>(); map.put("orientation", coords.orientation); map.put("pressure", coords.pressure); map.put("size", coords.size); map.put("toolMajor", coords.toolMajor); map.put("toolMinor", coords.toolMinor); map.put("touchMajor", coords.touchMajor); map.put("touchMinor", coords.touchMinor); map.put("x", coords.x); map.put("y", coords.y); return map; } @SuppressWarnings("unchecked") public static MotionEvent decode(HashMap<String, Object> data) { List<PointerProperties> pointerProperties = new ArrayList<>(); List<PointerCoords> pointerCoords = new ArrayList<>(); for (HashMap<String, Object> property : (List<HashMap<String, Object>>) data.get("pointerProperties")) { pointerProperties.add(decodePointerProperties(property)) ; } for (HashMap<String, Object> coord : (List<HashMap<String, Object>>) data.get("pointerCoords")) { pointerCoords.add(decodePointerCoords(coord)) ; } return MotionEvent.obtain( (int) data.get("downTime"), (int) data.get("eventTime"), (int) data.get("action"), (int) data.get("pointerCount"), pointerProperties.toArray(new PointerProperties[pointerProperties.size()]), pointerCoords.toArray(new PointerCoords[pointerCoords.size()]), (int) data.get("metaState"), (int) data.get("buttonState"), (float) (double) data.get("xPrecision"), (float) (double) data.get("yPrecision"), (int) data.get("deviceId"), (int) data.get("edgeFlags"), (int) data.get("source"), (int) data.get("flags") ); } private static PointerProperties decodePointerProperties(HashMap<String, Object> data) { PointerProperties properties = new PointerProperties(); properties.id = (int) data.get("id"); properties.toolType = (int) data.get("toolType"); return properties; } private static PointerCoords decodePointerCoords(HashMap<String, Object> data) { PointerCoords coords = new PointerCoords(); coords.orientation = (float) (double) data.get("orientation"); coords.pressure = (float) (double) data.get("pressure"); coords.size = (float) (double) data.get("size"); coords.toolMajor = (float) (double) data.get("toolMajor"); coords.toolMinor = (float) (double) data.get("toolMinor"); coords.touchMajor = (float) (double) data.get("touchMajor"); coords.touchMinor = (float) (double) data.get("touchMinor"); coords.x = (float) (double) data.get("x"); coords.y = (float) (double) data.get("y"); return coords; } }
flutter/dev/integration_tests/hybrid_android_views/android/app/src/main/java/io/flutter/integration/androidviews/MotionEventCodec.java/0
{ "file_path": "flutter/dev/integration_tests/hybrid_android_views/android/app/src/main/java/io/flutter/integration/androidviews/MotionEventCodec.java", "repo_id": "flutter", "token_count": 2209 }
588
// Copyright 2014 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:collection/collection.dart'; // Android MotionEvent actions for which a pointer index is encoded in the // unmasked action code. const List<int> kPointerActions = <int>[ 0, // DOWN 1, // UP 5, // POINTER_DOWN 6, // POINTER_UP ]; const double kDoubleErrorMargin = 1e-4; String diffMotionEvents( Map<String, dynamic> originalEvent, Map<String, dynamic> synthesizedEvent, ) { final StringBuffer diff = StringBuffer(); diffMaps(originalEvent, synthesizedEvent, diff, excludeKeys: const <String>[ 'pointerProperties', // Compared separately. 'pointerCoords', // Compared separately. 'source', // Unused by Flutter. 'deviceId', // Android documentation says that's an arbitrary number that shouldn't be depended on. 'action', // Compared separately. ]); diffActions(diff, originalEvent, synthesizedEvent); diffPointerProperties(diff, originalEvent, synthesizedEvent); diffPointerCoordsList(diff, originalEvent, synthesizedEvent); return diff.toString(); } void diffActions(StringBuffer diffBuffer, Map<String, dynamic> originalEvent, Map<String, dynamic> synthesizedEvent) { final int synthesizedActionMasked = getActionMasked(synthesizedEvent['action'] as int); final int originalActionMasked = getActionMasked(originalEvent['action'] as int); final String synthesizedActionName = getActionName(synthesizedActionMasked, synthesizedEvent['action'] as int); final String originalActionName = getActionName(originalActionMasked, originalEvent['action'] as int); if (synthesizedActionMasked != originalActionMasked) { diffBuffer.write( 'action (expected: $originalActionName actual: $synthesizedActionName) '); } if (kPointerActions.contains(originalActionMasked) && originalActionMasked == synthesizedActionMasked) { final int originalPointer = getPointerIdx(originalEvent['action'] as int); final int synthesizedPointer = getPointerIdx(synthesizedEvent['action'] as int); if (originalPointer != synthesizedPointer) { diffBuffer.write( 'pointerIdx (expected: $originalPointer actual: $synthesizedPointer action: $originalActionName '); } } } void diffPointerProperties(StringBuffer diffBuffer, Map<String, dynamic> originalEvent, Map<String, dynamic> synthesizedEvent) { final List<Map<dynamic, dynamic>> expectedList = (originalEvent['pointerProperties'] as List<dynamic>).cast<Map<dynamic, dynamic>>(); final List<Map<dynamic, dynamic>> actualList = (synthesizedEvent['pointerProperties'] as List<dynamic>).cast<Map<dynamic, dynamic>>(); if (expectedList.length != actualList.length) { diffBuffer.write( 'pointerProperties (actual length: ${actualList.length}, expected length: ${expectedList.length} '); return; } for (int i = 0; i < expectedList.length; i++) { final Map<String, dynamic> expected = expectedList[i].cast<String, dynamic>(); final Map<String, dynamic> actual = actualList[i].cast<String, dynamic>(); diffMaps(expected, actual, diffBuffer, messagePrefix: '[pointerProperty $i] '); } } void diffPointerCoordsList(StringBuffer diffBuffer, Map<String, dynamic> originalEvent, Map<String, dynamic> synthesizedEvent) { final List<Map<dynamic, dynamic>> expectedList = (originalEvent['pointerCoords'] as List<dynamic>).cast<Map<dynamic, dynamic>>(); final List<Map<dynamic, dynamic>> actualList = (synthesizedEvent['pointerCoords'] as List<dynamic>).cast<Map<dynamic, dynamic>>(); if (expectedList.length != actualList.length) { diffBuffer.write( 'pointerCoords (actual length: ${actualList.length}, expected length: ${expectedList.length} '); return; } for (int i = 0; i < expectedList.length; i++) { final Map<String, dynamic> expected = expectedList[i].cast<String, dynamic>(); final Map<String, dynamic> actual = actualList[i].cast<String, dynamic>(); diffPointerCoords(expected, actual, i, diffBuffer); } } void diffPointerCoords(Map<String, dynamic> expected, Map<String, dynamic> actual, int pointerIdx, StringBuffer diffBuffer) { diffMaps(expected, actual, diffBuffer, messagePrefix: '[pointerCoord $pointerIdx] '); } void diffMaps( Map<String, dynamic> expected, Map<String, dynamic> actual, StringBuffer diffBuffer, { List<String> excludeKeys = const <String>[], String messagePrefix = '', }) { const IterableEquality<String> eq = IterableEquality<String>(); if (!eq.equals(expected.keys, actual.keys)) { diffBuffer.write( '${messagePrefix}keys (expected: ${expected.keys} actual: ${actual.keys} '); return; } for (final String key in expected.keys) { if (excludeKeys.contains(key)) { continue; } if (doublesApproximatelyMatch(expected[key], actual[key])) { continue; } if (expected[key] != actual[key]) { diffBuffer.write( '$messagePrefix$key (expected: ${expected[key]} actual: ${actual[key]}) '); } } } int getActionMasked(int action) => action & 0xff; int getPointerIdx(int action) => (action >> 8) & 0xff; String getActionName(int actionMasked, int action) { const List<String> actionNames = <String>[ 'DOWN', 'UP', 'MOVE', 'CANCEL', 'OUTSIDE', 'POINTER_DOWN', 'POINTER_UP', 'HOVER_MOVE', 'SCROLL', 'HOVER_ENTER', 'HOVER_EXIT', 'BUTTON_PRESS', 'BUTTON_RELEASE', ]; if (actionMasked < actionNames.length) { return '${actionNames[actionMasked]}($action)'; } else { return 'ACTION_$actionMasked'; } } bool doublesApproximatelyMatch(dynamic a, dynamic b) => a is double && b is double && (a - b).abs() < kDoubleErrorMargin;
flutter/dev/integration_tests/hybrid_android_views/lib/motion_event_diff.dart/0
{ "file_path": "flutter/dev/integration_tests/hybrid_android_views/lib/motion_event_diff.dart", "repo_id": "flutter", "token_count": 1997 }
589
// Copyright 2014 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 <EarlGreyTest/EarlGrey.h> #import <XCTest/XCTest.h> #import "AppDelegate.h" #import "FullScreenViewController.h" @interface FlutterTests : XCTestCase @end @implementation FlutterTests - (void)setUp { self.continueAfterFailure = NO; XCUIApplication *app = [[XCUIApplication alloc] init]; [app launch]; } - (void)testFullScreenCanPop { XCTestExpectation *notificationReceived = [self expectationWithDescription:@"Remote semantics notification"]; NSNotificationCenter *notificationCenter = [[GREYHostApplicationDistantObject sharedInstance] notificationCenter]; id observer = [notificationCenter addObserverForName:FlutterSemanticsUpdateNotification object:nil queue:nil usingBlock:^(NSNotification *notification) { XCTAssertTrue([notification.object isKindOfClass:GREY_REMOTE_CLASS_IN_APP(FullScreenViewController)]); [notificationReceived fulfill]; }]; [[EarlGrey selectElementWithMatcher:grey_keyWindow()] assertWithMatcher:grey_sufficientlyVisible()]; [[EarlGrey selectElementWithMatcher:grey_buttonTitle(@"Full Screen (Cold)")] performAction:grey_tap()]; [self waitForExpectationsWithTimeout:30.0 handler:nil]; [notificationCenter removeObserver:observer]; } @end
flutter/dev/integration_tests/ios_add2app_life_cycle/ios_add2appTests/IntegrationTests.m/0
{ "file_path": "flutter/dev/integration_tests/ios_add2app_life_cycle/ios_add2appTests/IntegrationTests.m", "repo_id": "flutter", "token_count": 437 }
590
// Copyright 2014 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 XCTest; @import os.log; static const CGFloat kStandardTimeOut = 60.0; @interface FlutterUITests : XCTestCase @property (strong) XCUIApplication *app; @end @implementation FlutterUITests - (void)setUp { [super setUp]; self.continueAfterFailure = NO; XCUIApplication *app = [[XCUIApplication alloc] init]; [app launch]; self.app = app; } - (void)testFullScreenColdPop { XCUIApplication *app = self.app; [self waitForAndTapElement:app.buttons[@"Full Screen (Cold)"]]; XCTAssertTrue([app.staticTexts[@"Button tapped 0 times."] waitForExistenceWithTimeout:kStandardTimeOut]); [self waitForAndTapElement:app.otherElements[@"Increment via Flutter"]]; XCTAssertTrue([app.staticTexts[@"Button tapped 1 time."] waitForExistenceWithTimeout:kStandardTimeOut]); // Back navigation. [app.buttons[@"POP"] tap]; XCTAssertTrue([app.navigationBars[@"Flutter iOS Demos Home"] waitForExistenceWithTimeout:kStandardTimeOut]); } - (void)testFullScreenWarm { XCUIApplication *app = self.app; [self waitForAndTapElement:app.buttons[@"Full Screen (Warm)"]]; BOOL newPageAppeared = [app.staticTexts[@"Button tapped 0 times."] waitForExistenceWithTimeout:kStandardTimeOut]; if (!newPageAppeared) { // Sometimes, the element doesn't respond to the tap, it seems an XCUITest race condition where the tap happened // too soon. Trying to tap the element again. [self waitForAndTapElement:app.buttons[@"Full Screen (Warm)"]]; newPageAppeared = [app.staticTexts[@"Button tapped 0 times."] waitForExistenceWithTimeout:kStandardTimeOut]; } XCTAssertTrue(newPageAppeared); [self waitForAndTapElement:app.otherElements[@"Increment via Flutter"]]; XCTAssertTrue([app.staticTexts[@"Button tapped 1 time."] waitForExistenceWithTimeout:kStandardTimeOut]); // Back navigation. [app.buttons[@"POP"] tap]; XCTAssertTrue([app.navigationBars[@"Flutter iOS Demos Home"] waitForExistenceWithTimeout:kStandardTimeOut]); } - (void)testFlutterViewWarm { XCUIApplication *app = self.app; [self waitForAndTapElement:app.buttons[@"Flutter View (Warm)"]]; BOOL newPageAppeared = [app.staticTexts[@"Button tapped 0 times."] waitForExistenceWithTimeout:kStandardTimeOut]; if (!newPageAppeared) { // Sometimes, the element doesn't respond to the tap, it seems an XCUITest race condition where the tap happened // too soon. Trying to tap the element again. [self waitForAndTapElement:app.buttons[@"Flutter View (Warm)"]]; newPageAppeared = [app.staticTexts[@"Button tapped 0 times."] waitForExistenceWithTimeout:kStandardTimeOut]; if (!newPageAppeared) { os_log(OS_LOG_DEFAULT, "%@", app.debugDescription); } } XCTAssertTrue(newPageAppeared); [self waitForAndTapElement:app.otherElements[@"Increment via Flutter"]]; BOOL countIncremented = [app.staticTexts[@"Button tapped 1 time."] waitForExistenceWithTimeout:kStandardTimeOut]; if (!countIncremented) { // Sometimes, the element doesn't respond to the tap, it seems to be an iOS 17 Simulator issue where the // simulator reboots. Try to tap the element again. [self waitForAndTapElement:app.otherElements[@"Increment via Flutter"]]; countIncremented = [app.staticTexts[@"Button tapped 1 time."] waitForExistenceWithTimeout:kStandardTimeOut]; if (!countIncremented) { os_log(OS_LOG_DEFAULT, "%@", app.debugDescription); } } XCTAssertTrue(countIncremented); // Back navigation. [app.buttons[@"POP"] tap]; XCTAssertTrue([app.navigationBars[@"Flutter iOS Demos Home"] waitForExistenceWithTimeout:kStandardTimeOut]); } - (void)testHybridViewWarm { XCUIApplication *app = self.app; [self waitForAndTapElement:app.buttons[@"Hybrid View (Warm)"]]; XCTAssertTrue([app.staticTexts[@"Flutter button tapped 0 times."] waitForExistenceWithTimeout:kStandardTimeOut]); XCTAssertTrue(app.staticTexts[@"Platform button tapped 0 times."].exists); [self waitForAndTapElement:app.otherElements[@"Increment via Flutter"]]; XCTAssertTrue([app.staticTexts[@"Flutter button tapped 1 time."] waitForExistenceWithTimeout:kStandardTimeOut]); XCTAssertTrue(app.staticTexts[@"Platform button tapped 0 times."].exists); [app.buttons[@"Increment via iOS"] tap]; XCTAssertTrue([app.staticTexts[@"Flutter button tapped 1 time."] waitForExistenceWithTimeout:kStandardTimeOut]); XCTAssertTrue(app.staticTexts[@"Platform button tapped 1 time."].exists); // Back navigation. [app.navigationBars[@"Hybrid Flutter/Native"].buttons[@"Flutter iOS Demos Home"] tap]; XCTAssertTrue([app.navigationBars[@"Flutter iOS Demos Home"] waitForExistenceWithTimeout:kStandardTimeOut]); } - (void)testDualCold { XCUIApplication *app = self.app; [self waitForAndTapElement:app.buttons[@"Dual Flutter View (Cold)"]]; // There are two marquees. XCUIElementQuery *marqueeQuery = [app.staticTexts matchingIdentifier:@"This is Marquee"]; [self expectationForPredicate:[NSPredicate predicateWithFormat:@"count = 2"] evaluatedWithObject:marqueeQuery handler:nil]; [self waitForExpectationsWithTimeout:30.0 handler:nil]; // Back navigation. [app.navigationBars[@"Dual Flutter Views"].buttons[@"Flutter iOS Demos Home"] tap]; XCTAssertTrue([app.navigationBars[@"Flutter iOS Demos Home"] waitForExistenceWithTimeout:kStandardTimeOut]); } - (void)waitForAndTapElement:(XCUIElement *)element { NSPredicate *hittable = [NSPredicate predicateWithFormat:@"exists == YES AND hittable == YES"]; [self expectationForPredicate:hittable evaluatedWithObject:element handler:nil]; [self waitForExpectationsWithTimeout:30.0 handler:nil]; [element tap]; } @end
flutter/dev/integration_tests/ios_host_app/FlutterUITests/FlutterUITests.m/0
{ "file_path": "flutter/dev/integration_tests/ios_host_app/FlutterUITests/FlutterUITests.m", "repo_id": "flutter", "token_count": 2142 }
591
// Copyright 2014 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 "FullScreenViewController.h" @interface FullScreenViewController () @end @implementation FullScreenViewController -(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; self.title = @"Full Screen Flutter"; self.navigationController.navigationBarHidden = YES; self.navigationController.hidesBarsOnSwipe = YES; } -(void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; self.navigationController.navigationBarHidden = NO; self.navigationController.hidesBarsOnSwipe = NO; if (self.isMovingFromParentViewController) { // If we were doing things that might cause the VC // to disappear (like using the image_picker plugin) // we shouldn't do this, but in this case we know we're // just going back to the navigation controller. // If we needed Flutter to tell us when we could actually go away, // we'd need to communicate over a method channel with it. [self.engine setViewController:nil]; } } -(BOOL)prefersStatusBarHidden { return true; } @end
flutter/dev/integration_tests/ios_host_app/Host/FullScreenViewController.m/0
{ "file_path": "flutter/dev/integration_tests/ios_host_app/Host/FullScreenViewController.m", "repo_id": "flutter", "token_count": 372 }
592
// Copyright 2014 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/cupertino.dart'; import '../../gallery_localizations.dart'; // BEGIN cupertinoButtonDemo class CupertinoButtonDemo extends StatelessWidget { const CupertinoButtonDemo({super.key}); @override Widget build(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( automaticallyImplyLeading: false, middle: Text(localizations.demoCupertinoButtonsTitle), ), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ CupertinoButton( onPressed: () {}, child: Text( localizations.cupertinoButton, ), ), const SizedBox(height: 16), CupertinoButton.filled( onPressed: () {}, child: Text( localizations.cupertinoButtonWithBackground, ), ), const SizedBox(height: 30), // Disabled buttons CupertinoButton( onPressed: null, child: Text( localizations.cupertinoButton, ), ), const SizedBox(height: 16), CupertinoButton.filled( onPressed: null, child: Text( localizations.cupertinoButtonWithBackground, ), ), ], ), ), ); } } // END
flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_button_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_button_demo.dart", "repo_id": "flutter", "token_count": 839 }
593
// Copyright 2014 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 '../../gallery_localizations.dart'; import 'material_demo_types.dart'; // BEGIN progressIndicatorsDemo class ProgressIndicatorDemo extends StatefulWidget { const ProgressIndicatorDemo({super.key, required this.type}); final ProgressIndicatorDemoType type; @override State<ProgressIndicatorDemo> createState() => _ProgressIndicatorDemoState(); } class _ProgressIndicatorDemoState extends State<ProgressIndicatorDemo> with SingleTickerProviderStateMixin { late AnimationController _controller; late Animation<double> _animation; @override void initState() { super.initState(); _controller = AnimationController( duration: const Duration(milliseconds: 1500), vsync: this, animationBehavior: AnimationBehavior.preserve, )..forward(); _animation = CurvedAnimation( parent: _controller, curve: const Interval(0.0, 0.9, curve: Curves.fastOutSlowIn), reverseCurve: Curves.fastOutSlowIn, )..addStatusListener((AnimationStatus status) { if (status == AnimationStatus.dismissed) { _controller.forward(); } else if (status == AnimationStatus.completed) { _controller.reverse(); } }); } @override void dispose() { _controller.stop(); super.dispose(); } String get _title { switch (widget.type) { case ProgressIndicatorDemoType.circular: return GalleryLocalizations.of(context)! .demoCircularProgressIndicatorTitle; case ProgressIndicatorDemoType.linear: return GalleryLocalizations.of(context)! .demoLinearProgressIndicatorTitle; } } Widget _buildIndicators(BuildContext context, Widget? child) { switch (widget.type) { case ProgressIndicatorDemoType.circular: return Column( children: <Widget>[ CircularProgressIndicator( semanticsLabel: GalleryLocalizations.of(context)!.loading, ), const SizedBox(height: 32), CircularProgressIndicator(value: _animation.value), ], ); case ProgressIndicatorDemoType.linear: return Column( children: <Widget>[ const LinearProgressIndicator(), const SizedBox(height: 32), LinearProgressIndicator(value: _animation.value), ], ); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, title: Text(_title), ), body: Center( child: SingleChildScrollView( child: Container( padding: const EdgeInsets.all(8), child: AnimatedBuilder( animation: _animation, builder: _buildIndicators, ), ), ), ), ); } } // END
flutter/dev/integration_tests/new_gallery/lib/demos/material/progress_indicator_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/material/progress_indicator_demo.dart", "repo_id": "flutter", "token_count": 1224 }
594
// Copyright 2014 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:dual_screen/dual_screen.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart' show timeDilation; import 'package:flutter_localized_locales/flutter_localized_locales.dart'; import 'package:google_fonts/google_fonts.dart'; import 'constants.dart'; import 'data/gallery_options.dart'; import 'gallery_localizations.dart'; import 'layout/adaptive.dart'; import 'pages/backdrop.dart'; import 'pages/splash.dart'; import 'routes.dart'; import 'themes/gallery_theme_data.dart'; export 'package:gallery/data/demos.dart' show pumpDeferredLibraries; void main() async { GoogleFonts.config.allowRuntimeFetching = false; runApp(const GalleryApp()); } class GalleryApp extends StatelessWidget { const GalleryApp({ super.key, this.initialRoute, this.isTestMode = false, }); final String? initialRoute; final bool isTestMode; @override Widget build(BuildContext context) { return ModelBinding( initialModel: GalleryOptions( themeMode: ThemeMode.system, textScaleFactor: systemTextScaleFactorOption, customTextDirection: CustomTextDirection.localeBased, locale: null, timeDilation: timeDilation, platform: defaultTargetPlatform, isTestMode: isTestMode, ), child: Builder( builder: (BuildContext context) { final GalleryOptions options = GalleryOptions.of(context); final bool hasHinge = MediaQuery.of(context).hinge?.bounds != null; return MaterialApp( restorationScopeId: 'rootGallery', title: 'Flutter Gallery', debugShowCheckedModeBanner: false, themeMode: options.themeMode, theme: GalleryThemeData.lightThemeData.copyWith( platform: options.platform, ), darkTheme: GalleryThemeData.darkThemeData.copyWith( platform: options.platform, ), localizationsDelegates: const <LocalizationsDelegate<Object?>>[ ...GalleryLocalizations.localizationsDelegates, LocaleNamesLocalizationsDelegate() ], initialRoute: initialRoute, supportedLocales: GalleryLocalizations.supportedLocales, locale: options.locale, localeListResolutionCallback: (List<Locale>? locales, Iterable<Locale> supportedLocales) { deviceLocale = locales?.first; return basicLocaleListResolution(locales, supportedLocales); }, onGenerateRoute: (RouteSettings settings) => RouteConfiguration.onGenerateRoute(settings, hasHinge), ); }, ), ); } } // ignore: unreachable_from_main class RootPage extends StatelessWidget { // ignore: unreachable_from_main const RootPage({ super.key, }); @override Widget build(BuildContext context) { return ApplyTextOptions( child: SplashPage( child: Backdrop( isDesktop: isDisplayDesktop(context), ), ), ); } }
flutter/dev/integration_tests/new_gallery/lib/main.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/main.dart", "repo_id": "flutter", "token_count": 1297 }
595
// Copyright 2014 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'; const Color cranePurple700 = Color(0xFF720D5D); const Color cranePurple800 = Color(0xFF5D1049); const Color cranePurple900 = Color(0xFF4E0D3A); const Color craneRed700 = Color(0xFFE30425); const Color craneWhite60 = Color(0x99FFFFFF); const Color cranePrimaryWhite = Color(0xFFFFFFFF); const Color craneErrorOrange = Color(0xFFFF9100); const Color craneAlpha = Color(0x00FFFFFF); const Color craneGrey = Color(0xFF747474); const Color craneBlack = Color(0xFF1E252D);
flutter/dev/integration_tests/new_gallery/lib/studies/crane/colors.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/crane/colors.dart", "repo_id": "flutter", "token_count": 220 }
596
// Copyright 2014 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:math' as math; import 'package:flutter/material.dart'; import '../../../data/gallery_options.dart'; import '../../../layout/letter_spacing.dart'; import '../../../layout/text_scale.dart'; import '../colors.dart'; import '../data.dart'; import '../formatters.dart'; /// A colored piece of the [RallyPieChart]. class RallyPieChartSegment { const RallyPieChartSegment({ required this.color, required this.value, }); final Color color; final double value; } /// The max height and width of the [RallyPieChart]. const double pieChartMaxSize = 500.0; List<RallyPieChartSegment> buildSegmentsFromAccountItems( List<AccountData> items) { return List<RallyPieChartSegment>.generate( items.length, (int i) { return RallyPieChartSegment( color: RallyColors.accountColor(i), value: items[i].primaryAmount, ); }, ); } List<RallyPieChartSegment> buildSegmentsFromBillItems(List<BillData> items) { return List<RallyPieChartSegment>.generate( items.length, (int i) { return RallyPieChartSegment( color: RallyColors.billColor(i), value: items[i].primaryAmount, ); }, ); } List<RallyPieChartSegment> buildSegmentsFromBudgetItems( List<BudgetData> items) { return List<RallyPieChartSegment>.generate( items.length, (int i) { return RallyPieChartSegment( color: RallyColors.budgetColor(i), value: items[i].primaryAmount - items[i].amountUsed, ); }, ); } /// An animated circular pie chart to represent pieces of a whole, which can /// have empty space. class RallyPieChart extends StatefulWidget { const RallyPieChart({ super.key, required this.heroLabel, required this.heroAmount, required this.wholeAmount, required this.segments, }); final String heroLabel; final double heroAmount; final double wholeAmount; final List<RallyPieChartSegment> segments; @override State<RallyPieChart> createState() => _RallyPieChartState(); } class _RallyPieChartState extends State<RallyPieChart> with SingleTickerProviderStateMixin { late AnimationController controller; late Animation<double> animation; @override void initState() { super.initState(); controller = AnimationController( duration: const Duration(milliseconds: 600), vsync: this, ); animation = CurvedAnimation( parent: TweenSequence<double>(<TweenSequenceItem<double>>[ TweenSequenceItem<double>( tween: Tween<double>(begin: 0, end: 0), weight: 1, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 0, end: 1), weight: 1.5, ), ]).animate(controller), curve: Curves.decelerate); controller.forward(); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return MergeSemantics( child: _AnimatedRallyPieChart( animation: animation, centerLabel: widget.heroLabel, centerAmount: widget.heroAmount, total: widget.wholeAmount, segments: widget.segments, ), ); } } class _AnimatedRallyPieChart extends AnimatedWidget { const _AnimatedRallyPieChart({ required this.animation, required this.centerLabel, required this.centerAmount, required this.total, required this.segments, }) : super(listenable: animation); final Animation<double> animation; final String centerLabel; final double centerAmount; final double total; final List<RallyPieChartSegment> segments; @override Widget build(BuildContext context) { final TextTheme textTheme = Theme.of(context).textTheme; final TextStyle labelTextStyle = textTheme.bodyMedium!.copyWith( fontSize: 14, letterSpacing: letterSpacingOrNone(0.5), ); return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { // When the widget is larger, we increase the font size. TextStyle? headlineStyle = constraints.maxHeight >= pieChartMaxSize ? textTheme.headlineSmall!.copyWith(fontSize: 70) : textTheme.headlineSmall; // With a large text scale factor, we set a max font size. if (GalleryOptions.of(context).textScaleFactor(context) > 1.0) { headlineStyle = headlineStyle!.copyWith( fontSize: headlineStyle.fontSize! / reducedTextScale(context), ); } return DecoratedBox( decoration: _RallyPieChartOutlineDecoration( maxFraction: animation.value, total: total, segments: segments, ), child: Container( height: constraints.maxHeight, alignment: Alignment.center, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( centerLabel, style: labelTextStyle, ), SelectableText( usdWithSignFormat(context).format(centerAmount), style: headlineStyle, ), ], ), ), ); }); } } class _RallyPieChartOutlineDecoration extends Decoration { const _RallyPieChartOutlineDecoration({ required this.maxFraction, required this.total, required this.segments, }); final double maxFraction; final double total; final List<RallyPieChartSegment> segments; @override BoxPainter createBoxPainter([VoidCallback? onChanged]) { return _RallyPieChartOutlineBoxPainter( maxFraction: maxFraction, wholeAmount: total, segments: segments, ); } } class _RallyPieChartOutlineBoxPainter extends BoxPainter { _RallyPieChartOutlineBoxPainter({ required this.maxFraction, required this.wholeAmount, required this.segments, }); final double maxFraction; final double wholeAmount; final List<RallyPieChartSegment> segments; static const double wholeRadians = 2 * math.pi; static const double spaceRadians = wholeRadians / 180; @override void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) { // Create two padded reacts to draw arcs in: one for colored arcs and one for // inner bg arc. const double strokeWidth = 4.0; final double outerRadius = math.min( configuration.size!.width, configuration.size!.height, ) / 2; final Rect outerRect = Rect.fromCircle( center: configuration.size!.center(offset), radius: outerRadius - strokeWidth * 3, ); final Rect innerRect = Rect.fromCircle( center: configuration.size!.center(offset), radius: outerRadius - strokeWidth * 4, ); // Paint each arc with spacing. double cumulativeSpace = 0.0; double cumulativeTotal = 0.0; for (final RallyPieChartSegment segment in segments) { final Paint paint = Paint()..color = segment.color; final double startAngle = _calculateStartAngle(cumulativeTotal, cumulativeSpace); final double sweepAngle = _calculateSweepAngle(segment.value, 0); canvas.drawArc(outerRect, startAngle, sweepAngle, true, paint); cumulativeTotal += segment.value; cumulativeSpace += spaceRadians; } // Paint any remaining space black (e.g. budget amount remaining). final double remaining = wholeAmount - cumulativeTotal; if (remaining > 0) { final Paint paint = Paint()..color = Colors.black; final double startAngle = _calculateStartAngle(cumulativeTotal, spaceRadians * segments.length); final double sweepAngle = _calculateSweepAngle(remaining, -spaceRadians); canvas.drawArc(outerRect, startAngle, sweepAngle, true, paint); } // Paint a smaller inner circle to cover the painted arcs, so they are // display as segments. final Paint bgPaint = Paint()..color = RallyColors.primaryBackground; canvas.drawArc(innerRect, 0, 2 * math.pi, true, bgPaint); } double _calculateAngle(double amount, double offset) { final double wholeMinusSpacesRadians = wholeRadians - (segments.length * spaceRadians); return maxFraction * (amount / wholeAmount * wholeMinusSpacesRadians + offset); } double _calculateStartAngle(double total, double offset) => _calculateAngle(total, offset) - math.pi / 2; double _calculateSweepAngle(double total, double offset) => _calculateAngle(total, offset); }
flutter/dev/integration_tests/new_gallery/lib/studies/rally/charts/pie_chart.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/rally/charts/pie_chart.dart", "repo_id": "flutter", "token_count": 3245 }
597
// Copyright 2014 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:animations/animations.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:nested/nested.dart'; import 'package:provider/provider.dart'; import '../../data/gallery_options.dart'; import '../../gallery_localizations.dart'; import '../../layout/letter_spacing.dart'; import 'adaptive_nav.dart'; import 'colors.dart'; import 'compose_page.dart'; import 'model/email_model.dart'; import 'model/email_store.dart'; import 'routes.dart' as routes; final GlobalKey<NavigatorState> rootNavKey = GlobalKey<NavigatorState>(); class ReplyApp extends StatefulWidget { const ReplyApp({super.key}); static const String homeRoute = routes.homeRoute; static const String composeRoute = routes.composeRoute; static Route<void> createComposeRoute(RouteSettings settings) { return PageRouteBuilder<void>( pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) => const ComposePage(), transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { return FadeThroughTransition( fillColor: Theme.of(context).cardColor, animation: animation, secondaryAnimation: secondaryAnimation, child: child, ); }, settings: settings, ); } @override State<ReplyApp> createState() => _ReplyAppState(); } class _ReplyAppState extends State<ReplyApp> with RestorationMixin { final _RestorableEmailState _appState = _RestorableEmailState(); @override String get restorationId => 'replyState'; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_appState, 'state'); } @override void dispose() { _appState.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final ThemeMode galleryThemeMode = GalleryOptions.of(context).themeMode; final bool isDark = galleryThemeMode == ThemeMode.system ? Theme.of(context).brightness == Brightness.dark : galleryThemeMode == ThemeMode.dark; final ThemeData replyTheme = isDark ? _buildReplyDarkTheme(context) : _buildReplyLightTheme(context); return MultiProvider( providers: <SingleChildWidget>[ ChangeNotifierProvider<EmailStore>.value( value: _appState.value, ), ], child: MaterialApp( navigatorKey: rootNavKey, restorationScopeId: 'appNavigator', title: 'Reply', debugShowCheckedModeBanner: false, theme: replyTheme, localizationsDelegates: GalleryLocalizations.localizationsDelegates, supportedLocales: GalleryLocalizations.supportedLocales, locale: GalleryOptions.of(context).locale, initialRoute: ReplyApp.homeRoute, onGenerateRoute: (RouteSettings settings) { switch (settings.name) { case ReplyApp.homeRoute: return MaterialPageRoute<void>( builder: (BuildContext context) => const AdaptiveNav(), settings: settings, ); case ReplyApp.composeRoute: return ReplyApp.createComposeRoute(settings); } return null; }, ), ); } } class _RestorableEmailState extends RestorableListenable<EmailStore> { @override EmailStore createDefaultValue() { return EmailStore(); } @override EmailStore fromPrimitives(Object? data) { final EmailStore appState = EmailStore(); final Map<String, dynamic> appData = Map<String, dynamic>.from(data! as Map<dynamic, dynamic>); appState.selectedEmailId = appData['selectedEmailId'] as int; appState.onSearchPage = appData['onSearchPage'] as bool; // The index of the MailboxPageType enum is restored. final int mailboxPageIndex = appData['selectedMailboxPage'] as int; appState.selectedMailboxPage = MailboxPageType.values[mailboxPageIndex]; final List<dynamic> starredEmailIdsList = appData['starredEmailIds'] as List<dynamic>; appState.starredEmailIds = <int>{ ...starredEmailIdsList.map<int>((dynamic id) => id as int), }; final List<dynamic> trashEmailIdsList = appData['trashEmailIds'] as List<dynamic>; appState.trashEmailIds = <int>{ ...trashEmailIdsList.map<int>((dynamic id) => id as int), }; return appState; } @override Object toPrimitives() { return <String, dynamic>{ 'selectedEmailId': value.selectedEmailId, // The index of the MailboxPageType enum is stored, since the value // has to be serializable. 'selectedMailboxPage': value.selectedMailboxPage.index, 'onSearchPage': value.onSearchPage, 'starredEmailIds': value.starredEmailIds.toList(), 'trashEmailIds': value.trashEmailIds.toList(), }; } } ThemeData _buildReplyLightTheme(BuildContext context) { final ThemeData base = ThemeData.light(); return base.copyWith( bottomAppBarTheme: const BottomAppBarTheme(color: ReplyColors.blue700), bottomSheetTheme: BottomSheetThemeData( backgroundColor: ReplyColors.blue700, modalBackgroundColor: Colors.white.withOpacity(0.7), ), navigationRailTheme: NavigationRailThemeData( backgroundColor: ReplyColors.blue700, selectedIconTheme: const IconThemeData(color: ReplyColors.orange500), selectedLabelTextStyle: GoogleFonts.workSansTextTheme().headlineSmall!.copyWith( color: ReplyColors.orange500, ), unselectedIconTheme: const IconThemeData(color: ReplyColors.blue200), unselectedLabelTextStyle: GoogleFonts.workSansTextTheme().headlineSmall!.copyWith( color: ReplyColors.blue200, ), ), canvasColor: ReplyColors.white50, cardColor: ReplyColors.white50, chipTheme: _buildChipTheme( ReplyColors.blue700, ReplyColors.lightChipBackground, Brightness.light, ), colorScheme: const ColorScheme.light( primary: ReplyColors.blue700, primaryContainer: ReplyColors.blue800, secondary: ReplyColors.orange500, secondaryContainer: ReplyColors.orange400, error: ReplyColors.red400, onError: ReplyColors.black900, background: ReplyColors.blue50, ), textTheme: _buildReplyLightTextTheme(base.textTheme), scaffoldBackgroundColor: ReplyColors.blue50, ); } ThemeData _buildReplyDarkTheme(BuildContext context) { final ThemeData base = ThemeData.dark(); return base.copyWith( bottomAppBarTheme: const BottomAppBarTheme( color: ReplyColors.darkBottomAppBarBackground, ), bottomSheetTheme: BottomSheetThemeData( backgroundColor: ReplyColors.darkDrawerBackground, modalBackgroundColor: Colors.black.withOpacity(0.7), ), navigationRailTheme: NavigationRailThemeData( backgroundColor: ReplyColors.darkBottomAppBarBackground, selectedIconTheme: const IconThemeData(color: ReplyColors.orange300), selectedLabelTextStyle: GoogleFonts.workSansTextTheme().headlineSmall!.copyWith( color: ReplyColors.orange300, ), unselectedIconTheme: const IconThemeData(color: ReplyColors.greyLabel), unselectedLabelTextStyle: GoogleFonts.workSansTextTheme().headlineSmall!.copyWith( color: ReplyColors.greyLabel, ), ), canvasColor: ReplyColors.black900, cardColor: ReplyColors.darkCardBackground, chipTheme: _buildChipTheme( ReplyColors.blue200, ReplyColors.darkChipBackground, Brightness.dark, ), colorScheme: const ColorScheme.dark( primary: ReplyColors.blue200, primaryContainer: ReplyColors.blue300, secondary: ReplyColors.orange300, secondaryContainer: ReplyColors.orange300, error: ReplyColors.red200, background: ReplyColors.black900Alpha087, ), textTheme: _buildReplyDarkTextTheme(base.textTheme), scaffoldBackgroundColor: ReplyColors.black900, ); } ChipThemeData _buildChipTheme( Color primaryColor, Color chipBackground, Brightness brightness, ) { return ChipThemeData( backgroundColor: primaryColor.withOpacity(0.12), disabledColor: primaryColor.withOpacity(0.87), selectedColor: primaryColor.withOpacity(0.05), secondarySelectedColor: chipBackground, padding: const EdgeInsets.all(4), shape: const StadiumBorder(), labelStyle: GoogleFonts.workSansTextTheme().bodyMedium!.copyWith( color: brightness == Brightness.dark ? ReplyColors.white50 : ReplyColors.black900, ), secondaryLabelStyle: GoogleFonts.workSansTextTheme().bodyMedium, brightness: brightness, ); } TextTheme _buildReplyLightTextTheme(TextTheme base) { return base.copyWith( headlineMedium: GoogleFonts.workSans( fontWeight: FontWeight.w600, fontSize: 34, letterSpacing: letterSpacingOrNone(0.4), height: 0.9, color: ReplyColors.black900, ), headlineSmall: GoogleFonts.workSans( fontWeight: FontWeight.bold, fontSize: 24, letterSpacing: letterSpacingOrNone(0.27), color: ReplyColors.black900, ), titleLarge: GoogleFonts.workSans( fontWeight: FontWeight.w600, fontSize: 20, letterSpacing: letterSpacingOrNone(0.18), color: ReplyColors.black900, ), titleSmall: GoogleFonts.workSans( fontWeight: FontWeight.w600, fontSize: 14, letterSpacing: letterSpacingOrNone(-0.04), color: ReplyColors.black900, ), bodyLarge: GoogleFonts.workSans( fontWeight: FontWeight.normal, fontSize: 18, letterSpacing: letterSpacingOrNone(0.2), color: ReplyColors.black900, ), bodyMedium: GoogleFonts.workSans( fontWeight: FontWeight.normal, fontSize: 14, letterSpacing: letterSpacingOrNone(-0.05), color: ReplyColors.black900, ), bodySmall: GoogleFonts.workSans( fontWeight: FontWeight.normal, fontSize: 12, letterSpacing: letterSpacingOrNone(0.2), color: ReplyColors.black900, ), ); } TextTheme _buildReplyDarkTextTheme(TextTheme base) { return base.copyWith( headlineMedium: GoogleFonts.workSans( fontWeight: FontWeight.w600, fontSize: 34, letterSpacing: letterSpacingOrNone(0.4), height: 0.9, color: ReplyColors.white50, ), headlineSmall: GoogleFonts.workSans( fontWeight: FontWeight.bold, fontSize: 24, letterSpacing: letterSpacingOrNone(0.27), color: ReplyColors.white50, ), titleLarge: GoogleFonts.workSans( fontWeight: FontWeight.w600, fontSize: 20, letterSpacing: letterSpacingOrNone(0.18), color: ReplyColors.white50, ), titleSmall: GoogleFonts.workSans( fontWeight: FontWeight.w600, fontSize: 14, letterSpacing: letterSpacingOrNone(-0.04), color: ReplyColors.white50, ), bodyLarge: GoogleFonts.workSans( fontWeight: FontWeight.normal, fontSize: 18, letterSpacing: letterSpacingOrNone(0.2), color: ReplyColors.white50, ), bodyMedium: GoogleFonts.workSans( fontWeight: FontWeight.normal, fontSize: 14, letterSpacing: letterSpacingOrNone(-0.05), color: ReplyColors.white50, ), bodySmall: GoogleFonts.workSans( fontWeight: FontWeight.normal, fontSize: 12, letterSpacing: letterSpacingOrNone(0.2), color: ReplyColors.white50, ), ); }
flutter/dev/integration_tests/new_gallery/lib/studies/reply/app.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/reply/app.dart", "repo_id": "flutter", "token_count": 4520 }
598
// Copyright 2014 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'; const Color shrinePink50 = Color(0xFFFEEAE6); const Color shrinePink100 = Color(0xFFFEDBD0); const Color shrinePink300 = Color(0xFFFBB8AC); const Color shrinePink400 = Color(0xFFEAA4A4); const Color shrineBrown900 = Color(0xFF442B2D); const Color shrineBrown600 = Color(0xFF7D4F52); const Color shrineErrorRed = Color(0xFFC5032B); const Color shrineSurfaceWhite = Color(0xFFFFFBFA); const Color shrineBackgroundWhite = Colors.white;
flutter/dev/integration_tests/new_gallery/lib/studies/shrine/colors.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/shrine/colors.dart", "repo_id": "flutter", "token_count": 207 }
599
// Copyright 2014 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 'package:intl/intl.dart'; import 'package:scoped_model/scoped_model.dart'; import '../../../gallery_localizations.dart'; import '../../../layout/adaptive.dart'; import '../../../layout/image_placeholder.dart'; import '../model/app_state_model.dart'; import '../model/product.dart'; class MobileProductCard extends StatelessWidget { const MobileProductCard({ super.key, this.imageAspectRatio = 33 / 49, required this.product, }) : assert(imageAspectRatio > 0); final double imageAspectRatio; final Product product; static const double defaultTextBoxHeight = 65; @override Widget build(BuildContext context) { return Semantics( container: true, button: true, enabled: true, child: _buildProductCard( context: context, product: product, imageAspectRatio: imageAspectRatio, ), ); } } class DesktopProductCard extends StatelessWidget { const DesktopProductCard({ super.key, required this.product, required this.imageWidth, }); final Product product; final double imageWidth; @override Widget build(BuildContext context) { return _buildProductCard( context: context, product: product, imageWidth: imageWidth, ); } } Widget _buildProductCard({ required BuildContext context, required Product product, double? imageWidth, double? imageAspectRatio, }) { final bool isDesktop = isDisplayDesktop(context); // In case of desktop , imageWidth is passed through [DesktopProductCard] in // case of mobile imageAspectRatio is passed through [MobileProductCard]. // Below assert is so that correct combination should always be present. assert(isDesktop && imageWidth != null || !isDesktop && imageAspectRatio != null); final NumberFormat formatter = NumberFormat.simpleCurrency( decimalDigits: 0, locale: Localizations.localeOf(context).toString(), ); final ThemeData theme = Theme.of(context); final FadeInImagePlaceholder imageWidget = FadeInImagePlaceholder( image: AssetImage(product.assetName, package: product.assetPackage), placeholder: Container( color: Colors.black.withOpacity(0.1), width: imageWidth, height: imageWidth == null ? null : imageWidth / product.assetAspectRatio, ), fit: BoxFit.cover, width: isDesktop ? imageWidth : null, height: isDesktop ? null : double.infinity, excludeFromSemantics: true, ); return ScopedModelDescendant<AppStateModel>( builder: (BuildContext context, Widget? child, AppStateModel model) { return Semantics( hint: GalleryLocalizations.of(context)! .shrineScreenReaderProductAddToCart, child: MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { model.addProductToCart(product.id); }, child: child, ), ), ); }, child: Stack( children: <Widget>[ Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ if (isDesktop) imageWidget else AspectRatio( aspectRatio: imageAspectRatio!, child: imageWidget, ), SizedBox( child: Column( children: <Widget>[ const SizedBox(height: 23), SizedBox( width: imageWidth, child: Text( product.name(context), style: theme.textTheme.labelLarge, softWrap: true, textAlign: TextAlign.center, ), ), const SizedBox(height: 4), Text( formatter.format(product.price), style: theme.textTheme.bodySmall, ), ], ), ), ], ), const Padding( padding: EdgeInsets.all(16), child: Icon(Icons.add_shopping_cart), ), ], ), ); }
flutter/dev/integration_tests/new_gallery/lib/studies/shrine/supplemental/product_card.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/shrine/supplemental/product_card.dart", "repo_id": "flutter", "token_count": 1862 }
600
// Copyright 2014 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' show json; import 'dart:io' show sleep, stdout; import 'package:flutter_driver/flutter_driver.dart'; import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; // To run this test for all demos: // flutter drive --profile --trace-startup -t test_driver/transitions_perf.dart -d <device> // To run this test for just Crane, with scrolling: // flutter drive --profile --trace-startup -t test_driver/transitions_perf.dart -d <device> --dart-define=onlyCrane=true // To run this test for just Reply, with animations: // flutter drive --profile --trace-startup -t test_driver/transitions_perf.dart -d <device> --dart-define=onlyReply=true // Enable semantics with the --with_semantics flag // Note: The number of tests executed with timeline collection enabled // significantly impacts heap size of the running app. When run with // --trace-startup, as we do in this test, the VM stores trace events in an // endless buffer instead of a ring buffer. // Demos for which timeline data will be collected using // FlutterDriver.traceAction(). // // These names must match the output of GalleryDemo.describe in // lib/data/demos.dart. const List<String> _profiledDemos = <String>[ 'reply@study', 'shrine@study', 'rally@study', 'crane@study', 'fortnightly@study', 'bottom-navigation@material', 'button@material', 'card@material', 'chip@material', 'dialog@material', 'pickers@material', 'cupertino-alerts@cupertino', 'colors@other', ]; // Demos that will be backed out of within FlutterDriver.runUnsynchronized(); // // These names must match the output of GalleryDemo.describe in // lib/data/demos.dart. const List<String> _unsynchronizedDemos = <String>[ 'progress-indicator@material', 'cupertino-activity-indicator@cupertino', 'colors@other', ]; // Demos that will be not be launched. // // These names must match the output of GalleryDemo.describe in // lib/data/demos.dart. const List<String> _skippedDemos = <String>[]; // All of the gallery demos, identified as "title@category". // // These names are reported by the test app, see _handleMessages() // in transitions_perf.dart. List<String> _allDemos = <String>[]; // SerializableFinders for scrolling actions. final SerializableFinder homeList = find.byValueKey('HomeListView'); final SerializableFinder backButton = find.byValueKey('Back'); final SerializableFinder galleryHeader = find.text('Gallery'); final SerializableFinder categoriesHeader = find.text('Categories'); final SerializableFinder craneFlyList = find.byValueKey('CraneListView-0'); // SerializableFinders for reply study actions. final SerializableFinder replyFab = find.byValueKey('ReplyFab'); final SerializableFinder replySearch = find.byValueKey('ReplySearch'); final SerializableFinder replyEmail = find.byValueKey('ReplyEmail-0'); final SerializableFinder replyLogo = find.byValueKey('ReplyLogo'); final SerializableFinder replySentMailbox = find.byValueKey('Reply-Sent'); final SerializableFinder replyExit = find.byValueKey('ReplyExit'); // Let overscroll animation settle on iOS after driver.scroll. void handleOverscrollAnimation() { sleep(const Duration(seconds: 1)); } /// Scroll to the top of the app, given the current demo. Works with both mobile /// and desktop layouts. Future<void> scrollToTop(SerializableFinder demoItem, FlutterDriver driver) async { stdout.writeln('scrolling to top'); // Scroll to the Categories header. await driver.scroll( demoItem, 0, 5000, const Duration(milliseconds: 200), ); handleOverscrollAnimation(); // Scroll to top. await driver.scroll( categoriesHeader, 0, 500, const Duration(milliseconds: 200), ); handleOverscrollAnimation(); } /// Returns a [Future] that resolves to true if the widget specified by [finder] /// is present, false otherwise. Future<bool> isPresent(SerializableFinder finder, FlutterDriver driver, {Duration timeout = const Duration(seconds: 5)}) async { try { await driver.waitFor(finder, timeout: timeout); return true; } catch (exception) { return false; } } /// Scrolls each demo into view, launches it, then returns to the /// home screen, twice. /// /// Optionally specify a callback to perform further actions for each demo. /// Optionally specify whether a scroll to top should be performed after the /// demo has been opened twice (true by default). Future<void> runDemos( List<String> demos, FlutterDriver driver, { Future<void> Function()? additionalActions, bool scrollToTopWhenDone = true, }) async { String? currentDemoCategory; late SerializableFinder demoList; SerializableFinder? demoItem; for (final String demo in demos) { if (_skippedDemos.contains(demo)) { continue; } stdout.writeln('> $demo'); final String demoCategory = demo.substring(demo.indexOf('@') + 1); if (demoCategory != currentDemoCategory) { // We've switched categories. currentDemoCategory = demoCategory; demoList = find.byValueKey('${demoCategory}DemoList'); // We may want to return to the previous category later. // Reset its scroll (matters for desktop layout). if (demoItem != null) { await scrollToTop(demoItem, driver); } // Scroll to the category list. if (demoCategory != 'study') { stdout.writeln('scrolling to $currentDemoCategory category'); await driver.scrollUntilVisible( homeList, demoList, dyScroll: -1000, timeout: const Duration(seconds: 10), ); } } // Scroll to demo and open it twice. demoItem = find.byValueKey(demo); stdout.writeln('scrolling to demo'); // demoList below may be either the horizontally-scrolling Studies carousel // or vertically scrolling Material/Cupertino/Other demo lists. // // The Studies carousel has scroll physics that snap items to the starting // edge of the widget. TestDriver.scrollUntilVisible scrolls in increments // along the x and y axes; if the distance is too small, the list snaps // back to its previous position, if it's too large, it may scroll too far. // To resolve this, we scroll 75% of the list width/height dimensions on // each increment. final DriverOffset topLeft = await driver.getTopLeft(demoList, timeout: const Duration(seconds: 10)); final DriverOffset bottomRight = await driver.getBottomRight(demoList, timeout: const Duration(seconds: 10)); final double listWidth = bottomRight.dx - topLeft.dx; final double listHeight = bottomRight.dy - topLeft.dy; await driver.scrollUntilVisible( demoList, demoItem, dxScroll: -listWidth * 0.75, dyScroll: -listHeight * 0.75, alignment: 0.5, timeout: const Duration(seconds: 10), ); // We launch each demo twice to be able to measure and compare first and // subsequent builds. for (int i = 0; i < 2; i += 1) { stdout.writeln('tapping demo'); await driver.tap(demoItem); // Launch the demo sleep(const Duration(milliseconds: 500)); if (additionalActions != null) { await additionalActions(); } if (_unsynchronizedDemos.contains(demo)) { await driver.runUnsynchronized<void>(() async { await driver.tap(backButton); }); } else { await driver.tap(backButton); } } stdout.writeln('< Success'); } if (scrollToTopWhenDone) { await scrollToTop(demoItem!, driver); } } void main([List<String> args = const <String>[]]) { group('Flutter Gallery transitions', () { late FlutterDriver driver; late bool isTestingCraneOnly; late bool isTestingReplyOnly; setUpAll(() async { driver = await FlutterDriver.connect(); // See _handleMessages() in transitions_perf.dart. _allDemos = List<String>.from(json.decode( await driver.requestData('demoDescriptions'), ) as List<dynamic>); if (_allDemos.isEmpty) { throw 'no demo names found'; } // See _handleMessages() in transitions_perf.dart. isTestingCraneOnly = await driver.requestData('isTestingCraneOnly') == 'true'; // See _handleMessages() in transitions_perf.dart. isTestingReplyOnly = await driver.requestData('isTestingReplyOnly') == 'true'; if (args.contains('--with_semantics')) { stdout.writeln('Enabeling semantics...'); await driver.setSemantics(true); } await isPresent(galleryHeader, driver); }); tearDownAll(() async { await driver.close(); stdout.writeln( 'Timeline summaries for profiled demos have been output to the build/ directory.'); }); test('only Crane', () async { if (!isTestingCraneOnly) { return; } // Collect timeline data for just the Crane study. final Timeline timeline = await driver.traceAction( () async { await runDemos( <String>['crane@study'], driver, additionalActions: () async => driver.scroll( craneFlyList, 0, -1000, const Duration(seconds: 1), ), scrollToTopWhenDone: false, ); }, streams: const <TimelineStream>[ TimelineStream.dart, TimelineStream.embedder, ], ); final TimelineSummary summary = TimelineSummary.summarize(timeline); await summary.writeTimelineToFile('transitions-crane', pretty: true); }, timeout: Timeout.none); test('only Reply', () async { if (!isTestingReplyOnly) { return; } // Collect timeline data for just the Crane study. final Timeline timeline = await driver.traceAction( () async { await runDemos( <String>['reply@study'], driver, additionalActions: () async { // Tap compose fab to trigger open container transform/fade through await driver.tap(replyFab); // Exit compose page await driver.tap(replyExit); // Tap search icon to trigger shared axis transition await driver.tap(replySearch); // Exit search page await driver.tap(replyExit); // Tap on email to trigger open container transform await driver.tap(replyEmail); // Exit email page await driver.tap(replyExit); // Tap Reply logo to open bottom drawer/navigation rail await driver.tap(replyLogo); // Tap Reply logo to close bottom drawer/navigation rail await driver.tap(replyLogo); // Tap Reply logo to open bottom drawer/navigation rail await driver.tap(replyLogo); // Tap sent mailbox destination to trigger fade through transition await driver.tap(replySentMailbox); }, scrollToTopWhenDone: false, ); }, streams: const <TimelineStream>[ TimelineStream.dart, TimelineStream.embedder, ], ); final TimelineSummary summary = TimelineSummary.summarize(timeline); await summary.writeTimelineToFile('transitions-reply', pretty: true); }, timeout: Timeout.none); test('all demos', () async { if (isTestingCraneOnly || isTestingReplyOnly) { return; } // Collect timeline data for just a limited set of demos to avoid OOMs. final Timeline timeline = await driver.traceAction( () async { await runDemos(_profiledDemos, driver); }, streams: const <TimelineStream>[ TimelineStream.dart, TimelineStream.embedder, ], retainPriorEvents: true, ); final TimelineSummary summary = TimelineSummary.summarize(timeline); await summary.writeTimelineToFile('transitions', pretty: true); // Execute the remaining tests. final Set<String> unprofiledDemos = Set<String>.from(_allDemos) ..removeAll(_profiledDemos); await runDemos(unprofiledDemos.toList(), driver); }, timeout: Timeout.none); }); }
flutter/dev/integration_tests/new_gallery/test_driver/transitions_perf_test.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/test_driver/transitions_perf_test.dart", "repo_id": "flutter", "token_count": 4537 }
601
<?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="hIq-15-ITu"> <device id="retina4_7" orientation="portrait"> <adaptation id="fullscreen"/> </device> <dependencies> <deployment identifier="iOS"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <!--Flutter View Controller--> <scene sceneID="tne-QT-ifu"> <objects> <viewController id="BYZ-38-t0r" customClass="FlutterViewController" sceneMemberID="viewController"> <layoutGuides> <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/> <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/> </layoutGuides> <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC"> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> </view> <navigationItem key="navigationItem" id="GUu-dA-3Cs"/> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="1055.2" y="123.68815592203899"/> </scene> <!--Test Navigation Controller--> <scene sceneID="dG3-WE-vKQ"> <objects> <navigationController automaticallyAdjustsScrollViewInsets="NO" id="hIq-15-ITu" customClass="TestNavigationController" sceneMemberID="viewController"> <toolbarItems/> <navigationBar key="navigationBar" contentMode="scaleToFill" id="Tam-uN-fcI"> <rect key="frame" x="0.0" y="0.0" width="375" height="44"/> <autoresizingMask key="autoresizingMask"/> </navigationBar> <nil name="viewControllers"/> <connections> <segue destination="BYZ-38-t0r" kind="relationship" relationship="rootViewController" id="0aD-1I-Wci"/> </connections> </navigationController> <placeholder placeholderIdentifier="IBFirstResponder" id="8XK-Xi-qiO" userLabel="First Responder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="189.59999999999999" y="777.66116941529242"/> </scene> </scenes> </document>
flutter/dev/integration_tests/platform_interaction/ios/Runner/Base.lproj/Main.storyboard/0
{ "file_path": "flutter/dev/integration_tests/platform_interaction/ios/Runner/Base.lproj/Main.storyboard", "repo_id": "flutter", "token_count": 1465 }
602
// Copyright 2014 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:ui' as ui; import 'package:flutter_driver/driver_extension.dart'; // To use this test: "flutter drive --route '/smuggle-it' lib/route.dart" void main() { enableFlutterDriverExtension(handler: (String? message) async { return ui.PlatformDispatcher.instance.defaultRouteName; }); }
flutter/dev/integration_tests/ui/lib/route.dart/0
{ "file_path": "flutter/dev/integration_tests/ui/lib/route.dart", "repo_id": "flutter", "token_count": 148 }
603
// Copyright 2014 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_driver/flutter_driver.dart'; import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; void main() { group('flutter run test --route', () { late FlutterDriver driver; setUpAll(() async { driver = await FlutterDriver.connect(); }); tearDownAll(() async { await driver.close(); }); test('sanity check flutter drive --route', () async { // This only makes sense if you ran the test as described // in the test file. It's normally run from devicelab. expect(await driver.requestData('route'), '/smuggle-it'); }, timeout: Timeout.none); }); }
flutter/dev/integration_tests/ui/test_driver/route_test.dart/0
{ "file_path": "flutter/dev/integration_tests/ui/test_driver/route_test.dart", "repo_id": "flutter", "token_count": 267 }
604
name: web_integration description: Integration test for web compilation. environment: sdk: '>=3.2.0-0 <4.0.0' flutter: assets: - lib/a.dart - lib/b.dart uses-material-design: true dependencies: flutter: sdk: flutter characters: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" material_color_utilities: 0.8.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" meta: 1.12.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" # PUBSPEC CHECKSUM: 6f95
flutter/dev/integration_tests/web/pubspec.yaml/0
{ "file_path": "flutter/dev/integration_tests/web/pubspec.yaml", "repo_id": "flutter", "token_count": 292 }
605
# wide_gamut_test An integration test used for testing wide gamut color support in the engine. ## Local run ```sh flutter create --platforms="ios" --no-overwrite . flutter test integration_test/app_test.dart ```
flutter/dev/integration_tests/wide_gamut_test/README.md/0
{ "file_path": "flutter/dev/integration_tests/wide_gamut_test/README.md", "repo_id": "flutter", "token_count": 68 }
606
// Copyright 2014 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. #include "flutter_window.h" #include <optional> #include <mutex> #include <dwmapi.h> #include <flutter/method_channel.h> #include <flutter/standard_method_codec.h> #include "flutter/generated_plugin_registrant.h" #include "utils.h" /// Window attribute that enables dark mode window decorations. /// /// Redefined in case the developer's machine has a Windows SDK older than /// version 10.0.22000.0. /// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute #ifndef DWMWA_USE_IMMERSIVE_DARK_MODE #define DWMWA_USE_IMMERSIVE_DARK_MODE 20 #endif /// Registry key for app theme preference. /// /// A value of 0 indicates apps should use dark mode. A non-zero or missing /// value indicates apps should use light mode. constexpr const wchar_t kGetPreferredBrightnessRegKey[] = L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; FlutterWindow::FlutterWindow(const flutter::DartProject& project) : project_(project) {} FlutterWindow::~FlutterWindow() {} bool FlutterWindow::OnCreate() { if (!Win32Window::OnCreate()) { return false; } RECT frame = GetClientArea(); // The size here must match the window dimensions to avoid unnecessary surface // creation / destruction in the startup path. flutter_controller_ = std::make_unique<flutter::FlutterViewController>( frame.right - frame.left, frame.bottom - frame.top, project_); // Ensure that basic setup of the controller was successful. if (!flutter_controller_->engine() || !flutter_controller_->view()) { return false; } RegisterPlugins(flutter_controller_->engine()); SetChildContent(flutter_controller_->view()->GetNativeWindow()); static std::mutex visible_mutex; static bool visible = false; flutter_controller_->engine()->SetNextFrameCallback([&]() { std::scoped_lock lock(visible_mutex); this->Show(); visible = true; }); // Flutter can complete the first frame before the "show window" callback is // registered. The following call ensures a frame is pending to ensure the // window is shown. It is a no-op if the first frame hasn't completed yet. flutter_controller_->ForceRedraw(); // Create a method channel to check the window's visibility. flutter::MethodChannel<> channel( flutter_controller_->engine()->messenger(), "tests.flutter.dev/windows_startup_test", &flutter::StandardMethodCodec::GetInstance()); channel.SetMethodCallHandler( [&](const flutter::MethodCall<>& call, std::unique_ptr<flutter::MethodResult<>> result) { std::string method = call.method_name(); if (method == "isWindowVisible") { std::scoped_lock lock(visible_mutex); result->Success(visible); } else if (method == "isAppDarkModeEnabled") { BOOL enabled; HRESULT hr = DwmGetWindowAttribute(GetHandle(), DWMWA_USE_IMMERSIVE_DARK_MODE, &enabled, sizeof(enabled)); if (SUCCEEDED(hr)) { result->Success((bool)enabled); } else if (hr == E_INVALIDARG) { // Fallback if the operating system doesn't support dark mode. result->Success(false); } else { result->Error("error", "Received result handle " + hr); } } else if (method == "isSystemDarkModeEnabled") { DWORD data; DWORD data_size = sizeof(data); LONG status = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, kGetPreferredBrightnessRegValue, RRF_RT_REG_DWORD, nullptr, &data, &data_size); if (status == ERROR_SUCCESS) { // Preferred brightness is 0 if dark mode is enabled, // otherwise non-zero. result->Success(data == 0); } else if (status == ERROR_FILE_NOT_FOUND) { // Fallback if the operating system doesn't support dark mode. result->Success(false); } else { result->Error("error", "Received status " + status); } } else if (method == "convertString") { const flutter::EncodableValue* argument = call.arguments(); const std::vector<int32_t> code_points = std::get<std::vector<int32_t>>(*argument); std::vector<wchar_t> wide_str; for (int32_t code_point : code_points) { wide_str.push_back((wchar_t)(code_point)); } wide_str.push_back((wchar_t)0); const std::string string = Utf8FromUtf16(wide_str.data()); result->Success(string); } else { result->NotImplemented(); } }); return true; } void FlutterWindow::OnDestroy() { if (flutter_controller_) { flutter_controller_ = nullptr; } Win32Window::OnDestroy(); } LRESULT FlutterWindow::MessageHandler(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { // Give Flutter, including plugins, an opportunity to handle window messages. if (flutter_controller_) { std::optional<LRESULT> result = flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, lparam); if (result) { return *result; } } switch (message) { case WM_FONTCHANGE: flutter_controller_->engine()->ReloadSystemFonts(); break; } return Win32Window::MessageHandler(hwnd, message, wparam, lparam); }
flutter/dev/integration_tests/windows_startup_test/windows/runner/flutter_window.cpp/0
{ "file_path": "flutter/dev/integration_tests/windows_startup_test/windows/runner/flutter_window.cpp", "repo_id": "flutter", "token_count": 2281 }
607
// Copyright 2014 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 'package:flutter/services.dart'; void main() { runApp( const MaterialApp( title: 'Menu Tester', home: Material( child: Home(), ), ), ); } class Home extends StatefulWidget { const Home({super.key}); @override State<Home> createState() => _HomeState(); } class _HomeState extends State<Home> { final MenuController _controller = MenuController(); VisualDensity _density = VisualDensity.standard; TextDirection _textDirection = TextDirection.ltr; double _extraPadding = 0; bool _addItem = false; bool _accelerators = true; bool _transparent = false; bool _funkyTheme = false; @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); MenuThemeData menuTheme = MenuTheme.of(context); MenuBarThemeData menuBarTheme = MenuBarTheme.of(context); MenuButtonThemeData menuButtonTheme = MenuButtonTheme.of(context); if (_funkyTheme) { menuTheme = const MenuThemeData( style: MenuStyle( shape: MaterialStatePropertyAll<OutlinedBorder>( RoundedRectangleBorder( borderRadius: BorderRadius.all( Radius.circular(10), ), ), ), backgroundColor: MaterialStatePropertyAll<Color?>(Colors.blue), elevation: MaterialStatePropertyAll<double?>(10), padding: MaterialStatePropertyAll<EdgeInsetsDirectional>( EdgeInsetsDirectional.all(20), ), ), ); menuButtonTheme = const MenuButtonThemeData( style: ButtonStyle( shape: MaterialStatePropertyAll<OutlinedBorder>(StadiumBorder()), backgroundColor: MaterialStatePropertyAll<Color?>(Colors.green), foregroundColor: MaterialStatePropertyAll<Color?>(Colors.white), ), ); menuBarTheme = const MenuBarThemeData( style: MenuStyle( shape: MaterialStatePropertyAll<OutlinedBorder>(RoundedRectangleBorder()), backgroundColor: MaterialStatePropertyAll<Color?>(Colors.blue), elevation: MaterialStatePropertyAll<double?>(10), padding: MaterialStatePropertyAll<EdgeInsetsDirectional>( EdgeInsetsDirectional.all(20), ), ), ); } return SafeArea( child: Padding( padding: EdgeInsets.all(_extraPadding), child: Directionality( textDirection: _textDirection, child: Theme( data: theme.copyWith( visualDensity: _density, menuTheme: _transparent ? MenuThemeData( style: MenuStyle( backgroundColor: MaterialStatePropertyAll<Color>( Colors.blue.withOpacity(0.12), ), elevation: const MaterialStatePropertyAll<double>(0), ), ) : menuTheme, menuBarTheme: menuBarTheme, menuButtonTheme: menuButtonTheme, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ _TestMenus( menuController: _controller, accelerators: _accelerators, addItem: _addItem, ), Expanded( child: SingleChildScrollView( child: _Controls( menuController: _controller, density: _density, addItem: _addItem, accelerators: _accelerators, transparent: _transparent, funkyTheme: _funkyTheme, extraPadding: _extraPadding, textDirection: _textDirection, onDensityChanged: (VisualDensity value) { setState(() { _density = value; }); }, onTextDirectionChanged: (TextDirection value) { setState(() { _textDirection = value; }); }, onExtraPaddingChanged: (double value) { setState(() { _extraPadding = value; }); }, onAddItemChanged: (bool value) { setState(() { _addItem = value; }); }, onAcceleratorsChanged: (bool value) { setState(() { _accelerators = value; }); }, onTransparentChanged: (bool value) { setState(() { _transparent = value; }); }, onFunkyThemeChanged: (bool value) { setState(() { _funkyTheme = value; }); }, ), ), ), ], ), ), ), ), ); } } class _Controls extends StatefulWidget { const _Controls({ required this.density, required this.textDirection, required this.extraPadding, this.addItem = false, this.accelerators = true, this.transparent = false, this.funkyTheme = false, required this.onDensityChanged, required this.onTextDirectionChanged, required this.onExtraPaddingChanged, required this.onAddItemChanged, required this.onAcceleratorsChanged, required this.onTransparentChanged, required this.onFunkyThemeChanged, required this.menuController, }); final VisualDensity density; final TextDirection textDirection; final double extraPadding; final bool addItem; final bool accelerators; final bool transparent; final bool funkyTheme; final ValueChanged<VisualDensity> onDensityChanged; final ValueChanged<TextDirection> onTextDirectionChanged; final ValueChanged<double> onExtraPaddingChanged; final ValueChanged<bool> onAddItemChanged; final ValueChanged<bool> onAcceleratorsChanged; final ValueChanged<bool> onTransparentChanged; final ValueChanged<bool> onFunkyThemeChanged; final MenuController menuController; @override State<_Controls> createState() => _ControlsState(); } class _ControlsState extends State<_Controls> { final FocusNode _focusNode = FocusNode(debugLabel: 'Floating'); @override void dispose() { _focusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Center( child: SingleChildScrollView( child: Column( children: <Widget>[ MenuAnchor( childFocusNode: _focusNode, style: const MenuStyle(alignment: AlignmentDirectional.topEnd), alignmentOffset: const Offset(100, -8), menuChildren: <Widget>[ MenuItemButton( shortcut: TestMenu.standaloneMenu1.shortcut, onPressed: () { _itemSelected(TestMenu.standaloneMenu1); }, child: MenuAcceleratorLabel(TestMenu.standaloneMenu1.label), ), MenuItemButton( leadingIcon: const Icon(Icons.send), trailingIcon: const Icon(Icons.mail), onPressed: () { _itemSelected(TestMenu.standaloneMenu2); }, child: MenuAcceleratorLabel(TestMenu.standaloneMenu2.label), ), ], builder: (BuildContext context, MenuController controller, Widget? child) { return TextButton( focusNode: _focusNode, onPressed: () { if (controller.isOpen) { controller.close(); } else { controller.open(); } }, child: child!, ); }, child: const MenuAcceleratorLabel('Open Menu'), ), ConstrainedBox( constraints: const BoxConstraints(maxWidth: 400), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ _ControlSlider( label: 'Extra Padding: ${widget.extraPadding.toStringAsFixed(1)}', value: widget.extraPadding, max: 40, divisions: 20, onChanged: (double value) { widget.onExtraPaddingChanged(value); }, ), _ControlSlider( label: 'Horizontal Density: ${widget.density.horizontal.toStringAsFixed(1)}', value: widget.density.horizontal, max: 4, min: -4, divisions: 12, onChanged: (double value) { widget.onDensityChanged( VisualDensity( horizontal: value, vertical: widget.density.vertical, ), ); }, ), _ControlSlider( label: 'Vertical Density: ${widget.density.vertical.toStringAsFixed(1)}', value: widget.density.vertical, max: 4, min: -4, divisions: 12, onChanged: (double value) { widget.onDensityChanged( VisualDensity( horizontal: widget.density.horizontal, vertical: value, ), ); }, ), ], ), ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Checkbox( value: widget.textDirection == TextDirection.rtl, onChanged: (bool? value) { if (value ?? false) { widget.onTextDirectionChanged(TextDirection.rtl); } else { widget.onTextDirectionChanged(TextDirection.ltr); } }, ), const Text('RTL Text') ], ), Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Checkbox( value: widget.addItem, onChanged: (bool? value) { if (value ?? false) { widget.onAddItemChanged(true); } else { widget.onAddItemChanged(false); } }, ), const Text('Add Item') ], ), Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Checkbox( value: widget.accelerators, onChanged: (bool? value) { if (value ?? false) { widget.onAcceleratorsChanged(true); } else { widget.onAcceleratorsChanged(false); } }, ), const Text('Enable Accelerators') ], ), Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Checkbox( value: widget.transparent, onChanged: (bool? value) { if (value ?? false) { widget.onTransparentChanged(true); } else { widget.onTransparentChanged(false); } }, ), const Text('Transparent') ], ), Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Checkbox( value: widget.funkyTheme, onChanged: (bool? value) { if (value ?? false) { widget.onFunkyThemeChanged(true); } else { widget.onFunkyThemeChanged(false); } }, ), const Text('Funky Theme') ], ), ], ), ], ), ), ); } void _itemSelected(TestMenu item) { debugPrint('App: Selected item ${item.label}'); } } class _ControlSlider extends StatelessWidget { const _ControlSlider({ required this.label, required this.value, required this.onChanged, this.min = 0, this.max = 1, this.divisions, }); final String label; final double value; final ValueChanged<double> onChanged; final double min; final double max; final int? divisions; @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ Container( alignment: AlignmentDirectional.centerEnd, constraints: const BoxConstraints(minWidth: 150), child: Text(label), ), Expanded( child: Slider( value: value, min: min, max: max, divisions: divisions, onChanged: onChanged, ), ), ], ); } } class _TestMenus extends StatefulWidget { const _TestMenus({ required this.menuController, this.addItem = false, this.accelerators = false, }); final MenuController menuController; final bool addItem; final bool accelerators; @override State<_TestMenus> createState() => _TestMenusState(); } class _TestMenusState extends State<_TestMenus> { final TextEditingController textController = TextEditingController(); bool? checkboxState = false; TestMenu? radioValue; ShortcutRegistryEntry? _shortcutsEntry; void _itemSelected(TestMenu item) { debugPrint('App: Selected item ${item.label}'); } void _openItem(TestMenu item) { debugPrint('App: Opened item ${item.label}'); } void _closeItem(TestMenu item) { debugPrint('App: Closed item ${item.label}'); } void _setRadio(TestMenu? item) { debugPrint('App: Set Radio item ${item?.label}'); setState(() { radioValue = item; }); } void _setCheck(TestMenu item) { debugPrint('App: Set Checkbox item ${item.label}'); setState(() { checkboxState = switch (checkboxState) { false => true, true => null, null => false, }; }); } @override void didChangeDependencies() { super.didChangeDependencies(); _shortcutsEntry?.dispose(); final Map<ShortcutActivator, Intent> shortcuts = <ShortcutActivator, Intent>{}; for (final TestMenu item in TestMenu.values) { if (item.shortcut == null) { continue; } switch (item) { case TestMenu.radioMenu1: case TestMenu.radioMenu2: case TestMenu.radioMenu3: shortcuts[item.shortcut!] = VoidCallbackIntent(() => _setRadio(item)); case TestMenu.subMenu1: shortcuts[item.shortcut!] = VoidCallbackIntent(() => _setCheck(item)); case TestMenu.mainMenu1: case TestMenu.mainMenu2: case TestMenu.mainMenu3: case TestMenu.mainMenu4: case TestMenu.subMenu2: case TestMenu.subMenu3: case TestMenu.subMenu4: case TestMenu.subMenu5: case TestMenu.subMenu6: case TestMenu.subMenu7: case TestMenu.subMenu8: case TestMenu.subSubMenu1: case TestMenu.subSubMenu2: case TestMenu.subSubMenu3: case TestMenu.subSubSubMenu1: case TestMenu.testButton: case TestMenu.standaloneMenu1: case TestMenu.standaloneMenu2: shortcuts[item.shortcut!] = VoidCallbackIntent(() => _itemSelected(item)); } } _shortcutsEntry = ShortcutRegistry.of(context).addAll(shortcuts); } @override void dispose() { _shortcutsEntry?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Row( children: <Widget>[ Expanded( child: MenuBar( controller: widget.menuController, children: createTestMenus( onPressed: _itemSelected, onOpen: _openItem, onClose: _closeItem, onCheckboxChanged: (TestMenu menu, bool? value) { _setCheck(menu); }, onRadioChanged: _setRadio, checkboxValue: checkboxState, radioValue: radioValue, menuController: widget.menuController, textEditingController: textController, includeExtraGroups: widget.addItem, accelerators: widget.accelerators, ), ), ), ], ); } } List<Widget> createTestMenus({ void Function(TestMenu)? onPressed, void Function(TestMenu, bool?)? onCheckboxChanged, void Function(TestMenu?)? onRadioChanged, void Function(TestMenu)? onOpen, void Function(TestMenu)? onClose, Map<TestMenu, MenuSerializableShortcut> shortcuts = const <TestMenu, MenuSerializableShortcut>{}, bool? checkboxValue, TestMenu? radioValue, MenuController? menuController, TextEditingController? textEditingController, bool includeExtraGroups = false, bool accelerators = false, }) { Widget submenuButton( TestMenu menu, { required List<Widget> menuChildren, }) { return SubmenuButton( onOpen: onOpen != null ? () => onOpen(menu) : null, onClose: onClose != null ? () => onClose(menu) : null, menuChildren: menuChildren, child: accelerators ? MenuAcceleratorLabel(menu.acceleratorLabel) : Text(menu.label), ); } Widget menuItemButton( TestMenu menu, { bool enabled = true, Widget? leadingIcon, Widget? trailingIcon, Key? key, }) { return MenuItemButton( key: key, onPressed: enabled && onPressed != null ? () => onPressed(menu) : null, shortcut: shortcuts[menu], leadingIcon: leadingIcon, trailingIcon: trailingIcon, child: accelerators ? MenuAcceleratorLabel(menu.acceleratorLabel) : Text(menu.label), ); } Widget checkboxMenuButton( TestMenu menu, { bool enabled = true, bool tristate = false, Widget? leadingIcon, Widget? trailingIcon, Key? key, }) { return CheckboxMenuButton( key: key, value: checkboxValue, tristate: tristate, onChanged: enabled && onCheckboxChanged != null ? (bool? value) => onCheckboxChanged(menu, value) : null, shortcut: menu.shortcut, trailingIcon: trailingIcon, child: accelerators ? MenuAcceleratorLabel(menu.acceleratorLabel) : Text(menu.label), ); } Widget radioMenuButton( TestMenu menu, { bool enabled = true, bool toggleable = false, Widget? leadingIcon, Widget? trailingIcon, Key? key, }) { return RadioMenuButton<TestMenu>( key: key, groupValue: radioValue, value: menu, toggleable: toggleable, onChanged: enabled && onRadioChanged != null ? onRadioChanged : null, shortcut: menu.shortcut, trailingIcon: trailingIcon, child: accelerators ? MenuAcceleratorLabel(menu.acceleratorLabel) : Text(menu.label), ); } final List<Widget> result = <Widget>[ submenuButton( TestMenu.mainMenu1, menuChildren: <Widget>[ checkboxMenuButton( TestMenu.subMenu1, tristate: true, trailingIcon: const Icon(Icons.assessment), ), radioMenuButton( TestMenu.radioMenu1, toggleable: true, trailingIcon: const Icon(Icons.assessment), ), radioMenuButton( TestMenu.radioMenu2, toggleable: true, trailingIcon: const Icon(Icons.assessment), ), radioMenuButton( TestMenu.radioMenu3, toggleable: true, trailingIcon: const Icon(Icons.assessment), ), menuItemButton( TestMenu.subMenu2, leadingIcon: const Icon(Icons.send), trailingIcon: const Icon(Icons.mail), ), ], ), submenuButton( TestMenu.mainMenu2, menuChildren: <Widget>[ MenuAcceleratorCallbackBinding( onInvoke: onPressed != null ? () { onPressed.call(TestMenu.testButton); menuController?.close(); } : null, child: TextButton( onPressed: onPressed != null ? () { onPressed.call(TestMenu.testButton); menuController?.close(); } : null, child: accelerators ? MenuAcceleratorLabel(TestMenu.testButton.acceleratorLabel) : Text(TestMenu.testButton.label), ), ), menuItemButton(TestMenu.subMenu3), ], ), submenuButton( TestMenu.mainMenu3, menuChildren: <Widget>[ menuItemButton(TestMenu.subMenu8), MenuItemButton( onPressed: () { debugPrint('Focused Item: $primaryFocus'); }, child: const Text('Print Focused Item'), ) ], ), submenuButton( TestMenu.mainMenu4, menuChildren: <Widget>[ MenuItemButton( onPressed: () { debugPrint('Activated text input item with ${textEditingController?.text} as a value.'); }, child: SizedBox( width: 200, child: TextField( controller: textEditingController, onSubmitted: (String value) { debugPrint('String $value submitted.'); }, ), ), ), submenuButton( TestMenu.subMenu5, menuChildren: <Widget>[ menuItemButton(TestMenu.subSubMenu1), menuItemButton(TestMenu.subSubMenu2), if (includeExtraGroups) submenuButton( TestMenu.subSubMenu3, menuChildren: <Widget>[ for (int i=0; i < 100; ++i) MenuItemButton( onPressed: () {}, child: Text('Menu Item $i'), ), ], ), ], ), menuItemButton(TestMenu.subMenu6, enabled: false), menuItemButton(TestMenu.subMenu7), menuItemButton(TestMenu.subMenu7), menuItemButton(TestMenu.subMenu8), ], ), ]; return result; } enum TestMenu { mainMenu1('Menu 1'), mainMenu2('M&enu &2'), mainMenu3('Me&nu &3'), mainMenu4('Men&u &4'), radioMenu1('Radio Menu One', SingleActivator(LogicalKeyboardKey.digit1, control: true)), radioMenu2('Radio Menu Two', SingleActivator(LogicalKeyboardKey.digit2, control: true)), radioMenu3('Radio Menu Three', SingleActivator(LogicalKeyboardKey.digit3, control: true)), subMenu1('Sub Menu &1', SingleActivator(LogicalKeyboardKey.keyB, control: true)), subMenu2('Sub Menu &2'), subMenu3('Sub Menu &3', SingleActivator(LogicalKeyboardKey.enter, control: true)), subMenu4('Sub Menu &4'), subMenu5('Sub Menu &5'), subMenu6('Sub Menu &6', SingleActivator(LogicalKeyboardKey.tab, control: true)), subMenu7('Sub Menu &7'), subMenu8('Sub Menu &8'), subSubMenu1('Sub Sub Menu &1', SingleActivator(LogicalKeyboardKey.f10, control: true)), subSubMenu2('Sub Sub Menu &2'), subSubMenu3('Sub Sub Menu &3'), subSubSubMenu1('Sub Sub Sub Menu &1', SingleActivator(LogicalKeyboardKey.f11, control: true)), testButton('&TEST && &&& Button &'), standaloneMenu1('Standalone Menu &1', SingleActivator(LogicalKeyboardKey.keyC, control: true)), standaloneMenu2('Standalone Menu &2'); const TestMenu(this.acceleratorLabel, [this.shortcut]); final MenuSerializableShortcut? shortcut; final String acceleratorLabel; // Strip the accelerator markers. String get label => MenuAcceleratorLabel.stripAcceleratorMarkers(acceleratorLabel); }
flutter/dev/manual_tests/lib/menu_anchor.dart/0
{ "file_path": "flutter/dev/manual_tests/lib/menu_anchor.dart", "repo_id": "flutter", "token_count": 12947 }
608
// Copyright 2014 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:io'; void _validate(List<String> args) { bool errors = false; if (!File('bin/internal/engine.version').existsSync()) { errors = true; print('This program must be run from the root of your flutter repository.'); } if (!File('../engine/src/flutter/DEPS').existsSync()) { errors = true; print('This program assumes the engine directory is a sibling to the flutter repository directory.'); } if (args.length != 1) { errors = true; print('This program takes the engine revision as a single argument.'); } if (errors) { exit(-1); } } const String engineRepo = '../engine/src/flutter'; Future<void> main(List<String> args) async { _validate(args); await _fetchUpstream(); await _fetchUpstream(engineRepo); String? flutterRevision; await for (final FlutterEngineRevision revision in _logEngineVersions()) { if (!await containsRevision(args[0], revision.engineRevision)) { if (flutterRevision == null) { print('Revision not found.'); exit(-1); } print('earliest revision: $flutterRevision'); print('Tags that contain this engine revision:'); print(await _tagsForRevision(flutterRevision)); exit(0); } flutterRevision = revision.flutterRevision; } } Future<void> _fetchUpstream([String workingDirectory = '.']) async { print('Fetching remotes for "$workingDirectory" - you may be prompted for SSH credentials by git.'); final ProcessResult fetchResult = await Process.run( 'git', <String>[ 'fetch', '--all', ], workingDirectory: workingDirectory, ); if (fetchResult.exitCode != 0) { throw Exception('Failed to fetch upstream in repository $workingDirectory'); } } Future<String> _tagsForRevision(String flutterRevision) async { final ProcessResult tagResult = await Process.run( 'git', <String>[ 'tag', '--contains', flutterRevision, ], ); return tagResult.stdout as String; } Future<bool> containsRevision(String ancestorRevision, String revision) async { final ProcessResult result = await Process.run( 'git', <String>[ 'merge-base', '--is-ancestor', ancestorRevision, revision, ], workingDirectory: engineRepo, ); return result.exitCode == 0; } Stream<FlutterEngineRevision> _logEngineVersions() async* { final ProcessResult result = await Process.run( 'git', <String>[ 'log', '--oneline', '-p', '--', 'bin/internal/engine.version', ], ); if (result.exitCode != 0) { print(result.stderr); throw Exception('Failed to log bin/internal/engine.version'); } final List<String> lines = (result.stdout as String).split('\n'); int index = 0; while (index < lines.length - 1) { final String flutterRevision = lines[index].split(' ').first; index += 1; while (!lines[index].startsWith('+') || lines[index].startsWith('+++')) { index += 1; } if (index >= lines.length) { break; } final String engineRevision = lines[index].substring(1); yield FlutterEngineRevision(flutterRevision, engineRevision); index += lines[index + 1].startsWith(r'\ ') ? 2 : 1; } } class FlutterEngineRevision { const FlutterEngineRevision(this.flutterRevision, this.engineRevision); final String flutterRevision; final String engineRevision; @override String toString() => '$flutterRevision: $engineRevision'; }
flutter/dev/tools/find_engine_commit.dart/0
{ "file_path": "flutter/dev/tools/find_engine_commit.dart", "repo_id": "flutter", "token_count": 1300 }
609
{ "version": "v0_206", "md.comp.checkbox.container.size": 18.0, "md.comp.checkbox.error.focus.state-layer.color": "error", "md.comp.checkbox.error.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.checkbox.error.hover.state-layer.color": "error", "md.comp.checkbox.error.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity", "md.comp.checkbox.error.pressed.state-layer.color": "error", "md.comp.checkbox.error.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity", "md.comp.checkbox.focus.indicator.color": "secondary", "md.comp.checkbox.focus.indicator.outline.offset": "md.sys.state.focus-indicator.outer-offset", "md.comp.checkbox.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness", "md.comp.checkbox.icon.size": 18.0, "md.comp.checkbox.selected.container.color": "primary", "md.comp.checkbox.selected.disabled.container.color": "onSurface", "md.comp.checkbox.selected.disabled.container.opacity": 0.38, "md.comp.checkbox.selected.disabled.container.outline.width": 0.0, "md.comp.checkbox.selected.disabled.icon.color": "surface", "md.comp.checkbox.selected.error.container.color": "error", "md.comp.checkbox.selected.error.focus.container.color": "error", "md.comp.checkbox.selected.error.focus.icon.color": "onError", "md.comp.checkbox.selected.error.hover.container.color": "error", "md.comp.checkbox.selected.error.hover.icon.color": "onError", "md.comp.checkbox.selected.error.icon.color": "onError", "md.comp.checkbox.selected.error.pressed.container.color": "error", "md.comp.checkbox.selected.error.pressed.icon.color": "onError", "md.comp.checkbox.selected.focus.container.color": "primary", "md.comp.checkbox.selected.focus.icon.color": "onPrimary", "md.comp.checkbox.selected.focus.outline.width": 0.0, "md.comp.checkbox.selected.focus.state-layer.color": "primary", "md.comp.checkbox.selected.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.checkbox.selected.hover.container.color": "primary", "md.comp.checkbox.selected.hover.icon.color": "onPrimary", "md.comp.checkbox.selected.hover.outline.width": 0.0, "md.comp.checkbox.selected.hover.state-layer.color": "primary", "md.comp.checkbox.selected.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity", "md.comp.checkbox.selected.icon.color": "onPrimary", "md.comp.checkbox.selected.outline.width": 0.0, "md.comp.checkbox.selected.pressed.container.color": "primary", "md.comp.checkbox.selected.pressed.icon.color": "onPrimary", "md.comp.checkbox.selected.pressed.outline.width": 0.0, "md.comp.checkbox.selected.pressed.state-layer.color": "onSurface", "md.comp.checkbox.selected.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity", "md.comp.checkbox.state-layer.shape": "md.sys.shape.corner.full", "md.comp.checkbox.state-layer.size": 40.0, "md.comp.checkbox.unselected.disabled.container.opacity": 0.38, "md.comp.checkbox.unselected.disabled.outline.color": "onSurface", "md.comp.checkbox.unselected.disabled.outline.width": 2.0, "md.comp.checkbox.unselected.error.focus.outline.color": "error", "md.comp.checkbox.unselected.error.hover.outline.color": "error", "md.comp.checkbox.unselected.error.outline.color": "error", "md.comp.checkbox.unselected.error.pressed.outline.color": "error", "md.comp.checkbox.unselected.focus.outline.color": "onSurface", "md.comp.checkbox.unselected.focus.outline.width": 2.0, "md.comp.checkbox.unselected.focus.state-layer.color": "onSurface", "md.comp.checkbox.unselected.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.checkbox.unselected.hover.outline.color": "onSurface", "md.comp.checkbox.unselected.hover.outline.width": 2.0, "md.comp.checkbox.unselected.hover.state-layer.color": "onSurface", "md.comp.checkbox.unselected.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity", "md.comp.checkbox.unselected.outline.color": "onSurfaceVariant", "md.comp.checkbox.unselected.outline.width": 2.0, "md.comp.checkbox.unselected.pressed.outline.color": "onSurface", "md.comp.checkbox.unselected.pressed.outline.width": 2.0, "md.comp.checkbox.unselected.pressed.state-layer.color": "primary", "md.comp.checkbox.unselected.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity" }
flutter/dev/tools/gen_defaults/data/checkbox.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/checkbox.json", "repo_id": "flutter", "token_count": 1641 }
610
{ "version": "v0_206", "md.comp.fab.primary.container.color": "primaryContainer", "md.comp.fab.primary.container.elevation": "md.sys.elevation.level3", "md.comp.fab.primary.container.height": 56.0, "md.comp.fab.primary.container.shadow-color": "shadow", "md.comp.fab.primary.container.shape": "md.sys.shape.corner.large", "md.comp.fab.primary.container.width": 56.0, "md.comp.fab.primary.focus.container.elevation": "md.sys.elevation.level3", "md.comp.fab.primary.focus.icon.color": "onPrimaryContainer", "md.comp.fab.primary.focus.indicator.color": "secondary", "md.comp.fab.primary.focus.indicator.outline.offset": "md.sys.state.focus-indicator.outer-offset", "md.comp.fab.primary.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness", "md.comp.fab.primary.focus.state-layer.color": "onPrimaryContainer", "md.comp.fab.primary.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.fab.primary.hover.container.elevation": "md.sys.elevation.level4", "md.comp.fab.primary.hover.icon.color": "onPrimaryContainer", "md.comp.fab.primary.hover.state-layer.color": "onPrimaryContainer", "md.comp.fab.primary.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity", "md.comp.fab.primary.icon.color": "onPrimaryContainer", "md.comp.fab.primary.icon.size": 24.0, "md.comp.fab.primary.lowered.container.elevation": "md.sys.elevation.level1", "md.comp.fab.primary.lowered.focus.container.elevation": "md.sys.elevation.level1", "md.comp.fab.primary.lowered.hover.container.elevation": "md.sys.elevation.level2", "md.comp.fab.primary.lowered.pressed.container.elevation": "md.sys.elevation.level1", "md.comp.fab.primary.pressed.container.elevation": "md.sys.elevation.level3", "md.comp.fab.primary.pressed.icon.color": "onPrimaryContainer", "md.comp.fab.primary.pressed.state-layer.color": "onPrimaryContainer", "md.comp.fab.primary.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity" }
flutter/dev/tools/gen_defaults/data/fab_primary.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/fab_primary.json", "repo_id": "flutter", "token_count": 754 }
611
{ "version": "v0_206", "md.comp.linear-progress-indicator.active-indicator.color": "primary", "md.comp.linear-progress-indicator.active-indicator.height": 4.0, "md.comp.linear-progress-indicator.active-indicator.shape": "md.sys.shape.corner.none", "md.comp.linear-progress-indicator.four-color.active-indicator.four.color": "tertiaryContainer", "md.comp.linear-progress-indicator.four-color.active-indicator.one.color": "primary", "md.comp.linear-progress-indicator.four-color.active-indicator.three.color": "tertiary", "md.comp.linear-progress-indicator.four-color.active-indicator.two.color": "primaryContainer", "md.comp.linear-progress-indicator.track.color": "surfaceContainerHighest", "md.comp.linear-progress-indicator.track.height": 4.0, "md.comp.linear-progress-indicator.track.shape": "md.sys.shape.corner.none" }
flutter/dev/tools/gen_defaults/data/progress_indicator_linear.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/progress_indicator_linear.json", "repo_id": "flutter", "token_count": 299 }
612
{ "version": "v0_206", "md.comp.top-app-bar.medium.container.color": "surface", "md.comp.top-app-bar.medium.container.elevation": "md.sys.elevation.level0", "md.comp.top-app-bar.medium.container.height": 112.0, "md.comp.top-app-bar.medium.container.shape": "md.sys.shape.corner.none", "md.comp.top-app-bar.medium.headline.color": "onSurface", "md.comp.top-app-bar.medium.headline.text-style": "headlineSmall", "md.comp.top-app-bar.medium.leading-icon.color": "onSurface", "md.comp.top-app-bar.medium.leading-icon.size": 24.0, "md.comp.top-app-bar.medium.trailing-icon.color": "onSurfaceVariant", "md.comp.top-app-bar.medium.trailing-icon.size": 24.0 }
flutter/dev/tools/gen_defaults/data/top_app_bar_medium.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/top_app_bar_medium.json", "repo_id": "flutter", "token_count": 281 }
613
// Copyright 2014 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 'template.dart'; class DialogTemplate extends TokenTemplate { const DialogTemplate(super.blockName, super.fileName, super.tokens, { super.colorSchemePrefix = '_colors.', super.textThemePrefix = '_textTheme.' }); @override String generate() => ''' class _${blockName}DefaultsM3 extends DialogTheme { _${blockName}DefaultsM3(this.context) : super( alignment: Alignment.center, elevation: ${elevation("md.comp.dialog.container")}, shape: ${shape("md.comp.dialog.container")}, ); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; late final TextTheme _textTheme = Theme.of(context).textTheme; @override Color? get iconColor => _colors.secondary; @override Color? get backgroundColor => ${componentColor("md.comp.dialog.container")}; @override Color? get shadowColor => ${colorOrTransparent("md.comp.dialog.container.shadow-color")}; @override Color? get surfaceTintColor => ${colorOrTransparent("md.comp.dialog.container.surface-tint-layer.color")}; @override TextStyle? get titleTextStyle => ${textStyle("md.comp.dialog.headline")}; @override TextStyle? get contentTextStyle => ${textStyle("md.comp.dialog.supporting-text")}; @override EdgeInsetsGeometry? get actionsPadding => const EdgeInsets.only(left: 24.0, right: 24.0, bottom: 24.0); } '''; } class DialogFullscreenTemplate extends TokenTemplate { const DialogFullscreenTemplate(super.blockName, super.fileName, super.tokens); @override String generate() => ''' class _${blockName}DefaultsM3 extends DialogTheme { const _${blockName}DefaultsM3(this.context); final BuildContext context; @override Color? get backgroundColor => ${componentColor("md.comp.full-screen-dialog.container")}; } '''; }
flutter/dev/tools/gen_defaults/lib/dialog_template.dart/0
{ "file_path": "flutter/dev/tools/gen_defaults/lib/dialog_template.dart", "repo_id": "flutter", "token_count": 649 }
614
// Copyright 2014 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 'template.dart'; class ProgressIndicatorTemplate extends TokenTemplate { const ProgressIndicatorTemplate(super.blockName, super.fileName, super.tokens, { super.colorSchemePrefix = '_colors.', }); @override String generate() => ''' class _Circular${blockName}DefaultsM3 extends ProgressIndicatorThemeData { _Circular${blockName}DefaultsM3(this.context); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; @override Color get color => ${componentColor('md.comp.circular-progress-indicator.active-indicator')}; } class _Linear${blockName}DefaultsM3 extends ProgressIndicatorThemeData { _Linear${blockName}DefaultsM3(this.context); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; @override Color get color => ${componentColor('md.comp.linear-progress-indicator.active-indicator')}; @override Color get linearTrackColor => ${componentColor('md.comp.linear-progress-indicator.track')}; @override double get linearMinHeight => ${getToken('md.comp.linear-progress-indicator.track.height')}; } '''; }
flutter/dev/tools/gen_defaults/lib/progress_indicator_template.dart/0
{ "file_path": "flutter/dev/tools/gen_defaults/lib/progress_indicator_template.dart", "repo_id": "flutter", "token_count": 391 }
615
Versions used, v1.0.0, v2.0.0 bar, foo
flutter/dev/tools/gen_defaults/test.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/test.json", "repo_id": "flutter", "token_count": 22 }
616
{ "Numpad0": "NumpadInsert", "Numpad1": "NumpadEnd", "Numpad2": "NumpadDown", "Numpad3": "NumpadPageDown", "Numpad4": "NumpadLeft", "Numpad6": "NumpadRight", "Numpad7": "NumpadHome", "Numpad8": "NumpadUp", "Numpad9": "NumpadPageUp", "NumpadPeriod": "NumpadDelete" }
flutter/dev/tools/gen_keycodes/data/gtk_numpad_shift.json/0
{ "file_path": "flutter/dev/tools/gen_keycodes/data/gtk_numpad_shift.json", "repo_id": "flutter", "token_count": 147 }
617
// Copyright 2013 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. // DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT // This file is generated by dev/tools/gen_keycodes/bin/gen_keycodes.dart and // should not be edited directly. // // Edit the template dev/tools/gen_keycodes/data/web_key_map_dart.tmpl instead. // See dev/tools/gen_keycodes/README.md for more information. /// Maps Web KeyboardEvent keys to the matching LogicalKeyboardKey id. const Map<String, int> kWebToLogicalKey = <String, int>{ @@@WEB_LOGICAL_KEY_CODE_MAP@@@ }; /// Maps Web KeyboardEvent codes to the matching PhysicalKeyboardKey USB HID code. const Map<String, int> kWebToPhysicalKey = <String, int>{ @@@WEB_PHYSICAL_KEY_CODE_MAP@@@ }; /// Maps Web KeyboardEvent keys to Flutter logical IDs that depend on locations. /// /// `KeyboardEvent.location` is defined as: /// /// * 0: Standard /// * 1: Left /// * 2: Right /// * 3: Numpad const Map<String, List<int?>> kWebLogicalLocationMap = <String, List<int?>>{ @@@WEB_LOGICAL_LOCATION_MAP@@@ };
flutter/dev/tools/gen_keycodes/data/web_key_map_dart.tmpl/0
{ "file_path": "flutter/dev/tools/gen_keycodes/data/web_key_map_dart.tmpl", "repo_id": "flutter", "token_count": 367 }
618
// Copyright 2014 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:path/path.dart' as path; import 'base_code_gen.dart'; import 'logical_key_data.dart'; import 'physical_key_data.dart'; import 'utils.dart'; String _toUpperCamel(String lowerCamel) { return lowerCamel.substring(0, 1).toUpperCase() + lowerCamel.substring(1); } /// Generates the common/testing/key_codes.h based on the information in the key /// data structure given to it. class KeyCodesCcGenerator extends BaseCodeGenerator { KeyCodesCcGenerator(super.keyData, super.logicalData); /// Gets the generated definitions of PhysicalKeyboardKeys. String get _physicalDefinitions { final OutputLines<int> lines = OutputLines<int>('Physical Key list'); for (final PhysicalKeyEntry entry in keyData.entries) { lines.add(entry.usbHidCode, ''' constexpr uint64_t kPhysical${_toUpperCamel(entry.constantName)} = ${toHex(entry.usbHidCode)};'''); } return lines.sortedJoin().trimRight(); } /// Gets the generated definitions of PhysicalKeyboardKeys. String get _logicalDefinitions { final OutputLines<int> lines = OutputLines<int>('Logical Key list', behavior: DeduplicateBehavior.kSkip); for (final LogicalKeyEntry entry in logicalData.entries) { lines.add(entry.value, ''' constexpr uint64_t kLogical${_toUpperCamel(entry.constantName)} = ${toHex(entry.value, digits: 11)};'''); } return lines.sortedJoin().trimRight(); } @override String get templatePath => path.join(dataRoot, 'key_codes_h.tmpl'); @override Map<String, String> mappings() { return <String, String>{ 'LOGICAL_KEY_DEFINITIONS': _logicalDefinitions, 'PHYSICAL_KEY_DEFINITIONS': _physicalDefinitions, }; } }
flutter/dev/tools/gen_keycodes/lib/testing_key_codes_cc_gen.dart/0
{ "file_path": "flutter/dev/tools/gen_keycodes/lib/testing_key_codes_cc_gen.dart", "repo_id": "flutter", "token_count": 635 }
619
// Copyright 2014 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'; import 'dart:io'; import 'package:args/args.dart' as argslib; import 'package:meta/meta.dart'; import 'language_subtag_registry.dart'; typedef HeaderGenerator = String Function(String regenerateInstructions); typedef ConstructorGenerator = String Function(LocaleInfo locale); int sortFilesByPath (FileSystemEntity a, FileSystemEntity b) { return a.path.compareTo(b.path); } /// Simple data class to hold parsed locale. Does not promise validity of any data. @immutable class LocaleInfo implements Comparable<LocaleInfo> { const LocaleInfo({ required this.languageCode, this.scriptCode, this.countryCode, required this.length, required this.originalString, }); /// Simple parser. Expects the locale string to be in the form of 'language_script_COUNTRY' /// where the language is 2 characters, script is 4 characters with the first uppercase, /// and country is 2-3 characters and all uppercase. /// /// 'language_COUNTRY' or 'language_script' are also valid. Missing fields will be null. /// /// When `deriveScriptCode` is true, if [scriptCode] was unspecified, it will /// be derived from the [languageCode] and [countryCode] if possible. factory LocaleInfo.fromString(String locale, { bool deriveScriptCode = false }) { final List<String> codes = locale.split('_'); // [language, script, country] assert(codes.isNotEmpty && codes.length < 4); final String languageCode = codes[0]; String? scriptCode; String? countryCode; int length = codes.length; String originalString = locale; if (codes.length == 2) { scriptCode = codes[1].length >= 4 ? codes[1] : null; countryCode = codes[1].length < 4 ? codes[1] : null; } else if (codes.length == 3) { scriptCode = codes[1].length > codes[2].length ? codes[1] : codes[2]; countryCode = codes[1].length < codes[2].length ? codes[1] : codes[2]; } assert(codes[0].isNotEmpty); assert(countryCode == null || countryCode.isNotEmpty); assert(scriptCode == null || scriptCode.isNotEmpty); /// Adds scriptCodes to locales where we are able to assume it to provide /// finer granularity when resolving locales. /// /// The basis of the assumptions here are based off of known usage of scripts /// across various countries. For example, we know Taiwan uses traditional (Hant) /// script, so it is safe to apply (Hant) to Taiwanese languages. if (deriveScriptCode && scriptCode == null) { switch (languageCode) { case 'zh': { if (countryCode == null) { scriptCode = 'Hans'; } switch (countryCode) { case 'CN': case 'SG': scriptCode = 'Hans'; case 'TW': case 'HK': case 'MO': scriptCode = 'Hant'; } break; } case 'sr': { if (countryCode == null) { scriptCode = 'Cyrl'; } break; } } // Increment length if we were able to assume a scriptCode. if (scriptCode != null) { length += 1; } // Update the base string to reflect assumed scriptCodes. originalString = languageCode; if (scriptCode != null) { originalString += '_$scriptCode'; } if (countryCode != null) { originalString += '_$countryCode'; } } return LocaleInfo( languageCode: languageCode, scriptCode: scriptCode, countryCode: countryCode, length: length, originalString: originalString, ); } final String languageCode; final String? scriptCode; final String? countryCode; final int length; // The number of fields. Ranges from 1-3. final String originalString; // Original un-parsed locale string. String camelCase() { return originalString .split('_') .map<String>((String part) => part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase()) .join(); } @override bool operator ==(Object other) { return other is LocaleInfo && other.originalString == originalString; } @override int get hashCode => originalString.hashCode; @override String toString() { return originalString; } @override int compareTo(LocaleInfo other) { return originalString.compareTo(other.originalString); } } /// Parse the data for a locale from a file, and store it in the [attributes] /// and [resources] keys. void loadMatchingArbsIntoBundleMaps({ required Directory directory, required RegExp filenamePattern, required Map<LocaleInfo, Map<String, String>> localeToResources, required Map<LocaleInfo, Map<String, dynamic>> localeToResourceAttributes, }) { /// Set that holds the locales that were assumed from the existing locales. /// /// For example, when the data lacks data for zh_Hant, we will use the data of /// the first Hant Chinese locale as a default by repeating the data. If an /// explicit match is later found, we can reference this set to see if we should /// overwrite the existing assumed data. final Set<LocaleInfo> assumedLocales = <LocaleInfo>{}; for (final FileSystemEntity entity in directory.listSync().toList()..sort(sortFilesByPath)) { final String entityPath = entity.path; if (FileSystemEntity.isFileSync(entityPath) && filenamePattern.hasMatch(entityPath)) { final String localeString = filenamePattern.firstMatch(entityPath)![1]!; final File arbFile = File(entityPath); // Helper method to fill the maps with the correct data from file. void populateResources(LocaleInfo locale, File file) { final Map<String, String> resources = localeToResources[locale]!; final Map<String, dynamic> attributes = localeToResourceAttributes[locale]!; final Map<String, dynamic> bundle = json.decode(file.readAsStringSync()) as Map<String, dynamic>; for (final String key in bundle.keys) { // The ARB file resource "attributes" for foo are called @foo. if (key.startsWith('@')) { attributes[key.substring(1)] = bundle[key]; } else { resources[key] = bundle[key] as String; } } } // Only pre-assume scriptCode if there is a country or script code to assume off of. // When we assume scriptCode based on languageCode-only, we want this initial pass // to use the un-assumed version as a base class. LocaleInfo locale = LocaleInfo.fromString(localeString, deriveScriptCode: localeString.split('_').length > 1); // Allow overwrite if the existing data is assumed. if (assumedLocales.contains(locale)) { localeToResources[locale] = <String, String>{}; localeToResourceAttributes[locale] = <String, dynamic>{}; assumedLocales.remove(locale); } else { localeToResources[locale] ??= <String, String>{}; localeToResourceAttributes[locale] ??= <String, dynamic>{}; } populateResources(locale, arbFile); // Add an assumed locale to default to when there is no info on scriptOnly locales. locale = LocaleInfo.fromString(localeString, deriveScriptCode: true); if (locale.scriptCode != null) { final LocaleInfo scriptLocale = LocaleInfo.fromString('${locale.languageCode}_${locale.scriptCode}'); if (!localeToResources.containsKey(scriptLocale)) { assumedLocales.add(scriptLocale); localeToResources[scriptLocale] ??= <String, String>{}; localeToResourceAttributes[scriptLocale] ??= <String, dynamic>{}; populateResources(scriptLocale, arbFile); } } } } } void exitWithError(String errorMessage) { stderr.writeln('fatal: $errorMessage'); exit(1); } void checkCwdIsRepoRoot(String commandName) { final bool isRepoRoot = Directory('.git').existsSync(); if (!isRepoRoot) { exitWithError( '$commandName must be run from the root of the Flutter repository. The ' 'current working directory is: ${Directory.current.path}' ); } } GeneratorOptions parseArgs(List<String> rawArgs) { final argslib.ArgParser argParser = argslib.ArgParser() ..addFlag( 'help', abbr: 'h', help: 'Print the usage message for this command', ) ..addFlag( 'overwrite', abbr: 'w', help: 'Overwrite existing localizations', ) ..addFlag( 'remove-undefined', help: 'Remove any localizations that are not defined in the canonical locale.', ) ..addFlag( 'widgets', help: 'Whether to print the generated classes for the Widgets package only. Ignored when --overwrite is passed.', ) ..addFlag( 'material', help: 'Whether to print the generated classes for the Material package only. Ignored when --overwrite is passed.', ) ..addFlag( 'cupertino', help: 'Whether to print the generated classes for the Cupertino package only. Ignored when --overwrite is passed.', ); final argslib.ArgResults args = argParser.parse(rawArgs); if (args.wasParsed('help') && args['help'] == true) { stderr.writeln(argParser.usage); exit(0); } final bool writeToFile = args['overwrite'] as bool; final bool removeUndefined = args['remove-undefined'] as bool; final bool widgetsOnly = args['widgets'] as bool; final bool materialOnly = args['material'] as bool; final bool cupertinoOnly = args['cupertino'] as bool; return GeneratorOptions( writeToFile: writeToFile, materialOnly: materialOnly, cupertinoOnly: cupertinoOnly, widgetsOnly: widgetsOnly, removeUndefined: removeUndefined, ); } class GeneratorOptions { GeneratorOptions({ required this.writeToFile, required this.removeUndefined, required this.materialOnly, required this.cupertinoOnly, required this.widgetsOnly, }); final bool writeToFile; final bool removeUndefined; final bool materialOnly; final bool cupertinoOnly; final bool widgetsOnly; } // See also //master/tools/gen_locale.dart in the engine repo. Map<String, List<String>> _parseSection(String section) { final Map<String, List<String>> result = <String, List<String>>{}; late List<String> lastHeading; for (final String line in section.split('\n')) { if (line == '') { continue; } if (line.startsWith(' ')) { lastHeading[lastHeading.length - 1] = '${lastHeading.last}${line.substring(1)}'; continue; } final int colon = line.indexOf(':'); if (colon <= 0) { throw 'not sure how to deal with "$line"'; } final String name = line.substring(0, colon); final String value = line.substring(colon + 2); lastHeading = result.putIfAbsent(name, () => <String>[]); result[name]!.add(value); } return result; } final Map<String, String> _languages = <String, String>{}; final Map<String, String> _regions = <String, String>{}; final Map<String, String> _scripts = <String, String>{}; const String kProvincePrefix = ', Province of '; const String kParentheticalPrefix = ' ('; /// Prepares the data for the [describeLocale] method below. /// /// The data is obtained from the official IANA registry. void precacheLanguageAndRegionTags() { final List<Map<String, List<String>>> sections = languageSubtagRegistry.split('%%').skip(1).map<Map<String, List<String>>>(_parseSection).toList(); for (final Map<String, List<String>> section in sections) { assert(section.containsKey('Type'), section.toString()); final String type = section['Type']!.single; if (type == 'language' || type == 'region' || type == 'script') { assert(section.containsKey('Subtag') && section.containsKey('Description'), section.toString()); final String subtag = section['Subtag']!.single; String description = section['Description']!.join(' '); if (description.startsWith('United ')) { description = 'the $description'; } if (description.contains(kParentheticalPrefix)) { description = description.substring(0, description.indexOf(kParentheticalPrefix)); } if (description.contains(kProvincePrefix)) { description = description.substring(0, description.indexOf(kProvincePrefix)); } if (description.endsWith(' Republic')) { description = 'the $description'; } switch (type) { case 'language': _languages[subtag] = description; case 'region': _regions[subtag] = description; case 'script': _scripts[subtag] = description; } } } } String describeLocale(String tag) { final List<String> subtags = tag.split('_'); assert(subtags.isNotEmpty); assert(_languages.containsKey(subtags[0])); final String language = _languages[subtags[0]]!; String output = language; String? region; String? script; if (subtags.length == 2) { region = _regions[subtags[1]]; script = _scripts[subtags[1]]; assert(region != null || script != null); } else if (subtags.length >= 3) { region = _regions[subtags[2]]; script = _scripts[subtags[1]]; assert(region != null && script != null); } if (region != null) { output += ', as used in $region'; } if (script != null) { output += ', using the $script script'; } return output; } /// Writes the header of each class which corresponds to a locale. String generateClassDeclaration( LocaleInfo locale, String classNamePrefix, String superClass, ) { final String camelCaseName = locale.camelCase(); return ''' /// The translations for ${describeLocale(locale.originalString)} (`${locale.originalString}`). class $classNamePrefix$camelCaseName extends $superClass {'''; } /// Return the input string as a Dart-parseable string. /// /// ``` /// foo => 'foo' /// foo "bar" => 'foo "bar"' /// foo 'bar' => "foo 'bar'" /// foo 'bar' "baz" => '''foo 'bar' "baz"''' /// ``` /// /// This function is used by tools that take in a JSON-formatted file to /// generate Dart code. For this reason, characters with special meaning /// in JSON files are escaped. For example, the backspace character (\b) /// has to be properly escaped by this function so that the generated /// Dart code correctly represents this character: /// ``` /// foo\bar => 'foo\\bar' /// foo\nbar => 'foo\\nbar' /// foo\\nbar => 'foo\\\\nbar' /// foo\\bar => 'foo\\\\bar' /// foo\ bar => 'foo\\ bar' /// foo$bar = 'foo\$bar' /// ``` String generateString(String value) { if (<String>['\n', '\f', '\t', '\r', '\b'].every((String pattern) => !value.contains(pattern))) { final bool hasDollar = value.contains(r'$'); final bool hasBackslash = value.contains(r'\'); final bool hasQuote = value.contains("'"); final bool hasDoubleQuote = value.contains('"'); if (!hasQuote) { return hasBackslash || hasDollar ? "r'$value'" : "'$value'"; } if (!hasDoubleQuote) { return hasBackslash || hasDollar ? 'r"$value"' : '"$value"'; } } const String backslash = '__BACKSLASH__'; assert( !value.contains(backslash), 'Input string cannot contain the sequence: ' '"__BACKSLASH__", as it is used as part of ' 'backslash character processing.' ); value = value // Replace backslashes with a placeholder for now to properly parse // other special characters. .replaceAll(r'\', backslash) .replaceAll(r'$', r'\$') .replaceAll("'", r"\'") .replaceAll('"', r'\"') .replaceAll('\n', r'\n') .replaceAll('\f', r'\f') .replaceAll('\t', r'\t') .replaceAll('\r', r'\r') .replaceAll('\b', r'\b') // Reintroduce escaped backslashes into generated Dart string. .replaceAll(backslash, r'\\'); return "'$value'"; } /// Only used to generate localization strings for the Kannada locale ('kn') because /// some of the localized strings contain characters that can crash Emacs on Linux. /// See packages/flutter_localizations/lib/src/l10n/README for more information. String generateEncodedString(String? locale, String value) { if (locale != 'kn' || value.runes.every((int code) => code <= 0xFF)) { return generateString(value); } final String unicodeEscapes = value.runes.map((int code) => '\\u{${code.toRadixString(16)}}').join(); return "'$unicodeEscapes'"; }
flutter/dev/tools/localization/localizations_utils.dart/0
{ "file_path": "flutter/dev/tools/localization/localizations_utils.dart", "repo_id": "flutter", "token_count": 5886 }
620
<svg id="svg_build_00" xmlns="http://www.w3.org/2000/svg" width="48px" height="48px" > <g if="group_2" transform="scale(0.5,0.5)"> <path id="path_1" d="M 0,19.0 L 48.0, 19.0 L 48.0, 29.0 L 0, 29.0 Z " fill="#000000" /> </g> </svg>
flutter/dev/tools/vitool/test_assets/bar_group_scale.svg/0
{ "file_path": "flutter/dev/tools/vitool/test_assets/bar_group_scale.svg", "repo_id": "flutter", "token_count": 123 }
621