text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
/* * 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. /** * Adding new values to {@link InstanceKind} is considered a backwards compatible change. Clients * should treat unrecognized instance kinds as {@link PlainInstance}. */ @SuppressWarnings({"WeakerAccess", "unused"}) public enum InstanceKind { /** * true or false. */ Bool, /** * An instance of the Dart class BoundedType. */ BoundedType, /** * An instance of the built-in VM Closure implementation. User-defined Closures will be * PlainInstance. */ Closure, /** * An instance of the Dart class double. */ Double, Float32List, /** * Vector instance kinds. */ Float32x4, Float32x4List, Float64List, Float64x2, Float64x2List, /** * An instance of the Dart class FunctionType. */ FunctionType, /** * An instance of the Dart class int. */ Int, Int16List, Int32List, Int32x4, Int32x4List, Int64List, Int8List, /** * An instance of the built-in VM List implementation. User-defined Lists will be PlainInstance. */ List, /** * An instance of the built-in VM Map implementation. User-defined Maps will be PlainInstance. */ Map, /** * An instance of the Dart class MirrorReference. */ MirrorReference, /** * null instance. */ Null, /** * A general instance of the Dart class Object. */ PlainInstance, /** * An instance of the Dart class ReceivePort. */ ReceivePort, /** * An instance of the Dart class Record. */ Record, /** * An instance of the Dart class RecordType. */ RecordType, /** * An instance of the Dart class RegExp. */ RegExp, /** * An instance of the built-in VM Set implementation. User-defined Sets will be PlainInstance. */ Set, /** * An instance of the Dart class StackTrace. */ StackTrace, /** * An instance of the Dart class String. */ String, /** * An instance of the Dart class Type. */ Type, /** * An instance of the Dart class TypeParameter. */ TypeParameter, /** * An instance of the Dart class TypeRef. */ TypeRef, Uint16List, Uint32List, Uint64List, /** * An instance of the built-in VM TypedData implementations. User-defined TypedDatas will be * PlainInstance. */ Uint8ClampedList, Uint8List, /** * An instance of the Dart class WeakProperty. */ WeakProperty, /** * An instance of the Dart class WeakReference. */ WeakReference, /** * Represents a value returned by the VM but unknown to this client. */ Unknown }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/InstanceKind.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/InstanceKind.java", "repo_id": "flutter-intellij", "token_count": 1074 }
479
/* * 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; /** * See getRetainingPath. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class RetainingPath extends Response { public RetainingPath(JsonObject json) { super(json); } /** * The chain of objects which make up the retaining path. */ public ElementList<RetainingObject> getElements() { return new ElementList<RetainingObject>(json.get("elements").getAsJsonArray()) { @Override protected RetainingObject basicGet(JsonArray array, int index) { return new RetainingObject(array.get(index).getAsJsonObject()); } }; } /** * The type of GC root which is holding a reference to the specified object. Possible values * include: * class table * local handle * persistent handle * stack * user global * weak * persistent handle * unknown */ public String getGcRootType() { return getAsString("gcRootType"); } /** * The length of the retaining path. */ public int getLength() { return getAsInt("length"); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/RetainingPath.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/RetainingPath.java", "repo_id": "flutter-intellij", "token_count": 558 }
480
/* * 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; import java.util.List; @SuppressWarnings({"WeakerAccess", "unused"}) public class TimelineFlags extends Response { public TimelineFlags(JsonObject json) { super(json); } /** * The list of all available timeline streams. */ public List<String> getAvailableStreams() { return getListString("availableStreams"); } /** * The list of timeline streams that are currently enabled. */ public List<String> getRecordedStreams() { return getListString("recordedStreams"); } /** * The name of the recorder currently in use. Recorder types include, but are not limited to: * Callback, Endless, Fuchsia, Macos, Ring, Startup, and Systrace. Set to "null" if no recorder * is currently set. */ public String getRecorderName() { return getAsString("recorderName"); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/TimelineFlags.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/TimelineFlags.java", "repo_id": "flutter-intellij", "token_count": 469 }
481
/* * 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.internal; import com.google.gson.JsonObject; import de.roderick.weberknecht.WebSocket; import de.roderick.weberknecht.WebSocketException; import org.dartlang.vm.service.logging.Logging; /** * An {@link WebSocket} based implementation of {@link RequestSink}. */ public class WebSocketRequestSink implements RequestSink { private WebSocket webSocket; public WebSocketRequestSink(WebSocket webSocket) { this.webSocket = webSocket; } @Override public void add(JsonObject json) { String request = json.toString(); if (webSocket == null) { Logging.getLogger().logInformation("Dropped: " + request); return; } Logging.getLogger().logInformation("Sent: " + request); try { webSocket.send(request); } catch (WebSocketException e) { Logging.getLogger().logError("Failed to send request: " + request, e); } } @Override public void close() { if (webSocket != null) { try { webSocket.close(); } catch (WebSocketException e) { Logging.getLogger().logError("Failed to close websocket", e); } webSocket = null; } } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/internal/WebSocketRequestSink.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/internal/WebSocketRequestSink.java", "repo_id": "flutter-intellij", "token_count": 585 }
482
/* * 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.android; import static com.android.tools.idea.gradle.util.GradleProjectSystemUtil.GRADLE_SYSTEM_ID; import static com.google.wireless.android.sdk.stats.GradleSyncStats.Trigger.TRIGGER_PROJECT_MODIFIED; import static io.flutter.android.AndroidModuleLibraryType.LIBRARY_KIND; import static io.flutter.android.AndroidModuleLibraryType.LIBRARY_NAME; import com.android.tools.idea.gradle.project.sync.GradleSyncInvoker; import com.android.tools.idea.gradle.project.sync.GradleSyncListener; import com.intellij.ProjectTopics; import com.intellij.facet.FacetManager; import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.TransactionGuard; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.impl.stores.IProjectStore; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; //import com.intellij.openapi.project.impl.ProjectExImpl; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.project.impl.ProjectManagerImpl; import com.intellij.openapi.project.impl.ProjectStoreFactory; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.DependencyScope; import com.intellij.openapi.roots.JavaProjectModelModifier; import com.intellij.openapi.roots.ModuleRootEvent; import com.intellij.openapi.roots.ModuleRootListener; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.impl.IdeaProjectModelModifier; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; import com.intellij.openapi.roots.libraries.PersistentLibraryKind; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileContentsChangedAdapter; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.serviceContainer.ComponentManagerImpl; import com.intellij.util.ReflectionUtil; import com.intellij.util.modules.CircularModuleDependenciesDetector; import io.flutter.sdk.AbstractLibraryManager; import io.flutter.sdk.FlutterSdkUtil; import io.flutter.settings.FlutterSettings; import io.flutter.utils.FlutterModuleUtils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.stream.Collectors; import org.jetbrains.android.facet.AndroidFacet; import org.jetbrains.android.sdk.AndroidSdkUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Manages the Android libraries. Add the libraries used by Android modules referenced in a project * into the Flutter project, so full editing support is available. Add dependencies to each library * to the Android modules. Add a dependency from the Android module to the Flutter module so the * libraries can be resolved. Do not add a dependency from the Flutter module to the libraries since * Java and Kotlin code are only found in the Android modules. Also set the project SDK to that used * by Android. * <p> * TODO(messick) Test with plugins and modules * These are not looking so good. Source files are not marked correctly. Re-check make-host-app-editable. * * @see AndroidModuleLibraryType * @see AndroidModuleLibraryProperties */ public class AndroidModuleLibraryManager extends AbstractLibraryManager<AndroidModuleLibraryProperties> { private static final Logger LOG = Logger.getInstance(AndroidModuleLibraryManager.class); private static final String BUILD_FILE_NAME = "build.gradle"; private final AtomicBoolean isUpdating = new AtomicBoolean(false); private final AtomicBoolean isDisabled = new AtomicBoolean(false); public AndroidModuleLibraryManager(@NotNull Project project) { super(project); } public void update() { doGradleSync(getProject(), this::scheduleAddAndroidLibraryDeps); } private Void scheduleAddAndroidLibraryDeps(@NotNull Project androidProject) { ApplicationManager.getApplication().invokeLater( () -> addAndroidLibraryDependencies(androidProject), ModalityState.NON_MODAL); return null; } private void addAndroidLibraryDependencies(@NotNull Project androidProject) { for (Module flutterModule : FlutterModuleUtils.getModules(getProject())) { if (FlutterModuleUtils.isFlutterModule(flutterModule)) { for (Module module : ModuleManager.getInstance(androidProject).getModules()) { addAndroidLibraryDependencies(androidProject, module, flutterModule); } } } isUpdating.set(false); } private void addAndroidLibraryDependencies(@NotNull Project androidProject, @NotNull Module androidModule, @NotNull Module flutterModule) { //AndroidSdkUtils.setupAndroidPlatformIfNecessary(androidModule, true); Sdk currentSdk = ModuleRootManager.getInstance(androidModule).getSdk(); if (currentSdk != null) { // TODO(messick) Add sdk dependency on currentSdk if not already set } LibraryTable androidProjectLibraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(androidProject); Library[] androidProjectLibraries = androidProjectLibraryTable.getLibraries(); LibraryTable flutterProjectLibraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(getProject()); Library[] flutterProjectLibraries = flutterProjectLibraryTable.getLibraries(); Set<String> knownLibraryNames = new HashSet<>(flutterProjectLibraries.length); for (Library lib : flutterProjectLibraries) { if (lib.getName() != null) { knownLibraryNames.add(lib.getName()); } } for (Library library : androidProjectLibraries) { if (library.getName() != null && !knownLibraryNames.contains(library.getName())) { List<String> roots = Arrays.asList(library.getRootProvider().getUrls(OrderRootType.CLASSES)); Set<String> filteredRoots = roots.stream().filter(s -> shouldIncludeRoot(s)).collect(Collectors.toSet()); if (filteredRoots.isEmpty()) continue; HashSet<String> sources = new HashSet<>(Arrays.asList(library.getRootProvider().getUrls(OrderRootType.SOURCES))); updateLibraryContent(library.getName(), filteredRoots, sources); updateAndroidModuleLibraryDependencies(flutterModule); } } } @Override protected void updateModuleLibraryDependencies(@NotNull Library library) { for (final Module module : ModuleManager.getInstance(getProject()).getModules()) { // The logic is inverted wrt superclass. if (!FlutterModuleUtils.declaresFlutter(module)) { addFlutterLibraryDependency(module, library); } else { removeFlutterLibraryDependency(module, library); } } } private void updateAndroidModuleLibraryDependencies(Module flutterModule) { for (final Module module : ModuleManager.getInstance(getProject()).getModules()) { if (module != flutterModule) { if (null != FacetManager.getInstance(module).findFacet(AndroidFacet.ID, "Android")) { Object circularModules = CircularModuleDependenciesDetector.addingDependencyFormsCircularity(module, flutterModule); if (circularModules == null) { ModuleRootManager rootManager = ModuleRootManager.getInstance(module); if (!rootManager.isDependsOn(flutterModule)) { JavaProjectModelModifier[] modifiers = JavaProjectModelModifier.EP_NAME.getExtensions(getProject()); for (JavaProjectModelModifier modifier : modifiers) { if (modifier instanceof IdeaProjectModelModifier) { modifier.addModuleDependency(module, flutterModule, DependencyScope.COMPILE, false); } } } } } } } } @NotNull @Override protected String getLibraryName() { // This is not used since we create many libraries, not one. return LIBRARY_NAME; } @NotNull @Override protected PersistentLibraryKind<AndroidModuleLibraryProperties> getLibraryKind() { return LIBRARY_KIND; } private void scheduleUpdate() { if (isUpdating.get() || isDisabled.get()) { return; } final Runnable runnable = this::updateAndroidLibraries; DumbService.getInstance(getProject()).smartInvokeLater(runnable, ModalityState.NON_MODAL); } private void updateAndroidLibraries() { if (!isUpdating.compareAndSet(false, true)) { return; } update(); } private void doGradleSync(Project flutterProject, Function<Project, Void> callback) { // TODO(messick): Collect URLs for all Android modules, including those within plugins. VirtualFile dir = flutterProject.getBaseDir().findChild("android"); if (dir == null) dir = flutterProject.getBaseDir().findChild(".android"); // For modules. if (dir == null) return; EmbeddedAndroidProject androidProject = new EmbeddedAndroidProject(Paths.get(FileUtilRt.toSystemIndependentName(dir.getPath()))); androidProject.init42(null); Disposer.register(flutterProject, androidProject); GradleSyncListener listener = new GradleSyncListener() { @SuppressWarnings("override") public void syncTaskCreated(@NotNull Project project, @NotNull GradleSyncInvoker.Request request) {} // TODO(messick) Remove when 3.6 is stable. public void syncStarted(@NotNull Project project, boolean skipped, boolean sourceGenerationRequested) {} @SuppressWarnings("override") public void setupStarted(@NotNull Project project) {} @Override public void syncSucceeded(@NotNull Project project) { if (isUpdating.get()) { callback.apply(androidProject); } } @Override public void syncFailed(@NotNull Project project, @NotNull String errorMessage) { isUpdating.set(false); } @Override public void syncSkipped(@NotNull Project project) { isUpdating.set(false); } }; GradleSyncInvoker.Request request = new GradleSyncInvoker.Request(TRIGGER_PROJECT_MODIFIED); //request.runInBackground = true; GradleSyncInvoker gradleSyncInvoker = ApplicationManager.getApplication().getService(GradleSyncInvoker.class); gradleSyncInvoker.requestProjectSync(androidProject, request, listener); } private static boolean shouldIncludeRoot(String path) { return !path.endsWith("res") && !path.contains("flutter.jar") && !path.contains("flutter-x86.jar"); } @NotNull public static AndroidModuleLibraryManager getInstance(@NotNull final Project project) { return ServiceManager.getService(project, AndroidModuleLibraryManager.class); } public static void startWatching(@NotNull Project project) { // Start a process to monitor changes to Android dependencies and update the library content. if (project.isDefault()) { return; } if (hasAndroidDir(project)) { AndroidModuleLibraryManager manager = getInstance(project); VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileContentsChangedAdapter() { @Override protected void onFileChange(@NotNull VirtualFile file) { fileChanged(project, file); } @Override protected void onBeforeFileChange(@NotNull VirtualFile file) { } }, project); project.getMessageBus().connect().subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootListener() { @Override public void rootsChanged(@NotNull ModuleRootEvent event) { manager.scheduleUpdate(); } }); manager.scheduleUpdate(); } } private static boolean hasAndroidDir(Project project) { if (FlutterSdkUtil.hasFlutterModules(project)) { VirtualFile base = project.getBaseDir(); VirtualFile dir = base.findChild("android"); if (dir == null) dir = base.findChild(".android"); return dir != null; } else { return false; } } private static void fileChanged(@NotNull final Project project, @NotNull final VirtualFile file) { if (!BUILD_FILE_NAME.equals(file.getName())) { return; } if (LocalFileSystem.getInstance() != file.getFileSystem() && !ApplicationManager.getApplication().isUnitTestMode()) { return; } if (!VfsUtilCore.isAncestor(project.getBaseDir(), file, true)) { return; } getInstance(project).scheduleUpdate(); } private class EmbeddedAndroidProject extends ProjectImpl { private Path path; protected EmbeddedAndroidProject(@NotNull Path filePath) { super((ComponentManagerImpl) ApplicationManager.getApplication(), filePath, TEMPLATE_PROJECT_NAME); path = filePath; } static final String TEMPLATE_PROJECT_NAME = "_android"; public String getLocationHash() { return ""; } public void init42(@Nullable ProgressIndicator indicator) { boolean finished = false; try { //ProjectManagerImpl.initProject(path, this, true, true, null, null); Method method = ReflectionUtil .getDeclaredMethod(ProjectManagerImpl.class, "initProject", Path.class, ProjectImpl.class, boolean.class, boolean.class, Project.class, ProgressIndicator.class); if (method == null) { disableGradleSyncAndNotifyUser(); return; } try { method.invoke(null, path, this, true, true, null, null); } catch (IllegalAccessException | InvocationTargetException e) { disableGradleSyncAndNotifyUser(); return; } finished = true; } finally { if (!finished) { TransactionGuard.submitTransaction(this, () -> WriteAction.run(() -> { if (isDisposed() && !isDisabled.get()) { Disposer.dispose(this); } })); } } } private void disableGradleSyncAndNotifyUser() { final FlutterSettings instance = FlutterSettings.getInstance(); instance.setSyncingAndroidLibraries(false); isDisabled.set(true); final Notification notification = new Notification( GRADLE_SYSTEM_ID.getReadableName() + " sync", "Gradle sync disabled", "An internal error prevents Gradle from analyzing the Android module at " + path, NotificationType.WARNING, null); Notifications.Bus.notify(notification, this); } } }
flutter-intellij/flutter-studio/src/io/flutter/android/AndroidModuleLibraryManager.java/0
{ "file_path": "flutter-intellij/flutter-studio/src/io/flutter/android/AndroidModuleLibraryManager.java", "repo_id": "flutter-intellij", "token_count": 5432 }
483
Kokoro Job Config This is the configuration for the `flutter-intellij-kokoro` job. Currently, the `gcp_windows` config is ignored; when this project was under active development the Windows support was not adequate. The `macos_external` config is used to do CI activities. It runs unit tests on presubmit and commit, checks the code for compilation problems in all supported IDEs, and performs a weekly dev-channel build (fully automated). Kokoro jobs run on the internal Google infrastructure. See https://developers.google.com/marketing/engineering/tools/kokoro for more about it. It has no special permissions. It is maintained by the Dart DevTools team. Currently, the primary contacts are stevemessick and helin24 (GitHub ids).
flutter-intellij/kokoro/README.md/0
{ "file_path": "flutter-intellij/kokoro/README.md", "repo_id": "flutter-intellij", "token_count": 187 }
484
<!-- Do not edit; instead, modify studio-contribs_template.xml, and run './bin/plugin generate'. --> <!-- Defines Android Studio IDE-specific contributions and implementations. --> <idea-plugin> <extensions defaultExtensionNs="io.flutter"> <gradleSyncProvider implementation="io.flutter.android.AndroidStudioGradleSyncProvider" order="first"/> <colorPickerProvider implementation="io.flutter.editor.AndroidStudioColorPickerProvider" order="first"/> </extensions> <extensions defaultExtensionNs="com.intellij"> <externalSystemTaskNotificationListener implementation="io.flutter.utils.FlutterExternalSystemTaskNotificationListener"/> <androidStudioInitializer implementation="io.flutter.FlutterStudioInitializer"/> <postStartupActivity implementation="io.flutter.FlutterStudioStartupActivity"/> <projectOpenProcessor implementation="io.flutter.editor.FlutterStudioProjectOpenProcessor" order="after flutter"/> <library.type implementation="io.flutter.android.AndroidModuleLibraryType"/> <projectService serviceInterface="io.flutter.android.AndroidModuleLibraryManager" serviceImplementation="io.flutter.android.AndroidModuleLibraryManager"/> </extensions> <actions> <!-- Define the 'New Flutter Project' menu item --> <action id="flutter.NewProject" class="io.flutter.actions.FlutterNewProjectAction" text="New Flutter Project..." description="Create a new Flutter project"> <add-to-group group-id="JavaNewProjectOrModuleGroup" anchor="after" relative-to-action="NewProject"/> </action> <!-- The icon isn't being used here, but it is set by the action --> <action id="flutter.NewProject.welcome" class="io.flutter.actions.FlutterNewProjectAction" text="Create New Flutter Project" icon="FlutterIcons.Flutter" description="Create a new Flutter project"> <add-to-group group-id="WelcomeScreen.QuickStart" anchor="first"/> </action> <!-- action id="DeveloperServices.FlutterNewsAssistant" class="io.flutter.actions.OpenFlutterNewsSidePanelAction" icon="/icons/flutter.png" text="What's New in Flutter"> <add-to-group group-id="HelpMenu" /> </action --> </actions> </idea-plugin>
flutter-intellij/resources/META-INF/studio-contribs.xml/0
{ "file_path": "flutter-intellij/resources/META-INF/studio-contribs.xml", "repo_id": "flutter-intellij", "token_count": 738 }
485
/* * 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. */ import 'dart:async'; import 'dart:io'; import 'build_spec.dart'; import 'util.dart'; Set<EditCommand> appliedEditCommands = {}; void checkAndClearAppliedEditCommands() { if (appliedEditCommands.length != editCommands.length) { final commands = <EditCommand>{}; commands.addAll(editCommands); commands.removeAll(appliedEditCommands); separator("UNUSED EditCommand"); for (final cmd in commands) { log(cmd.toString()); } } appliedEditCommands.clear(); } List<EditCommand> editCommands = [ EditCommand( path: 'flutter-idea/src/io/flutter/FlutterUtils.java', initials: [ ''' final Yaml yaml = new Yaml(new SafeConstructor(), new Representer(), new DumperOptions(), new Resolver() { ''' ], replacements: [ ''' final Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()), new Representer(new DumperOptions()), new DumperOptions(), new Resolver() { ''' ], versions: ['2023.2'], ), // When using LATEST-EAP-SNAPSHOT, also set baseVersion to LATEST-EAP-SNAPSHOT in the build spec. // EditCommand( // path: 'build.gradle.kts', // initials: ['version.set(ideVersion)'], // replacements: ['version.set("LATEST-EAP-SNAPSHOT")'], // versions: ['2023.3'], // ), // EditCommand( // path: 'flutter-idea/build.gradle.kts', // initials: ['version.set(ideVersion)'], // replacements: ['version.set("LATEST-EAP-SNAPSHOT")'], // versions: ['2023.3'], // ), ]; /// Apply all the editCommands applicable to a given BuildSpec. Future<int> applyEdits(BuildSpec spec, Function compileFn) async { // Handle skipped files. for (String file in spec.filesToSkip) { final entity = FileSystemEntity.isFileSync(file) ? File(file) : Directory(file); if (entity.existsSync()) { await entity.rename('$file~'); log('renamed $file'); if (entity is File) { final stubFile = File('${file}_stub'); if (stubFile.existsSync()) { await stubFile.copy(file); log('copied ${file}_stub'); } } } } final edited = <EditCommand, String>{}; try { for (final edit in editCommands) { final source = edit.convert(spec); if (source != null) { edited[edit] = source; appliedEditCommands.add(edit); } } return await compileFn.call(); } finally { // Restore sources. edited.forEach((edit, source) { log('Restoring ${edit.path}'); edit.restore(source); }); // Restore skipped files. for (final file in spec.filesToSkip) { final name = '$file~'; final entity = FileSystemEntity.isFileSync(name) ? File(name) : Directory(name); if (entity.existsSync()) { await entity.rename(file); } } } } /// Make some changes to a source file prior to compiling for a specific IDE. class EditCommand { EditCommand({ required this.path, required List<String> initials, required List<String> replacements, this.versions = const [], }) : assert(initials.length == replacements.length), assert(initials.isNotEmpty), assert(versions.isNotEmpty), initials = initials.map(_platformAdaptiveString).toList(), replacements = replacements.map(_platformAdaptiveString).toList(); /// The target file path. final String path; final List<String> initials; final List<String> replacements; /// The list of platform versions to perform the substitution for. final List<String> versions; String? convert(BuildSpec spec) { if (versionMatches(spec)) { final processedFile = File(path); String source = processedFile.readAsStringSync(); final original = source; for (int i = 0; i < initials.length; i++) { source = source.replaceAll(initials[i], replacements[i]); } processedFile.writeAsStringSync(source); return original; } else { return null; } } bool versionMatches(BuildSpec spec) { return versions.any((v) => spec.version.startsWith(v)); } void restore(String source) { final processedFile = File(path); processedFile.writeAsStringSync(source); } @override String toString() => "EditCommand(path: $path, versions: $versions)"; } String _platformAdaptiveString(String value) { if (value.isEmpty) { return value; } else if (Platform.isWindows) { return value.replaceAll('\n', '\r\n'); } else { return value.replaceAll('\r\n', '\n'); } }
flutter-intellij/tool/plugin/lib/edit.dart/0
{ "file_path": "flutter-intellij/tool/plugin/lib/edit.dart", "repo_id": "flutter-intellij", "token_count": 1745 }
486
# Below is a list of Flutter team members' GitHub handles who are # suggested reviewers for contributions to this repository. # # These names are just suggestions. It is fine to have your changes # reviewed by someone else. # # Use git ls-files '<pattern>' without a / prefix to see the list of matching files. /packages/flutter_tools/pubspec.yaml @christopherfujino /packages/flutter_tools/templates/module/ios/ @jmagman /packages/flutter_tools/templates/**/Podfile* @jmagman
flutter/CODEOWNERS/0
{ "file_path": "flutter/CODEOWNERS", "repo_id": "flutter", "token_count": 137 }
487
912c61f30512f560a342778bd648022aff32394b
flutter/bin/internal/engine.version/0
{ "file_path": "flutter/bin/internal/engine.version", "repo_id": "flutter", "token_count": 22 }
488
# This file is used by dartdoc when generating API documentation for Flutter. dartdoc: # Before you can run dartdoc, the snippets tool needs to be # activated with "pub global activate snippets <version>" # The dev/bots/docs.sh script does this automatically. tools: snippet: command: ["bin/cache/dart-sdk/bin/dart", "pub", "global", "run", "snippets", "--output-directory=doc/snippets", "--type=snippet"] description: "Creates sample code documentation output from embedded documentation samples." sample: command: ["bin/cache/dart-sdk/bin/dart", "pub", "global", "run", "snippets", "--output-directory=doc/snippets", "--type=sample"] description: "Creates full application sample code documentation output from embedded documentation samples." dartpad: command: ["bin/cache/dart-sdk/bin/dart", "pub", "global", "run", "snippets", "--output-directory=doc/snippets", "--type=dartpad"] description: "Creates full application sample code documentation output from embedded documentation samples and displays it in an embedded DartPad." errors: ## Default errors of dartdoc: - duplicate-file - invalid-parameter - tool-error - unresolved-export ## Warnings that are elevated to errors: - ambiguous-doc-reference - ambiguous-reexport - broken-link - category-order-gives-missing-package-name - deprecated - ignored-canonical-for - missing-example-file - missing-from-search-index - no-canonical-found - no-documentable-libraries - no-library-level-docs - orphaned-file - reexported-private-api-across-packages - unknown-file - unknown-html-fragment - unknown-macro - unresolved-doc-reference ## Ignores that are elevated to errors: # - type-as-html # broken, https://github.com/dart-lang/dartdoc/issues/3545 - missing-constant-constructor - missing-code-block-language
flutter/dartdoc_options.yaml/0
{ "file_path": "flutter/dartdoc_options.yaml", "repo_id": "flutter", "token_count": 649 }
489
// 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/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('tests must restore the value of reportTestException', (WidgetTester tester) async { // This test is expected to fail. reportTestException = (FlutterErrorDetails details, String testDescription) {}; }); }
flutter/dev/automated_tests/test_smoke_test/disallow_error_reporter_modification_test.dart/0
{ "file_path": "flutter/dev/automated_tests/test_smoke_test/disallow_error_reporter_modification_test.dart", "repo_id": "flutter", "token_count": 143 }
490
// 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'; // Various tests to verify that animated opacity layers (i.e. FadeTransition) do not // dirty children even without explicit repaint boundaries. These intentionally use // text to ensure we don't measure the opacity peephole case. class AnimatedComplexOpacity extends StatefulWidget { const AnimatedComplexOpacity({ super.key }); @override State<AnimatedComplexOpacity> createState() => _AnimatedComplexOpacityState(); } class _AnimatedComplexOpacityState extends State<AnimatedComplexOpacity> with SingleTickerProviderStateMixin { late final AnimationController controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 5000)); late final Animation<double> animation = controller.drive(Tween<double>(begin: 0.0, end: 1.0)); @override void initState() { super.initState(); controller.repeat(); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: ListView( children: <Widget>[ for (int i = 0; i < 20; i++) FadeTransition(opacity: animation, child: Center( child: Transform.scale(scale: 1.01, child: const ModeratelyComplexWidget()), )), ], ), ), ); } } class ModeratelyComplexWidget extends StatelessWidget { const ModeratelyComplexWidget({ super.key }); @override Widget build(BuildContext context) { return const Material( elevation: 10, clipBehavior: Clip.hardEdge, child: ListTile( leading: Icon(Icons.abc, size: 24), title: DecoratedBox(decoration: BoxDecoration(color: Colors.red), child: Text('Hello World')), trailing: FlutterLogo(), ), ); } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/animated_complex_opacity.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/animated_complex_opacity.dart", "repo_id": "flutter", "token_count": 693 }
491
// 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 'dart:ui' as ui; import 'package:flutter/material.dart'; import '../common.dart'; Map<String, WidgetBuilder> gradientPerfRoutes = <String, WidgetBuilder>{ kGradientPerfRecreateDynamicRouteName: (BuildContext _) => const RecreateDynamicPainterPage(), kGradientPerfRecreateConsistentRouteName: (BuildContext _) => const RecreateConsistentPainterPage(), kGradientPerfStaticConsistentRouteName: (BuildContext _) => const StaticConsistentPainterPage(), }; typedef CustomPaintFactory = CustomPainter Function(double hue); class GradientPerfHomePage extends StatelessWidget { const GradientPerfHomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Gradient Perf')), body: ListView( key: const Key(kGradientPerfScrollableName), children: <Widget>[ ElevatedButton( key: const Key(kGradientPerfRecreateDynamicRouteName), child: const Text('Recreate Dynamic Gradients'), onPressed: () { Navigator.pushNamed(context, kGradientPerfRecreateDynamicRouteName); }, ), ElevatedButton( key: const Key(kGradientPerfRecreateConsistentRouteName), child: const Text('Recreate Same Gradients'), onPressed: () { Navigator.pushNamed(context, kGradientPerfRecreateConsistentRouteName); }, ), ElevatedButton( key: const Key(kGradientPerfStaticConsistentRouteName), child: const Text('Static Gradients'), onPressed: () { Navigator.pushNamed(context, kGradientPerfStaticConsistentRouteName); }, ), ], ), ); } } class _PainterPage extends StatefulWidget { const _PainterPage({super.key, required this.title, required this.factory}); final String title; final CustomPaintFactory factory; @override State<_PainterPage> createState() => _PainterPageState(); } class RecreateDynamicPainterPage extends _PainterPage { const RecreateDynamicPainterPage({super.key}) : super(title: 'Recreate Dynamic Gradients', factory: makePainter); static CustomPainter makePainter(double f) { return RecreatedDynamicGradients(baseFactor: f); } } class RecreateConsistentPainterPage extends _PainterPage { const RecreateConsistentPainterPage({super.key}) : super(title: 'Recreate Same Gradients', factory: makePainter); static CustomPainter makePainter(double f) { return RecreatedConsistentGradients(baseFactor: f); } } class StaticConsistentPainterPage extends _PainterPage { const StaticConsistentPainterPage({super.key}) : super(title: 'Reuse Same Gradients', factory: makePainter); static CustomPainter makePainter(double f) { return StaticConsistentGradients(baseFactor: f); } } class _PainterPageState extends State<_PainterPage> with SingleTickerProviderStateMixin { late AnimationController _controller; @override void initState() { super.initState(); _controller = AnimationController(vsync: this); _controller.repeat(period: const Duration(seconds: 2)); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: AnimatedBuilder( animation: _controller, builder: (BuildContext context, Widget? child) { return CustomPaint( size: const Size(paintW, paintH), painter: widget.factory(_controller.value), willChange: true, ); }, ), ), ); } } Color color(double factor) { int v = ((factor * 255 * 3) % (255 * 3)).round(); if (v < 0) { v += 255 * 3; } int r = 0; int g = 0; int b = 0; if (v < 255) { r = 255 - v; g = v; } else { v -= 255; if (v < 255) { g = 255 - v; b = v; } else { v -= 255; b = 255 - v; r = v; } } return Color.fromARGB(255, r, g, b); } Shader rotatingGradient(double factor, double x, double y, double h) { final double s = sin(factor * 2 * pi) * h/8; final double c = cos(factor * 2 * pi) * h/8; final double cx = x; final double cy = y + h/2; final Offset p0 = Offset(cx + s, cy + c); final Offset p1 = Offset(cx - s, cy - c); return ui.Gradient.linear(p0, p1, <Color>[ color(factor), color(factor + 0.5), ]); } const int nAcross = 12; const int nDown = 16; const double cellW = 20; const double cellH = 20; const double hGap = 5; const double vGap = 5; const double paintW = hGap + (cellW + hGap) * nAcross; const double paintH = vGap + (cellH + vGap) * nDown; double x(int i, int j) { return hGap + i * (cellW + hGap); } double y(int i, int j) { return vGap + j * (cellH + vGap); } Shader gradient(double baseFactor, int i, int j) { final double lineFactor = baseFactor + 1/3 + 0.5 * (j + 1) / (nDown + 1); final double cellFactor = lineFactor + 1/3 * (i + 1) / (nAcross + 1); return rotatingGradient(cellFactor, x(i, j) + cellW / 2, y(i, j), cellH); } class RecreatedDynamicGradients extends CustomPainter { RecreatedDynamicGradients({required this.baseFactor}); final double baseFactor; @override void paint(Canvas canvas, Size size) { final Paint p = Paint(); p.color = color(baseFactor); canvas.drawRect(Offset.zero & size, p); for (int j = 0; j < nDown; j++) { for (int i = 0; i < nAcross; i++) { p.shader = gradient(baseFactor, i, j); canvas.drawRect(Rect.fromLTWH(x(i, j), y(i, j), cellW, cellH), p); } } } @override bool shouldRepaint(CustomPainter oldDelegate) => true; } class RecreatedConsistentGradients extends CustomPainter { RecreatedConsistentGradients({required this.baseFactor}); final double baseFactor; @override void paint(Canvas canvas, Size size) { final Paint p = Paint(); p.color = color(baseFactor); canvas.drawRect(Offset.zero & size, p); for (int j = 0; j < nDown; j++) { for (int i = 0; i < nAcross; i++) { p.shader = gradient(0, i, j); canvas.drawRect(Rect.fromLTWH(x(i, j), y(i, j), cellW, cellH), p); } } } @override bool shouldRepaint(CustomPainter oldDelegate) => true; } class StaticConsistentGradients extends CustomPainter { StaticConsistentGradients({required this.baseFactor}); final double baseFactor; static List<List<Shader>> gradients = <List<Shader>>[ for (int j = 0; j < nDown; j++) <Shader>[ for (int i = 0; i < nAcross; i++) gradient(0, i, j), ], ]; @override void paint(Canvas canvas, Size size) { final Paint p = Paint(); p.color = color(baseFactor); canvas.drawRect(Offset.zero & size, p); for (int j = 0; j < nDown; j++) { for (int i = 0; i < nAcross; i++) { p.shader = gradients[j][i]; canvas.drawRect(Rect.fromLTWH(x(i, j), y(i, j), cellW, cellH), p); } } } @override bool shouldRepaint(CustomPainter oldDelegate) => true; }
flutter/dev/benchmarks/macrobenchmarks/lib/src/gradient_perf.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/gradient_perf.dart", "repo_id": "flutter", "token_count": 2951 }
492
// 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:ffi' as ffi; import 'dart:io' as io; import 'package:flutter/material.dart'; import '../common.dart'; typedef GetStackPointerCallback = int Function(); // c interop function: // void* mmap(void* addr, size_t len, int prot, int flags, int fd, off_t offset); typedef CMmap = ffi.Pointer<ffi.Void> Function( ffi.Pointer<ffi.Void>, ffi.IntPtr, ffi.Int32, ffi.Int32, ffi.Int32, ffi.IntPtr); typedef DartMmap = ffi.Pointer<ffi.Void> Function( ffi.Pointer<ffi.Void>, int, int, int, int, int); final DartMmap mmap = ffi.DynamicLibrary.process().lookupFunction<CMmap, DartMmap>('mmap'); // c interop function: // int mprotect(void* addr, size_t len, int prot); typedef CMprotect = ffi.Int32 Function(ffi.Pointer<ffi.Void>, ffi.IntPtr, ffi.Int32); typedef DartMprotect = int Function(ffi.Pointer<ffi.Void>, int, int); final DartMprotect mprotect = ffi.DynamicLibrary.process() .lookupFunction<CMprotect, DartMprotect>('mprotect'); const int kProtRead = 1; const int kProtWrite = 2; const int kProtExec = 4; const int kMapPrivate = 0x02; const int kMapJit = 0x0; const int kMapAnon = 0x20; const int kMemorySize = 16; const int kInvalidFileDescriptor = -1; const int kkFileMappingOffset = 0; const int kMemoryStartingIndex = 0; const int kExitCodeSuccess = 0; final GetStackPointerCallback getStackPointer = () { // Makes sure we are running on an Android arm64 device. if (!io.Platform.isAndroid) { throw 'This benchmark test can only be run on Android arm devices.'; } final io.ProcessResult result = io.Process.runSync('getprop', <String>['ro.product.cpu.abi']); if (result.exitCode != 0) { throw 'Failed to retrieve CPU information.'; } if (!result.stdout.toString().contains('armeabi')) { throw 'This benchmark test can only be run on Android arm devices.'; } // Creates a block of memory to store the assembly code. final ffi.Pointer<ffi.Void> region = mmap(ffi.nullptr, kMemorySize, kProtRead | kProtWrite, kMapPrivate | kMapAnon | kMapJit, kInvalidFileDescriptor, kkFileMappingOffset); if (region == ffi.nullptr) { throw 'Failed to acquire memory for the test.'; } // Writes the assembly code into the memory block. This assembly code returns // the memory address of the stack pointer. region.cast<ffi.Uint8>().asTypedList(kMemorySize).setAll( kMemoryStartingIndex, <int>[ // "mov r0, sp" in machine code: 0D00A0E1. 0x0d, 0x00, 0xa0, 0xe1, // "bx lr" in machine code: 1EFF2FE1. 0x1e, 0xff, 0x2f, 0xe1, ] ); // Makes sure the memory block is executable. if (mprotect(region, kMemorySize, kProtRead | kProtExec) != kExitCodeSuccess) { throw 'Failed to write executable code to the memory.'; } return region .cast<ffi.NativeFunction<ffi.IntPtr Function()>>() .asFunction<int Function()>(); }(); class StackSizePage extends StatelessWidget { const StackSizePage({super.key}); @override Widget build(BuildContext context) { return const Material( child: Column( children: <Widget>[ SizedBox( width: 200, height: 100, child: ParentWidget(), ), ], ), ); } } class ParentWidget extends StatelessWidget { const ParentWidget({super.key}); @override Widget build(BuildContext context) { final int myStackSize = getStackPointer(); return ChildWidget(parentStackSize: myStackSize); } } class ChildWidget extends StatelessWidget { const ChildWidget({required this.parentStackSize, super.key}); final int parentStackSize; @override Widget build(BuildContext context) { final int myStackSize = getStackPointer(); // Captures the stack size difference between parent widget and child widget // during the rendering pipeline, i.e. one layer of stateless widget. return Text( '${parentStackSize - myStackSize}', key: const ValueKey<String>(kStackSizeKey), ); } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/stack_size.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/stack_size.dart", "repo_id": "flutter", "token_count": 1508 }
493
// 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'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'recorder.dart'; /// Creates a grid of mouse regions, then continuously scrolls them up and down. /// /// Measures our ability to render mouse regions. class BenchMouseRegionGridScroll extends WidgetRecorder { BenchMouseRegionGridScroll() : super(name: benchmarkName); static const String benchmarkName = 'bench_mouse_region_grid_scroll'; final _Tester _tester = _Tester(); // Use a non-trivial border to force Web to switch painter Border _getBorder(int columnIndex, int rowIndex) { const BorderSide defaultBorderSide = BorderSide(); return Border( left: columnIndex == 0 ? defaultBorderSide : BorderSide.none, top: rowIndex == 0 ? defaultBorderSide : BorderSide.none, right: defaultBorderSide, bottom: defaultBorderSide, ); } bool started = false; @override void frameDidDraw() { if (!started) { started = true; SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) async { _tester.start(); registerDidStop(_tester.stop); }); } super.frameDidDraw(); } @override Widget createWidget() { const int rowsCount = 60; const int columnsCount = 20; const double containerSize = 20; return Directionality( textDirection: TextDirection.ltr, child: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, height: 400, child: ListView.builder( itemCount: rowsCount, cacheExtent: rowsCount * containerSize, physics: const ClampingScrollPhysics(), itemBuilder: (BuildContext context, int rowIndex) => Row( children: List<Widget>.generate( columnsCount, (int columnIndex) => MouseRegion( onEnter: (_) {}, child: Container( decoration: BoxDecoration( border: _getBorder(columnIndex, rowIndex), color: Color.fromARGB(255, rowIndex * 20 % 256, 127, 127), ), width: containerSize, height: containerSize, ), ), ), ), ), ), ), ); } } abstract final class _UntilNextFrame { static Completer<void>? _completer; static Future<void> wait() { if (_UntilNextFrame._completer == null) { _UntilNextFrame._completer = Completer<void>(); SchedulerBinding.instance.addPostFrameCallback((_) { _UntilNextFrame._completer!.complete(); _UntilNextFrame._completer = null; }); } return _UntilNextFrame._completer!.future; } } class _Tester { static const int scrollFrequency = 60; static const Offset dragStartLocation = Offset(200, 200); static const Offset dragUpOffset = Offset(0, 200); static const Offset dragDownOffset = Offset(0, -200); static const Duration dragDuration = Duration(milliseconds: 200); bool _stopped = false; TestGesture get gesture { return _gesture ??= TestGesture( dispatcher: (PointerEvent event) async { RendererBinding.instance.handlePointerEvent(event); }, kind: PointerDeviceKind.mouse, ); } TestGesture? _gesture; Duration currentTime = Duration.zero; Future<void> _scroll(Offset start, Offset offset, Duration duration) async { final int durationMs = duration.inMilliseconds; final Duration fullFrameDuration = const Duration(seconds: 1) ~/ scrollFrequency; final int frameDurationMs = fullFrameDuration.inMilliseconds; final int fullFrames = duration.inMilliseconds ~/ frameDurationMs; final Offset fullFrameOffset = offset * (frameDurationMs.toDouble() / durationMs); final Duration finalFrameDuration = duration - fullFrameDuration * fullFrames; final Offset finalFrameOffset = offset - fullFrameOffset * fullFrames.toDouble(); await gesture.down(start, timeStamp: currentTime); for (int frame = 0; frame < fullFrames; frame += 1) { currentTime += fullFrameDuration; await gesture.moveBy(fullFrameOffset, timeStamp: currentTime); await _UntilNextFrame.wait(); } if (finalFrameOffset != Offset.zero) { currentTime += finalFrameDuration; await gesture.moveBy(finalFrameOffset, timeStamp: currentTime); await _UntilNextFrame.wait(); } await gesture.up(timeStamp: currentTime); } Future<void> start() async { await Future<void>.delayed(Duration.zero); while (!_stopped) { await _scroll(dragStartLocation, dragUpOffset, dragDuration); await _scroll(dragStartLocation, dragDownOffset, dragDuration); } } void stop() { _stopped = true; } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_mouse_region_grid_scroll.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_mouse_region_grid_scroll.dart", "repo_id": "flutter", "token_count": 1956 }
494
// 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/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:macrobenchmarks/common.dart'; import 'util.dart'; void main() { macroPerfTestE2E( 'very_long_picture_scrolling_perf', kVeryLongPictureScrollingRouteName, pageDelay: const Duration(seconds: 1), duration: const Duration(seconds: 30), body: (WidgetController controller) async { final Finder nestedScroll = find.byKey(const ValueKey<String>('vlp_single_child_scrollable')); expect(nestedScroll, findsOneWidget); Future<void> scrollOnce(double offset) async { await controller.timedDrag( nestedScroll, Offset(offset, 0.0), const Duration(milliseconds: 3500), ); await Future<void>.delayed(const Duration(milliseconds: 500)); } for (int i = 0; i < 2; i += 1) { await scrollOnce(-3000.0); await scrollOnce(-3000.0); await scrollOnce(3000.0); await scrollOnce(3000.0); } }, ); }
flutter/dev/benchmarks/macrobenchmarks/test/very_long_picture_scrolling_perf_e2e.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/test/very_long_picture_scrolling_perf_e2e.dart", "repo_id": "flutter", "token_count": 463 }
495
// 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:integration_test/integration_test_driver.dart' as driver; Future<void> main() => driver.integrationDriver( responseDataCallback: (Map<String, dynamic>? data) async { final Map<String, dynamic> benchmarkLiveResult = data?['benchmarkLive'] as Map<String,dynamic>; final Map<String, dynamic> fullyLiveResult = data?['fullyLive'] as Map<String,dynamic>; if (benchmarkLiveResult['frame_count'] as int < 10 || fullyLiveResult['frame_count'] as int < 10) { print('Failure Details:\nNot Enough frames collected: ' 'benchmarkLive ${benchmarkLiveResult['frameCount']}, ' '${fullyLiveResult['frameCount']}.'); exit(1); } await driver.writeResponseData( <String, dynamic>{ 'benchmarkLive': benchmarkLiveResult, 'fullyLive': fullyLiveResult, }, testOutputFilename: 'frame_policy_event_delay', ); } );
flutter/dev/benchmarks/macrobenchmarks/test_driver/frame_policy_test.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/test_driver/frame_policy_test.dart", "repo_id": "flutter", "token_count": 401 }
496
// 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/gestures.dart'; import 'package:flutter_test/flutter_test.dart'; import '../common.dart'; import 'data/velocity_tracker_data.dart'; const int _kNumIters = 10000; class TrackerBenchmark { TrackerBenchmark({required this.name, required this.tracker }); final VelocityTracker tracker; final String name; } Future<void> main() async { assert(false, "Don't run benchmarks in debug mode! Use 'flutter run --release'."); final BenchmarkResultPrinter printer = BenchmarkResultPrinter(); final List<TrackerBenchmark> benchmarks = <TrackerBenchmark>[ TrackerBenchmark(name: 'velocity_tracker_iteration', tracker: VelocityTracker.withKind(PointerDeviceKind.touch)), TrackerBenchmark(name: 'velocity_tracker_iteration_ios_fling', tracker: IOSScrollViewFlingVelocityTracker(PointerDeviceKind.touch)), ]; final Stopwatch watch = Stopwatch(); await benchmarkWidgets((WidgetTester tester) async { for (final TrackerBenchmark benchmark in benchmarks) { print('${benchmark.name} benchmark...'); final VelocityTracker tracker = benchmark.tracker; watch.reset(); watch.start(); for (int i = 0; i < _kNumIters; i += 1) { for (final PointerEvent event in velocityEventData) { if (event is PointerDownEvent || event is PointerMoveEvent) { tracker.addPosition(event.timeStamp, event.position); } if (event is PointerUpEvent) { tracker.getVelocity(); } } } watch.stop(); printer.addResult( description: 'Velocity tracker: ${tracker.runtimeType}', value: watch.elapsedMicroseconds / _kNumIters, unit: 'µs per iteration', name: benchmark.name, ); } }); printer.printToStdout(); }
flutter/dev/benchmarks/microbenchmarks/lib/gestures/velocity_tracker_bench.dart/0
{ "file_path": "flutter/dev/benchmarks/microbenchmarks/lib/gestures/velocity_tracker_bench.dart", "repo_id": "flutter", "token_count": 711 }
497
<!-- 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. --> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application android:name=".App" android:allowBackup="true" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/Theme.MultipleFlutters"> <activity android:exported="true" android:name=".MainActivity" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
flutter/dev/benchmarks/multiple_flutters/android/app/src/main/AndroidManifest.xml/0
{ "file_path": "flutter/dev/benchmarks/multiple_flutters/android/app/src/main/AndroidManifest.xml", "repo_id": "flutter", "token_count": 426 }
498
name: multiple_flutters_module description: A module that is embedded in the multiple_flutters benchmark test. version: 1.0.0+1 environment: sdk: '>=3.2.0-0 <4.0.0' dependencies: flutter: sdk: flutter cupertino_icons: 1.0.6 google_fonts: 4.0.4 async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" 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" crypto: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" ffi: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" http: 0.13.6 # 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" 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" path: 1.9.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" path_provider: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" path_provider_android: 2.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" path_provider_foundation: 2.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" path_provider_linux: 2.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" path_provider_platform_interface: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" path_provider_windows: 2.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" platform: 3.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" plugin_platform_interface: 2.1.8 # 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" 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" vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" win32: 5.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" xdg_directories: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" flutter: uses-material-design: true module: androidX: true androidPackage: com.example.multiple_flutters_module iosBundleIdentifier: com.example.multipleFluttersModule # PUBSPEC CHECKSUM: 82b0
flutter/dev/benchmarks/multiple_flutters/module/pubspec.yaml/0
{ "file_path": "flutter/dev/benchmarks/multiple_flutters/module/pubspec.yaml", "repo_id": "flutter", "token_count": 1093 }
499
// 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/material.dart'; void main() { runApp( const PlatformViewApp() ); } class PlatformViewApp extends StatefulWidget { const PlatformViewApp({ super.key, }); @override PlatformViewAppState createState() => PlatformViewAppState(); } class PlatformViewAppState extends State<PlatformViewApp> { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData.light(), title: 'Advanced Layout', home: const PlatformViewLayout(), ); } } class PlatformViewLayout extends StatelessWidget { const PlatformViewLayout({ super.key }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Platform View Scrolling Layout')), body: ListView.builder( key: const Key('platform-views-scroll'), // This key is used by the driver test. itemCount: 200, itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.all(5.0), child: Material( elevation: (index % 5 + 1).toDouble(), color: Colors.white, child: index.isEven ? CustomPaint(painter: ExpensivePainter(), size: const Size(400, 200)) : const DummyPlatformView() ), ); }, ), ); } } class DummyPlatformView extends StatelessWidget { const DummyPlatformView({super.key}); @override Widget build(BuildContext context) { const String viewType = 'benchmarks/platform_views_layout/DummyPlatformView'; late Widget nativeView; if (Platform.isIOS) { nativeView = const UiKitView( viewType: viewType, ); } else if (Platform.isAndroid) { nativeView = const AndroidView( viewType: viewType, ); } else { assert(false, 'Invalid platform'); } return Container( color: Colors.purple, height: 200.0, child: nativeView, ); } } class ExpensivePainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { final double boxWidth = size.width / 50; final double boxHeight = size.height / 50; for (int i = 0; i < 50; i++) { for (int j = 0; j < 50; j++) { final Rect rect = Rect.fromLTWH(i * boxWidth, j * boxHeight, boxWidth, boxHeight); canvas.drawRect(rect, Paint() ..style = PaintingStyle.fill ..color = Colors.red ); } } } @override bool shouldRepaint(covariant CustomPainter oldDelegate) { return false; } }
flutter/dev/benchmarks/platform_views_layout/lib/main_non_intersecting.dart/0
{ "file_path": "flutter/dev/benchmarks/platform_views_layout/lib/main_non_intersecting.dart", "repo_id": "flutter", "token_count": 1097 }
500
# Stocks Demo app for the Material Design widgets and other features provided by Flutter. ## Building You can follow these instructions to build the stocks app and install it onto your device. ### Prerequisites If you are new to Flutter, please first follow the [Flutter Setup](https://flutter.dev/setup/) guide. ### Building and installing the stocks demo app * `cd $FLUTTER_ROOT/examples/stocks` * `flutter pub get` * `flutter run --release` The `flutter run --release` command both builds and installs the Flutter app. ## Internationalization This app has been internationalized (just enough to show how it's done). It's an example of how one can do so with the gen_l10n tool. See [regenerate.md](lib/i18n/regenerate.md) for an explanation for how the tool is used to generate localizations for this app. ## Icon The icon was created using Android Asset Studio: https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html#foreground.type=image&foreground.space.trim=0&foreground.space.pad=0&foreColor=607d8b%2C0&crop=0&backgroundShape=square&backColor=fff%2C100&effects=none From this clipart: https://openclipart.org/detail/30403/tango-go-up Which is in the public domain.
flutter/dev/benchmarks/test_apps/stocks/README.md/0
{ "file_path": "flutter/dev/benchmarks/test_apps/stocks/README.md", "repo_id": "flutter", "token_count": 362 }
501
#include "Generated.xcconfig"
flutter/dev/benchmarks/test_apps/stocks/ios/Flutter/Debug.xcconfig/0
{ "file_path": "flutter/dev/benchmarks/test_apps/stocks/ios/Flutter/Debug.xcconfig", "repo_id": "flutter", "token_count": 12 }
502
// 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 FOLLOWING FILES WERE GENERATED BY `flutter gen-l10n`. import 'stock_strings.dart'; /// The translations for English (`en`). class StockStringsEn extends StockStrings { StockStringsEn([super.locale = 'en']); @override String get title => 'Stocks'; @override String get market => 'MARKET'; @override String get portfolio => 'PORTFOLIO'; } /// The translations for English, as used in the United States (`en_US`). class StockStringsEnUs extends StockStringsEn { StockStringsEnUs(): super('en_US'); @override String get title => 'Stocks'; @override String get market => 'MARKET'; @override String get portfolio => 'PORTFOLIO'; }
flutter/dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings_en.dart/0
{ "file_path": "flutter/dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings_en.dart", "repo_id": "flutter", "token_count": 264 }
503
// 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_test/flutter_test.dart'; import 'package:stocks/main.dart' as stocks; import 'package:stocks/stock_data.dart' as stock_data; void main() { stock_data.StockData.actuallyFetchData = false; testWidgets('Changing locale', (WidgetTester tester) async { stocks.main(); await tester.pump(); // The initial test app's locale is "_", so we're seeing the fallback translation here. expect(find.text('MARKET'), findsOneWidget); await tester.binding.setLocale('es', ''); // The localized strings have finished loading and dependent // widgets have been updated. await tester.pump(); expect(find.text('MERCADO'), findsOneWidget); }); }
flutter/dev/benchmarks/test_apps/stocks/test/locale_test.dart/0
{ "file_path": "flutter/dev/benchmarks/test_apps/stocks/test/locale_test.dart", "repo_id": "flutter", "token_count": 272 }
504
// 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:analyzer/dart/analysis/results.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/type.dart'; import '../utils.dart'; import 'analyze.dart'; /// Don't use Future.catchError or Future.onError. /// /// See https://github.com/flutter/flutter/pull/130662 for more context. /// /// **BAD:** /// /// ```dart /// Future<Object?> doSomething() { /// return doSomethingAsync().catchError((_) => null); /// } /// /// Future<Object?> doSomethingAsync() { /// return Future<Object>.error(Exception('error')); /// } /// ``` /// /// **GOOD:** /// /// ```dart /// Future<Object?> doSomething() { /// return doSomethingAsync().then( /// (Object? obj) => obj, /// onError: (_) => null, /// ); /// } /// /// Future<Object?> doSomethingAsync() { /// return Future<Object>.error(Exception('error')); /// } /// ``` class AvoidFutureCatchError extends AnalyzeRule { final Map<ResolvedUnitResult, List<AstNode>> _errors = <ResolvedUnitResult, List<AstNode>>{}; @override void applyTo(ResolvedUnitResult unit) { final _Visitor visitor = _Visitor(); unit.unit.visitChildren(visitor); if (visitor._offendingNodes.isNotEmpty) { _errors.putIfAbsent(unit, () => <AstNode>[]).addAll(visitor._offendingNodes); } } @override void reportViolations(String workingDirectory) { if (_errors.isEmpty) { return; } foundError(<String>[ for (final MapEntry<ResolvedUnitResult, List<AstNode>> entry in _errors.entries) for (final AstNode node in entry.value) '${locationInFile(entry.key, node, workingDirectory)}: ${node.parent}', '\n${bold}Future.catchError and Future.onError are not type safe--instead use Future.then: https://github.com/dart-lang/sdk/issues/51248$reset', ]); } @override String toString() => 'Avoid "Future.catchError" and "Future.onError"'; } class _Visitor extends RecursiveAstVisitor<void> { _Visitor(); final List<AstNode> _offendingNodes = <AstNode>[]; @override void visitMethodInvocation(MethodInvocation node) { if (node.methodName.name != 'onError' && node.methodName.name != 'catchError') { return; } final DartType? targetType = node.realTarget?.staticType; if (targetType == null || !targetType.isDartAsyncFuture) { return; } _offendingNodes.add(node); } }
flutter/dev/bots/custom_rules/avoid_future_catcherror.dart/0
{ "file_path": "flutter/dev/bots/custom_rules/avoid_future_catcherror.dart", "repo_id": "flutter", "token_count": 926 }
505
// 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 file is used by ../analyze_snippet_code_test.dart, which depends on the // precise contents (including especially the comments) of this file. // Examples can assume: // import 'package:flutter/rendering.dart'; /// no error: rendering library was imported. /// ```dart /// print(RenderObject); /// ``` String? bar; /// error: widgets library was not imported (not even implicitly). /// ```dart /// print(Widget); // error (undefined_identifier) /// ``` String? foo;
flutter/dev/bots/test/analyze-snippet-code-test-input/custom_imports_broken.dart/0
{ "file_path": "flutter/dev/bots/test/analyze-snippet-code-test-input/custom_imports_broken.dart", "repo_id": "flutter", "token_count": 183 }
506
// 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 script removes published archives from the cloud storage and the /// corresponding JSON metadata file that the website uses to determine what /// releases are available. /// /// If asked to remove a release that is currently the release on that channel, /// it will replace that release with the next most recent release on that /// channel. library; import 'dart:async'; import 'dart:convert'; import 'dart:io' hide Platform; import 'package:args/args.dart'; import 'package:path/path.dart' as path; import 'package:platform/platform.dart' show LocalPlatform, Platform; import 'package:process/process.dart'; const String gsBase = 'gs://flutter_infra_release'; const String releaseFolder = '/releases'; const String gsReleaseFolder = '$gsBase$releaseFolder'; const String baseUrl = 'https://storage.googleapis.com/flutter_infra_release'; /// Exception class for when a process fails to run, so we can catch /// it and provide something more readable than a stack trace. class UnpublishException implements Exception { UnpublishException(this.message, [this.result]); final String message; final ProcessResult? result; int get exitCode => result?.exitCode ?? -1; @override String toString() { String output = runtimeType.toString(); output += ': $message'; final String stderr = result?.stderr as String? ?? ''; if (stderr.isNotEmpty) { output += ':\n$stderr'; } return output; } } enum Channel { dev, beta, stable } String getChannelName(Channel channel) { return switch (channel) { Channel.beta => 'beta', Channel.dev => 'dev', Channel.stable => 'stable', }; } Channel fromChannelName(String? name) { return switch (name) { 'beta' => Channel.beta, 'dev' => Channel.dev, 'stable' => Channel.stable, _ => throw ArgumentError('Invalid channel name.'), }; } enum PublishedPlatform { linux, macos, windows } String getPublishedPlatform(PublishedPlatform platform) { return switch (platform) { PublishedPlatform.linux => 'linux', PublishedPlatform.macos => 'macos', PublishedPlatform.windows => 'windows', }; } PublishedPlatform fromPublishedPlatform(String name) { return switch (name) { 'linux' => PublishedPlatform.linux, 'macos' => PublishedPlatform.macos, 'windows' => PublishedPlatform.windows, _ => throw ArgumentError('Invalid published platform name.'), }; } /// A helper class for classes that want to run a process, optionally have the /// stderr and stdout reported as the process runs, and capture the stdout /// properly without dropping any. class ProcessRunner { /// Creates a [ProcessRunner]. /// /// The [processManager], [subprocessOutput], and [platform] arguments must /// not be null. ProcessRunner({ this.processManager = const LocalProcessManager(), this.subprocessOutput = true, this.defaultWorkingDirectory, this.platform = const LocalPlatform(), }) { environment = Map<String, String>.from(platform.environment); } /// The platform to use for a starting environment. final Platform platform; /// Set [subprocessOutput] to show output as processes run. Stdout from the /// process will be printed to stdout, and stderr printed to stderr. final bool subprocessOutput; /// Set the [processManager] in order to inject a test instance to perform /// testing. final ProcessManager processManager; /// Sets the default directory used when `workingDirectory` is not specified /// to [runProcess]. final Directory? defaultWorkingDirectory; /// The environment to run processes with. late Map<String, String> environment; /// Run the command and arguments in `commandLine` as a sub-process from /// `workingDirectory` if set, or the [defaultWorkingDirectory] if not. Uses /// [Directory.current] if [defaultWorkingDirectory] is not set. /// /// Set `failOk` if [runProcess] should not throw an exception when the /// command completes with a non-zero exit code. Future<String> runProcess( List<String> commandLine, { Directory? workingDirectory, bool failOk = false, }) async { workingDirectory ??= defaultWorkingDirectory ?? Directory.current; if (subprocessOutput) { stderr.write('Running "${commandLine.join(' ')}" in ${workingDirectory.path}.\n'); } final List<int> output = <int>[]; final Completer<void> stdoutComplete = Completer<void>(); final Completer<void> stderrComplete = Completer<void>(); late Process process; Future<int> allComplete() async { await stderrComplete.future; await stdoutComplete.future; return process.exitCode; } try { process = await processManager.start( commandLine, workingDirectory: workingDirectory.absolute.path, environment: environment, ); process.stdout.listen( (List<int> event) { output.addAll(event); if (subprocessOutput) { stdout.add(event); } }, onDone: () async => stdoutComplete.complete(), ); if (subprocessOutput) { process.stderr.listen( (List<int> event) { stderr.add(event); }, onDone: () async => stderrComplete.complete(), ); } else { stderrComplete.complete(); } } on ProcessException catch (e) { final String message = 'Running "${commandLine.join(' ')}" in ${workingDirectory.path} ' 'failed with:\n$e'; throw UnpublishException(message); } on ArgumentError catch (e) { final String message = 'Running "${commandLine.join(' ')}" in ${workingDirectory.path} ' 'failed with:\n$e'; throw UnpublishException(message); } final int exitCode = await allComplete(); if (exitCode != 0 && !failOk) { final String message = 'Running "${commandLine.join(' ')}" in ${workingDirectory.path} failed'; throw UnpublishException( message, ProcessResult(0, exitCode, null, 'returned $exitCode'), ); } return utf8.decoder.convert(output).trim(); } } class ArchiveUnpublisher { ArchiveUnpublisher( this.tempDir, this.revisionsBeingRemoved, this.channels, this.platform, { this.confirmed = false, ProcessManager? processManager, bool subprocessOutput = true, }) : assert(revisionsBeingRemoved.length == 40), metadataGsPath = '$gsReleaseFolder/${getMetadataFilename(platform)}', _processRunner = ProcessRunner( processManager: processManager ?? const LocalProcessManager(), subprocessOutput: subprocessOutput, ); final PublishedPlatform platform; final String metadataGsPath; final Set<Channel> channels; final Set<String> revisionsBeingRemoved; final bool confirmed; final Directory tempDir; final ProcessRunner _processRunner; static String getMetadataFilename(PublishedPlatform platform) => 'releases_${getPublishedPlatform(platform)}.json'; /// Remove the archive from Google Storage. Future<void> unpublishArchive() async { final Map<String, dynamic> jsonData = await _loadMetadata(); final List<Map<String, String>> releases = (jsonData['releases'] as List<dynamic>).map<Map<String, String>>((dynamic entry) { final Map<String, dynamic> mapEntry = entry as Map<String, dynamic>; return mapEntry.cast<String, String>(); }).toList(); final Map<Channel, Map<String, String>> paths = await _getArchivePaths(releases); releases.removeWhere((Map<String, String> value) => revisionsBeingRemoved.contains(value['hash']) && channels.contains(fromChannelName(value['channel']))); releases.sort((Map<String, String> a, Map<String, String> b) { final DateTime aDate = DateTime.parse(a['release_date']!); final DateTime bDate = DateTime.parse(b['release_date']!); return bDate.compareTo(aDate); }); jsonData['releases'] = releases; for (final Channel channel in channels) { if (!revisionsBeingRemoved.contains((jsonData['current_release'] as Map<String, dynamic>)[getChannelName(channel)])) { // Don't replace the current release if it's not one of the revisions we're removing. continue; } final Map<String, String> replacementRelease = releases.firstWhere((Map<String, String> value) => value['channel'] == getChannelName(channel)); (jsonData['current_release'] as Map<String, dynamic>)[getChannelName(channel)] = replacementRelease['hash']; print( '${confirmed ? 'Reverting' : 'Would revert'} current ${getChannelName(channel)} ' '${getPublishedPlatform(platform)} release to ${replacementRelease['hash']} (version ${replacementRelease['version']}).' ); } await _cloudRemoveArchive(paths); await _updateMetadata(jsonData); } Future<Map<Channel, Map<String, String>>> _getArchivePaths(List<Map<String, String>> releases) async { final Set<String> hashes = <String>{}; final Map<Channel, Map<String, String>> paths = <Channel, Map<String, String>>{}; for (final Map<String, String> revision in releases) { final String hash = revision['hash']!; final Channel channel = fromChannelName(revision['channel']); hashes.add(hash); if (revisionsBeingRemoved.contains(hash) && channels.contains(channel)) { paths[channel] ??= <String, String>{}; paths[channel]![hash] = revision['archive']!; } } final Set<String> missingRevisions = revisionsBeingRemoved.difference(hashes.intersection(revisionsBeingRemoved)); if (missingRevisions.isNotEmpty) { final bool plural = missingRevisions.length > 1; throw UnpublishException('Revision${plural ? 's' : ''} $missingRevisions ${plural ? 'are' : 'is'} not present in the server metadata.'); } return paths; } Future<Map<String, dynamic>> _loadMetadata() async { final File metadataFile = File( path.join(tempDir.absolute.path, getMetadataFilename(platform)), ); // Always run this, even in dry runs. await _runGsUtil(<String>['cp', metadataGsPath, metadataFile.absolute.path], confirm: true); final String currentMetadata = metadataFile.readAsStringSync(); if (currentMetadata.isEmpty) { throw UnpublishException('Empty metadata received from server'); } Map<String, dynamic> jsonData; try { jsonData = json.decode(currentMetadata) as Map<String, dynamic>; } on FormatException catch (e) { throw UnpublishException('Unable to parse JSON metadata received from cloud: $e'); } return jsonData; } Future<void> _updateMetadata(Map<String, dynamic> jsonData) async { // We can't just cat the metadata from the server with 'gsutil cat', because // Windows wants to echo the commands that execute in gsutil.bat to the // stdout when we do that. So, we copy the file locally and then read it // back in. final File metadataFile = File( path.join(tempDir.absolute.path, getMetadataFilename(platform)), ); const JsonEncoder encoder = JsonEncoder.withIndent(' '); metadataFile.writeAsStringSync(encoder.convert(jsonData)); print('${confirmed ? 'Overwriting' : 'Would overwrite'} $metadataGsPath with contents of ${metadataFile.absolute.path}'); await _cloudReplaceDest(metadataFile.absolute.path, metadataGsPath); } Future<String> _runGsUtil( List<String> args, { Directory? workingDirectory, bool failOk = false, bool confirm = false, }) async { final List<String> command = <String>['gsutil', '--', ...args]; if (confirm) { return _processRunner.runProcess( command, workingDirectory: workingDirectory, failOk: failOk, ); } else { print('Would run: ${command.join(' ')}'); return ''; } } Future<void> _cloudRemoveArchive(Map<Channel, Map<String, String>> paths) async { final List<String> files = <String>[]; print('${confirmed ? 'Removing' : 'Would remove'} the following release archives:'); for (final Channel channel in paths.keys) { final Map<String, String> hashes = paths[channel]!; for (final String hash in hashes.keys) { final String file = '$gsReleaseFolder/${hashes[hash]}'; files.add(file); print(' $file'); } } await _runGsUtil(<String>['rm', ...files], failOk: true, confirm: confirmed); } Future<String> _cloudReplaceDest(String src, String dest) async { assert(dest.startsWith('gs:'), '_cloudReplaceDest must have a destination in cloud storage.'); assert(!src.startsWith('gs:'), '_cloudReplaceDest must have a local source file.'); // We often don't have permission to overwrite, but // we have permission to remove, so that's what we do first. await _runGsUtil(<String>['rm', dest], failOk: true, confirm: confirmed); String? mimeType; if (dest.endsWith('.tar.xz')) { mimeType = 'application/x-gtar'; } if (dest.endsWith('.zip')) { mimeType = 'application/zip'; } if (dest.endsWith('.json')) { mimeType = 'application/json'; } final List<String> args = <String>[ // Use our preferred MIME type for the files we care about // and let gsutil figure it out for anything else. if (mimeType != null) ...<String>['-h', 'Content-Type:$mimeType'], ...<String>['cp', src, dest], ]; return _runGsUtil(args, confirm: confirmed); } } void _printBanner(String message) { final String banner = '*** $message ***'; print('\n'); print('*' * banner.length); print(banner); print('*' * banner.length); print('\n'); } /// Prepares a flutter git repo to be removed from the published cloud storage. Future<void> main(List<String> rawArguments) async { final List<String> allowedChannelValues = Channel.values.map<String>((Channel channel) => getChannelName(channel)).toList(); final List<String> allowedPlatformNames = PublishedPlatform.values.map<String>((PublishedPlatform platform) => getPublishedPlatform(platform)).toList(); final ArgParser argParser = ArgParser(); argParser.addOption( 'temp_dir', help: 'A location where temporary files may be written. Defaults to a ' 'directory in the system temp folder. If a temp_dir is not ' 'specified, then by default a generated temporary directory will be ' 'created, used, and removed automatically when the script exits.', ); argParser.addMultiOption('revision', help: 'The Flutter git repo revisions to remove from the published site. ' 'Must be full 40-character hashes. More than one may be specified, ' 'either by giving the option more than once, or by giving a comma ' 'separated list. Required.'); argParser.addMultiOption( 'channel', allowed: allowedChannelValues, help: 'The Flutter channels to remove the archives corresponding to the ' 'revisions given with --revision. More than one may be specified, ' 'either by giving the option more than once, or by giving a ' 'comma separated list. If not specified, then the archives from all ' 'channels that a revision appears in will be removed.', ); argParser.addMultiOption( 'platform', allowed: allowedPlatformNames, help: 'The Flutter platforms to remove the archive from. May specify more ' 'than one, either by giving the option more than once, or by giving a ' 'comma separated list. If not specified, then the archives from all ' 'platforms that a revision appears in will be removed.', ); argParser.addFlag( 'confirm', help: 'If set, will actually remove the archive from Google Cloud Storage ' 'upon successful execution of this script. Published archives will be ' 'removed from this directory: $baseUrl$releaseFolder. This option ' 'must be set to perform any action on the server, otherwise only a dry ' 'run is performed.', ); argParser.addFlag( 'help', negatable: false, help: 'Print help for this command.', ); final ArgResults parsedArguments = argParser.parse(rawArguments); if (parsedArguments['help'] as bool) { print(argParser.usage); exit(0); } void errorExit(String message, {int exitCode = -1}) { stderr.write('Error: $message\n\n'); stderr.write('${argParser.usage}\n'); exit(exitCode); } final List<String> revisions = parsedArguments['revision'] as List<String>; if (revisions.isEmpty) { errorExit('Invalid argument: at least one --revision must be specified.'); } for (final String revision in revisions) { if (revision.length != 40) { errorExit('Invalid argument: --revision "$revision" must be the entire hash, not just a prefix.'); } if (revision.contains(RegExp(r'[^a-fA-F0-9]'))) { errorExit('Invalid argument: --revision "$revision" contains non-hex characters.'); } } final String tempDirArg = parsedArguments['temp_dir'] as String; Directory tempDir; bool removeTempDir = false; if (tempDirArg.isEmpty) { tempDir = Directory.systemTemp.createTempSync('flutter_package.'); removeTempDir = true; } else { tempDir = Directory(tempDirArg); if (!tempDir.existsSync()) { errorExit("Temporary directory $tempDirArg doesn't exist."); } } if (!(parsedArguments['confirm'] as bool)) { _printBanner('This will be just a dry run. To actually perform the changes below, re-run with --confirm argument.'); } final List<String> channelArg = parsedArguments['channel'] as List<String>; final List<String> channelOptions = channelArg.isNotEmpty ? channelArg : allowedChannelValues; final Set<Channel> channels = channelOptions.map<Channel>((String value) => fromChannelName(value)).toSet(); final List<String> platformArg = parsedArguments['platform'] as List<String>; final List<String> platformOptions = platformArg.isNotEmpty ? platformArg : allowedPlatformNames; final List<PublishedPlatform> platforms = platformOptions.map<PublishedPlatform>((String value) => fromPublishedPlatform(value)).toList(); int exitCode = 0; late String message; late String stack; try { for (final PublishedPlatform platform in platforms) { final ArchiveUnpublisher publisher = ArchiveUnpublisher( tempDir, revisions.toSet(), channels, platform, confirmed: parsedArguments['confirm'] as bool, ); await publisher.unpublishArchive(); } } on UnpublishException catch (e, s) { exitCode = e.exitCode; message = e.message; stack = s.toString(); } catch (e, s) { exitCode = -1; message = e.toString(); stack = s.toString(); } finally { if (removeTempDir) { tempDir.deleteSync(recursive: true); } if (exitCode != 0) { errorExit('$message\n$stack', exitCode: exitCode); } if (!(parsedArguments['confirm'] as bool)) { _printBanner('This was just a dry run. To actually perform the above changes, re-run with --confirm argument.'); } exit(0); } }
flutter/dev/bots/unpublish_package.dart/0
{ "file_path": "flutter/dev/bots/unpublish_package.dart", "repo_id": "flutter", "token_count": 6480 }
507
// 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/args.dart'; import 'proto/conductor_state.pb.dart' as pb; import 'repository.dart'; const String gsutilBinary = 'gsutil.py'; const String kFrameworkDefaultBranch = 'master'; const String kForceFlag = 'force'; const List<String> kBaseReleaseChannels = <String>['stable', 'beta']; const List<String> kReleaseChannels = <String>[...kBaseReleaseChannels, FrameworkRepository.defaultBranch]; const String kReleaseDocumentationUrl = 'https://github.com/flutter/flutter/wiki/Flutter-Cherrypick-Process'; const String kLuciPackagingConsoleLink = 'https://ci.chromium.org/p/dart-internal/g/flutter_packaging/console'; const String kWebsiteReleasesUrl = 'https://docs.flutter.dev/development/tools/sdk/releases'; const String discordReleaseChannel = 'https://discord.com/channels/608014603317936148/783492179922124850'; const String flutterReleaseHotline = 'https://mail.google.com/chat/u/0/#chat/space/AAAA6RKcK2k'; const String hotfixToStableWiki = 'https://github.com/flutter/flutter/wiki/Hotfixes-to-the-Stable-Channel'; const String flutterAnnounceGroup = 'https://groups.google.com/g/flutter-announce'; const String hotfixDocumentationBestPractices = 'https://github.com/flutter/flutter/wiki/Hotfix-Documentation-Best-Practices'; final RegExp releaseCandidateBranchRegex = RegExp( r'flutter-(\d+)\.(\d+)-candidate\.(\d+)', ); /// Cast a dynamic to String and trim. String stdoutToString(dynamic input) { final String str = input as String; return str.trim(); } class ConductorException implements Exception { ConductorException(this.message); final String message; @override String toString() => 'Exception: $message'; } bool assertsEnabled() { // Verify asserts enabled bool assertsEnabled = false; assert(() { assertsEnabled = true; return true; }()); return assertsEnabled; } /// Either return the value from [env] or fall back to [argResults]. /// /// If the key does not exist in either the environment or CLI args, throws a /// [ConductorException]. /// /// The environment is favored over CLI args since the latter can have a default /// value, which the environment should be able to override. String? getValueFromEnvOrArgs( String name, ArgResults argResults, Map<String, String> env, { bool allowNull = false, }) { final String envName = fromArgToEnvName(name); if (env[envName] != null) { return env[envName]; } final String? argValue = argResults[name] as String?; if (argValue != null) { return argValue; } if (allowNull) { return null; } throw ConductorException('Expected either the CLI arg --$name or the environment variable $envName ' 'to be provided!'); } bool getBoolFromEnvOrArgs( String name, ArgResults argResults, Map<String, String> env, ) { final String envName = fromArgToEnvName(name); if (env[envName] != null) { return env[envName]?.toUpperCase() == 'TRUE'; } return argResults[name] as bool; } /// Return multiple values from the environment or fall back to [argResults]. /// /// Values read from an environment variable are assumed to be comma-delimited. /// /// If the key does not exist in either the CLI args or environment, throws a /// [ConductorException]. /// /// The environment is favored over CLI args since the latter can have a default /// value, which the environment should be able to override. List<String> getValuesFromEnvOrArgs( String name, ArgResults argResults, Map<String, String> env, ) { final String envName = fromArgToEnvName(name); if (env[envName] != null && env[envName] != '') { return env[envName]!.split(','); } final List<String>? argValues = argResults[name] as List<String>?; if (argValues != null) { return argValues; } throw ConductorException('Expected either the CLI arg --$name or the environment variable $envName ' 'to be provided!'); } /// Translate CLI arg names to env variable names. /// /// For example, 'state-file' -> 'STATE_FILE'. String fromArgToEnvName(String argName) { return argName.toUpperCase().replaceAll(r'-', r'_'); } /// Return a web link for the user to open a new PR. /// /// Includes PR title and body via query params. String getNewPrLink({ required String userName, required String repoName, required pb.ConductorState state, }) { assert(state.releaseChannel.isNotEmpty); assert(state.releaseVersion.isNotEmpty); late final String candidateBranch; late final String workingBranch; late final String repoLabel; switch (repoName) { case 'flutter': candidateBranch = state.framework.candidateBranch; workingBranch = state.framework.workingBranch; repoLabel = 'Framework'; case 'engine': candidateBranch = state.engine.candidateBranch; workingBranch = state.engine.workingBranch; repoLabel = 'Engine'; default: throw ConductorException('Expected repoName to be one of flutter or engine but got $repoName.'); } assert(candidateBranch.isNotEmpty); assert(workingBranch.isNotEmpty); final String title = '[flutter_releases] Flutter ${state.releaseChannel} ' '${state.releaseVersion} $repoLabel Cherrypicks'; final StringBuffer body = StringBuffer(); body.write(''' # Flutter ${state.releaseChannel} ${state.releaseVersion} $repoLabel ## Scheduled Cherrypicks '''); if (repoName == 'engine') { if (state.engine.dartRevision.isNotEmpty) { // shorten hashes to make final link manageable // prefix with github org/repo so GitHub will auto-generate a hyperlink body.writeln('- Roll dart revision: dart-lang/sdk@${state.engine.dartRevision.substring(0, 9)}'); } for (final pb.Cherrypick cp in state.engine.cherrypicks) { // Only list commits that map to a commit that exists upstream. if (cp.trunkRevision.isNotEmpty) { body.writeln('- commit: flutter/engine@${cp.trunkRevision.substring(0, 9)}'); } } } else { for (final pb.Cherrypick cp in state.framework.cherrypicks) { // Only list commits that map to a commit that exists upstream. if (cp.trunkRevision.isNotEmpty) { body.writeln('- commit: ${cp.trunkRevision.substring(0, 9)}'); } } } return 'https://github.com/flutter/$repoName/compare/' '$candidateBranch...$userName:$workingBranch?' 'expand=1' '&title=${Uri.encodeQueryComponent(title)}' '&body=${Uri.encodeQueryComponent(body.toString())}'; }
flutter/dev/conductor/core/lib/src/globals.dart/0
{ "file_path": "flutter/dev/conductor/core/lib/src/globals.dart", "repo_id": "flutter", "token_count": 2213 }
508
// 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 'globals.dart' show ConductorException, releaseCandidateBranchRegex; import 'proto/conductor_state.pbenum.dart'; /// Possible string formats that `flutter --version` can return. enum VersionType { /// A stable flutter release. /// /// Example: '1.2.3' stable, /// A pre-stable flutter release. /// /// Example: '1.2.3-4.5.pre' development, /// A master channel flutter version. /// /// Example: '1.2.3-4.0.pre.10' /// /// The last number is the number of commits past the last tagged version. latest, /// A master channel flutter version from git describe. /// /// Example: '1.2.3-4.0.pre-10-gabc123'. /// Example: '1.2.3-10-gabc123'. gitDescribe, } final Map<VersionType, RegExp> versionPatterns = <VersionType, RegExp>{ VersionType.stable: RegExp(r'^(\d+)\.(\d+)\.(\d+)$'), VersionType.development: RegExp(r'^(\d+)\.(\d+)\.(\d+)-(\d+)\.(\d+)\.pre$'), VersionType.latest: RegExp(r'^(\d+)\.(\d+)\.(\d+)-(\d+)\.(\d+)\.pre\.(\d+)$'), VersionType.gitDescribe: RegExp(r'^(\d+)\.(\d+)\.(\d+)-((\d+)\.(\d+)\.pre-)?(\d+)-g[a-f0-9]+$'), }; class Version { Version({ required this.x, required this.y, required this.z, this.m, this.n, this.commits, required this.type, }) { switch (type) { case VersionType.stable: assert(m == null); assert(n == null); assert(commits == null); case VersionType.development: assert(m != null); assert(n != null); assert(commits == null); case VersionType.latest: assert(m != null); assert(n != null); assert(commits != null); case VersionType.gitDescribe: assert(commits != null); } } /// Create a new [Version] from a version string. /// /// It is expected that [versionString] will be generated by /// `flutter --version` and match one of `stablePattern`, `developmentPattern` /// and `latestPattern`. factory Version.fromString(String versionString) { versionString = versionString.trim(); // stable tag Match? match = versionPatterns[VersionType.stable]!.firstMatch(versionString); if (match != null) { // parse stable final List<int> parts = match .groups(<int>[1, 2, 3]) .map((String? s) => int.parse(s!)) .toList(); return Version( x: parts[0], y: parts[1], z: parts[2], type: VersionType.stable, ); } // development tag match = versionPatterns[VersionType.development]!.firstMatch(versionString); if (match != null) { // parse development final List<int> parts = match.groups(<int>[1, 2, 3, 4, 5]).map((String? s) => int.parse(s!)).toList(); return Version( x: parts[0], y: parts[1], z: parts[2], m: parts[3], n: parts[4], type: VersionType.development, ); } // latest tag match = versionPatterns[VersionType.latest]!.firstMatch(versionString); if (match != null) { // parse latest final List<int> parts = match.groups( <int>[1, 2, 3, 4, 5, 6], ).map( (String? s) => int.parse(s!), ).toList(); return Version( x: parts[0], y: parts[1], z: parts[2], m: parts[3], n: parts[4], commits: parts[5], type: VersionType.latest, ); } match = versionPatterns[VersionType.gitDescribe]!.firstMatch(versionString); if (match != null) { // parse latest final int x = int.parse(match.group(1)!); final int y = int.parse(match.group(2)!); final int z = int.parse(match.group(3)!); final int? m = int.tryParse(match.group(5) ?? ''); final int? n = int.tryParse(match.group(6) ?? ''); final int commits = int.parse(match.group(7)!); return Version( x: x, y: y, z: z, m: m, n: n, commits: commits, type: VersionType.gitDescribe, ); } throw Exception('${versionString.trim()} cannot be parsed'); } // Returns a new version with the given [increment] part incremented. // NOTE new version must be of same type as previousVersion. factory Version.increment( Version previousVersion, String increment, { VersionType? nextVersionType, }) { final int nextX = previousVersion.x; int nextY = previousVersion.y; int nextZ = previousVersion.z; int? nextM = previousVersion.m; int? nextN = previousVersion.n; nextVersionType ??= switch (previousVersion.type) { VersionType.stable => VersionType.stable, VersionType.latest || VersionType.gitDescribe || VersionType.development => VersionType.development, }; switch (increment) { case 'x': // This was probably a mistake. throw Exception('Incrementing x is not supported by this tool.'); case 'y': // Dev release following a beta release. nextY += 1; nextZ = 0; if (previousVersion.type != VersionType.stable) { nextM = 0; nextN = 0; } case 'z': // Hotfix to stable release. assert(previousVersion.type == VersionType.stable); nextZ += 1; case 'm': assert(false, "Do not increment 'm' via Version.increment, use instead Version.fromCandidateBranch()"); case 'n': // Hotfix to internal roll. nextN = nextN! + 1; default: throw Exception('Unknown increment level $increment.'); } return Version( x: nextX, y: nextY, z: nextZ, m: nextM, n: nextN, type: nextVersionType, ); } factory Version.fromCandidateBranch(String branchName) { // Regular dev release. final RegExp pattern = RegExp(r'flutter-(\d+)\.(\d+)-candidate.(\d+)'); final RegExpMatch? match = pattern.firstMatch(branchName); late final int x; late final int y; late final int m; try { x = int.parse(match!.group(1)!); y = int.parse(match.group(2)!); m = int.parse(match.group(3)!); } on Exception { throw ConductorException('branch named $branchName not recognized as a valid candidate branch'); } return Version( type: VersionType.development, x: x, y: y, z: 0, m: m, n: 0, ); } /// Major version. final int x; /// Zero-indexed count of beta releases after a major release. final int y; /// Number of hotfix releases after a stable release. /// /// For non-stable releases, this will be 0. final int z; /// Zero-indexed count of dev releases after a beta release. /// /// For stable releases, this will be null. final int? m; /// Number of hotfixes required to make a dev release. /// /// For stable releases, this will be null. final int? n; /// Number of commits past last tagged dev release. final int? commits; final VersionType type; /// Validate that the parsed version is valid. /// /// Will throw a [ConductorException] if the version is not possible given the /// [candidateBranch] and [incrementLetter]. void ensureValid(String candidateBranch, ReleaseType releaseType) { final RegExpMatch? branchMatch = releaseCandidateBranchRegex.firstMatch(candidateBranch); if (branchMatch == null) { throw ConductorException( 'Candidate branch $candidateBranch does not match the pattern ' '${releaseCandidateBranchRegex.pattern}', ); } // These groups are required in the pattern, so these match groups should // not be null final String branchX = branchMatch.group(1)!; if (x != int.tryParse(branchX)) { throw ConductorException( 'Parsed version $this has a different x value than candidate ' 'branch $candidateBranch', ); } final String branchY = branchMatch.group(2)!; if (y != int.tryParse(branchY)) { throw ConductorException( 'Parsed version $this has a different y value than candidate ' 'branch $candidateBranch', ); } // stable type versions don't have an m field set if (type != VersionType.stable && releaseType != ReleaseType.STABLE_HOTFIX && releaseType != ReleaseType.STABLE_INITIAL) { final String branchM = branchMatch.group(3)!; if (m != int.tryParse(branchM)) { throw ConductorException( 'Parsed version $this has a different m value than candidate ' 'branch $candidateBranch with type $type', ); } } } @override String toString() { return switch (type) { VersionType.stable => '$x.$y.$z', VersionType.development => '$x.$y.$z-$m.$n.pre', VersionType.latest => '$x.$y.$z-$m.$n.pre.$commits', VersionType.gitDescribe => '$x.$y.$z-$m.$n.pre.$commits', }; } }
flutter/dev/conductor/core/lib/src/version.dart/0
{ "file_path": "flutter/dev/conductor/core/lib/src/version.dart", "repo_id": "flutter", "token_count": 3649 }
509
// 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/apk_utils.dart'; 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 { try { await runPluginProjectTest((FlutterPluginProject pluginProject) async { section('check main plugin file exists'); final File pluginMainKotlinFile = File( path.join( pluginProject.rootPath, 'android', 'src', 'main', 'kotlin', path.join( 'com', 'example', 'aaa', 'AaaPlugin.kt', ), ), ); if (!pluginMainKotlinFile.existsSync()) { throw TaskResult.failure("Expected ${pluginMainKotlinFile.path} to exist, but it doesn't"); } section('add java 8 feature'); pluginMainKotlinFile.writeAsStringSync(r''' package com.example.aaa import android.util.Log import androidx.annotation.NonNull import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler import io.flutter.plugin.common.MethodChannel.Result import java.util.HashMap /** AaaPlugin */ class AaaPlugin: FlutterPlugin, MethodCallHandler { init { val map: HashMap<String, String> = HashMap<String, String>() // getOrDefault is a JAVA8 feature. Log.d("AaaPlugin", map.getOrDefault("foo", "baz")) } /// The MethodChannel that will the communication between Flutter and native Android /// /// This local reference serves to register the plugin with the Flutter Engine and unregister it /// when the Flutter Engine is detached from the Activity private lateinit var channel : MethodChannel override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { channel = MethodChannel(flutterPluginBinding.binaryMessenger, "aaa") channel.setMethodCallHandler(this) } override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { if (call.method == "getPlatformVersion") { result.success("Android ${android.os.Build.VERSION.RELEASE}") } else { result.notImplemented() } } override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { channel.setMethodCallHandler(null) } } '''); section('Compiles'); await inDirectory(pluginProject.exampleAndroidPath, () { return flutter( 'build', options: <String>[ 'apk', '--debug', '--target-platform=android-arm', ], ); }); }); return TaskResult.success(null); } on TaskResult catch (taskResult) { return taskResult; } catch (e) { return TaskResult.failure(e.toString()); } }); }
flutter/dev/devicelab/bin/tasks/gradle_java8_compile_test.dart/0
{ "file_path": "flutter/dev/devicelab/bin/tasks/gradle_java8_compile_test.dart", "repo_id": "flutter", "token_count": 1278 }
510
// 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; /// Tests that the Flutter plugin template works. Use `pod lib lint` /// to confirm the plugin module can be imported into an app. Future<void> main() async { await task(() async { final Directory tempDir = Directory.systemTemp.createTempSync('flutter_plugin_test.'); try { section('Lint integration_test'); await inDirectory(tempDir, () async { // Update pod repo. await exec( 'pod', <String>['repo', 'update'], ); // Relative to this script. final String flutterRoot = path.dirname(path.dirname(path.dirname(path.dirname(path.dirname(path.fromUri(Platform.script)))))); print('Flutter root at $flutterRoot'); final String integrationTestPackage = path.join(flutterRoot, 'packages', 'integration_test'); final String iosintegrationTestPodspec = path.join(integrationTestPackage, 'ios', 'integration_test.podspec'); await exec( 'pod', <String>[ 'lib', 'lint', iosintegrationTestPodspec, '--use-libraries', '--verbose', ], ); final String macosintegrationTestPodspec = path.join(integrationTestPackage, 'integration_test_macos', 'macos', 'integration_test_macos.podspec'); await _tryMacOSLint( macosintegrationTestPodspec, <String>[ '--verbose', ], ); }); section('Create Objective-C plugin'); const String objcPluginName = 'test_plugin_objc'; await inDirectory(tempDir, () async { await flutter( 'create', options: <String>[ '--org', 'io.flutter.devicelab', '--template=plugin', '--platforms=ios,android', '--ios-language=objc', objcPluginName, ], ); }); section('Lint Objective-C iOS podspec plugin as framework'); final String objcPluginPath = path.join(tempDir.path, objcPluginName); final String objcPodspecPath = path.join(objcPluginPath, 'ios', '$objcPluginName.podspec'); await inDirectory(tempDir, () async { await exec( 'pod', <String>[ 'lib', 'lint', objcPodspecPath, '--allow-warnings', '--verbose', ], ); }); section('Lint Objective-C iOS podspec plugin as library'); await inDirectory(tempDir, () async { await exec( 'pod', <String>[ 'lib', 'lint', objcPodspecPath, '--allow-warnings', '--use-libraries', '--verbose', ], ); }); section('Create Swift plugin'); const String swiftPluginName = 'test_plugin_swift'; await inDirectory(tempDir, () async { await flutter( 'create', options: <String>[ '--org', 'io.flutter.devicelab', '--template=plugin', '--platforms=ios,macos', '--ios-language=swift', swiftPluginName, ], ); }); section('Lint Swift iOS podspec plugin as framework'); final String swiftPluginPath = path.join(tempDir.path, swiftPluginName); final String swiftPodspecPath = path.join(swiftPluginPath, 'ios', '$swiftPluginName.podspec'); await inDirectory(tempDir, () async { await exec( 'pod', <String>[ 'lib', 'lint', swiftPodspecPath, '--allow-warnings', '--verbose', ], ); }); section('Lint Swift iOS podspec plugin as library'); await inDirectory(tempDir, () async { await exec( 'pod', <String>[ 'lib', 'lint', swiftPodspecPath, '--allow-warnings', '--use-libraries', '--verbose', ], ); }); section('Lint Swift macOS podspec plugin as framework'); final String macOSPodspecPath = path.join(swiftPluginPath, 'macos', '$swiftPluginName.podspec'); await inDirectory(tempDir, () async { await _tryMacOSLint( macOSPodspecPath, <String>[ '--allow-warnings', '--verbose', ], ); }); section('Lint Swift macOS podspec plugin as library'); await inDirectory(tempDir, () async { await _tryMacOSLint( macOSPodspecPath, <String>[ '--allow-warnings', '--use-libraries', '--verbose', ], ); }); section('Create Objective-C application'); const String objcAppName = 'test_app_objc'; await inDirectory(tempDir, () async { await flutter( 'create', options: <String>[ '--org', 'io.flutter.devicelab', '--platforms=ios', '--ios-language=objc', objcAppName, ], ); }); section('Build Objective-C application with Swift and Objective-C plugins as libraries'); final String objcAppPath = path.join(tempDir.path, objcAppName); final File objcPubspec = File(path.join(objcAppPath, 'pubspec.yaml')); String pubspecContent = objcPubspec.readAsStringSync(); // Add (randomly selected) first-party plugins that support iOS and macOS. // Add the new plugins we just made. pubspecContent = pubspecContent.replaceFirst( '\ndependencies:\n', '\ndependencies:\n $objcPluginName:\n path: $objcPluginPath\n $swiftPluginName:\n path: $swiftPluginPath\n url_launcher: 6.0.16\n url_launcher_macos:\n', ); objcPubspec.writeAsStringSync(pubspecContent, flush: true); await inDirectory(objcAppPath, () async { await flutter( 'build', options: <String>[ 'ios', '--no-codesign', ], // TODO(jmagman): Make Objective-C applications handle Swift libraries https://github.com/flutter/flutter/issues/16049 canFail: true ); }); final File objcPodfile = File(path.join(objcAppPath, 'ios', 'Podfile')); String objcPodfileContent = objcPodfile.readAsStringSync(); if (objcPodfileContent.contains('use_frameworks!')) { return TaskResult.failure('Expected default Objective-C Podfile to not contain use_frameworks'); } _validateIosPodfile(objcAppPath); section('Build Objective-C application with Swift and Objective-C plugins as frameworks'); objcPodfileContent = 'use_frameworks!\n$objcPodfileContent'; objcPodfile.writeAsStringSync(objcPodfileContent, flush: true); await inDirectory(objcAppPath, () async { await flutter( 'build', options: <String>[ 'ios', '--no-codesign', ], ); }); section('Create Swift application'); const String swiftAppName = 'test_app_swift'; await inDirectory(tempDir, () async { await flutter( 'create', options: <String>[ '--org', 'io.flutter.devicelab', '--platforms=ios,macos', '--ios-language=swift', swiftAppName, ], ); }); section('Build Swift iOS application with Swift and Objective-C plugins as frameworks'); final String swiftAppPath = path.join(tempDir.path, swiftAppName); final File swiftPubspec = File(path.join(swiftAppPath, 'pubspec.yaml')); swiftPubspec.writeAsStringSync(pubspecContent, flush: true); await inDirectory(swiftAppPath, () async { await flutter( 'build', options: <String>[ 'ios', '--no-codesign', ], ); }); final File swiftPodfile = File(path.join(swiftAppPath, 'ios', 'Podfile')); String swiftPodfileContent = swiftPodfile.readAsStringSync(); if (!swiftPodfileContent.contains('use_frameworks!')) { return TaskResult.failure('Expected default Swift Podfile to contain use_frameworks'); } section('Build Swift iOS application with Swift and Objective-C plugins as libraries'); swiftPodfileContent = swiftPodfileContent.replaceAll('use_frameworks!', ''); swiftPodfile.writeAsStringSync(swiftPodfileContent, flush: true); await inDirectory(swiftAppPath, () async { await flutter( 'build', options: <String>[ 'ios', '--no-codesign', ], ); }); _validateIosPodfile(swiftAppPath); section('Build Swift macOS application with plugins as frameworks'); await inDirectory(swiftAppPath, () async { await flutter( 'build', options: <String>[ 'macos', ], ); }); final File macOSPodfile = File(path.join(swiftAppPath, 'macos', 'Podfile')); String macosPodfileContent = macOSPodfile.readAsStringSync(); if (!macosPodfileContent.contains('use_frameworks!')) { return TaskResult.failure('Expected default Swift Podfile to contain use_frameworks'); } _validateMacOSPodfile(swiftAppPath); section('Build Swift macOS application with plugins as libraries'); macosPodfileContent = macosPodfileContent.replaceAll('use_frameworks!', ''); macOSPodfile.writeAsStringSync(macosPodfileContent, flush: true); await inDirectory(swiftAppPath, () async { await flutter( 'build', options: <String>[ 'macos', ], ); }); _validateMacOSPodfile(swiftAppPath); section('Remove iOS support from plugin'); Directory(path.join(objcPluginPath, 'ios')).deleteSync(recursive: true); const String iosPlatformMap = ''' ios: pluginClass: TestPluginObjcPlugin'''; final File pluginPubspec = File(path.join(objcPluginPath, 'pubspec.yaml')); String pluginPubspecContent = pluginPubspec.readAsStringSync(); if (!pluginPubspecContent.contains(iosPlatformMap)) { return TaskResult.failure('Plugin pubspec.yaml missing iOS platform map'); } pluginPubspecContent = pluginPubspecContent.replaceFirst(iosPlatformMap, ''); pluginPubspec.writeAsStringSync(pluginPubspecContent, flush: true); await inDirectory(swiftAppPath, () async { await flutter('clean'); await flutter( 'build', options: <String>[ 'ios', '--no-codesign', ], ); }); section('Validate plugin without iOS platform'); final File podfileLockFile = File(path.join(swiftAppPath, 'ios', 'Podfile.lock')); final String podfileLockOutput = podfileLockFile.readAsStringSync(); if (!podfileLockOutput.contains(':path: ".symlinks/plugins/url_launcher_ios/ios"') || !podfileLockOutput.contains(':path: Flutter') // test_plugin_objc no longer supports iOS, shouldn't be present. || podfileLockOutput.contains(':path: ".symlinks/plugins/test_plugin_objc/ios"') || !podfileLockOutput.contains(':path: ".symlinks/plugins/test_plugin_swift/ios"')) { print(podfileLockOutput); return TaskResult.failure('Podfile.lock does not contain expected pods'); } final String pluginSymlinks = path.join( swiftAppPath, 'ios', '.symlinks', 'plugins', ); checkDirectoryExists(path.join( pluginSymlinks, 'url_launcher_ios', 'ios', )); checkDirectoryExists(path.join( pluginSymlinks, 'test_plugin_swift', 'ios', )); // test_plugin_objc no longer supports iOS, shouldn't exist! checkDirectoryNotExists(path.join( pluginSymlinks, 'test_plugin_objc', )); return TaskResult.success(null); } catch (e) { return TaskResult.failure(e.toString()); } finally { rmTree(tempDir); } }); } void _validateIosPodfile(String appPath) { section('Validate iOS Podfile'); final File podfileLockFile = File(path.join(appPath, 'ios', 'Podfile.lock')); final String podfileLockOutput = podfileLockFile.readAsStringSync(); if (!podfileLockOutput.contains(':path: ".symlinks/plugins/url_launcher_ios/ios"') || !podfileLockOutput.contains(':path: Flutter') || !podfileLockOutput.contains(':path: ".symlinks/plugins/test_plugin_objc/ios"') || !podfileLockOutput.contains(':path: ".symlinks/plugins/test_plugin_swift/ios"') || podfileLockOutput.contains('url_launcher_macos')) { print(podfileLockOutput); throw TaskResult.failure('iOS Podfile.lock does not contain expected pods'); } checkDirectoryNotExists(path.join( appPath, 'ios', 'Flutter', 'Flutter.framework', )); checkFileExists(path.join( appPath, 'ios', 'Flutter', 'Flutter.podspec', )); final String pluginSymlinks = path.join( appPath, 'ios', '.symlinks', 'plugins', ); checkDirectoryExists(path.join( pluginSymlinks, 'url_launcher_ios', 'ios', )); checkDirectoryNotExists(path.join( pluginSymlinks, 'url_launcher_macos', )); checkDirectoryExists(path.join( pluginSymlinks, 'test_plugin_objc', 'ios', )); checkDirectoryExists(path.join( pluginSymlinks, 'test_plugin_swift', 'ios', )); // Make sure no Xcode build settings are leaking derived data/build directory into the ios directory. checkDirectoryNotExists(path.join( appPath, 'ios', 'build', )); } void _validateMacOSPodfile(String appPath) { section('Validate macOS Podfile'); final File podfileLockFile = File(path.join(appPath, 'macos', 'Podfile.lock')); final String podfileLockOutput = podfileLockFile.readAsStringSync(); if (!podfileLockOutput.contains(':path: Flutter/ephemeral\n') || !podfileLockOutput.contains(':path: Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos') || !podfileLockOutput.contains(':path: Flutter/ephemeral/.symlinks/plugins/test_plugin_swift/macos') || podfileLockOutput.contains('url_launcher_ios/')) { print(podfileLockOutput); throw TaskResult.failure('macOS Podfile.lock does not contain expected pods'); } checkFileExists(path.join( appPath, 'macos', 'Flutter', 'ephemeral', 'FlutterMacOS.podspec', )); final String pluginSymlinks = path.join( appPath, 'macos', 'Flutter', 'ephemeral', '.symlinks', 'plugins', ); checkDirectoryExists(path.join( pluginSymlinks, 'url_launcher_macos', 'macos', )); checkDirectoryNotExists(path.join( pluginSymlinks, 'url_launcher_ios', )); checkDirectoryExists(path.join( pluginSymlinks, 'test_plugin_swift', 'macos', )); } Future<void> _tryMacOSLint( String podspecPath, List<String> extraArguments, ) async { await eval( 'pod', <String>[ 'lib', 'lint', podspecPath, ...extraArguments, ], ); }
flutter/dev/devicelab/bin/tasks/plugin_lint_mac.dart/0
{ "file_path": "flutter/dev/devicelab/bin/tasks/plugin_lint_mac.dart", "repo_id": "flutter", "token_count": 6828 }
511
// 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: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; import 'package:pub_semver/pub_semver.dart'; import 'package:pubspec_parse/pubspec_parse.dart'; // the numbers below are prime, so that the totals don't seem round. :-) const double todoCost = 1009.0; // about two average SWE days, in dollars const double ignoreCost = 2003.0; // four average SWE days, in dollars const double pythonCost = 3001.0; // six average SWE days, in dollars const double skipCost = 2473.0; // 20 hours: 5 to fix the issue we're ignoring, 15 to fix the bugs we missed because the test was off const double ignoreForFileCost = 2477.0; // similar thinking as skipCost const double asDynamicCost = 2011.0; // a few days to refactor the code. const double deprecationCost = 233.0; // a few hours to remove the old code. const double legacyDeprecationCost = 9973.0; // a couple of weeks. const double packageNullSafetyMigrationCost = 2017.0; // a few days to migrate package. const double fileNullSafetyMigrationCost = 257.0; // a few hours to migrate file. final RegExp todoPattern = RegExp(r'(?://|#) *TODO'); final RegExp ignorePattern = RegExp(r'// *ignore:'); final RegExp ignoreForFilePattern = RegExp(r'// *ignore_for_file:'); final RegExp asDynamicPattern = RegExp(r'\bas dynamic\b'); final RegExp deprecationPattern = RegExp(r'^ *@[dD]eprecated'); const Pattern globalsPattern = 'globals.'; const String legacyDeprecationPattern = '// flutter_ignore: deprecation_syntax, https'; final RegExp dartVersionPattern = RegExp(r'// *@dart *= *(\d+).(\d+)'); final Version firstNullSafeDartVersion = Version(2, 12, 0); Future<double> findCostsForFile(File file) async { if (path.extension(file.path) == '.py') { return pythonCost; } if (path.extension(file.path) != '.dart' && path.extension(file.path) != '.yaml' && path.extension(file.path) != '.sh') { return 0.0; } final bool isTest = file.path.endsWith('_test.dart'); final bool isDart = file.path.endsWith('.dart'); double total = 0.0; for (final String line in await file.readAsLines()) { if (line.contains(todoPattern)) { total += todoCost; } if (line.contains(ignorePattern)) { total += ignoreCost; } if (line.contains(ignoreForFilePattern)) { total += ignoreForFileCost; } if (!isTest && line.contains(asDynamicPattern)) { total += asDynamicCost; } if (line.contains(deprecationPattern)) { total += deprecationCost; } if (line.contains(legacyDeprecationPattern)) { total += legacyDeprecationCost; } if (isTest && line.contains('skip:') && !line.contains('[intended]')) { total += skipCost; } if (isDart && isOptingOutOfNullSafety(line)) { total += fileNullSafetyMigrationCost; } } if (path.basename(file.path) == 'pubspec.yaml' && !packageIsNullSafe(file)) { total += packageNullSafetyMigrationCost; } return total; } bool isOptingOutOfNullSafety(String line) { final RegExpMatch? match = dartVersionPattern.firstMatch(line); if (match == null) { return false; } assert(match.groupCount == 2); return Version(int.parse(match.group(1)!), int.parse(match.group(2)!), 0) < firstNullSafeDartVersion; } bool packageIsNullSafe(File file) { assert(path.basename(file.path) == 'pubspec.yaml'); final Pubspec pubspec = Pubspec.parse(file.readAsStringSync()); final VersionConstraint? constraint = pubspec.environment == null ? null : pubspec.environment!['sdk']; final bool hasConstraint = constraint != null && !constraint.isAny && !constraint.isEmpty; return hasConstraint && constraint is VersionRange && constraint.min != null && Version(constraint.min!.major, constraint.min!.minor, 0) >= firstNullSafeDartVersion; } Future<int> findGlobalsForFile(File file) async { if (path.extension(file.path) != '.dart') { return 0; } int total = 0; for (final String line in await file.readAsLines()) { if (line.contains(globalsPattern)) { total += 1; } } return total; } Future<double> findCostsForRepo() async { final Process git = await startProcess( 'git', <String>['ls-files', '--full-name', flutterDirectory.path], workingDirectory: flutterDirectory.path, ); double total = 0.0; await for (final String entry in git.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter())) { total += await findCostsForFile(File(path.join(flutterDirectory.path, entry))); } final int gitExitCode = await git.exitCode; if (gitExitCode != 0) { throw Exception('git exit with unexpected error code $gitExitCode'); } return total; } Future<int> findGlobalsForTool() async { final Process git = await startProcess( 'git', <String>['ls-files', '--full-name', path.join(flutterDirectory.path, 'packages', 'flutter_tools')], workingDirectory: flutterDirectory.path, ); int total = 0; await for (final String entry in git.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter())) { total += await findGlobalsForFile(File(path.join(flutterDirectory.path, entry))); } final int gitExitCode = await git.exitCode; if (gitExitCode != 0) { throw Exception('git exit with unexpected error code $gitExitCode'); } return total; } Future<int> countDependencies() async { final List<String> lines = (await evalFlutter( 'update-packages', options: <String>['--transitive-closure'], )).split('\n'); final int count = lines.where((String line) => line.contains('->')).length; if (count < 2) { throw Exception('"flutter update-packages --transitive-closure" returned bogus output:\n${lines.join("\n")}'); } return count; } Future<int> countConsumerDependencies() async { final List<String> lines = (await evalFlutter( 'update-packages', options: <String>['--transitive-closure', '--consumer-only'], )).split('\n'); final int count = lines.where((String line) => line.contains('->')).length; if (count < 2) { throw Exception('"flutter update-packages --transitive-closure" returned bogus output:\n${lines.join("\n")}'); } return count; } const String _kCostBenchmarkKey = 'technical_debt_in_dollars'; const String _kNumberOfDependenciesKey = 'dependencies_count'; const String _kNumberOfConsumerDependenciesKey = 'consumer_dependencies_count'; const String _kNumberOfFlutterToolGlobals = 'flutter_tool_globals_count'; Future<void> main() async { await task(() async { return TaskResult.success( <String, dynamic>{ _kCostBenchmarkKey: await findCostsForRepo(), _kNumberOfDependenciesKey: await countDependencies(), _kNumberOfConsumerDependenciesKey: await countConsumerDependencies(), _kNumberOfFlutterToolGlobals: await findGlobalsForTool(), }, benchmarkScoreKeys: <String>[ _kCostBenchmarkKey, _kNumberOfDependenciesKey, _kNumberOfConsumerDependenciesKey, _kNumberOfFlutterToolGlobals, ], ); }); }
flutter/dev/devicelab/bin/tasks/technical_debt__cost.dart/0
{ "file_path": "flutter/dev/devicelab/bin/tasks/technical_debt__cost.dart", "repo_id": "flutter", "token_count": 2570 }
512
// 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 '../framework/runner.dart'; class TestCommand extends Command<void> { TestCommand() { argParser.addOption('task', abbr: 't', help: 'The name of a task listed under bin/tasks.\n' ' Example: complex_layout__start_up.\n'); argParser.addMultiOption('task-args', help: 'List of arguments to pass to the task.\n' 'For example, "--task-args build" is passed as "bin/task/task.dart --build"'); argParser.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.', ); argParser.addFlag( 'exit', help: 'Exit on the first test failure. Currently flakes are intentionally (though ' 'incorrectly) not considered to be failures.', ); argParser.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.', ); argParser.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).', ); argParser.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).', ); argParser.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.', ); argParser.addOption('luci-builder', help: '[Flutter infrastructure] Name of the LUCI builder being run on.'); argParser.addOption('results-file', help: '[Flutter infrastructure] File path for test results. If passed with\n' 'task, will write test results to the file.'); argParser.addFlag( 'silent', help: 'Suppresses standard output and only print standard error output.', ); argParser.addFlag( 'use-emulator', help: 'Use an emulator instead of a device to run tests.' ); } @override String get name => 'test'; @override String get description => 'Run Flutter DeviceLab test'; @override Future<void> run() async { final List<String> taskArgsRaw = argResults!['task-args'] as List<String>; // Prepend '--' to convert args to options when passed to task final List<String> taskArgs = taskArgsRaw.map((String taskArg) => '--$taskArg').toList(); print(taskArgs); await runTasks( <String>[argResults!['task'] as String], deviceId: argResults!['device-id'] as String?, gitBranch: argResults!['git-branch'] as String?, localEngine: argResults!['local-engine'] as String?, localEngineHost: argResults!['local-engine-host'] as String?, localEngineSrcPath: argResults!['local-engine-src-path'] as String?, luciBuilder: argResults!['luci-builder'] as String?, resultsPath: argResults!['results-file'] as String?, silent: (argResults!['silent'] as bool?) ?? false, useEmulator: (argResults!['use-emulator'] as bool?) ?? false, taskArgs: taskArgs, exitOnFirstTestFailure: argResults!['exit'] as bool, ); } }
flutter/dev/devicelab/lib/command/test.dart/0
{ "file_path": "flutter/dev/devicelab/lib/command/test.dart", "repo_id": "flutter", "token_count": 1624 }
513
// 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'; /// Reads through the print commands from [process] waiting for the magic phase /// that contains microbenchmarks results as defined in /// `dev/benchmarks/microbenchmarks/lib/common.dart`. Future<Map<String, double>> readJsonResults(Process process) { // IMPORTANT: keep these values in sync with dev/benchmarks/microbenchmarks/lib/common.dart const String jsonStart = '================ RESULTS ================'; const String jsonEnd = '================ FORMATTED =============='; const String jsonPrefix = ':::JSON:::'; bool jsonStarted = false; final StringBuffer jsonBuf = StringBuffer(); final Completer<Map<String, double>> completer = Completer<Map<String, double>>(); final StreamSubscription<String> stderrSub = process.stderr .transform<String>(const Utf8Decoder()) .transform<String>(const LineSplitter()) .listen((String line) { stderr.writeln('[STDERR] $line'); }); bool processWasKilledIntentionally = false; bool resultsHaveBeenParsed = false; final StreamSubscription<String> stdoutSub = process.stdout .transform<String>(const Utf8Decoder()) .transform<String>(const LineSplitter()) .listen((String line) async { print('[STDOUT] $line'); if (line.contains(jsonStart)) { jsonStarted = true; return; } if (jsonStarted && line.contains(jsonEnd)) { final String jsonOutput = jsonBuf.toString(); // If we end up here and have already parsed the results, it suggests that // we have received output from another test because our `flutter run` // process did not terminate correctly. // https://github.com/flutter/flutter/issues/19096#issuecomment-402756549 if (resultsHaveBeenParsed) { throw 'Additional JSON was received after results has already been ' 'processed. This suggests the `flutter run` process may have lived ' 'past the end of our test and collected additional output from the ' 'next test.\n\n' 'The JSON below contains all collected output, including both from ' 'the original test and what followed.\n\n' '$jsonOutput'; } jsonStarted = false; processWasKilledIntentionally = true; resultsHaveBeenParsed = true; // Sending a SIGINT/SIGTERM to the process here isn't reliable because [process] is // the shell (flutter is a shell script) and doesn't pass the signal on. // Sending a `q` is an instruction to quit using the console runner. // See https://github.com/flutter/flutter/issues/19208 process.stdin.write('q'); await process.stdin.flush(); // Give the process a couple of seconds to exit and run shutdown hooks // before sending kill signal. // TODO(fujino): https://github.com/flutter/flutter/issues/134566 await Future<void>.delayed(const Duration(seconds: 2)); // Also send a kill signal in case the `q` above didn't work. process.kill(ProcessSignal.sigint); try { completer.complete(Map<String, double>.from(json.decode(jsonOutput) as Map<String, dynamic>)); } catch (ex) { completer.completeError('Decoding JSON failed ($ex). JSON string was: $jsonOutput'); } return; } if (jsonStarted && line.contains(jsonPrefix)) { jsonBuf.writeln(line.substring(line.indexOf(jsonPrefix) + jsonPrefix.length)); } }); process.exitCode.then<void>((int code) async { await Future.wait<void>(<Future<void>>[ stdoutSub.cancel(), stderrSub.cancel(), ]); if (!processWasKilledIntentionally && code != 0) { completer.completeError('flutter run failed: exit code=$code'); } }); return completer.future; }
flutter/dev/devicelab/lib/microbenchmarks.dart/0
{ "file_path": "flutter/dev/devicelab/lib/microbenchmarks.dart", "repo_id": "flutter", "token_count": 1412 }
514
// 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' show LineSplitter, json, utf8; import 'dart:ffi' show Abi; import 'dart:io'; import 'dart:math' as math; import 'package:meta/meta.dart'; import 'package:path/path.dart' as path; import 'package:xml/xml.dart'; import '../framework/devices.dart'; import '../framework/framework.dart'; import '../framework/host_agent.dart'; import '../framework/task_result.dart'; import '../framework/utils.dart'; /// Must match flutter_driver/lib/src/common.dart. /// /// Redefined here to avoid taking a dependency on flutter_driver. String _testOutputDirectory(String testDirectory) { return Platform.environment['FLUTTER_TEST_OUTPUTS_DIR'] ?? '$testDirectory/build'; } TaskFunction createComplexLayoutScrollPerfTest({ bool measureCpuGpu = true, bool badScroll = false, bool? enableImpeller, bool forceOpenGLES = false, }) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/complex_layout', badScroll ? 'test_driver/scroll_perf_bad.dart' : 'test_driver/scroll_perf.dart', 'complex_layout_scroll_perf', measureCpuGpu: measureCpuGpu, enableImpeller: enableImpeller, forceOpenGLES: forceOpenGLES, ).run; } TaskFunction createTilesScrollPerfTest({bool? enableImpeller}) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/complex_layout', 'test_driver/scroll_perf.dart', 'tiles_scroll_perf', enableImpeller: enableImpeller, ).run; } TaskFunction createUiKitViewScrollPerfTest({bool? enableImpeller}) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/platform_views_layout', 'test_driver/uikit_view_scroll_perf.dart', 'platform_views_scroll_perf', testDriver: 'test_driver/scroll_perf_test.dart', needsFullTimeline: false, enableImpeller: enableImpeller, ).run; } TaskFunction createUiKitViewScrollPerfAdBannersTest({bool? enableImpeller}) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/platform_views_layout', 'test_driver/uikit_view_scroll_perf_ad_banners.dart', 'platform_views_scroll_perf_ad_banners', testDriver: 'test_driver/scroll_perf_ad_banners_test.dart', needsFullTimeline: false, enableImpeller: enableImpeller, ).run; } TaskFunction createUiKitViewScrollPerfNonIntersectingTest({bool? enableImpeller}) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/platform_views_layout', 'test_driver/uikit_view_scroll_perf_non_intersecting.dart', 'platform_views_scroll_perf_non_intersecting', testDriver: 'test_driver/scroll_perf_non_intersecting_test.dart', needsFullTimeline: false, enableImpeller: enableImpeller, ).run; } TaskFunction createAndroidTextureScrollPerfTest({bool? enableImpeller}) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/platform_views_layout', 'test_driver/android_view_scroll_perf.dart', 'platform_views_scroll_perf', testDriver: 'test_driver/scroll_perf_test.dart', needsFullTimeline: false, enableImpeller: enableImpeller, ).run; } TaskFunction createAndroidViewScrollPerfTest() { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/platform_views_layout_hybrid_composition', 'test_driver/android_view_scroll_perf.dart', 'platform_views_scroll_perf_hybrid_composition', testDriver: 'test_driver/scroll_perf_test.dart', ).run; } TaskFunction createHomeScrollPerfTest() { return PerfTest( '${flutterDirectory.path}/dev/integration_tests/flutter_gallery', 'test_driver/scroll_perf.dart', 'home_scroll_perf', ).run; } TaskFunction createCullOpacityPerfTest() { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'cull_opacity_perf', testDriver: 'test_driver/cull_opacity_perf_test.dart', ).run; } TaskFunction createCullOpacityPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/cull_opacity_perf_e2e.dart', ).run; } TaskFunction createCubicBezierPerfTest() { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'cubic_bezier_perf', testDriver: 'test_driver/cubic_bezier_perf_test.dart', ).run; } TaskFunction createCubicBezierPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/cubic_bezier_perf_e2e.dart', ).run; } TaskFunction createBackdropFilterPerfTest({ bool measureCpuGpu = true, bool? enableImpeller, }) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'backdrop_filter_perf', measureCpuGpu: measureCpuGpu, testDriver: 'test_driver/backdrop_filter_perf_test.dart', saveTraceFile: true, enableImpeller: enableImpeller, disablePartialRepaint: true, ).run; } TaskFunction createAnimationWithMicrotasksPerfTest({bool measureCpuGpu = true}) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'animation_with_microtasks_perf', measureCpuGpu: measureCpuGpu, testDriver: 'test_driver/animation_with_microtasks_perf_test.dart', saveTraceFile: true, ).run; } TaskFunction createBackdropFilterPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/backdrop_filter_perf_e2e.dart', ).run; } TaskFunction createPostBackdropFilterPerfTest({bool measureCpuGpu = true}) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'post_backdrop_filter_perf', measureCpuGpu: measureCpuGpu, testDriver: 'test_driver/post_backdrop_filter_perf_test.dart', saveTraceFile: true, ).run; } TaskFunction createSimpleAnimationPerfTest({ bool measureCpuGpu = true, bool? enableImpeller, }) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'simple_animation_perf', measureCpuGpu: measureCpuGpu, testDriver: 'test_driver/simple_animation_perf_test.dart', saveTraceFile: true, enableImpeller: enableImpeller, ).run; } TaskFunction createAnimatedPlaceholderPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/animated_placeholder_perf_e2e.dart', ).run; } TaskFunction createPictureCachePerfTest() { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'picture_cache_perf', testDriver: 'test_driver/picture_cache_perf_test.dart', ).run; } TaskFunction createPictureCachePerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/picture_cache_perf_e2e.dart', ).run; } TaskFunction createPictureCacheComplexityScoringPerfTest() { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'picture_cache_complexity_scoring_perf', testDriver: 'test_driver/picture_cache_complexity_scoring_perf_test.dart', ).run; } TaskFunction createOpenPayScrollPerfTest({bool measureCpuGpu = true}) { return PerfTest( openpayDirectory.path, 'test_driver/scroll_perf.dart', 'openpay_scroll_perf', measureCpuGpu: measureCpuGpu, testDriver: 'test_driver/scroll_perf_test.dart', saveTraceFile: true, ).run; } TaskFunction createFlutterGalleryStartupTest({String target = 'lib/main.dart', Map<String, String>? runEnvironment}) { return StartupTest( '${flutterDirectory.path}/dev/integration_tests/flutter_gallery', target: target, runEnvironment: runEnvironment, ).run; } TaskFunction createComplexLayoutStartupTest() { return StartupTest( '${flutterDirectory.path}/dev/benchmarks/complex_layout', ).run; } TaskFunction createFlutterGalleryCompileTest() { return CompileTest('${flutterDirectory.path}/dev/integration_tests/flutter_gallery').run; } TaskFunction createHelloWorldCompileTest() { return CompileTest('${flutterDirectory.path}/examples/hello_world', reportPackageContentSizes: true).run; } TaskFunction createWebCompileTest() { return const WebCompileTest().run; } TaskFunction createFlutterViewStartupTest() { return StartupTest( '${flutterDirectory.path}/examples/flutter_view', reportMetrics: false, ).run; } TaskFunction createPlatformViewStartupTest() { return StartupTest( '${flutterDirectory.path}/examples/platform_view', reportMetrics: false, ).run; } TaskFunction createBasicMaterialCompileTest() { return () async { const String sampleAppName = 'sample_flutter_app'; final Directory sampleDir = dir('${Directory.systemTemp.path}/$sampleAppName'); rmTree(sampleDir); await inDirectory<void>(Directory.systemTemp, () async { await flutter('create', options: <String>['--template=app', sampleAppName]); }); if (!sampleDir.existsSync()) { throw 'Failed to create default Flutter app in ${sampleDir.path}'; } return CompileTest(sampleDir.path).run(); }; } TaskFunction createTextfieldPerfTest() { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'textfield_perf', testDriver: 'test_driver/textfield_perf_test.dart', ).run; } TaskFunction createTextfieldPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/textfield_perf_e2e.dart', ).run; } TaskFunction createVeryLongPictureScrollingPerfE2ETest({required bool enableImpeller}) { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/very_long_picture_scrolling_perf_e2e.dart', enableImpeller: enableImpeller, ).run; } TaskFunction createSlidersPerfTest() { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'sliders_perf', testDriver: 'test_driver/sliders_perf_test.dart', ).run; } TaskFunction createStackSizeTest() { final String testDirectory = '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks'; const String testTarget = 'test_driver/run_app.dart'; const String testDriver = 'test_driver/stack_size_perf_test.dart'; return () { return inDirectory<TaskResult>(testDirectory, () async { final Device device = await devices.workingDevice; await device.unlock(); final String deviceId = device.deviceId; await flutter('packages', options: <String>['get']); await flutter('drive', options: <String>[ '--no-android-gradle-daemon', '-v', '--verbose-system-logs', '--profile', '-t', testTarget, '--driver', testDriver, '-d', deviceId, ]); final Map<String, dynamic> data = json.decode( file('${_testOutputDirectory(testDirectory)}/stack_size.json').readAsStringSync(), ) as Map<String, dynamic>; final Map<String, dynamic> result = <String, dynamic>{ 'stack_size_per_nesting_level': data['stack_size'], }; return TaskResult.success( result, benchmarkScoreKeys: result.keys.toList(), ); }); }; } TaskFunction createFullscreenTextfieldPerfTest() { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'fullscreen_textfield_perf', testDriver: 'test_driver/fullscreen_textfield_perf_test.dart', ).run; } TaskFunction createFullscreenTextfieldPerfE2ETest({ bool? enableImpeller, }) { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/fullscreen_textfield_perf_e2e.dart', enableImpeller: enableImpeller, ).run; } TaskFunction createClipperCachePerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/clipper_cache_perf_e2e.dart', ).run; } TaskFunction createColorFilterAndFadePerfTest() { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'color_filter_and_fade_perf', testDriver: 'test_driver/color_filter_and_fade_perf_test.dart', saveTraceFile: true, ).run; } TaskFunction createColorFilterAndFadePerfE2ETest({bool? enableImpeller}) { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/color_filter_and_fade_perf_e2e.dart', enableImpeller: enableImpeller, ).run; } TaskFunction createColorFilterCachePerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/color_filter_cache_perf_e2e.dart', ).run; } TaskFunction createColorFilterWithUnstableChildPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/color_filter_with_unstable_child_perf_e2e.dart', ).run; } TaskFunction createRasterCacheUseMemoryPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/raster_cache_use_memory_perf_e2e.dart', ).run; } TaskFunction createShaderMaskCachePerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/shader_mask_cache_perf_e2e.dart', ).run; } TaskFunction createFadingChildAnimationPerfTest() { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'fading_child_animation_perf', testDriver: 'test_driver/fading_child_animation_perf_test.dart', saveTraceFile: true, ).run; } TaskFunction createImageFilteredTransformAnimationPerfTest({ bool? enableImpeller, }) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'imagefiltered_transform_animation_perf', testDriver: 'test_driver/imagefiltered_transform_animation_perf_test.dart', saveTraceFile: true, enableImpeller: enableImpeller, ).run; } TaskFunction createsMultiWidgetConstructPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/multi_widget_construction_perf_e2e.dart', ).run; } TaskFunction createListTextLayoutPerfE2ETest({bool? enableImpeller}) { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/list_text_layout_perf_e2e.dart', enableImpeller: enableImpeller, ).run; } TaskFunction createsScrollSmoothnessPerfTest() { final String testDirectory = '${flutterDirectory.path}/dev/benchmarks/complex_layout'; const String testTarget = 'test/measure_scroll_smoothness.dart'; return () { return inDirectory<TaskResult>(testDirectory, () async { final Device device = await devices.workingDevice; await device.unlock(); final String deviceId = device.deviceId; await flutter('packages', options: <String>['get']); await flutter('drive', options: <String>[ '--no-android-gradle-daemon', '-v', '--verbose-system-logs', '--profile', '-t', testTarget, '-d', deviceId, ]); final Map<String, dynamic> data = json.decode( file('${_testOutputDirectory(testDirectory)}/scroll_smoothness_test.json').readAsStringSync(), ) as Map<String, dynamic>; final Map<String, dynamic> result = <String, dynamic>{}; void addResult(dynamic data, String suffix) { assert(data is Map<String, dynamic>); if (data is Map<String, dynamic>) { const List<String> metricKeys = <String>[ 'janky_count', 'average_abs_jerk', 'dropped_frame_count', ]; for (final String key in metricKeys) { result[key + suffix] = data[key]; } } } addResult(data['resample on with 90Hz input'], '_with_resampler_90Hz'); addResult(data['resample on with 59Hz input'], '_with_resampler_59Hz'); addResult(data['resample off with 90Hz input'], '_without_resampler_90Hz'); addResult(data['resample off with 59Hz input'], '_without_resampler_59Hz'); return TaskResult.success( result, benchmarkScoreKeys: result.keys.toList(), ); }); }; } TaskFunction createFramePolicyIntegrationTest() { final String testDirectory = '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks'; const String testTarget = 'test/frame_policy.dart'; return () { return inDirectory<TaskResult>(testDirectory, () async { final Device device = await devices.workingDevice; await device.unlock(); final String deviceId = device.deviceId; await flutter('packages', options: <String>['get']); await flutter('drive', options: <String>[ '--no-android-gradle-daemon', '-v', '--verbose-system-logs', '--profile', '-t', testTarget, '-d', deviceId, ]); final Map<String, dynamic> data = json.decode( file('${_testOutputDirectory(testDirectory)}/frame_policy_event_delay.json').readAsStringSync(), ) as Map<String, dynamic>; final Map<String, dynamic> fullLiveData = data['fullyLive'] as Map<String, dynamic>; final Map<String, dynamic> benchmarkLiveData = data['benchmarkLive'] as Map<String, dynamic>; final Map<String, dynamic> dataFormatted = <String, dynamic>{ 'average_delay_fullyLive_millis': fullLiveData['average_delay_millis'], 'average_delay_benchmarkLive_millis': benchmarkLiveData['average_delay_millis'], '90th_percentile_delay_fullyLive_millis': fullLiveData['90th_percentile_delay_millis'], '90th_percentile_delay_benchmarkLive_millis': benchmarkLiveData['90th_percentile_delay_millis'], }; return TaskResult.success( dataFormatted, benchmarkScoreKeys: dataFormatted.keys.toList(), ); }); }; } TaskFunction createOpacityPeepholeOneRectPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/opacity_peephole_one_rect_perf_e2e.dart', ).run; } TaskFunction createOpacityPeepholeColOfRowsPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/opacity_peephole_col_of_rows_perf_e2e.dart', ).run; } TaskFunction createOpacityPeepholeOpacityOfGridPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/opacity_peephole_opacity_of_grid_perf_e2e.dart', ).run; } TaskFunction createOpacityPeepholeGridOfOpacityPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/opacity_peephole_grid_of_opacity_perf_e2e.dart', ).run; } TaskFunction createOpacityPeepholeFadeTransitionTextPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/opacity_peephole_fade_transition_text_perf_e2e.dart', ).run; } TaskFunction createOpacityPeepholeGridOfAlphaSaveLayersPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/opacity_peephole_grid_of_alpha_savelayers_perf_e2e.dart', ).run; } TaskFunction createOpacityPeepholeColOfAlphaSaveLayerRowsPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/opacity_peephole_col_of_alpha_savelayer_rows_perf_e2e.dart', ).run; } TaskFunction createGradientDynamicPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/gradient_dynamic_perf_e2e.dart', ).run; } TaskFunction createGradientConsistentPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/gradient_consistent_perf_e2e.dart', ).run; } TaskFunction createGradientStaticPerfE2ETest() { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/gradient_static_perf_e2e.dart', ).run; } TaskFunction createAnimatedAdvancedBlendPerfTest({ bool? enableImpeller, bool? forceOpenGLES, }) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'animated_advanced_blend_perf', enableImpeller: enableImpeller, forceOpenGLES: forceOpenGLES, testDriver: 'test_driver/animated_advanced_blend_perf_test.dart', saveTraceFile: true, ).run; } TaskFunction createAnimatedBlurBackropFilterPerfTest({ bool? enableImpeller, bool? forceOpenGLES, }) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'animated_blur_backdrop_filter_perf', enableImpeller: enableImpeller, forceOpenGLES: forceOpenGLES, testDriver: 'test_driver/animated_blur_backdrop_filter_perf_test.dart', saveTraceFile: true, ).run; } TaskFunction createDrawPointsPerfTest({ bool? enableImpeller, }) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'draw_points_perf', enableImpeller: enableImpeller, testDriver: 'test_driver/draw_points_perf_test.dart', saveTraceFile: true, ).run; } TaskFunction createDrawAtlasPerfTest({ bool? forceOpenGLES, }) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'draw_atlas_perf', enableImpeller: true, testDriver: 'test_driver/draw_atlas_perf_test.dart', saveTraceFile: true, forceOpenGLES: forceOpenGLES, ).run; } TaskFunction createDrawVerticesPerfTest({ bool? forceOpenGLES, }) { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'draw_vertices_perf', enableImpeller: true, testDriver: 'test_driver/draw_vertices_perf_test.dart', saveTraceFile: true, forceOpenGLES: forceOpenGLES, ).run; } TaskFunction createPathTessellationStaticPerfTest() { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'tessellation_perf_static', enableImpeller: true, testDriver: 'test_driver/path_tessellation_static_perf_test.dart', saveTraceFile: true, ).run; } TaskFunction createPathTessellationDynamicPerfTest() { return PerfTest( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test_driver/run_app.dart', 'tessellation_perf_dynamic', enableImpeller: true, testDriver: 'test_driver/path_tessellation_dynamic_perf_test.dart', saveTraceFile: true, ).run; } TaskFunction createAnimatedComplexOpacityPerfE2ETest({ bool? enableImpeller, }) { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/animated_complex_opacity_perf_e2e.dart', enableImpeller: enableImpeller, ).run; } TaskFunction createAnimatedComplexImageFilteredPerfE2ETest({ bool? enableImpeller, }) { return PerfTest.e2e( '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks', 'test/animated_complex_image_filtered_perf_e2e.dart', enableImpeller: enableImpeller, ).run; } Map<String, dynamic> _average(List<Map<String, dynamic>> results, int iterations) { final Map<String, dynamic> tally = <String, dynamic>{}; for (final Map<String, dynamic> item in results) { item.forEach((String key, dynamic value) { if (tally.containsKey(key)) { tally[key] = (tally[key] as int) + (value as int); } else { tally[key] = value; } }); } tally.forEach((String key, dynamic value) { tally[key] = (value as int) ~/ iterations; }); return tally; } /// Opens the file at testDirectory + 'ios/Runner/Info.plist' /// and adds the following entry to the application. /// <FTLDisablePartialRepaint/> /// <true/> void _disablePartialRepaint(String testDirectory) { final String manifestPath = path.join( testDirectory, 'ios', 'Runner', 'Info.plist'); final File file = File(manifestPath); if (!file.existsSync()) { throw Exception('Info.plist not found at $manifestPath'); } final String xmlStr = file.readAsStringSync(); final XmlDocument xmlDoc = XmlDocument.parse(xmlStr); final List<(String, String)> keyPairs = <(String, String)>[ ('FLTDisablePartialRepaint', 'true'), ]; final XmlElement applicationNode = xmlDoc.findAllElements('dict').first; // Check if the meta-data node already exists. for (final (String key, String value) in keyPairs) { applicationNode.children.add(XmlElement(XmlName('key'), <XmlAttribute>[], <XmlNode>[ XmlText(key) ], false)); applicationNode.children.add(XmlElement(XmlName(value))); } file.writeAsStringSync(xmlDoc.toXmlString(pretty: true, indent: ' ')); } Future<void> _resetPlist(String testDirectory) async { final String manifestPath = path.join( testDirectory, 'ios', 'Runner', 'Info.plist'); final File file = File(manifestPath); if (!file.existsSync()) { throw Exception('Info.plist not found at $manifestPath'); } await exec('git', <String>['checkout', file.path]); } void _addMetadataToManifest(String testDirectory, List<(String, String)> keyPairs) { final String manifestPath = path.join( testDirectory, 'android', 'app', 'src', 'main', 'AndroidManifest.xml'); final File file = File(manifestPath); if (!file.existsSync()) { throw Exception('AndroidManifest.xml not found at $manifestPath'); } final String xmlStr = file.readAsStringSync(); final XmlDocument xmlDoc = XmlDocument.parse(xmlStr); final XmlElement applicationNode = xmlDoc.findAllElements('application').first; // Check if the meta-data node already exists. for (final (String key, String value) in keyPairs) { final Iterable<XmlElement> existingMetaData = applicationNode .findAllElements('meta-data') .where((XmlElement node) => node.getAttribute('android:name') == key); if (existingMetaData.isNotEmpty) { final XmlElement existingEntry = existingMetaData.first; existingEntry.setAttribute('android:value', value); } else { final XmlElement metaData = XmlElement( XmlName('meta-data'), <XmlAttribute>[ XmlAttribute(XmlName('android:name'), key), XmlAttribute(XmlName('android:value'), value) ], ); applicationNode.children.add(metaData); } } file.writeAsStringSync(xmlDoc.toXmlString(pretty: true, indent: ' ')); } /// Opens the file at testDirectory + 'android/app/src/main/AndroidManifest.xml' /// <meta-data /// android:name="io.flutter.embedding.android.EnableVulkanGPUTracing" /// android:value="true" /> void _addVulkanGPUTracingToManifest(String testDirectory) { final List<(String, String)> keyPairs = <(String, String)>[ ('io.flutter.embedding.android.EnableVulkanGPUTracing', 'true'), ]; _addMetadataToManifest(testDirectory, keyPairs); } /// Opens the file at testDirectory + 'android/app/src/main/AndroidManifest.xml' /// and adds the following entry to the application. /// <meta-data /// android:name="io.flutter.embedding.android.ImpellerBackend" /// android:value="opengles" /> /// <meta-data /// android:name="io.flutter.embedding.android.EnableOpenGLGPUTracing" /// android:value="true" /> void _addOpenGLESToManifest(String testDirectory) { final List<(String, String)> keyPairs = <(String, String)>[ ('io.flutter.embedding.android.ImpellerBackend', 'opengles'), ('io.flutter.embedding.android.EnableOpenGLGPUTracing', 'true'), ]; _addMetadataToManifest(testDirectory, keyPairs); } Future<void> _resetManifest(String testDirectory) async { final String manifestPath = path.join( testDirectory, 'android', 'app', 'src', 'main', 'AndroidManifest.xml'); final File file = File(manifestPath); if (!file.existsSync()) { throw Exception('AndroidManifest.xml not found at $manifestPath'); } await exec('git', <String>['checkout', file.path]); } /// Measure application startup performance. class StartupTest { const StartupTest( this.testDirectory, { this.reportMetrics = true, this.target = 'lib/main.dart', this.runEnvironment, }); final String testDirectory; final bool reportMetrics; final String target; final Map<String, String>? runEnvironment; Future<TaskResult> run() async { return inDirectory<TaskResult>(testDirectory, () async { final Device device = await devices.workingDevice; await device.unlock(); const int iterations = 5; final List<Map<String, dynamic>> results = <Map<String, dynamic>>[]; section('Building application'); String? applicationBinaryPath; switch (deviceOperatingSystem) { case DeviceOperatingSystem.android: await flutter('build', options: <String>[ 'apk', '-v', '--profile', '--target-platform=android-arm,android-arm64', '--target=$target', ]); applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk'; case DeviceOperatingSystem.androidArm: await flutter('build', options: <String>[ 'apk', '-v', '--profile', '--target-platform=android-arm', '--target=$target', ]); applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk'; case DeviceOperatingSystem.androidArm64: await flutter('build', options: <String>[ 'apk', '-v', '--profile', '--target-platform=android-arm64', '--target=$target', ]); applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk'; case DeviceOperatingSystem.fake: case DeviceOperatingSystem.fuchsia: case DeviceOperatingSystem.linux: break; case DeviceOperatingSystem.ios: case DeviceOperatingSystem.macos: await flutter('build', options: <String>[ if (deviceOperatingSystem == DeviceOperatingSystem.ios) 'ios' else 'macos', '-v', '--profile', '--target=$target', if (deviceOperatingSystem == DeviceOperatingSystem.ios) '--no-publish-port', ]); final String buildRoot = path.join(testDirectory, 'build'); applicationBinaryPath = _findDarwinAppInBuildDirectory(buildRoot); case DeviceOperatingSystem.windows: await flutter('build', options: <String>[ 'windows', '-v', '--profile', '--target=$target', ]); final String basename = path.basename(testDirectory); final String arch = Abi.current() == Abi.windowsX64 ? 'x64': 'arm64'; applicationBinaryPath = path.join( testDirectory, 'build', 'windows', arch, 'runner', 'Profile', '$basename.exe' ); } const int maxFailures = 3; int currentFailures = 0; for (int i = 0; i < iterations; i += 1) { // Startup should not take more than a few minutes. After 10 minutes, // take a screenshot to help debug. final Timer timer = Timer(const Duration(minutes: 10), () async { print('Startup not completed within 10 minutes. Taking a screenshot...'); await _flutterScreenshot( device.deviceId, 'screenshot_startup_${DateTime.now().toLocal().toIso8601String()}.png', ); }); final int result = await flutter( 'run', options: <String>[ '--no-android-gradle-daemon', '--no-publish-port', '--verbose', '--profile', '--trace-startup', '--target=$target', '-d', device.deviceId, if (applicationBinaryPath != null) '--use-application-binary=$applicationBinaryPath', ], environment: runEnvironment, canFail: true, ); timer.cancel(); if (result == 0) { final Map<String, dynamic> data = json.decode( file('${_testOutputDirectory(testDirectory)}/start_up_info.json').readAsStringSync(), ) as Map<String, dynamic>; results.add(data); } else { currentFailures += 1; await _flutterScreenshot( device.deviceId, 'screenshot_startup_failure_$currentFailures.png', ); i -= 1; if (currentFailures == maxFailures) { return TaskResult.failure('Application failed to start $maxFailures times'); } } await device.uninstallApp(); } final Map<String, dynamic> averageResults = _average(results, iterations); if (!reportMetrics) { return TaskResult.success(averageResults); } return TaskResult.success(averageResults, benchmarkScoreKeys: <String>[ 'timeToFirstFrameMicros', 'timeToFirstFrameRasterizedMicros', ]); }); } Future<void> _flutterScreenshot(String deviceId, String screenshotName) async { if (hostAgent.dumpDirectory != null) { await flutter( 'screenshot', options: <String>[ '-d', deviceId, '--out', hostAgent.dumpDirectory! .childFile(screenshotName) .path, ], canFail: true, ); } } } /// A one-off test to verify that devtools starts in profile mode. class DevtoolsStartupTest { const DevtoolsStartupTest(this.testDirectory); final String testDirectory; Future<TaskResult> run() async { return inDirectory<TaskResult>(testDirectory, () async { final Device device = await devices.workingDevice; section('Building application'); String? applicationBinaryPath; switch (deviceOperatingSystem) { case DeviceOperatingSystem.android: await flutter('build', options: <String>[ 'apk', '-v', '--profile', '--target-platform=android-arm,android-arm64', ]); applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk'; case DeviceOperatingSystem.androidArm: await flutter('build', options: <String>[ 'apk', '-v', '--profile', '--target-platform=android-arm', ]); applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk'; case DeviceOperatingSystem.androidArm64: await flutter('build', options: <String>[ 'apk', '-v', '--profile', '--target-platform=android-arm64', ]); applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk'; case DeviceOperatingSystem.ios: await flutter('build', options: <String>[ 'ios', '-v', '--profile', ]); applicationBinaryPath = _findDarwinAppInBuildDirectory('$testDirectory/build/ios/iphoneos'); case DeviceOperatingSystem.fake: case DeviceOperatingSystem.fuchsia: case DeviceOperatingSystem.linux: case DeviceOperatingSystem.macos: case DeviceOperatingSystem.windows: break; } final Process process = await startFlutter( 'run', options: <String>[ '--no-android-gradle-daemon', '--no-publish-port', '--verbose', '--profile', '-d', device.deviceId, if (applicationBinaryPath != null) '--use-application-binary=$applicationBinaryPath', ], ); final Completer<void> completer = Completer<void>(); bool sawLine = false; process.stdout .transform(utf8.decoder) .transform(const LineSplitter()) .listen((String line) { print('[STDOUT]: $line'); // Wait for devtools output. if (line.contains('The Flutter DevTools debugger and profiler')) { sawLine = true; completer.complete(); } }); bool didExit = false; unawaited(process.exitCode.whenComplete(() { didExit = true; })); await Future.any(<Future<void>>[completer.future, Future<void>.delayed(const Duration(minutes: 5)), process.exitCode]); if (!didExit) { process.stdin.writeln('q'); await process.exitCode; } await device.uninstallApp(); if (sawLine) { return TaskResult.success(null, benchmarkScoreKeys: <String>[]); } return TaskResult.failure('Did not see line "The Flutter DevTools debugger and profiler" in output'); }); } } /// A callback function to be used to mock the flutter drive command in PerfTests. /// /// The `options` contains all the arguments in the `flutter drive` command in PerfTests. typedef FlutterDriveCallback = void Function(List<String> options); /// Measures application runtime performance, specifically per-frame /// performance. class PerfTest { const PerfTest( this.testDirectory, this.testTarget, this.timelineFileName, { this.measureCpuGpu = true, this.measureMemory = true, this.measureTotalGCTime = true, this.saveTraceFile = false, this.testDriver, this.needsFullTimeline = true, this.benchmarkScoreKeys, this.dartDefine = '', String? resultFilename, this.device, this.flutterDriveCallback, this.timeoutSeconds, this.enableImpeller, this.forceOpenGLES, this.disablePartialRepaint = false, this.createPlatforms = const <String>[], }): _resultFilename = resultFilename; const PerfTest.e2e( this.testDirectory, this.testTarget, { this.measureCpuGpu = false, this.measureMemory = false, this.measureTotalGCTime = false, this.testDriver = 'test_driver/e2e_test.dart', this.needsFullTimeline = false, this.benchmarkScoreKeys = _kCommonScoreKeys, this.dartDefine = '', String resultFilename = 'e2e_perf_summary', this.device, this.flutterDriveCallback, this.timeoutSeconds, this.enableImpeller, this.forceOpenGLES, this.disablePartialRepaint = false, this.createPlatforms = const <String>[], }) : saveTraceFile = false, timelineFileName = null, _resultFilename = resultFilename; /// The directory where the app under test is defined. final String testDirectory; /// The main entry-point file of the application, as run on the device. final String testTarget; // The prefix name of the filename such as `<timelineFileName>.timeline_summary.json`. final String? timelineFileName; String get traceFilename => '$timelineFileName.timeline'; String get resultFilename => _resultFilename ?? '$timelineFileName.timeline_summary'; final String? _resultFilename; /// The test file to run on the host. final String? testDriver; /// Whether to collect CPU and GPU metrics. final bool measureCpuGpu; /// Whether to collect memory metrics. final bool measureMemory; /// Whether to summarize total GC time on the UI thread from the timeline. final bool measureTotalGCTime; /// Whether to collect full timeline, meaning if `--trace-startup` flag is needed. final bool needsFullTimeline; /// Whether to save the trace timeline file `*.timeline.json`. final bool saveTraceFile; /// The device to test on. /// /// If null, the device is selected depending on the current environment. final Device? device; /// The function called instead of the actually `flutter drive`. /// /// If it is not `null`, `flutter drive` will not happen in the PerfTests. final FlutterDriveCallback? flutterDriveCallback; /// Whether the perf test should enable Impeller. final bool? enableImpeller; /// Whether the perf test force Impeller's OpenGLES backend. final bool? forceOpenGLES; /// Whether partial repaint functionality should be disabled (iOS only). final bool disablePartialRepaint; /// Number of seconds to time out the test after, allowing debug callbacks to run. final int? timeoutSeconds; /// The keys of the values that need to be reported. /// /// If it's `null`, then report: /// ```Dart /// <String>[ /// 'average_frame_build_time_millis', /// 'worst_frame_build_time_millis', /// '90th_percentile_frame_build_time_millis', /// '99th_percentile_frame_build_time_millis', /// 'average_frame_rasterizer_time_millis', /// 'worst_frame_rasterizer_time_millis', /// '90th_percentile_frame_rasterizer_time_millis', /// '99th_percentile_frame_rasterizer_time_millis', /// 'average_vsync_transitions_missed', /// '90th_percentile_vsync_transitions_missed', /// '99th_percentile_vsync_transitions_missed', /// if (measureCpuGpu) 'average_cpu_usage', /// if (measureCpuGpu) 'average_gpu_usage', /// ] /// ``` final List<String>? benchmarkScoreKeys; /// Additional flags for `--dart-define` to control the test final String dartDefine; /// Additional platforms to create with `flutter create` before running /// the test. final List<String> createPlatforms; Future<TaskResult> run() { return internalRun(); } @protected Future<TaskResult> internalRun({ String? existingApp, }) { return inDirectory<TaskResult>(testDirectory, () async { late Device selectedDevice; selectedDevice = device ?? await devices.workingDevice; await selectedDevice.unlock(); final String deviceId = selectedDevice.deviceId; final String? localEngine = localEngineFromEnv; final String? localEngineHost = localEngineHostFromEnv; final String? localEngineSrcPath = localEngineSrcPathFromEnv; if (createPlatforms.isNotEmpty) { await flutter('create', options: <String>[ '--platforms', createPlatforms.join(','), '--no-overwrite', '.' ]); } bool changedPlist = false; bool changedManifest = false; Future<void> resetManifest() async { if (!changedManifest) { return; } try { await _resetManifest(testDirectory); } catch (err) { print('Caught exception while trying to reset AndroidManifest: $err'); } } Future<void> resetPlist() async { if (!changedPlist) { return; } try { await _resetPlist(testDirectory); } catch (err) { print('Caught exception while trying to reset Info.plist: $err'); } } try { if (enableImpeller ?? false) { changedManifest = true; _addVulkanGPUTracingToManifest(testDirectory); if (forceOpenGLES ?? false) { _addOpenGLESToManifest(testDirectory); } } if (disablePartialRepaint) { changedPlist = true; _disablePartialRepaint(testDirectory); } final List<String> options = <String>[ if (localEngine != null) ...<String>['--local-engine', localEngine], if (localEngineHost != null) ...<String>[ '--local-engine-host', localEngineHost ], if (localEngineSrcPath != null) ...<String>[ '--local-engine-src-path', localEngineSrcPath ], '--no-dds', '--no-android-gradle-daemon', '-v', '--verbose-system-logs', '--profile', if (timeoutSeconds != null) ...<String>[ '--timeout', timeoutSeconds.toString(), ], if (needsFullTimeline) '--trace-startup', // Enables "endless" timeline event buffering. '-t', testTarget, if (testDriver != null) ...<String>['--driver', testDriver!], if (existingApp != null) ...<String>[ '--use-existing-app', existingApp ], if (dartDefine.isNotEmpty) ...<String>['--dart-define', dartDefine], if (enableImpeller != null && enableImpeller!) '--enable-impeller', if (enableImpeller != null && !enableImpeller!) '--no-enable-impeller', '-d', deviceId, ]; if (flutterDriveCallback != null) { flutterDriveCallback!(options); } else { await flutter('drive', options: options); } } finally { await resetManifest(); await resetPlist(); } final Map<String, dynamic> data = json.decode( file('${_testOutputDirectory(testDirectory)}/$resultFilename.json').readAsStringSync(), ) as Map<String, dynamic>; if (data['frame_count'] as int < 5) { return TaskResult.failure( 'Timeline contains too few frames: ${data['frame_count']}. Possibly ' 'trace events are not being captured.', ); } final bool recordGPU; switch (deviceOperatingSystem) { case DeviceOperatingSystem.ios: recordGPU = true; case DeviceOperatingSystem.android: case DeviceOperatingSystem.androidArm: case DeviceOperatingSystem.androidArm64: recordGPU = enableImpeller ?? false; case DeviceOperatingSystem.fake: case DeviceOperatingSystem.fuchsia: case DeviceOperatingSystem.linux: case DeviceOperatingSystem.macos: case DeviceOperatingSystem.windows: recordGPU = false; } // TODO(liyuqian): Remove isAndroid restriction once // https://github.com/flutter/flutter/issues/61567 is fixed. final bool isAndroid = deviceOperatingSystem == DeviceOperatingSystem.android; return TaskResult.success( data, detailFiles: <String>[ if (saveTraceFile) '${_testOutputDirectory(testDirectory)}/$traceFilename.json', ], benchmarkScoreKeys: benchmarkScoreKeys ?? <String>[ ..._kCommonScoreKeys, 'average_vsync_transitions_missed', '90th_percentile_vsync_transitions_missed', '99th_percentile_vsync_transitions_missed', 'average_frame_request_pending_latency', '90th_percentile_frame_request_pending_latency', '99th_percentile_frame_request_pending_latency', if (measureCpuGpu && !isAndroid) ...<String>[ // See https://github.com/flutter/flutter/issues/68888 if (data['average_cpu_usage'] != null) 'average_cpu_usage', if (data['average_gpu_usage'] != null) 'average_gpu_usage', ], if (measureMemory && !isAndroid) ...<String>[ // See https://github.com/flutter/flutter/issues/68888 if (data['average_memory_usage'] != null) 'average_memory_usage', if (data['90th_percentile_memory_usage'] != null) '90th_percentile_memory_usage', if (data['99th_percentile_memory_usage'] != null) '99th_percentile_memory_usage', ], if (measureTotalGCTime) 'total_ui_gc_time', if (data['30hz_frame_percentage'] != null) '30hz_frame_percentage', if (data['60hz_frame_percentage'] != null) '60hz_frame_percentage', if (data['80hz_frame_percentage'] != null) '80hz_frame_percentage', if (data['90hz_frame_percentage'] != null) '90hz_frame_percentage', if (data['120hz_frame_percentage'] != null) '120hz_frame_percentage', if (data['illegal_refresh_rate_frame_count'] != null) 'illegal_refresh_rate_frame_count', if (recordGPU) ...<String>[ // GPU Frame Time. if (data['average_gpu_frame_time'] != null) 'average_gpu_frame_time', if (data['90th_percentile_gpu_frame_time'] != null) '90th_percentile_gpu_frame_time', if (data['99th_percentile_gpu_frame_time'] != null) '99th_percentile_gpu_frame_time', if (data['worst_gpu_frame_time'] != null) 'worst_gpu_frame_time', // GPU Memory. if (data['average_gpu_memory_mb'] != null) 'average_gpu_memory_mb', if (data['90th_percentile_gpu_memory_mb'] != null) '90th_percentile_gpu_memory_mb', if (data['99th_percentile_gpu_memory_mb'] != null) '99th_percentile_gpu_memory_mb', if (data['worst_gpu_memory_mb'] != null) 'worst_gpu_memory_mb', ] ], ); }); } } const List<String> _kCommonScoreKeys = <String>[ 'average_frame_build_time_millis', 'worst_frame_build_time_millis', '90th_percentile_frame_build_time_millis', '99th_percentile_frame_build_time_millis', 'average_frame_rasterizer_time_millis', 'worst_frame_rasterizer_time_millis', '90th_percentile_frame_rasterizer_time_millis', '99th_percentile_frame_rasterizer_time_millis', 'average_layer_cache_count', '90th_percentile_layer_cache_count', '99th_percentile_layer_cache_count', 'worst_layer_cache_count', 'average_layer_cache_memory', '90th_percentile_layer_cache_memory', '99th_percentile_layer_cache_memory', 'worst_layer_cache_memory', 'average_picture_cache_count', '90th_percentile_picture_cache_count', '99th_percentile_picture_cache_count', 'worst_picture_cache_count', 'average_picture_cache_memory', '90th_percentile_picture_cache_memory', '99th_percentile_picture_cache_memory', 'worst_picture_cache_memory', 'old_gen_gc_count', ]; /// Measures how long it takes to compile a Flutter app to JavaScript and how /// big the compiled code is. class WebCompileTest { const WebCompileTest(); Future<TaskResult> run() async { final Map<String, Object> metrics = <String, Object>{}; metrics.addAll(await runSingleBuildTest( directory: '${flutterDirectory.path}/examples/hello_world', metric: 'hello_world', )); metrics.addAll(await runSingleBuildTest( directory: '${flutterDirectory.path}/dev/integration_tests/flutter_gallery', metric: 'flutter_gallery', )); const String sampleAppName = 'sample_flutter_app'; final Directory sampleDir = dir('${Directory.systemTemp.path}/$sampleAppName'); rmTree(sampleDir); await inDirectory<void>(Directory.systemTemp, () async { await flutter('create', options: <String>['--template=app', sampleAppName]); }); metrics.addAll(await runSingleBuildTest( directory: sampleDir.path, metric: 'basic_material_app', )); return TaskResult.success(metrics, benchmarkScoreKeys: metrics.keys.toList()); } /// Run a single web compile test and return its metrics. /// /// Run a single web compile test for the app under [directory], and store /// its metrics with prefix [metric]. static Future<Map<String, int>> runSingleBuildTest({ required String directory, required String metric, bool measureBuildTime = false, }) { return inDirectory<Map<String, int>>(directory, () async { final Map<String, int> metrics = <String, int>{}; await flutter('clean'); await flutter('packages', options: <String>['get']); final Stopwatch? watch = measureBuildTime ? Stopwatch() : null; watch?.start(); await evalFlutter('build', options: <String>[ 'web', '-v', '--release', '--no-pub', '--no-web-resources-cdn', ]); watch?.stop(); final String buildDir = path.join(directory, 'build', 'web'); metrics.addAll(await getSize( directories: <String, String>{'web_build_dir': buildDir}, files: <String, String>{ 'dart2js': path.join(buildDir, 'main.dart.js'), 'canvaskit_wasm': path.join(buildDir, 'canvaskit', 'canvaskit.wasm'), 'canvaskit_js': path.join(buildDir, 'canvaskit', 'canvaskit.js'), 'flutter_js': path.join(buildDir, 'flutter.js'), }, metric: metric, )); if (measureBuildTime) { metrics['${metric}_dart2js_millis'] = watch!.elapsedMilliseconds; } return metrics; }); } /// Obtains the size and gzipped size of both [dartBundleFile] and [buildDir]. static Future<Map<String, int>> getSize({ /// Mapping of metric key name to file system path for directories to measure Map<String, String> directories = const <String, String>{}, /// Mapping of metric key name to file system path for files to measure Map<String, String> files = const <String, String>{}, required String metric, }) async { const String kGzipCompressionLevel = '-9'; final Map<String, int> sizeMetrics = <String, int>{}; final Directory tempDir = Directory.systemTemp.createTempSync('perf_tests_gzips'); try { for (final MapEntry<String, String> entry in files.entries) { final String key = entry.key; final String filePath = entry.value; sizeMetrics['${metric}_${key}_uncompressed_bytes'] = File(filePath).lengthSync(); await Process.run('gzip',<String>['--keep', kGzipCompressionLevel, filePath]); // gzip does not provide a CLI option to specify an output file, so // instead just move the output file to the temp dir final File compressedFile = File('$filePath.gz') .renameSync(path.join(tempDir.absolute.path, '$key.gz')); sizeMetrics['${metric}_${key}_compressed_bytes'] = compressedFile.lengthSync(); } for (final MapEntry<String, String> entry in directories.entries) { final String key = entry.key; final String dirPath = entry.value; final String tarball = path.join(tempDir.absolute.path, '$key.tar'); await Process.run('tar', <String>[ '--create', '--verbose', '--file=$tarball', dirPath, ]); sizeMetrics['${metric}_${key}_uncompressed_bytes'] = File(tarball).lengthSync(); // get size of compressed build directory await Process.run('gzip',<String>['--keep', kGzipCompressionLevel, tarball]); sizeMetrics['${metric}_${key}_compressed_bytes'] = File('$tarball.gz').lengthSync(); } } finally { try { tempDir.deleteSync(recursive: true); } on FileSystemException { print('Failed to delete ${tempDir.path}.'); } } return sizeMetrics; } } /// Measures how long it takes to compile a Flutter app and how big the compiled /// code is. class CompileTest { const CompileTest(this.testDirectory, { this.reportPackageContentSizes = false }); final String testDirectory; final bool reportPackageContentSizes; Future<TaskResult> run() async { return inDirectory<TaskResult>(testDirectory, () async { await flutter('packages', options: <String>['get']); // "initial" compile required downloading and creating the `android/.gradle` directory while "full" // compiles only run `flutter clean` between runs. final Map<String, dynamic> compileInitialRelease = await _compileApp(deleteGradleCache: true); final Map<String, dynamic> compileFullRelease = await _compileApp(deleteGradleCache: false); final Map<String, dynamic> compileInitialDebug = await _compileDebug( clean: true, deleteGradleCache: true, metricKey: 'debug_initial_compile_millis', ); final Map<String, dynamic> compileFullDebug = await _compileDebug( clean: true, deleteGradleCache: false, metricKey: 'debug_full_compile_millis', ); // Build again without cleaning, should be faster. final Map<String, dynamic> compileSecondDebug = await _compileDebug( clean: false, deleteGradleCache: false, metricKey: 'debug_second_compile_millis', ); final Map<String, dynamic> metrics = <String, dynamic>{ ...compileInitialRelease, ...compileFullRelease, ...compileInitialDebug, ...compileFullDebug, ...compileSecondDebug, }; final File mainDart = File('$testDirectory/lib/main.dart'); if (mainDart.existsSync()) { final List<int> bytes = mainDart.readAsBytesSync(); // "Touch" the file mainDart.writeAsStringSync(' ', mode: FileMode.append, flush: true); // Build after "edit" without clean should be faster than first build final Map<String, dynamic> compileAfterEditDebug = await _compileDebug( clean: false, deleteGradleCache: false, metricKey: 'debug_compile_after_edit_millis', ); metrics.addAll(compileAfterEditDebug); // Revert the changes mainDart.writeAsBytesSync(bytes, flush: true); } return TaskResult.success(metrics, benchmarkScoreKeys: metrics.keys.toList()); }); } Future<Map<String, dynamic>> _compileApp({required bool deleteGradleCache}) async { await flutter('clean'); if (deleteGradleCache) { final Directory gradleCacheDir = Directory('$testDirectory/android/.gradle'); rmTree(gradleCacheDir); } final Stopwatch watch = Stopwatch(); int releaseSizeInBytes; final List<String> options = <String>['--release']; final Map<String, dynamic> metrics = <String, dynamic>{}; switch (deviceOperatingSystem) { case DeviceOperatingSystem.ios: case DeviceOperatingSystem.macos: unawaited(stderr.flush()); late final String deviceId; if (deviceOperatingSystem == DeviceOperatingSystem.ios) { deviceId = 'ios'; } else if (deviceOperatingSystem == DeviceOperatingSystem.macos) { deviceId = 'macos'; } else { throw Exception('Attempted to run darwin compile workflow with $deviceOperatingSystem'); } options.insert(0, deviceId); options.add('--tree-shake-icons'); options.add('--split-debug-info=infos/'); watch.start(); await flutter( 'build', options: options, environment: <String, String> { // iOS 12.1 and lower did not have Swift ABI compatibility so Swift apps embedded the Swift runtime. // https://developer.apple.com/documentation/xcode-release-notes/swift-5-release-notes-for-xcode-10_2#App-Thinning // The gallery pulls in Swift plugins. Set lowest version to 12.2 to avoid benchmark noise. // This should be removed when when Flutter's minimum supported version is >12.2. 'FLUTTER_XCODE_IPHONEOS_DEPLOYMENT_TARGET': '12.2', }, ); watch.stop(); final Directory buildDirectory = dir(path.join( cwd, 'build', )); final String? appPath = _findDarwinAppInBuildDirectory(buildDirectory.path); if (appPath == null) { throw 'Failed to find app bundle in ${buildDirectory.path}'; } // Validate changes in Dart snapshot format and data layout do not // change compression size. This also simulates the size of an IPA on iOS. await exec('tar', <String>['-zcf', 'build/app.tar.gz', appPath]); releaseSizeInBytes = await file('$cwd/build/app.tar.gz').length(); if (reportPackageContentSizes) { final Map<String, Object> sizeMetrics = await getSizesFromDarwinApp( appPath: appPath, operatingSystem: deviceOperatingSystem, ); metrics.addAll(sizeMetrics); } case DeviceOperatingSystem.android: case DeviceOperatingSystem.androidArm: options.insert(0, 'apk'); options.add('--target-platform=android-arm'); options.add('--tree-shake-icons'); options.add('--split-debug-info=infos/'); watch.start(); await flutter('build', options: options); watch.stop(); final String apkPath = '$cwd/build/app/outputs/flutter-apk/app-release.apk'; final File apk = file(apkPath); releaseSizeInBytes = apk.lengthSync(); if (reportPackageContentSizes) { metrics.addAll(await getSizesFromApk(apkPath)); } case DeviceOperatingSystem.androidArm64: options.insert(0, 'apk'); options.add('--target-platform=android-arm64'); options.add('--tree-shake-icons'); options.add('--split-debug-info=infos/'); watch.start(); await flutter('build', options: options); watch.stop(); final String apkPath = '$cwd/build/app/outputs/flutter-apk/app-release.apk'; final File apk = file(apkPath); releaseSizeInBytes = apk.lengthSync(); if (reportPackageContentSizes) { metrics.addAll(await getSizesFromApk(apkPath)); } case DeviceOperatingSystem.fake: throw Exception('Unsupported option for fake devices'); case DeviceOperatingSystem.fuchsia: throw Exception('Unsupported option for Fuchsia devices'); case DeviceOperatingSystem.linux: throw Exception('Unsupported option for Linux devices'); case DeviceOperatingSystem.windows: unawaited(stderr.flush()); options.insert(0, 'windows'); options.add('--tree-shake-icons'); options.add('--split-debug-info=infos/'); watch.start(); await flutter('build', options: options); watch.stop(); final String basename = path.basename(cwd); final String arch = Abi.current() == Abi.windowsX64 ? 'x64': 'arm64'; final String exePath = path.join( cwd, 'build', 'windows', arch, 'runner', 'release', '$basename.exe'); final File exe = file(exePath); // On Windows, we do not produce a single installation package file, // rather a directory containing an .exe and .dll files. // The release size is set to the size of the produced .exe file releaseSizeInBytes = exe.lengthSync(); } metrics.addAll(<String, dynamic>{ 'release_${deleteGradleCache ? 'initial' : 'full'}_compile_millis': watch.elapsedMilliseconds, 'release_size_bytes': releaseSizeInBytes, }); return metrics; } Future<Map<String, dynamic>> _compileDebug({ required bool deleteGradleCache, required bool clean, required String metricKey, }) async { if (clean) { await flutter('clean'); } if (deleteGradleCache) { final Directory gradleCacheDir = Directory('$testDirectory/android/.gradle'); rmTree(gradleCacheDir); } final Stopwatch watch = Stopwatch(); final List<String> options = <String>['--debug']; switch (deviceOperatingSystem) { case DeviceOperatingSystem.ios: options.insert(0, 'ios'); case DeviceOperatingSystem.android: case DeviceOperatingSystem.androidArm: options.insert(0, 'apk'); options.add('--target-platform=android-arm'); case DeviceOperatingSystem.androidArm64: options.insert(0, 'apk'); options.add('--target-platform=android-arm64'); case DeviceOperatingSystem.fake: throw Exception('Unsupported option for fake devices'); case DeviceOperatingSystem.fuchsia: throw Exception('Unsupported option for Fuchsia devices'); case DeviceOperatingSystem.linux: throw Exception('Unsupported option for Linux devices'); case DeviceOperatingSystem.macos: unawaited(stderr.flush()); options.insert(0, 'macos'); case DeviceOperatingSystem.windows: unawaited(stderr.flush()); options.insert(0, 'windows'); } watch.start(); await flutter('build', options: options); watch.stop(); return <String, dynamic>{ metricKey: watch.elapsedMilliseconds, }; } static Future<Map<String, Object>> getSizesFromDarwinApp({ required String appPath, required DeviceOperatingSystem operatingSystem, }) async { late final File flutterFramework; late final String frameworkDirectory; switch (deviceOperatingSystem) { case DeviceOperatingSystem.ios: frameworkDirectory = path.join( appPath, 'Frameworks', ); flutterFramework = File(path.join( frameworkDirectory, 'Flutter.framework', 'Flutter', )); case DeviceOperatingSystem.macos: frameworkDirectory = path.join( appPath, 'Contents', 'Frameworks', ); flutterFramework = File(path.join( frameworkDirectory, 'FlutterMacOS.framework', 'FlutterMacOS', )); // https://github.com/flutter/flutter/issues/70413 case DeviceOperatingSystem.android: case DeviceOperatingSystem.androidArm: case DeviceOperatingSystem.androidArm64: case DeviceOperatingSystem.fake: case DeviceOperatingSystem.fuchsia: case DeviceOperatingSystem.linux: case DeviceOperatingSystem.windows: throw Exception('Called ${CompileTest.getSizesFromDarwinApp} with $operatingSystem.'); } final File appFramework = File(path.join( frameworkDirectory, 'App.framework', 'App', )); return <String, Object>{ 'app_framework_uncompressed_bytes': await appFramework.length(), 'flutter_framework_uncompressed_bytes': await flutterFramework.length(), }; } static Future<Map<String, dynamic>> getSizesFromApk(String apkPath) async { final String output = await eval('unzip', <String>['-v', apkPath]); final List<String> lines = output.split('\n'); final Map<String, _UnzipListEntry> fileToMetadata = <String, _UnzipListEntry>{}; // First three lines are header, last two lines are footer. for (int i = 3; i < lines.length - 2; i++) { final _UnzipListEntry entry = _UnzipListEntry.fromLine(lines[i]); fileToMetadata[entry.path] = entry; } final _UnzipListEntry libflutter = fileToMetadata['lib/armeabi-v7a/libflutter.so']!; final _UnzipListEntry libapp = fileToMetadata['lib/armeabi-v7a/libapp.so']!; final _UnzipListEntry license = fileToMetadata['assets/flutter_assets/NOTICES.Z']!; return <String, dynamic>{ 'libflutter_uncompressed_bytes': libflutter.uncompressedSize, 'libflutter_compressed_bytes': libflutter.compressedSize, 'libapp_uncompressed_bytes': libapp.uncompressedSize, 'libapp_compressed_bytes': libapp.compressedSize, 'license_uncompressed_bytes': license.uncompressedSize, 'license_compressed_bytes': license.compressedSize, }; } } /// Measure application memory usage. class MemoryTest { MemoryTest(this.project, this.test, this.package); final String project; final String test; final String package; /// Completes when the log line specified in the last call to /// [prepareForNextMessage] is seen by `adb logcat`. Future<void>? get receivedNextMessage => _receivedNextMessage?.future; Completer<void>? _receivedNextMessage; String? _nextMessage; /// Prepares the [receivedNextMessage] future such that it will complete /// when `adb logcat` sees a log line with the given `message`. void prepareForNextMessage(String message) { _nextMessage = message; _receivedNextMessage = Completer<void>(); } int get iterationCount => 10; Device? get device => _device; Device? _device; Future<TaskResult> run() { return inDirectory<TaskResult>(project, () async { // This test currently only works on Android, because device.logcat, // device.getMemoryStats, etc, aren't implemented for iOS. _device = await devices.workingDevice; await device!.unlock(); await flutter('packages', options: <String>['get']); final StreamSubscription<String> adb = device!.logcat.listen( (String data) { if (data.contains('==== MEMORY BENCHMARK ==== $_nextMessage ====')) { _receivedNextMessage?.complete(); } }, ); for (int iteration = 0; iteration < iterationCount; iteration += 1) { print('running memory test iteration $iteration...'); _startMemoryUsage = null; await useMemory(); assert(_startMemoryUsage != null); assert(_startMemory.length == iteration + 1); assert(_endMemory.length == iteration + 1); assert(_diffMemory.length == iteration + 1); print('terminating...'); await device!.stop(package); await Future<void>.delayed(const Duration(milliseconds: 10)); } await adb.cancel(); await device!.uninstallApp(); final ListStatistics startMemoryStatistics = ListStatistics(_startMemory); final ListStatistics endMemoryStatistics = ListStatistics(_endMemory); final ListStatistics diffMemoryStatistics = ListStatistics(_diffMemory); final Map<String, dynamic> memoryUsage = <String, dynamic>{ ...startMemoryStatistics.asMap('start'), ...endMemoryStatistics.asMap('end'), ...diffMemoryStatistics.asMap('diff'), }; _device = null; _startMemory.clear(); _endMemory.clear(); _diffMemory.clear(); return TaskResult.success(memoryUsage, benchmarkScoreKeys: memoryUsage.keys.toList()); }); } /// Starts the app specified by [test] on the [device]. /// /// The [run] method will terminate it by its package name ([package]). Future<void> launchApp() async { prepareForNextMessage('READY'); print('launching $project$test on device...'); await flutter('run', options: <String>[ '--verbose', '--release', '--no-resident', '-d', device!.deviceId, test, ]); print('awaiting "ready" message...'); await receivedNextMessage; } /// To change the behavior of the test, override this. /// /// Make sure to call recordStart() and recordEnd() once each in that order. /// /// By default it just launches the app, records memory usage, taps the device, /// awaits a DONE notification, and records memory usage again. Future<void> useMemory() async { await launchApp(); await recordStart(); prepareForNextMessage('DONE'); print('tapping device...'); await device!.tap(100, 100); print('awaiting "done" message...'); await receivedNextMessage; await recordEnd(); } final List<int> _startMemory = <int>[]; final List<int> _endMemory = <int>[]; final List<int> _diffMemory = <int>[]; Map<String, dynamic>? _startMemoryUsage; @protected Future<void> recordStart() async { assert(_startMemoryUsage == null); print('snapshotting memory usage...'); _startMemoryUsage = await device!.getMemoryStats(package); } @protected Future<void> recordEnd() async { assert(_startMemoryUsage != null); print('snapshotting memory usage...'); final Map<String, dynamic> endMemoryUsage = await device!.getMemoryStats(package); _startMemory.add(_startMemoryUsage!['total_kb'] as int); _endMemory.add(endMemoryUsage['total_kb'] as int); _diffMemory.add((endMemoryUsage['total_kb'] as int) - (_startMemoryUsage!['total_kb'] as int)); } } class DevToolsMemoryTest { DevToolsMemoryTest(this.project, this.driverTest); final String project; final String driverTest; Future<TaskResult> run() { return inDirectory<TaskResult>(project, () async { _device = await devices.workingDevice; await _device.unlock(); await flutter( 'drive', options: <String>[ '-d', _device.deviceId, '--profile', '--profile-memory', _kJsonFileName, '--no-publish-port', '-v', driverTest, ], ); final Map<String, dynamic> data = json.decode( file('$project/$_kJsonFileName').readAsStringSync(), ) as Map<String, dynamic>; final List<dynamic> samples = (data['samples'] as Map<String, dynamic>)['data'] as List<dynamic>; int maxRss = 0; int maxAdbTotal = 0; for (final Map<String, dynamic> sample in samples.cast<Map<String, dynamic>>()) { if (sample['rss'] != null) { maxRss = math.max(maxRss, sample['rss'] as int); } if (sample['adb_memoryInfo'] != null) { maxAdbTotal = math.max(maxAdbTotal, (sample['adb_memoryInfo'] as Map<String, dynamic>)['Total'] as int); } } return TaskResult.success( <String, dynamic>{'maxRss': maxRss, 'maxAdbTotal': maxAdbTotal}, benchmarkScoreKeys: <String>['maxRss', 'maxAdbTotal'], ); }); } late Device _device; static const String _kJsonFileName = 'devtools_memory.json'; } enum ReportedDurationTestFlavor { debug, profile, release } String _reportedDurationTestToString(ReportedDurationTestFlavor flavor) { return switch (flavor) { ReportedDurationTestFlavor.debug => 'debug', ReportedDurationTestFlavor.profile => 'profile', ReportedDurationTestFlavor.release => 'release', }; } class ReportedDurationTest { ReportedDurationTest(this.flavor, this.project, this.test, this.package, this.durationPattern); final ReportedDurationTestFlavor flavor; final String project; final String test; final String package; final RegExp durationPattern; final Completer<int> durationCompleter = Completer<int>(); int get iterationCount => 10; Device? get device => _device; Device? _device; Future<TaskResult> run() { return inDirectory<TaskResult>(project, () async { // This test currently only works on Android, because device.logcat, // device.getMemoryStats, etc, aren't implemented for iOS. _device = await devices.workingDevice; await device!.unlock(); await flutter('packages', options: <String>['get']); final StreamSubscription<String> adb = device!.logcat.listen( (String data) { if (durationPattern.hasMatch(data)) { durationCompleter.complete(int.parse(durationPattern.firstMatch(data)!.group(1)!)); } }, ); print('launching $project$test on device...'); await flutter('run', options: <String>[ '--verbose', '--no-publish-port', '--no-fast-start', '--${_reportedDurationTestToString(flavor)}', '--no-resident', '-d', device!.deviceId, test, ]); final int duration = await durationCompleter.future; print('terminating...'); await device!.stop(package); await adb.cancel(); _device = null; final Map<String, dynamic> reportedDuration = <String, dynamic>{ 'duration': duration, }; _device = null; return TaskResult.success(reportedDuration, benchmarkScoreKeys: reportedDuration.keys.toList()); }); } } /// Holds simple statistics of an odd-lengthed list of integers. class ListStatistics { factory ListStatistics(Iterable<int> data) { assert(data.isNotEmpty); assert(data.length.isOdd); final List<int> sortedData = data.toList()..sort(); return ListStatistics._( sortedData.first, sortedData.last, sortedData[(sortedData.length - 1) ~/ 2], ); } const ListStatistics._(this.min, this.max, this.median); final int min; final int max; final int median; Map<String, int> asMap(String prefix) { return <String, int>{ '$prefix-min': min, '$prefix-max': max, '$prefix-median': median, }; } } class _UnzipListEntry { factory _UnzipListEntry.fromLine(String line) { final List<String> data = line.trim().split(RegExp(r'\s+')); assert(data.length == 8); return _UnzipListEntry._( uncompressedSize: int.parse(data[0]), compressedSize: int.parse(data[2]), path: data[7], ); } _UnzipListEntry._({ required this.uncompressedSize, required this.compressedSize, required this.path, }) : assert(compressedSize <= uncompressedSize); final int uncompressedSize; final int compressedSize; final String path; } /// Wait for up to 1 hour for the file to appear. Future<File> waitForFile(String path) async { for (int i = 0; i < 180; i += 1) { final File file = File(path); print('looking for ${file.path}'); if (file.existsSync()) { return file; } await Future<void>.delayed(const Duration(seconds: 20)); } throw StateError('Did not find vmservice out file after 1 hour'); } String? _findDarwinAppInBuildDirectory(String searchDirectory) { for (final FileSystemEntity entity in Directory(searchDirectory) .listSync(recursive: true)) { if (entity.path.endsWith('.app')) { return entity.path; } } return null; }
flutter/dev/devicelab/lib/tasks/perf_tests.dart/0
{ "file_path": "flutter/dev/devicelab/lib/tasks/perf_tests.dart", "repo_id": "flutter", "token_count": 30529 }
515
// 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:flutter_devicelab/framework/utils.dart' show rm; import 'package:path/path.dart' as path; import 'package:process/process.dart'; import 'common.dart'; void main() { const ProcessManager processManager = LocalProcessManager(); final String dart = path.absolute( path.join('..', '..', 'bin', 'cache', 'dart-sdk', 'bin', 'dart')); group('run.dart script', () { // The tasks here refer to files in ../bin/tasks/*.dart Future<ProcessResult> runScript(List<String> taskNames, [List<String> otherArgs = const <String>[]]) async { final ProcessResult scriptProcess = processManager.runSync(<String>[ dart, 'bin/run.dart', '--no-terminate-stray-dart-processes', ...otherArgs, for (final String testName in taskNames) ...<String>['-t', testName], ]); return scriptProcess; } Future<void> expectScriptResult( List<String> taskNames, int expectedExitCode, {String? deviceId} ) async { final ProcessResult result = await runScript(taskNames, <String>[ if (deviceId != null) ...<String>['-d', deviceId], ]); expect( result.exitCode, expectedExitCode, reason: '[ stderr from test process ]\n' '\n' '${result.stderr}\n' '\n' '[ end of stderr ]\n' '\n' '[ stdout from test process ]\n' '\n' '${result.stdout}\n' '\n' '[ end of stdout ]', ); } test('exits with code 0 when succeeds', () async { await expectScriptResult(<String>['smoke_test_success'], 0); }); test('rejects invalid file paths', () async { await expectScriptResult(<String>['lib/framework/adb.dart'], 1); }); test('exits with code 1 when task throws', () async { await expectScriptResult(<String>['smoke_test_throws'], 1); }); test('exits with code 1 when fails', () async { await expectScriptResult(<String>['smoke_test_failure'], 1); }); test('prints a message after a few seconds when failing to connect (this test takes >10s)', () async { final Process process = await processManager.start(<String>[ dart, 'bin/run.dart', '--no-terminate-stray-dart-processes', '-t', 'smoke_test_setup_failure', ]); await process.stdout.transform(utf8.decoder).where( (String line) => line.contains('VM service still not ready. It is possible the target has failed') ).first; expect(process.kill(), isTrue); }); test('exits with code 1 when results are mixed', () async { await expectScriptResult( <String>[ 'smoke_test_failure', 'smoke_test_success', ], 1, ); }); test('exits with code 0 when provided a valid device ID', () async { await expectScriptResult(<String>['smoke_test_device'], 0, deviceId: 'FAKE'); }); test('exits with code 1 when provided a bad device ID', () async { await expectScriptResult(<String>['smoke_test_device'], 1, deviceId: 'THIS_IS_NOT_VALID'); }); test('runs A/B test', () async { final Directory tempDirectory = Directory.systemTemp.createTempSync('flutter_devicelab_ab_test.'); final File abResultsFile = File(path.join(tempDirectory.path, 'test_results.json')); expect(abResultsFile.existsSync(), isFalse); final ProcessResult result = await runScript( <String>['smoke_test_success'], <String>['--ab=2', '--local-engine=host_debug_unopt', '--local-engine-host=host_debug_unopt', '--ab-result-file', abResultsFile.path], ); expect(result.exitCode, 0); String sectionHeader = !Platform.isWindows ? '═════════════════════════╡ ••• A/B results so far ••• ╞═════════════════════════' : 'A/B results so far'; expect( result.stdout, contains( '$sectionHeader\n' '\n' 'Score\tAverage A (noise)\tAverage B (noise)\tSpeed-up\n' 'metric1\t42.00 (0.00%)\t42.00 (0.00%)\t1.00x\t\n' 'metric2\t123.00 (0.00%)\t123.00 (0.00%)\t1.00x\t\n', ), ); sectionHeader = !Platform.isWindows ? '════════════════════════════╡ ••• Raw results ••• ╞═════════════════════════════' : 'Raw results'; expect( result.stdout, contains( '$sectionHeader\n' '\n' 'metric1:\n' ' A:\t42.00\t42.00\t\n' ' B:\t42.00\t42.00\t\n' 'metric2:\n' ' A:\t123.00\t123.00\t\n' ' B:\t123.00\t123.00\t\n', ), ); sectionHeader = !Platform.isWindows ? '═════════════════════════╡ ••• Final A/B results ••• ╞══════════════════════════' : 'Final A/B results'; expect( result.stdout, contains( '$sectionHeader\n' '\n' 'Score\tAverage A (noise)\tAverage B (noise)\tSpeed-up\n' 'metric1\t42.00 (0.00%)\t42.00 (0.00%)\t1.00x\t\n' 'metric2\t123.00 (0.00%)\t123.00 (0.00%)\t1.00x\t\n', ), ); expect(abResultsFile.existsSync(), isTrue); rm(tempDirectory, recursive: true); }); test('fails to upload results to Cocoon if flags given', () async { // CocoonClient will fail to find test-file, and will not send any http requests. final ProcessResult result = await runScript( <String>['smoke_test_success'], <String>['--service-account-file=test-file', '--task-key=task123'], ); expect(result.exitCode, 1); }); }); }
flutter/dev/devicelab/test/run_test.dart/0
{ "file_path": "flutter/dev/devicelab/test/run_test.dart", "repo_id": "flutter", "token_count": 2689 }
516
dartdoc: ignore: # The stub `Flutter` package is expected to have no # documentable libraries. - no-documentable-libraries
flutter/dev/docs/dartdoc_options.yaml/0
{ "file_path": "flutter/dev/docs/dartdoc_options.yaml", "repo_id": "flutter", "token_count": 47 }
517
<!-- style overrides for dartdoc --> <style> @import 'https://fonts.googleapis.com/css?family=Roboto:500,400italic,300,400,100i'; @import 'https://fonts.googleapis.com/css?family=Google+Sans:500,400italic,300,400,100i'; @import 'https://fonts.googleapis.com/css?family=Open+Sans:500,400italic,300,400,100i'; @import 'https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Sharp|Material+Icons+Round'; </style> <link href="https://flutter.github.io/assets-for-api-docs/assets/cupertino/cupertino.css" rel="stylesheet" type="text/css"> <link href="../assets/overrides.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Sharp|Material+Icons+Round" rel="stylesheet"> <style> /* Rule for sizing the icon. */ .md-36 { font-size: 36px; } </style>
flutter/dev/docs/styles.html/0
{ "file_path": "flutter/dev/docs/styles.html", "repo_id": "flutter", "token_count": 331 }
518
# App using Android Embedding 2 A new Flutter project using the Android embedding 2. This smoke test uses the following plugins: | Plugin | Android Embedding | |--------------------|-------------------| | battery: 0.3.0+5 | 1 |
flutter/dev/integration_tests/android_embedding_v2_smoke_test/README.md/0
{ "file_path": "flutter/dev/integration_tests/android_embedding_v2_smoke_test/README.md", "repo_id": "flutter", "token_count": 94 }
519
// 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 'src/tests/controls_page.dart'; import 'src/tests/headings_page.dart'; import 'src/tests/popup_page.dart'; import 'src/tests/text_field_page.dart'; void main() { runApp(const TestApp()); } Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ selectionControlsRoute : (BuildContext context) => const SelectionControlsPage(), popupControlsRoute : (BuildContext context) => const PopupControlsPage(), textFieldRoute : (BuildContext context) => const TextFieldPage(), headingsRoute: (BuildContext context) => const HeadingsPage(), }; class TestApp extends StatelessWidget { const TestApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( routes: routes, home: Builder( builder: (BuildContext context) { return Scaffold( body: ListView( children: routes.keys.map<Widget>((String value) { return MaterialButton( child: Text(value), onPressed: () { Navigator.of(context).pushNamed(value); }, ); }).toList(), ), ); } ), ); } }
flutter/dev/integration_tests/android_semantics_testing/lib/main.dart/0
{ "file_path": "flutter/dev/integration_tests/android_semantics_testing/lib/main.dart", "repo_id": "flutter", "token_count": 576 }
520
// 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; Future<void> main() async { late FlutterDriver driver; setUpAll(() async { driver = await FlutterDriver.connect(); }); tearDownAll(() { driver.close(); }); // Each test below must return back to the home page after finishing. test('MotionEvent recomposition', () async { final SerializableFinder motionEventsListTile = find.byValueKey('MotionEventsListTile'); await driver.tap(motionEventsListTile); await driver.runUnsynchronized(() async { driver.waitFor(find.byValueKey('PlatformView')); }); final String errorMessage = await driver.requestData('run test'); expect(errorMessage, ''); final SerializableFinder backButton = find.byValueKey('back'); await driver.tap(backButton); }, timeout: Timeout.none); group('WindowManager', () { setUpAll(() async { final SerializableFinder wmListTile = find.byValueKey('WmIntegrationsListTile'); await driver.tap(wmListTile); }); tearDownAll(() async { await driver.waitFor(find.pageBack()); await driver.tap(find.pageBack()); }); test('AlertDialog from platform view context', () async { final SerializableFinder showAlertDialog = find.byValueKey( 'ShowAlertDialog'); await driver.waitFor(showAlertDialog); await driver.tap(showAlertDialog); final String status = await driver.getText(find.byValueKey('Status')); expect(status, 'Success'); }, timeout: Timeout.none); test('Child windows can handle touches', () async { final SerializableFinder addWindow = find.byValueKey('AddWindow'); await driver.waitFor(addWindow); await driver.tap(addWindow); final SerializableFinder tapWindow = find.byValueKey('TapWindow'); await driver.tap(tapWindow); final String windowClickCount = await driver.getText( find.byValueKey('WindowClickCount'), ); expect(windowClickCount, 'Click count: 1'); }, timeout: Timeout.none, skip: true); // TODO(garyq): Skipped, see https://github.com/flutter/flutter/issues/88479 }); }
flutter/dev/integration_tests/android_views/test_driver/main_test.dart/0
{ "file_path": "flutter/dev/integration_tests/android_views/test_driver/main_test.dart", "repo_id": "flutter", "token_count": 800 }
521
// 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:typed_data'; import 'package:flutter/material.dart'; import 'pair.dart'; enum TestStatus { ok, pending, failed, complete } typedef TestStep = Future<TestStepResult> Function(); const String nothing = '-'; /// Result of a test step checking a nested communication handshake /// between the Flutter app and the platform: /// /// - The Flutter app sends a message to the platform. /// - The platform, on receipt, echos the message back to Flutter in a separate message. /// - The Flutter app records the incoming message echo and replies. /// - The platform, on receipt of reply, echos the reply back to Flutter in a separate message. /// - The Flutter app records the incoming reply echo. /// - The platform finally replies to the original message with another echo. class TestStepResult { const TestStepResult( this.name, this.description, this.status, { this.messageSent = nothing, this.messageEcho = nothing, this.messageReceived = nothing, this.replyEcho = nothing, this.error = nothing, }); factory TestStepResult.fromSnapshot(AsyncSnapshot<TestStepResult> snapshot) { switch (snapshot.connectionState) { case ConnectionState.none: return const TestStepResult('Not started', nothing, TestStatus.ok); case ConnectionState.waiting: return const TestStepResult('Executing', nothing, TestStatus.pending); case ConnectionState.done: if (snapshot.hasData) { return snapshot.data!; } return snapshot.error! as TestStepResult; case ConnectionState.active: throw 'Unsupported state ${snapshot.connectionState}'; } } final String name; final String description; final TestStatus status; final dynamic messageSent; final dynamic messageEcho; final dynamic messageReceived; final dynamic replyEcho; final dynamic error; static const TextStyle bold = TextStyle(fontWeight: FontWeight.bold); static const TestStepResult complete = TestStepResult( 'Test complete', nothing, TestStatus.complete, ); Widget asWidget(BuildContext context) { return ListView( children: <Widget>[ Text('Step: $name', style: bold), Text(description), const Text(' '), Text('Msg sent: ${_toString(messageSent)}'), Text('Msg rvcd: ${_toString(messageReceived)}'), Text('Reply echo: ${_toString(replyEcho)}'), Text('Msg echo: ${_toString(messageEcho)}'), Text('Error: ${_toString(error)}'), const Text(' '), Text( status.name, key: ValueKey<String>( status == TestStatus.pending ? 'nostatus' : 'status'), style: bold, ), ], ); } static bool deepEquals(dynamic a, dynamic b) => _deepEquals(a, b); @override String toString() { return 'TestStepResult($status)'; } } Future<TestStepResult> resultOfHandshake( String name, String description, dynamic message, List<dynamic> received, dynamic messageEcho, dynamic error, ) async { assert(message != nothing); while (received.length < 2) { received.add(nothing); } TestStatus status; if (!_deepEquals(messageEcho, message) || received.length != 2 || !_deepEquals(received[0], message) || !_deepEquals(received[1], message)) { status = TestStatus.failed; } else if (error != nothing) { status = TestStatus.failed; } else { status = TestStatus.ok; } return TestStepResult( name, description, status, messageSent: message, messageEcho: messageEcho, messageReceived: received[0], replyEcho: received[1], error: error, ); } String _toString(dynamic message) { if (message is ByteData) { return message.buffer .asUint8List(message.offsetInBytes, message.lengthInBytes) .toString(); } else { return '$message'; } } bool _deepEquals(dynamic a, dynamic b) { if (a == b) { return true; } if (a is double && a.isNaN) { return b is double && b.isNaN; } if (a is ByteData) { return b is ByteData && _deepEqualsByteData(a, b); } if (a is List) { return b is List && _deepEqualsList(a, b); } if (a is Map) { return b is Map && _deepEqualsMap(a, b); } if (a is Pair) { return b is Pair && _deepEqualsPair(a, b); } return false; } bool _deepEqualsByteData(ByteData a, ByteData b) { return _deepEqualsList( a.buffer.asUint8List(a.offsetInBytes, a.lengthInBytes), b.buffer.asUint8List(b.offsetInBytes, b.lengthInBytes), ); } bool _deepEqualsList(List<dynamic> a, List<dynamic> b) { if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { if (!_deepEquals(a[i], b[i])) { return false; } } return true; } bool _deepEqualsMap(Map<dynamic, dynamic> a, Map<dynamic, dynamic> b) { if (a.length != b.length) { return false; } for (final dynamic key in a.keys) { if (!b.containsKey(key) || !_deepEquals(a[key], b[key])) { return false; } } return true; } bool _deepEqualsPair(Pair a, Pair b) { return _deepEquals(a.left, b.left) && _deepEquals(a.right, b.right); }
flutter/dev/integration_tests/channels/lib/src/test_step.dart/0
{ "file_path": "flutter/dev/integration_tests/channels/lib/src/test_step.dart", "repo_id": "flutter", "token_count": 2002 }
522
<!-- 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. --> <resources> <!--Begin Deferred Components strings.--> <string name="component1Name">component1</string> <!--End Deferred Components strings.--> </resources>
flutter/dev/integration_tests/deferred_components_test/android/app/src/main/res/values/strings.xml/0
{ "file_path": "flutter/dev/integration_tests/deferred_components_test/android/app/src/main/res/values/strings.xml", "repo_id": "flutter", "token_count": 91 }
523
#!/usr/bin/env bash # 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. # Usage: # # ./run_release_test.sh <bundletool.jar path> <adb path> # # In CI, this script currently depends on a modified version of bundletool because # ddmlib which bundletool depends on does not yet support detecting QEMU emulator device # density system properties. See https://android.googlesource.com/platform/tools/base/+/refs/heads/master/ddmlib/src/main/java/com/android/ddmlib/IDevice.java#46 # # The modified bundletool which waives the density requirement is at: # https://chrome-infra-packages.appspot.com/p/flutter/android/bundletool/+/vFt1jA0cUeZLmUCVR5NG2JVB-SgJ18GH_pVYKMOlfUIC bundletool_jar_path=$1 adb_path=$2 # Store the time to prevent capturing logs from previous runs. script_start_time=$($adb_path shell 'date +"%m-%d %H:%M:%S.0"') $adb_path uninstall "io.flutter.integration.deferred_components_test" rm -f build/app/outputs/bundle/release/app-release.apks rm -f build/app/outputs/bundle/release/run_logcat.log flutter build appbundle java -jar $bundletool_jar_path build-apks --bundle=build/app/outputs/bundle/release/app-release.aab --output=build/app/outputs/bundle/release/app-release.apks --local-testing --ks android/testing-keystore.jks --ks-key-alias testing_key --ks-pass pass:012345 java -jar $bundletool_jar_path install-apks --apks=build/app/outputs/bundle/release/app-release.apks $adb_path shell " am start -n io.flutter.integration.deferred_components_test/.MainActivity exit " run_start_time_seconds=$(date +%s) while read LOGLINE do if [[ "${LOGLINE}" == *"Running deferred code"* ]]; then echo "Found ${LOGLINE}" echo "All tests passed." pkill -P $$ exit 0 fi # Timeout if expected log not found current_time=$(date +%s) if [[ $((current_time - run_start_time_seconds)) -ge 300 ]]; then echo "Failure: Timed out, deferred component did not load." pkill -P $$ exit 1 fi done < <($adb_path logcat -T "$script_start_time") echo "Failure: Deferred component did not load." exit 1
flutter/dev/integration_tests/deferred_components_test/run_release_test.sh/0
{ "file_path": "flutter/dev/integration_tests/deferred_components_test/run_release_test.sh", "repo_id": "flutter", "token_count": 816 }
524
# flavors Integration test of build flavors (Android product flavors, Xcode schemes).
flutter/dev/integration_tests/flavors/README.md/0
{ "file_path": "flutter/dev/integration_tests/flavors/README.md", "repo_id": "flutter", "token_count": 20 }
525
// 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/app.dart'; Object? createGarbage() { final List<dynamic> garbage = <dynamic>[]; for (int index = 0; index < 1000; index += 1) { final List<int> moreGarbage = List<int>.filled(1000, index); if (index.isOdd) { garbage.add(moreGarbage); } } return garbage; } Future<void> main() async { // Create some garbage, and simulate some delays between that could be // plugin or network call related. final List<dynamic> garbage = <dynamic>[]; for (int index = 0; index < 20; index += 1) { final Object? moreGarbage = createGarbage(); if (index.isOdd) { garbage.add(moreGarbage); await Future<void>.delayed(const Duration(milliseconds: 7)); } } runApp(const GalleryApp()); }
flutter/dev/integration_tests/flutter_gallery/lib/delayed_main.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/delayed_main.dart", "repo_id": "flutter", "token_count": 324 }
526
// 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:intl/intl.dart'; import '../../gallery/demo.dart'; import 'cupertino_navigation_demo.dart' show coolColorNames; const double _kPickerSheetHeight = 216.0; const double _kPickerItemHeight = 32.0; class CupertinoPickerDemo extends StatefulWidget { const CupertinoPickerDemo({super.key}); static const String routeName = '/cupertino/picker'; @override State<CupertinoPickerDemo> createState() => _CupertinoPickerDemoState(); } class _BottomPicker extends StatelessWidget { const _BottomPicker({ required this.child, }); final Widget child; @override Widget build(BuildContext context) { return Container( height: _kPickerSheetHeight, padding: const EdgeInsets.only(top: 6.0), color: CupertinoColors.systemBackground.resolveFrom(context), child: DefaultTextStyle( style: TextStyle( color: CupertinoColors.label.resolveFrom(context), fontSize: 22.0, ), child: GestureDetector( // Blocks taps from propagating to the modal sheet and popping. onTap: () { }, child: SafeArea( top: false, child: child, ), ), ), ); } } class _Menu extends StatelessWidget { const _Menu({ required this.children, }); final List<Widget> children; @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration( color: CupertinoTheme.of(context).scaffoldBackgroundColor, border: const Border( top: BorderSide(color: Color(0xFFBCBBC1), width: 0.0), bottom: BorderSide(color: Color(0xFFBCBBC1), width: 0.0), ), ), height: 44.0, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: SafeArea( top: false, bottom: false, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: children, ), ), ), ); } } class _CupertinoPickerDemoState extends State<CupertinoPickerDemo> { int _selectedColorIndex = 0; Duration timer = Duration.zero; // Value that is shown in the date picker in date mode. DateTime date = DateTime.now(); // Value that is shown in the date picker in time mode. DateTime time = DateTime.now(); // Value that is shown in the date picker in dateAndTime mode. DateTime dateTime = DateTime.now(); Widget _buildColorPicker(BuildContext context) { final FixedExtentScrollController scrollController = FixedExtentScrollController(initialItem: _selectedColorIndex); return GestureDetector( onTap: () async { await showCupertinoModalPopup<void>( context: context, semanticsDismissible: true, builder: (BuildContext context) { return _BottomPicker( child: CupertinoPicker( scrollController: scrollController, itemExtent: _kPickerItemHeight, backgroundColor: CupertinoColors.systemBackground.resolveFrom(context), onSelectedItemChanged: (int index) { setState(() => _selectedColorIndex = index); }, children: List<Widget>.generate(coolColorNames.length, (int index) { return Center( child: Text(coolColorNames[index]), ); }), ), ); }, ); }, child: _Menu( children: <Widget>[ const Text('Favorite Color'), Text( coolColorNames[_selectedColorIndex], style: TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context)), ), ], ), ); } Widget _buildCountdownTimerPicker(BuildContext context) { return GestureDetector( onTap: () { showCupertinoModalPopup<void>( context: context, semanticsDismissible: true, builder: (BuildContext context) { return _BottomPicker( child: CupertinoTimerPicker( backgroundColor: CupertinoColors.systemBackground.resolveFrom(context), initialTimerDuration: timer, onTimerDurationChanged: (Duration newTimer) { setState(() => timer = newTimer); }, ), ); }, ); }, child: _Menu( children: <Widget>[ const Text('Countdown Timer'), Text( '${timer.inHours}:' '${(timer.inMinutes % 60).toString().padLeft(2,'0')}:' '${(timer.inSeconds % 60).toString().padLeft(2,'0')}', style: TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context)), ), ], ), ); } Widget _buildDatePicker(BuildContext context) { return GestureDetector( onTap: () { showCupertinoModalPopup<void>( context: context, semanticsDismissible: true, builder: (BuildContext context) { return _BottomPicker( child: CupertinoDatePicker( backgroundColor: CupertinoColors.systemBackground.resolveFrom(context), mode: CupertinoDatePickerMode.date, initialDateTime: date, onDateTimeChanged: (DateTime newDateTime) { setState(() => date = newDateTime); }, ), ); }, ); }, child: _Menu( children: <Widget>[ const Text('Date'), Text( DateFormat.yMMMMd().format(date), style: TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context)), ), ] ), ); } Widget _buildTimePicker(BuildContext context) { return GestureDetector( onTap: () { showCupertinoModalPopup<void>( context: context, semanticsDismissible: true, builder: (BuildContext context) { return _BottomPicker( child: CupertinoDatePicker( backgroundColor: CupertinoColors.systemBackground.resolveFrom(context), mode: CupertinoDatePickerMode.time, initialDateTime: time, onDateTimeChanged: (DateTime newDateTime) { setState(() => time = newDateTime); }, ), ); }, ); }, child: _Menu( children: <Widget>[ const Text('Time'), Text( DateFormat.jm().format(time), style: TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context)), ), ], ), ); } Widget _buildDateAndTimePicker(BuildContext context) { return GestureDetector( onTap: () { showCupertinoModalPopup<void>( context: context, semanticsDismissible: true, builder: (BuildContext context) { return _BottomPicker( child: CupertinoDatePicker( backgroundColor: CupertinoColors.systemBackground.resolveFrom(context), initialDateTime: dateTime, onDateTimeChanged: (DateTime newDateTime) { setState(() => dateTime = newDateTime); }, ), ); }, ); }, child: _Menu( children: <Widget>[ const Text('Date and Time'), Text( DateFormat.yMMMd().add_jm().format(dateTime), style: TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context)), ), ], ), ); } @override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( middle: const Text('Picker'), // We're specifying a back label here because the previous page is a // Material page. CupertinoPageRoutes could auto-populate these back // labels. previousPageTitle: 'Cupertino', trailing: CupertinoDemoDocumentationButton(CupertinoPickerDemo.routeName), ), child: DefaultTextStyle( style: CupertinoTheme.of(context).textTheme.textStyle, child: ListView( children: <Widget>[ const Padding(padding: EdgeInsets.only(top: 32.0)), _buildColorPicker(context), _buildCountdownTimerPicker(context), _buildDatePicker(context), _buildTimePicker(context), _buildDateAndTimePicker(context), ], ), ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_picker_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_picker_demo.dart", "repo_id": "flutter", "token_count": 4199 }
527
// 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 Dessert { Dessert(this.name, this.calories, this.fat, this.carbs, this.protein, this.sodium, this.calcium, this.iron); final String name; final int calories; final double fat; final int carbs; final double protein; final int sodium; final int calcium; final int iron; bool? selected = false; } class DessertDataSource extends DataTableSource { final List<Dessert> _desserts = <Dessert>[ Dessert('Frozen yogurt', 159, 6.0, 24, 4.0, 87, 14, 1), Dessert('Ice cream sandwich', 237, 9.0, 37, 4.3, 129, 8, 1), Dessert('Eclair', 262, 16.0, 24, 6.0, 337, 6, 7), Dessert('Cupcake', 305, 3.7, 67, 4.3, 413, 3, 8), Dessert('Gingerbread', 356, 15.0, 49, 3.9, 327, 7, 16), Dessert('Jelly bean', 375, 0.0, 94, 0.0, 50, 0, 0), Dessert('Lollipop', 392, 0.2, 98, 0.0, 38, 0, 2), Dessert('Honeycomb', 408, 3.2, 87, 6.5, 562, 0, 45), Dessert('Donut', 452, 25.0, 51, 4.9, 326, 2, 22), Dessert('KitKat', 518, 26.0, 65, 7.0, 54, 12, 6), Dessert('Frozen yogurt with sugar', 168, 6.0, 26, 4.0, 87, 14, 1), Dessert('Ice cream sandwich with sugar', 246, 9.0, 39, 4.3, 129, 8, 1), Dessert('Eclair with sugar', 271, 14.0, 26, 6.0, 337, 6, 7), Dessert('Cupcake with sugar', 314, 3.7, 69, 4.3, 413, 3, 8), Dessert('Gingerbread with sugar', 345, 13.0, 51, 3.9, 327, 7, 16), Dessert('Jelly bean with sugar', 364, 0.0, 96, 0.0, 50, 0, 0), Dessert('Lollipop with sugar', 401, 0.2, 100, 0.0, 38, 0, 2), Dessert('Honeycomb with sugar', 417, 3.2, 89, 6.5, 562, 0, 45), Dessert('Donut with sugar', 461, 25.0, 53, 4.9, 326, 2, 22), Dessert('KitKat with sugar', 527, 26.0, 67, 7.0, 54, 12, 6), Dessert('Frozen yogurt with honey', 223, 6.0, 36, 4.0, 87, 14, 1), Dessert('Ice cream sandwich with honey', 301, 9.0, 49, 4.3, 129, 8, 1), Dessert('Eclair with honey', 326, 12.0, 36, 6.0, 337, 6, 7), Dessert('Cupcake with honey', 369, 3.7, 79, 4.3, 413, 3, 8), Dessert('Gingerbread with honey', 420, 11.0, 61, 3.9, 327, 7, 16), Dessert('Jelly bean with honey', 439, 0.0, 106, 0.0, 50, 0, 0), Dessert('Lollipop with honey', 456, 0.2, 110, 0.0, 38, 0, 2), Dessert('Honeycomb with honey', 472, 3.2, 99, 6.5, 562, 0, 45), Dessert('Donut with honey', 516, 25.0, 63, 4.9, 326, 2, 22), Dessert('KitKat with honey', 582, 26.0, 77, 7.0, 54, 12, 6), Dessert('Frozen yogurt with milk', 262, 8.4, 36, 12.0, 194, 44, 1), Dessert('Ice cream sandwich with milk', 339, 11.4, 49, 12.3, 236, 38, 1), Dessert('Eclair with milk', 365, 18.4, 36, 14.0, 444, 36, 7), Dessert('Cupcake with milk', 408, 6.1, 79, 12.3, 520, 33, 8), Dessert('Gingerbread with milk', 459, 18.4, 61, 11.9, 434, 37, 16), Dessert('Jelly bean with milk', 478, 2.4, 106, 8.0, 157, 30, 0), Dessert('Lollipop with milk', 495, 2.6, 110, 8.0, 145, 30, 2), Dessert('Honeycomb with milk', 511, 5.6, 99, 14.5, 669, 30, 45), Dessert('Donut with milk', 555, 27.4, 63, 12.9, 433, 32, 22), Dessert('KitKat with milk', 621, 28.4, 77, 15.0, 161, 42, 6), Dessert('Coconut slice and frozen yogurt', 318, 21.0, 31, 5.5, 96, 14, 7), Dessert('Coconut slice and ice cream sandwich', 396, 24.0, 44, 5.8, 138, 8, 7), Dessert('Coconut slice and eclair', 421, 31.0, 31, 7.5, 346, 6, 13), Dessert('Coconut slice and cupcake', 464, 18.7, 74, 5.8, 422, 3, 14), Dessert('Coconut slice and gingerbread', 515, 31.0, 56, 5.4, 316, 7, 22), Dessert('Coconut slice and jelly bean', 534, 15.0, 101, 1.5, 59, 0, 6), Dessert('Coconut slice and lollipop', 551, 15.2, 105, 1.5, 47, 0, 8), Dessert('Coconut slice and honeycomb', 567, 18.2, 94, 8.0, 571, 0, 51), Dessert('Coconut slice and donut', 611, 40.0, 58, 6.4, 335, 2, 28), Dessert('Coconut slice and KitKat', 677, 41.0, 72, 8.5, 63, 12, 12), ]; void _sort<T>(Comparable<T> Function(Dessert d) getField, bool ascending) { _desserts.sort((Dessert a, Dessert b) { if (!ascending) { final Dessert c = a; a = b; b = c; } final Comparable<T> aValue = getField(a); final Comparable<T> bValue = getField(b); return Comparable.compare(aValue, bValue); }); notifyListeners(); } int _selectedCount = 0; @override DataRow? getRow(int index) { assert(index >= 0); if (index >= _desserts.length) { return null; } final Dessert dessert = _desserts[index]; return DataRow.byIndex( index: index, selected: dessert.selected!, onSelectChanged: (bool? value) { if (dessert.selected != value) { _selectedCount += value! ? 1 : -1; assert(_selectedCount >= 0); dessert.selected = value; notifyListeners(); } }, cells: <DataCell>[ DataCell(Text(dessert.name)), DataCell(Text('${dessert.calories}')), DataCell(Text(dessert.fat.toStringAsFixed(1))), DataCell(Text('${dessert.carbs}')), DataCell(Text(dessert.protein.toStringAsFixed(1))), DataCell(Text('${dessert.sodium}')), DataCell(Text('${dessert.calcium}%')), DataCell(Text('${dessert.iron}%')), ], ); } @override int get rowCount => _desserts.length; @override bool get isRowCountApproximate => false; @override int get selectedRowCount => _selectedCount; void _selectAll(bool? checked) { for (final Dessert dessert in _desserts) { dessert.selected = checked; } _selectedCount = checked! ? _desserts.length : 0; notifyListeners(); } } class DataTableDemo extends StatefulWidget { const DataTableDemo({super.key}); static const String routeName = '/material/data-table'; @override State<DataTableDemo> createState() => _DataTableDemoState(); } class _DataTableDemoState extends State<DataTableDemo> { int? _rowsPerPage = PaginatedDataTable.defaultRowsPerPage; int? _sortColumnIndex; bool _sortAscending = true; final DessertDataSource _dessertsDataSource = DessertDataSource(); void _sort<T>(Comparable<T> Function(Dessert d) getField, int columnIndex, bool ascending) { _dessertsDataSource._sort<T>(getField, ascending); setState(() { _sortColumnIndex = columnIndex; _sortAscending = ascending; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Data tables'), actions: <Widget>[ MaterialDemoDocumentationButton(DataTableDemo.routeName), ], ), body: Scrollbar( child: ListView( primary: true, padding: const EdgeInsets.all(20.0), children: <Widget>[ PaginatedDataTable( header: const Text('Nutrition'), rowsPerPage: _rowsPerPage!, onRowsPerPageChanged: (int? value) { setState(() { _rowsPerPage = value; }); }, sortColumnIndex: _sortColumnIndex, sortAscending: _sortAscending, onSelectAll: _dessertsDataSource._selectAll, columns: <DataColumn>[ DataColumn( label: const Text('Dessert (100g serving)'), onSort: (int columnIndex, bool ascending) => _sort<String>((Dessert d) => d.name, columnIndex, ascending), ), DataColumn( label: const Text('Calories'), tooltip: 'The total amount of food energy in the given serving size.', numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.calories, columnIndex, ascending), ), DataColumn( label: const Text('Fat (g)'), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.fat, columnIndex, ascending), ), DataColumn( label: const Text('Carbs (g)'), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.carbs, columnIndex, ascending), ), DataColumn( label: const Text('Protein (g)'), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.protein, columnIndex, ascending), ), DataColumn( label: const Text('Sodium (mg)'), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.sodium, columnIndex, ascending), ), DataColumn( label: const Text('Calcium (%)'), tooltip: 'The amount of calcium as a percentage of the recommended daily amount.', numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.calcium, columnIndex, ascending), ), DataColumn( label: const Text('Iron (%)'), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.iron, columnIndex, ascending), ), ], source: _dessertsDataSource, ), ], ), ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/material/data_table_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/data_table_demo.dart", "repo_id": "flutter", "token_count": 5398 }
528
// 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 _PageSelector extends StatelessWidget { const _PageSelector({ this.icons }); final List<Icon>? icons; void _handleArrowButtonPress(BuildContext context, int delta) { final TabController controller = DefaultTabController.of(context); if (!controller.indexIsChanging) { controller.animateTo((controller.index + delta).clamp(0, icons!.length - 1)); } } @override Widget build(BuildContext context) { final TabController? controller = DefaultTabController.maybeOf(context); final Color color = Theme.of(context).colorScheme.secondary; return SafeArea( top: false, bottom: false, child: Column( children: <Widget>[ Container( margin: const EdgeInsets.only(top: 16.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ IconButton( icon: const Icon(Icons.chevron_left), color: color, onPressed: () { _handleArrowButtonPress(context, -1); }, tooltip: 'Page back', ), TabPageSelector(controller: controller), IconButton( icon: const Icon(Icons.chevron_right), color: color, onPressed: () { _handleArrowButtonPress(context, 1); }, tooltip: 'Page forward', ), ], ), ), Expanded( child: IconTheme( data: IconThemeData( size: 128.0, color: color, ), child: TabBarView( children: icons!.map<Widget>((Icon icon) { return Container( padding: const EdgeInsets.all(12.0), child: Card( child: Center( child: icon, ), ), ); }).toList(), ), ), ), ], ), ); } } class PageSelectorDemo extends StatelessWidget { const PageSelectorDemo({super.key}); static const String routeName = '/material/page-selector'; static final List<Icon> icons = <Icon>[ const Icon(Icons.event, semanticLabel: 'Event'), const Icon(Icons.home, semanticLabel: 'Home'), const Icon(Icons.android, semanticLabel: 'Android'), const Icon(Icons.alarm, semanticLabel: 'Alarm'), const Icon(Icons.face, semanticLabel: 'Face'), const Icon(Icons.language, semanticLabel: 'Language'), ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Page selector'), actions: <Widget>[MaterialDemoDocumentationButton(routeName)], ), body: DefaultTabController( length: icons.length, child: _PageSelector(icons: icons), ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/material/page_selector_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/page_selector_demo.dart", "repo_id": "flutter", "token_count": 1510 }
529
// 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:scoped_model/scoped_model.dart'; import 'colors.dart'; import 'model/app_state_model.dart'; import 'model/product.dart'; class CategoryMenuPage extends StatelessWidget { const CategoryMenuPage({ super.key, this.onCategoryTap, }); final VoidCallback? onCategoryTap; Widget _buildCategory(Category category, BuildContext context) { final String categoryString = category.toString().replaceAll('Category.', '').toUpperCase(); final ThemeData theme = Theme.of(context); return ScopedModelDescendant<AppStateModel>( builder: (BuildContext context, Widget? child, AppStateModel model) => GestureDetector( onTap: () { model.setCategory(category); onCategoryTap?.call(); }, child: model.selectedCategory == category ? Column( children: <Widget>[ const SizedBox(height: 16.0), Text( categoryString, style: theme.textTheme.bodyLarge, textAlign: TextAlign.center, ), const SizedBox(height: 14.0), Container( width: 70.0, height: 2.0, color: kShrinePink400, ), ], ) : Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: Text( categoryString, style: theme.textTheme.bodyLarge!.copyWith( color: kShrineBrown900.withAlpha(153) ), textAlign: TextAlign.center, ), ), ), ); } @override Widget build(BuildContext context) { return Center( child: Container( padding: const EdgeInsets.only(top: 40.0), color: kShrinePink100, child: ListView( children: Category.values.map((Category c) => _buildCategory(c, context)).toList(), ), ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/category_menu_page.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/category_menu_page.dart", "repo_id": "flutter", "token_count": 1176 }
530
// 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'; // A generic widget for a list of selectable colors. @immutable class ColorPicker extends StatelessWidget { const ColorPicker({ super.key, required this.colors, required this.selectedColor, this.onColorSelection, }); final Set<Color> colors; final Color selectedColor; final ValueChanged<Color>? onColorSelection; @override Widget build (BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: colors.map((Color color) { return _ColorPickerSwatch( color: color, selected: color == selectedColor, onTap: () { onColorSelection?.call(color); }, ); }).toList(), ); } } // A single selectable color widget in the ColorPicker. @immutable class _ColorPickerSwatch extends StatelessWidget { const _ColorPickerSwatch({ required this.color, required this.selected, this.onTap, }); final Color color; final bool selected; final VoidCallback? onTap; @override Widget build (BuildContext context) { return Container( width: 60.0, height: 60.0, padding: const EdgeInsets.fromLTRB(2.0, 0.0, 2.0, 0.0), child: RawMaterialButton( fillColor: color, onPressed: () { onTap?.call(); }, child: !selected ? null : const Icon( Icons.check, color: Colors.white, ), ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/transformations/transformations_demo_color_picker.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/transformations/transformations_demo_color_picker.dart", "repo_id": "flutter", "token_count": 659 }
531
// 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 'about.dart'; import 'scales.dart'; @immutable class GalleryOptions { const GalleryOptions({ this.themeMode, this.textScaleFactor, this.visualDensity, this.textDirection = TextDirection.ltr, this.timeDilation = 1.0, this.platform, this.showOffscreenLayersCheckerboard = false, this.showRasterCacheImagesCheckerboard = false, this.showPerformanceOverlay = false, }); final ThemeMode? themeMode; final GalleryTextScaleValue? textScaleFactor; final GalleryVisualDensityValue? visualDensity; final TextDirection textDirection; final double timeDilation; final TargetPlatform? platform; final bool showPerformanceOverlay; final bool showRasterCacheImagesCheckerboard; final bool showOffscreenLayersCheckerboard; GalleryOptions copyWith({ ThemeMode? themeMode, GalleryTextScaleValue? textScaleFactor, GalleryVisualDensityValue? visualDensity, TextDirection? textDirection, double? timeDilation, TargetPlatform? platform, bool? showPerformanceOverlay, bool? showRasterCacheImagesCheckerboard, bool? showOffscreenLayersCheckerboard, }) { return GalleryOptions( themeMode: themeMode ?? this.themeMode, textScaleFactor: textScaleFactor ?? this.textScaleFactor, visualDensity: visualDensity ?? this.visualDensity, textDirection: textDirection ?? this.textDirection, timeDilation: timeDilation ?? this.timeDilation, platform: platform ?? this.platform, showPerformanceOverlay: showPerformanceOverlay ?? this.showPerformanceOverlay, showOffscreenLayersCheckerboard: showOffscreenLayersCheckerboard ?? this.showOffscreenLayersCheckerboard, showRasterCacheImagesCheckerboard: showRasterCacheImagesCheckerboard ?? this.showRasterCacheImagesCheckerboard, ); } @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is GalleryOptions && other.themeMode == themeMode && other.textScaleFactor == textScaleFactor && other.visualDensity == visualDensity && other.textDirection == textDirection && other.platform == platform && other.showPerformanceOverlay == showPerformanceOverlay && other.showRasterCacheImagesCheckerboard == showRasterCacheImagesCheckerboard && other.showOffscreenLayersCheckerboard == showRasterCacheImagesCheckerboard; } @override int get hashCode => Object.hash( themeMode, textScaleFactor, visualDensity, textDirection, timeDilation, platform, showPerformanceOverlay, showRasterCacheImagesCheckerboard, showOffscreenLayersCheckerboard, ); @override String toString() { return '$runtimeType($themeMode)'; } } const double _kItemHeight = 48.0; const EdgeInsetsDirectional _kItemPadding = EdgeInsetsDirectional.only(start: 56.0); class _OptionsItem extends StatelessWidget { const _OptionsItem({ this.child }); final Widget? child; @override Widget build(BuildContext context) { final double textScaleFactor = MediaQuery.textScalerOf(context).textScaleFactor; return MergeSemantics( child: Container( constraints: BoxConstraints(minHeight: _kItemHeight * textScaleFactor), padding: _kItemPadding, alignment: AlignmentDirectional.centerStart, child: DefaultTextStyle( style: DefaultTextStyle.of(context).style, maxLines: 2, overflow: TextOverflow.fade, child: IconTheme( data: Theme.of(context).primaryIconTheme, child: child!, ), ), ), ); } } class _BooleanItem extends StatelessWidget { const _BooleanItem(this.title, this.value, this.onChanged, { this.switchKey }); final String title; final bool value; final ValueChanged<bool> onChanged; // [switchKey] is used for accessing the switch from driver tests. final Key? switchKey; @override Widget build(BuildContext context) { final bool isDark = Theme.of(context).brightness == Brightness.dark; return _OptionsItem( child: Row( children: <Widget>[ Expanded(child: Text(title)), Switch( key: switchKey, value: value, onChanged: onChanged, activeColor: const Color(0xFF39CEFD), activeTrackColor: isDark ? Colors.white30 : Colors.black26, ), ], ), ); } } class _ActionItem extends StatelessWidget { const _ActionItem(this.text, this.onTap); final String text; final VoidCallback? onTap; @override Widget build(BuildContext context) { return _OptionsItem( child: _TextButton( onPressed: onTap, child: Text(text), ), ); } } class _TextButton extends StatelessWidget { const _TextButton({ this.onPressed, this.child }); final VoidCallback? onPressed; final Widget? child; @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); return TextButton( style: TextButton.styleFrom( foregroundColor: theme.colorScheme.onPrimary, textStyle: theme.textTheme.titleMedium, padding: EdgeInsets.zero, ), onPressed: onPressed, child: child!, ); } } class _Heading extends StatelessWidget { const _Heading(this.text); final String text; @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); return _OptionsItem( child: DefaultTextStyle( style: theme.textTheme.titleLarge!.copyWith( fontFamily: 'GoogleSans', color: theme.colorScheme.onPrimary, fontWeight: FontWeight.w700, ), child: Semantics( header: true, child: Text(text), ), ), ); } } class _ThemeModeItem extends StatelessWidget { const _ThemeModeItem(this.options, this.onOptionsChanged); final GalleryOptions? options; final ValueChanged<GalleryOptions>? onOptionsChanged; static final Map<ThemeMode, String> modeLabels = <ThemeMode, String>{ ThemeMode.system: 'System Default', ThemeMode.light: 'Light', ThemeMode.dark: 'Dark', }; @override Widget build(BuildContext context) { return _OptionsItem( child: Row( children: <Widget>[ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ const Text('Theme'), Text( modeLabels[options!.themeMode!]!, style: Theme.of(context).primaryTextTheme.bodyMedium, ), ], ), ), PopupMenuButton<ThemeMode>( padding: const EdgeInsetsDirectional.only(end: 16.0), icon: const Icon(Icons.arrow_drop_down), initialValue: options!.themeMode, itemBuilder: (BuildContext context) { return ThemeMode.values.map<PopupMenuItem<ThemeMode>>((ThemeMode mode) { return PopupMenuItem<ThemeMode>( value: mode, child: Text(modeLabels[mode]!), ); }).toList(); }, onSelected: (ThemeMode mode) { onOptionsChanged!( options!.copyWith(themeMode: mode), ); }, ), ], ), ); } } class _TextScaleFactorItem extends StatelessWidget { const _TextScaleFactorItem(this.options, this.onOptionsChanged); final GalleryOptions? options; final ValueChanged<GalleryOptions>? onOptionsChanged; @override Widget build(BuildContext context) { return _OptionsItem( child: Row( children: <Widget>[ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ const Text('Text size'), Text( options!.textScaleFactor!.label, style: Theme.of(context).primaryTextTheme.bodyMedium, ), ], ), ), PopupMenuButton<GalleryTextScaleValue>( padding: const EdgeInsetsDirectional.only(end: 16.0), icon: const Icon(Icons.arrow_drop_down), itemBuilder: (BuildContext context) { return kAllGalleryTextScaleValues.map<PopupMenuItem<GalleryTextScaleValue>>((GalleryTextScaleValue scaleValue) { return PopupMenuItem<GalleryTextScaleValue>( value: scaleValue, child: Text(scaleValue.label), ); }).toList(); }, onSelected: (GalleryTextScaleValue scaleValue) { onOptionsChanged!( options!.copyWith(textScaleFactor: scaleValue), ); }, ), ], ), ); } } class _VisualDensityItem extends StatelessWidget { const _VisualDensityItem(this.options, this.onOptionsChanged); final GalleryOptions? options; final ValueChanged<GalleryOptions>? onOptionsChanged; @override Widget build(BuildContext context) { return _OptionsItem( child: Row( children: <Widget>[ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ const Text('Visual density'), Text( options!.visualDensity!.label, style: Theme.of(context).primaryTextTheme.bodyMedium, ), ], ), ), PopupMenuButton<GalleryVisualDensityValue>( padding: const EdgeInsetsDirectional.only(end: 16.0), icon: const Icon(Icons.arrow_drop_down), itemBuilder: (BuildContext context) { return kAllGalleryVisualDensityValues.map<PopupMenuItem<GalleryVisualDensityValue>>((GalleryVisualDensityValue densityValue) { return PopupMenuItem<GalleryVisualDensityValue>( value: densityValue, child: Text(densityValue.label), ); }).toList(); }, onSelected: (GalleryVisualDensityValue densityValue) { onOptionsChanged!( options!.copyWith(visualDensity: densityValue), ); }, ), ], ), ); } } class _TextDirectionItem extends StatelessWidget { const _TextDirectionItem(this.options, this.onOptionsChanged); final GalleryOptions? options; final ValueChanged<GalleryOptions>? onOptionsChanged; @override Widget build(BuildContext context) { return _BooleanItem( 'Force RTL', options!.textDirection == TextDirection.rtl, (bool value) { onOptionsChanged!( options!.copyWith( textDirection: value ? TextDirection.rtl : TextDirection.ltr, ), ); }, switchKey: const Key('text_direction'), ); } } class _TimeDilationItem extends StatelessWidget { const _TimeDilationItem(this.options, this.onOptionsChanged); final GalleryOptions? options; final ValueChanged<GalleryOptions>? onOptionsChanged; @override Widget build(BuildContext context) { return _BooleanItem( 'Slow motion', options!.timeDilation != 1.0, (bool value) { onOptionsChanged!( options!.copyWith( timeDilation: value ? 20.0 : 1.0, ), ); }, switchKey: const Key('slow_motion'), ); } } class _PlatformItem extends StatelessWidget { const _PlatformItem(this.options, this.onOptionsChanged); final GalleryOptions? options; final ValueChanged<GalleryOptions>? onOptionsChanged; String _platformLabel(TargetPlatform platform) { return switch (platform) { TargetPlatform.android => 'Mountain View', TargetPlatform.fuchsia => 'Fuchsia', TargetPlatform.iOS => 'Cupertino', TargetPlatform.linux => 'Material Desktop (linux)', TargetPlatform.macOS => 'Material Desktop (macOS)', TargetPlatform.windows => 'Material Desktop (Windows)', }; } @override Widget build(BuildContext context) { return _OptionsItem( child: Row( children: <Widget>[ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ const Text('Platform mechanics'), Text( _platformLabel(options!.platform!), style: Theme.of(context).primaryTextTheme.bodyMedium, ), ], ), ), PopupMenuButton<TargetPlatform>( padding: const EdgeInsetsDirectional.only(end: 16.0), icon: const Icon(Icons.arrow_drop_down), itemBuilder: (BuildContext context) { return TargetPlatform.values.map((TargetPlatform platform) { return PopupMenuItem<TargetPlatform>( value: platform, child: Text(_platformLabel(platform)), ); }).toList(); }, onSelected: (TargetPlatform platform) { onOptionsChanged!( options!.copyWith(platform: platform), ); }, ), ], ), ); } } class GalleryOptionsPage extends StatelessWidget { const GalleryOptionsPage({ super.key, this.options, this.onOptionsChanged, this.onSendFeedback, }); final GalleryOptions? options; final ValueChanged<GalleryOptions>? onOptionsChanged; final VoidCallback? onSendFeedback; List<Widget> _enabledDiagnosticItems() { // Boolean showFoo options with a value of null: don't display // the showFoo option at all. if (options == null) { return const <Widget>[]; } return <Widget>[ const Divider(), const _Heading('Diagnostics'), _BooleanItem( 'Highlight offscreen layers', options!.showOffscreenLayersCheckerboard, (bool value) { onOptionsChanged!(options!.copyWith(showOffscreenLayersCheckerboard: value)); }, ), _BooleanItem( 'Highlight raster cache images', options!.showRasterCacheImagesCheckerboard, (bool value) { onOptionsChanged!(options!.copyWith(showRasterCacheImagesCheckerboard: value)); }, ), _BooleanItem( 'Show performance overlay', options!.showPerformanceOverlay, (bool value) { onOptionsChanged!(options!.copyWith(showPerformanceOverlay: value)); }, ), ]; } @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); return DefaultTextStyle( style: theme.primaryTextTheme.titleMedium!, child: ListView( padding: const EdgeInsets.only(bottom: 124.0), children: <Widget>[ const _Heading('Display'), _ThemeModeItem(options, onOptionsChanged), _TextScaleFactorItem(options, onOptionsChanged), _VisualDensityItem(options, onOptionsChanged), _TextDirectionItem(options, onOptionsChanged), _TimeDilationItem(options, onOptionsChanged), const Divider(), const ExcludeSemantics(child: _Heading('Platform mechanics')), _PlatformItem(options, onOptionsChanged), ..._enabledDiagnosticItems(), const Divider(), const _Heading('Flutter gallery'), _ActionItem('About Flutter Gallery', () { showGalleryAboutDialog(context); }), _ActionItem('Send feedback', onSendFeedback), ], ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/gallery/options.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/gallery/options.dart", "repo_id": "flutter", "token_count": 6777 }
532
// 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/demo/material/chip_demo.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Chip demo has semantic labels', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp( theme: ThemeData(platform: TargetPlatform.iOS), home: const ChipDemo(), )); expect(tester.getSemantics(find.byIcon(Icons.vignette)), matchesSemantics( isButton: true, hasEnabledState: true, isEnabled: true, isFocusable: true, hasTapAction: true, label: 'Update border shape', )); expect(tester.getSemantics(find.byIcon(Icons.refresh)), matchesSemantics( isButton: true, hasEnabledState: true, isEnabled: true, isFocusable: true, hasTapAction: true, label: 'Reset chips', )); handle.dispose(); }); }
flutter/dev/integration_tests/flutter_gallery/test/demo/material/chip_demo_test.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/test/demo/material/chip_demo_test.dart", "repo_id": "flutter", "token_count": 414 }
533
// 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_gallery/demo_lists.dart'; import 'package:flutter_test/flutter_test.dart'; /// The demos we don't run as part of the integration test. /// /// Demo names are formatted as 'DEMO_NAME@DEMO_CATEGORY' (see /// `demo_lists.dart` for more examples). final List<String> kSkippedDemos = <String>[ // This demo is flaky on CI due to hitting the network. // See: https://github.com/flutter/flutter/issues/100497 'Video@Media', ]; /// Scrolls each demo menu item into view, launches it, then returns to the /// home screen twice. Future<void> runDemos(List<String> demos, WidgetController controller) async { final Finder demoList = find.byType(Scrollable); String? currentDemoCategory; for (final String demo in demos) { if (kSkippedDemos.contains(demo)) { continue; } final String demoName = demo.substring(0, demo.indexOf('@')); final String demoCategory = demo.substring(demo.indexOf('@') + 1); print('> $demo'); await controller.pump(const Duration(milliseconds: 250)); final Finder demoCategoryItem = find.text(demoCategory); if (currentDemoCategory == null) { await controller.scrollUntilVisible(demoCategoryItem, 48.0); await controller.tap(demoCategoryItem); await controller.pumpAndSettle(); } else if (currentDemoCategory != demoCategory) { await controller.tap(find.byTooltip('Back')); await controller.pumpAndSettle(); await controller.scrollUntilVisible(demoCategoryItem, 48.0); await controller.tap(demoCategoryItem); await controller.pumpAndSettle(); // Scroll back to the top await controller.drag(demoList, const Offset(0.0, 10000.0)); await controller.pumpAndSettle(); } currentDemoCategory = demoCategory; Future<void> pageBack() { Finder backButton = find.byTooltip('Back'); if (backButton.evaluate().isEmpty) { backButton = find.byType(CupertinoNavigationBarBackButton); } return controller.tap(backButton); } for (int i = 0; i < 2; i += 1) { final Finder demoItem = find.text(demoName); await controller.scrollUntilVisible(demoItem, 48.0); await controller.pumpAndSettle(); if (demoItem.evaluate().isEmpty) { print('Failed to find $demoItem'); print('All available elements:'); print(controller.allElements.toList().join('\n')); print('App structure:'); debugDumpApp(); throw TestFailure('Failed to find element'); } await controller.tap(demoItem); // Launch the demo if (kUnsynchronizedDemos.contains(demo)) { // These tests have animation, pumpAndSettle cannot be used. // This time is questionable. 400ms is the tested reasonable result. await controller.pump(const Duration(milliseconds: 400)); await controller.pump(); await pageBack(); } else { await controller.pumpAndSettle(); // page back await pageBack(); } await controller.pumpAndSettle(); } print('< Success'); } // Return to the home screen await controller.tap(find.byTooltip('Back')); await controller.pumpAndSettle(); }
flutter/dev/integration_tests/flutter_gallery/test_driver/run_demos.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/test_driver/run_demos.dart", "repo_id": "flutter", "token_count": 1229 }
534
{ "images" : [ { "size" : "24x24", "idiom" : "watch", "scale" : "2x", "role" : "notificationCenter", "subtype" : "38mm" }, { "size" : "27.5x27.5", "idiom" : "watch", "scale" : "2x", "role" : "notificationCenter", "subtype" : "42mm" }, { "size" : "29x29", "idiom" : "watch", "role" : "companionSettings", "scale" : "2x" }, { "size" : "29x29", "idiom" : "watch", "role" : "companionSettings", "scale" : "3x" }, { "size" : "40x40", "idiom" : "watch", "scale" : "2x", "role" : "appLauncher", "subtype" : "38mm" }, { "size" : "44x44", "idiom" : "watch", "scale" : "2x", "role" : "appLauncher", "subtype" : "40mm" }, { "size" : "50x50", "idiom" : "watch", "scale" : "2x", "role" : "appLauncher", "subtype" : "44mm" }, { "size" : "86x86", "idiom" : "watch", "scale" : "2x", "role" : "quickLook", "subtype" : "38mm" }, { "size" : "98x98", "idiom" : "watch", "scale" : "2x", "role" : "quickLook", "subtype" : "42mm" }, { "size" : "108x108", "idiom" : "watch", "scale" : "2x", "role" : "quickLook", "subtype" : "44mm" }, { "idiom" : "watch-marketing", "size" : "1024x1024", "scale" : "1x" } ], "info" : { "version" : 1, "author" : "xcode" } }
flutter/dev/integration_tests/ios_app_with_extensions/ios/watch/Assets.xcassets/AppIcon.appiconset/Contents.json/0
{ "file_path": "flutter/dev/integration_tests/ios_app_with_extensions/ios/watch/Assets.xcassets/AppIcon.appiconset/Contents.json", "repo_id": "flutter", "token_count": 902 }
535
# iOS host app Used by the `module_test_ios.dart` device lab test. iOS 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. `flutterapp/lib/marquee.dart` and `flutterapp/lib/main.dart` must be copied into the new module `lib` for platform unit tests to pass. This application demonstrates some basic functionality for Add2App, along with a native iOS ViewController as a baseline and to demonstrate interaction. 1. A regular iOS view controller (UIViewController), similar to the default `flutter create` template (NativeViewController.m). 1. A FlutterViewController subclass that takes over the full screen. Demos showing this both from a cold/fresh engine state and a warm engine state (FullScreenViewController.m). 1. A demo of pushing a FlutterViewController on as a child view. 1. A demo of showing both the native and the Flutter views using a platform channel to interact with each other (HybridViewController.m). 1. A demo of showing two FlutterViewControllers simultaneously (DualViewController.m). A few key things are tested here (FlutterUITests.m): 1. The ability to pre-warm the engine and attach/detach a ViewController from it. 1. The ability to use platform channels to communicate between views. 1. The ability to simultaneously run two instances of the engine.
flutter/dev/integration_tests/ios_host_app/README.md/0
{ "file_path": "flutter/dev/integration_tests/ios_host_app/README.md", "repo_id": "flutter", "token_count": 377 }
536
# ios_platform_view_test A simple app contains: * A home with a button that pushes a new page into the scene. * A page contains a platform view, a button, and a text. * Press the button will update the text. We use this app to test platform views in general such as platform view creation, destruction, and thread merging(iOS only).
flutter/dev/integration_tests/ios_platform_view_tests/README.md/0
{ "file_path": "flutter/dev/integration_tests/ios_platform_view_tests/README.md", "repo_id": "flutter", "token_count": 90 }
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_driver/flutter_driver.dart'; import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; void main() { group('FlutterDriver', () { late FlutterDriver driver; setUpAll(() async { driver = await FlutterDriver.connect(); }); tearDownAll(() => driver.close()); test('Merge thread to create and remove platform views should not crash', () async { // Start pushing in a page with platform view, merge threads. final SerializableFinder platformViewButton = find.byValueKey('platform_view_button'); await driver.waitFor(platformViewButton); await driver.tap(platformViewButton); // Wait for the platform view page to show. final SerializableFinder plusButton = find.byValueKey('plus_button'); await driver.waitFor(plusButton); await driver.waitUntilNoTransientCallbacks(); // Tapping an elevated button runs an animation that pumps enough frames to un-merge the threads. await driver.tap(plusButton); await driver.waitUntilNoTransientCallbacks(); // Remove the page with platform view, merge threads again. final SerializableFinder backButton = find.pageBack(); await driver.tap(backButton); await driver.waitUntilNoTransientCallbacks(); final Health driverHealth = await driver.checkHealth(); expect(driverHealth.status, HealthStatus.ok); }, timeout: Timeout.none); test('Merge thread to create and remove platform views should not crash', () async { // Start pushing in a page with platform view, merge threads. final SerializableFinder platformViewButton = find.byValueKey('platform_view_button'); await driver.waitFor(platformViewButton); await driver.tap(platformViewButton); await driver.waitUntilNoTransientCallbacks(); // Remove the page with platform view, threads are still merged. final SerializableFinder backButton = find.pageBack(); await driver.tap(backButton); await driver.waitUntilNoTransientCallbacks(); // The animation of tapping a `ElevatedButton` should pump enough frames to un-merge the thread. final SerializableFinder unmergeButton = find.byValueKey('unmerge_button'); await driver.waitFor(unmergeButton); await driver.tap(unmergeButton); await driver.waitUntilNoTransientCallbacks(); final Health driverHealth = await driver.checkHealth(); expect(driverHealth.status, HealthStatus.ok); }, timeout: Timeout.none); }); }
flutter/dev/integration_tests/ios_platform_view_tests/test_driver/main_test.dart/0
{ "file_path": "flutter/dev/integration_tests/ios_platform_view_tests/test_driver/main_test.dart", "repo_id": "flutter", "token_count": 888 }
538
// 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:collection'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../codeviewer/code_displayer.dart'; import '../deferred_widget.dart'; import '../demos/cupertino/cupertino_demos.dart' deferred as cupertino_demos; import '../demos/cupertino/demo_types.dart'; import '../demos/material/material_demo_types.dart'; import '../demos/material/material_demos.dart' deferred as material_demos; import '../demos/reference/colors_demo.dart' deferred as colors_demo; import '../demos/reference/motion_demo_container_transition.dart' deferred as motion_demo_container; import '../demos/reference/motion_demo_fade_scale_transition.dart'; import '../demos/reference/motion_demo_fade_through_transition.dart'; import '../demos/reference/motion_demo_shared_x_axis_transition.dart'; import '../demos/reference/motion_demo_shared_y_axis_transition.dart'; import '../demos/reference/motion_demo_shared_z_axis_transition.dart'; import '../demos/reference/transformations_demo.dart' deferred as transformations_demo; import '../demos/reference/two_pane_demo.dart' deferred as twopane_demo; import '../demos/reference/typography_demo.dart' deferred as typography; import '../gallery_localizations.dart'; import '../gallery_localizations_en.dart'; import 'icons.dart'; const String _docsBaseUrl = 'https://api.flutter.dev/flutter'; const String _docsAnimationsUrl = 'https://pub.dev/documentation/animations/latest/animations'; enum GalleryDemoCategory { study, material, cupertino, other; @override String toString() { return name.toUpperCase(); } String? displayTitle(GalleryLocalizations localizations) { switch (this) { case GalleryDemoCategory.other: return localizations.homeCategoryReference; case GalleryDemoCategory.material: case GalleryDemoCategory.cupertino: return toString(); case GalleryDemoCategory.study: } return null; } } class GalleryDemo { const GalleryDemo({ required this.title, required this.category, required this.subtitle, // This parameter is required for studies. this.studyId, // Parameters below are required for non-study demos. this.slug, this.icon, this.configurations = const <GalleryDemoConfiguration>[], }) : assert(category == GalleryDemoCategory.study || (slug != null && icon != null)), assert(slug != null || studyId != null); final String title; final GalleryDemoCategory category; final String subtitle; final String? studyId; final String? slug; final IconData? icon; final List<GalleryDemoConfiguration> configurations; String get describe => '${slug ?? studyId}@${category.name}'; } TextSpan noOpCodeDisplayer(BuildContext context) { return const TextSpan(text: ''); } class GalleryDemoConfiguration { const GalleryDemoConfiguration({ required this.title, required this.description, required this.documentationUrl, required this.buildRoute, this.code = noOpCodeDisplayer, }); final String title; final String description; final String documentationUrl; final WidgetBuilder buildRoute; final CodeDisplayer code; } /// Awaits all deferred libraries for tests. Future<void> pumpDeferredLibraries() { final List<Future<void>> futures = <Future<void>>[ DeferredWidget.preload(cupertino_demos.loadLibrary), DeferredWidget.preload(material_demos.loadLibrary), DeferredWidget.preload(motion_demo_container.loadLibrary), DeferredWidget.preload(colors_demo.loadLibrary), DeferredWidget.preload(transformations_demo.loadLibrary), DeferredWidget.preload(typography.loadLibrary), ]; return Future.wait(futures); } class Demos { static Map<String?, GalleryDemo> asSlugToDemoMap(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return LinkedHashMap<String?, GalleryDemo>.fromIterable( all(localizations), // ignore: avoid_dynamic_calls key: (dynamic demo) => demo.slug as String?, ); } static List<GalleryDemo> all(GalleryLocalizations localizations) => studies(localizations).values.toList() + materialDemos(localizations) + cupertinoDemos(localizations) + otherDemos(localizations); static List<String> allDescriptions() => all(GalleryLocalizationsEn()).map((GalleryDemo demo) => demo.describe).toList(); static Map<String, GalleryDemo> studies(GalleryLocalizations localizations) { return <String, GalleryDemo>{ 'shrine': GalleryDemo( title: 'Shrine', subtitle: localizations.shrineDescription, category: GalleryDemoCategory.study, studyId: 'shrine', ), 'rally': GalleryDemo( title: 'Rally', subtitle: localizations.rallyDescription, category: GalleryDemoCategory.study, studyId: 'rally', ), 'crane': GalleryDemo( title: 'Crane', subtitle: localizations.craneDescription, category: GalleryDemoCategory.study, studyId: 'crane', ), 'fortnightly': GalleryDemo( title: 'Fortnightly', subtitle: localizations.fortnightlyDescription, category: GalleryDemoCategory.study, studyId: 'fortnightly', ), 'reply': GalleryDemo( title: 'Reply', subtitle: localizations.replyDescription, category: GalleryDemoCategory.study, studyId: 'reply', ), 'starterApp': GalleryDemo( title: localizations.starterAppTitle, subtitle: localizations.starterAppDescription, category: GalleryDemoCategory.study, studyId: 'starter', ), }; } static List<GalleryDemo> materialDemos(GalleryLocalizations localizations) { final LibraryLoader materialDemosLibrary = material_demos.loadLibrary; return <GalleryDemo>[ GalleryDemo( title: localizations.demoAppBarTitle, icon: GalleryIcons.appbar, slug: 'app-bar', subtitle: localizations.demoAppBarSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoAppBarTitle, description: localizations.demoAppBarDescription, documentationUrl: '$_docsBaseUrl/material/AppBar-class.html', buildRoute: (_) => DeferredWidget( materialDemosLibrary, () => material_demos.AppBarDemo(), ), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoBannerTitle, icon: GalleryIcons.listsLeaveBehind, slug: 'banner', subtitle: localizations.demoBannerSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoBannerTitle, description: localizations.demoBannerDescription, documentationUrl: '$_docsBaseUrl/material/MaterialBanner-class.html', buildRoute: (_) => DeferredWidget( materialDemosLibrary, () => material_demos.BannerDemo(), ), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoBottomAppBarTitle, icon: GalleryIcons.bottomAppBar, slug: 'bottom-app-bar', subtitle: localizations.demoBottomAppBarSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoBottomAppBarTitle, description: localizations.demoBottomAppBarDescription, documentationUrl: '$_docsBaseUrl/material/BottomAppBar-class.html', buildRoute: (_) => DeferredWidget( materialDemosLibrary, () => material_demos.BottomAppBarDemo(), ), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoBottomNavigationTitle, icon: GalleryIcons.bottomNavigation, slug: 'bottom-navigation', subtitle: localizations.demoBottomNavigationSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoBottomNavigationPersistentLabels, description: localizations.demoBottomNavigationDescription, documentationUrl: '$_docsBaseUrl/material/BottomNavigationBar-class.html', buildRoute: (_) => DeferredWidget( materialDemosLibrary, () => material_demos.BottomNavigationDemo( type: BottomNavigationDemoType.withLabels, restorationId: 'bottom_navigation_labels_demo', )), ), GalleryDemoConfiguration( title: localizations.demoBottomNavigationSelectedLabel, description: localizations.demoBottomNavigationDescription, documentationUrl: '$_docsBaseUrl/material/BottomNavigationBar-class.html', buildRoute: (_) => DeferredWidget( materialDemosLibrary, () => material_demos.BottomNavigationDemo( type: BottomNavigationDemoType.withoutLabels, restorationId: 'bottom_navigation_without_labels_demo', )), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoBottomSheetTitle, icon: GalleryIcons.bottomSheets, slug: 'bottom-sheet', subtitle: localizations.demoBottomSheetSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoBottomSheetPersistentTitle, description: localizations.demoBottomSheetPersistentDescription, documentationUrl: '$_docsBaseUrl/material/BottomSheet-class.html', buildRoute: (_) => DeferredWidget( materialDemosLibrary, () => material_demos.BottomSheetDemo( type: BottomSheetDemoType.persistent, )), ), GalleryDemoConfiguration( title: localizations.demoBottomSheetModalTitle, description: localizations.demoBottomSheetModalDescription, documentationUrl: '$_docsBaseUrl/material/BottomSheet-class.html', buildRoute: (_) => DeferredWidget( materialDemosLibrary, () => material_demos.BottomSheetDemo( type: BottomSheetDemoType.modal, )), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoButtonTitle, icon: GalleryIcons.genericButtons, slug: 'button', subtitle: localizations.demoButtonSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoTextButtonTitle, description: localizations.demoTextButtonDescription, documentationUrl: '$_docsBaseUrl/material/TextButton-class.html', buildRoute: (_) => DeferredWidget(materialDemosLibrary, () => material_demos.ButtonDemo(type: ButtonDemoType.text)), ), GalleryDemoConfiguration( title: localizations.demoElevatedButtonTitle, description: localizations.demoElevatedButtonDescription, documentationUrl: '$_docsBaseUrl/material/ElevatedButton-class.html', buildRoute: (_) => DeferredWidget(materialDemosLibrary, () => material_demos.ButtonDemo(type: ButtonDemoType.elevated)), ), GalleryDemoConfiguration( title: localizations.demoOutlinedButtonTitle, description: localizations.demoOutlinedButtonDescription, documentationUrl: '$_docsBaseUrl/material/OutlinedButton-class.html', buildRoute: (_) => DeferredWidget(materialDemosLibrary, () => material_demos.ButtonDemo(type: ButtonDemoType.outlined)), ), GalleryDemoConfiguration( title: localizations.demoToggleButtonTitle, description: localizations.demoToggleButtonDescription, documentationUrl: '$_docsBaseUrl/material/ToggleButtons-class.html', buildRoute: (_) => DeferredWidget(materialDemosLibrary, () => material_demos.ButtonDemo(type: ButtonDemoType.toggle)), ), GalleryDemoConfiguration( title: localizations.demoFloatingButtonTitle, description: localizations.demoFloatingButtonDescription, documentationUrl: '$_docsBaseUrl/material/FloatingActionButton-class.html', buildRoute: (_) => DeferredWidget(materialDemosLibrary, () => material_demos.ButtonDemo(type: ButtonDemoType.floating)), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoCardTitle, icon: GalleryIcons.cards, slug: 'card', subtitle: localizations.demoCardSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoCardTitle, description: localizations.demoCardDescription, documentationUrl: '$_docsBaseUrl/material/Card-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.CardsDemo(), ), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoChipTitle, icon: GalleryIcons.chips, slug: 'chip', subtitle: localizations.demoChipSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoActionChipTitle, description: localizations.demoActionChipDescription, documentationUrl: '$_docsBaseUrl/material/ActionChip-class.html', buildRoute: (BuildContext context) => DeferredWidget(materialDemosLibrary, () => material_demos.ChipDemo(type: ChipDemoType.action)), ), GalleryDemoConfiguration( title: localizations.demoChoiceChipTitle, description: localizations.demoChoiceChipDescription, documentationUrl: '$_docsBaseUrl/material/ChoiceChip-class.html', buildRoute: (BuildContext context) => DeferredWidget(materialDemosLibrary, () => material_demos.ChipDemo(type: ChipDemoType.choice)), ), GalleryDemoConfiguration( title: localizations.demoFilterChipTitle, description: localizations.demoFilterChipDescription, documentationUrl: '$_docsBaseUrl/material/FilterChip-class.html', buildRoute: (BuildContext context) => DeferredWidget(materialDemosLibrary, () => material_demos.ChipDemo(type: ChipDemoType.filter)), ), GalleryDemoConfiguration( title: localizations.demoInputChipTitle, description: localizations.demoInputChipDescription, documentationUrl: '$_docsBaseUrl/material/InputChip-class.html', buildRoute: (BuildContext context) => DeferredWidget(materialDemosLibrary, () => material_demos.ChipDemo(type: ChipDemoType.input)), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoDataTableTitle, icon: GalleryIcons.dataTable, slug: 'data-table', subtitle: localizations.demoDataTableSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoDataTableTitle, description: localizations.demoDataTableDescription, documentationUrl: '$_docsBaseUrl/material/DataTable-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.DataTableDemo(), ), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoDialogTitle, icon: GalleryIcons.dialogs, slug: 'dialog', subtitle: localizations.demoDialogSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoAlertDialogTitle, description: localizations.demoAlertDialogDescription, documentationUrl: '$_docsBaseUrl/material/AlertDialog-class.html', buildRoute: (BuildContext context) => DeferredWidget(materialDemosLibrary, () => material_demos.DialogDemo(type: DialogDemoType.alert)), ), GalleryDemoConfiguration( title: localizations.demoAlertTitleDialogTitle, description: localizations.demoAlertDialogDescription, documentationUrl: '$_docsBaseUrl/material/AlertDialog-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.DialogDemo(type: DialogDemoType.alertTitle)), ), GalleryDemoConfiguration( title: localizations.demoSimpleDialogTitle, description: localizations.demoSimpleDialogDescription, documentationUrl: '$_docsBaseUrl/material/SimpleDialog-class.html', buildRoute: (BuildContext context) => DeferredWidget(materialDemosLibrary, () => material_demos.DialogDemo(type: DialogDemoType.simple)), ), GalleryDemoConfiguration( title: localizations.demoFullscreenDialogTitle, description: localizations.demoFullscreenDialogDescription, documentationUrl: '$_docsBaseUrl/widgets/PageRoute/fullscreenDialog.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.DialogDemo(type: DialogDemoType.fullscreen)), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoDividerTitle, icon: GalleryIcons.divider, slug: 'divider', subtitle: localizations.demoDividerSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoDividerTitle, description: localizations.demoDividerDescription, documentationUrl: '$_docsBaseUrl/material/Divider-class.html', buildRoute: (_) => DeferredWidget( materialDemosLibrary, () => material_demos.DividerDemo( type: DividerDemoType.horizontal)), ), GalleryDemoConfiguration( title: localizations.demoVerticalDividerTitle, description: localizations.demoDividerDescription, documentationUrl: '$_docsBaseUrl/material/VerticalDivider-class.html', buildRoute: (_) => DeferredWidget( materialDemosLibrary, () => material_demos.DividerDemo(type: DividerDemoType.vertical)), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoGridListsTitle, icon: GalleryIcons.gridOn, slug: 'grid-lists', subtitle: localizations.demoGridListsSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoGridListsImageOnlyTitle, description: localizations.demoGridListsDescription, documentationUrl: '$_docsBaseUrl/widgets/GridView-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.GridListDemo( type: GridListDemoType.imageOnly)), ), GalleryDemoConfiguration( title: localizations.demoGridListsHeaderTitle, description: localizations.demoGridListsDescription, documentationUrl: '$_docsBaseUrl/widgets/GridView-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.GridListDemo(type: GridListDemoType.header)), ), GalleryDemoConfiguration( title: localizations.demoGridListsFooterTitle, description: localizations.demoGridListsDescription, documentationUrl: '$_docsBaseUrl/widgets/GridView-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.GridListDemo(type: GridListDemoType.footer)), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoListsTitle, icon: GalleryIcons.listAlt, slug: 'lists', subtitle: localizations.demoListsSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoOneLineListsTitle, description: localizations.demoListsDescription, documentationUrl: '$_docsBaseUrl/material/ListTile-class.html', buildRoute: (BuildContext context) => DeferredWidget(materialDemosLibrary, () => material_demos.ListDemo(type: ListDemoType.oneLine)), ), GalleryDemoConfiguration( title: localizations.demoTwoLineListsTitle, description: localizations.demoListsDescription, documentationUrl: '$_docsBaseUrl/material/ListTile-class.html', buildRoute: (BuildContext context) => DeferredWidget(materialDemosLibrary, () => material_demos.ListDemo(type: ListDemoType.twoLine)), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoMenuTitle, icon: GalleryIcons.moreVert, slug: 'menu', subtitle: localizations.demoMenuSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoContextMenuTitle, description: localizations.demoMenuDescription, documentationUrl: '$_docsBaseUrl/material/PopupMenuItem-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.MenuDemo(type: MenuDemoType.contextMenu), ), ), GalleryDemoConfiguration( title: localizations.demoSectionedMenuTitle, description: localizations.demoMenuDescription, documentationUrl: '$_docsBaseUrl/material/PopupMenuItem-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.MenuDemo(type: MenuDemoType.sectionedMenu), ), ), GalleryDemoConfiguration( title: localizations.demoChecklistMenuTitle, description: localizations.demoMenuDescription, documentationUrl: '$_docsBaseUrl/material/CheckedPopupMenuItem-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.MenuDemo(type: MenuDemoType.checklistMenu), ), ), GalleryDemoConfiguration( title: localizations.demoSimpleMenuTitle, description: localizations.demoMenuDescription, documentationUrl: '$_docsBaseUrl/material/PopupMenuItem-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.MenuDemo(type: MenuDemoType.simpleMenu), ), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoNavigationDrawerTitle, icon: GalleryIcons.menu, slug: 'nav_drawer', subtitle: localizations.demoNavigationDrawerSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoNavigationDrawerTitle, description: localizations.demoNavigationDrawerDescription, documentationUrl: '$_docsBaseUrl/material/Drawer-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.NavDrawerDemo(), ), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoNavigationRailTitle, icon: GalleryIcons.navigationRail, slug: 'nav_rail', subtitle: localizations.demoNavigationRailSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoNavigationRailTitle, description: localizations.demoNavigationRailDescription, documentationUrl: '$_docsBaseUrl/material/NavigationRail-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.NavRailDemo(), ), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoPickersTitle, icon: GalleryIcons.event, slug: 'pickers', subtitle: localizations.demoPickersSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoDatePickerTitle, description: localizations.demoDatePickerDescription, documentationUrl: '$_docsBaseUrl/material/showDatePicker.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.PickerDemo(type: PickerDemoType.date), ), ), GalleryDemoConfiguration( title: localizations.demoTimePickerTitle, description: localizations.demoTimePickerDescription, documentationUrl: '$_docsBaseUrl/material/showTimePicker.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.PickerDemo(type: PickerDemoType.time), ), ), GalleryDemoConfiguration( title: localizations.demoDateRangePickerTitle, description: localizations.demoDateRangePickerDescription, documentationUrl: '$_docsBaseUrl/material/showDateRangePicker.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.PickerDemo(type: PickerDemoType.range), ), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoProgressIndicatorTitle, icon: GalleryIcons.progressActivity, slug: 'progress-indicator', subtitle: localizations.demoProgressIndicatorSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoCircularProgressIndicatorTitle, description: localizations.demoCircularProgressIndicatorDescription, documentationUrl: '$_docsBaseUrl/material/CircularProgressIndicator-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.ProgressIndicatorDemo( type: ProgressIndicatorDemoType.circular, ), ), ), GalleryDemoConfiguration( title: localizations.demoLinearProgressIndicatorTitle, description: localizations.demoLinearProgressIndicatorDescription, documentationUrl: '$_docsBaseUrl/material/LinearProgressIndicator-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.ProgressIndicatorDemo( type: ProgressIndicatorDemoType.linear, ), ), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoSelectionControlsTitle, icon: GalleryIcons.checkBox, slug: 'selection-controls', subtitle: localizations.demoSelectionControlsSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoSelectionControlsCheckboxTitle, description: localizations.demoSelectionControlsCheckboxDescription, documentationUrl: '$_docsBaseUrl/material/Checkbox-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.SelectionControlsDemo( type: SelectionControlsDemoType.checkbox, ), ), ), GalleryDemoConfiguration( title: localizations.demoSelectionControlsRadioTitle, description: localizations.demoSelectionControlsRadioDescription, documentationUrl: '$_docsBaseUrl/material/Radio-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.SelectionControlsDemo( type: SelectionControlsDemoType.radio, ), ), ), GalleryDemoConfiguration( title: localizations.demoSelectionControlsSwitchTitle, description: localizations.demoSelectionControlsSwitchDescription, documentationUrl: '$_docsBaseUrl/material/Switch-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.SelectionControlsDemo( type: SelectionControlsDemoType.switches, ), ), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoSlidersTitle, icon: GalleryIcons.sliders, slug: 'sliders', subtitle: localizations.demoSlidersSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoSlidersTitle, description: localizations.demoSlidersDescription, documentationUrl: '$_docsBaseUrl/material/Slider-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.SlidersDemo(type: SlidersDemoType.sliders), ), ), GalleryDemoConfiguration( title: localizations.demoRangeSlidersTitle, description: localizations.demoRangeSlidersDescription, documentationUrl: '$_docsBaseUrl/material/RangeSlider-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.SlidersDemo( type: SlidersDemoType.rangeSliders), ), ), GalleryDemoConfiguration( title: localizations.demoCustomSlidersTitle, description: localizations.demoCustomSlidersDescription, documentationUrl: '$_docsBaseUrl/material/SliderTheme-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.SlidersDemo( type: SlidersDemoType.customSliders), ), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoSnackbarsTitle, icon: GalleryIcons.snackbar, slug: 'snackbars', subtitle: localizations.demoSnackbarsSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoSnackbarsTitle, description: localizations.demoSnackbarsDescription, documentationUrl: '$_docsBaseUrl/material/SnackBar-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.SnackbarsDemo(), ), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoTabsTitle, icon: GalleryIcons.tabs, slug: 'tabs', subtitle: localizations.demoTabsSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoTabsScrollingTitle, description: localizations.demoTabsDescription, documentationUrl: '$_docsBaseUrl/material/TabBar-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.TabsDemo(type: TabsDemoType.scrollable), ), ), GalleryDemoConfiguration( title: localizations.demoTabsNonScrollingTitle, description: localizations.demoTabsDescription, documentationUrl: '$_docsBaseUrl/material/TabBar-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.TabsDemo(type: TabsDemoType.nonScrollable), ), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoTextFieldTitle, icon: GalleryIcons.textFieldsAlt, slug: 'text-field', subtitle: localizations.demoTextFieldSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoTextFieldTitle, description: localizations.demoTextFieldDescription, documentationUrl: '$_docsBaseUrl/material/TextField-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.TextFieldDemo(), ), ), ], category: GalleryDemoCategory.material, ), GalleryDemo( title: localizations.demoTooltipTitle, icon: GalleryIcons.tooltip, slug: 'tooltip', subtitle: localizations.demoTooltipSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoTooltipTitle, description: localizations.demoTooltipDescription, documentationUrl: '$_docsBaseUrl/material/Tooltip-class.html', buildRoute: (BuildContext context) => DeferredWidget( materialDemosLibrary, () => material_demos.TooltipDemo(), ), ), ], category: GalleryDemoCategory.material, ), ]; } static List<GalleryDemo> cupertinoDemos(GalleryLocalizations localizations) { final LibraryLoader cupertinoLoader = cupertino_demos.loadLibrary; return <GalleryDemo>[ GalleryDemo( title: localizations.demoCupertinoActivityIndicatorTitle, icon: GalleryIcons.cupertinoProgress, slug: 'cupertino-activity-indicator', subtitle: localizations.demoCupertinoActivityIndicatorSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoCupertinoActivityIndicatorTitle, description: localizations.demoCupertinoActivityIndicatorDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoActivityIndicator-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, () => cupertino_demos.CupertinoProgressIndicatorDemo(), ), ), ], category: GalleryDemoCategory.cupertino, ), GalleryDemo( title: localizations.demoCupertinoAlertsTitle, icon: GalleryIcons.dialogs, slug: 'cupertino-alerts', subtitle: localizations.demoCupertinoAlertsSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoCupertinoAlertTitle, description: localizations.demoCupertinoAlertDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoAlertDialog-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, () => cupertino_demos.CupertinoAlertDemo( type: AlertDemoType.alert)), ), GalleryDemoConfiguration( title: localizations.demoCupertinoAlertWithTitleTitle, description: localizations.demoCupertinoAlertDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoAlertDialog-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, () => cupertino_demos.CupertinoAlertDemo( type: AlertDemoType.alertTitle)), ), GalleryDemoConfiguration( title: localizations.demoCupertinoAlertButtonsTitle, description: localizations.demoCupertinoAlertDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoAlertDialog-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, () => cupertino_demos.CupertinoAlertDemo( type: AlertDemoType.alertButtons)), ), GalleryDemoConfiguration( title: localizations.demoCupertinoAlertButtonsOnlyTitle, description: localizations.demoCupertinoAlertDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoAlertDialog-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, () => cupertino_demos.CupertinoAlertDemo( type: AlertDemoType.alertButtonsOnly)), ), GalleryDemoConfiguration( title: localizations.demoCupertinoActionSheetTitle, description: localizations.demoCupertinoActionSheetDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoActionSheet-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, () => cupertino_demos.CupertinoAlertDemo( type: AlertDemoType.actionSheet)), ), ], category: GalleryDemoCategory.cupertino, ), GalleryDemo( title: localizations.demoCupertinoButtonsTitle, icon: GalleryIcons.genericButtons, slug: 'cupertino-buttons', subtitle: localizations.demoCupertinoButtonsSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoCupertinoButtonsTitle, description: localizations.demoCupertinoButtonsDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoButton-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, () => cupertino_demos.CupertinoButtonDemo(), ), ), ], category: GalleryDemoCategory.cupertino, ), GalleryDemo( title: localizations.demoCupertinoContextMenuTitle, icon: GalleryIcons.moreVert, slug: 'cupertino-context-menu', subtitle: localizations.demoCupertinoContextMenuSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoCupertinoContextMenuTitle, description: localizations.demoCupertinoContextMenuDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoContextMenu-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, () => cupertino_demos.CupertinoContextMenuDemo(), ), ), ], category: GalleryDemoCategory.cupertino, ), GalleryDemo( title: localizations.demoCupertinoNavigationBarTitle, icon: GalleryIcons.bottomSheetPersistent, slug: 'cupertino-navigation-bar', subtitle: localizations.demoCupertinoNavigationBarSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoCupertinoNavigationBarTitle, description: localizations.demoCupertinoNavigationBarDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoNavigationBar-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, () => cupertino_demos.CupertinoNavigationBarDemo(), ), ), ], category: GalleryDemoCategory.cupertino, ), GalleryDemo( title: localizations.demoCupertinoPickerTitle, icon: GalleryIcons.listAlt, slug: 'cupertino-picker', subtitle: localizations.demoCupertinoPickerSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoCupertinoPickerTitle, description: localizations.demoCupertinoPickerDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoDatePicker-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, // ignore: prefer_const_constructors () => cupertino_demos.CupertinoPickerDemo()), ), ], category: GalleryDemoCategory.cupertino, ), GalleryDemo( title: localizations.demoCupertinoScrollbarTitle, icon: GalleryIcons.listAlt, slug: 'cupertino-scrollbar', subtitle: localizations.demoCupertinoScrollbarSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoCupertinoScrollbarTitle, description: localizations.demoCupertinoScrollbarDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoScrollbar-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, // ignore: prefer_const_constructors () => cupertino_demos.CupertinoScrollbarDemo()), ), ], category: GalleryDemoCategory.cupertino, ), GalleryDemo( title: localizations.demoCupertinoSegmentedControlTitle, icon: GalleryIcons.tabs, slug: 'cupertino-segmented-control', subtitle: localizations.demoCupertinoSegmentedControlSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoCupertinoSegmentedControlTitle, description: localizations.demoCupertinoSegmentedControlDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoSegmentedControl-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, () => cupertino_demos.CupertinoSegmentedControlDemo(), ), ), ], category: GalleryDemoCategory.cupertino, ), GalleryDemo( title: localizations.demoCupertinoSliderTitle, icon: GalleryIcons.sliders, slug: 'cupertino-slider', subtitle: localizations.demoCupertinoSliderSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoCupertinoSliderTitle, description: localizations.demoCupertinoSliderDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoSlider-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, () => cupertino_demos.CupertinoSliderDemo(), ), ), ], category: GalleryDemoCategory.cupertino, ), GalleryDemo( title: localizations.demoSelectionControlsSwitchTitle, icon: GalleryIcons.cupertinoSwitch, slug: 'cupertino-switch', subtitle: localizations.demoCupertinoSwitchSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoSelectionControlsSwitchTitle, description: localizations.demoCupertinoSwitchDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoSwitch-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, () => cupertino_demos.CupertinoSwitchDemo(), ), ), ], category: GalleryDemoCategory.cupertino, ), GalleryDemo( title: localizations.demoCupertinoTabBarTitle, icon: GalleryIcons.bottomNavigation, slug: 'cupertino-tab-bar', subtitle: localizations.demoCupertinoTabBarSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoCupertinoTabBarTitle, description: localizations.demoCupertinoTabBarDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoTabBar-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, () => cupertino_demos.CupertinoTabBarDemo(), ), ), ], category: GalleryDemoCategory.cupertino, ), GalleryDemo( title: localizations.demoCupertinoTextFieldTitle, icon: GalleryIcons.textFieldsAlt, slug: 'cupertino-text-field', subtitle: localizations.demoCupertinoTextFieldSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoCupertinoTextFieldTitle, description: localizations.demoCupertinoTextFieldDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoTextField-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, () => cupertino_demos.CupertinoTextFieldDemo(), ), ), ], category: GalleryDemoCategory.cupertino, ), GalleryDemo( title: localizations.demoCupertinoSearchTextFieldTitle, icon: GalleryIcons.search, slug: 'cupertino-search-text-field', subtitle: localizations.demoCupertinoSearchTextFieldSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoCupertinoSearchTextFieldTitle, description: localizations.demoCupertinoSearchTextFieldDescription, documentationUrl: '$_docsBaseUrl/cupertino/CupertinoSearchTextField-class.html', buildRoute: (_) => DeferredWidget( cupertinoLoader, () => cupertino_demos.CupertinoSearchTextFieldDemo(), ), ), ], category: GalleryDemoCategory.cupertino, ), ]; } static List<GalleryDemo> otherDemos(GalleryLocalizations localizations) { return <GalleryDemo>[ GalleryDemo( title: localizations.demoTwoPaneTitle, icon: GalleryIcons.bottomSheetPersistent, slug: 'two-pane', subtitle: localizations.demoTwoPaneSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoTwoPaneFoldableLabel, description: localizations.demoTwoPaneFoldableDescription, documentationUrl: 'https://pub.dev/documentation/dual_screen/latest/dual_screen/TwoPane-class.html', buildRoute: (_) => DeferredWidget( twopane_demo.loadLibrary, () => twopane_demo.TwoPaneDemo( type: twopane_demo.TwoPaneDemoType.foldable, restorationId: 'two_pane_foldable', ), ), ), GalleryDemoConfiguration( title: localizations.demoTwoPaneTabletLabel, description: localizations.demoTwoPaneTabletDescription, documentationUrl: 'https://pub.dev/documentation/dual_screen/latest/dual_screen/TwoPane-class.html', buildRoute: (_) => DeferredWidget( twopane_demo.loadLibrary, () => twopane_demo.TwoPaneDemo( type: twopane_demo.TwoPaneDemoType.tablet, restorationId: 'two_pane_tablet', ), ), ), GalleryDemoConfiguration( title: localizations.demoTwoPaneSmallScreenLabel, description: localizations.demoTwoPaneSmallScreenDescription, documentationUrl: 'https://pub.dev/documentation/dual_screen/latest/dual_screen/TwoPane-class.html', buildRoute: (_) => DeferredWidget( twopane_demo.loadLibrary, () => twopane_demo.TwoPaneDemo( type: twopane_demo.TwoPaneDemoType.smallScreen, restorationId: 'two_pane_single', ), ), ), ], category: GalleryDemoCategory.other, ), GalleryDemo( title: localizations.demoMotionTitle, icon: GalleryIcons.animation, slug: 'motion', subtitle: localizations.demoMotionSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoContainerTransformTitle, description: localizations.demoContainerTransformDescription, documentationUrl: '$_docsAnimationsUrl/OpenContainer-class.html', buildRoute: (_) => DeferredWidget( motion_demo_container.loadLibrary, () => motion_demo_container.OpenContainerTransformDemo(), ), ), GalleryDemoConfiguration( title: localizations.demoSharedXAxisTitle, description: localizations.demoSharedAxisDescription, documentationUrl: '$_docsAnimationsUrl/SharedAxisTransition-class.html', buildRoute: (_) => const SharedXAxisTransitionDemo(), ), GalleryDemoConfiguration( title: localizations.demoSharedYAxisTitle, description: localizations.demoSharedAxisDescription, documentationUrl: '$_docsAnimationsUrl/SharedAxisTransition-class.html', buildRoute: (_) => const SharedYAxisTransitionDemo(), ), GalleryDemoConfiguration( title: localizations.demoSharedZAxisTitle, description: localizations.demoSharedAxisDescription, documentationUrl: '$_docsAnimationsUrl/SharedAxisTransition-class.html', buildRoute: (_) => const SharedZAxisTransitionDemo(), ), GalleryDemoConfiguration( title: localizations.demoFadeThroughTitle, description: localizations.demoFadeThroughDescription, documentationUrl: '$_docsAnimationsUrl/FadeThroughTransition-class.html', buildRoute: (_) => const FadeThroughTransitionDemo(), ), GalleryDemoConfiguration( title: localizations.demoFadeScaleTitle, description: localizations.demoFadeScaleDescription, documentationUrl: '$_docsAnimationsUrl/FadeScaleTransition-class.html', buildRoute: (_) => const FadeScaleTransitionDemo(), ), ], category: GalleryDemoCategory.other, ), GalleryDemo( title: localizations.demoColorsTitle, icon: GalleryIcons.colors, slug: 'colors', subtitle: localizations.demoColorsSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoColorsTitle, description: localizations.demoColorsDescription, documentationUrl: '$_docsBaseUrl/material/MaterialColor-class.html', buildRoute: (_) => DeferredWidget( colors_demo.loadLibrary, () => colors_demo.ColorsDemo(), ), ), ], category: GalleryDemoCategory.other, ), GalleryDemo( title: localizations.demoTypographyTitle, icon: GalleryIcons.customTypography, slug: 'typography', subtitle: localizations.demoTypographySubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demoTypographyTitle, description: localizations.demoTypographyDescription, documentationUrl: '$_docsBaseUrl/material/TextTheme-class.html', buildRoute: (_) => DeferredWidget( typography.loadLibrary, () => typography.TypographyDemo(), ), ), ], category: GalleryDemoCategory.other, ), GalleryDemo( title: localizations.demo2dTransformationsTitle, icon: GalleryIcons.gridOn, slug: '2d-transformations', subtitle: localizations.demo2dTransformationsSubtitle, configurations: <GalleryDemoConfiguration>[ GalleryDemoConfiguration( title: localizations.demo2dTransformationsTitle, description: localizations.demo2dTransformationsDescription, documentationUrl: '$_docsBaseUrl/widgets/GestureDetector-class.html', buildRoute: (_) => DeferredWidget( transformations_demo.loadLibrary, () => transformations_demo.TransformationsDemo(), ), ), ], category: GalleryDemoCategory.other, ), ]; } }
flutter/dev/integration_tests/new_gallery/lib/data/demos.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/data/demos.dart", "repo_id": "flutter", "token_count": 25527 }
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:flutter/cupertino.dart'; import '../../gallery_localizations.dart'; // BEGIN cupertinoNavigationDemo class _TabInfo { const _TabInfo(this.title, this.icon); final String title; final IconData icon; } class CupertinoTabBarDemo extends StatelessWidget { const CupertinoTabBarDemo({super.key}); @override Widget build(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; final List<_TabInfo> tabInfo = <_TabInfo>[ _TabInfo( localizations.cupertinoTabBarHomeTab, CupertinoIcons.home, ), _TabInfo( localizations.cupertinoTabBarChatTab, CupertinoIcons.conversation_bubble, ), _TabInfo( localizations.cupertinoTabBarProfileTab, CupertinoIcons.profile_circled, ), ]; return DefaultTextStyle( style: CupertinoTheme.of(context).textTheme.textStyle, child: CupertinoTabScaffold( restorationId: 'cupertino_tab_scaffold', tabBar: CupertinoTabBar( items: <BottomNavigationBarItem>[ for (final _TabInfo tabInfo in tabInfo) BottomNavigationBarItem( label: tabInfo.title, icon: Icon(tabInfo.icon), ), ], ), tabBuilder: (BuildContext context, int index) { return CupertinoTabView( restorationScopeId: 'cupertino_tab_view_$index', builder: (BuildContext context) => _CupertinoDemoTab( title: tabInfo[index].title, icon: tabInfo[index].icon, ), defaultTitle: tabInfo[index].title, ); }, ), ); } } class _CupertinoDemoTab extends StatelessWidget { const _CupertinoDemoTab({ required this.title, required this.icon, }); final String title; final IconData icon; @override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar(), backgroundColor: CupertinoColors.systemBackground, child: Center( child: Icon( icon, semanticLabel: title, size: 100, ), ), ); } } // END
flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_tab_bar_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_tab_bar_demo.dart", "repo_id": "flutter", "token_count": 1036 }
540
// 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 BottomNavigationDemoType { withLabels, withoutLabels, } enum BottomSheetDemoType { persistent, modal, } enum ButtonDemoType { text, elevated, outlined, toggle, floating, } enum ChipDemoType { action, choice, filter, input, } enum DialogDemoType { alert, alertTitle, simple, fullscreen, } enum GridListDemoType { imageOnly, header, footer, } enum ListDemoType { oneLine, twoLine, } enum MenuDemoType { contextMenu, sectionedMenu, simpleMenu, checklistMenu, } enum PickerDemoType { date, time, range, } enum ProgressIndicatorDemoType { circular, linear, } enum SelectionControlsDemoType { checkbox, radio, switches, } enum SlidersDemoType { sliders, rangeSliders, customSliders, } enum TabsDemoType { scrollable, nonScrollable, } enum DividerDemoType { horizontal, vertical, }
flutter/dev/integration_tests/new_gallery/lib/demos/material/material_demo_types.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/material/material_demo_types.dart", "repo_id": "flutter", "token_count": 384 }
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:animations/animations.dart'; import 'package:flutter/material.dart'; import '../../gallery_localizations.dart'; // BEGIN fadeThroughTransitionDemo class FadeThroughTransitionDemo extends StatefulWidget { const FadeThroughTransitionDemo({super.key}); @override State<FadeThroughTransitionDemo> createState() => _FadeThroughTransitionDemoState(); } class _FadeThroughTransitionDemoState extends State<FadeThroughTransitionDemo> { int _pageIndex = 0; final List<Widget> _pageList = <Widget>[ _AlbumsPage(), _PhotosPage(), _SearchPage(), ]; @override Widget build(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, title: Column( children: <Widget>[ Text(localizations.demoFadeThroughTitle), Text( '(${localizations.demoFadeThroughDemoInstructions})', style: Theme.of(context) .textTheme .titleSmall! .copyWith(color: Colors.white), ), ], ), ), body: PageTransitionSwitcher( transitionBuilder: ( Widget child, Animation<double> animation, Animation<double> secondaryAnimation, ) { return FadeThroughTransition( animation: animation, secondaryAnimation: secondaryAnimation, child: child, ); }, child: _pageList[_pageIndex], ), bottomNavigationBar: BottomNavigationBar( currentIndex: _pageIndex, onTap: (int selectedIndex) { setState(() { _pageIndex = selectedIndex; }); }, items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: const Icon(Icons.photo_library), label: localizations.demoFadeThroughAlbumsDestination, ), BottomNavigationBarItem( icon: const Icon(Icons.photo), label: localizations.demoFadeThroughPhotosDestination, ), BottomNavigationBarItem( icon: const Icon(Icons.search), label: localizations.demoFadeThroughSearchDestination, ), ], ), ); } } class _ExampleCard extends StatelessWidget { @override Widget build(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; final TextTheme textTheme = Theme.of(context).textTheme; return Expanded( child: Card( child: Stack( children: <Widget>[ Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Expanded( child: ColoredBox( color: Colors.black26, child: Padding( padding: const EdgeInsets.all(30), child: Ink.image( image: const AssetImage( 'placeholders/placeholder_image.png', package: 'flutter_gallery_assets', ), ), ), ), ), Padding( padding: const EdgeInsets.all(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( localizations.demoFadeThroughTextPlaceholder, style: textTheme.bodyLarge, ), Text( localizations.demoFadeThroughTextPlaceholder, style: textTheme.bodySmall, ), ], ), ), ], ), InkWell( splashColor: Colors.black38, onTap: () {}, ), ], ), ), ); } } class _AlbumsPage extends StatelessWidget { @override Widget build(BuildContext context) { return Column( children: <Widget>[ ...List<Widget>.generate( 3, (int index) => Expanded( child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ _ExampleCard(), _ExampleCard(), ], ), ), ), ], ); } } class _PhotosPage extends StatelessWidget { @override Widget build(BuildContext context) { return Column( children: <Widget>[ _ExampleCard(), _ExampleCard(), ], ); } } class _SearchPage extends StatelessWidget { @override Widget build(BuildContext context) { final GalleryLocalizations? localizations = GalleryLocalizations.of(context); return ListView.builder( itemBuilder: (BuildContext context, int index) { return ListTile( leading: Image.asset( 'placeholders/avatar_logo.png', package: 'flutter_gallery_assets', width: 40, ), title: Text('${localizations!.demoMotionListTileTitle} ${index + 1}'), subtitle: Text(localizations.demoMotionPlaceholderSubtitle), ); }, itemCount: 10, ); } } // END fadeThroughTransitionDemo
flutter/dev/integration_tests/new_gallery/lib/demos/reference/motion_demo_fade_through_transition.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/reference/motion_demo_fade_through_transition.dart", "repo_id": "flutter", "token_count": 2824 }
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. import 'dart:math'; import 'package:dual_screen/dual_screen.dart'; import 'package:flutter/material.dart'; import '../constants.dart'; import '../gallery_localizations.dart'; import '../layout/adaptive.dart'; import 'home.dart'; const double homePeekDesktop = 210.0; const double homePeekMobile = 60.0; class SplashPageAnimation extends InheritedWidget { const SplashPageAnimation({ super.key, required this.isFinished, required super.child, }); final bool isFinished; static SplashPageAnimation? of(BuildContext context) { return context.dependOnInheritedWidgetOfExactType(); } @override bool updateShouldNotify(SplashPageAnimation oldWidget) => true; } class SplashPage extends StatefulWidget { const SplashPage({ super.key, required this.child, }); final Widget child; @override State<SplashPage> createState() => _SplashPageState(); } class _SplashPageState extends State<SplashPage> with SingleTickerProviderStateMixin { late AnimationController _controller; late int _effect; final Random _random = Random(); // A map of the effect index to its duration. This duration is used to // determine how long to display the splash animation at launch. // // If a new effect is added, this map should be updated. final Map<int, int> _effectDurations = <int, int>{ 1: 5, 2: 4, 3: 4, 4: 5, 5: 5, 6: 4, 7: 4, 8: 4, 9: 3, 10: 6, }; bool get _isSplashVisible { return _controller.status == AnimationStatus.completed || _controller.status == AnimationStatus.forward; } @override void initState() { super.initState(); // If the number of included effects changes, this number should be changed. _effect = _random.nextInt(_effectDurations.length) + 1; _controller = AnimationController(duration: splashPageAnimationDuration, vsync: this) ..addListener(() { setState(() {}); }); } @override void dispose() { _controller.dispose(); super.dispose(); } Animation<RelativeRect> _getPanelAnimation( BuildContext context, BoxConstraints constraints, ) { final double height = constraints.biggest.height - (isDisplayDesktop(context) ? homePeekDesktop : homePeekMobile); return RelativeRectTween( begin: RelativeRect.fill, end: RelativeRect.fromLTRB(0, height, 0, 0), ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeInOut)); } @override Widget build(BuildContext context) { return NotificationListener<ToggleSplashNotification>( onNotification: (_) { _controller.forward(); return true; }, child: SplashPageAnimation( isFinished: _controller.status == AnimationStatus.dismissed, child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { final Animation<RelativeRect> animation = _getPanelAnimation(context, constraints); Widget frontLayer = widget.child; if (_isSplashVisible) { frontLayer = MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { _controller.reverse(); }, onVerticalDragEnd: (DragEndDetails details) { if (details.velocity.pixelsPerSecond.dy < -200) { _controller.reverse(); } }, child: IgnorePointer(child: frontLayer), ), ); } if (isDisplayDesktop(context)) { frontLayer = Padding( padding: const EdgeInsets.only(top: 136), child: ClipRRect( borderRadius: const BorderRadius.vertical( top: Radius.circular(40), ), child: frontLayer, ), ); } if (isDisplayFoldable(context)) { return TwoPane( startPane: frontLayer, endPane: GestureDetector( onTap: () { if (_isSplashVisible) { _controller.reverse(); } else { _controller.forward(); } }, child: _SplashBackLayer( isSplashCollapsed: !_isSplashVisible, effect: _effect), ), ); } else { return Stack( children: <Widget>[ _SplashBackLayer( isSplashCollapsed: !_isSplashVisible, effect: _effect, onTap: () { _controller.forward(); }, ), PositionedTransition( rect: animation, child: frontLayer, ), ], ); } }, ), ), ); } } class _SplashBackLayer extends StatelessWidget { const _SplashBackLayer({ required this.isSplashCollapsed, required this.effect, this.onTap, }); final bool isSplashCollapsed; final int effect; final GestureTapCallback? onTap; @override Widget build(BuildContext context) { final String effectAsset = 'splash_effects/splash_effect_$effect.gif'; final Image flutterLogo = Image.asset( 'assets/logo/flutter_logo.png', package: 'flutter_gallery_assets', ); Widget? child; if (isSplashCollapsed) { if (isDisplayDesktop(context)) { child = Padding( padding: const EdgeInsets.only(top: 50), child: Align( alignment: Alignment.topCenter, child: MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: onTap, child: flutterLogo, ), ), ), ); } if (isDisplayFoldable(context)) { child = ColoredBox( color: Theme.of(context).colorScheme.background, child: Stack( children: <Widget>[ Center( child: flutterLogo, ), Padding( padding: const EdgeInsets.only(top: 100.0), child: Center( child: Text( GalleryLocalizations.of(context)!.splashSelectDemo, ), ), ) ], ), ); } } else { child = Stack( children: <Widget>[ Center( child: Image.asset( effectAsset, package: 'flutter_gallery_assets', ), ), Center(child: flutterLogo), ], ); } return ExcludeSemantics( child: Material( // This is the background color of the gifs. color: const Color(0xFF030303), child: Padding( padding: EdgeInsets.only( bottom: isDisplayDesktop(context) ? homePeekDesktop : isDisplayFoldable(context) ? 0 : homePeekMobile, ), child: child, ), ), ); } }
flutter/dev/integration_tests/new_gallery/lib/pages/splash.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/pages/splash.dart", "repo_id": "flutter", "token_count": 3733 }
543
// 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:google_fonts/google_fonts.dart'; import '../../layout/letter_spacing.dart'; import 'colors.dart'; final ThemeData craneTheme = _buildCraneTheme(); IconThemeData _customIconTheme(IconThemeData original, Color color) { return original.copyWith(color: color); } ThemeData _buildCraneTheme() { final ThemeData base = ThemeData.light(); return base.copyWith( colorScheme: const ColorScheme.light().copyWith( primary: cranePurple800, secondary: craneRed700, error: craneErrorOrange, ), hintColor: craneWhite60, indicatorColor: cranePrimaryWhite, scaffoldBackgroundColor: cranePrimaryWhite, cardColor: cranePrimaryWhite, highlightColor: Colors.transparent, textTheme: _buildCraneTextTheme(base.textTheme), textSelectionTheme: const TextSelectionThemeData( selectionColor: cranePurple700, ), primaryTextTheme: _buildCraneTextTheme(base.primaryTextTheme), iconTheme: _customIconTheme(base.iconTheme, craneWhite60), primaryIconTheme: _customIconTheme(base.iconTheme, cranePrimaryWhite), ); } TextTheme _buildCraneTextTheme(TextTheme base) { return GoogleFonts.ralewayTextTheme( base.copyWith( displayLarge: base.displayLarge!.copyWith( fontWeight: FontWeight.w300, fontSize: 96, ), displayMedium: base.displayMedium!.copyWith( fontWeight: FontWeight.w400, fontSize: 60, ), displaySmall: base.displaySmall!.copyWith( fontWeight: FontWeight.w600, fontSize: 48, ), headlineMedium: base.headlineMedium!.copyWith( fontWeight: FontWeight.w600, fontSize: 34, ), headlineSmall: base.headlineSmall!.copyWith( fontWeight: FontWeight.w600, fontSize: 24, ), titleLarge: base.titleLarge!.copyWith( fontWeight: FontWeight.w600, fontSize: 20, ), titleMedium: base.titleMedium!.copyWith( fontWeight: FontWeight.w500, fontSize: 16, letterSpacing: letterSpacingOrNone(0.5), ), titleSmall: base.titleSmall!.copyWith( fontWeight: FontWeight.w600, fontSize: 12, color: craneGrey, ), bodyLarge: base.bodyLarge!.copyWith( fontWeight: FontWeight.w500, fontSize: 16, ), bodyMedium: base.bodyMedium!.copyWith( fontWeight: FontWeight.w400, fontSize: 14, ), labelLarge: base.labelLarge!.copyWith( fontWeight: FontWeight.w600, fontSize: 13, letterSpacing: letterSpacingOrNone(0.8), ), bodySmall: base.bodySmall!.copyWith( fontWeight: FontWeight.w500, fontSize: 12, color: craneGrey, ), labelSmall: base.labelSmall!.copyWith( fontWeight: FontWeight.w600, fontSize: 12, ), ), ); }
flutter/dev/integration_tests/new_gallery/lib/studies/crane/theme.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/crane/theme.dart", "repo_id": "flutter", "token_count": 1238 }
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 'package:flutter/widgets.dart'; import '../../../gallery_localizations.dart'; import '../charts/pie_chart.dart'; import '../data.dart'; import '../finance.dart'; import 'sidebar.dart'; /// A page that shows a summary of bills. class BillsView extends StatefulWidget { const BillsView({super.key}); @override State<BillsView> createState() => _BillsViewState(); } class _BillsViewState extends State<BillsView> with SingleTickerProviderStateMixin { @override Widget build(BuildContext context) { final List<BillData> items = DummyDataService.getBillDataList(context); final double dueTotal = sumBillDataPrimaryAmount(items); final double paidTotal = sumBillDataPaidAmount(items); final List<UserDetailData> detailItems = DummyDataService.getBillDetailList( context, dueTotal: dueTotal, paidTotal: paidTotal, ); return TabWithSidebar( restorationId: 'bills_view', mainView: FinancialEntityView( heroLabel: GalleryLocalizations.of(context)!.rallyBillsDue, heroAmount: dueTotal, segments: buildSegmentsFromBillItems(items), wholeAmount: dueTotal, financialEntityCards: buildBillDataListViews(items, context), ), sidebarItems: <Widget>[ for (final UserDetailData item in detailItems) SidebarItem(title: item.title, value: item.value) ], ); } }
flutter/dev/integration_tests/new_gallery/lib/studies/rally/tabs/bills.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/rally/tabs/bills.dart", "repo_id": "flutter", "token_count": 552 }
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 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:intl/intl.dart'; import 'package:scoped_model/scoped_model.dart'; import '../../gallery_localizations.dart'; import '../../layout/letter_spacing.dart'; import 'colors.dart'; import 'expanding_bottom_sheet.dart'; import 'model/app_state_model.dart'; import 'model/product.dart'; import 'theme.dart'; const double _startColumnWidth = 60.0; const String _ordinalSortKeyName = 'shopping_cart'; class ShoppingCartPage extends StatefulWidget { const ShoppingCartPage({super.key}); @override State<ShoppingCartPage> createState() => _ShoppingCartPageState(); } class _ShoppingCartPageState extends State<ShoppingCartPage> { List<Widget> _createShoppingCartRows(AppStateModel model) { return model.productsInCart.keys .map( (int id) => ShoppingCartRow( product: model.getProductById(id), quantity: model.productsInCart[id], onPressed: () { model.removeItemFromCart(id); }, ), ) .toList(); } @override Widget build(BuildContext context) { final ThemeData localTheme = Theme.of(context); return Scaffold( backgroundColor: shrinePink50, body: SafeArea( child: ScopedModelDescendant<AppStateModel>( builder: (BuildContext context, Widget? child, AppStateModel model) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; final ExpandingBottomSheetState? expandingBottomSheet = ExpandingBottomSheet.of(context); return Stack( children: <Widget>[ ListView( children: <Widget>[ Semantics( sortKey: const OrdinalSortKey(0, name: _ordinalSortKeyName), child: Row( children: <Widget>[ SizedBox( width: _startColumnWidth, child: IconButton( icon: const Icon(Icons.keyboard_arrow_down), onPressed: () => expandingBottomSheet!.close(), tooltip: localizations.shrineTooltipCloseCart, ), ), Text( localizations.shrineCartPageCaption, style: localTheme.textTheme.titleMedium! .copyWith(fontWeight: FontWeight.w600), ), const SizedBox(width: 16), Text( localizations.shrineCartItemCount( model.totalCartQuantity, ), ), ], ), ), const SizedBox(height: 16), Semantics( sortKey: const OrdinalSortKey(1, name: _ordinalSortKeyName), child: Column( children: _createShoppingCartRows(model), ), ), Semantics( sortKey: const OrdinalSortKey(2, name: _ordinalSortKeyName), child: ShoppingCartSummary(model: model), ), const SizedBox(height: 100), ], ), PositionedDirectional( bottom: 16, start: 16, end: 16, child: Semantics( sortKey: const OrdinalSortKey(3, name: _ordinalSortKeyName), child: ElevatedButton( style: ElevatedButton.styleFrom( shape: const BeveledRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(7)), ), backgroundColor: shrinePink100, ), onPressed: () { model.clearCart(); expandingBottomSheet!.close(); }, child: Padding( padding: const EdgeInsets.symmetric(vertical: 12), child: Text( localizations.shrineCartClearButtonCaption, style: TextStyle( letterSpacing: letterSpacingOrNone(largeLetterSpacing)), ), ), ), ), ), ], ); }, ), ), ); } } class ShoppingCartSummary extends StatelessWidget { const ShoppingCartSummary({ super.key, required this.model, }); final AppStateModel model; @override Widget build(BuildContext context) { final TextStyle smallAmountStyle = Theme.of(context).textTheme.bodyMedium!.copyWith(color: shrineBrown600); final TextStyle largeAmountStyle = Theme.of(context) .textTheme .headlineMedium! .copyWith(letterSpacing: letterSpacingOrNone(mediumLetterSpacing)); final NumberFormat formatter = NumberFormat.simpleCurrency( decimalDigits: 2, locale: Localizations.localeOf(context).toString(), ); final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return Row( children: <Widget>[ const SizedBox(width: _startColumnWidth), Expanded( child: Padding( padding: const EdgeInsetsDirectional.only(end: 16), child: Column( children: <Widget>[ MergeSemantics( child: Row( children: <Widget>[ SelectableText( localizations.shrineCartTotalCaption, ), Expanded( child: SelectableText( formatter.format(model.totalCost), style: largeAmountStyle, textAlign: TextAlign.end, ), ), ], ), ), const SizedBox(height: 16), MergeSemantics( child: Row( children: <Widget>[ SelectableText( localizations.shrineCartSubtotalCaption, ), Expanded( child: SelectableText( formatter.format(model.subtotalCost), style: smallAmountStyle, textAlign: TextAlign.end, ), ), ], ), ), const SizedBox(height: 4), MergeSemantics( child: Row( children: <Widget>[ SelectableText( localizations.shrineCartShippingCaption, ), Expanded( child: SelectableText( formatter.format(model.shippingCost), style: smallAmountStyle, textAlign: TextAlign.end, ), ), ], ), ), const SizedBox(height: 4), MergeSemantics( child: Row( children: <Widget>[ SelectableText( localizations.shrineCartTaxCaption, ), Expanded( child: SelectableText( formatter.format(model.tax), style: smallAmountStyle, textAlign: TextAlign.end, ), ), ], ), ), ], ), ), ), ], ); } } class ShoppingCartRow extends StatelessWidget { const ShoppingCartRow({ super.key, required this.product, required this.quantity, this.onPressed, }); final Product product; final int? quantity; final VoidCallback? onPressed; @override Widget build(BuildContext context) { final NumberFormat formatter = NumberFormat.simpleCurrency( decimalDigits: 0, locale: Localizations.localeOf(context).toString(), ); final ThemeData localTheme = Theme.of(context); final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return Padding( padding: const EdgeInsets.only(bottom: 16), child: Row( key: ValueKey<int>(product.id), crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Semantics( container: true, label: localizations .shrineScreenReaderRemoveProductButton(product.name(context)), button: true, enabled: true, child: ExcludeSemantics( child: SizedBox( width: _startColumnWidth, child: IconButton( icon: const Icon(Icons.remove_circle_outline), onPressed: onPressed, tooltip: localizations.shrineTooltipRemoveItem, ), ), ), ), Expanded( child: Padding( padding: const EdgeInsetsDirectional.only(end: 16), child: Column( children: <Widget>[ Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Image.asset( product.assetName, package: product.assetPackage, fit: BoxFit.cover, width: 75, height: 75, excludeFromSemantics: true, ), const SizedBox(width: 16), Expanded( child: MergeSemantics( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ MergeSemantics( child: Row( children: <Widget>[ Expanded( child: SelectableText( localizations .shrineProductQuantity(quantity!), ), ), SelectableText( localizations.shrineProductPrice( formatter.format(product.price), ), ), ], ), ), SelectableText( product.name(context), style: localTheme.textTheme.titleMedium! .copyWith(fontWeight: FontWeight.w600), ), ], ), ), ), ], ), const SizedBox(height: 16), const Divider( color: shrineBrown900, height: 10, ), ], ), ), ), ], ), ); } }
flutter/dev/integration_tests/new_gallery/lib/studies/shrine/shopping_cart.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/shrine/shopping_cart.dart", "repo_id": "flutter", "token_count": 7512 }
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 'package:collection/collection.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:gallery/data/demos.dart'; import 'package:gallery/gallery_localizations_en.dart'; bool _isUnique(List<String> list) { final Set<String> covered = <String>{}; for (final String element in list) { if (covered.contains(element)) { return false; } else { covered.add(element); } } return true; } const ListEquality<String> _stringListEquality = ListEquality<String>(); void main() { test('_isUnique works correctly', () { expect(_isUnique(<String>['a', 'b', 'c']), true); expect(_isUnique(<String>['a', 'c', 'a', 'b']), false); expect(_isUnique(<String>['a']), true); expect(_isUnique(<String>[]), true); }); test('Demo descriptions are unique and correct', () { final List<GalleryDemo> allDemos = Demos.all(GalleryLocalizationsEn()); final List<String> allDemoDescriptions = allDemos.map((GalleryDemo d) => d.describe).toList(); expect(_isUnique(allDemoDescriptions), true); expect( _stringListEquality.equals( allDemoDescriptions, Demos.allDescriptions(), ), true, ); }); test('Special demo descriptions are correct', () { final List<String> allDemos = Demos.allDescriptions(); final List<String> specialDemos = <String>[ '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', 'progress-indicator@material', 'cupertino-activity-indicator@cupertino', 'colors@other', ]; for (final String specialDemo in specialDemos) { expect(allDemos.contains(specialDemo), true); } }); }
flutter/dev/integration_tests/new_gallery/test/demo_descriptions_test.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/test/demo_descriptions_test.dart", "repo_id": "flutter", "token_count": 794 }
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 'package:flutter/material.dart'; import 'package:flutter_driver/driver_extension.dart'; import 'keys.dart' as keys; void main() { enableFlutterDriverExtension(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Keyboard & TextField', theme: ThemeData(primarySwatch: Colors.blue), home: const MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { final ScrollController _controller = ScrollController(); double offset = 0.0; @override void initState() { super.initState(); _controller.addListener(() { setState(() { offset = _controller.offset; }); }); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final bool isSoftKeyboardVisible = MediaQuery.of(context).viewInsets.bottom > 100; return Scaffold( body: Column( children: <Widget>[ Text('$offset', key: const ValueKey<String>(keys.kOffsetText), ), if (isSoftKeyboardVisible) const Text( 'keyboard visible', key: ValueKey<String>(keys.kKeyboardVisibleView), ), Expanded( child: ListView( key: const ValueKey<String>(keys.kListView), controller: _controller, children: <Widget>[ Container( height: MediaQuery.of(context).size.height, ), const TextField( key: ValueKey<String>(keys.kDefaultTextField), ), ], ), ), ], ), ); } }
flutter/dev/integration_tests/ui/lib/keyboard_textfield.dart/0
{ "file_path": "flutter/dev/integration_tests/ui/lib/keyboard_textfield.dart", "repo_id": "flutter", "token_count": 904 }
548
// 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_driver/flutter_driver.dart'; import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; void main() { group('FlutterDriver', () { final SerializableFinder presentText = find.text('present'); late FlutterDriver driver; setUpAll(() async { driver = await FlutterDriver.connect(); }); tearDownAll(() async { await driver.close(); }); test('waitFor should find text "present"', () async { await driver.waitFor(presentText); }, timeout: Timeout.none); test('waitForAbsent should time out waiting for text "present" to disappear', () async { await expectLater( () => driver.waitForAbsent(presentText, timeout: const Duration(seconds: 1)), throwsA(isA<DriverError>().having( (DriverError error) => error.message, 'message', contains('Timeout while executing waitForAbsent'), )), ); }, timeout: Timeout.none); test('waitForAbsent should resolve when text "present" disappears', () async { // Begin waiting for it to disappear final Completer<void> whenWaitForAbsentResolves = Completer<void>(); driver.waitForAbsent(presentText).then( whenWaitForAbsentResolves.complete, onError: whenWaitForAbsentResolves.completeError, ); // Wait 1 second then make it disappear await Future<void>.delayed(const Duration(seconds: 1)); await driver.tap(find.byValueKey('togglePresent')); // Ensure waitForAbsent resolves await whenWaitForAbsentResolves.future; }, timeout: Timeout.none); test('waitFor times out waiting for "present" to reappear', () async { await expectLater( () => driver.waitFor(presentText, timeout: const Duration(seconds: 1)), throwsA(isA<DriverError>().having( (DriverError error) => error.message, 'message', contains('Timeout while executing waitFor'), )), ); }, timeout: Timeout.none); test('waitFor should resolve when text "present" reappears', () async { // Begin waiting for it to reappear final Completer<void> whenWaitForResolves = Completer<void>(); driver.waitFor(presentText).then( whenWaitForResolves.complete, onError: whenWaitForResolves.completeError, ); // Wait 1 second then make it appear await Future<void>.delayed(const Duration(seconds: 1)); await driver.tap(find.byValueKey('togglePresent')); // Ensure waitFor resolves await whenWaitForResolves.future; }, timeout: Timeout.none); test('waitForAbsent resolves immediately when the element does not exist', () async { await driver.waitForAbsent(find.text('that does not exist')); }, timeout: Timeout.none); test('uses hit test to determine tappable elements', () async { final SerializableFinder a = find.byValueKey('a'); final SerializableFinder menu = find.byType('_DropdownMenu<Letter>'); // Dropdown is closed await driver.waitForAbsent(menu); // Open dropdown await driver.tap(a); await driver.waitFor(menu); // Close it again await driver.tap(a); await driver.waitForAbsent(menu); }, timeout: Timeout.none); test('enters text in a text field', () async { final SerializableFinder textField = find.byValueKey('enter-text-field'); await driver.tap(textField); await driver.enterText('Hello!'); await driver.waitFor(find.text('Hello!')); await driver.enterText('World!'); await driver.waitFor(find.text('World!')); }, timeout: Timeout.none); }); }
flutter/dev/integration_tests/ui/test_driver/driver_test.dart/0
{ "file_path": "flutter/dev/integration_tests/ui/test_driver/driver_test.dart", "repo_id": "flutter", "token_count": 1387 }
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/material.dart'; Future<void> main() async { runApp(const Directionality( textDirection: TextDirection.ltr, child: Scaffold( body: Center( child: Column( children: <Widget>[ Icon(Icons.ac_unit), Text('Hello, World', textDirection: TextDirection.ltr), ], ), ), ))); }
flutter/dev/integration_tests/web/lib/service_worker_test_cached_resources.dart/0
{ "file_path": "flutter/dev/integration_tests/web/lib/service_worker_test_cached_resources.dart", "repo_id": "flutter", "token_count": 219 }
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'; final GlobalKey<NavigatorState> navKey = GlobalKey(debugLabel: 'mainNavigator'); Map<String, WidgetBuilder>? appRoutes; final Map<String, WidgetBuilder> _defaultAppRoutes = <String, WidgetBuilder>{ '/': (BuildContext context) => Container(), }; void main() { runApp(MyApp(appRoutes ?? _defaultAppRoutes)); } class MyApp extends StatelessWidget { const MyApp(this.routes, {super.key}); final Map<String, WidgetBuilder> routes; @override Widget build(BuildContext context) { return MaterialApp( key: const Key('mainapp'), navigatorKey: navKey, theme: ThemeData(fontFamily: 'RobotoMono'), title: 'Integration Test App', routes: routes, ); } }
flutter/dev/integration_tests/web_e2e_tests/lib/url_strategy_main.dart/0
{ "file_path": "flutter/dev/integration_tests/web_e2e_tests/lib/url_strategy_main.dart", "repo_id": "flutter", "token_count": 307 }
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 'dart:async'; import 'dart:html' as html; import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'package:integration_test/integration_test.dart'; import 'package:web_e2e_tests/url_strategy_main.dart' as app; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('Can customize url strategy', (WidgetTester tester) async { final TestUrlStrategy strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry('initial state', null, '/'), ); setUrlStrategy(strategy); app.appRoutes = <String, WidgetBuilder>{ '/': (BuildContext context) => Container(), '/foo': (BuildContext context) => Container(), }; app.main(); await tester.pumpAndSettle(); // checking whether the previously set strategy is properly preserved expect(urlStrategy, strategy); expect(strategy.getPath(), '/'); final NavigatorState navigator = app.navKey.currentState!; navigator.pushNamed('/foo'); await tester.pump(); expect(strategy.getPath(), '/foo'); }); } /// This URL strategy mimics the browser's history as closely as possible /// while doing it all in memory with no interaction with the browser. /// /// It keeps a list of history entries and event listeners in memory and /// manipulates them in order to achieve the desired functionality. class TestUrlStrategy extends UrlStrategy { /// Creates an instance of [TestUrlStrategy] and populates it with a list /// that has [initialEntry] as the only item. TestUrlStrategy.fromEntry(TestHistoryEntry initialEntry) : _currentEntryIndex = 0, history = <TestHistoryEntry>[initialEntry]; @override String getPath() => currentEntry.url; @override dynamic getState() => currentEntry.state; int _currentEntryIndex; final List<TestHistoryEntry> history; TestHistoryEntry get currentEntry { assert(withinAppHistory); return history[_currentEntryIndex]; } set currentEntry(TestHistoryEntry entry) { assert(withinAppHistory); history[_currentEntryIndex] = entry; } /// Whether we are still within the history of the Flutter Web app. This /// remains true until we go back in history beyond the entry where the app /// started. bool get withinAppHistory => _currentEntryIndex >= 0; @override void pushState(dynamic state, String title, String url) { assert(withinAppHistory); _currentEntryIndex++; // When pushing a new state, we need to remove all entries that exist after // the current entry. // // If the user goes A -> B -> C -> D, then goes back to B and pushes a new // entry called E, we should end up with: A -> B -> E in the history list. history.removeRange(_currentEntryIndex, history.length); history.add(TestHistoryEntry(state, title, url)); } @override void replaceState(dynamic state, String title, String url) { assert(withinAppHistory); if (url == '') { url = currentEntry.url; } currentEntry = TestHistoryEntry(state, title, url); } @override Future<void> go(int count) { assert(withinAppHistory); // Browsers don't move in history immediately. They do it at the next // event loop. So let's simulate that. return _nextEventLoop(() { _currentEntryIndex = _currentEntryIndex + count; if (withinAppHistory) { _firePopStateEvent(); } }); } final List<html.EventListener> listeners = <html.EventListener>[]; @override ui.VoidCallback addPopStateListener(html.EventListener fn) { listeners.add(fn); return () { // Schedule a micro task here to avoid removing the listener during // iteration in [_firePopStateEvent]. scheduleMicrotask(() => listeners.remove(fn)); }; } /// Simulates the scheduling of a new event loop by creating a delayed future. /// Details explained here: https://webdev.dartlang.org/articles/performance/event-loop Future<void> _nextEventLoop(ui.VoidCallback callback) { return Future<void>.delayed(Duration.zero).then((_) => callback()); } /// Invokes all the attached event listeners in order of /// attaching. This method should be called asynchronously to make it behave /// like a real browser. void _firePopStateEvent() { assert(withinAppHistory); final html.PopStateEvent event = html.PopStateEvent( 'popstate', <String, dynamic>{'state': currentEntry.state}, ); for (int i = 0; i < listeners.length; i++) { listeners[i](event); } } @override String prepareExternalUrl(String internalUrl) => internalUrl; @override String toString() { final List<String> lines = <String>[]; for (int i = 0; i < history.length; i++) { final TestHistoryEntry entry = history[i]; lines.add(_currentEntryIndex == i ? '* $entry' : ' $entry'); } return '$runtimeType: [\n${lines.join('\n')}\n]'; } } class TestHistoryEntry { const TestHistoryEntry(this.state, this.title, this.url); final dynamic state; final String? title; final String url; @override String toString() { return '$runtimeType(state:$state, title:"$title", url:"$url")'; } }
flutter/dev/integration_tests/web_e2e_tests/test_driver/url_strategy_integration.dart/0
{ "file_path": "flutter/dev/integration_tests/web_e2e_tests/test_driver/url_strategy_integration.dart", "repo_id": "flutter", "token_count": 1760 }
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 'package:flutter_driver/flutter_driver.dart'; import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; void main() { test('Windows app starts and draws frame', () async { final FlutterDriver driver = await FlutterDriver.connect(printCommunication: true); final String result = await driver.requestData('verifyWindowVisibility'); expect(result, equals('success')); await driver.close(); }, timeout: Timeout.none); test('Windows app theme matches system theme', () async { final FlutterDriver driver = await FlutterDriver.connect(printCommunication: true); final String result = await driver.requestData('verifyTheme'); expect(result, equals('success')); await driver.close(); }, timeout: Timeout.none); test('Windows app template can convert string from UTF16 to UTF8', () async { final FlutterDriver driver = await FlutterDriver.connect(printCommunication: true); final String result = await driver.requestData('verifyStringConversion'); expect(result, equals('success')); await driver.close(); }, timeout: Timeout.none); }
flutter/dev/integration_tests/windows_startup_test/test_driver/main_test.dart/0
{ "file_path": "flutter/dev/integration_tests/windows_startup_test/test_driver/main_test.dart", "repo_id": "flutter", "token_count": 360 }
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 ExampleDragTarget extends StatefulWidget { const ExampleDragTarget({super.key}); @override ExampleDragTargetState createState() => ExampleDragTargetState(); } class ExampleDragTargetState extends State<ExampleDragTarget> { Color _color = Colors.grey; void _handleAccept(DragTargetDetails<Color> details) { setState(() { _color = details.data; }); } @override Widget build(BuildContext context) { return DragTarget<Color>( onAcceptWithDetails: _handleAccept, builder: (BuildContext context, List<Color?> data, List<dynamic> rejectedData) { return Container( height: 100.0, margin: const EdgeInsets.all(10.0), decoration: BoxDecoration( color: data.isEmpty ? _color : Colors.grey.shade200, border: Border.all( width: 3.0, color: data.isEmpty ? Colors.white : Colors.blue, ), ), ); }, ); } } class Dot extends StatefulWidget { const Dot({ super.key, this.color, this.size, this.child, this.tappable = false }); final Color? color; final double? size; final Widget? child; final bool tappable; @override DotState createState() => DotState(); } class DotState extends State<Dot> { int taps = 0; @override Widget build(BuildContext context) { return GestureDetector( onTap: widget.tappable ? () { setState(() { taps += 1; }); } : null, child: Container( width: widget.size, height: widget.size, decoration: BoxDecoration( color: widget.color, border: Border.all(width: taps.toDouble()), shape: BoxShape.circle, ), child: widget.child, ), ); } } class ExampleDragSource extends StatelessWidget { const ExampleDragSource({ super.key, this.color, this.heavy = false, this.under = true, this.child, }); final Color? color; final bool heavy; final bool under; final Widget? child; static const double kDotSize = 50.0; static const double kHeavyMultiplier = 1.5; static const double kFingerSize = 50.0; @override Widget build(BuildContext context) { double size = kDotSize; if (heavy) { size *= kHeavyMultiplier; } final Widget contents = DefaultTextStyle( style: Theme.of(context).textTheme.bodyMedium!, textAlign: TextAlign.center, child: Dot( color: color, size: size, child: Center(child: child), ), ); Widget feedback = Opacity( opacity: 0.75, child: contents, ); Offset feedbackOffset; DragAnchorStrategy dragAnchorStrategy; if (!under) { feedback = Transform( transform: Matrix4.identity() ..translate(-size / 2.0, -(size / 2.0 + kFingerSize)), child: feedback, ); feedbackOffset = const Offset(0.0, -kFingerSize); dragAnchorStrategy = pointerDragAnchorStrategy; } else { feedbackOffset = Offset.zero; dragAnchorStrategy = childDragAnchorStrategy; } if (heavy) { return LongPressDraggable<Color>( data: color, feedback: feedback, feedbackOffset: feedbackOffset, dragAnchorStrategy: dragAnchorStrategy, child: contents, ); } else { return Draggable<Color>( data: color, feedback: feedback, feedbackOffset: feedbackOffset, dragAnchorStrategy: dragAnchorStrategy, child: contents, ); } } } class DashOutlineCirclePainter extends CustomPainter { const DashOutlineCirclePainter(); static const int segments = 17; static const double deltaTheta = math.pi * 2 / segments; // radians static const double segmentArc = deltaTheta / 2.0; // radians static const double startOffset = 1.0; // radians @override void paint(Canvas canvas, Size size) { final double radius = size.shortestSide / 2.0; final Paint paint = Paint() ..color = const Color(0xFF000000) ..style = PaintingStyle.stroke ..strokeWidth = radius / 10.0; final Path path = Path(); final Rect box = Offset.zero & size; for (double theta = 0.0; theta < math.pi * 2.0; theta += deltaTheta) { path.addArc(box, theta + startOffset, segmentArc); } canvas.drawPath(path, paint); } @override bool shouldRepaint(DashOutlineCirclePainter oldDelegate) => false; } class MovableBall extends StatelessWidget { const MovableBall(this.position, this.ballPosition, this.callback, {super.key}); final int position; final int ballPosition; final ValueChanged<int> callback; static final GlobalKey kBallKey = GlobalKey(); static const double kBallSize = 50.0; @override Widget build(BuildContext context) { final Widget ball = DefaultTextStyle( style: Theme.of(context).primaryTextTheme.bodyMedium!, textAlign: TextAlign.center, child: Dot( key: kBallKey, color: Colors.blue.shade700, size: kBallSize, tappable: true, child: const Center(child: Text('BALL')), ), ); const Widget dashedBall = SizedBox( width: kBallSize, height: kBallSize, child: CustomPaint( painter: DashOutlineCirclePainter() ), ); if (position == ballPosition) { return Draggable<bool>( data: true, childWhenDragging: dashedBall, feedback: ball, maxSimultaneousDrags: 1, child: ball, ); } else { return DragTarget<bool>( onAcceptWithDetails: (DragTargetDetails<bool> data) { callback(position); }, builder: (BuildContext context, List<bool?> accepted, List<dynamic> rejected) { return dashedBall; }, ); } } } class DragAndDropApp extends StatefulWidget { const DragAndDropApp({super.key}); @override DragAndDropAppState createState() => DragAndDropAppState(); } class DragAndDropAppState extends State<DragAndDropApp> { int position = 1; void moveBall(int newPosition) { setState(() { position = newPosition; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Drag and Drop Flutter Demo'), ), body: Column( children: <Widget>[ Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ ExampleDragSource( color: Colors.yellow.shade300, child: const Text('under'), ), ExampleDragSource( color: Colors.green.shade300, under: false, heavy: true, child: const Text('long-press above'), ), ExampleDragSource( color: Colors.indigo.shade300, under: false, child: const Text('above'), ), ], ), ), const Expanded( child: Row( children: <Widget>[ Expanded(child: ExampleDragTarget()), Expanded(child: ExampleDragTarget()), Expanded(child: ExampleDragTarget()), Expanded(child: ExampleDragTarget()), ], ), ), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ MovableBall(1, position, moveBall), MovableBall(2, position, moveBall), MovableBall(3, position, moveBall), ], ), ), ], ), ); } } void main() { runApp(const MaterialApp( title: 'Drag and Drop Flutter Demo', home: DragAndDropApp(), )); }
flutter/dev/manual_tests/lib/drag_and_drop.dart/0
{ "file_path": "flutter/dev/manual_tests/lib/drag_and_drop.dart", "repo_id": "flutter", "token_count": 3508 }
554
{ "version": "v0_206", "md.comp.outlined-button.container.height": 40.0, "md.comp.outlined-button.container.shape": "md.sys.shape.corner.full", "md.comp.outlined-button.disabled.label-text.color": "onSurface", "md.comp.outlined-button.disabled.label-text.opacity": 0.38, "md.comp.outlined-button.disabled.outline.color": "onSurface", "md.comp.outlined-button.disabled.outline.opacity": 0.12, "md.comp.outlined-button.focus.indicator.color": "secondary", "md.comp.outlined-button.focus.indicator.outline.offset": "md.sys.state.focus-indicator.outer-offset", "md.comp.outlined-button.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness", "md.comp.outlined-button.focus.label-text.color": "primary", "md.comp.outlined-button.focus.outline.color": "primary", "md.comp.outlined-button.focus.state-layer.color": "primary", "md.comp.outlined-button.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.outlined-button.hover.label-text.color": "primary", "md.comp.outlined-button.hover.outline.color": "outline", "md.comp.outlined-button.hover.state-layer.color": "primary", "md.comp.outlined-button.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity", "md.comp.outlined-button.label-text.color": "primary", "md.comp.outlined-button.label-text.text-style": "labelLarge", "md.comp.outlined-button.outline.color": "outline", "md.comp.outlined-button.outline.width": 1.0, "md.comp.outlined-button.pressed.label-text.color": "primary", "md.comp.outlined-button.pressed.outline.color": "outline", "md.comp.outlined-button.pressed.state-layer.color": "primary", "md.comp.outlined-button.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity", "md.comp.outlined-button.with-icon.disabled.icon.color": "onSurface", "md.comp.outlined-button.with-icon.disabled.icon.opacity": 0.38, "md.comp.outlined-button.with-icon.focus.icon.color": "primary", "md.comp.outlined-button.with-icon.hover.icon.color": "primary", "md.comp.outlined-button.with-icon.icon.color": "primary", "md.comp.outlined-button.with-icon.icon.size": 18.0, "md.comp.outlined-button.with-icon.pressed.icon.color": "primary" }
flutter/dev/tools/gen_defaults/data/button_outlined.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/button_outlined.json", "repo_id": "flutter", "token_count": 838 }
555
{ "version": "v0_206", "md.comp.dialog.action.focus.label-text.color": "primary", "md.comp.dialog.action.focus.state-layer.color": "primary", "md.comp.dialog.action.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.dialog.action.hover.label-text.color": "primary", "md.comp.dialog.action.hover.state-layer.color": "primary", "md.comp.dialog.action.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity", "md.comp.dialog.action.label-text.color": "primary", "md.comp.dialog.action.label-text.text-style": "labelLarge", "md.comp.dialog.action.pressed.label-text.color": "primary", "md.comp.dialog.action.pressed.state-layer.color": "primary", "md.comp.dialog.action.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity", "md.comp.dialog.container.color": "surfaceContainerHigh", "md.comp.dialog.container.elevation": "md.sys.elevation.level3", "md.comp.dialog.container.shape": "md.sys.shape.corner.extra-large", "md.comp.dialog.headline.color": "onSurface", "md.comp.dialog.headline.text-style": "headlineSmall", "md.comp.dialog.supporting-text.color": "onSurfaceVariant", "md.comp.dialog.supporting-text.text-style": "bodyMedium", "md.comp.dialog.with-icon.icon.color": "secondary", "md.comp.dialog.with-icon.icon.size": 24.0 }
flutter/dev/tools/gen_defaults/data/dialog.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/dialog.json", "repo_id": "flutter", "token_count": 515 }
556
{ "version": "v0_206", "md.comp.navigation-drawer.active.focus.icon.color": "onSecondaryContainer", "md.comp.navigation-drawer.active.focus.label-text.color": "onSecondaryContainer", "md.comp.navigation-drawer.active.focus.state-layer.color": "onSecondaryContainer", "md.comp.navigation-drawer.active.hover.icon.color": "onSecondaryContainer", "md.comp.navigation-drawer.active.hover.label-text.color": "onSecondaryContainer", "md.comp.navigation-drawer.active.hover.state-layer.color": "onSecondaryContainer", "md.comp.navigation-drawer.active.icon.color": "onSecondaryContainer", "md.comp.navigation-drawer.active-indicator.color": "secondaryContainer", "md.comp.navigation-drawer.active-indicator.height": 56.0, "md.comp.navigation-drawer.active-indicator.shape": "md.sys.shape.corner.full", "md.comp.navigation-drawer.active-indicator.width": 336.0, "md.comp.navigation-drawer.active.label-text.color": "onSecondaryContainer", "md.comp.navigation-drawer.active.pressed.icon.color": "onSecondaryContainer", "md.comp.navigation-drawer.active.pressed.label-text.color": "onSecondaryContainer", "md.comp.navigation-drawer.active.pressed.state-layer.color": "onSecondaryContainer", "md.comp.navigation-drawer.bottom.container.shape": "md.sys.shape.corner.large.top", "md.comp.navigation-drawer.container.height": 100.0, "md.comp.navigation-drawer.container.shape": "md.sys.shape.corner.large.end", "md.comp.navigation-drawer.container.width": 360.0, "md.comp.navigation-drawer.focus.indicator.color": "secondary", "md.comp.navigation-drawer.focus.indicator.outline.offset": "md.sys.state.focus-indicator.inner-offset", "md.comp.navigation-drawer.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness", "md.comp.navigation-drawer.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.navigation-drawer.headline.color": "onSurfaceVariant", "md.comp.navigation-drawer.headline.text-style": "titleSmall", "md.comp.navigation-drawer.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity", "md.comp.navigation-drawer.icon.size": 24.0, "md.comp.navigation-drawer.inactive.focus.icon.color": "onSurface", "md.comp.navigation-drawer.inactive.focus.label-text.color": "onSurface", "md.comp.navigation-drawer.inactive.focus.state-layer.color": "onSurface", "md.comp.navigation-drawer.inactive.hover.icon.color": "onSurface", "md.comp.navigation-drawer.inactive.hover.label-text.color": "onSurface", "md.comp.navigation-drawer.inactive.hover.state-layer.color": "onSurface", "md.comp.navigation-drawer.inactive.icon.color": "onSurfaceVariant", "md.comp.navigation-drawer.inactive.label-text.color": "onSurfaceVariant", "md.comp.navigation-drawer.inactive.pressed.icon.color": "onSurface", "md.comp.navigation-drawer.inactive.pressed.label-text.color": "onSurface", "md.comp.navigation-drawer.inactive.pressed.state-layer.color": "onSecondaryContainer", "md.comp.navigation-drawer.label-text.text-style": "labelLarge", "md.comp.navigation-drawer.large-badge-label.color": "onSurfaceVariant", "md.comp.navigation-drawer.large-badge-label.text-style": "labelLarge", "md.comp.navigation-drawer.modal.container.color": "surfaceContainerLow", "md.comp.navigation-drawer.modal.container.elevation": "md.sys.elevation.level1", "md.comp.navigation-drawer.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity", "md.comp.navigation-drawer.standard.container.color": "surface", "md.comp.navigation-drawer.standard.container.elevation": "md.sys.elevation.level0" }
flutter/dev/tools/gen_defaults/data/navigation_drawer.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/navigation_drawer.json", "repo_id": "flutter", "token_count": 1324 }
557
{ "version": "v0_206", "md.comp.switch.disabled.selected.handle.color": "surface", "md.comp.switch.disabled.selected.handle.opacity": 1.0, "md.comp.switch.disabled.selected.icon.color": "onSurface", "md.comp.switch.disabled.selected.icon.opacity": 0.38, "md.comp.switch.disabled.selected.track.color": "onSurface", "md.comp.switch.disabled.track.opacity": 0.12, "md.comp.switch.disabled.unselected.handle.color": "onSurface", "md.comp.switch.disabled.unselected.handle.opacity": 0.38, "md.comp.switch.disabled.unselected.icon.color": "surfaceContainerHighest", "md.comp.switch.disabled.unselected.icon.opacity": 0.38, "md.comp.switch.disabled.unselected.track.color": "surfaceContainerHighest", "md.comp.switch.disabled.unselected.track.outline.color": "onSurface", "md.comp.switch.focus.indicator.color": "secondary", "md.comp.switch.focus.indicator.offset": "md.sys.state.focus-indicator.outer-offset", "md.comp.switch.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness", "md.comp.switch.handle.shape": "md.sys.shape.corner.full", "md.comp.switch.pressed.handle.height": 28.0, "md.comp.switch.pressed.handle.width": 28.0, "md.comp.switch.selected.focus.handle.color": "primaryContainer", "md.comp.switch.selected.focus.icon.color": "onPrimaryContainer", "md.comp.switch.selected.focus.state-layer.color": "primary", "md.comp.switch.selected.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.switch.selected.focus.track.color": "primary", "md.comp.switch.selected.handle.color": "onPrimary", "md.comp.switch.selected.handle.height": 24.0, "md.comp.switch.selected.handle.width": 24.0, "md.comp.switch.selected.hover.handle.color": "primaryContainer", "md.comp.switch.selected.hover.icon.color": "onPrimaryContainer", "md.comp.switch.selected.hover.state-layer.color": "primary", "md.comp.switch.selected.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity", "md.comp.switch.selected.hover.track.color": "primary", "md.comp.switch.selected.icon.color": "onPrimaryContainer", "md.comp.switch.selected.icon.size": 16.0, "md.comp.switch.selected.pressed.handle.color": "primaryContainer", "md.comp.switch.selected.pressed.icon.color": "onPrimaryContainer", "md.comp.switch.selected.pressed.state-layer.color": "primary", "md.comp.switch.selected.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity", "md.comp.switch.selected.pressed.track.color": "primary", "md.comp.switch.selected.track.color": "primary", "md.comp.switch.state-layer.shape": "md.sys.shape.corner.full", "md.comp.switch.state-layer.size": 40.0, "md.comp.switch.track.height": 32.0, "md.comp.switch.track.outline.width": 2.0, "md.comp.switch.track.shape": "md.sys.shape.corner.full", "md.comp.switch.track.width": 52.0, "md.comp.switch.unselected.focus.handle.color": "onSurfaceVariant", "md.comp.switch.unselected.focus.icon.color": "surfaceContainerHighest", "md.comp.switch.unselected.focus.state-layer.color": "onSurface", "md.comp.switch.unselected.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.switch.unselected.focus.track.color": "surfaceContainerHighest", "md.comp.switch.unselected.focus.track.outline.color": "outline", "md.comp.switch.unselected.handle.color": "outline", "md.comp.switch.unselected.handle.height": 16.0, "md.comp.switch.unselected.handle.width": 16.0, "md.comp.switch.unselected.hover.handle.color": "onSurfaceVariant", "md.comp.switch.unselected.hover.icon.color": "surfaceContainerHighest", "md.comp.switch.unselected.hover.state-layer.color": "onSurface", "md.comp.switch.unselected.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity", "md.comp.switch.unselected.hover.track.color": "surfaceContainerHighest", "md.comp.switch.unselected.hover.track.outline.color": "outline", "md.comp.switch.unselected.icon.color": "surfaceContainerHighest", "md.comp.switch.unselected.icon.size": 16.0, "md.comp.switch.unselected.pressed.handle.color": "onSurfaceVariant", "md.comp.switch.unselected.pressed.icon.color": "surfaceContainerHighest", "md.comp.switch.unselected.pressed.state-layer.color": "onSurface", "md.comp.switch.unselected.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity", "md.comp.switch.unselected.pressed.track.color": "surfaceContainerHighest", "md.comp.switch.unselected.pressed.track.outline.color": "outline", "md.comp.switch.unselected.track.color": "surfaceContainerHighest", "md.comp.switch.unselected.track.outline.color": "outline", "md.comp.switch.with-icon.handle.height": 24.0, "md.comp.switch.with-icon.handle.width": 24.0 }
flutter/dev/tools/gen_defaults/data/switch.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/switch.json", "repo_id": "flutter", "token_count": 1704 }
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. import 'template.dart'; class ButtonTemplate extends TokenTemplate { const ButtonTemplate(this.tokenGroup, super.blockName, super.fileName, super.tokens, { super.colorSchemePrefix = '_colors.', }); final String tokenGroup; String _backgroundColor() { if (tokenAvailable('$tokenGroup.container.color')) { return ''' MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return ${componentColor('$tokenGroup.disabled.container')}; } return ${componentColor('$tokenGroup.container')}; })'''; } return ''' const MaterialStatePropertyAll<Color>(Colors.transparent)'''; } String _elevation() { if (tokenAvailable('$tokenGroup.container.elevation')) { return ''' MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return ${elevation("$tokenGroup.disabled.container")}; } if (states.contains(MaterialState.pressed)) { return ${elevation("$tokenGroup.pressed.container")}; } if (states.contains(MaterialState.hovered)) { return ${elevation("$tokenGroup.hover.container")}; } if (states.contains(MaterialState.focused)) { return ${elevation("$tokenGroup.focus.container")}; } return ${elevation("$tokenGroup.container")}; })'''; } return ''' const MaterialStatePropertyAll<double>(0.0)'''; } String _elevationColor(String token) { if (tokenAvailable(token)) { return 'MaterialStatePropertyAll<Color>(${color(token)})'; } else { return 'const MaterialStatePropertyAll<Color>(Colors.transparent)'; } } @override String generate() => ''' class _${blockName}DefaultsM3 extends ButtonStyle { _${blockName}DefaultsM3(this.context) : super( animationDuration: kThemeChangeDuration, enableFeedback: true, alignment: Alignment.center, ); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; @override MaterialStateProperty<TextStyle?> get textStyle => MaterialStatePropertyAll<TextStyle?>(${textStyle("$tokenGroup.label-text")}); @override MaterialStateProperty<Color?>? get backgroundColor =>${_backgroundColor()}; @override MaterialStateProperty<Color?>? get foregroundColor => MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return ${componentColor('$tokenGroup.disabled.label-text')}; } return ${componentColor('$tokenGroup.label-text')}; }); @override MaterialStateProperty<Color?>? get overlayColor => MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return ${componentColor('$tokenGroup.pressed.state-layer')}; } if (states.contains(MaterialState.hovered)) { return ${componentColor('$tokenGroup.hover.state-layer')}; } if (states.contains(MaterialState.focused)) { return ${componentColor('$tokenGroup.focus.state-layer')}; } return null; }); @override MaterialStateProperty<Color>? get shadowColor => ${_elevationColor("$tokenGroup.container.shadow-color")}; @override MaterialStateProperty<Color>? get surfaceTintColor => ${_elevationColor("$tokenGroup.container.surface-tint-layer.color")}; @override MaterialStateProperty<double>? get elevation =>${_elevation()}; @override MaterialStateProperty<EdgeInsetsGeometry>? get padding => MaterialStatePropertyAll<EdgeInsetsGeometry>(_scaledPadding(context)); @override MaterialStateProperty<Size>? get minimumSize => const MaterialStatePropertyAll<Size>(Size(64.0, ${getToken("$tokenGroup.container.height")})); // No default fixedSize @override MaterialStateProperty<Size>? get maximumSize => const MaterialStatePropertyAll<Size>(Size.infinite); ${tokenAvailable("$tokenGroup.outline.color") ? ''' @override MaterialStateProperty<BorderSide>? get side => MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return ${border("$tokenGroup.disabled.outline")}; } if (states.contains(MaterialState.focused)) { return ${border('$tokenGroup.focus.outline')}; } return ${border("$tokenGroup.outline")}; });''' : ''' // No default side'''} @override MaterialStateProperty<OutlinedBorder>? get shape => const MaterialStatePropertyAll<OutlinedBorder>(${shape("$tokenGroup.container", '')}); @override MaterialStateProperty<MouseCursor?>? get mouseCursor => MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return SystemMouseCursors.basic; } return SystemMouseCursors.click; }); @override VisualDensity? get visualDensity => Theme.of(context).visualDensity; @override MaterialTapTargetSize? get tapTargetSize => Theme.of(context).materialTapTargetSize; @override InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory; } '''; }
flutter/dev/tools/gen_defaults/lib/button_template.dart/0
{ "file_path": "flutter/dev/tools/gen_defaults/lib/button_template.dart", "repo_id": "flutter", "token_count": 1854 }
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. import 'template.dart'; class MenuTemplate extends TokenTemplate { const MenuTemplate(super.blockName, super.fileName, super.tokens, { super.colorSchemePrefix = '_colors.', }); @override String generate() => ''' class _MenuBarDefaultsM3 extends MenuStyle { _MenuBarDefaultsM3(this.context) : super( elevation: const MaterialStatePropertyAll<double?>(${elevation('md.comp.menu.container')}), shape: const MaterialStatePropertyAll<OutlinedBorder>(_defaultMenuBorder), alignment: AlignmentDirectional.bottomStart, ); static const RoundedRectangleBorder _defaultMenuBorder = ${shape('md.comp.menu.container', '')}; final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; @override MaterialStateProperty<Color?> get backgroundColor { return MaterialStatePropertyAll<Color?>(${componentColor('md.comp.menu.container')}); } @override MaterialStateProperty<Color?>? get shadowColor { return MaterialStatePropertyAll<Color?>(${color('md.comp.menu.container.shadow-color')}); } @override MaterialStateProperty<Color?>? get surfaceTintColor { return const MaterialStatePropertyAll<Color?>(${colorOrTransparent('md.comp.menu.container.surface-tint-layer')}); } @override MaterialStateProperty<EdgeInsetsGeometry?>? get padding { return const MaterialStatePropertyAll<EdgeInsetsGeometry>( EdgeInsetsDirectional.symmetric( horizontal: _kTopLevelMenuHorizontalMinPadding ), ); } @override VisualDensity get visualDensity => Theme.of(context).visualDensity; } class _MenuButtonDefaultsM3 extends ButtonStyle { _MenuButtonDefaultsM3(this.context) : super( animationDuration: kThemeChangeDuration, enableFeedback: true, alignment: AlignmentDirectional.centerStart, ); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; late final TextTheme _textTheme = Theme.of(context).textTheme; @override MaterialStateProperty<Color?>? get backgroundColor { return ButtonStyleButton.allOrNull<Color>(Colors.transparent); } // No default shadow color // No default surface tint color @override MaterialStateProperty<double>? get elevation { return ButtonStyleButton.allOrNull<double>(0.0); } @override MaterialStateProperty<Color?>? get foregroundColor { return MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return ${componentColor('md.comp.list.list-item.disabled.label-text')}; } if (states.contains(MaterialState.pressed)) { return ${componentColor('md.comp.list.list-item.pressed.label-text')}; } if (states.contains(MaterialState.hovered)) { return ${componentColor('md.comp.list.list-item.hover.label-text')}; } if (states.contains(MaterialState.focused)) { return ${componentColor('md.comp.list.list-item.focus.label-text')}; } return ${componentColor('md.comp.list.list-item.label-text')}; }); } @override MaterialStateProperty<Color?>? get iconColor { return MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return ${componentColor('md.comp.list.list-item.disabled.leading-icon')}; } if (states.contains(MaterialState.pressed)) { return ${componentColor('md.comp.list.list-item.pressed.leading-icon.icon')}; } if (states.contains(MaterialState.hovered)) { return ${componentColor('md.comp.list.list-item.hover.leading-icon.icon')}; } if (states.contains(MaterialState.focused)) { return ${componentColor('md.comp.list.list-item.focus.leading-icon.icon')}; } return ${componentColor('md.comp.list.list-item.leading-icon')}; }); } // No default fixedSize @override MaterialStateProperty<Size>? get maximumSize { return ButtonStyleButton.allOrNull<Size>(Size.infinite); } @override MaterialStateProperty<Size>? get minimumSize { return ButtonStyleButton.allOrNull<Size>(const Size(64.0, 48.0)); } @override MaterialStateProperty<MouseCursor?>? get mouseCursor { return MaterialStateProperty.resolveWith( (Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return SystemMouseCursors.basic; } return SystemMouseCursors.click; }, ); } @override MaterialStateProperty<Color?>? get overlayColor { return MaterialStateProperty.resolveWith( (Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return ${componentColor('md.comp.list.list-item.pressed.state-layer')}; } if (states.contains(MaterialState.hovered)) { return ${componentColor('md.comp.list.list-item.hover.state-layer')}; } if (states.contains(MaterialState.focused)) { return ${componentColor('md.comp.list.list-item.focus.state-layer')}; } return Colors.transparent; }, ); } @override MaterialStateProperty<EdgeInsetsGeometry>? get padding { return ButtonStyleButton.allOrNull<EdgeInsetsGeometry>(_scaledPadding(context)); } // No default side @override MaterialStateProperty<OutlinedBorder>? get shape { return ButtonStyleButton.allOrNull<OutlinedBorder>(const RoundedRectangleBorder()); } @override InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory; @override MaterialTapTargetSize? get tapTargetSize => Theme.of(context).materialTapTargetSize; @override MaterialStateProperty<TextStyle?> get textStyle { // TODO(tahatesser): This is taken from https://m3.material.io/components/menus/specs // Update this when the token is available. return MaterialStatePropertyAll<TextStyle?>(_textTheme.labelLarge); } @override VisualDensity? get visualDensity => Theme.of(context).visualDensity; // The horizontal padding number comes from the spec. EdgeInsetsGeometry _scaledPadding(BuildContext context) { VisualDensity visualDensity = Theme.of(context).visualDensity; // When horizontal VisualDensity is greater than zero, set it to zero // because the [ButtonStyleButton] has already handle the padding based on the density. // However, the [ButtonStyleButton] doesn't allow the [VisualDensity] adjustment // to reduce the width of the left/right padding, so we need to handle it here if // the density is less than zero, such as on desktop platforms. if (visualDensity.horizontal > 0) { visualDensity = VisualDensity(vertical: visualDensity.vertical); } // Since the threshold paddings used below are empirical values determined // at a font size of 14.0, 14.0 is used as the base value for scaling the // padding. final double fontSize = Theme.of(context).textTheme.labelLarge?.fontSize ?? 14.0; final double fontSizeRatio = MediaQuery.textScalerOf(context).scale(fontSize) / 14.0; return ButtonStyleButton.scaledPadding( EdgeInsets.symmetric(horizontal: math.max( _kMenuViewPadding, _kLabelItemDefaultSpacing + visualDensity.baseSizeAdjustment.dx, )), EdgeInsets.symmetric(horizontal: math.max( _kMenuViewPadding, 8 + visualDensity.baseSizeAdjustment.dx, )), const EdgeInsets.symmetric(horizontal: _kMenuViewPadding), fontSizeRatio, ); } } class _MenuDefaultsM3 extends MenuStyle { _MenuDefaultsM3(this.context) : super( elevation: const MaterialStatePropertyAll<double?>(${elevation('md.comp.menu.container')}), shape: const MaterialStatePropertyAll<OutlinedBorder>(_defaultMenuBorder), alignment: AlignmentDirectional.topEnd, ); static const RoundedRectangleBorder _defaultMenuBorder = ${shape('md.comp.menu.container', '')}; final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; @override MaterialStateProperty<Color?> get backgroundColor { return MaterialStatePropertyAll<Color?>(${componentColor('md.comp.menu.container')}); } @override MaterialStateProperty<Color?>? get surfaceTintColor { return ${componentColor('md.comp.menu.container.surface-tint-layer') == 'null' ? 'const MaterialStatePropertyAll<Color?>(Colors.transparent)' : 'MaterialStatePropertyAll<Color?>(${componentColor('md.comp.menu.container.surface-tint-layer')})' }; } @override MaterialStateProperty<Color?>? get shadowColor { return MaterialStatePropertyAll<Color?>(${color('md.comp.menu.container.shadow-color')}); } @override MaterialStateProperty<EdgeInsetsGeometry?>? get padding { return const MaterialStatePropertyAll<EdgeInsetsGeometry>( EdgeInsetsDirectional.symmetric(vertical: _kMenuVerticalMinPadding), ); } @override VisualDensity get visualDensity => Theme.of(context).visualDensity; } '''; }
flutter/dev/tools/gen_defaults/lib/menu_template.dart/0
{ "file_path": "flutter/dev/tools/gen_defaults/lib/menu_template.dart", "repo_id": "flutter", "token_count": 3164 }
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 'dart:io'; import 'token_logger.dart'; /// Base class for code generation templates. abstract class TokenTemplate { const TokenTemplate(this.blockName, this.fileName, this._tokens, { this.colorSchemePrefix = 'Theme.of(context).colorScheme.', this.textThemePrefix = 'Theme.of(context).textTheme.' }); /// Name of the code block that this template will generate. /// /// Used to identify an existing block when updating it. final String blockName; /// Name of the file that will be updated with the generated code. final String fileName; /// Map of token data extracted from the Material Design token database. final Map<String, dynamic> _tokens; /// Optional prefix prepended to color definitions. /// /// Defaults to 'Theme.of(context).colorScheme.' final String colorSchemePrefix; /// Optional prefix prepended to text style definitions. /// /// Defaults to 'Theme.of(context).textTheme.' final String textThemePrefix; /// Check if a token is available. bool tokenAvailable(String tokenName) => _tokens.containsKey(tokenName); /// Resolve a token while logging its usage. /// There will be no log if [optional] is true and the token doesn't exist. dynamic getToken(String tokenName, {bool optional = false}) { if (optional && !tokenAvailable(tokenName)) { return null; } tokenLogger.log(tokenName); return _tokens[tokenName]; } static const String beginGeneratedComment = ''' // BEGIN GENERATED TOKEN PROPERTIES'''; static const String headerComment = ''' // Do not edit by hand. The code between the "BEGIN GENERATED" and // "END GENERATED" comments are generated from data in the Material // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. '''; static const String endGeneratedComment = ''' // END GENERATED TOKEN PROPERTIES'''; /// Replace or append the contents of the file with the text from [generate]. /// /// If the file already contains a generated text block matching the /// [blockName], it will be replaced by the [generate] output. Otherwise /// the content will just be appended to the end of the file. Future<void> updateFile() async { final String contents = File(fileName).readAsStringSync(); final String beginComment = '$beginGeneratedComment - $blockName\n'; final String endComment = '$endGeneratedComment - $blockName\n'; final int beginPreviousBlock = contents.indexOf(beginComment); final int endPreviousBlock = contents.indexOf(endComment); late String contentBeforeBlock; late String contentAfterBlock; if (beginPreviousBlock != -1) { if (endPreviousBlock < beginPreviousBlock) { print('Unable to find block named $blockName in $fileName, skipping code generation.'); return; } // Found a valid block matching the name, so record the content before and after. contentBeforeBlock = contents.substring(0, beginPreviousBlock); contentAfterBlock = contents.substring(endPreviousBlock + endComment.length); } else { // Just append to the bottom. contentBeforeBlock = contents; contentAfterBlock = ''; } final StringBuffer buffer = StringBuffer(contentBeforeBlock); buffer.write(beginComment); buffer.write(headerComment); buffer.write(generate()); buffer.write(endComment); buffer.write(contentAfterBlock); File(fileName).writeAsStringSync(buffer.toString()); } /// Provide the generated content for the template. /// /// This abstract method needs to be implemented by subclasses /// to provide the content that [updateFile] will append to the /// bottom of the file. String generate(); /// Generate a [ColorScheme] color name for the given token. /// /// If there is a value for the given token, this will return /// the value prepended with [colorSchemePrefix]. /// /// Otherwise it will return [defaultValue] if provided or 'null' if not. /// /// If a [defaultValue] is not provided and the token doesn't exist, the token /// lookup is logged and a warning will be shown at the end of the process. /// /// See also: /// * [componentColor], that provides support for an optional opacity. String color(String colorToken, [String? defaultValue]) { final String effectiveDefault = defaultValue ?? 'null'; final dynamic tokenVal = getToken(colorToken, optional: defaultValue != null); return tokenVal == null ? effectiveDefault : '$colorSchemePrefix$tokenVal'; } /// Generate a [ColorScheme] color name for the given token or a transparent /// color if there is no value for the token. /// /// If there is a value for the given token, this will return /// the value prepended with [colorSchemePrefix]. /// /// Otherwise it will return 'Colors.transparent'. /// /// See also: /// * [componentColor], that provides support for an optional opacity. String? colorOrTransparent(String token) => color(token, 'Colors.transparent'); /// Generate a [ColorScheme] color name for the given component's color /// with opacity if available. /// /// If there is a value for the given component's color, this will return /// the value prepended with [colorSchemePrefix]. If there is also /// an opacity specified for the component, then the returned value /// will include this opacity calculation. /// /// If there is no value for the component's color, 'null' will be returned. /// /// See also: /// * [color], that provides support for looking up a raw color token. String componentColor(String componentToken) { final String colorToken = '$componentToken.color'; if (!tokenAvailable(colorToken)) { return 'null'; } String value = color(colorToken); final String opacityToken = '$componentToken.opacity'; if (tokenAvailable(opacityToken)) { value += '.withOpacity(${opacity(opacityToken)})'; } return value; } /// Generate the opacity value for the given token. String? opacity(String token) { tokenLogger.log(token); return _numToString(getToken(token)); } String? _numToString(Object? value, [int? digits]) { if (value == null) { return null; } if (value is num) { if (value == double.infinity) { return 'double.infinity'; } return digits == null ? value.toString() : value.toStringAsFixed(digits); } return getToken(value as String).toString(); } /// Generate an elevation value for the given component token. String elevation(String componentToken) { return getToken(getToken('$componentToken.elevation')! as String)!.toString(); } /// Generate a size value for the given component token. /// /// Non-square sizes are specified as width and height. String size(String componentToken) { final String sizeToken = '$componentToken.size'; if (!tokenAvailable(sizeToken)) { final String widthToken = '$componentToken.width'; final String heightToken = '$componentToken.height'; if (!tokenAvailable(widthToken) && !tokenAvailable(heightToken)) { throw Exception('Unable to find width, height, or size tokens for $componentToken'); } final String? width = _numToString(tokenAvailable(widthToken) ? getToken(widthToken)! as num : double.infinity, 0); final String? height = _numToString(tokenAvailable(heightToken) ? getToken(heightToken)! as num : double.infinity, 0); return 'const Size($width, $height)'; } return 'const Size.square(${_numToString(getToken(sizeToken))})'; } /// Generate a shape constant for the given component token. /// /// Currently supports family: /// - "SHAPE_FAMILY_ROUNDED_CORNERS" which maps to [RoundedRectangleBorder]. /// - "SHAPE_FAMILY_CIRCULAR" which maps to a [StadiumBorder]. String shape(String componentToken, [String prefix = 'const ']) { final Map<String, dynamic> shape = getToken(getToken('$componentToken.shape') as String) as Map<String, dynamic>; switch (shape['family']) { case 'SHAPE_FAMILY_ROUNDED_CORNERS': final double topLeft = shape['topLeft'] as double; final double topRight = shape['topRight'] as double; final double bottomLeft = shape['bottomLeft'] as double; final double bottomRight = shape['bottomRight'] as double; if (topLeft == topRight && topLeft == bottomLeft && topLeft == bottomRight) { if (topLeft == 0) { return '${prefix}RoundedRectangleBorder()'; } return '${prefix}RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular($topLeft)))'; } if (topLeft == topRight && bottomLeft == bottomRight) { return '${prefix}RoundedRectangleBorder(borderRadius: BorderRadius.vertical(' '${topLeft > 0 ? 'top: Radius.circular($topLeft)':''}' '${topLeft > 0 && bottomLeft > 0 ? ',':''}' '${bottomLeft > 0 ? 'bottom: Radius.circular($bottomLeft)':''}' '))'; } return '${prefix}RoundedRectangleBorder(borderRadius: ' 'BorderRadius.only(' 'topLeft: Radius.circular(${shape['topLeft']}), ' 'topRight: Radius.circular(${shape['topRight']}), ' 'bottomLeft: Radius.circular(${shape['bottomLeft']}), ' 'bottomRight: Radius.circular(${shape['bottomRight']})))'; case 'SHAPE_FAMILY_CIRCULAR': return '${prefix}StadiumBorder()'; } print('Unsupported shape family type: ${shape['family']} for $componentToken'); return ''; } /// Generate a [BorderSide] for the given component. String border(String componentToken) { if (!tokenAvailable('$componentToken.color')) { return 'null'; } final String borderColor = componentColor(componentToken); final double width = ( getToken('$componentToken.width', optional: true) ?? getToken('$componentToken.height', optional: true) ?? 1.0 ) as double; return 'BorderSide(color: $borderColor${width != 1.0 ? ", width: $width" : ""})'; } /// Generate a [TextTheme] text style name for the given component token. String textStyle(String componentToken) { return '$textThemePrefix${getToken("$componentToken.text-style")}'; } String textStyleWithColor(String componentToken) { if (!tokenAvailable('$componentToken.text-style')) { return 'null'; } String style = textStyle(componentToken); if (tokenAvailable('$componentToken.color')) { style = '$style?.copyWith(color: ${componentColor(componentToken)})'; } return style; } }
flutter/dev/tools/gen_defaults/lib/template.dart/0
{ "file_path": "flutter/dev/tools/gen_defaults/lib/template.dart", "repo_id": "flutter", "token_count": 3468 }
561
{ "AltLeft": ["LEFT_ALT"], "AltRight": ["RIGHT_ALT"], "ArrowDown": ["DOWN"], "ArrowLeft": ["LEFT"], "ArrowRight": ["RIGHT"], "ArrowUp": ["UP"], "Backquote": ["GRAVE_ACCENT"], "Backslash": ["BACKSLASH"], "Backspace": ["BACKSPACE"], "BracketLeft": ["LEFT_BRACKET"], "BracketRight": ["RIGHT_BRACKET"], "CapsLock": ["CAPS_LOCK"], "Comma": ["COMMA"], "ContextMenu": ["MENU"], "ControlLeft": ["LEFT_CONTROL"], "ControlRight": ["RIGHT_CONTROL"], "Delete": ["DELETE"], "Digit0": ["0"], "Digit1": ["1"], "Digit2": ["2"], "Digit3": ["3"], "Digit4": ["4"], "Digit5": ["5"], "Digit6": ["6"], "Digit7": ["7"], "Digit8": ["8"], "Digit9": ["9"], "End": ["END"], "Enter": ["ENTER"], "Equal": ["EQUAL"], "Escape": ["ESCAPE"], "F1": ["F1"], "F2": ["F2"], "F3": ["F3"], "F4": ["F4"], "F5": ["F5"], "F6": ["F6"], "F7": ["F7"], "F8": ["F8"], "F9": ["F9"], "F10": ["F10"], "F11": ["F11"], "F12": ["F12"], "F13": ["F13"], "F14": ["F14"], "F15": ["F15"], "F16": ["F16"], "F17": ["F17"], "F18": ["F18"], "F19": ["F19"], "F20": ["F20"], "F21": ["F21"], "F22": ["F22"], "F23": ["F23"], "F25": ["F25"], "Home": ["HOME"], "Insert": ["INSERT"], "KeyA": ["A"], "KeyB": ["B"], "KeyC": ["C"], "KeyD": ["D"], "KeyE": ["E"], "KeyF": ["F"], "KeyG": ["G"], "KeyH": ["H"], "KeyI": ["I"], "KeyJ": ["J"], "KeyK": ["K"], "KeyL": ["L"], "KeyM": ["M"], "KeyN": ["N"], "KeyO": ["O"], "KeyP": ["P"], "KeyQ": ["Q"], "KeyR": ["R"], "KeyS": ["S"], "KeyT": ["T"], "KeyU": ["U"], "KeyV": ["V"], "KeyW": ["W"], "KeyX": ["X"], "KeyY": ["Y"], "KeyZ": ["Z"], "MetaLeft": ["LEFT_SUPER"], "MetaRight": ["RIGHT_SUPER"], "Minus": ["MINUS"], "NumLock": ["NUM_LOCK"], "Numpad0": ["KP_0"], "Numpad1": ["KP_1"], "Numpad2": ["KP_2"], "Numpad3": ["KP_3"], "Numpad4": ["KP_4"], "Numpad5": ["KP_5"], "Numpad6": ["KP_6"], "Numpad7": ["KP_7"], "Numpad8": ["KP_8"], "Numpad9": ["KP_9"], "NumpadAdd": ["KP_ADD"], "NumpadDecimal": ["KP_DECIMAL"], "NumpadDivide": ["KP_DIVIDE"], "NumpadEnter": ["KP_ENTER"], "NumpadEqual": ["KP_EQUAL"], "NumpadMultiply": ["KP_MULTIPLY"], "NumpadSubtract": ["NUMPAD_SUBTRACT"], "PageDown": ["PAGE_DOWN"], "PageUp": ["PAGE_UP"], "Pause": ["PAUSE"], "Period": ["PERIOD"], "PrintScreen": ["PRINT_SCREEN"], "Quote": ["APOSTROPHE"], "Semicolon": ["SEMICOLON"], "ShiftLeft": ["LEFT_SHIFT"], "ShiftRight": ["RIGHT_SHIFT"], "Slash": ["SLASH"], "Space": ["SPACE"], "Tab": ["TAB"] }
flutter/dev/tools/gen_keycodes/data/glfw_key_name_to_name.json/0
{ "file_path": "flutter/dev/tools/gen_keycodes/data/glfw_key_name_to_name.json", "repo_id": "flutter", "token_count": 1281 }
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:path/path.dart' as path; import 'base_code_gen.dart'; import 'constants.dart'; import 'data.dart'; import 'logical_key_data.dart'; import 'physical_key_data.dart'; import 'utils.dart'; const List<String> kModifiersOfInterest = <String>[ 'ShiftLeft', 'ShiftRight', 'ControlLeft', 'ControlRight', 'AltLeft', 'AltRight', 'MetaLeft', 'MetaRight', ]; // The name of keys that require special attention. const List<String> kSpecialPhysicalKeys = <String>['CapsLock']; const List<String> kSpecialLogicalKeys = <String>['CapsLock']; /// Generates the key mapping for iOS, based on the information in the key /// data structure given to it. class IOSCodeGenerator extends PlatformCodeGenerator { IOSCodeGenerator(super.keyData, super.logicalData); /// This generates the map of iOS key codes to physical keys. String get _scanCodeMap { final OutputLines<int> lines = OutputLines<int>('iOS scancode map'); for (final PhysicalKeyEntry entry in keyData.entries) { if (entry.iOSScanCode != null) { lines.add(entry.iOSScanCode!, ' {${toHex(entry.iOSScanCode)}, ${toHex(entry.usbHidCode)}}, // ${entry.constantName}'); } } return lines.sortedJoin().trimRight(); } Iterable<PhysicalKeyEntry> get _functionKeyData { final RegExp functionKeyRe = RegExp(r'^f[0-9]+$'); return keyData.entries.where((PhysicalKeyEntry entry) { return functionKeyRe.hasMatch(entry.constantName); }); } String get _functionKeys { final StringBuffer result = StringBuffer(); for (final PhysicalKeyEntry entry in _functionKeyData) { result.writeln(' ${toHex(entry.iOSScanCode)}, // ${entry.constantName}'); } return result.toString().trimRight(); } String get _keyCodeToLogicalMap { final OutputLines<int> lines = OutputLines<int>('iOS keycode map'); for (final LogicalKeyEntry entry in logicalData.entries) { zipStrict(entry.iOSKeyCodeValues, entry.iOSKeyCodeNames, (int iOSValue, String iOSName) { lines.add(iOSValue, ' {${toHex(iOSValue)}, ${toHex(entry.value, digits: 11)}}, // $iOSName'); }); } return lines.sortedJoin().trimRight(); } /// This generates the mask values for the part of a key code that defines its plane. String get _maskConstants { final StringBuffer buffer = StringBuffer(); const List<MaskConstant> maskConstants = <MaskConstant>[ kValueMask, kUnicodePlane, kIosPlane, ]; for (final MaskConstant constant in maskConstants) { buffer.writeln('/**'); buffer.write(wrapString(constant.description, prefix: ' * ')); buffer.writeln(' */'); buffer.writeln('const uint64_t k${constant.upperCamelName} = ${toHex(constant.value, digits: 11)};'); buffer.writeln(); } return buffer.toString().trimRight(); } /// This generates a map from the key code to a modifier flag. String get _keyToModifierFlagMap { final StringBuffer modifierKeyMap = StringBuffer(); for (final String name in kModifiersOfInterest) { final String line = '{${toHex(logicalData.entryByName(name).iOSKeyCodeValues[0])}, kModifierFlag${lowerCamelToUpperCamel(name)}},'; modifierKeyMap.writeln(' ${line.padRight(42)}// $name'); } return modifierKeyMap.toString().trimRight(); } /// This generates a map from the modifier flag to the key code. String get _modifierFlagToKeyMap { final StringBuffer modifierKeyMap = StringBuffer(); for (final String name in kModifiersOfInterest) { final String line = '{kModifierFlag${lowerCamelToUpperCamel(name)}, ${toHex(logicalData.entryByName(name).iOSKeyCodeValues[0])}},'; modifierKeyMap.writeln(' ${line.padRight(42)}// $name'); } return modifierKeyMap.toString().trimRight(); } String get _specialKeyMapping { final OutputLines<int> lines = OutputLines<int>('iOS special key mapping'); kIosSpecialKeyMapping.forEach((String key, String logicalName) { final int value = logicalData.entryByName(logicalName).value; lines.add(value, ' @"$key" : @(${toHex(value)}),'); }); return lines.join().trimRight(); } /// This generates some keys that needs special attention. String get _specialKeyConstants { final StringBuffer specialKeyConstants = StringBuffer(); for (final String keyName in kSpecialPhysicalKeys) { specialKeyConstants.writeln('const uint64_t k${keyName}PhysicalKey = ${toHex(keyData.entryByName(keyName).usbHidCode)};'); } for (final String keyName in kSpecialLogicalKeys) { specialKeyConstants.writeln('const uint64_t k${lowerCamelToUpperCamel(keyName)}LogicalKey = ${toHex(logicalData.entryByName(keyName).value)};'); } return specialKeyConstants.toString().trimRight(); } @override String get templatePath => path.join(dataRoot, 'ios_key_code_map_mm.tmpl'); @override String outputPath(String platform) => path.join(PlatformCodeGenerator.engineRoot, 'shell', 'platform', 'darwin', 'ios', 'framework', 'Source', 'KeyCodeMap.g.mm'); @override Map<String, String> mappings() { // There is no iOS keycode map since iOS uses keycode to represent a physical key. // The LogicalKeyboardKey is generated by raw_keyboard_ios.dart from the unmodified characters // from NSEvent. return <String, String>{ 'MASK_CONSTANTS': _maskConstants, 'IOS_SCAN_CODE_MAP': _scanCodeMap, 'IOS_KEYCODE_LOGICAL_MAP': _keyCodeToLogicalMap, 'IOS_FUNCTION_KEY_SET': _functionKeys, 'KEYCODE_TO_MODIFIER_FLAG_MAP': _keyToModifierFlagMap, 'MODIFIER_FLAG_TO_KEYCODE_MAP': _modifierFlagToKeyMap, 'SPECIAL_KEY_CONSTANTS': _specialKeyConstants, 'SPECIAL_KEY_MAPPING': _specialKeyMapping, }; } }
flutter/dev/tools/gen_keycodes/lib/ios_code_gen.dart/0
{ "file_path": "flutter/dev/tools/gen_keycodes/lib/ios_code_gen.dart", "repo_id": "flutter", "token_count": 2139 }
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. // This program updates the language locale arb files with any missing resource // entries that are included in the English arb files. This is useful when // adding new resources for localization. You can just add the appropriate // entries to the English arb file and then run this script. It will then check // all of the other language locale arb files and update them with the English // source for any missing resources. These will be picked up by the localization // team and then translated. // // ## Usage // // Run this program from the root of the git repository. // // ``` // dart dev/tools/localization/bin/gen_missing_localizations.dart // ``` import 'dart:convert'; import 'dart:io'; import 'package:path/path.dart' as path; import '../localizations_utils.dart'; import '../localizations_validator.dart'; Future<void> main(List<String> rawArgs) async { bool removeUndefined = false; if (rawArgs.contains('--remove-undefined')) { removeUndefined = true; } checkCwdIsRepoRoot('gen_missing_localizations'); final String localizationPath = path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n'); updateMissingResources(localizationPath, 'material', removeUndefined: removeUndefined); updateMissingResources(localizationPath, 'cupertino', removeUndefined: removeUndefined); } Map<String, dynamic> loadBundle(File file) { if (!FileSystemEntity.isFileSync(file.path)) { exitWithError('Unable to find input file: ${file.path}'); } return json.decode(file.readAsStringSync()) as Map<String, dynamic>; } void writeBundle(File file, Map<String, dynamic> bundle) { final StringBuffer contents = StringBuffer(); contents.writeln('{'); for (final String key in bundle.keys) { contents.writeln(' "$key": ${json.encode(bundle[key])}${key == bundle.keys.last ? '' : ','}'); } contents.writeln('}'); file.writeAsStringSync(contents.toString()); } Set<String> resourceKeys(Map<String, dynamic> bundle) { return Set<String>.from( // Skip any attribute keys bundle.keys.where((String key) => !key.startsWith('@')) ); } bool intentionallyOmitted(String key, Map<String, dynamic> bundle) { final String attributeKey = '@$key'; final dynamic attribute = bundle[attributeKey]; return attribute is Map && attribute.containsKey('notUsed'); } /// Whether `key` corresponds to one of the plural variations of a key with /// the same prefix and suffix "Other". bool isPluralVariation(String key, Map<String, dynamic> bundle) { final Match? pluralMatch = kPluralRegexp.firstMatch(key); if (pluralMatch == null) { return false; } final String prefix = pluralMatch[1]!; return bundle.containsKey('${prefix}Other'); } void updateMissingResources(String localizationPath, String groupPrefix, {bool removeUndefined = false}) { final Directory localizationDir = Directory(localizationPath); final RegExp filenamePattern = RegExp('${groupPrefix}_(\\w+)\\.arb'); final Map<String, dynamic> englishBundle = loadBundle(File(path.join(localizationPath, '${groupPrefix}_en.arb'))); final Set<String> requiredKeys = resourceKeys(englishBundle); for (final FileSystemEntity entity in localizationDir.listSync().toList()..sort(sortFilesByPath)) { final String entityPath = entity.path; if (FileSystemEntity.isFileSync(entityPath) && filenamePattern.hasMatch(entityPath)) { final String localeString = filenamePattern.firstMatch(entityPath)![1]!; final LocaleInfo locale = LocaleInfo.fromString(localeString); // Only look at top-level language locales if (locale.length == 1) { final File arbFile = File(entityPath); final Map<String, dynamic> localeBundle = loadBundle(arbFile); final Set<String> localeResources = resourceKeys(localeBundle); // Whether or not the resources were modified and need to be updated. bool shouldWrite = false; // Remove any localizations that are not defined in the canonical // locale. This allows unused localizations to be removed if // --remove-undefined is passed. if (removeUndefined) { bool isIncluded(String key) { return !isPluralVariation(key, localeBundle) && !intentionallyOmitted(key, localeBundle); } // Find any resources in this locale that don't appear in the // canonical locale, and skipping any which should not be included // (plurals and intentionally omitted). final Set<String> extraResources = localeResources .difference(requiredKeys) .where(isIncluded) .toSet(); // Remove them. localeBundle.removeWhere((String key, dynamic value) { final bool found = extraResources.contains(key); if (found) { shouldWrite = true; } return found; }); if (shouldWrite) { print('Updating $entityPath by removing extra entries for $extraResources'); } } // Add in any resources that are in the canonical locale and not present // in this locale. final Set<String> missingResources = requiredKeys.difference(localeResources).where( (String key) => !isPluralVariation(key, localeBundle) && !intentionallyOmitted(key, localeBundle) ).toSet(); if (missingResources.isNotEmpty) { localeBundle.addEntries(missingResources.map((String k) => MapEntry<String, String>(k, englishBundle[k].toString()))); shouldWrite = true; print('Updating $entityPath with missing entries for $missingResources'); } if (shouldWrite) { writeBundle(arbFile, localeBundle); } } } } }
flutter/dev/tools/localization/bin/gen_missing_localizations.dart/0
{ "file_path": "flutter/dev/tools/localization/bin/gen_missing_localizations.dart", "repo_id": "flutter", "token_count": 2033 }
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:args/args.dart'; import 'package:vitool/vitool.dart'; const String kCodegenComment = '// AUTOGENERATED FILE DO NOT EDIT!\n' '// This file was generated by vitool.\n'; void main(List<String> args) { final ArgParser parser = ArgParser(); parser.addFlag( 'help', abbr: 'h', negatable: false, help: "Display the tool's usage instructions and quit.", ); parser.addOption( 'output', abbr: 'o', help: 'Target path to write the generated Dart file to.', ); parser.addOption( 'asset-name', abbr: 'n', help: 'Name to be used for the generated constant.', ); parser.addOption( 'part-of', abbr: 'p', help: "Library name to add a dart 'part of' clause for.", ); parser.addOption( 'header', abbr: 'd', help: 'File whose contents are to be prepended to the beginning of ' 'the generated Dart file; this can be used for a license comment.', ); parser.addFlag( 'codegen_comment', abbr: 'c', defaultsTo: true, help: 'Whether to include the following comment after the header:\n' '$kCodegenComment', ); final ArgResults argResults = parser.parse(args); if (argResults['help'] as bool || !argResults.wasParsed('output') || !argResults.wasParsed('asset-name') || argResults.rest.isEmpty) { printUsage(parser); return; } final List<FrameData> frames = <FrameData>[ for (final String filePath in argResults.rest) interpretSvg(filePath), ]; final StringBuffer generatedSb = StringBuffer(); if (argResults.wasParsed('header')) { generatedSb.write(File(argResults['header'] as String).readAsStringSync()); generatedSb.write('\n'); } if (argResults['codegen_comment'] as bool) { generatedSb.write(kCodegenComment); } if (argResults.wasParsed('part-of')) { generatedSb.write('part of ${argResults['part-of']}; // ignore: use_string_in_part_of_directives\n'); } final Animation animation = Animation.fromFrameData(frames); generatedSb.write(animation.toDart('_AnimatedIconData', argResults['asset-name'] as String)); final File outFile = File(argResults['output'] as String); outFile.writeAsStringSync(generatedSb.toString()); } void printUsage(ArgParser parser) { print('Usage: vitool --asset-name=<asset_name> --output=<output_path> <frames_list>'); print('\nExample: vitool --asset-name=_\$menu_arrow --output=lib/data/menu_arrow.g.dart assets/svg/menu_arrow/*.svg\n'); print(parser.usage); }
flutter/dev/tools/vitool/bin/main.dart/0
{ "file_path": "flutter/dev/tools/vitool/bin/main.dart", "repo_id": "flutter", "token_count": 1011 }
565
BasedOnStyle: Google --- Language: Cpp DerivePointerAlignment: false PointerAlignment: Left
flutter/examples/.clang-format/0
{ "file_path": "flutter/examples/.clang-format", "repo_id": "flutter", "token_count": 29 }
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 'package:flutter/cupertino.dart'; /// Flutter code sample for [CupertinoButton]. void main() => runApp(const CupertinoButtonApp()); class CupertinoButtonApp extends StatelessWidget { const CupertinoButtonApp({super.key}); @override Widget build(BuildContext context) { return const CupertinoApp( theme: CupertinoThemeData(brightness: Brightness.light), home: CupertinoButtonExample(), ); } } class CupertinoButtonExample extends StatelessWidget { const CupertinoButtonExample({super.key}); @override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar( middle: Text('CupertinoButton Sample'), ), child: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ const CupertinoButton( onPressed: null, child: Text('Disabled'), ), const SizedBox(height: 30), const CupertinoButton.filled( onPressed: null, child: Text('Disabled'), ), const SizedBox(height: 30), CupertinoButton( onPressed: () {}, child: const Text('Enabled'), ), const SizedBox(height: 30), CupertinoButton.filled( onPressed: () {}, child: const Text('Enabled'), ), ], ), ), ); } }
flutter/examples/api/lib/cupertino/button/cupertino_button.0.dart/0
{ "file_path": "flutter/examples/api/lib/cupertino/button/cupertino_button.0.dart", "repo_id": "flutter", "token_count": 734 }
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 'package:flutter/cupertino.dart'; /// Flutter code sample for [CupertinoSliverRefreshControl]. void main() => runApp(const RefreshControlApp()); class RefreshControlApp extends StatelessWidget { const RefreshControlApp({super.key}); @override Widget build(BuildContext context) { return const CupertinoApp( theme: CupertinoThemeData(brightness: Brightness.light), home: RefreshControlExample(), ); } } class RefreshControlExample extends StatefulWidget { const RefreshControlExample({super.key}); @override State<RefreshControlExample> createState() => _RefreshControlExampleState(); } class _RefreshControlExampleState extends State<RefreshControlExample> { List<Color> colors = <Color>[ CupertinoColors.systemYellow, CupertinoColors.systemOrange, CupertinoColors.systemPink, ]; List<Widget> items = <Widget>[ Container(color: CupertinoColors.systemPink, height: 100.0), Container(color: CupertinoColors.systemOrange, height: 100.0), Container(color: CupertinoColors.systemYellow, height: 100.0), ]; @override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar( middle: Text('CupertinoSliverRefreshControl Sample'), ), child: CustomScrollView( physics: const BouncingScrollPhysics( parent: AlwaysScrollableScrollPhysics(), ), slivers: <Widget>[ const CupertinoSliverNavigationBar( largeTitle: Text('Scroll down'), ), CupertinoSliverRefreshControl( onRefresh: () async { await Future<void>.delayed( const Duration(milliseconds: 1000), ); setState(() { items.insert( 0, Container(color: colors[items.length % 3], height: 100.0), ); }); }, ), SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => items[index], childCount: items.length, ), ), ], ), ); } }
flutter/examples/api/lib/cupertino/refresh/cupertino_sliver_refresh_control.0.dart/0
{ "file_path": "flutter/examples/api/lib/cupertino/refresh/cupertino_sliver_refresh_control.0.dart", "repo_id": "flutter", "token_count": 966 }
568
// 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/gestures.dart'; import 'package:flutter/material.dart'; /// Flutter code sample for [TapAndPanGestureRecognizer]. void main() { runApp(const TapAndDragToZoomApp()); } class TapAndDragToZoomApp extends StatelessWidget { const TapAndDragToZoomApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: Scaffold( body: Center( child: TapAndDragToZoomWidget( child: MyBoxWidget(), ), ), ), ); } } class MyBoxWidget extends StatelessWidget { const MyBoxWidget({super.key}); @override Widget build(BuildContext context) { return Container( color: Colors.blueAccent, height: 100.0, width: 100.0, ); } } // This widget will scale its child up when it detects a drag up, after a // double tap/click. It will scale the widget down when it detects a drag down, // after a double tap. Dragging down and then up after a double tap/click will // zoom the child in/out. The scale of the child will be reset when the drag ends. class TapAndDragToZoomWidget extends StatefulWidget { const TapAndDragToZoomWidget({super.key, required this.child}); final Widget child; @override State<TapAndDragToZoomWidget> createState() => _TapAndDragToZoomWidgetState(); } class _TapAndDragToZoomWidgetState extends State<TapAndDragToZoomWidget> { final double scaleMultiplier = -0.0001; double _currentScale = 1.0; Offset? _previousDragPosition; static double _keepScaleWithinBounds(double scale) { const double minScale = 0.1; const double maxScale = 30; if (scale <= 0) { return minScale; } if (scale >= 30) { return maxScale; } return scale; } void _zoomLogic(Offset currentDragPosition) { final double dx = (_previousDragPosition!.dx - currentDragPosition.dx).abs(); final double dy = (_previousDragPosition!.dy - currentDragPosition.dy).abs(); if (dx > dy) { // Ignore horizontal drags. _previousDragPosition = currentDragPosition; return; } if (currentDragPosition.dy < _previousDragPosition!.dy) { // Zoom out on drag up. setState(() { _currentScale += currentDragPosition.dy * scaleMultiplier; _currentScale = _keepScaleWithinBounds(_currentScale); }); } else { // Zoom in on drag down. setState(() { _currentScale -= currentDragPosition.dy * scaleMultiplier; _currentScale = _keepScaleWithinBounds(_currentScale); }); } _previousDragPosition = currentDragPosition; } @override Widget build(BuildContext context) { return RawGestureDetector( gestures: <Type, GestureRecognizerFactory>{ TapAndPanGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapAndPanGestureRecognizer>( () => TapAndPanGestureRecognizer(), (TapAndPanGestureRecognizer instance) { instance ..onTapDown = (TapDragDownDetails details) { _previousDragPosition = details.globalPosition; } ..onDragStart = (TapDragStartDetails details) { if (details.consecutiveTapCount == 2) { _zoomLogic(details.globalPosition); } } ..onDragUpdate = (TapDragUpdateDetails details) { if (details.consecutiveTapCount == 2) { _zoomLogic(details.globalPosition); } } ..onDragEnd = (TapDragEndDetails details) { if (details.consecutiveTapCount == 2) { setState(() { _currentScale = 1.0; }); _previousDragPosition = null; } }; } ), }, child: Transform.scale( scale: _currentScale, child: widget.child, ), ); } }
flutter/examples/api/lib/gestures/tap_and_drag/tap_and_drag.0.dart/0
{ "file_path": "flutter/examples/api/lib/gestures/tap_and_drag/tap_and_drag.0.dart", "repo_id": "flutter", "token_count": 1704 }
569
// 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'; /// Flutter code sample for [Autocomplete]. void main() => runApp(const AutocompleteExampleApp()); class AutocompleteExampleApp extends StatelessWidget { const AutocompleteExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Autocomplete Basic User'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Type below to autocomplete the following possible results: ${AutocompleteBasicUserExample._userOptions}.'), const AutocompleteBasicUserExample(), ], ), ), ), ); } } @immutable class User { const User({ required this.email, required this.name, }); final String email; final String name; @override String toString() { return '$name, $email'; } @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is User && other.name == name && other.email == email; } @override int get hashCode => Object.hash(email, name); } class AutocompleteBasicUserExample extends StatelessWidget { const AutocompleteBasicUserExample({super.key}); static const List<User> _userOptions = <User>[ User(name: 'Alice', email: '[email protected]'), User(name: 'Bob', email: '[email protected]'), User(name: 'Charlie', email: '[email protected]'), ]; static String _displayStringForOption(User option) => option.name; @override Widget build(BuildContext context) { return Autocomplete<User>( displayStringForOption: _displayStringForOption, optionsBuilder: (TextEditingValue textEditingValue) { if (textEditingValue.text == '') { return const Iterable<User>.empty(); } return _userOptions.where((User option) { return option.toString().contains(textEditingValue.text.toLowerCase()); }); }, onSelected: (User selection) { debugPrint('You just selected ${_displayStringForOption(selection)}'); }, ); } }
flutter/examples/api/lib/material/autocomplete/autocomplete.1.dart/0
{ "file_path": "flutter/examples/api/lib/material/autocomplete/autocomplete.1.dart", "repo_id": "flutter", "token_count": 897 }
570
// 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'; /// Flutter code sample for [Card]. void main() => runApp(const CardExampleApp()); class CardExampleApp extends StatelessWidget { const CardExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Card Sample')), body: const CardExample(), ), ); } } class CardExample extends StatelessWidget { const CardExample({super.key}); @override Widget build(BuildContext context) { return Center( child: Card( // clipBehavior is necessary because, without it, the InkWell's animation // will extend beyond the rounded edges of the [Card] (see https://github.com/flutter/flutter/issues/109776) // This comes with a small performance cost, and you should not set [clipBehavior] // unless you need it. clipBehavior: Clip.hardEdge, child: InkWell( splashColor: Colors.blue.withAlpha(30), onTap: () { debugPrint('Card tapped.'); }, child: const SizedBox( width: 300, height: 100, child: Text('A card that can be tapped'), ), ), ), ); } }
flutter/examples/api/lib/material/card/card.1.dart/0
{ "file_path": "flutter/examples/api/lib/material/card/card.1.dart", "repo_id": "flutter", "token_count": 555 }
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. // This example demonstrates showing a custom context menu only when some // narrowly defined text is selected. import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() => runApp(const EditableTextToolbarBuilderExampleApp()); const String emailAddress = '[email protected]'; const String text = 'Select the email address and open the menu: $emailAddress'; class EditableTextToolbarBuilderExampleApp extends StatefulWidget { const EditableTextToolbarBuilderExampleApp({super.key}); @override State<EditableTextToolbarBuilderExampleApp> createState() => _EditableTextToolbarBuilderExampleAppState(); } class _EditableTextToolbarBuilderExampleAppState extends State<EditableTextToolbarBuilderExampleApp> { final TextEditingController _controller = TextEditingController( text: text, ); void _showDialog(BuildContext context) { Navigator.of(context).push( DialogRoute<void>( context: context, builder: (BuildContext context) => const AlertDialog(title: Text('You clicked send email!')), ), ); } @override void initState() { super.initState(); // On web, disable the browser's context menu since this example uses a custom // Flutter-rendered context menu. if (kIsWeb) { BrowserContextMenu.disableContextMenu(); } } @override void dispose() { if (kIsWeb) { BrowserContextMenu.enableContextMenu(); } super.dispose(); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Custom button for emails'), ), body: Center( child: Column( children: <Widget>[ Container(height: 20.0), TextField( controller: _controller, contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { final List<ContextMenuButtonItem> buttonItems = editableTextState.contextMenuButtonItems; // Here we add an "Email" button to the default TextField // context menu for the current platform, but only if an email // address is currently selected. final TextEditingValue value = _controller.value; if (_isValidEmail(value.selection.textInside(value.text))) { buttonItems.insert( 0, ContextMenuButtonItem( label: 'Send email', onPressed: () { ContextMenuController.removeAny(); _showDialog(context); }, ), ); } return AdaptiveTextSelectionToolbar.buttonItems( anchors: editableTextState.contextMenuAnchors, buttonItems: buttonItems, ); }, ), ], ), ), ), ); } } bool _isValidEmail(String text) { return RegExp( r'(?<name>[a-zA-Z0-9]+)' r'@' r'(?<domain>[a-zA-Z0-9]+)' r'\.' r'(?<topLevelDomain>[a-zA-Z0-9]+)', ).hasMatch(text); }
flutter/examples/api/lib/material/context_menu/editable_text_toolbar_builder.1.dart/0
{ "file_path": "flutter/examples/api/lib/material/context_menu/editable_text_toolbar_builder.1.dart", "repo_id": "flutter", "token_count": 1511 }
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. import 'package:flutter/material.dart'; /// Flutter code sample for [Divider]. void main() => runApp(const DividerExampleApp()); class DividerExampleApp extends StatelessWidget { const DividerExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(colorSchemeSeed: const Color(0xff6750a4), useMaterial3: true), home: Scaffold( appBar: AppBar(title: const Text('Divider Sample')), body: const DividerExample(), ), ); } } class DividerExample extends StatelessWidget { const DividerExample({super.key}); @override Widget build(BuildContext context) { return const Center( child: Padding( padding: EdgeInsets.all(16.0), child: Column( children: <Widget>[ Expanded( child: Card( child: SizedBox.expand(), ), ), Divider(), Expanded( child: Card( child: SizedBox.expand(), ), ), ], ), ), ); } }
flutter/examples/api/lib/material/divider/divider.1.dart/0
{ "file_path": "flutter/examples/api/lib/material/divider/divider.1.dart", "repo_id": "flutter", "token_count": 559 }
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. import 'package:flutter/material.dart'; /// Flutter code sample for [FilledButton]. void main() { runApp(const FilledButtonApp()); } class FilledButtonApp extends StatelessWidget { const FilledButtonApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(colorSchemeSeed: const Color(0xff6750a4), useMaterial3: true), home: Scaffold( appBar: AppBar(title: const Text('FilledButton Sample')), body: Center( child: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Column(children: <Widget>[ const SizedBox(height: 30), const Text('Filled'), const SizedBox(height: 15), FilledButton( onPressed: () {}, child: const Text('Enabled'), ), const SizedBox(height: 30), const FilledButton( onPressed: null, child: Text('Disabled'), ), ]), const SizedBox(width: 30), Column(children: <Widget>[ const SizedBox(height: 30), const Text('Filled tonal'), const SizedBox(height: 15), FilledButton.tonal( onPressed: () {}, child: const Text('Enabled'), ), const SizedBox(height: 30), const FilledButton.tonal( onPressed: null, child: Text('Disabled'), ), ]) ], ), ), ), ); } }
flutter/examples/api/lib/material/filled_button/filled_button.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/filled_button/filled_button.0.dart", "repo_id": "flutter", "token_count": 968 }
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 'package:flutter/material.dart'; /// Flutter code sample for [InputDecoration]. void main() => runApp(const InputDecorationExampleApp()); class InputDecorationExampleApp extends StatelessWidget { const InputDecorationExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Scaffold( appBar: AppBar(title: const Text('InputDecoration Sample')), body: const InputDecorationExample(), ), ); } } class InputDecorationExample extends StatelessWidget { const InputDecorationExample({super.key}); @override Widget build(BuildContext context) { return const TextField( decoration: InputDecoration( icon: Icon(Icons.send), hintText: 'Hint Text', helperText: 'Helper Text', counterText: '0 characters', border: OutlineInputBorder(), ), ); } }
flutter/examples/api/lib/material/input_decorator/input_decoration.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/input_decorator/input_decoration.0.dart", "repo_id": "flutter", "token_count": 377 }
575
// 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'; /// Flutter code sample for [ListTile]. void main() => runApp(const ListTileApp()); class ListTileApp extends StatelessWidget { const ListTileApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( listTileTheme: const ListTileThemeData( textColor: Colors.white, ), useMaterial3: true, ), home: const ListTileExample(), ); } } class ListTileExample extends StatefulWidget { const ListTileExample({super.key}); @override State<ListTileExample> createState() => _ListTileExampleState(); } class _ListTileExampleState extends State<ListTileExample> with TickerProviderStateMixin { late final AnimationController _fadeController; late final AnimationController _sizeController; late final Animation<double> _fadeAnimation; late final Animation<double> _sizeAnimation; @override void initState() { super.initState(); _fadeController = AnimationController( duration: const Duration(seconds: 1), vsync: this, )..repeat(reverse: true); _sizeController = AnimationController( duration: const Duration(milliseconds: 850), vsync: this, )..repeat(reverse: true); _fadeAnimation = CurvedAnimation( parent: _fadeController, curve: Curves.easeInOut, ); _sizeAnimation = CurvedAnimation( parent: _sizeController, curve: Curves.easeOut, ); } @override void dispose() { _fadeController.dispose(); _sizeController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('ListTile Samples')), body: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Hero( tag: 'ListTile-Hero', // Wrap the ListTile in a Material widget so the ListTile has someplace // to draw the animated colors during the hero transition. child: Material( child: ListTile( title: const Text('ListTile with Hero'), subtitle: const Text('Tap here for Hero transition'), tileColor: Colors.cyan, onTap: () { Navigator.push( context, MaterialPageRoute<Widget>(builder: (BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('ListTile Hero')), body: Center( child: Hero( tag: 'ListTile-Hero', child: Material( child: ListTile( title: const Text('ListTile with Hero'), subtitle: const Text('Tap here to go back'), tileColor: Colors.blue[700], onTap: () { Navigator.pop(context); }, ), ), ), ), ); }), ); }, ), ), ), FadeTransition( opacity: _fadeAnimation, // Wrap the ListTile in a Material widget so the ListTile has someplace // to draw the animated colors during the fade transition. child: const Material( child: ListTile( title: Text('ListTile with FadeTransition'), selectedTileColor: Colors.green, selectedColor: Colors.white, selected: true, ), ), ), SizedBox( height: 100, child: Center( child: SizeTransition( sizeFactor: _sizeAnimation, axisAlignment: -1.0, // Wrap the ListTile in a Material widget so the ListTile has someplace // to draw the animated colors during the size transition. child: const Material( child: ListTile( title: Text('ListTile with SizeTransition'), tileColor: Colors.red, minVerticalPadding: 25.0, ), ), ), ), ), ], ), ); } }
flutter/examples/api/lib/material/list_tile/list_tile.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/list_tile/list_tile.0.dart", "repo_id": "flutter", "token_count": 2352 }
576
// 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'; /// Flutter code sample for [RadioMenuButton]. void main() => runApp(const MenuApp()); class MyRadioMenu extends StatefulWidget { const MyRadioMenu({super.key}); @override State<MyRadioMenu> createState() => _MyRadioMenuState(); } class _MyRadioMenuState extends State<MyRadioMenu> { final FocusNode _buttonFocusNode = FocusNode(debugLabel: 'Menu Button'); Color _backgroundColor = Colors.red; late ShortcutRegistryEntry _entry; static const SingleActivator _redShortcut = SingleActivator(LogicalKeyboardKey.keyR, control: true); static const SingleActivator _greenShortcut = SingleActivator(LogicalKeyboardKey.keyG, control: true); static const SingleActivator _blueShortcut = SingleActivator(LogicalKeyboardKey.keyB, control: true); @override void didChangeDependencies() { super.didChangeDependencies(); _entry = ShortcutRegistry.of(context).addAll(<ShortcutActivator, VoidCallbackIntent>{ _redShortcut: VoidCallbackIntent(() => _setBackgroundColor(Colors.red)), _greenShortcut: VoidCallbackIntent(() => _setBackgroundColor(Colors.green)), _blueShortcut: VoidCallbackIntent(() => _setBackgroundColor(Colors.blue)), }); } @override void dispose() { _buttonFocusNode.dispose(); _entry.dispose(); super.dispose(); } void _setBackgroundColor(Color? color) { setState(() { _backgroundColor = color!; }); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ MenuAnchor( childFocusNode: _buttonFocusNode, menuChildren: <Widget>[ RadioMenuButton<Color>( value: Colors.red, shortcut: _redShortcut, groupValue: _backgroundColor, onChanged: _setBackgroundColor, child: const Text('Red Background'), ), RadioMenuButton<Color>( value: Colors.green, shortcut: _greenShortcut, groupValue: _backgroundColor, onChanged: _setBackgroundColor, child: const Text('Green Background'), ), RadioMenuButton<Color>( value: Colors.blue, shortcut: _blueShortcut, groupValue: _backgroundColor, onChanged: _setBackgroundColor, child: const Text('Blue Background'), ), ], builder: (BuildContext context, MenuController controller, Widget? child) { return TextButton( focusNode: _buttonFocusNode, onPressed: () { if (controller.isOpen) { controller.close(); } else { controller.open(); } }, child: const Text('OPEN MENU'), ); }, ), Expanded( child: Container( color: _backgroundColor, ), ), ], ); } } class MenuApp extends StatelessWidget { const MenuApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: const Scaffold(body: SafeArea(child: MyRadioMenu())), ); } }
flutter/examples/api/lib/material/menu_anchor/radio_menu_button.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/menu_anchor/radio_menu_button.0.dart", "repo_id": "flutter", "token_count": 1485 }
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 'package:flutter/material.dart'; /// Flutter code sample for [PopupMenuButton]. void main() => runApp(const PopupMenuApp()); class PopupMenuApp extends StatelessWidget { const PopupMenuApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: PopupMenuExample(), ); } } enum AnimationStyles { defaultStyle, custom, none } const List<(AnimationStyles, String)> animationStyleSegments = <(AnimationStyles, String)>[ (AnimationStyles.defaultStyle, 'Default'), (AnimationStyles.custom, 'Custom'), (AnimationStyles.none, 'None'), ]; enum Menu { preview, share, getLink, remove, download } class PopupMenuExample extends StatefulWidget { const PopupMenuExample({super.key}); @override State<PopupMenuExample> createState() => _PopupMenuExampleState(); } class _PopupMenuExampleState extends State<PopupMenuExample> { Set<AnimationStyles> _animationStyleSelection = <AnimationStyles>{AnimationStyles.defaultStyle}; AnimationStyle? _animationStyle; @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Padding( padding: const EdgeInsets.only(top: 50), child: Align( alignment: Alignment.topCenter, child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SegmentedButton<AnimationStyles>( selected: _animationStyleSelection, onSelectionChanged: (Set<AnimationStyles> styles) { setState(() { _animationStyleSelection = styles; switch (styles.first) { case AnimationStyles.defaultStyle: _animationStyle = null; case AnimationStyles.custom: _animationStyle = AnimationStyle( curve: Easing.emphasizedDecelerate, duration: const Duration(seconds: 3), ); case AnimationStyles.none: _animationStyle = AnimationStyle.noAnimation; } }); }, segments: animationStyleSegments .map<ButtonSegment<AnimationStyles>>(((AnimationStyles, String) shirt) { return ButtonSegment<AnimationStyles>(value: shirt.$1, label: Text(shirt.$2)); }) .toList(), ), const SizedBox(height: 10), PopupMenuButton<Menu>( popUpAnimationStyle: _animationStyle, icon: const Icon(Icons.more_vert), onSelected: (Menu item) { }, itemBuilder: (BuildContext context) => <PopupMenuEntry<Menu>>[ const PopupMenuItem<Menu>( value: Menu.preview, child: ListTile( leading: Icon(Icons.visibility_outlined), title: Text('Preview'), ), ), const PopupMenuItem<Menu>( value: Menu.share, child: ListTile( leading: Icon(Icons.share_outlined), title: Text('Share'), ), ), const PopupMenuItem<Menu>( value: Menu.getLink, child: ListTile( leading: Icon(Icons.link_outlined), title: Text('Get link'), ), ), const PopupMenuDivider(), const PopupMenuItem<Menu>( value: Menu.remove, child: ListTile( leading: Icon(Icons.delete_outline), title: Text('Remove'), ), ), const PopupMenuItem<Menu>( value: Menu.download, child: ListTile( leading: Icon(Icons.download_outlined), title: Text('Download'), ), ), ], ), ], ), ), ), ), ); } }
flutter/examples/api/lib/material/popup_menu/popup_menu.2.dart/0
{ "file_path": "flutter/examples/api/lib/material/popup_menu/popup_menu.2.dart", "repo_id": "flutter", "token_count": 2529 }
578