text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
*
* 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 io.flutter.actions;
import com.android.tools.idea.assistant.AssistantBundleCreator;
import com.android.tools.idea.assistant.OpenAssistSidePanelAction;
import com.intellij.ide.actions.WhatsNewAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerListener;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.wm.ex.ToolWindowManagerListener;
import io.flutter.FlutterInitializer;
import io.flutter.assistant.whatsnew.FlutterNewsBundleCreator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.jetbrains.annotations.NotNull;
// Adapted from com.android.tools.idea.whatsnew.assistant.WhatsNewSidePanelAction.
public class OpenFlutterNewsSidePanelAction extends OpenAssistSidePanelAction {
@NotNull
private static final WhatsNewAction action = new WhatsNewAction();
@NotNull
private static final Set<Project> openProjectTools = new HashSet<>();
@NotNull
private final Map<Project, FlutterNewsToolWindowListener> myProjectToListenerMap;
public OpenFlutterNewsSidePanelAction() {
myProjectToListenerMap = new HashMap<>();
}
@Override
public void update(@NotNull AnActionEvent e) {
// Project being null can happen when Studio first starts and doesn't have window focus
Presentation presentation = e.getPresentation();
if (e.getProject() == null) {
presentation.setEnabled(false);
}
else if (!presentation.isEnabled()) {
presentation.setEnabled(true);
}
action.update(e);
presentation.setText("What's New in Flutter");
presentation.setDescription("See the recent updates to Flutter and the plugin.");
}
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
openWhatsNewSidePanel(Objects.requireNonNull(event.getProject()), false);
}
public void openWhatsNewSidePanel(@NotNull Project project, boolean isAutoOpened) {
FlutterNewsBundleCreator bundleCreator = AssistantBundleCreator.EP_NAME.findExtension(FlutterNewsBundleCreator.class);
if (bundleCreator == null) {
return;
}
FlutterNewsToolWindowListener.fireOpenEvent(project, isAutoOpened);
openWindow(FlutterNewsBundleCreator.BUNDLE_ID, project);
// Only register a new listener if there isn't already one, to avoid multiple OPEN/CLOSE events
myProjectToListenerMap.computeIfAbsent(project, this::newFlutterNewsToolWindowListener);
}
@NotNull
private OpenFlutterNewsSidePanelAction.FlutterNewsToolWindowListener newFlutterNewsToolWindowListener(@NotNull Project project) {
FlutterNewsToolWindowListener listener = new FlutterNewsToolWindowListener(project, myProjectToListenerMap);
project.getMessageBus().connect(project).subscribe(ToolWindowManagerListener.TOPIC, listener);
return listener;
}
static class FlutterNewsToolWindowListener implements ToolWindowManagerListener {
@NotNull private final Project myProject;
@NotNull Map<Project, FlutterNewsToolWindowListener> myProjectToListenerMap;
private boolean isOpen;
private FlutterNewsToolWindowListener(@NotNull Project project,
@NotNull Map<Project, FlutterNewsToolWindowListener> projectToListenerMap) {
myProject = project;
myProjectToListenerMap = projectToListenerMap;
isOpen = true; // Start off as opened so we don't fire an extra opened event
// Need an additional listener for project close, because the below invokeLater isn't fired in time before closing
project.getMessageBus().connect(project).subscribe(ProjectManager.TOPIC, new ProjectManagerListener() {
@Override
public void projectClosed(@NotNull Project project) {
if (!project.equals(myProject)) {
return;
}
if (isOpen) {
fireClosedEvent(myProject);
isOpen = false;
}
myProjectToListenerMap.remove(project);
}
});
}
@Override
public void toolWindowRegistered(@NotNull String id) {
}
@Override
public void toolWindowUnregistered(@NotNull String id, @NotNull ToolWindow toolWindow) {
if (id.equals("Assistant:")) {
myProjectToListenerMap.remove(myProject);
}
}
/**
* Fire metrics and update the actual state after a state change is received.
* The logic is wrapped in invokeLater because dragging and dropping the StripeButton temporarily
* hides and then shows the window. Otherwise, the handler would think the window was closed,
* even though it was only dragged.
*/
@SuppressWarnings("override")
public void stateChanged(@NotNull ToolWindowManager toolWindowManager) {
ApplicationManager.getApplication().invokeLater(() -> {
if (myProject.isDisposed()) {
myProjectToListenerMap.remove(myProject);
return;
}
ToolWindow window = ToolWindowManager.getInstance(myProject).getToolWindow("Assistant:");
if (window == null) {
return;
}
if (!FlutterNewsBundleCreator.BUNDLE_ID.equals(window.getHelpId())) {
return;
}
if (isOpen && !window.isVisible()) {
fireClosedEvent(myProject);
isOpen = false;
}
else if (!isOpen && window.isVisible()) {
fireOpenEvent(myProject, false);
isOpen = true;
}
});
}
private static void fireOpenEvent(@NotNull Project project, boolean isAutoOpened) {
// An extra "open" can fire when the window is already open and the user manually uses the OpenFlutterNewsSidePanelAction
// again, so in this case just ignore the call.
if (openProjectTools.contains(project)) return;
FlutterInitializer.getAnalytics().sendEvent("intellij", isAutoOpened ? "AutoOpenFlutterNews" : "OpenFlutterNews");
}
private static void fireClosedEvent(@NotNull Project project) {
openProjectTools.remove(project);
FlutterInitializer.getAnalytics().sendEvent("intellij", "CloseFlutterNews");
}
}
}
| flutter-intellij/flutter-studio/src/io/flutter/actions/OpenFlutterNewsSidePanelAction.java/0 | {
"file_path": "flutter-intellij/flutter-studio/src/io/flutter/actions/OpenFlutterNewsSidePanelAction.java",
"repo_id": "flutter-intellij",
"token_count": 2346
} | 471 |
name = "flutter-intellij"
org.gradle.parallel=true
org.gradle.jvmargs=-Xms1024m -Xmx4048m
javaVersion=17
androidVersion=233.13135.106
dartVersion=233.14888
flutterPluginVersion=SNAPSHOT
ide=android-studio
testing=false
buildSpec=2023.3
baseVersion=233.13135.103
smaliPlugin=com.android.tools.idea.smali
langPlugin=org.intellij.intelliLang
kotlin.stdlib.default.dependency=false
ideVersion=2023.3.1.13 | flutter-intellij/gradle.properties/0 | {
"file_path": "flutter-intellij/gradle.properties",
"repo_id": "flutter-intellij",
"token_count": 159
} | 472 |
<idea-plugin>
<id>@PLUGINID@</id>
<name>Flutter</name>
<description>
<![CDATA[
<p>Support for developing Flutter applications. Flutter gives developers an easy and productive
way to build and deploy cross-platform, high-performance mobile apps for both Android and iOS.
Installing this plugin will also install the Dart plugin.</p>
<br>
<p>For some tools, this plugin uses Chromium through JxBrowser to display content from the web.
JxBrowser complies with LGPL and offers an option to replace Chromium with another component.
To do this:</p>
<li>Find the JxBrowser files stored in the <a href="https://www.jetbrains.com/help/idea/tuning-the-ide.html?_ga=2.242942337.2083770720.1598541288-1470153005.1588544220#plugins-directory">plugins directory</a>, under /flutter-intellij/jxbrowser.</li>
<li>The LGPL requirements are at <a href="https://teamdev.com/jxbrowser/lgpl-compliance/#source-code">from JxBrowser</a>, here you can also download the build script to relink with modified components.</li>
]]>
</description>
<!--suppress PluginXmlValidity -->
<vendor url="https://google.com">Google</vendor>
<category>Custom Languages</category>
@VERSION@
<idea-version since-build="@SINCE@" until-build="@UNTIL@"/>
<depends>com.intellij.modules.platform</depends>
<depends>com.intellij.modules.lang</depends>
<depends>com.intellij.modules.xdebugger</depends>
<depends>com.intellij.modules.coverage</depends>
<depends>org.jetbrains.plugins.yaml</depends>
<depends>org.jetbrains.android</depends>
<depends>Dart</depends>
<depends>Git4Idea</depends>
<!-- plugin compatibility -->
<!-- see: http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/plugin_compatibility.html -->
<!-- Contributes IDEA-specific features and implementations. -->
<depends optional="true" config-file="idea-contribs.xml">com.intellij.modules.java</depends>
<depends optional="true" config-file="flutter-coverage.xml">com.intellij.modules.coverage</depends>
<!-- Contributes Android Studio-specific features and implementations. -->
<!--suppress PluginXmlValidity -->
<depends optional="true" config-file="studio-contribs.xml">@DEPEND@</depends>
<change-notes>
<![CDATA[
@CHANGELOG@]]>
</change-notes>
<!-- Everything following should be SmallIDE-friendly.-->
<!-- See: http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/plugin_compatibility.html -->
<actions>
<group id="Flutter.InspectorActions">
<action id="Flutter.JumpToTypeSource" class="io.flutter.inspector.JumpToTypeSourceAction"
description="Jump to Type Source"
text="Jump to Type Source">
<keyboard-shortcut keymap="$default" first-keystroke="shift F4"/>
</action>
<action id="Flutter.JumpToSource" class="io.flutter.inspector.JumpToSourceAction"
text="Jump to Source">
<keyboard-shortcut keymap="$default" first-keystroke="control DOWN"/>
</action>
</group>
<group id="Flutter.MainToolbarActions">
<action id="Flutter.DeviceSelector" class="io.flutter.actions.DeviceSelectorAction"
description="Flutter Device Selection"
icon="FlutterIcons.Phone"/>
<action id="Flutter.DeviceSelectorRefresher" class="io.flutter.actions.DeviceSelectorRefresherAction"
text="Refresh Device List"
description="Refresh device list" />
<add-to-group group-id="MainToolbarRight" />
<add-to-group anchor="before" group-id="ToolbarRunGroup" relative-to-action="RunConfiguration"/>
</group>
<group id="FlutterToolsActionGroup" class="io.flutter.actions.FlutterToolsActionGroup" popup="true"
text="Flutter" description="Flutter Tools" icon="FlutterIcons.Flutter">
<add-to-group group-id="ToolsMenu" anchor="last"/>
<action id="flutter.gettingStarted" class="io.flutter.actions.FlutterGettingStartedAction"
text="Getting Started"
description="View the online getting started documentation"/>
<separator/>
<action id="flutter.upgrade" class="io.flutter.actions.FlutterUpgradeAction"
text="Flutter Upgrade"
description="Run 'flutter upgrade'"/>
<action id="flutter.doctor" class="io.flutter.actions.FlutterDoctorAction"
text="Flutter Doctor"
description="Run 'flutter doctor'"/>
<separator/>
<action id="flutter.pub.get" class="io.flutter.actions.FlutterPackagesGetAction"
text="Flutter Pub Get"
description="Run 'flutter pub get'"/>
<action id="flutter.pub.upgrade" class="io.flutter.actions.FlutterPackagesUpgradeAction"
text="Flutter Pub Upgrade"
description="Run 'flutter pub upgrade'"/>
<separator/>
<action id="flutter.clean" class="io.flutter.actions.FlutterCleanAction"
text="Flutter Clean"
description="Run 'flutter clean'"/>
<separator/>
<action id="flutter.devtools.open" class="io.flutter.run.OpenDevToolsAction"
text="Open Flutter DevTools"
description="Open Flutter DevTools"/>
<separator/>
<action id="flutter.androidstudio.open" class="io.flutter.actions.OpenInAndroidStudioAction"
text="Open Android module in Android Studio"
description="Launch Android Studio to edit the Android module as a top-level project"/>
<action id="flutter.xcode.open" class="io.flutter.actions.OpenInXcodeAction"
text="Open iOS/macOS module in Xcode"
description="Launch Xcode to edit the iOS module as a top-level project"/>
<action id="flutter.appcode.open" class="io.flutter.actions.OpenInAppCodeAction"
text="Open iOS module in AppCode"
description="Launch AppCode to edit the iOS module as a top-level project"/>
<separator/>
<action id="flutter.submitFeedback" class="io.flutter.actions.FlutterSubmitFeedback"
text="Submit Feedback..."
description="Provide feedback for the Flutter plugin"/>
</group>
<!-- project explorer actions -->
<group id="FlutterPackagesExplorerActionGroup" class="io.flutter.actions.FlutterPackagesExplorerActionGroup">
<separator/>
<group text="Flutter" description="Flutter Tools" icon="FlutterIcons.Flutter" popup="true">
<separator/>
<reference ref="flutter.pub.get"/>
<reference ref="flutter.pub.upgrade"/>
<separator/>
<reference ref="flutter.androidstudio.open"/>
<reference ref="flutter.xcode.open"/>
<reference ref="flutter.appcode.open"/>
<separator/>
<reference ref="flutter.upgrade"/>
<reference ref="flutter.doctor"/>
</group>
<separator/>
<add-to-group group-id="ProjectViewPopupMenu" relative-to-action="AddToFavorites" anchor="before"/>
</group>
<group id="FlutterExternalIdeActionGroup" class="io.flutter.actions.FlutterExternalIdeActionGroup">
<separator/>
<group text="Flutter" description="Flutter Tools" icon="FlutterIcons.Flutter" popup="true">
<reference ref="flutter.androidstudio.open"/>
<reference ref="flutter.xcode.open"/>
<reference ref="flutter.appcode.open"/>
</group>
<separator/>
<add-to-group group-id="ProjectViewPopupMenu" relative-to-action="AddToFavorites" anchor="before"/>
</group>
<group id="FlutterBuildActionGroup" class="io.flutter.actions.FlutterBuildActionGroup">
<separator/>
<group text="Flutter" popup="true">
<action id="flutter.build.aar" text="Build AAR" description="Building a Flutter module for Android add-to-app"
class="io.flutter.actions.FlutterBuildActionGroup$AAR"/>
<action id="flutter.build.apk" text="Build APK" description="Building a Flutter app for general distribution"
class="io.flutter.actions.FlutterBuildActionGroup$APK"/>
<!--suppress PluginXmlCapitalization -->
<action id="flutter.build.aab" text="Build App Bundle" description="Building a Flutter app for Google Play Store distribution"
class="io.flutter.actions.FlutterBuildActionGroup$AppBundle"/>
<!--suppress PluginXmlCapitalization -->
<action id="flutter.build.ios" text="Build iOS" description="Building a Flutter app for Apple App Store distribution"
class="io.flutter.actions.FlutterBuildActionGroup$Ios"/>
<action id="flutter.build.web" text="Build Web" description="Building a Flutter app for web"
class="io.flutter.actions.FlutterBuildActionGroup$Web"/>
</group>
<add-to-group group-id="BuildMenu" anchor="first"/>
</group>
<!-- main toolbar run actions -->
<action id="AttachDebuggerAction"
class="io.flutter.actions.AttachDebuggerAction"
text="Flutter Attach"
description="Attach debugger to a Flutter process embedded in an Android app"
icon="FlutterIcons.AttachDebugger">
<add-to-group group-id="ToolbarRunGroup" anchor="after" relative-to-action="RunnerActions"/>
</action>
<action id="Flutter.Toolbar.ReloadAction" class="io.flutter.actions.ReloadFlutterAppRetarget"
description="Reload"
icon="FlutterIcons.HotReload">
<add-to-group group-id="ToolbarRunGroup" anchor="after" relative-to-action="RunnerActions"/>
<keyboard-shortcut keymap="$default" first-keystroke="ctrl BACK_SLASH"/>
</action>
<!-- run menu actions -->
<group id="Flutter.MenuActions.Run">
<separator/>
<reference ref="Flutter.Toolbar.ReloadAction"/>
<action id="Flutter.Toolbar.RestartAction" class="io.flutter.actions.RestartFlutterAppRetarget"
description="Restart"
icon="FlutterIcons.HotRestart">
<keyboard-shortcut keymap="$default" first-keystroke="ctrl shift BACK_SLASH"/>
</action>
<action id="Flutter.Toolbar.ReloadAllAction" class="io.flutter.actions.ReloadAllFlutterAppsRetarget"
description="Reload All Devices"
icon="FlutterIcons.HotReload">
<keyboard-shortcut keymap="$default" first-keystroke="ctrl alt BACK_SLASH"/>
</action>
<action id="Flutter.Toolbar.RestartAllAction" class="io.flutter.actions.RestartAllFlutterAppsRetarget"
description="Restart All Devices"
icon="FlutterIcons.HotRestart">
<keyboard-shortcut keymap="$default" first-keystroke="ctrl alt shift BACK_SLASH"/>
</action>
<separator/>
<action id="Flutter.Menu.RunProfileAction" class="io.flutter.actions.RunProfileFlutterApp"
description="Flutter Run Profile Mode"
icon="AllIcons.Actions.Execute">
</action>
<action id="Flutter.Menu.RunReleaseAction" class="io.flutter.actions.RunReleaseFlutterApp"
description="Flutter Run Release Mode"
icon="AllIcons.Actions.Execute">
</action>
<reference ref="AttachDebuggerAction"/>
<separator/>
<add-to-group group-id="RunMenu" anchor="after" relative-to-action="Stop"/>
</group>
<!-- refactoring menu -->
<action class="io.flutter.actions.ExtractWidgetAction" id="Flutter.ExtractWidget" text="Extract Flutter Widget...">
<add-to-group group-id="IntroduceActionsGroup" anchor="after" relative-to-action="ExtractMethod"/>
<keyboard-shortcut keymap="$default" first-keystroke="ctrl alt W"/>
</action>
<!-- help menu -->
<action class="io.flutter.actions.FlutterGettingStartedAction" id="Flutter.FlutterHelp" text="Flutter Plugin Help">
<add-to-group group-id="HelpMenu" anchor="after" relative-to-action="HelpTopics"/>
</action>
<action id="io.flutter.RestartDaemon" class="io.flutter.actions.RestartFlutterDaemonAction"
text="Restart Flutter Daemon" description="Restart Flutter Daemon" icon="FlutterIcons.Flutter">
</action>
<action id="io.flutter.OpenDevToolsAction" class="io.flutter.run.OpenDevToolsAction"
text="Open Flutter DevTools" description="Open Flutter DevTools" icon="FlutterIcons.Dart_16">
</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>
<applicationListeners>
<listener class="io.flutter.font.ProjectOpenListener"
topic="com.intellij.openapi.project.ProjectManagerListener"/>
</applicationListeners>
<projectListeners>
<listener class="io.flutter.view.FlutterViewFactory$FlutterViewListener" topic="com.intellij.openapi.wm.ex.ToolWindowManagerListener"/>
<listener class="io.flutter.performance.FlutterPerformanceViewFactory$FlutterPerformanceViewListener"
topic="com.intellij.openapi.wm.ex.ToolWindowManagerListener"/>
<listener class="io.flutter.preview.PreviewViewFactory$PreviewViewListener"
topic="com.intellij.openapi.wm.ex.ToolWindowManagerListener"/>
</projectListeners>
<extensionPoints>
<extensionPoint name="gradleSyncProvider" interface="io.flutter.android.GradleSyncProvider"/>
<extensionPoint name="colorPickerProvider" interface="io.flutter.editor.ColorPickerProvider"/>
</extensionPoints>
<extensions defaultExtensionNs="io.flutter">
<gradleSyncProvider implementation="io.flutter.android.IntellijGradleSyncProvider" order="last"/>
<colorPickerProvider implementation="io.flutter.editor.IntellijColorPickerProvider" order="last"/>
</extensions>
<extensions defaultExtensionNs="com.intellij">
<postStartupActivity implementation="io.flutter.ProjectOpenActivity"/>
<postStartupActivity implementation="io.flutter.FlutterInitializer"/>
<projectService serviceInterface="io.flutter.run.daemon.DeviceService"
serviceImplementation="io.flutter.run.daemon.DeviceService"/>
<projectService serviceInterface="io.flutter.run.daemon.DevToolsService"
serviceImplementation="io.flutter.run.daemon.DevToolsService"/>
<projectService serviceInterface="io.flutter.dart.FlutterDartAnalysisServer"
serviceImplementation="io.flutter.dart.FlutterDartAnalysisServer"/>
<projectService serviceInterface="io.flutter.bazel.WorkspaceCache"
serviceImplementation="io.flutter.bazel.WorkspaceCache"/>
<projectService serviceImplementation="io.flutter.pub.PubRootCache"/>
<projectService serviceImplementation="io.flutter.analytics.FlutterAnalysisServerListener"/>
<configurationType implementation="io.flutter.run.FlutterRunConfigurationType"/>
<runConfigurationProducer implementation="io.flutter.run.FlutterRunConfigurationProducer"/>
<programRunner implementation="io.flutter.run.FlutterRunner"/>
<configurationType implementation="io.flutter.run.test.FlutterTestConfigType"/>
<runConfigurationProducer implementation="io.flutter.run.test.FlutterTestConfigProducer"/>
<programRunner implementation="io.flutter.run.test.FlutterTestRunner"/>
<runLineMarkerContributor language="Dart" implementationClass="io.flutter.run.test.FlutterTestLineMarkerContributor"/>
<configurationType implementation="io.flutter.run.bazel.FlutterBazelRunConfigurationType"/>
<programRunner implementation="io.flutter.run.bazel.BazelRunner"/>
<configurationType implementation="io.flutter.run.bazelTest.FlutterBazelTestConfigurationType"/>
<runConfigurationProducer implementation="io.flutter.run.bazelTest.BazelTestConfigProducer"/>
<runConfigurationProducer implementation="io.flutter.run.bazelTest.BazelWatchTestConfigProducer"/>
<programRunner implementation="io.flutter.run.bazelTest.BazelTestRunner"/>
<runLineMarkerContributor language="Dart" implementationClass="io.flutter.run.bazelTest.FlutterBazelTestLineMarkerContributor"/>
<defaultLiveTemplatesProvider implementation="io.flutter.template.FlutterLiveTemplatesProvider"/>
<liveTemplateContext implementation="io.flutter.template.DartToplevelTemplateContextType"/>
<!-- IDEA only -->
<moduleBuilder builderClass="io.flutter.module.FlutterModuleBuilder"/>
<projectService serviceImplementation="io.flutter.sdk.FlutterSdkManager"/>
<projectService serviceImplementation="io.flutter.sdk.AndroidEmulatorManager"/>
<applicationService serviceInterface="io.flutter.settings.FlutterSettings"
serviceImplementation="io.flutter.settings.FlutterSettings"
overrides="false"/>
<applicationService serviceImplementation="io.flutter.jxbrowser.EmbeddedBrowserEngine" overrides="false" />
<applicationService serviceImplementation="io.flutter.font.FontPreviewProcessor"/>
<console.folding implementation="io.flutter.console.FlutterConsoleFolding" id="1"/>
<console.folding implementation="io.flutter.console.FlutterConsoleExceptionFolding" order="after 1"/>
<console.folding implementation="io.flutter.logging.FlutterConsoleLogFolding" order="last"/>
<projectConfigurable groupId="language" instance="io.flutter.sdk.FlutterSettingsConfigurable"
id="flutter.settings" key="flutter.title" bundle="io.flutter.FlutterBundle" nonDefaultProject="true"/>
<colorProvider implementation="io.flutter.editor.FlutterColorProvider"/>
<codeInsight.lineMarkerProvider language="Dart" implementationClass="io.flutter.editor.FlutterIconLineMarkerProvider"/>
<errorHandler implementation="io.flutter.FlutterErrorReportSubmitter"/>
<toolWindow id="Flutter Outline" anchor="right" icon="FlutterIcons.Flutter_13"
factoryClass="io.flutter.preview.PreviewViewFactory"/>
<projectService serviceImplementation="io.flutter.preview.PreviewView" overrides="false"/>
<toolWindow id="Flutter Inspector" anchor="right" icon="FlutterIcons.Flutter_13"
factoryClass="io.flutter.view.FlutterViewFactory"/>
<projectService serviceImplementation="io.flutter.view.FlutterView" overrides="false"/>
<toolWindow id="Flutter Performance" anchor="right" icon="FlutterIcons.Flutter_13"
factoryClass="io.flutter.performance.FlutterPerformanceViewFactory"/>
<projectService serviceImplementation="io.flutter.performance.FlutterPerformanceView" overrides="false"/>
<projectOpenProcessor id="flutter" implementation="io.flutter.project.FlutterProjectOpenProcessor" order="first"/>
<localInspection bundle="io.flutter.FlutterBundle" key="outdated.dependencies.inspection.name"
groupName="Flutter" enabledByDefault="true" level="WARNING" language="Dart"
implementationClass="io.flutter.inspections.FlutterDependencyInspection"/>
<editorNotificationProvider implementation="io.flutter.editor.FlutterPubspecNotificationProvider"/>
<editorNotificationProvider implementation="io.flutter.inspections.SdkConfigurationNotificationProvider"/>
<editorNotificationProvider implementation="io.flutter.editor.NativeEditorNotificationProvider"/>
<editorNotificationProvider implementation="io.flutter.samples.FlutterSampleNotificationProvider"/>
<projectService serviceInterface="io.flutter.run.FlutterReloadManager"
serviceImplementation="io.flutter.run.FlutterReloadManager"
overrides="false"/>
<projectService serviceInterface="io.flutter.editor.FlutterSaveActionsManager"
serviceImplementation="io.flutter.editor.FlutterSaveActionsManager"
overrides="false"/>
<projectService serviceInterface="io.flutter.run.FlutterAppManager"
serviceImplementation="io.flutter.run.FlutterAppManager"
overrides="false"/>
<projectService serviceInterface="io.flutter.perf.FlutterWidgetPerfManager"
serviceImplementation="io.flutter.perf.FlutterWidgetPerfManager"
overrides="false"/>
<projectService serviceInterface="io.flutter.editor.ActiveEditorsOutlineService"
serviceImplementation="io.flutter.editor.ActiveEditorsOutlineService"
overrides="false"/>
<projectService serviceInterface="io.flutter.editor.EditorMouseEventService"
serviceImplementation="io.flutter.editor.EditorMouseEventService"
overrides="false"/>
<projectService serviceInterface="io.flutter.editor.EditorPositionService"
serviceImplementation="io.flutter.editor.EditorPositionService"
overrides="false"/>
<projectService serviceInterface="io.flutter.inspector.InspectorGroupManagerService"
serviceImplementation="io.flutter.inspector.InspectorGroupManagerService"
overrides="false"/>
<iconProvider implementation="io.flutter.project.FlutterIconProvider" order="first"/>
<library.type implementation="io.flutter.sdk.FlutterPluginLibraryType"/>
<projectStructureDetector implementation="io.flutter.project.FlutterProjectStructureDetector"/>
<additionalTextAttributes scheme="Default" file="colorSchemes/FlutterLogColorSchemeDefault.xml"/>
<additionalTextAttributes scheme="Default" file="colorSchemes/FlutterCodeColorSchemeDefault.xml"/>
<search.optionContributor implementation="io.flutter.sdk.FlutterSearchableOptionContributor"/>
<readerModeMatcher implementation="io.flutter.editor.FlutterReaderModeMatcher"/>
<projectService serviceInterface="io.flutter.editor.WidgetIndentsHighlightingPassFactory"
serviceImplementation="io.flutter.editor.WidgetIndentsHighlightingPassFactory"
overrides="false"/>
<highlightingPassFactory implementation="io.flutter.editor.WidgetIndentsHighlightingPassFactoryRegistrar"/>
<projectService serviceInterface="io.flutter.jxbrowser.EmbeddedJxBrowser"
serviceImplementation="io.flutter.jxbrowser.EmbeddedJxBrowser"
overrides="false"/>
<projectService serviceInterface="io.flutter.view.EmbeddedJcefBrowser"
serviceImplementation="io.flutter.view.EmbeddedJcefBrowser"
overrides="false"/>
<notificationGroup displayType="STICKY_BALLOON" id="deeplink"/>
</extensions>
<!-- Dart Plugin extensions -->
<extensions defaultExtensionNs="Dart">
<completionExtension implementation="io.flutter.editor.FlutterCompletionContributor" order="last"/>
<completionTimerExtension implementation="io.flutter.analytics.DartCompletionTimerListener"/>
</extensions>
</idea-plugin>
| flutter-intellij/resources/META-INF/plugin_template.xml/0 | {
"file_path": "flutter-intellij/resources/META-INF/plugin_template.xml",
"repo_id": "flutter-intellij",
"token_count": 8260
} | 473 |
<templateSet group="Flutter">
<template name="stless" value="class $NAME$ extends StatelessWidget { const $NAME$({super.key}); @override Widget build(BuildContext context) { return const Placeholder($END$); } } " description="New Stateless widget" toReformat="false" toShortenFQNames="true">
<variable name="NAME" expression="" defaultValue="" alwaysStopAt="true" />
<context>
<option name="DART_TOPLEVEL" value="true" />
</context>
</template>
<template name="stful" value="class $NAME$ extends StatefulWidget { const $NAME$({super.key}); @override State<$NAME$> createState() => $SNAME$(); } class $SNAME$ extends State<$NAME$> { @override Widget build(BuildContext context) { return const Placeholder($END$); } } " description="New Stateful widget" toReformat="false" toShortenFQNames="true">
<variable name="NAME" expression="" defaultValue="" alwaysStopAt="true" />
<variable name="SNAME" expression="regularExpression(concat("_", NAME, "State"), "^__", "_")" defaultValue="" alwaysStopAt="false" />
<context>
<option name="DART_TOPLEVEL" value="true" />
</context>
</template>
<template name="inh" value="class $NAME$ extends InheritedWidget { const $NAME$({ super.key, required Widget child, }) : super(child: child); static $NAME$ of(BuildContext context) { final $NAME$? result = context.dependOnInheritedWidgetOfExactType<$NAME$>(); assert(result != null, 'No $NAME$ found in context'); return result!; } @override bool updateShouldNotify($NAME$ old) { return $SHOULD_NOTIFY$; } } " description="New Inherited widget" toReformat="true" toShortenFQNames="true">
<variable name="NAME" expression="" defaultValue="" alwaysStopAt="true" />
<variable name="SHOULD_NOTIFY" expression="" defaultValue="" alwaysStopAt="true" />
<context>
<option name="DART_TOPLEVEL" value="true" />
</context>
</template>
<template name="stanim" value="class $NAME$ extends StatefulWidget { const $NAME$({super.key}); @override State<$NAME$> createState() => _$NAME$State(); } class _$NAME$State extends State<$NAME$> with SingleTickerProviderStateMixin { late AnimationController _controller; @override void initState() { super.initState(); _controller = AnimationController(vsync: this); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return const Placeholder($END$); } } " description="New Stateful widget with AnimationController" toReformat="false" toShortenFQNames="true">
<variable name="NAME" expression="" defaultValue="" alwaysStopAt="true" />
<context>
<option name="DART_TOPLEVEL" value="true" />
</context>
</template>
<template name="thof" value="Theme.of(context)" description="Create ThemeData from build context" toReformat="false" toShortenFQNames="true">
<context>
<option name="DART_STATEMENT" value="true"/>
</context>
</template>
<template name="ihof" value="$NAME$.of(context)" description="Create ThemeData from an InheritedWidget" toReformat="false" toShortenFQNames="true">
<variable name="NAME" expression="" defaultValue="" alwaysStopAt="true" />
<context>
<option name="DART_STATEMENT" value="true"/>
</context>
</template>
<template name="mdof" value="MediaQuery.of(context)" description="Create MediaQueryData from build context" toReformat="false" toShortenFQNames="true">
<context>
<option name="DART_STATEMENT" value="true"/>
</context>
</template>
</templateSet>
| flutter-intellij/resources/liveTemplates/flutter_miscellaneous.xml/0 | {
"file_path": "flutter-intellij/resources/liveTemplates/flutter_miscellaneous.xml",
"repo_id": "flutter-intellij",
"token_count": 1473
} | 474 |
// Copyright 2017 The Chromium Authors. All rights reserved. Use of this source
// code is governed by a BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'package:markdown/markdown.dart';
import 'util.dart';
class BuildSpec {
// Build targets
final String name;
final String version;
final String? ijVersion;
final bool isTestTarget;
final bool isUnitTestTarget;
final String ideaProduct;
final String ideaVersion;
final String androidPluginVersion;
final String dartPluginVersion;
final String baseVersion;
// plugin.xml variables
final String sinceBuild;
final String untilBuild;
final String pluginId = 'io.flutter';
final String? release;
final List<dynamic> filesToSkip;
String channel;
String? _changeLog;
BuildSpec.fromJson(Map json, this.release)
: name = json['name'],
channel = json['channel'],
version = json['version'],
ijVersion = json['ijVersion'],
ideaProduct = json['ideaProduct'],
ideaVersion = json['ideaVersion'],
baseVersion = json['baseVersion'] ?? json['ideaVersion'],
androidPluginVersion = json['androidPluginVersion'],
dartPluginVersion = json['dartPluginVersion'],
sinceBuild = json['sinceBuild'],
untilBuild = json['untilBuild'],
filesToSkip = json['filesToSkip'] ?? [],
isUnitTestTarget = (json['isUnitTestTarget'] ?? 'false') == 'true',
isTestTarget = (json['isTestTarget'] ?? 'false') == 'true';
bool get copyIjVersion => isAndroidStudio && ijVersion != null;
bool get isAndroidStudio => ideaProduct.contains('android-studio');
bool get isDevChannel => channel == 'dev';
bool get isStableChannel => channel == 'stable';
bool get isReleaseMode => release != null;
bool get isSynthetic => false;
String get productFile => isAndroidStudio ? "$ideaProduct-ide" : ideaProduct;
String get changeLog {
if (_changeLog == null) {
if (channel == 'stable') {
_changeLog = _parseChangelog();
} else {
_changeLog = '';
}
}
return _changeLog!;
}
String _parseChangelog() {
var text = File('CHANGELOG.md').readAsStringSync();
return _parseChanges(text);
}
String _parseChanges(String text) {
var html = markdownToHtml(text);
// Translate our markdown based changelog into html; remove unwanted
// paragraph tags.
return html
.replaceAll('</h2><ul>', '</h2>\n<ul>')
.replaceAll('<ul>\n<li>', '<ul>\n <li>')
.replaceAll('</li>\n<li>', '</li>\n <li>')
.replaceAll('</li></ul>', '</li>\n</ul>')
.replaceAll('\n<p>', '')
.replaceAll('<p>', '')
.replaceAll('</p>\n', '')
.replaceAll('</p>', '');
}
@override
String toString() {
return 'BuildSpec($ideaProduct $ideaVersion $dartPluginVersion $sinceBuild '
'$untilBuild version: "$release")';
}
Future<BuildSpec> initChangeLog() async {
if (channel == 'dev') {
_changeLog = _parseChanges(await makeDevLog(this));
}
return this;
}
void buildForDev() {
// Build everything. For release builds we do not build specs on the dev channel.
if (channel == 'stable') channel = 'dev';
}
void buildForMaster() {
// Ensure the dev-channel-only files are stored in release_master.
if (channel == 'dev') channel = 'stable';
}
}
/// This represents a BuildSpec that is used to generate the plugin.xml
/// that is used during development. It needs to span all possible versions.
/// The product-matrix.json file lists the versions in increasing build order.
/// The first one is the earliest version used during development and the
/// last one is the latest used during development. This BuildSpec combines
/// those two.
class SyntheticBuildSpec extends BuildSpec {
late BuildSpec alternate;
SyntheticBuildSpec.fromJson(
super.json, super.releaseNum, List<BuildSpec> specs) :super.fromJson() {
try {
// 'isUnitTestTarget' should always be in the spec for the latest IntelliJ (not AS).
alternate = specs.firstWhere((s) => s.isUnitTestTarget);
} on StateError catch (_) {
log('No build spec defines "isUnitTestTarget"');
exit(1);
}
}
@override
String get sinceBuild => alternate.sinceBuild;
@override
String get untilBuild => alternate.untilBuild;
@override
bool get isSynthetic => true;
}
| flutter-intellij/tool/plugin/lib/build_spec.dart/0 | {
"file_path": "flutter-intellij/tool/plugin/lib/build_spec.dart",
"repo_id": "flutter-intellij",
"token_count": 1554
} | 475 |
# Below is a list of people and organizations that have contributed
# to the Flutter project. Names should be added to the list like so:
#
# Name/Organization <email address>
#
# Anyone who has contributed to the Flutter project in any way (not
# limited to submitting PRs) is welcome to submit a PR to add their
# name to this file.
#
# Thanks to everyone for your contributions!
Google Inc.
The Chromium Authors
The Fuchsia Authors
Jim Simon <[email protected]>
Lex Berezhny <[email protected]>
Wyatt Arent <[email protected]>
Michael Perrotte <[email protected]>
Günter Zöchbauer <[email protected]>
Raju Bitter <[email protected]>
Michael Beckler <[email protected]>
Alexandre Ardhuin <[email protected]>
Luke Freeman <[email protected]>
Vincent Le Quéméner <[email protected]>
Mike Hoolehan <[email protected]>
German Saprykin <[email protected]>
Stefano Rodriguez <[email protected]>
Yusuke Konishi <[email protected]>
Fredrik Simón <[email protected]>
Ali Bitek <[email protected]>
Tetsuhiro Ueda <[email protected]>
Dan Field <[email protected]>
Noah Groß <[email protected]>
Victor Choueiri <[email protected]>
Christian Mürtz <[email protected]>
Lukasz Piliszczuk <[email protected]>
Felix Schmidt <[email protected]>
Artur Rymarz <[email protected]>
Chema Molins <[email protected]>
Stefan Mitev <[email protected]>
Jasper van Riet <[email protected]>
Mattijs Fuijkschot <[email protected]>
Volodymyr Lykhonis <[email protected]>
TruongSinh Tran-Nguyen <[email protected]>
Sander Dalby Larsen <[email protected]>
Marco Scannadinari <[email protected]>
Frederik Schweiger <[email protected]>
Martin Staadecker <[email protected]>
Igor Katsuba <[email protected]>
Diego Velásquez <[email protected]>
Simon Lightfoot <[email protected]>
Sarbagya Dhaubanjar <[email protected]>
Rody Davis Jr <[email protected]>
Robin Jespersen <[email protected]>
Jefferson Quesado <[email protected]>
Mark Diener <[email protected]>
Alek Åström <[email protected]>
Efthymios Sarpmpanis <[email protected]>
Cédric Wyss <[email protected]>
Michel Feinstein <[email protected]>
Michael Lee <[email protected]>
Katarina Sheremet <[email protected]>
Nicolas Schneider <[email protected]>
Mikhail Zotyev <[email protected]>
Maria Melnik <[email protected]>
Ayush Bherwani <[email protected]>
Luke Cheng <[email protected]>
Brian Wang <[email protected]>
法的空间 <[email protected]>
CaiJingLong <[email protected]>
Alex Li <[email protected]>
Ram Navan <[email protected]>
meritozh <[email protected]>
Terrence Addison Tandijono(flotilla) <[email protected]>
YeungKC <[email protected]>
Nobuhiro Tabuki <[email protected]>
nt4f04uNd <[email protected]>
Anurag Roy <[email protected]>
Andrey Kabylin <[email protected]>
vimerzhao <[email protected]>
Pedro Massango <[email protected]>
Hidenori Matsubayashi <[email protected]>
Perqin Xie <[email protected]>
Seongyun Kim <[email protected]>
Ludwik Trammer <[email protected]>
J-P Nurmi <[email protected]>
Marian Triebe <[email protected]>
Alexis Rouillard <[email protected]>
Mirko Mucaria <[email protected]>
Karol Czeryna <[email protected]>
Callum Moffat <[email protected]>
Koutaro Mori <[email protected]>
Sergei Smitskoi <[email protected]>
Casey Rogers <[email protected]>
Pradumna Saraf <[email protected]>
Kai Yu <[email protected]>
Denis Grafov <[email protected]>
TheOneWithTheBraid <[email protected]>
Alberto Miola <[email protected]>
Twin Sun, LLC <[email protected]>
Taskulu LDA <[email protected]>
Jonathan Joelson <[email protected]>
Elsabe Ros <[email protected]>
Nguyễn Phúc Lợi <[email protected]>
Jingyi Chen <[email protected]>
Junhua Lin <[email protected]>
Tomasz Gucio <[email protected]>
Jason C.H <[email protected]>
Hubert Jóźwiak <[email protected]>
David Neuy <[email protected]>
Eli Albert <[email protected]>
Jan Kuß <[email protected]>
André Sousa <[email protected]>
Bartek Pacia <[email protected]>
Mike Rydstrom <[email protected]>
Harish Anbalagan <[email protected]>
Kim Jiun <[email protected]>
LinXunFeng <[email protected]>
Sabin Neupane <[email protected]>
Mahdi Bagheri <[email protected]>
Mok Kah Wai <[email protected]>
Lucas Saudon <[email protected]>
Om Phatak <[email protected]>
| flutter/AUTHORS/0 | {
"file_path": "flutter/AUTHORS",
"repo_id": "flutter",
"token_count": 1957
} | 476 |
c7d7d1a03f65a27be2eddb13d1f2b0c0e7a60ec6
| flutter/bin/internal/usbmuxd.version/0 | {
"file_path": "flutter/bin/internal/usbmuxd.version",
"repo_id": "flutter",
"token_count": 32
} | 477 |
// 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 Cocoa
import FlutterMacOS
import XCTest
class RunnerTests: XCTestCase {
func testExample() {
// If you add code to the Runner application, consider adding tests here.
// See https://developer.apple.com/documentation/xctest for more information about using XCTest.
}
}
| flutter/dev/a11y_assessments/macos/RunnerTests/RunnerTests.swift/0 | {
"file_path": "flutter/dev/a11y_assessments/macos/RunnerTests/RunnerTests.swift",
"repo_id": "flutter",
"token_count": 131
} | 478 |
// 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';
void main() {
testWidgets('included', (WidgetTester tester) async {
expect(2 + 2, 4);
}, tags: <String>['include-tag']);
testWidgets('excluded', (WidgetTester tester) async {
throw 'this test should have been filtered out';
}, tags: <String>['exclude-tag']);
}
| flutter/dev/automated_tests/flutter_test/filtering_tag_widget_test.dart/0 | {
"file_path": "flutter/dev/automated_tests/flutter_test/filtering_tag_widget_test.dart",
"repo_id": "flutter",
"token_count": 161
} | 479 |
// 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' as system;
// this is a test to make sure our tests consider engine crashes to be failures
// see //flutter/dev/bots/test.dart
void main() {
system.Process.killPid(system.pid, system.ProcessSignal.sigsegv);
}
| flutter/dev/automated_tests/test_smoke_test/crash2_test.dart/0 | {
"file_path": "flutter/dev/automated_tests/test_smoke_test/crash2_test.dart",
"repo_id": "flutter",
"token_count": 120
} | 480 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
// Various tests to verify that animated image filtered layers do not
// dirty children even without explicit repaint boundaries. These intentionally use
// text to ensure we don't measure the opacity peephole case.
class AnimatedComplexImageFiltered extends StatefulWidget {
const AnimatedComplexImageFiltered({ super.key });
@override
State<AnimatedComplexImageFiltered> createState() => _AnimatedComplexImageFilteredState();
}
class _AnimatedComplexImageFilteredState extends State<AnimatedComplexImageFiltered> 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));
ui.ImageFilter imageFilter = ui.ImageFilter.blur();
@override
void initState() {
super.initState();
controller.repeat();
animation.addListener(() {
setState(() {
imageFilter = ui.ImageFilter.blur(sigmaX: animation.value * 5, sigmaY: animation.value * 5);
});
});
}
@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++)
ImageFiltered(
imageFilter: imageFilter,
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_image_filtered.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/animated_complex_image_filtered.dart",
"repo_id": "flutter",
"token_count": 839
} | 481 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:flutter/material.dart';
class SlidersPage extends StatefulWidget {
const SlidersPage({super.key});
@override
State<SlidersPage> createState() => _SlidersPageState();
}
class _SlidersPageState extends State<SlidersPage> with TickerProviderStateMixin {
late AnimationController _sliderController;
late Animation<double> _sliderAnimation;
double _sliderValue = 0.0;
RangeValues _rangeSliderValues = const RangeValues(0.0, 1.0);
@override
void initState() {
super.initState();
_sliderController = AnimationController(
duration: const Duration(seconds: 1),
vsync: this,
)..repeat();
_sliderAnimation = Tween<double>(begin: 0, end: 1).animate(_sliderController)
..addListener(() {
setState(() {
_sliderValue = _sliderAnimation.value;
_rangeSliderValues = RangeValues(
clampDouble(_sliderAnimation.value, 0, 0.45),
1.0 - clampDouble(_sliderAnimation.value, 0, 0.45),
);
});
});
}
@override
void dispose() {
_sliderController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Material(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Slider(
value: _sliderValue,
onChanged: (double value) { },
),
RangeSlider(
values: _rangeSliderValues,
onChanged: (RangeValues values) { },
),
],
),
);
}
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/sliders.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/sliders.dart",
"repo_id": "flutter",
"token_count": 698
} | 482 |
// 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';
class _NestedMouseRegion extends StatelessWidget {
const _NestedMouseRegion({required this.nests, required this.child});
final int nests;
final Widget child;
@override
Widget build(BuildContext context) {
Widget current = child;
for (int i = 0; i < nests; i++) {
current = MouseRegion(
onEnter: (_) {},
child: child,
);
}
return current;
}
}
/// Creates a grid of mouse regions, then continuously hover over them.
///
/// Measures our ability to hit test mouse regions.
class BenchMouseRegionGridHover extends WidgetRecorder {
BenchMouseRegionGridHover() : super(name: benchmarkName) {
_tester = _Tester(onDataPoint: handleDataPoint);
}
static const String benchmarkName = 'bench_mouse_region_grid_hover';
late _Tester _tester;
void handleDataPoint(Duration duration) {
profile!.addDataPoint('hitTestDuration', duration, reported: true);
}
// 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) => _NestedMouseRegion(
nests: 10,
child: Row(
children: List<Widget>.generate(
columnsCount,
(int columnIndex) => _NestedMouseRegion(
nests: 10,
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 {
_Tester({required this.onDataPoint});
final ValueSetter<Duration> onDataPoint;
static const Duration hoverDuration = Duration(milliseconds: 20);
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> _hoverTo(Offset location, Duration duration) async {
currentTime += duration;
final Stopwatch stopwatch = Stopwatch()..start();
await gesture.moveTo(location, timeStamp: currentTime);
stopwatch.stop();
onDataPoint(stopwatch.elapsed);
await _UntilNextFrame.wait();
}
Future<void> start() async {
await Future<void>.delayed(Duration.zero);
while (!_stopped) {
await _hoverTo(const Offset(30, 10), hoverDuration);
await _hoverTo(const Offset(10, 370), hoverDuration);
await _hoverTo(const Offset(370, 390), hoverDuration);
await _hoverTo(const Offset(390, 30), hoverDuration);
}
}
void stop() {
_stopped = true;
}
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_mouse_region_grid_hover.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_mouse_region_grid_hover.dart",
"repo_id": "flutter",
"token_count": 2004
} | 483 |
// 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 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:macrobenchmarks/common.dart';
import 'package:macrobenchmarks/main.dart' as app;
typedef ControlCallback = Future<void> Function(WidgetController controller);
class ScrollableButtonRoute {
ScrollableButtonRoute(this.listViewKey, this.buttonKey);
final String listViewKey;
final String buttonKey;
}
void macroPerfTestE2E(
String testName,
String routeName, {
Duration? pageDelay,
Duration duration = const Duration(seconds: 3),
ControlCallback? body,
ControlCallback? setup,
}) {
macroPerfTestMultiPageE2E(
testName,
<ScrollableButtonRoute>[
ScrollableButtonRoute(kScrollableName, routeName),
],
pageDelay: pageDelay,
duration: duration,
body: body,
setup: setup,
);
}
void macroPerfTestMultiPageE2E(
String testName,
List<ScrollableButtonRoute> routes, {
Duration? pageDelay,
Duration duration = const Duration(seconds: 3),
ControlCallback? body,
ControlCallback? setup,
}) {
final WidgetsBinding widgetsBinding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
assert(widgetsBinding is IntegrationTestWidgetsFlutterBinding);
final IntegrationTestWidgetsFlutterBinding binding = widgetsBinding as IntegrationTestWidgetsFlutterBinding;
binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.benchmarkLive;
testWidgets(testName, (WidgetTester tester) async {
assert(tester.binding == binding);
app.main();
await tester.pumpAndSettle();
// The slight initial delay avoids starting the timing during a
// period of increased load on the device. Without this delay, the
// benchmark has greater noise.
// See: https://github.com/flutter/flutter/issues/19434
await tester.binding.delayed(const Duration(microseconds: 250));
for (final ScrollableButtonRoute route in routes) {
expect(route.listViewKey, startsWith('/'));
expect(route.buttonKey, startsWith('/'));
// Make sure each list view page is settled
await tester.pumpAndSettle();
final Finder listView = find.byKey(ValueKey<String>(route.listViewKey));
// ListView is not a Scrollable, but it contains one
final Finder scrollable = find.descendant(of: listView, matching: find.byType(Scrollable));
// scrollable should find one widget as soon as the page is loaded
expect(scrollable, findsOneWidget);
final Finder button = find.byKey(ValueKey<String>(route.buttonKey), skipOffstage: false);
// button may or may not find a widget right away until we scroll to it
await tester.scrollUntilVisible(button, 50, scrollable: scrollable);
// After scrolling, button should find one Widget
expect(button, findsOneWidget);
// Allow scrolling to settle
await tester.pumpAndSettle();
await tester.tap(button);
// Cannot be pumpAndSettle because some tests have infinite animation.
await tester.pump(const Duration(milliseconds: 20));
}
if (pageDelay != null) {
// Wait for the page to load
await tester.binding.delayed(pageDelay);
}
if (setup != null) {
await setup(tester);
}
await binding.watchPerformance(() async {
final Future<void> durationFuture = tester.binding.delayed(duration);
if (body != null) {
await body(tester);
}
await durationFuture;
});
}, semanticsEnabled: false, timeout: Timeout.none);
}
| flutter/dev/benchmarks/macrobenchmarks/test/util.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/test/util.dart",
"repo_id": "flutter",
"token_count": 1243
} | 484 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert' show JsonEncoder;
import 'package:file/file.dart';
import 'package:flutter_driver/flutter_driver.dart';
import 'package:macrobenchmarks/common.dart';
import 'package:path/path.dart' as path;
import 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
import 'util.dart';
const JsonEncoder _prettyEncoder = JsonEncoder.withIndent(' ');
void main() {
test('stack_size', () async {
late int stackSizeInBytes;
await runDriverTestForRoute(kStackSizeRouteName, (FlutterDriver driver) async {
final String stackSize = await driver.getText(find.byValueKey(kStackSizeKey));
expect(stackSize.isNotEmpty, isTrue);
stackSizeInBytes = int.parse(stackSize);
});
expect(stackSizeInBytes > 0, isTrue);
await fs.directory(testOutputsDirectory).create(recursive: true);
final File file = fs.file(path.join(testOutputsDirectory, 'stack_size.json'));
await file.writeAsString(_encodeJson(<String, dynamic>{
'stack_size': stackSizeInBytes,
}));
}, timeout: Timeout.none);
}
String _encodeJson(Map<String, dynamic> jsonObject) {
return _prettyEncoder.convert(jsonObject);
}
| flutter/dev/benchmarks/macrobenchmarks/test_driver/stack_size_perf_test.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/test_driver/stack_size_perf_test.dart",
"repo_id": "flutter",
"token_count": 451
} | 485 |
// 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 '../common.dart';
import 'apps/button_matrix_app.dart' as button_matrix;
const int _kNumWarmUpIters = 20;
const int _kNumIters = 300;
Future<void> main() async {
assert(false, "Don't run benchmarks in debug mode! Use 'flutter run --release'.");
final Stopwatch watch = Stopwatch();
print('GestureDetector semantics benchmark...');
await benchmarkWidgets((WidgetTester tester) async {
button_matrix.main();
await tester.pump();
await tester.pump(const Duration(seconds: 1));
Future<void> iter() async {
// Press a button to update the screen
await tester.tapAt(const Offset(760.0, 30.0));
await tester.pump();
}
// Warm up runs get the app into steady state, making benchmark
// results more credible
for (int i = 0; i < _kNumWarmUpIters; i += 1) {
await iter();
}
await tester.pumpAndSettle();
watch.start();
for (int i = 0; i < _kNumIters; i += 1) {
await iter();
}
watch.stop();
}, semanticsEnabled: true);
final BenchmarkResultPrinter printer = BenchmarkResultPrinter();
printer.addResult(
description: 'GestureDetector',
value: watch.elapsedMicroseconds / _kNumIters,
unit: 'µs per iteration',
name: 'gesture_detector_bench',
);
printer.printToStdout();
}
| flutter/dev/benchmarks/microbenchmarks/lib/gestures/gesture_detector_bench.dart/0 | {
"file_path": "flutter/dev/benchmarks/microbenchmarks/lib/gestures/gesture_detector_bench.dart",
"repo_id": "flutter",
"token_count": 539
} | 486 |
// 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/semantics.dart';
import 'package:google_fonts/google_fonts.dart';
void main() => runApp(const MyApp(Colors.blue));
@pragma('vm:entry-point')
void topMain() => runApp(const MyApp(Colors.green));
@pragma('vm:entry-point')
void bottomMain() => runApp(const MyApp(Colors.purple));
class MyApp extends StatelessWidget {
const MyApp(this.color, {super.key});
final Color color;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: color as MaterialColor,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, this.title});
final String? title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class Sky extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final Rect rect = Offset.zero & size;
const RadialGradient gradient = RadialGradient(
center: Alignment(0.7, -0.6),
radius: 0.2,
colors: <Color>[Color(0xFFFFFF00), Color(0xFF0099FF)],
stops: <double>[0.4, 1.0],
);
canvas.drawRect(
rect,
Paint()..shader = gradient.createShader(rect),
);
}
@override
SemanticsBuilderCallback get semanticsBuilder {
return (Size size) {
// Annotate a rectangle containing the picture of the sun
// with the label "Sun". When text to speech feature is enabled on the
// device, a user will be able to locate the sun on this picture by
// touch.
Rect rect = Offset.zero & size;
final double width = size.shortestSide * 0.4;
rect = const Alignment(0.8, -0.9).inscribe(Size(width, width), rect);
return <CustomPainterSemantics>[
CustomPainterSemantics(
rect: rect,
properties: const SemanticsProperties(
label: 'Sun',
textDirection: TextDirection.ltr,
),
),
];
};
}
// Since this Sky painter has no fields, it always paints
// the same thing and semantics information is the same.
// Therefore we return false here. If we had fields (set
// from the constructor) then we would return true if any
// of them differed from the same fields on the oldDelegate.
@override
bool shouldRepaint(Sky oldDelegate) => false;
@override
bool shouldRebuildSemantics(Sky oldDelegate) => false;
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title ?? ''),
),
body: Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
style: GoogleFonts.lato(),
),
Text(
'0',
style: Theme.of(context).textTheme.headlineMedium,
),
TextButton(
onPressed: () {},
child: const Text('Add'),
),
TextButton(
onPressed: () {},
child: const Text('Next'),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
const Icon(
Icons.favorite,
color: Colors.pink,
size: 24.0,
semanticLabel: 'Text to announce in accessibility modes',
),
const Icon(
Icons.audiotrack,
color: Colors.green,
size: 30.0,
),
const Icon(
Icons.beach_access,
color: Colors.blue,
size: 36.0,
),
const Icon(
Icons.zoom_out,
color: Colors.amber,
size: 36.0,
),
const Icon(
Icons.money,
color: Colors.lightGreen,
size: 36.0,
),
const Icon(
Icons.bug_report,
color: Colors.teal,
size: 36.0,
),
Container(
width: 36.0,
height: 36.0,
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment(0.8,
0.0), // 10% of the width, so there are ten blinds.
colors: <Color>[
Color(0xffee0000),
Color(0xffeeee00),
], // red to yellow
tileMode: TileMode
.repeated, // repeats the gradient over the canvas
),
),
),
],
),
CustomPaint(
painter: Sky(),
size: const Size(200.0, 36.0),
),
],
),
),
),
);
}
}
| flutter/dev/benchmarks/multiple_flutters/module/lib/main.dart/0 | {
"file_path": "flutter/dev/benchmarks/multiple_flutters/module/lib/main.dart",
"repo_id": "flutter",
"token_count": 2917
} | 487 |
// 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';
import 'package:google_mobile_ads/google_mobile_ads.dart';
void main() {
runApp(
const PlatformViewApp()
);
}
class PlatformViewApp extends StatefulWidget {
const PlatformViewApp({
super.key,
});
@override
PlatformViewAppState createState() => PlatformViewAppState();
}
class PlatformViewAppState extends State<PlatformViewApp> {
AdWidget _getBannerWidget() {
// Test IDs from Admob:
// https://developers.google.com/admob/ios/test-ads
// https://developers.google.com/admob/android/test-ads
final String bannerId = Platform.isAndroid
? 'ca-app-pub-3940256099942544/6300978111'
: 'ca-app-pub-3940256099942544/2934735716';
final BannerAd bannerAd = BannerAd(
adUnitId: bannerId,
request: const AdRequest(),
size: AdSize.banner,
listener: const BannerAdListener(),
);
bannerAd.load();
return AdWidget(ad: bannerAd);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light(),
title: 'Advanced Layout',
home: Scaffold(
appBar: AppBar(title: const Text('Platform View Ad Banners')),
body: ListView.builder(
key: const Key('platform-views-scroll'), // This key is used by the driver test.
itemCount: 250,
itemBuilder: (BuildContext context, int index) {
return index.isEven
// Use 320x50 Admob standard banner size.
? SizedBox(width: 320, height: 50, child: _getBannerWidget())
// Adjust the height to control number of platform views on screen.
// TODO(hellohuanlin): Having more than 5 banners on screen causes an unknown crash.
// See: https://github.com/flutter/flutter/issues/144339
: const SizedBox(height: 150, child: ColoredBox(color: Colors.yellow));
},
),
),
);
}
}
| flutter/dev/benchmarks/platform_views_layout/lib/main_ad_banners.dart/0 | {
"file_path": "flutter/dev/benchmarks/platform_views_layout/lib/main_ad_banners.dart",
"repo_id": "flutter",
"token_count": 824
} | 488 |
// 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 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/intl.dart' as intl;
import 'stock_strings_en.dart';
import 'stock_strings_es.dart';
/// Callers can lookup localized strings with an instance of StockStrings returned
/// by `StockStrings.of(context)`.
///
/// Applications need to include `StockStrings.delegate()` in their app's
/// localizationDelegates list, and the locales they support in the app's
/// supportedLocales list. For example:
///
/// ```
/// import 'i18n/stock_strings.dart';
///
/// return MaterialApp(
/// localizationsDelegates: StockStrings.localizationsDelegates,
/// supportedLocales: StockStrings.supportedLocales,
/// home: MyApplicationHome(),
/// );
/// ```
///
/// ## Update pubspec.yaml
///
/// Please make sure to update your pubspec.yaml to include the following
/// packages:
///
/// ```
/// dependencies:
/// # Internationalization support.
/// flutter_localizations:
/// sdk: flutter
/// intl: any # Use the pinned version from flutter_localizations
///
/// # rest of dependencies
/// ```
///
/// ## iOS Applications
///
/// iOS applications define key application metadata, including supported
/// locales, in an Info.plist file that is built into the application bundle.
/// To configure the locales supported by your app, you’ll need to edit this
/// file.
///
/// First, open your project’s ios/Runner.xcworkspace Xcode workspace file.
/// Then, in the Project Navigator, open the Info.plist file under the Runner
/// project’s Runner folder.
///
/// Next, select the Information Property List item, select Add Item from the
/// Editor menu, then select Localizations from the pop-up menu.
///
/// Select and expand the newly-created Localizations item then, for each
/// locale your application supports, add a new item and select the locale
/// you wish to add from the pop-up menu in the Value field. This list should
/// be consistent with the languages listed in the StockStrings.supportedLocales
/// property.
abstract class StockStrings {
StockStrings(String locale) : localeName = intl.Intl.canonicalizedLocale(locale);
final String localeName;
static StockStrings of(BuildContext context) {
return Localizations.of<StockStrings>(context, StockStrings)!;
}
static const LocalizationsDelegate<StockStrings> delegate = _StockStringsDelegate();
/// A list of this localizations delegate along with the default localizations
/// delegates.
///
/// Returns a list of localizations delegates containing this delegate along with
/// GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate,
/// and GlobalWidgetsLocalizations.delegate.
///
/// Additional delegates can be added by appending to this list in
/// MaterialApp. This list does not have to be used at all if a custom list
/// of delegates is preferred or required.
static const List<LocalizationsDelegate<dynamic>> localizationsDelegates = <LocalizationsDelegate<dynamic>>[
delegate,
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
];
/// A list of this localizations delegate's supported locales.
static const List<Locale> supportedLocales = <Locale>[
Locale('en'),
Locale('en', 'US'),
Locale('es'),
];
/// Title for the Stocks application
///
/// In en, this message translates to:
/// **'Stocks'**
String get title;
/// Label for the Market tab
///
/// In en, this message translates to:
/// **'MARKET'**
String get market;
/// Label for the Portfolio tab
///
/// In en, this message translates to:
/// **'PORTFOLIO'**
String get portfolio;
}
class _StockStringsDelegate extends LocalizationsDelegate<StockStrings> {
const _StockStringsDelegate();
@override
Future<StockStrings> load(Locale locale) {
return SynchronousFuture<StockStrings>(_lookupStockStrings(locale));
}
@override
bool isSupported(Locale locale) => <String>['en', 'es'].contains(locale.languageCode);
@override
bool shouldReload(_StockStringsDelegate old) => false;
}
StockStrings _lookupStockStrings(Locale locale) {
// Lookup logic when language+country codes are specified.
switch (locale.languageCode) {
case 'en': {
switch (locale.countryCode) {
case 'US': return StockStringsEnUs();
}
break;
}
}
// Lookup logic when only language code is specified.
switch (locale.languageCode) {
case 'en': return StockStringsEn();
case 'es': return StockStringsEs();
}
throw FlutterError(
'StockStrings.delegate failed to load unsupported locale "$locale". This is likely '
'an issue with the localizations generation tool. Please file an issue '
'on GitHub with a reproducible sample app and the gen-l10n configuration '
'that was used.'
);
}
| flutter/dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings.dart/0 | {
"file_path": "flutter/dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings.dart",
"repo_id": "flutter",
"token_count": 1527
} | 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/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:stocks/main.dart' as stocks;
import 'package:stocks/stock_data.dart' as stock_data;
Element? findElementOfExactWidgetTypeGoingDown(Element node, Type targetType) {
void walker(Element child) {
if (child.widget.runtimeType == targetType) {
throw child;
}
child.visitChildElements(walker);
}
try {
walker(node);
} on Element catch (result) {
return result;
}
return null;
}
Element? findElementOfExactWidgetTypeGoingUp(Element node, Type targetType) {
Element? result;
bool walker(Element ancestor) {
if (ancestor.widget.runtimeType == targetType) {
result = ancestor;
return false;
}
return true;
}
node.visitAncestorElements(walker);
return result;
}
void checkIconColor(WidgetTester tester, String label, Color color) {
final Element listTile = findElementOfExactWidgetTypeGoingUp(tester.element(find.text(label)), ListTile)!;
final Element asset = findElementOfExactWidgetTypeGoingDown(listTile, RichText)!;
final RichText richText = asset.widget as RichText;
expect(richText.text.style!.color, equals(color));
}
void main() {
stock_data.StockData.actuallyFetchData = false;
testWidgets('Icon colors', (WidgetTester tester) async {
stocks.main(); // builds the app and schedules a frame but doesn't trigger one
await tester.pump(); // see https://github.com/flutter/flutter/issues/1865
await tester.pump(); // triggers a frame
// sanity check
expect(find.text('MARKET'), findsOneWidget);
expect(find.text('Account Balance'), findsNothing);
await tester.pump(const Duration(seconds: 2));
expect(find.text('MARKET'), findsOneWidget);
expect(find.text('Account Balance'), findsNothing);
// drag the drawer out
final Offset left = Offset(0.0, (tester.view.physicalSize / tester.view.devicePixelRatio).height / 2.0);
final Offset right = Offset((tester.view.physicalSize / tester.view.devicePixelRatio).width, left.dy);
final TestGesture gesture = await tester.startGesture(left);
await tester.pump();
await gesture.moveTo(right);
await tester.pump();
await gesture.up();
await tester.pump();
expect(find.text('MARKET'), findsOneWidget);
expect(find.text('Account Balance'), findsOneWidget);
// check the color of the icon - light mode
checkIconColor(tester, 'Stock List', Colors.purple); // theme primary color
checkIconColor(tester, 'Account Balance', Colors.black38); // disabled
checkIconColor(tester, 'About', Colors.black45); // enabled
// switch to dark mode
await tester.tap(find.text('Pessimistic'));
await tester.pump(); // get the tap and send the notification that the theme has changed
await tester.pump(); // start the theme transition
await tester.pump(const Duration(seconds: 5)); // end the transition
// check the color of the icon - dark mode
checkIconColor(tester, 'Stock List', Colors.purple); // theme primary color
checkIconColor(tester, 'Account Balance', Colors.white38); // disabled
checkIconColor(tester, 'About', Colors.white); // enabled
});
}
| flutter/dev/benchmarks/test_apps/stocks/test/icon_color_test.dart/0 | {
"file_path": "flutter/dev/benchmarks/test_apps/stocks/test/icon_color_test.dart",
"repo_id": "flutter",
"token_count": 1100
} | 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 'dart:io' show Directory;
import 'package:analyzer/dart/analysis/analysis_context.dart';
import 'package:analyzer/dart/analysis/analysis_context_collection.dart';
import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/dart/analysis/session.dart';
import 'package:path/path.dart' as path;
import '../utils.dart';
/// Analyzes the dart source files in the given `flutterRootDirectory` with the
/// given [AnalyzeRule]s.
///
/// The `includePath` parameter takes a collection of paths relative to the given
/// `flutterRootDirectory`. It specifies the files or directory this function
/// should analyze. Defaults to null in which case this function analyzes the
/// all dart source files in `flutterRootDirectory`.
///
/// The `excludePath` parameter takes a collection of paths relative to the given
/// `flutterRootDirectory` that this function should skip analyzing.
///
/// If a compilation unit can not be resolved, this function ignores the
/// corresponding dart source file and logs an error using [foundError].
Future<void> analyzeWithRules(String flutterRootDirectory, List<AnalyzeRule> rules, {
Iterable<String>? includePaths,
Iterable<String>? excludePaths,
}) async {
if (!Directory(flutterRootDirectory).existsSync()) {
foundError(<String>['Analyzer error: the specified $flutterRootDirectory does not exist.']);
}
final Iterable<String> includes = includePaths?.map((String relativePath) => path.canonicalize('$flutterRootDirectory/$relativePath'))
?? <String>[path.canonicalize(flutterRootDirectory)];
final AnalysisContextCollection collection = AnalysisContextCollection(
includedPaths: includes.toList(),
excludedPaths: excludePaths?.map((String relativePath) => path.canonicalize('$flutterRootDirectory/$relativePath')).toList(),
);
final List<String> analyzerErrors = <String>[];
for (final AnalysisContext context in collection.contexts) {
final Iterable<String> analyzedFilePaths = context.contextRoot.analyzedFiles();
final AnalysisSession session = context.currentSession;
for (final String filePath in analyzedFilePaths) {
final SomeResolvedUnitResult unit = await session.getResolvedUnit(filePath);
if (unit is ResolvedUnitResult) {
for (final AnalyzeRule rule in rules) {
rule.applyTo(unit);
}
} else {
analyzerErrors.add('Analyzer error: file $unit could not be resolved. Expected "ResolvedUnitResult", got ${unit.runtimeType}.');
}
}
}
if (analyzerErrors.isNotEmpty) {
foundError(analyzerErrors);
}
for (final AnalyzeRule verifier in rules) {
verifier.reportViolations(flutterRootDirectory);
}
}
Future<void> analyzeToolWithRules(String flutterRootDirectory, List<AnalyzeRule> rules) async {
final String libPath = path.canonicalize('$flutterRootDirectory/packages/flutter_tools/lib');
if (!Directory(libPath).existsSync()) {
foundError(<String>['Analyzer error: the specified $libPath does not exist.']);
}
final String testPath = path.canonicalize('$flutterRootDirectory/packages/flutter_tools/test');
final AnalysisContextCollection collection = AnalysisContextCollection(
includedPaths: <String>[libPath, testPath],
);
final List<String> analyzerErrors = <String>[];
for (final AnalysisContext context in collection.contexts) {
final Iterable<String> analyzedFilePaths = context.contextRoot.analyzedFiles();
final AnalysisSession session = context.currentSession;
for (final String filePath in analyzedFilePaths) {
final SomeResolvedUnitResult unit = await session.getResolvedUnit(filePath);
if (unit is ResolvedUnitResult) {
for (final AnalyzeRule rule in rules) {
rule.applyTo(unit);
}
} else {
analyzerErrors.add('Analyzer error: file $unit could not be resolved. Expected "ResolvedUnitResult", got ${unit.runtimeType}.');
}
}
}
if (analyzerErrors.isNotEmpty) {
foundError(analyzerErrors);
}
for (final AnalyzeRule verifier in rules) {
verifier.reportViolations(flutterRootDirectory);
}
}
/// An interface that defines a set of best practices, and collects information
/// about code that violates the best practices in a [ResolvedUnitResult].
///
/// The [analyzeWithRules] function scans and analyzes the specified
/// source directory using the dart analyzer package, and applies custom rules
/// defined in the form of this interface on each resulting [ResolvedUnitResult].
/// The [reportViolations] method will be called at the end, once all
/// [ResolvedUnitResult]s are parsed.
///
/// Implementers can assume each [ResolvedUnitResult] is valid compilable dart
/// code, as the caller only applies the custom rules once the code passes
/// `flutter analyze`.
abstract class AnalyzeRule {
/// Applies this rule to the given [ResolvedUnitResult] (typically a file), and
/// collects information about violations occurred in the compilation unit.
void applyTo(ResolvedUnitResult unit);
/// Reports all violations in the resolved compilation units [applyTo] was
/// called on, if any.
///
/// This method is called once all [ResolvedUnitResult] are parsed.
///
/// The implementation typically calls [foundErrors] to report violations.
void reportViolations(String workingDirectory);
}
| flutter/dev/bots/custom_rules/analyze.dart/0 | {
"file_path": "flutter/dev/bots/custom_rules/analyze.dart",
"repo_id": "flutter",
"token_count": 1627
} | 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.
// @dart = 2.12
/// This is a dummy dart:ui package for the sample code analyzer tests to use.
library dart.ui;
/// Bla bla bla bla bla bla bla bla bla.
///
/// ```dart
/// class MyStringBuffer {
/// error; // error (prefer_typing_uninitialized_variables, inference_failure_on_uninitialized_variable, missing_const_final_var_or_type)
///
/// StringBuffer _buffer = StringBuffer(); // error (prefer_final_fields, unused_field)
/// }
/// ```
class Foo {
const Foo();
}
| flutter/dev/bots/test/analyze-snippet-code-test-dart-ui/ui.dart/0 | {
"file_path": "flutter/dev/bots/test/analyze-snippet-code-test-dart-ui/ui.dart",
"repo_id": "flutter",
"token_count": 206
} | 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:convert';
import 'dart:io';
class TestSpecs {
TestSpecs({
required this.path,
required this.startTime,
});
final String path;
int startTime;
int? _endTime;
int get milliseconds => endTime - startTime;
set endTime(int value) {
_endTime = value;
}
int get endTime => _endTime ?? 0;
String toJson() {
return json.encode(
<String, String>{'path': path, 'runtime': milliseconds.toString()}
);
}
}
class TestFileReporterResults {
TestFileReporterResults._({
required this.allTestSpecs,
required this.hasFailedTests,
required this.errors,
});
/// Intended to parse the output file of `dart test --file-reporter json:file_name
factory TestFileReporterResults.fromFile(File metrics) {
if (!metrics.existsSync()) {
throw Exception('${metrics.path} does not exist');
}
final Map<int, TestSpecs> testSpecs = <int, TestSpecs>{};
bool hasFailedTests = true;
final List<String> errors = <String>[];
for (final String metric in metrics.readAsLinesSync()) {
final Map<String, Object?> entry = json.decode(metric) as Map<String, Object?>;
if (entry.containsKey('suite')) {
final Map<String, Object?> suite = entry['suite']! as Map<String, Object?>;
addTestSpec(suite, entry['time']! as int, testSpecs);
} else if (isMetricDone(entry, testSpecs)) {
final Map<String, Object?> group = entry['group']! as Map<String, Object?>;
final int suiteID = group['suiteID']! as int;
addMetricDone(suiteID, entry['time']! as int, testSpecs);
} else if (entry.containsKey('error')) {
final String stackTrace = entry.containsKey('stackTrace') ? entry['stackTrace']! as String : '';
errors.add('${entry['error']}\n $stackTrace');
} else if (entry.containsKey('success') && entry['success'] == true) {
hasFailedTests = false;
}
}
return TestFileReporterResults._(allTestSpecs: testSpecs, hasFailedTests: hasFailedTests, errors: errors);
}
final Map<int, TestSpecs> allTestSpecs;
final bool hasFailedTests;
final List<String> errors;
static void addTestSpec(Map<String, Object?> suite, int time, Map<int, TestSpecs> allTestSpecs) {
allTestSpecs[suite['id']! as int] = TestSpecs(
path: suite['path']! as String,
startTime: time,
);
}
static void addMetricDone(int suiteID, int time, Map<int, TestSpecs> allTestSpecs) {
final TestSpecs testSpec = allTestSpecs[suiteID]!;
testSpec.endTime = time;
}
static bool isMetricDone(Map<String, Object?> entry, Map<int, TestSpecs> allTestSpecs) {
if (entry.containsKey('group') && entry['type']! as String == 'group') {
final Map<String, Object?> group = entry['group']! as Map<String, Object?>;
return allTestSpecs.containsKey(group['suiteID']! as int);
}
return false;
}
}
| flutter/dev/bots/tool_subsharding.dart/0 | {
"file_path": "flutter/dev/bots/tool_subsharding.dart",
"repo_id": "flutter",
"token_count": 1144
} | 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:io';
import 'package:process/process.dart';
import './globals.dart';
/// A wrapper around git process calls that can be mocked for unit testing.
///
/// The `Git` class is a relatively (compared to `Repository`) lightweight
/// abstraction over invocations to the `git` cli tool. The main
/// motivation for creating this class was so that it could be overridden in
/// tests. However, now that tests rely on the [FakeProcessManager] this
/// abstraction is redundant.
class Git {
const Git(this.processManager);
final ProcessManager processManager;
Future<String> getOutput(
List<String> args,
String explanation, {
required String workingDirectory,
bool allowFailures = false,
}) async {
final ProcessResult result = await _run(args, workingDirectory);
if (result.exitCode == 0) {
return stdoutToString(result.stdout);
}
_reportFailureAndExit(args, workingDirectory, result, explanation);
}
Future<int> run(
List<String> args,
String explanation, {
bool allowNonZeroExitCode = false,
required String workingDirectory,
}) async {
late final ProcessResult result;
try {
result = await _run(args, workingDirectory);
} on ProcessException {
_reportFailureAndExit(args, workingDirectory, result, explanation);
}
if (result.exitCode != 0 && !allowNonZeroExitCode) {
_reportFailureAndExit(args, workingDirectory, result, explanation);
}
return result.exitCode;
}
Future<ProcessResult> _run(List<String> args, String workingDirectory) async {
return processManager.run(
<String>['git', ...args],
workingDirectory: workingDirectory,
environment: <String, String>{'GIT_TRACE': '1'},
);
}
Never _reportFailureAndExit(
List<String> args,
String workingDirectory,
ProcessResult result,
String explanation,
) {
final StringBuffer message = StringBuffer();
if (result.exitCode != 0) {
message.writeln(
'Command "git ${args.join(' ')}" failed in directory "$workingDirectory" to '
'$explanation. Git exited with error code ${result.exitCode}.',
);
} else {
message.writeln('Command "git ${args.join(' ')}" failed to $explanation.');
}
if ((result.stdout as String).isNotEmpty) {
message.writeln('stdout from git:\n${result.stdout}\n');
}
if ((result.stderr as String).isNotEmpty) {
message.writeln('stderr from git:\n${result.stderr}\n');
}
throw GitException(message.toString(), args);
}
}
enum GitExceptionType {
/// Git push failed because the remote branch contained commits the local did
/// not.
///
/// Either the local branch was wrong, and needs a rebase before pushing
/// again, or the remote branch needs to be overwritten with a force push.
///
/// Example output:
///
/// ```
/// To github.com:user/engine.git
///
/// ! [rejected] HEAD -> cherrypicks-flutter-2.8-candidate.3 (non-fast-forward)
/// error: failed to push some refs to 'github.com:user/engine.git'
/// hint: Updates were rejected because the tip of your current branch is behind
/// hint: its remote counterpart. Integrate the remote changes (e.g.
/// hint: 'git pull ...') before pushing again.
/// hint: See the 'Note about fast-forwards' in 'git push --help' for details.
/// ```
PushRejected,
}
/// An exception created because a git subprocess failed.
///
/// Known git failures will be assigned a [GitExceptionType] in the [type]
/// field. If this field is null it means and unknown git failure.
class GitException implements Exception {
GitException(this.message, this.args) {
if (_pushRejectedPattern.hasMatch(message)) {
type = GitExceptionType.PushRejected;
} else {
// because type is late final, it must be explicitly set before it is
// accessed.
type = null;
}
}
static final RegExp _pushRejectedPattern = RegExp(
r'Updates were rejected because the tip of your current branch is behind',
);
final String message;
final List<String> args;
late final GitExceptionType? type;
@override
String toString() => 'Exception on command "${args.join(' ')}": $message';
}
| flutter/dev/conductor/core/lib/src/git.dart/0 | {
"file_path": "flutter/dev/conductor/core/lib/src/git.dart",
"repo_id": "flutter",
"token_count": 1409
} | 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 'dart:io' as io;
import 'package:meta/meta.dart';
/// An interface for presenting text output to the user.
///
/// Although this could have been simplified by calling `print()`
/// from the tool, this abstraction allows unit tests to verify output
/// and allows a GUI frontend to provide an alternative implementation.
///
/// User input probably should be part of this class–however it is currently
/// part of context.dart.
abstract class Stdio {
final List<String> logs = <String>[];
/// Error messages printed to STDERR.
///
/// Display an error `message` to the user on stderr. Print errors if the code
/// fails in some way. Errors are typically followed shortly by exiting the
/// app with a non-zero exit status.
@mustCallSuper
void printError(String message) {
logs.add('[error] $message');
}
/// Warning messages printed to STDERR.
///
/// Display a warning `message` to the user on stderr. Print warnings if there
/// is important information to convey to the user that is not fatal.
@mustCallSuper
void printWarning(String message) {
logs.add('[warning] $message');
}
/// Ordinary STDOUT messages.
///
/// Displays normal output on stdout. This should be used for things like
/// progress messages, success messages, or just normal command output.
@mustCallSuper
void printStatus(String message) {
logs.add('[status] $message');
}
/// Debug messages that are only printed in verbose mode.
///
/// Use this for verbose tracing output. Users can turn this output on in order
/// to help diagnose issues.
@mustCallSuper
void printTrace(String message) {
logs.add('[trace] $message');
}
/// Write the `message` string to STDOUT without a trailing newline.
@mustCallSuper
void write(String message) {
logs.add('[write] $message');
}
/// Read a line of text from STDIN.
String readLineSync();
}
/// A logger that will print out trace messages.
class VerboseStdio extends Stdio {
VerboseStdio({
required this.stdout,
required this.stderr,
required this.stdin,
this.filter,
});
factory VerboseStdio.local() => VerboseStdio(
stdout: io.stdout,
stderr: io.stderr,
stdin: io.stdin,
);
final io.Stdout stdout;
final io.Stdout stderr;
final io.Stdin stdin;
/// If provided, all messages will be passed through this function before being logged.
final String Function(String)? filter;
@override
void printError(String message) {
if (filter != null) {
message = filter!(message);
}
super.printError(message);
stderr.writeln(message);
}
@override
void printWarning(String message) {
if (filter != null) {
message = filter!(message);
}
super.printWarning(message);
stderr.writeln(message);
}
@override
void printStatus(String message) {
if (filter != null) {
message = filter!(message);
}
super.printStatus(message);
stdout.writeln(message);
}
@override
void printTrace(String message) {
if (filter != null) {
message = filter!(message);
}
super.printTrace(message);
stdout.writeln(message);
}
@override
void write(String message) {
if (filter != null) {
message = filter!(message);
}
super.write(message);
stdout.write(message);
}
@override
String readLineSync() {
return stdin.readLineSync()!;
}
}
| flutter/dev/conductor/core/lib/src/stdio.dart/0 | {
"file_path": "flutter/dev/conductor/core/lib/src/stdio.dart",
"repo_id": "flutter",
"token_count": 1171
} | 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:convert';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'customer_test.dart';
Future<bool> runTests({
int repeat = 1,
bool skipOnFetchFailure = false,
bool verbose = false,
int numberShards = 1,
int shardIndex = 0,
required List<File> files,
}) async {
if (verbose) {
print('Starting run_tests.dart...');
}
// Best attempt at evenly splitting tests among the shards
final List<File> shardedFiles = <File>[];
for (int i = shardIndex; i < files.length; i += numberShards) {
shardedFiles.add(files[i]);
}
int testCount = 0;
int failures = 0;
if (verbose) {
final String s = files.length == 1 ? '' : 's';
if (numberShards > 1) {
final String ss = shardedFiles.length == 1 ? '' : 's';
print('${files.length} file$s specified. ${shardedFiles.length} test$ss in shard #$shardIndex ($numberShards shards total).');
} else {
print('${files.length} file$s specified.');
}
print('');
}
if (verbose) {
if (numberShards > 1) {
print('Tests in this shard:');
} else {
print('Tests:');
}
for (final File file in shardedFiles) {
print(file.path);
}
}
print('');
for (final File file in shardedFiles) {
if (verbose) {
print('Processing ${file.path}...');
}
void printHeader() {
if (!verbose) {
print('Processing ${file.path}...');
}
}
void failure(String message) {
printHeader();
print('ERROR: $message');
failures += 1;
}
CustomerTest instructions;
try {
instructions = CustomerTest(file);
} on FormatException catch (error) {
failure(error.message);
print('');
continue;
} on FileSystemException catch (error) {
failure(error.message);
print('');
continue;
}
bool success = true;
final Directory checkout = Directory.systemTemp.createTempSync('flutter_customer_testing.${path.basenameWithoutExtension(file.path)}.');
if (verbose) {
print('Created temporary directory: ${checkout.path}');
}
try {
assert(instructions.fetch.isNotEmpty);
for (final String fetchCommand in instructions.fetch) {
success = await shell(fetchCommand, checkout, verbose: verbose, silentFailure: skipOnFetchFailure, failedCallback: printHeader);
if (!success) {
if (skipOnFetchFailure) {
if (verbose) {
print('Skipping (fetch failed).');
} else {
print('Skipping ${file.path} (fetch failed).');
}
} else {
failure('Failed to fetch repository.');
}
break;
}
}
if (success) {
final Directory customerRepo = Directory(path.join(checkout.path, 'tests'));
for (final String setupCommand in instructions.setup) {
if (verbose) {
print('Running setup command: $setupCommand');
}
success = await shell(
setupCommand,
customerRepo,
verbose: verbose,
failedCallback: printHeader,
);
if (!success) {
failure('Setup command failed: $setupCommand');
break;
}
}
for (final Directory updateDirectory in instructions.update) {
final Directory resolvedUpdateDirectory = Directory(path.join(customerRepo.path, updateDirectory.path));
if (verbose) {
print('Updating code in ${resolvedUpdateDirectory.path}...');
}
if (!File(path.join(resolvedUpdateDirectory.path, 'pubspec.yaml')).existsSync()) {
failure('The directory ${updateDirectory.path}, which was specified as an update directory, does not contain a "pubspec.yaml" file.');
success = false;
break;
}
success = await shell('flutter packages get', resolvedUpdateDirectory, verbose: verbose, failedCallback: printHeader);
if (!success) {
failure('Could not run "flutter pub get" in ${updateDirectory.path}, which was specified as an update directory.');
break;
}
success = await shell('dart fix --apply', resolvedUpdateDirectory, verbose: verbose, failedCallback: printHeader);
if (!success) {
failure('Could not run "dart fix" in ${updateDirectory.path}, which was specified as an update directory.');
break;
}
}
if (success) {
if (verbose) {
print('Running tests...');
}
if (instructions.iterations != null && instructions.iterations! < repeat) {
if (verbose) {
final String s = instructions.iterations == 1 ? '' : 's';
print('Limiting to ${instructions.iterations} round$s rather than $repeat rounds because of "iterations" directive.');
}
repeat = instructions.iterations!;
}
final Stopwatch stopwatch = Stopwatch()..start();
for (int iteration = 0; iteration < repeat; iteration += 1) {
if (verbose && repeat > 1) {
print('Round ${iteration + 1} of $repeat.');
}
for (final String testCommand in instructions.tests) {
testCount += 1;
success = await shell(testCommand, customerRepo, verbose: verbose, failedCallback: printHeader);
if (!success) {
failure('One or more tests from ${path.basenameWithoutExtension(file.path)} failed.');
break;
}
}
}
stopwatch.stop();
if (verbose && success) {
print('Tests finished in ${(stopwatch.elapsed.inSeconds / repeat).toStringAsFixed(2)} seconds per iteration.');
}
}
}
} finally {
if (verbose) {
print('Deleting temporary directory...');
}
try {
checkout.deleteSync(recursive: true);
} on FileSystemException {
print('Failed to delete "${checkout.path}".');
}
}
if (!success) {
final String s = instructions.contacts.length == 1 ? '' : 's';
print('Contact$s: ${instructions.contacts.join(", ")}');
}
if (verbose || !success) {
print('');
}
}
if (failures > 0) {
final String s = failures == 1 ? '' : 's';
print('$failures failure$s.');
return false;
}
print('$testCount tests all passed!');
return true;
}
final RegExp _spaces = RegExp(r' +');
Future<bool> shell(String command, Directory directory, { bool verbose = false, bool silentFailure = false, void Function()? failedCallback }) async {
if (verbose) {
print('>> $command');
}
Process process;
if (Platform.isWindows) {
process = await Process.start('CMD.EXE', <String>['/S', '/C', command], workingDirectory: directory.path);
} else {
final List<String> segments = command.trim().split(_spaces);
process = await Process.start(segments.first, segments.skip(1).toList(), workingDirectory: directory.path);
}
final List<String> output = <String>[];
utf8.decoder.bind(process.stdout).transform(const LineSplitter()).listen(verbose ? printLog : output.add);
utf8.decoder.bind(process.stderr).transform(const LineSplitter()).listen(verbose ? printLog : output.add);
final bool success = await process.exitCode == 0;
if (success || silentFailure) {
return success;
}
if (!verbose) {
if (failedCallback != null) {
failedCallback();
}
print('>> $command');
output.forEach(printLog);
}
return success;
}
void printLog(String line) {
print('| $line'.trimRight());
}
| flutter/dev/customer_testing/lib/runner.dart/0 | {
"file_path": "flutter/dev/customer_testing/lib/runner.dart",
"repo_id": "flutter",
"token_count": 3208
} | 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 'dart:io';
import 'package:flutter_devicelab/framework/devices.dart';
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/framework/task_result.dart';
import 'package:flutter_devicelab/framework/utils.dart';
import 'package:path/path.dart' as p;
void main() {
task(() async {
deviceOperatingSystem = DeviceOperatingSystem.android;
final Device device = await devices.workingDevice;
await device.unlock();
final String deviceId = device.deviceId;
await flutter('packages', options: <String>['get']);
final String complexLayoutPath = p.join(flutterDirectory.path, 'dev', 'benchmarks', 'complex_layout');
await inDirectory(complexLayoutPath, () async {
await flutter('drive', options: <String>[
'--no-android-gradle-daemon',
'-v',
'--profile',
'--trace-startup', // Enables "endless" timeline event buffering.
'-t',
p.join(complexLayoutPath, 'test_driver', 'semantics_perf.dart'),
'-d',
deviceId,
]);
});
final String outputPath = Platform.environment['FLUTTER_TEST_OUTPUTS_DIR'] ?? p.join(complexLayoutPath, 'build');
final String dataPath = p.join(outputPath, 'complex_layout_semantics_perf.json');
return TaskResult.successFromFile(file(dataPath), benchmarkScoreKeys: <String>[
'initialSemanticsTreeCreation',
]);
});
}
| flutter/dev/devicelab/bin/tasks/complex_layout_semantics_perf.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/complex_layout_semantics_perf.dart",
"repo_id": "flutter",
"token_count": 565
} | 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.
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';
Future<void> main() async {
await task(() async {
try {
await runProjectTest((FlutterProject flutterProject) async {
section('APK contains plugin classes');
await flutterProject.setMinSdkVersion(20);
flutterProject.addPlugin('google_maps_flutter', value: '^2.2.1');
await inDirectory(flutterProject.rootPath, () async {
await flutter('build', options: <String>[
'apk',
'--debug',
'--target-platform=android-arm',
]);
final File apk = File('${flutterProject.rootPath}/build/app/outputs/flutter-apk/app-debug.apk');
if (!apk.existsSync()) {
throw TaskResult.failure("Expected ${apk.path} to exist, but it doesn't");
}
// https://github.com/flutter/flutter/issues/72185
await checkApkContainsMethods(apk, <String>[
'io.flutter.plugins.googlemaps.GoogleMapController void onFlutterViewAttached(android.view.View)',
'io.flutter.plugins.googlemaps.GoogleMapController void onFlutterViewDetached()',
]);
});
});
return TaskResult.success(null);
} on TaskResult catch (taskResult) {
return taskResult;
} catch (e) {
return TaskResult.failure(e.toString());
}
});
}
| flutter/dev/devicelab/bin/tasks/gradle_desugar_classes_test.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/gradle_desugar_classes_test.dart",
"repo_id": "flutter",
"token_count": 701
} | 498 |
// 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;
final String platformLineSep = Platform.isWindows ? '\r\n': '\n';
/// Tests that a plugin A can depend on platform code from a plugin B
/// as long as plugin B is defined as a pub dependency of plugin A.
///
/// This test fails when `flutter build apk` fails and the stderr from this command
/// contains "Unresolved reference: plugin_b".
Future<void> main() async {
await task(() async {
section('Find Java');
final String? javaHome = await findJavaHome();
if (javaHome == null) {
return TaskResult.failure('Could not find Java');
}
print('\nUsing JAVA_HOME=$javaHome');
final Directory tempDir = Directory.systemTemp.createTempSync('flutter_plugin_dependencies.');
try {
section('Create plugin A');
final Directory pluginADirectory = Directory(path.join(tempDir.path, 'plugin_a'));
await inDirectory(tempDir, () async {
await flutter(
'create',
options: <String>[
'--org',
'io.flutter.devicelab.plugin_a',
'--template=plugin',
'--platforms=android,ios',
pluginADirectory.path,
],
);
});
section('Create plugin B');
final Directory pluginBDirectory = Directory(path.join(tempDir.path, 'plugin_b'));
await inDirectory(tempDir, () async {
await flutter(
'create',
options: <String>[
'--org',
'io.flutter.devicelab.plugin_b',
'--template=plugin',
'--platforms=android,ios',
pluginBDirectory.path,
],
);
});
section('Create plugin C without android/ directory');
final Directory pluginCDirectory = Directory(path.join(tempDir.path, 'plugin_c'));
await inDirectory(tempDir, () async {
await flutter(
'create',
options: <String>[
'--org',
'io.flutter.devicelab.plugin_c',
'--template=plugin',
'--platforms=ios',
pluginCDirectory.path,
],
);
});
checkDirectoryNotExists(path.join(
pluginCDirectory.path,
'android',
));
final File pluginCpubspec = File(path.join(pluginCDirectory.path, 'pubspec.yaml'));
await pluginCpubspec.writeAsString('''
name: plugin_c
version: 0.0.1
flutter:
plugin:
platforms:
ios:
pluginClass: Plugin_cPlugin
dependencies:
flutter:
sdk: flutter
environment:
sdk: '>=3.2.0-0 <4.0.0'
flutter: ">=1.5.0"
''', flush: true);
section('Create plugin D without ios/ directory');
final Directory pluginDDirectory = Directory(path.join(tempDir.path, 'plugin_d'));
await inDirectory(tempDir, () async {
await flutter(
'create',
options: <String>[
'--org',
'io.flutter.devicelab.plugin_d',
'--template=plugin',
'--platforms=android',
pluginDDirectory.path,
],
);
});
checkDirectoryNotExists(path.join(
pluginDDirectory.path,
'ios',
));
section('Write dummy Kotlin code in plugin B');
final File pluginBKotlinClass = File(path.join(
pluginBDirectory.path,
'android',
'src',
'main',
'kotlin',
'DummyPluginBClass.kt',
));
await pluginBKotlinClass.writeAsString('''
package io.flutter.devicelab.plugin_b
public class DummyPluginBClass {
companion object {
fun dummyStaticMethod() {
}
}
}
''', flush: true);
section('Make plugin A depend on plugin B, C, and D');
final File pluginApubspec = File(path.join(pluginADirectory.path, 'pubspec.yaml'));
String pluginApubspecContent = await pluginApubspec.readAsString();
pluginApubspecContent = pluginApubspecContent.replaceFirst(
'${platformLineSep}dependencies:$platformLineSep',
'${platformLineSep}dependencies:$platformLineSep'
' plugin_b:$platformLineSep'
' path: ${pluginBDirectory.path}$platformLineSep'
' plugin_c:$platformLineSep'
' path: ${pluginCDirectory.path}$platformLineSep'
' plugin_d:$platformLineSep'
' path: ${pluginDDirectory.path}$platformLineSep',
);
await pluginApubspec.writeAsString(pluginApubspecContent, flush: true);
section('Write Kotlin code in plugin A that references Kotlin code from plugin B');
final File pluginAKotlinClass = File(path.join(
pluginADirectory.path,
'android',
'src',
'main',
'kotlin',
'DummyPluginAClass.kt',
));
await pluginAKotlinClass.writeAsString('''
package io.flutter.devicelab.plugin_a
import io.flutter.devicelab.plugin_b.DummyPluginBClass
public class DummyPluginAClass {
constructor() {
// Call a method from plugin b.
DummyPluginBClass.dummyStaticMethod();
}
}
''', flush: true);
section('Verify .flutter-plugins-dependencies');
final Directory exampleApp = Directory(path.join(pluginADirectory.path, 'example'));
await inDirectory(exampleApp, () async {
await flutter(
'packages',
options: <String>['get'],
);
});
final File flutterPluginsDependenciesFile =
File(path.join(exampleApp.path, '.flutter-plugins-dependencies'));
if (!flutterPluginsDependenciesFile.existsSync()) {
return TaskResult.failure("${flutterPluginsDependenciesFile.path} doesn't exist");
}
final String flutterPluginsDependenciesFileContent = flutterPluginsDependenciesFile.readAsStringSync();
final Map<String, dynamic> jsonContent = json.decode(flutterPluginsDependenciesFileContent) as Map<String, dynamic>;
// Verify the dependencyGraph object is valid. The rest of the contents of this file are not relevant to the
// dependency graph and are tested by unit tests.
final List<dynamic> dependencyGraph = jsonContent['dependencyGraph'] as List<dynamic>;
const String kExpectedPluginsDependenciesContent =
'['
'{'
'"name":"integration_test",'
'"dependencies":[]'
'},'
'{'
'"name":"plugin_a",'
'"dependencies":["plugin_b","plugin_c","plugin_d"]'
'},'
'{'
'"name":"plugin_b",'
'"dependencies":[]'
'},'
'{'
'"name":"plugin_c",'
'"dependencies":[]'
'},'
'{'
'"name":"plugin_d",'
'"dependencies":[]'
'}'
']';
final String graphString = json.encode(dependencyGraph);
if (graphString != kExpectedPluginsDependenciesContent) {
return TaskResult.failure(
'Unexpected file content in ${flutterPluginsDependenciesFile.path}: '
'Found "$graphString" instead of "$kExpectedPluginsDependenciesContent"'
);
}
section('Build plugin A example Android app');
final StringBuffer stderr = StringBuffer();
await inDirectory(exampleApp, () async {
await evalFlutter(
'build',
options: <String>['apk', '--target-platform', 'android-arm'],
canFail: true,
stderr: stderr,
);
});
if (stderr.toString().contains('Unresolved reference: plugin_b')) {
return TaskResult.failure('plugin_a cannot reference plugin_b');
}
final bool pluginAExampleApk = exists(File(path.join(
pluginADirectory.path,
'example',
'build',
'app',
'outputs',
'apk',
'release',
'app-release.apk',
)));
if (!pluginAExampleApk) {
return TaskResult.failure('Failed to build plugin A example APK');
}
if (Platform.isMacOS) {
section('Build plugin A example iOS app');
await inDirectory(exampleApp, () async {
await evalFlutter(
'build',
options: <String>[
'ios',
'--no-codesign',
'--verbose',
],
);
});
final Directory appBundle = Directory(path.join(
pluginADirectory.path,
'example',
'build',
'ios',
'iphoneos',
'Runner.app',
));
if (!exists(appBundle)) {
return TaskResult.failure('Failed to build plugin A example iOS app');
}
checkDirectoryExists(path.join(
appBundle.path,
'Frameworks',
'plugin_a.framework',
));
checkDirectoryExists(path.join(
appBundle.path,
'Frameworks',
'plugin_b.framework',
));
checkDirectoryExists(path.join(
appBundle.path,
'Frameworks',
'plugin_c.framework',
));
// Plugin D is Android only and should not be embedded.
checkDirectoryNotExists(path.join(
appBundle.path,
'Frameworks',
'plugin_d.framework',
));
}
return TaskResult.success(null);
} on TaskResult catch (taskResult) {
return taskResult;
} catch (e) {
return TaskResult.failure(e.toString());
} finally {
rmTree(tempDir);
}
});
}
| flutter/dev/devicelab/bin/tasks/plugin_dependencies_test.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/plugin_dependencies_test.dart",
"repo_id": "flutter",
"token_count": 4320
} | 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:async';
import 'dart:io';
import 'package:args/command_runner.dart';
import 'package:flutter_devicelab/command/test.dart';
import 'package:flutter_devicelab/command/upload_results.dart';
final CommandRunner<void> runner =
CommandRunner<void>('devicelab_runner', 'DeviceLab test runner for recording test results')
..addCommand(TestCommand())
..addCommand(UploadResultsCommand());
Future<void> main(List<String> rawArgs) async {
unawaited(runner.run(rawArgs).catchError((dynamic error) {
stderr.writeln('$error\n');
stderr.writeln('Usage:\n');
stderr.writeln(runner.usage);
exit(64); // Exit code 64 indicates a usage error.
}));
}
| flutter/dev/devicelab/bin/test_runner.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/test_runner.dart",
"repo_id": "flutter",
"token_count": 287
} | 500 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math' as math;
import 'package:path/path.dart' as path;
import 'package:process/process.dart';
import 'package:stack_trace/stack_trace.dart';
import 'devices.dart';
import 'host_agent.dart';
import 'task_result.dart';
/// Virtual current working directory, which affect functions, such as [exec].
String cwd = Directory.current.path;
/// The local engine to use for [flutter] and [evalFlutter], if any.
///
/// This is set as an environment variable when running the task, see runTask in runner.dart.
String? get localEngineFromEnv {
const bool isDefined = bool.hasEnvironment('localEngine');
return isDefined ? const String.fromEnvironment('localEngine') : null;
}
/// The local engine host to use for [flutter] and [evalFlutter], if any.
///
/// This is set as an environment variable when running the task, see runTask in runner.dart.
String? get localEngineHostFromEnv {
const bool isDefined = bool.hasEnvironment('localEngineHost');
return isDefined ? const String.fromEnvironment('localEngineHost') : null;
}
/// The local engine source path to use if a local engine is used for [flutter]
/// and [evalFlutter].
///
/// This is set as an environment variable when running the task, see runTask in runner.dart.
String? get localEngineSrcPathFromEnv {
const bool isDefined = bool.hasEnvironment('localEngineSrcPath');
return isDefined ? const String.fromEnvironment('localEngineSrcPath') : null;
}
/// The local Web SDK to use for [flutter] and [evalFlutter], if any.
///
/// This is set as an environment variable when running the task, see runTask in runner.dart.
String? get localWebSdkFromEnv {
const bool isDefined = bool.hasEnvironment('localWebSdk');
return isDefined ? const String.fromEnvironment('localWebSdk') : null;
}
List<ProcessInfo> _runningProcesses = <ProcessInfo>[];
ProcessManager _processManager = const LocalProcessManager();
class ProcessInfo {
ProcessInfo(this.command, this.process);
final DateTime startTime = DateTime.now();
final String command;
final Process process;
@override
String toString() {
return '''
command: $command
started: $startTime
pid : ${process.pid}
'''
.trim();
}
}
/// Result of a health check for a specific parameter.
class HealthCheckResult {
HealthCheckResult.success([this.details]) : succeeded = true;
HealthCheckResult.failure(this.details) : succeeded = false;
HealthCheckResult.error(dynamic error, dynamic stackTrace)
: succeeded = false,
details = 'ERROR: $error${stackTrace != null ? '\n$stackTrace' : ''}';
final bool succeeded;
final String? details;
@override
String toString() {
final StringBuffer buf = StringBuffer(succeeded ? 'succeeded' : 'failed');
if (details != null && details!.trim().isNotEmpty) {
buf.writeln();
// Indent details by 4 spaces
for (final String line in details!.trim().split('\n')) {
buf.writeln(' $line');
}
}
return '$buf';
}
}
class BuildFailedError extends Error {
BuildFailedError(this.message);
final String message;
@override
String toString() => message;
}
void fail(String message) {
throw BuildFailedError(message);
}
// Remove the given file or directory.
void rm(FileSystemEntity entity, { bool recursive = false}) {
if (entity.existsSync()) {
// This should not be necessary, but it turns out that
// on Windows it's common for deletions to fail due to
// bogus (we think) "access denied" errors.
try {
entity.deleteSync(recursive: recursive);
} on FileSystemException catch (error) {
print('Failed to delete ${entity.path}: $error');
}
}
}
/// Remove recursively.
void rmTree(FileSystemEntity entity) {
rm(entity, recursive: true);
}
List<FileSystemEntity> ls(Directory directory) => directory.listSync();
Directory dir(String path) => Directory(path);
File file(String path) => File(path);
void copy(File sourceFile, Directory targetDirectory, {String? name}) {
final File target = file(
path.join(targetDirectory.path, name ?? path.basename(sourceFile.path)));
target.writeAsBytesSync(sourceFile.readAsBytesSync());
}
void recursiveCopy(Directory source, Directory target) {
if (!target.existsSync()) {
target.createSync();
}
for (final FileSystemEntity entity in source.listSync(followLinks: false)) {
final String name = path.basename(entity.path);
if (entity is Directory && !entity.path.contains('.dart_tool')) {
recursiveCopy(entity, Directory(path.join(target.path, name)));
} else if (entity is File) {
final File dest = File(path.join(target.path, name));
dest.writeAsBytesSync(entity.readAsBytesSync());
// Preserve executable bit
final String modes = entity.statSync().modeString();
if (modes.contains('x')) {
makeExecutable(dest);
}
}
}
}
FileSystemEntity move(FileSystemEntity whatToMove,
{required Directory to, String? name}) {
return whatToMove
.renameSync(path.join(to.path, name ?? path.basename(whatToMove.path)));
}
/// Equivalent of `chmod a+x file`
void makeExecutable(File file) {
// Windows files do not have an executable bit
if (Platform.isWindows) {
return;
}
final ProcessResult result = _processManager.runSync(<String>[
'chmod',
'a+x',
file.path,
]);
if (result.exitCode != 0) {
throw FileSystemException(
'Error making ${file.path} executable.\n'
'${result.stderr}',
file.path,
);
}
}
/// Equivalent of `mkdir directory`.
void mkdir(Directory directory) {
directory.createSync();
}
/// Equivalent of `mkdir -p directory`.
void mkdirs(Directory directory) {
directory.createSync(recursive: true);
}
bool exists(FileSystemEntity entity) => entity.existsSync();
void section(String title) {
String output;
if (Platform.isWindows) {
// Windows doesn't cope well with characters produced for *nix systems, so
// just output the title with no decoration.
output = title;
} else {
title = '╡ ••• $title ••• ╞';
final String line = '═' * math.max((80 - title.length) ~/ 2, 2);
output = '$line$title$line';
if (output.length == 79) {
output += '═';
}
}
print('\n\n$output\n');
}
Future<String> getDartVersion() async {
// The Dart VM returns the version text to stderr.
final ProcessResult result = _processManager.runSync(<String>[dartBin, '--version']);
String version = (result.stderr as String).trim();
// Convert:
// Dart VM version: 1.17.0-dev.2.0 (Tue May 3 12:14:52 2016) on "macos_x64"
// to:
// 1.17.0-dev.2.0
if (version.contains('(')) {
version = version.substring(0, version.indexOf('(')).trim();
}
if (version.contains(':')) {
version = version.substring(version.indexOf(':') + 1).trim();
}
return version.replaceAll('"', "'");
}
Future<String?> getCurrentFlutterRepoCommit() {
if (!dir('${flutterDirectory.path}/.git').existsSync()) {
return Future<String?>.value();
}
return inDirectory<String>(flutterDirectory, () {
return eval('git', <String>['rev-parse', 'HEAD']);
});
}
Future<DateTime> getFlutterRepoCommitTimestamp(String commit) {
// git show -s --format=%at 4b546df7f0b3858aaaa56c4079e5be1ba91fbb65
return inDirectory<DateTime>(flutterDirectory, () async {
final String unixTimestamp = await eval('git', <String>[
'show',
'-s',
'--format=%at',
commit,
]);
final int secondsSinceEpoch = int.parse(unixTimestamp);
return DateTime.fromMillisecondsSinceEpoch(secondsSinceEpoch * 1000);
});
}
/// Starts a subprocess.
///
/// The first argument is the full path to the executable to run.
///
/// The second argument is the list of arguments to provide on the command line.
/// This argument can be null, indicating no arguments (same as the empty list).
///
/// The `environment` argument can be provided to configure environment variables
/// that will be made available to the subprocess. The `BOT` environment variable
/// is always set and overrides any value provided in the `environment` argument.
/// The `isBot` argument controls the value of the `BOT` variable. It will either
/// be "true", if `isBot` is true (the default), or "false" if it is false.
///
/// The `BOT` variable is in particular used by the `flutter` tool to determine
/// how verbose to be and whether to enable analytics by default.
///
/// The working directory can be provided using the `workingDirectory` argument.
/// By default it will default to the current working directory (see [cwd]).
///
/// Information regarding the execution of the subprocess is printed to the
/// console.
///
/// The actual process executes asynchronously. A handle to the subprocess is
/// returned in the form of a [Future] that completes to a [Process] object.
Future<Process> startProcess(
String executable,
List<String>? arguments, {
Map<String, String>? environment,
bool isBot = true, // set to false to pretend not to be on a bot (e.g. to test user-facing outputs)
String? workingDirectory,
}) async {
final String command = '$executable ${arguments?.join(" ") ?? ""}';
final String finalWorkingDirectory = workingDirectory ?? cwd;
final Map<String, String> newEnvironment = Map<String, String>.from(environment ?? <String, String>{});
newEnvironment['BOT'] = isBot ? 'true' : 'false';
newEnvironment['LANG'] = 'en_US.UTF-8';
print('Executing "$command" in "$finalWorkingDirectory" with environment $newEnvironment');
final Process process = await _processManager.start(
<String>[executable, ...?arguments],
environment: newEnvironment,
workingDirectory: finalWorkingDirectory,
);
final ProcessInfo processInfo = ProcessInfo(command, process);
_runningProcesses.add(processInfo);
unawaited(process.exitCode.then<void>((int exitCode) {
_runningProcesses.remove(processInfo);
}));
return process;
}
Future<void> forceQuitRunningProcesses() async {
if (_runningProcesses.isEmpty) {
return;
}
// Give normally quitting processes a chance to report their exit code.
await Future<void>.delayed(const Duration(seconds: 1));
// Whatever's left, kill it.
for (final ProcessInfo p in _runningProcesses) {
print('Force-quitting process:\n$p');
if (!p.process.kill()) {
print('Failed to force quit process.');
}
}
_runningProcesses.clear();
}
/// Executes a command and returns its exit code.
Future<int> exec(
String executable,
List<String> arguments, {
Map<String, String>? environment,
bool canFail = false, // as in, whether failures are ok. False means that they are fatal.
String? workingDirectory,
StringBuffer? output, // if not null, the stdout will be written here
StringBuffer? stderr, // if not null, the stderr will be written here
}) async {
return _execute(
executable,
arguments,
environment: environment,
canFail : canFail,
workingDirectory: workingDirectory,
output: output,
stderr: stderr,
);
}
Future<int> _execute(
String executable,
List<String> arguments, {
Map<String, String>? environment,
bool canFail = false, // as in, whether failures are ok. False means that they are fatal.
String? workingDirectory,
StringBuffer? output, // if not null, the stdout will be written here
StringBuffer? stderr, // if not null, the stderr will be written here
bool printStdout = true,
bool printStderr = true,
}) async {
final Process process = await startProcess(
executable,
arguments,
environment: environment,
workingDirectory: workingDirectory,
);
await forwardStandardStreams(
process,
output: output,
stderr: stderr,
printStdout: printStdout,
printStderr: printStderr,
);
final int exitCode = await process.exitCode;
if (exitCode != 0 && !canFail) {
fail('Executable "$executable" failed with exit code $exitCode.');
}
return exitCode;
}
/// Forwards standard out and standard error from [process] to this process'
/// respective outputs. Also writes stdout to [output] and stderr to [stderr]
/// if they are not null.
///
/// Returns a future that completes when both out and error streams a closed.
Future<void> forwardStandardStreams(
Process process, {
StringBuffer? output,
StringBuffer? stderr,
bool printStdout = true,
bool printStderr = true,
}) {
final Completer<void> stdoutDone = Completer<void>();
final Completer<void> stderrDone = Completer<void>();
process.stdout
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen((String line) {
if (printStdout) {
print('stdout: $line');
}
output?.writeln(line);
}, onDone: () { stdoutDone.complete(); });
process.stderr
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen((String line) {
if (printStderr) {
print('stderr: $line');
}
stderr?.writeln(line);
}, onDone: () { stderrDone.complete(); });
return Future.wait<void>(<Future<void>>[
stdoutDone.future,
stderrDone.future,
]);
}
/// Executes a command and returns its standard output as a String.
///
/// For logging purposes, the command's output is also printed out by default.
Future<String> eval(
String executable,
List<String> arguments, {
Map<String, String>? environment,
bool canFail = false, // as in, whether failures are ok. False means that they are fatal.
String? workingDirectory,
StringBuffer? stdout, // if not null, the stdout will be written here
StringBuffer? stderr, // if not null, the stderr will be written here
bool printStdout = true,
bool printStderr = true,
}) async {
final StringBuffer output = stdout ?? StringBuffer();
await _execute(
executable,
arguments,
environment: environment,
canFail: canFail,
workingDirectory: workingDirectory,
output: output,
stderr: stderr,
printStdout: printStdout,
printStderr: printStderr,
);
return output.toString().trimRight();
}
List<String> _flutterCommandArgs(String command, List<String> options) {
// Commands support the --device-timeout flag.
final Set<String> supportedDeviceTimeoutCommands = <String>{
'attach',
'devices',
'drive',
'install',
'logs',
'run',
'screenshot',
};
final String? localEngine = localEngineFromEnv;
final String? localEngineHost = localEngineHostFromEnv;
final String? localEngineSrcPath = localEngineSrcPathFromEnv;
final String? localWebSdk = localWebSdkFromEnv;
final bool pubOrPackagesCommand = command.startsWith('packages') || command.startsWith('pub');
return <String>[
command,
if (deviceOperatingSystem == DeviceOperatingSystem.ios && supportedDeviceTimeoutCommands.contains(command))
...<String>[
'--device-timeout',
'5',
],
if (command == 'drive' && hostAgent.dumpDirectory != null) ...<String>[
'--screenshot',
hostAgent.dumpDirectory!.path,
],
if (localEngine != null) ...<String>['--local-engine', localEngine],
if (localEngineHost != null) ...<String>['--local-engine-host', localEngineHost],
if (localEngineSrcPath != null) ...<String>['--local-engine-src-path', localEngineSrcPath],
if (localWebSdk != null) ...<String>['--local-web-sdk', localWebSdk],
...options,
// Use CI flag when running devicelab tests, except for `packages`/`pub` commands.
// `packages`/`pub` commands effectively runs the `pub` tool, which does not have
// the same allowed args.
if (!pubOrPackagesCommand) '--ci',
if (!pubOrPackagesCommand && hostAgent.dumpDirectory != null)
'--debug-logs-dir=${hostAgent.dumpDirectory!.path}'
];
}
/// Runs the flutter `command`, and returns the exit code.
/// If `canFail` is `false`, the future completes with an error.
Future<int> flutter(String command, {
List<String> options = const <String>[],
bool canFail = false, // as in, whether failures are ok. False means that they are fatal.
Map<String, String>? environment,
String? workingDirectory,
}) async {
final List<String> args = _flutterCommandArgs(command, options);
final int exitCode = await exec(path.join(flutterDirectory.path, 'bin', 'flutter'), args,
canFail: canFail, environment: environment, workingDirectory: workingDirectory);
if (exitCode != 0 && !canFail) {
await _flutterScreenshot(workingDirectory: workingDirectory);
}
return exitCode;
}
/// Starts a Flutter subprocess.
///
/// The first argument is the flutter command to run.
///
/// The second argument is the list of arguments to provide on the command line.
/// This argument can be null, indicating no arguments (same as the empty list).
///
/// The `environment` argument can be provided to configure environment variables
/// that will be made available to the subprocess. The `BOT` environment variable
/// is always set and overrides any value provided in the `environment` argument.
/// The `isBot` argument controls the value of the `BOT` variable. It will either
/// be "true", if `isBot` is true (the default), or "false" if it is false.
///
/// The `isBot` argument controls whether the `BOT` environment variable is set
/// to `true` or `false` and is used by the `flutter` tool to determine how
/// verbose to be and whether to enable analytics by default.
///
/// Information regarding the execution of the subprocess is printed to the
/// console.
///
/// The actual process executes asynchronously. A handle to the subprocess is
/// returned in the form of a [Future] that completes to a [Process] object.
Future<Process> startFlutter(String command, {
List<String> options = const <String>[],
Map<String, String> environment = const <String, String>{},
bool isBot = true, // set to false to pretend not to be on a bot (e.g. to test user-facing outputs)
String? workingDirectory,
}) async {
final List<String> args = _flutterCommandArgs(command, options);
final Process process = await startProcess(
path.join(flutterDirectory.path, 'bin', 'flutter'),
args,
environment: environment,
isBot: isBot,
workingDirectory: workingDirectory,
);
unawaited(process.exitCode.then<void>((int exitCode) async {
if (exitCode != 0) {
await _flutterScreenshot(workingDirectory: workingDirectory);
}
}));
return process;
}
/// Runs a `flutter` command and returns the standard output as a string.
Future<String> evalFlutter(String command, {
List<String> options = const <String>[],
bool canFail = false, // as in, whether failures are ok. False means that they are fatal.
Map<String, String>? environment,
StringBuffer? stderr, // if not null, the stderr will be written here.
String? workingDirectory,
}) {
final List<String> args = _flutterCommandArgs(command, options);
return eval(path.join(flutterDirectory.path, 'bin', 'flutter'), args,
canFail: canFail, environment: environment, stderr: stderr, workingDirectory: workingDirectory);
}
Future<ProcessResult> executeFlutter(String command, {
List<String> options = const <String>[],
bool canFail = false, // as in, whether failures are ok. False means that they are fatal.
}) async {
final List<String> args = _flutterCommandArgs(command, options);
final ProcessResult processResult = await _processManager.run(
<String>[path.join(flutterDirectory.path, 'bin', 'flutter'), ...args],
workingDirectory: cwd,
);
if (processResult.exitCode != 0 && !canFail) {
await _flutterScreenshot();
}
return processResult;
}
Future<void> _flutterScreenshot({ String? workingDirectory }) async {
try {
final Directory? dumpDirectory = hostAgent.dumpDirectory;
if (dumpDirectory == null) {
return;
}
// On command failure try uploading screenshot of failing command.
final String screenshotPath = path.join(
dumpDirectory.path,
'device-screenshot-${DateTime.now().toLocal().toIso8601String()}.png',
);
final String deviceId = (await devices.workingDevice).deviceId;
print('Taking screenshot of working device $deviceId at $screenshotPath');
final List<String> args = _flutterCommandArgs(
'screenshot',
<String>[
'--out',
screenshotPath,
'-d', deviceId,
],
);
final ProcessResult screenshot = await _processManager.run(
<String>[path.join(flutterDirectory.path, 'bin', 'flutter'), ...args],
workingDirectory: workingDirectory ?? cwd,
);
if (screenshot.exitCode != 0) {
print('Failed to take screenshot. Continuing.');
}
} catch (exception) {
print('Failed to take screenshot. Continuing.\n$exception');
}
}
String get dartBin =>
path.join(flutterDirectory.path, 'bin', 'cache', 'dart-sdk', 'bin', 'dart');
String get pubBin =>
path.join(flutterDirectory.path, 'bin', 'cache', 'dart-sdk', 'bin', 'pub');
Future<int> dart(List<String> args) => exec(dartBin, <String>['--disable-dart-dev', ...args]);
/// Returns a future that completes with a path suitable for JAVA_HOME
/// or with null, if Java cannot be found.
Future<String?> findJavaHome() async {
if (_javaHome == null) {
final Iterable<String> hits = grep(
'Java binary at: ',
from: await evalFlutter('doctor', options: <String>['-v']),
);
if (hits.isEmpty) {
return null;
}
final String javaBinary = hits.first
.split(': ')
.last;
// javaBinary == /some/path/to/java/home/bin/java
_javaHome = path.dirname(path.dirname(javaBinary));
}
return _javaHome;
}
String? _javaHome;
Future<T> inDirectory<T>(dynamic directory, Future<T> Function() action) async {
final String previousCwd = cwd;
try {
cd(directory);
return await action();
} finally {
cd(previousCwd);
}
}
void cd(dynamic directory) {
Directory d;
if (directory is String) {
cwd = directory;
d = dir(directory);
} else if (directory is Directory) {
cwd = directory.path;
d = directory;
} else {
throw FileSystemException('Unsupported directory type ${directory.runtimeType}', directory.toString());
}
if (!d.existsSync()) {
throw FileSystemException('Cannot cd into directory that does not exist', d.toString());
}
}
Directory get flutterDirectory => Directory.current.parent.parent;
Directory get openpayDirectory => Directory(requireEnvVar('OPENPAY_CHECKOUT_PATH'));
String requireEnvVar(String name) {
final String? value = Platform.environment[name];
if (value == null) {
fail('$name environment variable is missing. Quitting.');
}
return value!;
}
T requireConfigProperty<T>(Map<String, dynamic> map, String propertyName) {
if (!map.containsKey(propertyName)) {
fail('Configuration property not found: $propertyName');
}
final T result = map[propertyName] as T;
return result;
}
String jsonEncode(dynamic data) {
final String jsonValue = const JsonEncoder.withIndent(' ').convert(data);
return '$jsonValue\n';
}
/// Splits [from] into lines and selects those that contain [pattern].
Iterable<String> grep(Pattern pattern, {required String from}) {
return from.split('\n').where((String line) {
return line.contains(pattern);
});
}
/// Captures asynchronous stack traces thrown by [callback].
///
/// This is a convenience wrapper around [Chain] optimized for use with
/// `async`/`await`.
///
/// Example:
///
/// try {
/// await captureAsyncStacks(() { /* async things */ });
/// } catch (error, chain) {
///
/// }
Future<void> runAndCaptureAsyncStacks(Future<void> Function() callback) {
final Completer<void> completer = Completer<void>();
Chain.capture(() async {
await callback();
completer.complete();
}, onError: completer.completeError);
return completer.future;
}
bool canRun(String path) => _processManager.canRun(path);
final RegExp _obsRegExp =
RegExp('A Dart VM Service .* is available at: ');
final RegExp _obsPortRegExp = RegExp(r'(\S+:(\d+)/\S*)$');
final RegExp _obsUriRegExp = RegExp(r'((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+)');
/// Tries to extract a port from the string.
///
/// The `prefix`, if specified, is a regular expression pattern and must not contain groups.
/// `prefix` defaults to the RegExp: `A Dart VM Service .* is available at: `.
int? parseServicePort(String line, {
Pattern? prefix,
}) {
prefix ??= _obsRegExp;
final Iterable<Match> matchesIter = prefix.allMatches(line);
if (matchesIter.isEmpty) {
return null;
}
final Match prefixMatch = matchesIter.first;
final List<Match> matches =
_obsPortRegExp.allMatches(line, prefixMatch.end).toList();
return matches.isEmpty ? null : int.parse(matches[0].group(2)!);
}
/// Tries to extract a URL from the string.
///
/// The `prefix`, if specified, is a regular expression pattern and must not contain groups.
/// `prefix` defaults to the RegExp: `A Dart VM Service .* is available at: `.
Uri? parseServiceUri(String line, {
Pattern? prefix,
}) {
prefix ??= _obsRegExp;
final Iterable<Match> matchesIter = prefix.allMatches(line);
if (matchesIter.isEmpty) {
return null;
}
final Match prefixMatch = matchesIter.first;
final List<Match> matches =
_obsUriRegExp.allMatches(line, prefixMatch.end).toList();
return matches.isEmpty ? null : Uri.parse(matches[0].group(0)!);
}
/// Checks that the file exists, otherwise throws a [FileSystemException].
void checkFileExists(String file) {
if (!exists(File(file))) {
throw FileSystemException('Expected file to exist.', file);
}
}
/// Checks that the file does not exists, otherwise throws a [FileSystemException].
void checkFileNotExists(String file) {
if (exists(File(file))) {
throw FileSystemException('Expected file to not exist.', file);
}
}
/// Checks that the directory exists, otherwise throws a [FileSystemException].
void checkDirectoryExists(String directory) {
if (!exists(Directory(directory))) {
throw FileSystemException('Expected directory to exist.', directory);
}
}
/// Checks that the directory does not exist, otherwise throws a [FileSystemException].
void checkDirectoryNotExists(String directory) {
if (exists(Directory(directory))) {
throw FileSystemException('Expected directory to not exist.', directory);
}
}
/// Checks that the symlink exists, otherwise throws a [FileSystemException].
void checkSymlinkExists(String file) {
if (!exists(Link(file))) {
throw FileSystemException('Expected symlink to exist.', file);
}
}
/// Check that `collection` contains all entries in `values`.
void checkCollectionContains<T>(Iterable<T> values, Iterable<T> collection) {
for (final T value in values) {
if (!collection.contains(value)) {
throw TaskResult.failure('Expected to find `$value` in `$collection`.');
}
}
}
/// Check that `collection` does not contain any entries in `values`
void checkCollectionDoesNotContain<T>(Iterable<T> values, Iterable<T> collection) {
for (final T value in values) {
if (collection.contains(value)) {
throw TaskResult.failure('Did not expect to find `$value` in `$collection`.');
}
}
}
/// Checks that the contents of a [File] at `filePath` contains the specified
/// [Pattern]s, otherwise throws a [TaskResult].
void checkFileContains(List<Pattern> patterns, String filePath) {
final String fileContent = File(filePath).readAsStringSync();
for (final Pattern pattern in patterns) {
if (!fileContent.contains(pattern)) {
throw TaskResult.failure(
'Expected to find `$pattern` in `$filePath` '
'instead it found:\n$fileContent'
);
}
}
}
/// Clones a git repository.
///
/// Removes the directory [path], then clones the git repository
/// specified by [repo] to the directory [path].
Future<int> gitClone({required String path, required String repo}) async {
rmTree(Directory(path));
await Directory(path).create(recursive: true);
return inDirectory<int>(
path,
() => exec('git', <String>['clone', repo]),
);
}
/// Call [fn] retrying so long as [retryIf] return `true` for the exception
/// thrown and [maxAttempts] has not been reached.
///
/// If no [retryIf] function is given this will retry any for any [Exception]
/// thrown. To retry on an [Error], the error must be caught and _rethrown_
/// as an [Exception].
///
/// Waits a constant duration of [delayDuration] between every retry attempt.
Future<T> retry<T>(
FutureOr<T> Function() fn, {
FutureOr<bool> Function(Exception)? retryIf,
int maxAttempts = 5,
Duration delayDuration = const Duration(seconds: 3),
}) async {
int attempt = 0;
while (true) {
attempt++; // first invocation is the first attempt
try {
return await fn();
} on Exception catch (e) {
if (attempt >= maxAttempts ||
(retryIf != null && !(await retryIf(e)))) {
rethrow;
}
}
// Sleep for a delay
await Future<void>.delayed(delayDuration);
}
}
Future<void> createFfiPackage(String name, Directory parent) async {
await inDirectory(parent, () async {
await flutter(
'create',
options: <String>[
'--no-pub',
'--org',
'io.flutter.devicelab',
'--template=package_ffi',
name,
],
);
await _pinDependencies(
File(path.join(parent.path, name, 'pubspec.yaml')),
);
await _pinDependencies(
File(path.join(parent.path, name, 'example', 'pubspec.yaml')),
);
});
}
Future<void> _pinDependencies(File pubspecFile) async {
final String oldPubspec = await pubspecFile.readAsString();
final String newPubspec = oldPubspec.replaceAll(': ^', ': ');
await pubspecFile.writeAsString(newPubspec);
}
| flutter/dev/devicelab/lib/framework/utils.dart/0 | {
"file_path": "flutter/dev/devicelab/lib/framework/utils.dart",
"repo_id": "flutter",
"token_count": 9754
} | 501 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert' show json;
import 'dart:io';
import 'package:flutter_devicelab/framework/devices.dart';
import 'package:flutter_devicelab/framework/task_result.dart';
import 'package:flutter_devicelab/tasks/perf_tests.dart';
import 'common.dart';
void main() {
late Directory testDirectory;
late File testTarget;
late Device device;
setUp(() async {
testDirectory = Directory.systemTemp.createTempSync('test_dir');
testTarget = File('${testDirectory.absolute.path}/test_file')..createSync();
device = const FakeDevice(deviceId: 'fakeDeviceId');
deviceOperatingSystem = DeviceOperatingSystem.fake;
});
// This tests when keys like `30hz_frame_percentage`, `60hz_frame_percentage` are not in the generated file.
test('runs perf tests, no crash if refresh rate percentage keys are not in the data', () async {
final Map<String, dynamic> fakeData = <String, dynamic>{
'frame_count': 5,
'average_frame_build_time_millis': 0.1,
'worst_frame_build_time_millis': 0.1,
'90th_percentile_frame_build_time_millis': 0.1,
'99th_percentile_frame_build_time_millis': 0.1,
'average_frame_rasterizer_time_millis': 0.1,
'worst_frame_rasterizer_time_millis': 0.1,
'90th_percentile_frame_rasterizer_time_millis': 0.1,
'99th_percentile_frame_rasterizer_time_millis': 0.1,
'average_layer_cache_count': 1,
'90th_percentile_layer_cache_count': 1,
'99th_percentile_layer_cache_count': 1,
'worst_layer_cache_count': 1,
'average_layer_cache_memory': 1,
'90th_percentile_layer_cache_memory': 1,
'99th_percentile_layer_cache_memory': 1,
'worst_layer_cache_memory': 1,
'average_picture_cache_count': 1,
'90th_percentile_picture_cache_count': 1,
'99th_percentile_picture_cache_count': 1,
'worst_picture_cache_count': 1,
'average_picture_cache_memory': 1,
'90th_percentile_picture_cache_memory': 1,
'99th_percentile_picture_cache_memory': 1,
'worst_picture_cache_memory': 1,
'total_ui_gc_time': 1,
'new_gen_gc_count': 1,
'old_gen_gc_count': 1,
'average_vsync_transitions_missed': 1,
'90th_percentile_vsync_transitions_missed': 1,
'99th_percentile_vsync_transitions_missed': 1,
'average_frame_request_pending_latency': 0.1,
'90th_percentile_frame_request_pending_latency': 0.1,
'99th_percentile_frame_request_pending_latency': 0.1,
};
const String resultFileName = 'fake_result';
void driveCallback(List<String> arguments) {
final File resultFile = File('${testDirectory.absolute.path}/build/$resultFileName.json')..createSync(recursive: true);
resultFile.writeAsStringSync(json.encode(fakeData));
}
final PerfTest perfTest = PerfTest(testDirectory.absolute.path, testTarget.absolute.path, 'test_file', resultFilename: resultFileName, device: device, flutterDriveCallback: driveCallback);
final TaskResult result = await perfTest.run();
expect(result.data!['frame_count'], 5);
});
test('runs perf tests, successfully parse refresh rate percentage key-values from data`', () async {
final Map<String, dynamic> fakeData = <String, dynamic>{
'frame_count': 5,
'average_frame_build_time_millis': 0.1,
'worst_frame_build_time_millis': 0.1,
'90th_percentile_frame_build_time_millis': 0.1,
'99th_percentile_frame_build_time_millis': 0.1,
'average_frame_rasterizer_time_millis': 0.1,
'worst_frame_rasterizer_time_millis': 0.1,
'90th_percentile_frame_rasterizer_time_millis': 0.1,
'99th_percentile_frame_rasterizer_time_millis': 0.1,
'average_layer_cache_count': 1,
'90th_percentile_layer_cache_count': 1,
'99th_percentile_layer_cache_count': 1,
'worst_layer_cache_count': 1,
'average_layer_cache_memory': 1,
'90th_percentile_layer_cache_memory': 1,
'99th_percentile_layer_cache_memory': 1,
'worst_layer_cache_memory': 1,
'average_picture_cache_count': 1,
'90th_percentile_picture_cache_count': 1,
'99th_percentile_picture_cache_count': 1,
'worst_picture_cache_count': 1,
'average_picture_cache_memory': 1,
'90th_percentile_picture_cache_memory': 1,
'99th_percentile_picture_cache_memory': 1,
'worst_picture_cache_memory': 1,
'total_ui_gc_time': 1,
'new_gen_gc_count': 1,
'old_gen_gc_count': 1,
'average_vsync_transitions_missed': 1,
'90th_percentile_vsync_transitions_missed': 1,
'99th_percentile_vsync_transitions_missed': 1,
'30hz_frame_percentage': 0.1,
'60hz_frame_percentage': 0.2,
'80hz_frame_percentage': 0.3,
'90hz_frame_percentage': 0.4,
'120hz_frame_percentage': 0.6,
'illegal_refresh_rate_frame_count': 10,
'average_frame_request_pending_latency': 0.1,
'90th_percentile_frame_request_pending_latency': 0.1,
'99th_percentile_frame_request_pending_latency': 0.1,
};
const String resultFileName = 'fake_result';
void driveCallback(List<String> arguments) {
final File resultFile = File('${testDirectory.absolute.path}/build/$resultFileName.json')..createSync(recursive: true);
resultFile.writeAsStringSync(json.encode(fakeData));
}
final PerfTest perfTest = PerfTest(testDirectory.absolute.path, testTarget.absolute.path, 'test_file', resultFilename: resultFileName, device: device, flutterDriveCallback: driveCallback);
final TaskResult result = await perfTest.run();
expect(result.data!['30hz_frame_percentage'], 0.1);
expect(result.data!['60hz_frame_percentage'], 0.2);
expect(result.data!['80hz_frame_percentage'], 0.3);
expect(result.data!['90hz_frame_percentage'], 0.4);
expect(result.data!['120hz_frame_percentage'], 0.6);
expect(result.data!['illegal_refresh_rate_frame_count'], 10);
});
}
| flutter/dev/devicelab/test/perf_tests_test.dart/0 | {
"file_path": "flutter/dev/devicelab/test/perf_tests_test.dart",
"repo_id": "flutter",
"token_count": 2425
} | 502 |
/**
* Scripting for handling custom code snippets
*/
/**
* Shows the requested snippet, and stores the current state in visibleSnippet.
*/
function showSnippet(name, visibleSnippet) {
if (visibleSnippet == name) return;
if (visibleSnippet != null) {
var shown = document.getElementById(visibleSnippet);
var attribute = document.createAttribute('hidden');
if (shown != null) {
shown.setAttributeNode(attribute);
}
var button = document.getElementById(visibleSnippet + 'Button');
if (button != null) {
button.removeAttribute('selected');
}
}
if (name == null || name == '') {
visibleSnippet = null;
return;
}
var newlyVisible = document.getElementById(name);
if (newlyVisible != null) {
visibleSnippet = name;
newlyVisible.removeAttribute('hidden');
} else {
visibleSnippet = null;
}
var button = document.getElementById(name + 'Button');
var selectedAttribute = document.createAttribute('selected');
if (button != null) {
button.setAttributeNode(selectedAttribute);
}
return visibleSnippet;
}
// Finds a sibling to given element with the given id.
function findSiblingWithId(element, id) {
var siblings = element.parentNode.children;
var siblingWithId = null;
for (var i = siblings.length; i--;) {
if (siblings[i] == element) continue;
if (siblings[i].id == id) {
siblingWithId = siblings[i];
break;
}
}
return siblingWithId;
};
// Returns true if the browser supports the "copy" command.
function supportsCopying() {
return !!document.queryCommandSupported &&
!!document.queryCommandSupported('copy');
}
// Copies the given string to the clipboard.
function copyStringToClipboard(string) {
var textArea = document.createElement("textarea");
textArea.value = string;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
if (!supportsCopying()) {
alert('Unable to copy to clipboard (not supported by browser)');
return;
}
try {
document.execCommand('copy');
} finally {
document.body.removeChild(textArea);
}
}
function fixHref(anchor, id) {
anchor.href = window.location.href.replace(/#.*$/, '') + '#' + id;
}
// Copies the text inside the currently visible snippet to the clipboard, or the
// given element, if any.
function copyTextToClipboard(element) {
if (typeof element === 'string') {
var elementSelector = '#' + element + ' .language-dart';
element = document.querySelector(elementSelector);
if (element == null) {
console.log(
'copyTextToClipboard: Unable to find element for "' +
elementSelector + '"');
return;
}
}
if (!supportsCopying()) {
alert('Unable to copy to clipboard (not supported by browser)');
return;
}
if (element.hasAttribute('contenteditable')) {
element.focus();
}
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
}
| flutter/dev/docs/assets/snippets.js/0 | {
"file_path": "flutter/dev/docs/assets/snippets.js",
"repo_id": "flutter",
"token_count": 1026
} | 503 |
<!-- Styles and scripting for handling custom code snippets -->
<link href="../assets/snippets.css" rel="stylesheet" type="text/css">
<script src="../assets/snippets.js"></script>
| flutter/dev/docs/snippets.html/0 | {
"file_path": "flutter/dev/docs/snippets.html",
"repo_id": "flutter",
"token_count": 53
} | 504 |
org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError
android.enableJetifier=true
android.useAndroidX=true
| flutter/dev/integration_tests/abstract_method_smoke_test/android/gradle.properties/0 | {
"file_path": "flutter/dev/integration_tests/abstract_method_smoke_test/android/gradle.properties",
"repo_id": "flutter",
"token_count": 54
} | 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 library provides constants and matchers for testing the Android
/// accessibility implementation in a flutter driver environment.
library android_semantics_testing;
export 'src/common.dart';
export 'src/constants.dart';
export 'src/matcher.dart';
| flutter/dev/integration_tests/android_semantics_testing/lib/android_semantics_testing.dart/0 | {
"file_path": "flutter/dev/integration_tests/android_semantics_testing/lib/android_semantics_testing.dart",
"repo_id": "flutter",
"token_count": 108
} | 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.
/// A pair of values. Used for testing custom codecs.
class Pair {
Pair(this.left, this.right);
final dynamic left;
final dynamic right;
@override
String toString() => 'Pair[$left, $right]';
}
| flutter/dev/integration_tests/channels/lib/src/pair.dart/0 | {
"file_path": "flutter/dev/integration_tests/channels/lib/src/pair.dart",
"repo_id": "flutter",
"token_count": 109
} | 507 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| flutter/dev/integration_tests/channels/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "flutter/dev/integration_tests/channels/macos/Runner/Configs/Release.xcconfig",
"repo_id": "flutter",
"token_count": 32
} | 508 |
#include "Generated.xcconfig"
| flutter/dev/integration_tests/external_textures/ios/Flutter/Release.xcconfig/0 | {
"file_path": "flutter/dev/integration_tests/external_textures/ios/Flutter/Release.xcconfig",
"repo_id": "flutter",
"token_count": 12
} | 509 |
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "e0caf9ca0b7c592bd7b00d5413fae534738bb385"
channel: "[user-branch]"
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: e0caf9ca0b7c592bd7b00d5413fae534738bb385
base_revision: e0caf9ca0b7c592bd7b00d5413fae534738bb385
- platform: macos
create_revision: e0caf9ca0b7c592bd7b00d5413fae534738bb385
base_revision: e0caf9ca0b7c592bd7b00d5413fae534738bb385
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
| flutter/dev/integration_tests/flavors/.metadata/0 | {
"file_path": "flutter/dev/integration_tests/flavors/.metadata",
"repo_id": "flutter",
"token_count": 370
} | 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 'package:flavors/main.dart' as app;
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('Flavor Test', () {
testWidgets('check flavor', (WidgetTester tester) async {
app.runMainApp();
await tester.pumpAndSettle();
await tester.pumpAndSettle();
expect(find.text('paid'), findsOneWidget);
expect(appFlavor, 'paid');
});
});
}
| flutter/dev/integration_tests/flavors/integration_test/integration_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/flavors/integration_test/integration_test.dart",
"repo_id": "flutter",
"token_count": 248
} | 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:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
const String _kGalleryAssetsPackage = 'flutter_gallery_assets';
const List<Color> coolColors = <Color>[
Color.fromARGB(255, 255, 59, 48),
Color.fromARGB(255, 255, 149, 0),
Color.fromARGB(255, 255, 204, 0),
Color.fromARGB(255, 76, 217, 100),
Color.fromARGB(255, 90, 200, 250),
Color.fromARGB(255, 0, 122, 255),
Color.fromARGB(255, 88, 86, 214),
Color.fromARGB(255, 255, 45, 85),
];
const List<String> coolColorNames = <String>[
'Sarcoline', 'Coquelicot', 'Smaragdine', 'Mikado', 'Glaucous', 'Wenge',
'Fulvous', 'Xanadu', 'Falu', 'Eburnean', 'Amaranth', 'Australien',
'Banan', 'Falu', 'Gingerline', 'Incarnadine', 'Labrador', 'Nattier',
'Pervenche', 'Sinoper', 'Verditer', 'Watchet', 'Zaffre',
];
const int _kChildCount = 50;
class CupertinoNavigationDemo extends StatelessWidget {
CupertinoNavigationDemo({ super.key, this.randomSeed })
: colorItems = List<Color>.generate(_kChildCount, (int index) {
return coolColors[math.Random(randomSeed).nextInt(coolColors.length)];
}) ,
colorNameItems = List<String>.generate(_kChildCount, (int index) {
return coolColorNames[math.Random(randomSeed).nextInt(coolColorNames.length)];
});
static const String routeName = '/cupertino/navigation';
final List<Color> colorItems;
final List<String> colorNameItems;
final int? randomSeed;
@override
Widget build(BuildContext context) {
return PopScope(
// Prevent swipe popping of this page. Use explicit exit buttons only.
canPop: false,
child: DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.house, size: 27),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.chat_bubble, size: 27),
label: 'Support',
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.person_circle, size: 27),
label: 'Profile',
),
],
),
tabBuilder: (BuildContext context, int index) {
switch (index) {
case 0:
return CupertinoTabView(
builder: (BuildContext context) {
return CupertinoDemoTab1(
colorItems: colorItems,
colorNameItems: colorNameItems,
randomSeed: randomSeed,
);
},
defaultTitle: 'Colors',
);
case 1:
return CupertinoTabView(
builder: (BuildContext context) => const CupertinoDemoTab2(),
defaultTitle: 'Support Chat',
);
case 2:
return CupertinoTabView(
builder: (BuildContext context) => const CupertinoDemoTab3(),
defaultTitle: 'Account',
);
}
assert(false);
return const CupertinoTabView();
},
),
),
);
}
}
class ExitButton extends StatelessWidget {
const ExitButton({super.key});
@override
Widget build(BuildContext context) {
return CupertinoButton(
padding: EdgeInsets.zero,
child: const Tooltip(
message: 'Back',
excludeFromSemantics: true,
child: Text('Exit'),
),
onPressed: () {
// The demo is on the root navigator.
Navigator.of(context, rootNavigator: true).pop();
},
);
}
}
final Widget trailingButtons = Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
CupertinoDemoDocumentationButton(CupertinoNavigationDemo.routeName),
const Padding(padding: EdgeInsets.only(left: 8.0)),
const ExitButton(),
],
);
class CupertinoDemoTab1 extends StatelessWidget {
const CupertinoDemoTab1({
super.key,
this.colorItems,
this.colorNameItems,
this.randomSeed,
});
final List<Color>? colorItems;
final List<String>? colorNameItems;
final int? randomSeed;
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
backgroundColor: CupertinoColors.systemGroupedBackground,
child: CustomScrollView(
semanticChildCount: _kChildCount,
slivers: <Widget>[
CupertinoSliverNavigationBar(
trailing: trailingButtons,
),
SliverPadding(
// Top media padding consumed by CupertinoSliverNavigationBar.
// Left/Right media padding consumed by Tab1RowItem.
padding: MediaQuery.of(context).removePadding(
removeTop: true,
removeLeft: true,
removeRight: true,
).padding,
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Tab1RowItem(
index: index,
lastItem: index == _kChildCount - 1,
color: colorItems![index],
colorName: colorNameItems![index],
randomSeed: randomSeed,
);
},
childCount: _kChildCount,
),
),
),
],
),
);
}
}
class Tab1RowItem extends StatelessWidget {
const Tab1RowItem({
super.key,
this.index,
this.lastItem,
this.color,
this.colorName,
this.randomSeed,
});
final int? index;
final bool? lastItem;
final Color? color;
final String? colorName;
final int? randomSeed;
@override
Widget build(BuildContext context) {
final Widget row = GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
Navigator.of(context).push(CupertinoPageRoute<void>(
title: colorName,
builder: (BuildContext context) => Tab1ItemPage(
color: color,
colorName: colorName,
index: index,
randomSeed: randomSeed,
),
));
},
child: ColoredBox(
color: CupertinoDynamicColor.resolve(CupertinoColors.systemBackground, context),
child: SafeArea(
top: false,
bottom: false,
child: Padding(
padding: const EdgeInsets.only(left: 16.0, top: 8.0, bottom: 8.0, right: 8.0),
child: Row(
children: <Widget>[
Container(
height: 60.0,
width: 60.0,
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(8.0),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(colorName!),
const Padding(padding: EdgeInsets.only(top: 8.0)),
Text(
'Buy this cool color',
style: TextStyle(
color: CupertinoDynamicColor.resolve(CupertinoColors.secondaryLabel, context),
fontSize: 13.0,
fontWeight: FontWeight.w300,
),
),
],
),
),
),
CupertinoButton(
padding: EdgeInsets.zero,
child: const Icon(CupertinoIcons.plus_circled,
semanticLabel: 'Add',
),
onPressed: () { },
),
CupertinoButton(
padding: EdgeInsets.zero,
child: const Icon(CupertinoIcons.share,
semanticLabel: 'Share',
),
onPressed: () { },
),
],
),
),
),
),
);
if (lastItem!) {
return row;
}
return Column(
children: <Widget>[
row,
Container(
height: 1.0,
color: CupertinoDynamicColor.resolve(CupertinoColors.separator, context),
),
],
);
}
}
class Tab1ItemPage extends StatefulWidget {
const Tab1ItemPage({super.key, this.color, this.colorName, this.index, this.randomSeed});
final Color? color;
final String? colorName;
final int? index;
final int? randomSeed;
@override
State<StatefulWidget> createState() => Tab1ItemPageState();
}
class Tab1ItemPageState extends State<Tab1ItemPage> {
late final List<Color> relatedColors = List<Color>.generate(10, (int index) {
final math.Random random = math.Random(widget.randomSeed);
return Color.fromARGB(
255,
(widget.color!.red + random.nextInt(100) - 50).clamp(0, 255),
(widget.color!.green + random.nextInt(100) - 50).clamp(0, 255),
(widget.color!.blue + random.nextInt(100) - 50).clamp(0, 255),
);
});
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
trailing: ExitButton(),
),
child: SafeArea(
top: false,
bottom: false,
child: ListView(
children: <Widget>[
const Padding(padding: EdgeInsets.only(top: 16.0)),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Row(
children: <Widget>[
Container(
height: 128.0,
width: 128.0,
decoration: BoxDecoration(
color: widget.color,
borderRadius: BorderRadius.circular(24.0),
),
),
const Padding(padding: EdgeInsets.only(left: 18.0)),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
widget.colorName!,
style: const TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),
),
const Padding(padding: EdgeInsets.only(top: 6.0)),
Text(
'Item number ${widget.index}',
style: TextStyle(
color: CupertinoDynamicColor.resolve(CupertinoColors.secondaryLabel, context),
fontSize: 16.0,
fontWeight: FontWeight.w100,
),
),
const Padding(padding: EdgeInsets.only(top: 20.0)),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
CupertinoButton.filled(
minSize: 30.0,
padding: const EdgeInsets.symmetric(horizontal: 24.0),
borderRadius: BorderRadius.circular(32.0),
child: const Text(
'GET',
style: TextStyle(
fontSize: 14.0,
fontWeight: FontWeight.w700,
letterSpacing: -0.28,
),
),
onPressed: () { },
),
CupertinoButton.filled(
minSize: 30.0,
padding: EdgeInsets.zero,
borderRadius: BorderRadius.circular(32.0),
child: const Icon(CupertinoIcons.ellipsis),
onPressed: () { },
),
],
),
],
),
),
],
),
),
const Padding(
padding: EdgeInsets.only(left: 16.0, top: 28.0, bottom: 8.0),
child: Text(
'USERS ALSO LIKED',
style: TextStyle(
color: Color(0xFF646464),
letterSpacing: -0.60,
fontSize: 15.0,
fontWeight: FontWeight.w500,
),
),
),
SizedBox(
height: 200.0,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 10,
itemExtent: 160.0,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8.0),
color: relatedColors[index],
),
child: Center(
child: CupertinoButton(
child: const Icon(
CupertinoIcons.plus_circled,
color: CupertinoColors.white,
size: 36.0,
),
onPressed: () { },
),
),
),
);
},
),
),
],
),
),
);
}
}
class CupertinoDemoTab2 extends StatelessWidget {
const CupertinoDemoTab2({super.key});
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
trailing: trailingButtons,
),
child: CupertinoScrollbar(
child: ListView(
primary: true,
children: <Widget>[
const CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated,
child: Tab2Header(),
),
...buildTab2Conversation(),
],
),
),
);
}
}
class Tab2Header extends StatelessWidget {
const Tab2Header({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: SafeArea(
top: false,
bottom: false,
child: ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(16.0)),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
decoration: BoxDecoration(
color: CupertinoDynamicColor.resolve(CupertinoColors.systemFill, context),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 18.0, vertical: 12.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'SUPPORT TICKET',
style: TextStyle(
color: CupertinoDynamicColor.resolve(CupertinoColors.secondaryLabel, context),
letterSpacing: -0.9,
fontSize: 14.0,
fontWeight: FontWeight.w500,
),
),
Text(
'Show More',
style: TextStyle(
color: CupertinoDynamicColor.resolve(CupertinoColors.secondaryLabel, context),
letterSpacing: -0.6,
fontSize: 12.0,
fontWeight: FontWeight.w500,
),
),
],
),
),
),
Container(
decoration: BoxDecoration(
color: CupertinoDynamicColor.resolve(CupertinoColors.quaternarySystemFill, context),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 18.0, vertical: 12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const Text(
'Product or product packaging damaged during transit',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.w700,
letterSpacing: -0.46,
),
),
const Padding(padding: EdgeInsets.only(top: 16.0)),
const Text(
'REVIEWERS',
style: TextStyle(
color: Color(0xFF646464),
fontSize: 12.0,
letterSpacing: -0.6,
fontWeight: FontWeight.w500,
),
),
const Padding(padding: EdgeInsets.only(top: 8.0)),
Row(
children: <Widget>[
Container(
width: 44.0,
height: 44.0,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage(
'people/square/trevor.png',
package: _kGalleryAssetsPackage,
),
),
shape: BoxShape.circle,
),
),
const Padding(padding: EdgeInsets.only(left: 8.0)),
Container(
width: 44.0,
height: 44.0,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage(
'people/square/sandra.png',
package: _kGalleryAssetsPackage,
),
),
shape: BoxShape.circle,
),
),
const Padding(padding: EdgeInsets.only(left: 2.0)),
const Icon(
CupertinoIcons.check_mark_circled,
color: Color(0xFF646464),
size: 20.0,
),
],
),
],
),
),
),
],
),
),
),
);
}
}
enum Tab2ConversationBubbleColor {
blue,
gray,
}
class Tab2ConversationBubble extends StatelessWidget {
const Tab2ConversationBubble({super.key, this.text, this.color});
final String? text;
final Tab2ConversationBubbleColor? color;
@override
Widget build(BuildContext context) {
Color? backgroundColor;
Color? foregroundColor;
switch (color) {
case Tab2ConversationBubbleColor.gray:
backgroundColor = CupertinoDynamicColor.resolve(CupertinoColors.systemFill, context);
foregroundColor = CupertinoDynamicColor.resolve(CupertinoColors.label, context);
case Tab2ConversationBubbleColor.blue:
backgroundColor = CupertinoTheme.of(context).primaryColor;
foregroundColor = CupertinoColors.white;
case null:
break;
}
return Container(
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(18.0)),
color: backgroundColor,
),
margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 8.0),
padding: const EdgeInsets.symmetric(horizontal: 14.0, vertical: 10.0),
child: Text(
text!,
style: TextStyle(
color: foregroundColor,
letterSpacing: -0.4,
fontSize: 15.0,
fontWeight: FontWeight.w400,
),
),
);
}
}
class Tab2ConversationAvatar extends StatelessWidget {
const Tab2ConversationAvatar({super.key, this.text, this.color});
final String? text;
final Color? color;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(
begin: FractionalOffset.topCenter,
end: FractionalOffset.bottomCenter,
colors: <Color>[
color!,
Color.fromARGB(
color!.alpha,
(color!.red - 60).clamp(0, 255),
(color!.green - 60).clamp(0, 255),
(color!.blue - 60).clamp(0, 255),
),
]
),
),
margin: const EdgeInsets.only(left: 8.0, bottom: 8.0),
padding: const EdgeInsets.all(12.0),
child: Text(
text!,
style: const TextStyle(
color: CupertinoColors.white,
fontSize: 13.0,
fontWeight: FontWeight.w500,
),
),
);
}
}
class Tab2ConversationRow extends StatelessWidget {
const Tab2ConversationRow({super.key, this.avatar, this.text});
final Tab2ConversationAvatar? avatar;
final String? text;
@override
Widget build(BuildContext context) {
final bool isSelf = avatar == null;
return SafeArea(
child: Row(
mainAxisAlignment: isSelf ? MainAxisAlignment.end : MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: isSelf ? CrossAxisAlignment.center : CrossAxisAlignment.end,
children: <Widget>[
if (avatar != null)
avatar!,
CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated,
child: Tab2ConversationBubble(
text: text,
color: isSelf
? Tab2ConversationBubbleColor.blue
: Tab2ConversationBubbleColor.gray,
),
),
],
),
);
}
}
List<Widget> buildTab2Conversation() {
return <Widget>[
const Tab2ConversationRow(
text: "My Xanadu doesn't look right",
),
const Tab2ConversationRow(
avatar: Tab2ConversationAvatar(
text: 'KL',
color: Color(0xFFFD5015),
),
text: "We'll rush you a new one.\nIt's gonna be incredible",
),
const Tab2ConversationRow(
text: 'Awesome thanks!',
),
const Tab2ConversationRow(
avatar: Tab2ConversationAvatar(
text: 'SJ',
color: Color(0xFF34CAD6),
),
text: "We'll send you our\nnewest Labrador too!",
),
const Tab2ConversationRow(
text: 'Yay',
),
const Tab2ConversationRow(
avatar: Tab2ConversationAvatar(
text: 'KL',
color: Color(0xFFFD5015),
),
text: "Actually there's one more thing...",
),
const Tab2ConversationRow(
text: "What's that?",
),
];
}
class CupertinoDemoTab3 extends StatelessWidget {
const CupertinoDemoTab3({super.key});
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(trailing: trailingButtons),
backgroundColor: CupertinoColors.systemBackground,
child: ListView(
children: <Widget>[
const Padding(padding: EdgeInsets.only(top: 32.0)),
GestureDetector(
onTap: () {
Navigator.of(context, rootNavigator: true).push(
CupertinoPageRoute<bool>(
fullscreenDialog: true,
builder: (BuildContext context) => const Tab3Dialog(),
),
);
},
child: 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, vertical: 8.0),
child: SafeArea(
top: false,
bottom: false,
child: Row(
children: <Widget>[
Text(
'Sign in',
style: TextStyle(color: CupertinoTheme.of(context).primaryColor),
),
],
),
),
),
),
),
],
),
);
}
}
class Tab3Dialog extends StatelessWidget {
const Tab3Dialog({super.key});
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
leading: CupertinoButton(
padding: EdgeInsets.zero,
child: const Text('Cancel'),
onPressed: () {
Navigator.of(context).pop(false);
},
),
),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Icon(
CupertinoIcons.profile_circled,
size: 160.0,
color: Color(0xFF646464),
),
const Padding(padding: EdgeInsets.only(top: 18.0)),
CupertinoButton.filled(
child: const Text('Sign in'),
onPressed: () {
Navigator.pop(context);
},
),
],
),
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_navigation_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_navigation_demo.dart",
"repo_id": "flutter",
"token_count": 15029
} | 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:flutter/material.dart';
import '../../gallery/demo.dart';
const List<String> _defaultMaterialsA = <String>[
'poker',
'tortilla',
'fish and',
'micro',
'wood',
];
const List<String> _defaultMaterialsB = <String>[
'apple',
'orange',
'tomato',
'grape',
'lettuce',
];
const List<String> _defaultActions = <String>[
'flake',
'cut',
'fragment',
'splinter',
'nick',
'fry',
'solder',
'cash in',
'eat',
];
const Map<String, String> _results = <String, String>{
'flake': 'flaking',
'cut': 'cutting',
'fragment': 'fragmenting',
'splinter': 'splintering',
'nick': 'nicking',
'fry': 'frying',
'solder': 'soldering',
'cash in': 'cashing in',
'eat': 'eating',
};
const List<String> _defaultToolsA = <String>[
'hammer',
'chisel',
'fryer',
'fabricator',
'customer',
];
const List<String> _defaultToolsB = <String>[
'keyboard',
'mouse',
'monitor',
'printer',
'cable',
];
const Map<String, String> _avatars = <String, String>{
'hammer': 'people/square/ali.png',
'chisel': 'people/square/sandra.png',
'fryer': 'people/square/trevor.png',
'fabricator': 'people/square/stella.png',
'customer': 'people/square/peter.png',
};
const Map<String, Set<String>> _toolActions = <String, Set<String>>{
'hammer': <String>{'flake', 'fragment', 'splinter'},
'chisel': <String>{'flake', 'nick', 'splinter'},
'fryer': <String>{'fry'},
'fabricator': <String>{'solder'},
'customer': <String>{'cash in', 'eat'},
};
const Map<String, Set<String>> _materialActions = <String, Set<String>>{
'poker': <String>{'cash in'},
'tortilla': <String>{'fry', 'eat'},
'fish and': <String>{'fry', 'eat'},
'micro': <String>{'solder', 'fragment'},
'wood': <String>{'flake', 'cut', 'splinter', 'nick'},
};
class _ChipsTile extends StatelessWidget {
const _ChipsTile({
this.label,
this.children,
});
final String? label;
final List<Widget>? children;
// Wraps a list of chips into a ListTile for display as a section in the demo.
@override
Widget build(BuildContext context) {
return Card(
semanticContainer: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
padding: const EdgeInsets.only(top: 16.0, bottom: 4.0),
alignment: Alignment.center,
child: Text(label!, textAlign: TextAlign.start),
),
if (children!.isNotEmpty)
Wrap(
children: children!.map<Widget>((Widget chip) {
return Padding(
padding: const EdgeInsets.all(2.0),
child: chip,
);
}).toList(),
)
else
Semantics(
container: true,
child: Container(
alignment: Alignment.center,
constraints: const BoxConstraints(minWidth: 48.0, minHeight: 48.0),
padding: const EdgeInsets.all(8.0),
child: Text('None', style: Theme.of(context).textTheme.bodySmall!.copyWith(fontStyle: FontStyle.italic)),
),
),
],
),
);
}
}
class ChipDemo extends StatefulWidget {
const ChipDemo({super.key});
static const String routeName = '/material/chip';
@override
State<ChipDemo> createState() => _ChipDemoState();
}
class _ChipDemoState extends State<ChipDemo> {
_ChipDemoState() {
_reset();
}
final Set<String> _materialsA = <String>{};
final Set<String> _materialsB = <String>{};
String _selectedMaterial = '';
String _selectedAction = '';
final Set<String> _toolsA = <String>{};
final Set<String> _toolsB = <String>{};
final Set<String> _selectedTools = <String>{};
final Set<String> _actions = <String>{};
bool _showShapeBorder = false;
// Initialize members with the default data.
void _reset() {
_materialsA.clear();
_materialsA.addAll(_defaultMaterialsA);
_materialsB.clear();
_materialsB.addAll(_defaultMaterialsB);
_actions.clear();
_actions.addAll(_defaultActions);
_toolsA.clear();
_toolsA.addAll(_defaultToolsA);
_toolsB.clear();
_toolsB.addAll(_defaultToolsB);
_selectedMaterial = '';
_selectedAction = '';
_selectedTools.clear();
}
void _removeMaterial(String name) {
_materialsA.remove(name);
_materialsB.remove(name);
if (_selectedMaterial == name) {
_selectedMaterial = '';
}
}
void _removeTool(String name) {
_toolsA.remove(name);
_toolsB.remove(name);
_selectedTools.remove(name);
}
String _capitalize(String name) {
assert(name.isNotEmpty);
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
// This converts a String to a unique color, based on the hash value of the
// String object. It takes the bottom 16 bits of the hash, and uses that to
// pick a hue for an HSV color, and then creates the color (with a preset
// saturation and value). This means that any unique strings will also have
// unique colors, but they'll all be readable, since they have the same
// saturation and value.
Color _nameToColor(String name, ThemeData theme) {
assert(name.length > 1);
final int hash = name.hashCode & 0xffff;
final double hue = (360.0 * hash / (1 << 15)) % 360.0;
final double themeValue = HSVColor.fromColor(theme.colorScheme.surface).value;
return HSVColor.fromAHSV(1.0, hue, 0.4, themeValue).toColor();
}
AssetImage _nameToAvatar(String name) {
assert(_avatars.containsKey(name));
return AssetImage(
_avatars[name]!,
package: 'flutter_gallery_assets',
);
}
String _createResult() {
if (_selectedAction.isEmpty) {
return '';
}
final String value = _capitalize(_results[_selectedAction]!);
return '$value!';
}
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final List<Widget> chips = _materialsA.map<Widget>((String name) {
return Chip(
key: ValueKey<String>(name),
backgroundColor: _nameToColor(name, theme),
label: Text(_capitalize(name)),
onDeleted: () {
setState(() {
_removeMaterial(name);
});
},
);
}).toList();
final List<Widget> inputChips = _toolsA.map<Widget>((String name) {
return InputChip(
key: ValueKey<String>(name),
avatar: CircleAvatar(
backgroundImage: _nameToAvatar(name),
),
label: Text(_capitalize(name)),
onDeleted: () {
setState(() {
_removeTool(name);
});
});
}).toList();
final List<Widget> choiceChips = _materialsB.map<Widget>((String name) {
return ChoiceChip(
key: ValueKey<String>(name),
backgroundColor: _nameToColor(name, theme),
label: Text(_capitalize(name)),
selected: _selectedMaterial == name,
onSelected: (bool value) {
setState(() {
_selectedMaterial = value ? name : '';
});
},
);
}).toList();
final List<Widget> filterChips = _toolsB.map<Widget>((String name) {
return FilterChip(
key: ValueKey<String>(name),
label: Text(_capitalize(name)),
selected: _toolsB.contains(name) && _selectedTools.contains(name),
onSelected: !_toolsB.contains(name)
? null
: (bool value) {
setState(() {
if (!value) {
_selectedTools.remove(name);
} else {
_selectedTools.add(name);
}
});
},
);
}).toList();
Set<String> allowedActions = <String>{};
if (_selectedMaterial.isNotEmpty) {
for (final String tool in _selectedTools) {
allowedActions.addAll(_toolActions[tool]!);
}
allowedActions = allowedActions.intersection(_materialActions[_selectedMaterial]!);
}
final List<Widget> actionChips = allowedActions.map<Widget>((String name) {
return ActionChip(
label: Text(_capitalize(name)),
onPressed: () {
setState(() {
_selectedAction = name;
});
},
);
}).toList();
final List<Widget> tiles = <Widget>[
const SizedBox(height: 8.0, width: 0.0),
_ChipsTile(label: 'Available Materials (Chip)', children: chips),
_ChipsTile(label: 'Available Tools (InputChip)', children: inputChips),
_ChipsTile(label: 'Choose a Material (ChoiceChip)', children: choiceChips),
_ChipsTile(label: 'Choose Tools (FilterChip)', children: filterChips),
_ChipsTile(label: 'Perform Allowed Action (ActionChip)', children: actionChips),
const Divider(),
Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Text(
_createResult(),
style: theme.textTheme.titleLarge,
),
),
),
];
return Scaffold(
appBar: AppBar(
title: const Text('Chips'),
actions: <Widget>[
MaterialDemoDocumentationButton(ChipDemo.routeName),
IconButton(
onPressed: () {
setState(() {
_showShapeBorder = !_showShapeBorder;
});
},
icon: const Icon(Icons.vignette, semanticLabel: 'Update border shape'),
),
],
),
body: ChipTheme(
data: _showShapeBorder
? theme.chipTheme.copyWith(
shape: BeveledRectangleBorder(
side: const BorderSide(width: 0.66, color: Colors.grey),
borderRadius: BorderRadius.circular(10.0),
))
: theme.chipTheme,
child: Scrollbar(
child: ListView(
primary: true,
children: tiles,
)
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(_reset),
child: const Icon(Icons.refresh, semanticLabel: 'Reset chips'),
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/material/chip_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/chip_demo.dart",
"repo_id": "flutter",
"token_count": 4480
} | 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 'package:flutter/material.dart';
import '../../gallery/demo.dart';
enum IndicatorType { overscroll, refresh }
class OverscrollDemo extends StatefulWidget {
const OverscrollDemo({ super.key });
static const String routeName = '/material/overscroll';
@override
OverscrollDemoState createState() => OverscrollDemoState();
}
class OverscrollDemoState extends State<OverscrollDemo> {
final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey = GlobalKey<RefreshIndicatorState>();
static final List<String> _items = <String>[
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
];
Future<void> _handleRefresh() {
final Completer<void> completer = Completer<void>();
Timer(const Duration(seconds: 3), () => completer.complete());
return completer.future.then((_) {
if (!mounted) {
return;
}
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text('Refresh complete'),
action: SnackBarAction(
label: 'RETRY',
onPressed: () {
_refreshIndicatorKey.currentState!.show();
},
),
));
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Pull to refresh'),
actions: <Widget>[
MaterialDemoDocumentationButton(OverscrollDemo.routeName),
IconButton(
icon: const Icon(Icons.refresh),
tooltip: 'Refresh',
onPressed: () {
_refreshIndicatorKey.currentState!.show();
},
),
],
),
body: RefreshIndicator(
key: _refreshIndicatorKey,
onRefresh: _handleRefresh,
child: Scrollbar(
child: ListView.builder(
primary: true,
padding: kMaterialListPadding,
itemCount: _items.length,
itemBuilder: (BuildContext context, int index) {
final String item = _items[index];
return ListTile(
isThreeLine: true,
leading: CircleAvatar(child: Text(item)),
title: Text('This item represents $item.'),
subtitle: const Text('Even more additional list item information appears on line three.'),
);
},
),
),
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/material/overscroll_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/overscroll_demo.dart",
"repo_id": "flutter",
"token_count": 1119
} | 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 'package:flutter/material.dart';
import 'login.dart';
const Cubic _kAccelerateCurve = Cubic(0.548, 0.0, 0.757, 0.464);
const Cubic _kDecelerateCurve = Cubic(0.23, 0.94, 0.41, 1.0);
const double _kPeakVelocityTime = 0.248210;
const double _kPeakVelocityProgress = 0.379146;
class _TappableWhileStatusIs extends StatefulWidget {
const _TappableWhileStatusIs(
this.status, {
this.controller,
this.child,
});
final AnimationController? controller;
final AnimationStatus status;
final Widget? child;
@override
_TappableWhileStatusIsState createState() => _TappableWhileStatusIsState();
}
class _TappableWhileStatusIsState extends State<_TappableWhileStatusIs> {
bool? _active;
@override
void initState() {
super.initState();
widget.controller!.addStatusListener(_handleStatusChange);
_active = widget.controller!.status == widget.status;
}
@override
void dispose() {
widget.controller!.removeStatusListener(_handleStatusChange);
super.dispose();
}
void _handleStatusChange(AnimationStatus status) {
final bool value = widget.controller!.status == widget.status;
if (_active != value) {
setState(() {
_active = value;
});
}
}
@override
Widget build(BuildContext context) {
Widget child = AbsorbPointer(
absorbing: !_active!,
child: widget.child,
);
if (!_active!) {
child = FocusScope(
canRequestFocus: false,
debugLabel: '$_TappableWhileStatusIs',
child: child,
);
}
return child;
}
}
class _FrontLayer extends StatelessWidget {
const _FrontLayer({
this.onTap,
this.child,
});
final VoidCallback? onTap;
final Widget? child;
@override
Widget build(BuildContext context) {
return Material(
elevation: 16.0,
shape: const BeveledRectangleBorder(
borderRadius: BorderRadius.only(topLeft: Radius.circular(46.0)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: Container(
height: 40.0,
alignment: AlignmentDirectional.centerStart,
),
),
Expanded(
child: child!,
),
],
),
);
}
}
class _BackdropTitle extends AnimatedWidget {
const _BackdropTitle({
required Animation<double> super.listenable,
this.onPress,
required this.frontTitle,
required this.backTitle,
});
final void Function()? onPress;
final Widget frontTitle;
final Widget backTitle;
@override
Widget build(BuildContext context) {
final Animation<double> animation = CurvedAnimation(
parent: listenable as Animation<double>,
curve: const Interval(0.0, 0.78),
);
return DefaultTextStyle(
style: Theme.of(context).primaryTextTheme.titleLarge!,
softWrap: false,
overflow: TextOverflow.ellipsis,
child: Row(children: <Widget>[
// branded icon
SizedBox(
width: 72.0,
child: IconButton(
padding: const EdgeInsets.only(right: 8.0),
onPressed: onPress,
icon: Stack(children: <Widget>[
Opacity(
opacity: animation.value,
child: const ImageIcon(AssetImage('packages/shrine_images/slanted_menu.png')),
),
FractionalTranslation(
translation: Tween<Offset>(
begin: Offset.zero,
end: const Offset(1.0, 0.0),
).evaluate(animation),
child: const ImageIcon(AssetImage('packages/shrine_images/diamond.png')),
),
]),
),
),
// Here, we do a custom cross fade between backTitle and frontTitle.
// This makes a smooth animation between the two texts.
Stack(
children: <Widget>[
Opacity(
opacity: CurvedAnimation(
parent: ReverseAnimation(animation),
curve: const Interval(0.5, 1.0),
).value,
child: FractionalTranslation(
translation: Tween<Offset>(
begin: Offset.zero,
end: const Offset(0.5, 0.0),
).evaluate(animation),
child: backTitle,
),
),
Opacity(
opacity: CurvedAnimation(
parent: animation,
curve: const Interval(0.5, 1.0),
).value,
child: FractionalTranslation(
translation: Tween<Offset>(
begin: const Offset(-0.25, 0.0),
end: Offset.zero,
).evaluate(animation),
child: frontTitle,
),
),
],
),
]),
);
}
}
/// Builds a Backdrop.
///
/// A Backdrop widget has two layers, front and back. The front layer is shown
/// by default, and slides down to show the back layer, from which a user
/// can make a selection. The user can also configure the titles for when the
/// front or back layer is showing.
class Backdrop extends StatefulWidget {
const Backdrop({
super.key,
required this.frontLayer,
required this.backLayer,
required this.frontTitle,
required this.backTitle,
required this.controller,
});
final Widget frontLayer;
final Widget backLayer;
final Widget frontTitle;
final Widget backTitle;
final AnimationController controller;
@override
State<Backdrop> createState() => _BackdropState();
}
class _BackdropState extends State<Backdrop> with SingleTickerProviderStateMixin {
final GlobalKey _backdropKey = GlobalKey(debugLabel: 'Backdrop');
AnimationController? _controller;
late Animation<RelativeRect> _layerAnimation;
@override
void initState() {
super.initState();
_controller = widget.controller;
}
@override
void dispose() {
_controller!.dispose();
super.dispose();
}
bool get _frontLayerVisible {
final AnimationStatus status = _controller!.status;
return status == AnimationStatus.completed || status == AnimationStatus.forward;
}
void _toggleBackdropLayerVisibility() {
// Call setState here to update layerAnimation if that's necessary
setState(() {
_frontLayerVisible ? _controller!.reverse() : _controller!.forward();
});
}
// _layerAnimation animates the front layer between open and close.
// _getLayerAnimation adjusts the values in the TweenSequence so the
// curve and timing are correct in both directions.
Animation<RelativeRect> _getLayerAnimation(Size layerSize, double layerTop) {
Curve firstCurve; // Curve for first TweenSequenceItem
Curve secondCurve; // Curve for second TweenSequenceItem
double firstWeight; // Weight of first TweenSequenceItem
double secondWeight; // Weight of second TweenSequenceItem
Animation<double> animation; // Animation on which TweenSequence runs
if (_frontLayerVisible) {
firstCurve = _kAccelerateCurve;
secondCurve = _kDecelerateCurve;
firstWeight = _kPeakVelocityTime;
secondWeight = 1.0 - _kPeakVelocityTime;
animation = CurvedAnimation(
parent: _controller!.view,
curve: const Interval(0.0, 0.78),
);
} else {
// These values are only used when the controller runs from t=1.0 to t=0.0
firstCurve = _kDecelerateCurve.flipped;
secondCurve = _kAccelerateCurve.flipped;
firstWeight = 1.0 - _kPeakVelocityTime;
secondWeight = _kPeakVelocityTime;
animation = _controller!.view;
}
return TweenSequence<RelativeRect>(
<TweenSequenceItem<RelativeRect>>[
TweenSequenceItem<RelativeRect>(
tween: RelativeRectTween(
begin: RelativeRect.fromLTRB(
0.0,
layerTop,
0.0,
layerTop - layerSize.height,
),
end: RelativeRect.fromLTRB(
0.0,
layerTop * _kPeakVelocityProgress,
0.0,
(layerTop - layerSize.height) * _kPeakVelocityProgress,
),
).chain(CurveTween(curve: firstCurve)),
weight: firstWeight,
),
TweenSequenceItem<RelativeRect>(
tween: RelativeRectTween(
begin: RelativeRect.fromLTRB(
0.0,
layerTop * _kPeakVelocityProgress,
0.0,
(layerTop - layerSize.height) * _kPeakVelocityProgress,
),
end: RelativeRect.fill,
).chain(CurveTween(curve: secondCurve)),
weight: secondWeight,
),
],
).animate(animation);
}
Widget _buildStack(BuildContext context, BoxConstraints constraints) {
const double layerTitleHeight = 48.0;
final Size layerSize = constraints.biggest;
final double layerTop = layerSize.height - layerTitleHeight;
_layerAnimation = _getLayerAnimation(layerSize, layerTop);
return Stack(
key: _backdropKey,
children: <Widget>[
_TappableWhileStatusIs(
AnimationStatus.dismissed,
controller: _controller,
child: widget.backLayer,
),
PositionedTransition(
rect: _layerAnimation,
child: _FrontLayer(
onTap: _toggleBackdropLayerVisibility,
child: _TappableWhileStatusIs(
AnimationStatus.completed,
controller: _controller,
child: widget.frontLayer,
),
),
),
],
);
}
@override
Widget build(BuildContext context) {
final AppBar appBar = AppBar(
elevation: 0.0,
titleSpacing: 0.0,
title: _BackdropTitle(
listenable: _controller!.view,
onPress: _toggleBackdropLayerVisibility,
frontTitle: widget.frontTitle,
backTitle: widget.backTitle,
),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.search, semanticLabel: 'login'),
onPressed: () {
Navigator.push<void>(
context,
MaterialPageRoute<void>(builder: (BuildContext context) => const LoginPage()),
);
},
),
IconButton(
icon: const Icon(Icons.tune, semanticLabel: 'login'),
onPressed: () {
Navigator.push<void>(
context,
MaterialPageRoute<void>(builder: (BuildContext context) => const LoginPage()),
);
},
),
],
);
return Scaffold(
appBar: appBar,
body: LayoutBuilder(
builder: _buildStack,
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/backdrop.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/backdrop.dart",
"repo_id": "flutter",
"token_count": 4771
} | 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 'package:flutter/material.dart';
abstract final class GalleryIcons {
static const IconData tooltip = IconData(0xe900, fontFamily: 'GalleryIcons');
static const IconData text_fields_alt = IconData(0xe901, fontFamily: 'GalleryIcons');
static const IconData tabs = IconData(0xe902, fontFamily: 'GalleryIcons');
static const IconData switches = IconData(0xe903, fontFamily: 'GalleryIcons');
static const IconData sliders = IconData(0xe904, fontFamily: 'GalleryIcons');
static const IconData shrine = IconData(0xe905, fontFamily: 'GalleryIcons');
static const IconData sentiment_very_satisfied = IconData(0xe906, fontFamily: 'GalleryIcons');
static const IconData refresh = IconData(0xe907, fontFamily: 'GalleryIcons');
static const IconData progress_activity = IconData(0xe908, fontFamily: 'GalleryIcons');
static const IconData phone_iphone = IconData(0xe909, fontFamily: 'GalleryIcons');
static const IconData page_control = IconData(0xe90a, fontFamily: 'GalleryIcons');
static const IconData more_vert = IconData(0xe90b, fontFamily: 'GalleryIcons');
static const IconData menu = IconData(0xe90c, fontFamily: 'GalleryIcons');
static const IconData list_alt = IconData(0xe90d, fontFamily: 'GalleryIcons');
static const IconData grid_on = IconData(0xe90e, fontFamily: 'GalleryIcons');
static const IconData expand_all = IconData(0xe90f, fontFamily: 'GalleryIcons');
static const IconData event = IconData(0xe910, fontFamily: 'GalleryIcons');
static const IconData drive_video = IconData(0xe911, fontFamily: 'GalleryIcons');
static const IconData dialogs = IconData(0xe912, fontFamily: 'GalleryIcons');
static const IconData data_table = IconData(0xe913, fontFamily: 'GalleryIcons');
static const IconData custom_typography = IconData(0xe914, fontFamily: 'GalleryIcons');
static const IconData colors = IconData(0xe915, fontFamily: 'GalleryIcons');
static const IconData chips = IconData(0xe916, fontFamily: 'GalleryIcons');
static const IconData check_box = IconData(0xe917, fontFamily: 'GalleryIcons');
static const IconData cards = IconData(0xe918, fontFamily: 'GalleryIcons');
static const IconData buttons = IconData(0xe919, fontFamily: 'GalleryIcons');
static const IconData bottom_sheets = IconData(0xe91a, fontFamily: 'GalleryIcons');
static const IconData bottom_navigation = IconData(0xe91b, fontFamily: 'GalleryIcons');
static const IconData animation = IconData(0xe91c, fontFamily: 'GalleryIcons');
static const IconData account_box = IconData(0xe91d, fontFamily: 'GalleryIcons');
static const IconData snackbar = IconData(0xe91e, fontFamily: 'GalleryIcons');
static const IconData category_mdc = IconData(0xe91f, fontFamily: 'GalleryIcons');
static const IconData cupertino_progress = IconData(0xe920, fontFamily: 'GalleryIcons');
static const IconData cupertino_pull_to_refresh = IconData(0xe921, fontFamily: 'GalleryIcons');
static const IconData cupertino_switch = IconData(0xe922, fontFamily: 'GalleryIcons');
static const IconData generic_buttons = IconData(0xe923, fontFamily: 'GalleryIcons');
static const IconData backdrop = IconData(0xe924, fontFamily: 'GalleryIcons');
static const IconData bottom_app_bar = IconData(0xe925, fontFamily: 'GalleryIcons');
static const IconData bottom_sheet_persistent = IconData(0xe926, fontFamily: 'GalleryIcons');
static const IconData lists_leave_behind = IconData(0xe927, fontFamily: 'GalleryIcons');
}
| flutter/dev/integration_tests/flutter_gallery/lib/gallery/icons.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/gallery/icons.dart",
"repo_id": "flutter",
"token_count": 1097
} | 516 |
// 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/buttons_demo.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Button locations are OK', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/pull/85351
{
await tester.pumpWidget(MaterialApp(theme: ThemeData(useMaterial3: false), home: const ButtonsDemo()));
expect(find.byType(ElevatedButton).evaluate().length, 2);
final Offset topLeft1 = tester.getTopLeft(find.byType(ElevatedButton).first);
final Offset topLeft2 = tester.getTopLeft(find.byType(ElevatedButton).last);
expect(topLeft1.dx, 203);
expect(topLeft2.dx, 453);
expect(topLeft1.dy, topLeft2.dy);
}
{
await tester.tap(find.text('TEXT'));
await tester.pumpAndSettle();
expect(find.byType(TextButton).evaluate().length, 2);
final Offset topLeft1 = tester.getTopLeft(find.byType(TextButton).first);
final Offset topLeft2 = tester.getTopLeft(find.byType(TextButton).last);
expect(topLeft1.dx, 247);
expect(topLeft2.dx, 425);
expect(topLeft1.dy, topLeft2.dy);
}
{
await tester.tap(find.text('OUTLINED'));
await tester.pumpAndSettle();
expect(find.byType(OutlinedButton).evaluate().length, 2);
final Offset topLeft1 = tester.getTopLeft(find.byType(OutlinedButton).first);
final Offset topLeft2 = tester.getTopLeft(find.byType(OutlinedButton).last);
expect(topLeft1.dx, 203);
expect(topLeft2.dx, 453);
expect(topLeft1.dy, topLeft2.dy);
}
});
}
| flutter/dev/integration_tests/flutter_gallery/test/demo/material/buttons_demo_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/test/demo/material/buttons_demo_test.dart",
"repo_id": "flutter",
"token_count": 706
} | 517 |
// 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('page transition performance test', () {
late FlutterDriver driver;
setUpAll(() async {
driver = await FlutterDriver.connect();
await driver.waitUntilFirstFrameRasterized();
});
tearDownAll(() async {
driver.close();
});
test('measure', () async {
final Timeline timeline = await driver.traceAction(() async {
await driver.tap(find.text('Material'));
for (int i = 0; i < 10; i++) {
await driver.tap(find.text('Banner'));
await Future<void>.delayed(const Duration(milliseconds: 500));
await driver.waitFor(find.byTooltip('Back'));
await driver.tap(find.byTooltip('Back'));
await Future<void>.delayed(const Duration(milliseconds: 500));
}
}, retainPriorEvents: true);
final TimelineSummary summary = TimelineSummary.summarize(timeline);
await summary.writeTimelineToFile('page_transition_perf', pretty: true);
}, timeout: Timeout.none);
});
}
| flutter/dev/integration_tests/flutter_gallery/test_driver/page_transitions_perf_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/test_driver/page_transitions_perf_test.dart",
"repo_id": "flutter",
"token_count": 470
} | 518 |
#!/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.
set -e
if [ ! -f "./pubspec.yaml" ]; then
echo "ERROR: current directory must be the root of flutter_gallery package"
exit 1
fi
cd android
# Currently there's no non-hacky way to pass a device ID to gradlew, but it's
# OK as in the devicelab we have one device per host.
#
# See also: https://goo.gl/oe5aUW
./gradlew connectedAndroidTest -Ptarget=test/live_smoketest.dart
| flutter/dev/integration_tests/flutter_gallery/tool/run_instrumentation_test.sh/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/tool/run_instrumentation_test.sh",
"repo_id": "flutter",
"token_count": 184
} | 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.
// This is the `settings.gradle` file that apps were created with until Flutter
// v1.22.0. This file has changed, so it must be migrated in existing projects.
include ':app'
def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
def properties = new Properties()
def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
if (pluginsFile.exists()) {
pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
}
plugins.each { name, path ->
def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
include ":$name"
project(":$name").projectDir = pluginDirectory
}
| flutter/dev/integration_tests/gradle_deprecated_settings/android/settings.gradle/0 | {
"file_path": "flutter/dev/integration_tests/gradle_deprecated_settings/android/settings.gradle",
"repo_id": "flutter",
"token_count": 269
} | 520 |
#!/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.
set -e
cd "$(dirname "$0")"
pushd flutterapp
../../../../bin/flutter build ios --debug --simulator --no-codesign
popd
pod install
xcrun xcodebuild \
-workspace ios_add2app.xcworkspace \
-scheme ios_add2app \
-sdk "iphonesimulator" \
-destination "OS=latest,name=iPhone 12" test
| flutter/dev/integration_tests/ios_add2app_life_cycle/build_and_test.sh/0 | {
"file_path": "flutter/dev/integration_tests/ios_add2app_life_cycle/build_and_test.sh",
"repo_id": "flutter",
"token_count": 166
} | 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 "AppDelegate.h"
#import "MainViewController.h"
@interface AppDelegate ()
@end
static NSString *_kReloadChannelName = @"reload";
@implementation AppDelegate {
MainViewController *_mainViewController;
UINavigationController *_navigationController;
FlutterEngine *_engine;
FlutterBasicMessageChannel *_reloadMessageChannel;
}
- (FlutterEngine *)engine {
return _engine;
}
- (FlutterBasicMessageChannel *)reloadMessageChannel {
return _reloadMessageChannel;
}
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
_mainViewController = [[MainViewController alloc] init];
_navigationController = [[UINavigationController alloc]
initWithRootViewController:_mainViewController];
_navigationController.navigationBar.translucent = NO;
_engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
[_engine runWithEntrypoint:nil];
_reloadMessageChannel = [[FlutterBasicMessageChannel alloc]
initWithName:_kReloadChannelName
binaryMessenger:_engine.binaryMessenger
codec:[FlutterStringCodec sharedInstance]];
self.window.rootViewController = _navigationController;
[self.window makeKeyAndVisible];
return YES;
}
@end
| flutter/dev/integration_tests/ios_host_app/Host/AppDelegate.m/0 | {
"file_path": "flutter/dev/integration_tests/ios_host_app/Host/AppDelegate.m",
"repo_id": "flutter",
"token_count": 466
} | 522 |
platform :ios, '12.0'
flutter_application_path = '../hello'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
target 'Host' do
install_all_flutter_pods flutter_application_path
end
target 'FlutterUITests' do
inherit! :search_paths
end
| flutter/dev/integration_tests/ios_host_app/Podfile/0 | {
"file_path": "flutter/dev/integration_tests/ios_host_app/Podfile",
"repo_id": "flutter",
"token_count": 98
} | 523 |
// 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.
// Only put constants shared between files here.
import 'dart:typed_data';
// Height of the 'Gallery' header
const double galleryHeaderHeight = 64;
// The font size delta for headline4 font.
const double desktopDisplay1FontDelta = 16;
// The width of the settingsDesktop.
const double desktopSettingsWidth = 520;
// Sentinel value for the system text scale factor option.
const double systemTextScaleFactorOption = -1;
// The splash page animation duration.
const Duration splashPageAnimationDuration = Duration(milliseconds: 300);
// Half the splash page animation duration.
const Duration halfSplashPageAnimationDuration = Duration(milliseconds: 150);
// Duration for settings panel to open on mobile.
const Duration settingsPanelMobileAnimationDuration =
Duration(milliseconds: 200);
// Duration for settings panel to open on desktop.
const Duration settingsPanelDesktopAnimationDuration =
Duration(milliseconds: 600);
// Duration for home page elements to fade in.
const Duration entranceAnimationDuration = Duration(milliseconds: 200);
// The desktop top padding for a page's first header (e.g. Gallery, Settings)
const double firstHeaderDesktopTopPadding = 5.0;
// A transparent image used to avoid loading images when they are not needed.
final Uint8List kTransparentImage = Uint8List.fromList(<int>[
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49,
0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06,
0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x06, 0x62, 0x4B,
0x47, 0x44, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xA0, 0xBD, 0xA7, 0x93, 0x00,
0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0B, 0x13, 0x00, 0x00,
0x0B, 0x13, 0x01, 0x00, 0x9A, 0x9C, 0x18, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49,
0x4D, 0x45, 0x07, 0xE6, 0x03, 0x10, 0x17, 0x07, 0x1D, 0x2E, 0x5E, 0x30, 0x9B,
0x00, 0x00, 0x00, 0x0B, 0x49, 0x44, 0x41, 0x54, 0x08, 0xD7, 0x63, 0x60, 0x00,
0x02, 0x00, 0x00, 0x05, 0x00, 0x01, 0xE2, 0x26, 0x05, 0x9B, 0x00, 0x00, 0x00,
0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
]);
| flutter/dev/integration_tests/new_gallery/lib/constants.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/constants.dart",
"repo_id": "flutter",
"token_count": 923
} | 524 |
// 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 cupertinoSwitchDemo
class CupertinoSwitchDemo extends StatefulWidget {
const CupertinoSwitchDemo({super.key});
@override
State<CupertinoSwitchDemo> createState() => _CupertinoSwitchDemoState();
}
class _CupertinoSwitchDemoState extends State<CupertinoSwitchDemo>
with RestorationMixin {
final RestorableBool _switchValueA = RestorableBool(false);
final RestorableBool _switchValueB = RestorableBool(true);
@override
String get restorationId => 'cupertino_switch_demo';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_switchValueA, 'switch_valueA');
registerForRestoration(_switchValueB, 'switch_valueB');
}
@override
Widget build(BuildContext context) {
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
automaticallyImplyLeading: false,
middle: Text(
localizations.demoSelectionControlsSwitchTitle,
),
),
child: Center(
child: Semantics(
container: true,
label: localizations.demoSelectionControlsSwitchTitle,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CupertinoSwitch(
value: _switchValueA.value,
onChanged: (bool value) {
setState(() {
_switchValueA.value = value;
});
},
),
CupertinoSwitch(
value: _switchValueB.value,
onChanged: (bool value) {
setState(() {
_switchValueB.value = value;
});
},
),
],
),
// Disabled switches
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CupertinoSwitch(
value: _switchValueA.value,
onChanged: null,
),
CupertinoSwitch(
value: _switchValueB.value,
onChanged: null,
),
],
),
],
),
),
),
);
}
}
// END
| flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_switch_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_switch_demo.dart",
"repo_id": "flutter",
"token_count": 1413
} | 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_localizations.dart';
import 'material_demo_types.dart';
// BEGIN listDemo
class ListDemo extends StatelessWidget {
const ListDemo({super.key, required this.type});
final ListDemoType type;
@override
Widget build(BuildContext context) {
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(localizations.demoListsTitle),
),
body: Scrollbar(
child: ListView(
restorationId: 'list_demo_list_view',
padding: const EdgeInsets.symmetric(vertical: 8),
children: <Widget>[
for (int index = 1; index < 21; index++)
ListTile(
leading: ExcludeSemantics(
child: CircleAvatar(child: Text('$index')),
),
title: Text(
localizations.demoBottomSheetItem(index),
),
subtitle: type == ListDemoType.twoLine
? Text(localizations.demoListsSecondary)
: null,
),
],
),
),
);
}
}
// END
| flutter/dev/integration_tests/new_gallery/lib/demos/material/list_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/material/list_demo.dart",
"repo_id": "flutter",
"token_count": 635
} | 526 |
{
"githubRepo": "{repoName} GitHub repository",
"@githubRepo": {
"description": "Represents a link to a GitHub repository.",
"placeholders": {
"repoName": {
"example": "Flutter Gallery"
}
}
},
"aboutDialogDescription": "To see the source code for this app, please visit the {repoLink}.",
"@aboutDialogDescription": {
"description": "A description about how to view the source code for this app.",
"placeholders": {
"repoLink": {
"example": "Flutter Gallery GitHub repository"
}
}
},
"deselect": "Deselect",
"@deselect": {
"description": "Deselect a (selectable) item"
},
"notSelected": "Not selected",
"@notSelected": {
"description": "Indicates the status of a (selectable) item not being selected"
},
"select": "Select",
"@select": {
"description": "Select a (selectable) item"
},
"selectable": "Selectable (long press)",
"@selectable": {
"description": "Indicates the associated piece of UI is selectable by long pressing it"
},
"selected": "Selected",
"@selected": {
"description": "Indicates status of a (selectable) item being selected"
},
"signIn": "SIGN IN",
"@signIn": {
"description": "Sign in label to sign into website."
},
"bannerDemoText": "Your password was updated on your other device. Please sign in again.",
"@bannerDemoText": {
"description": "Password was updated on a different device and the user is required to sign in again"
},
"bannerDemoResetText": "Reset the banner",
"@bannerDemoResetText": {
"description": "Show the Banner to the user again."
},
"bannerDemoMultipleText": "Multiple actions",
"@bannerDemoMultipleText": {
"description": "When the user clicks this button the Banner will toggle multiple actions or a single action"
},
"bannerDemoLeadingText": "Leading Icon",
"@bannerDemoLeadingText": {
"description": "If user clicks this button the leading icon in the Banner will disappear"
},
"dismiss": "DISMISS",
"@dismiss": {
"description": "When text is pressed the banner widget will be removed from the screen."
},
"backToGallery": "Back to Gallery",
"@backToGallery": {
"description": "Semantic label for back button to exit a study and return to the gallery home page."
},
"cardsDemoExplore": "Explore",
"@cardsDemoExplore": {
"description": "Click to see more about the content in the cards demo."
},
"cardsDemoExploreSemantics": "Explore {destinationName}",
"@cardsDemoExploreSemantics": {
"description": "Semantics label for Explore. Label tells user to explore the destinationName to the user. Example Explore Tamil",
"placeholders": {
"destinationName": {
"example": "Tamil"
}
}
},
"cardsDemoShareSemantics": "Share {destinationName}",
"@cardsDemoShareSemantics": {
"description": "Semantics label for Share. Label tells user to share the destinationName to the user. Example Share Tamil",
"placeholders": {
"destinationName": {
"example": "Tamil"
}
}
},
"cardsDemoTappable": "Tappable",
"@cardsDemoTappable": {
"description": "The user can tap this button"
},
"cardsDemoTravelDestinationTitle1": "Top 10 Cities to Visit in Tamil Nadu",
"@cardsDemoTravelDestinationTitle1": {
"description": "The top 10 cities that you can visit in Tamil Nadu"
},
"cardsDemoTravelDestinationDescription1": "Number 10",
"@cardsDemoTravelDestinationDescription1": {
"description": "Number 10"
},
"cardsDemoTravelDestinationCity1": "Thanjavur",
"@cardsDemoTravelDestinationCity1": {
"description": "Thanjavur the city"
},
"cardsDemoTravelDestinationLocation1": "Thanjavur, Tamil Nadu",
"@cardsDemoTravelDestinationLocation1": {
"description": "Thanjavur, Tamil Nadu is a location"
},
"cardsDemoTravelDestinationTitle2": "Artisans of Southern India",
"@cardsDemoTravelDestinationTitle2": {
"description": "Artist that are from Southern India"
},
"cardsDemoTravelDestinationDescription2": "Silk Spinners",
"@cardsDemoTravelDestinationDescription2": {
"description": "Silk Spinners"
},
"cardsDemoTravelDestinationCity2": "Chettinad",
"@cardsDemoTravelDestinationCity2": {
"description": "Chettinad the city"
},
"cardsDemoTravelDestinationLocation2": "Sivaganga, Tamil Nadu",
"@cardsDemoTravelDestinationLocation2": {
"description": "Sivaganga, Tamil Nadu is a location"
},
"cardsDemoTravelDestinationTitle3": "Brihadisvara Temple",
"@cardsDemoTravelDestinationTitle3": {
"description": "Brihadisvara Temple"
},
"cardsDemoTravelDestinationDescription3": "Temples",
"@cardsDemoTravelDestinationDescription3": {
"description": "Temples"
},
"homeHeaderGallery": "Gallery",
"@homeHeaderGallery": {
"description": "Header title on home screen for Gallery section."
},
"homeHeaderCategories": "Categories",
"@homeHeaderCategories": {
"description": "Header title on home screen for Categories section."
},
"shrineDescription": "A fashionable retail app",
"@shrineDescription": {
"description": "Study description for Shrine."
},
"fortnightlyDescription": "A content-focused news app",
"@fortnightlyDescription": {
"description": "Study description for Fortnightly."
},
"rallyDescription": "A personal finance app",
"@rallyDescription": {
"description": "Study description for Rally."
},
"replyDescription": "An efficient, focused email app",
"@replyDescription": {
"description": "Study description for Reply."
},
"rallyAccountDataChecking": "Checking",
"@rallyAccountDataChecking": {
"description": "Name for account made up by user."
},
"rallyAccountDataHomeSavings": "Home Savings",
"@rallyAccountDataHomeSavings": {
"description": "Name for account made up by user."
},
"rallyAccountDataCarSavings": "Car Savings",
"@rallyAccountDataCarSavings": {
"description": "Name for account made up by user."
},
"rallyAccountDataVacation": "Vacation",
"@rallyAccountDataVacation": {
"description": "Name for account made up by user."
},
"rallyAccountDetailDataAnnualPercentageYield": "Annual Percentage Yield",
"@rallyAccountDetailDataAnnualPercentageYield": {
"description": "Title for account statistics. Below a percentage such as 0.10% will be displayed."
},
"rallyAccountDetailDataInterestRate": "Interest Rate",
"@rallyAccountDetailDataInterestRate": {
"description": "Title for account statistics. Below a dollar amount such as $100 will be displayed."
},
"rallyAccountDetailDataInterestYtd": "Interest YTD",
"@rallyAccountDetailDataInterestYtd": {
"description": "Title for account statistics. Below a dollar amount such as $100 will be displayed."
},
"rallyAccountDetailDataInterestPaidLastYear": "Interest Paid Last Year",
"@rallyAccountDetailDataInterestPaidLastYear": {
"description": "Title for account statistics. Below a dollar amount such as $100 will be displayed."
},
"rallyAccountDetailDataNextStatement": "Next Statement",
"@rallyAccountDetailDataNextStatement": {
"description": "Title for an account detail. Below a date for when the next account statement is released."
},
"rallyAccountDetailDataAccountOwner": "Account Owner",
"@rallyAccountDetailDataAccountOwner": {
"description": "Title for an account detail. Below the name of the account owner will be displayed."
},
"rallyBillDetailTotalAmount": "Total Amount",
"@rallyBillDetailTotalAmount": {
"description": "Title for column where it displays the total dollar amount that the user has in bills."
},
"rallyBillDetailAmountPaid": "Amount Paid",
"@rallyBillDetailAmountPaid": {
"description": "Title for column where it displays the amount that the user has paid."
},
"rallyBillDetailAmountDue": "Amount Due",
"@rallyBillDetailAmountDue": {
"description": "Title for column where it displays the amount that the user has due."
},
"rallyBudgetCategoryCoffeeShops": "Coffee Shops",
"@rallyBudgetCategoryCoffeeShops": {
"description": "Category for budget, to sort expenses / bills in."
},
"rallyBudgetCategoryGroceries": "Groceries",
"@rallyBudgetCategoryGroceries": {
"description": "Category for budget, to sort expenses / bills in."
},
"rallyBudgetCategoryRestaurants": "Restaurants",
"@rallyBudgetCategoryRestaurants": {
"description": "Category for budget, to sort expenses / bills in."
},
"rallyBudgetCategoryClothing": "Clothing",
"@rallyBudgetCategoryClothing": {
"description": "Category for budget, to sort expenses / bills in."
},
"rallyBudgetDetailTotalCap": "Total Cap",
"@rallyBudgetDetailTotalCap": {
"description": "Title for column where it displays the total dollar cap that the user has for its budget."
},
"rallyBudgetDetailAmountUsed": "Amount Used",
"@rallyBudgetDetailAmountUsed": {
"description": "Title for column where it displays the dollar amount that the user has used in its budget."
},
"rallyBudgetDetailAmountLeft": "Amount Left",
"@rallyBudgetDetailAmountLeft": {
"description": "Title for column where it displays the dollar amount that the user has left in its budget."
},
"rallySettingsManageAccounts": "Manage Accounts",
"@rallySettingsManageAccounts": {
"description": "Link to go to the page 'Manage Accounts."
},
"rallySettingsTaxDocuments": "Tax Documents",
"@rallySettingsTaxDocuments": {
"description": "Link to go to the page 'Tax Documents'."
},
"rallySettingsPasscodeAndTouchId": "Passcode and Touch ID",
"@rallySettingsPasscodeAndTouchId": {
"description": "Link to go to the page 'Passcode and Touch ID'."
},
"rallySettingsNotifications": "Notifications",
"@rallySettingsNotifications": {
"description": "Link to go to the page 'Notifications'."
},
"rallySettingsPersonalInformation": "Personal Information",
"@rallySettingsPersonalInformation": {
"description": "Link to go to the page 'Personal Information'."
},
"rallySettingsPaperlessSettings": "Paperless Settings",
"@rallySettingsPaperlessSettings": {
"description": "Link to go to the page 'Paperless Settings'."
},
"rallySettingsFindAtms": "Find ATMs",
"@rallySettingsFindAtms": {
"description": "Link to go to the page 'Find ATMs'."
},
"rallySettingsHelp": "Help",
"@rallySettingsHelp": {
"description": "Link to go to the page 'Help'."
},
"rallySettingsSignOut": "Sign out",
"@rallySettingsSignOut": {
"description": "Link to go to the page 'Sign out'."
},
"rallyAccountTotal": "Total",
"@rallyAccountTotal": {
"description": "Title for 'total account value' overview page, a dollar value is displayed next to it."
},
"rallyBillsDue": "Due",
"@rallyBillsDue": {
"description": "Title for 'bills due' page, a dollar value is displayed next to it."
},
"rallyBudgetLeft": "Left",
"@rallyBudgetLeft": {
"description": "Title for 'budget left' page, a dollar value is displayed next to it."
},
"rallyAccounts": "Accounts",
"@rallyAccounts": {
"description": "Link text for accounts page."
},
"rallyBills": "Bills",
"@rallyBills": {
"description": "Link text for bills page."
},
"rallyBudgets": "Budgets",
"@rallyBudgets": {
"description": "Link text for budgets page."
},
"rallyAlerts": "Alerts",
"@rallyAlerts": {
"description": "Title for alerts part of overview page."
},
"rallySeeAll": "SEE ALL",
"@rallySeeAll": {
"description": "Link text for button to see all data for category."
},
"rallyFinanceLeft": " LEFT",
"@rallyFinanceLeft": {
"description": "Displayed as 'dollar amount left', for example $46.70 LEFT, for a budget category."
},
"rallyTitleOverview": "OVERVIEW",
"@rallyTitleOverview": {
"description": "The navigation link to the overview page."
},
"rallyTitleAccounts": "ACCOUNTS",
"@rallyTitleAccounts": {
"description": "The navigation link to the accounts page."
},
"rallyTitleBills": "BILLS",
"@rallyTitleBills": {
"description": "The navigation link to the bills page."
},
"rallyTitleBudgets": "BUDGETS",
"@rallyTitleBudgets": {
"description": "The navigation link to the budgets page."
},
"rallyTitleSettings": "SETTINGS",
"@rallyTitleSettings": {
"description": "The navigation link to the settings page."
},
"rallyLoginLoginToRally": "Login to Rally",
"@rallyLoginLoginToRally": {
"description": "Title for login page for the Rally app (Rally does not need to be translated as it is a product name)."
},
"rallyLoginNoAccount": "Don't have an account?",
"@rallyLoginNoAccount": {
"description": "Prompt for signing up for an account."
},
"rallyLoginSignUp": "SIGN UP",
"@rallyLoginSignUp": {
"description": "Button text to sign up for an account."
},
"rallyLoginUsername": "Username",
"@rallyLoginUsername": {
"description": "The username field in an login form."
},
"rallyLoginPassword": "Password",
"@rallyLoginPassword": {
"description": "The password field in an login form."
},
"rallyLoginLabelLogin": "Login",
"@rallyLoginLabelLogin": {
"description": "The label text to login."
},
"rallyLoginRememberMe": "Remember Me",
"@rallyLoginRememberMe": {
"description": "Text if the user wants to stay logged in."
},
"rallyLoginButtonLogin": "LOGIN",
"@rallyLoginButtonLogin": {
"description": "Text for login button."
},
"rallyAlertsMessageHeadsUpShopping": "Heads up, you've used up {percent} of your Shopping budget for this month.",
"@rallyAlertsMessageHeadsUpShopping": {
"description": "Alert message shown when for example, user has used more than 90% of their shopping budget.",
"placeholders": {
"percent": {
"example": "90%"
}
}
},
"rallyAlertsMessageSpentOnRestaurants": "You've spent {amount} on Restaurants this week.",
"@rallyAlertsMessageSpentOnRestaurants": {
"description": "Alert message shown when for example, user has spent $120 on Restaurants this week.",
"placeholders": {
"amount": {
"example": "$120"
}
}
},
"rallyAlertsMessageATMFees": "You've spent {amount} in ATM fees this month",
"@rallyAlertsMessageATMFees": {
"description": "Alert message shown when for example, the user has spent $24 in ATM fees this month.",
"placeholders": {
"amount": {
"example": "24"
}
}
},
"rallyAlertsMessageCheckingAccount": "Good work! Your checking account is {percent} higher than last month.",
"@rallyAlertsMessageCheckingAccount": {
"description": "Alert message shown when for example, the checking account is 1% higher than last month.",
"placeholders": {
"percent": {
"example": "1%"
}
}
},
"rallyAlertsMessageUnassignedTransactions": "{count, plural, =1{Increase your potential tax deduction! Assign categories to 1 unassigned transaction.}other{Increase your potential tax deduction! Assign categories to {count} unassigned transactions.}}",
"@rallyAlertsMessageUnassignedTransactions": {
"description": "Alert message shown when you have unassigned transactions.",
"placeholders": {
"count": {
"example": "2"
}
}
},
"rallySeeAllAccounts": "See all accounts",
"@rallySeeAllAccounts": {
"description": "Semantics label for button to see all accounts. Accounts refer to bank account here."
},
"rallySeeAllBills": "See all bills",
"@rallySeeAllBills": {
"description": "Semantics label for button to see all bills."
},
"rallySeeAllBudgets": "See all budgets",
"@rallySeeAllBudgets": {
"description": "Semantics label for button to see all budgets."
},
"rallyAccountAmount": "{accountName} account {accountNumber} with {amount}.",
"@rallyAccountAmount": {
"description": "Semantics label for row with bank account name (for example checking) and its bank account number (for example 123), with how much money is deposited in it (for example $12).",
"placeholders": {
"accountName": {
"example": "Home Savings"
},
"accountNumber": {
"example": "1234"
},
"amount": {
"example": "$12"
}
}
},
"rallyBillAmount": "{billName} bill due {date} for {amount}.",
"@rallyBillAmount": {
"description": "Semantics label for row with a bill (example name is rent), when the bill is due (1/12/2019 for example) and for how much money ($12).",
"placeholders": {
"billName": {
"example": "Rent"
},
"date": {
"example": "1/24/2019"
},
"amount": {
"example": "$12"
}
}
},
"rallyBudgetAmount": "{budgetName} budget with {amountUsed} used of {amountTotal}, {amountLeft} left",
"@rallyBudgetAmount": {
"description": "Semantics label for row with a budget (housing budget for example), with how much is used of the budget (for example $5), the total budget (for example $100) and the amount left in the budget (for example $95).",
"placeholders": {
"budgetName": {
"example": "Groceries"
},
"amountUsed": {
"example": "$5"
},
"amountTotal": {
"example": "$100"
},
"amountLeft": {
"example": "$95"
}
}
},
"craneDescription": "A personalized travel app",
"@craneDescription": {
"description": "Study description for Crane."
},
"homeCategoryReference": "STYLES & OTHER",
"@homeCategoryReference": {
"description": "Category title on home screen for styles & other demos (for context, the styles demos consist of a color demo and a typography demo)."
},
"demoInvalidURL": "Couldn't display URL:",
"@demoInvalidURL": {
"description": "Error message when opening the URL for a demo."
},
"demoOptionsTooltip": "Options",
"@demoOptionsTooltip": {
"description": "Tooltip for options button in a demo."
},
"demoInfoTooltip": "Info",
"@demoInfoTooltip": {
"description": "Tooltip for info button in a demo."
},
"demoCodeTooltip": "Demo Code",
"@demoCodeTooltip": {
"description": "Tooltip for demo code button in a demo."
},
"demoDocumentationTooltip": "API Documentation",
"@demoDocumentationTooltip": {
"description": "Tooltip for API documentation button in a demo."
},
"demoFullscreenTooltip": "Full Screen",
"@demoFullscreenTooltip": {
"description": "Tooltip for Full Screen button in a demo."
},
"demoCodeViewerCopyAll": "COPY ALL",
"@demoCodeViewerCopyAll": {
"description": "Caption for a button to copy all text."
},
"demoCodeViewerCopiedToClipboardMessage": "Copied to clipboard.",
"@demoCodeViewerCopiedToClipboardMessage": {
"description": "A message displayed to the user after clicking the COPY ALL button, if the text is successfully copied to the clipboard."
},
"demoCodeViewerFailedToCopyToClipboardMessage": "Failed to copy to clipboard: {error}",
"@demoCodeViewerFailedToCopyToClipboardMessage": {
"description": "A message displayed to the user after clicking the COPY ALL button, if the text CANNOT be copied to the clipboard.",
"placeholders": {
"error": {
"example": "Your browser does not have clipboard support."
}
}
},
"demoOptionsFeatureTitle": "View options",
"@demoOptionsFeatureTitle": {
"description": "Title for an alert that explains what the options button does."
},
"demoOptionsFeatureDescription": "Tap here to view available options for this demo.",
"@demoOptionsFeatureDescription": {
"description": "Description for an alert that explains what the options button does."
},
"settingsTitle": "Settings",
"@settingsTitle": {
"description": "Title for the settings screen."
},
"settingsButtonLabel": "Settings",
"@settingsButtonLabel": {
"description": "Accessibility label for the settings button when settings are not showing."
},
"settingsButtonCloseLabel": "Close settings",
"@settingsButtonCloseLabel": {
"description": "Accessibility label for the settings button when settings are showing."
},
"settingsSystemDefault": "System",
"@settingsSystemDefault": {
"description": "Option label to indicate the system default will be used."
},
"settingsTextScaling": "Text scaling",
"@settingsTextScaling": {
"description": "Title for text scaling setting."
},
"settingsTextScalingSmall": "Small",
"@settingsTextScalingSmall": {
"description": "Option label for small text scale setting."
},
"settingsTextScalingNormal": "Normal",
"@settingsTextScalingNormal": {
"description": "Option label for normal text scale setting."
},
"settingsTextScalingLarge": "Large",
"@settingsTextScalingLarge": {
"description": "Option label for large text scale setting."
},
"settingsTextScalingHuge": "Huge",
"@settingsTextScalingHuge": {
"description": "Option label for huge text scale setting."
},
"settingsTextDirection": "Text direction",
"@settingsTextDirection": {
"description": "Title for text direction setting."
},
"settingsTextDirectionLocaleBased": "Based on locale",
"@settingsTextDirectionLocaleBased": {
"description": "Option label for locale-based text direction setting."
},
"settingsTextDirectionLTR": "LTR",
"@settingsTextDirectionLTR": {
"description": "Option label for left-to-right text direction setting."
},
"settingsTextDirectionRTL": "RTL",
"@settingsTextDirectionRTL": {
"description": "Option label for right-to-left text direction setting."
},
"settingsLocale": "Locale",
"@settingsLocale": {
"description": "Title for locale setting."
},
"settingsPlatformMechanics": "Platform mechanics",
"@settingsPlatformMechanics": {
"description": "Title for platform mechanics (iOS, Android, macOS, etc.) setting."
},
"settingsTheme": "Theme",
"@settingsTheme": {
"description": "Title for the theme setting."
},
"settingsDarkTheme": "Dark",
"@settingsDarkTheme": {
"description": "Title for the dark theme setting."
},
"settingsLightTheme": "Light",
"@settingsLightTheme": {
"description": "Title for the light theme setting."
},
"settingsSlowMotion": "Slow motion",
"@settingsSlowMotion": {
"description": "Title for slow motion setting."
},
"settingsAbout": "About Flutter Gallery",
"@settingsAbout": {
"description": "Title for information button."
},
"settingsFeedback": "Send feedback",
"@settingsFeedback": {
"description": "Title for feedback button."
},
"settingsAttribution": "Designed by TOASTER in London",
"@settingsAttribution": {
"description": "Title for attribution (TOASTER is a proper name and should remain in English)."
},
"demoAppBarTitle": "App bar",
"@demoAppBarTitle": {
"description": "Title for the material App bar component demo."
},
"demoAppBarSubtitle": "Displays information and actions relating to the current screen",
"@demoAppBarSubtitle": {
"description": "Subtitle for the material App bar component demo."
},
"demoAppBarDescription": "The App bar provides content and actions related to the current screen. It's used for branding, screen titles, navigation, and actions",
"@demoAppBarDescription": {
"description": "Description for the material App bar component demo."
},
"demoBottomAppBarTitle": "Bottom app bar",
"@demoBottomAppBarTitle": {
"description": "Title for the material bottom app bar component demo."
},
"demoBottomAppBarSubtitle": "Displays navigation and actions at the bottom",
"@demoBottomAppBarSubtitle": {
"description": "Subtitle for the material bottom app bar component demo."
},
"demoBottomAppBarDescription": "Bottom app bars provide access to a bottom navigation drawer and up to four actions, including the floating action button.",
"@demoBottomAppBarDescription": {
"description": "Description for the material bottom app bar component demo."
},
"bottomAppBarNotch": "Notch",
"@bottomAppBarNotch": {
"description": "A toggle for whether to have a notch (or cutout) in the bottom app bar demo."
},
"bottomAppBarPosition": "Floating Action Button Position",
"@bottomAppBarPosition": {
"description": "A setting for the position of the floating action button in the bottom app bar demo."
},
"bottomAppBarPositionDockedEnd": "Docked - End",
"@bottomAppBarPositionDockedEnd": {
"description": "A setting for the position of the floating action button in the bottom app bar that docks the button in the bar and aligns it at the end."
},
"bottomAppBarPositionDockedCenter": "Docked - Center",
"@bottomAppBarPositionDockedCenter": {
"description": "A setting for the position of the floating action button in the bottom app bar that docks the button in the bar and aligns it in the center."
},
"bottomAppBarPositionFloatingEnd": "Floating - End",
"@bottomAppBarPositionFloatingEnd": {
"description": "A setting for the position of the floating action button in the bottom app bar that places the button above the bar and aligns it at the end."
},
"bottomAppBarPositionFloatingCenter": "Floating - Center",
"@bottomAppBarPositionFloatingCenter": {
"description": "A setting for the position of the floating action button in the bottom app bar that places the button above the bar and aligns it in the center."
},
"demoBannerTitle": "Banner",
"@demoBannerTitle": {
"description": "Title for the material banner component demo."
},
"demoBannerSubtitle": "Displaying a banner within a list",
"@demoBannerSubtitle": {
"description": "Subtitle for the material banner component demo."
},
"demoBannerDescription": "A banner displays an important, succinct message, and provides actions for users to address (or dismiss the banner). A user action is required for it to be dismissed.",
"@demoBannerDescription": {
"description": "Description for the material banner component demo."
},
"demoBottomNavigationTitle": "Bottom navigation",
"@demoBottomNavigationTitle": {
"description": "Title for the material bottom navigation component demo."
},
"demoBottomNavigationSubtitle": "Bottom navigation with cross-fading views",
"@demoBottomNavigationSubtitle": {
"description": "Subtitle for the material bottom navigation component demo."
},
"demoBottomNavigationPersistentLabels": "Persistent labels",
"@demoBottomNavigationPersistentLabels": {
"description": "Option title for bottom navigation with persistent labels."
},
"demoBottomNavigationSelectedLabel": "Selected label",
"@demoBottomNavigationSelectedLabel": {
"description": "Option title for bottom navigation with only a selected label."
},
"demoBottomNavigationDescription": "Bottom navigation bars display three to five destinations at the bottom of a screen. Each destination is represented by an icon and an optional text label. When a bottom navigation icon is tapped, the user is taken to the top-level navigation destination associated with that icon.",
"@demoBottomNavigationDescription": {
"description": "Description for the material bottom navigation component demo."
},
"demoButtonTitle": "Buttons",
"@demoButtonTitle": {
"description": "Title for the material buttons component demo."
},
"demoButtonSubtitle": "Text, elevated, outlined, and more",
"@demoButtonSubtitle": {
"description": "Subtitle for the material buttons component demo."
},
"demoTextButtonTitle": "Text Button",
"@demoTextButtonTitle": {
"description": "Title for the text button component demo."
},
"demoTextButtonDescription": "A text button displays an ink splash on press but does not lift. Use text buttons on toolbars, in dialogs and inline with padding",
"@demoTextButtonDescription": {
"description": "Description for the text button component demo."
},
"demoElevatedButtonTitle": "Elevated Button",
"@demoElevatedButtonTitle": {
"description": "Title for the elevated button component demo."
},
"demoElevatedButtonDescription": "Elevated buttons add dimension to mostly flat layouts. They emphasize functions on busy or wide spaces.",
"@demoElevatedButtonDescription": {
"description": "Description for the elevated button component demo."
},
"demoOutlinedButtonTitle": "Outlined Button",
"@demoOutlinedButtonTitle": {
"description": "Title for the outlined button component demo."
},
"demoOutlinedButtonDescription": "Outlined buttons become opaque and elevate when pressed. They are often paired with raised buttons to indicate an alternative, secondary action.",
"@demoOutlinedButtonDescription": {
"description": "Description for the outlined button component demo."
},
"demoToggleButtonTitle": "Toggle Buttons",
"@demoToggleButtonTitle": {
"description": "Title for the toggle buttons component demo."
},
"demoToggleButtonDescription": "Toggle buttons can be used to group related options. To emphasize groups of related toggle buttons, a group should share a common container",
"@demoToggleButtonDescription": {
"description": "Description for the toggle buttons component demo."
},
"demoFloatingButtonTitle": "Floating Action Button",
"@demoFloatingButtonTitle": {
"description": "Title for the floating action button component demo."
},
"demoFloatingButtonDescription": "A floating action button is a circular icon button that hovers over content to promote a primary action in the application.",
"@demoFloatingButtonDescription": {
"description": "Description for the floating action button component demo."
},
"demoCardTitle": "Cards",
"@demoCardTitle": {
"description": "Title for the material cards component demo."
},
"demoCardSubtitle": "Baseline cards with rounded corners",
"@demoCardSubtitle": {
"description": "Subtitle for the material cards component demo."
},
"demoChipTitle": "Chips",
"@demoChipTitle": {
"description": "Title for the material chips component demo."
},
"demoCardDescription": "A card is a sheet of Material used to represent some related information, for example an album, a geographical location, a meal, contact details, etc.",
"@demoCardDescription": {
"description": "Description for the material cards component demo."
},
"demoChipSubtitle": "Compact elements that represent an input, attribute, or action",
"@demoChipSubtitle": {
"description": "Subtitle for the material chips component demo."
},
"demoActionChipTitle": "Action Chip",
"@demoActionChipTitle": {
"description": "Title for the action chip component demo."
},
"demoActionChipDescription": "Action chips are a set of options which trigger an action related to primary content. Action chips should appear dynamically and contextually in a UI.",
"@demoActionChipDescription": {
"description": "Description for the action chip component demo."
},
"demoChoiceChipTitle": "Choice Chip",
"@demoChoiceChipTitle": {
"description": "Title for the choice chip component demo."
},
"demoChoiceChipDescription": "Choice chips represent a single choice from a set. Choice chips contain related descriptive text or categories.",
"@demoChoiceChipDescription": {
"description": "Description for the choice chip component demo."
},
"demoFilterChipTitle": "Filter Chip",
"@demoFilterChipTitle": {
"description": "Title for the filter chip component demo."
},
"demoFilterChipDescription": "Filter chips use tags or descriptive words as a way to filter content.",
"@demoFilterChipDescription": {
"description": "Description for the filter chip component demo."
},
"demoInputChipTitle": "Input Chip",
"@demoInputChipTitle": {
"description": "Title for the input chip component demo."
},
"demoInputChipDescription": "Input chips represent a complex piece of information, such as an entity (person, place, or thing) or conversational text, in a compact form.",
"@demoInputChipDescription": {
"description": "Description for the input chip component demo."
},
"demoDataTableTitle": "Data Tables",
"@demoDataTableTitle": {
"description": "Title for the material data table component demo."
},
"demoDataTableSubtitle": "Rows and columns of information",
"@demoDataTableSubtitle": {
"description": "Subtitle for the material data table component demo."
},
"demoDataTableDescription": "Data tables display information in a grid-like format of rows and columns. They organize information in a way that's easy to scan, so that users can look for patterns and insights.",
"@demoDataTableDescription": {
"description": "Description for the material data table component demo."
},
"dataTableHeader": "Nutrition",
"@dataTableHeader": {
"description": "Header for the data table component demo about nutrition."
},
"dataTableColumnDessert": "Dessert (1 serving)",
"@dataTableColumnDessert": {
"description": "Column header for desserts."
},
"dataTableColumnCalories": "Calories",
"@dataTableColumnCalories": {
"description": "Column header for number of calories."
},
"dataTableColumnFat": "Fat (g)",
"@dataTableColumnFat": {
"description": "Column header for number of grams of fat."
},
"dataTableColumnCarbs": "Carbs (g)",
"@dataTableColumnCarbs": {
"description": "Column header for number of grams of carbs."
},
"dataTableColumnProtein": "Protein (g)",
"@dataTableColumnProtein": {
"description": "Column header for number of grams of protein."
},
"dataTableColumnSodium": "Sodium (mg)",
"@dataTableColumnSodium": {
"description": "Column header for number of milligrams of sodium."
},
"dataTableColumnCalcium": "Calcium (%)",
"@dataTableColumnCalcium": {
"description": "Column header for daily percentage of calcium."
},
"dataTableColumnIron": "Iron (%)",
"@dataTableColumnIron": {
"description": "Column header for daily percentage of iron."
},
"dataTableRowFrozenYogurt": "Frozen yogurt",
"@dataTableRowFrozenYogurt": {
"description": "Column row for frozen yogurt."
},
"dataTableRowIceCreamSandwich": "Ice cream sandwich",
"@dataTableRowIceCreamSandwich": {
"description": "Column row for Ice cream sandwich."
},
"dataTableRowEclair": "Eclair",
"@dataTableRowEclair": {
"description": "Column row for Eclair."
},
"dataTableRowCupcake": "Cupcake",
"@dataTableRowCupcake": {
"description": "Column row for Cupcake."
},
"dataTableRowGingerbread": "Gingerbread",
"@dataTableRowGingerbread": {
"description": "Column row for Gingerbread."
},
"dataTableRowJellyBean": "Jelly bean",
"@dataTableRowJellyBean": {
"description": "Column row for Jelly bean."
},
"dataTableRowLollipop": "Lollipop",
"@dataTableRowLollipop": {
"description": "Column row for Lollipop."
},
"dataTableRowHoneycomb": "Honeycomb",
"@dataTableRowHoneycomb": {
"description": "Column row for Honeycomb."
},
"dataTableRowDonut": "Donut",
"@dataTableRowDonut": {
"description": "Column row for Donut."
},
"dataTableRowApplePie": "Apple pie",
"@dataTableRowApplePie": {
"description": "Column row for Apple pie."
},
"dataTableRowWithSugar": "{value} with sugar",
"@dataTableRowWithSugar": {
"description": "A dessert with sugar on it. The parameter is some type of dessert.",
"placeholders": {
"value": {
"example": "Apple pie"
}
}
},
"dataTableRowWithHoney": "{value} with honey",
"@dataTableRowWithHoney": {
"description": "A dessert with honey on it. The parameter is some type of dessert.",
"placeholders": {
"value": {
"example": "Apple pie"
}
}
},
"demoDialogTitle": "Dialogs",
"@demoDialogTitle": {
"description": "Title for the material dialog component demo."
},
"demoDialogSubtitle": "Simple, alert, and fullscreen",
"@demoDialogSubtitle": {
"description": "Subtitle for the material dialog component demo."
},
"demoAlertDialogTitle": "Alert",
"@demoAlertDialogTitle": {
"description": "Title for the alert dialog component demo."
},
"demoAlertDialogDescription": "An alert dialog informs the user about situations that require acknowledgement. An alert dialog has an optional title and an optional list of actions.",
"@demoAlertDialogDescription": {
"description": "Description for the alert dialog component demo."
},
"demoAlertTitleDialogTitle": "Alert With Title",
"@demoAlertTitleDialogTitle": {
"description": "Title for the alert dialog with title component demo."
},
"demoSimpleDialogTitle": "Simple",
"@demoSimpleDialogTitle": {
"description": "Title for the simple dialog component demo."
},
"demoSimpleDialogDescription": "A simple dialog offers the user a choice between several options. A simple dialog has an optional title that is displayed above the choices.",
"@demoSimpleDialogDescription": {
"description": "Description for the simple dialog component demo."
},
"demoDividerTitle": "Divider",
"@demoDividerTitle": {
"description": "Title for the divider component demo."
},
"demoDividerSubtitle": "A divider is a thin line that groups content in lists and layouts.",
"@demoDividerSubtitle": {
"description": "Subtitle for the divider component demo."
},
"demoDividerDescription": "Dividers can be used in lists, drawers, and elsewhere to separate content.",
"@demoDividerDescription": {
"description": "Description for the divider component demo."
},
"demoVerticalDividerTitle": "Vertical Divider",
"@demoVerticalDividerTitle": {
"description": "Title for the vertical divider component demo."
},
"demoGridListsTitle": "Grid Lists",
"@demoGridListsTitle": {
"description": "Title for the grid lists component demo."
},
"demoGridListsSubtitle": "Row and column layout",
"@demoGridListsSubtitle": {
"description": "Subtitle for the grid lists component demo."
},
"demoGridListsDescription": "Grid Lists are best suited for presenting homogeneous data, typically images. Each item in a grid list is called a tile.",
"@demoGridListsDescription": {
"description": "Description for the grid lists component demo."
},
"demoGridListsImageOnlyTitle": "Image only",
"@demoGridListsImageOnlyTitle": {
"description": "Title for the grid lists image-only component demo."
},
"demoGridListsHeaderTitle": "With header",
"@demoGridListsHeaderTitle": {
"description": "Title for the grid lists component demo with headers on each tile."
},
"demoGridListsFooterTitle": "With footer",
"@demoGridListsFooterTitle": {
"description": "Title for the grid lists component demo with footers on each tile."
},
"demoSlidersTitle": "Sliders",
"@demoSlidersTitle": {
"description": "Title for the sliders component demo."
},
"demoSlidersSubtitle": "Widgets for selecting a value by swiping",
"@demoSlidersSubtitle": {
"description": "Short description for the sliders component demo."
},
"demoSlidersDescription": "Sliders reflect a range of values along a bar, from which users may select a single value. They are ideal for adjusting settings such as volume, brightness, or applying image filters.",
"@demoSlidersDescription": {
"description": "Description for the sliders demo."
},
"demoRangeSlidersTitle": "Range Sliders",
"@demoRangeSlidersTitle": {
"description": "Title for the range sliders component demo."
},
"demoRangeSlidersDescription": "Sliders reflect a range of values along a bar. They can have icons on both ends of the bar that reflect a range of values. They are ideal for adjusting settings such as volume, brightness, or applying image filters.",
"@demoRangeSlidersDescription": {
"description": "Description for the range sliders demo."
},
"demoCustomSlidersTitle": "Custom Sliders",
"@demoCustomSlidersTitle": {
"description": "Title for the custom sliders component demo."
},
"demoCustomSlidersDescription": "Sliders reflect a range of values along a bar, from which users may select a single value or range of values. The sliders can be themed and customized.",
"@demoCustomSlidersDescription": {
"description": "Description for the custom sliders demo."
},
"demoSlidersContinuousWithEditableNumericalValue": "Continuous with Editable Numerical Value",
"@demoSlidersContinuousWithEditableNumericalValue": {
"description": "Text to describe a slider has a continuous value with an editable numerical value."
},
"demoSlidersDiscrete": "Discrete",
"@demoSlidersDiscrete": {
"description": "Text to describe that we have a slider with discrete values."
},
"demoSlidersDiscreteSliderWithCustomTheme": "Discrete Slider with Custom Theme",
"@demoSlidersDiscreteSliderWithCustomTheme": {
"description": "Text to describe that we have a slider with discrete values and a custom theme. "
},
"demoSlidersContinuousRangeSliderWithCustomTheme": "Continuous Range Slider with Custom Theme",
"@demoSlidersContinuousRangeSliderWithCustomTheme": {
"description": "Text to describe that we have a range slider with continuous values and a custom theme. "
},
"demoSlidersContinuous": "Continuous",
"@demoSlidersContinuous": {
"description": "Text to describe that we have a slider with continuous values."
},
"demoSlidersEditableNumericalValue": "Editable numerical value",
"@demoSlidersEditableNumericalValue": {
"description": "Label for input field that has an editable numerical value."
},
"demoMenuTitle": "Menu",
"@demoMenuTitle": {
"description": "Title for the menu component demo."
},
"demoContextMenuTitle": "Context menu",
"@demoContextMenuTitle": {
"description": "Title for the context menu component demo."
},
"demoSectionedMenuTitle": "Sectioned menu",
"@demoSectionedMenuTitle": {
"description": "Title for the sectioned menu component demo."
},
"demoSimpleMenuTitle": "Simple menu",
"@demoSimpleMenuTitle": {
"description": "Title for the simple menu component demo."
},
"demoChecklistMenuTitle": "Checklist menu",
"@demoChecklistMenuTitle": {
"description": "Title for the checklist menu component demo."
},
"demoMenuSubtitle": "Menu buttons and simple menus",
"@demoMenuSubtitle": {
"description": "Short description for the menu component demo."
},
"demoMenuDescription": "A menu displays a list of choices on a temporary surface. They appear when users interact with a button, action, or other control.",
"@demoMenuDescription": {
"description": "Description for the menu demo."
},
"demoMenuItemValueOne": "Menu item one",
"@demoMenuItemValueOne": {
"description": "The first item in a menu."
},
"demoMenuItemValueTwo": "Menu item two",
"@demoMenuItemValueTwo": {
"description": "The second item in a menu."
},
"demoMenuItemValueThree": "Menu item three",
"@demoMenuItemValueThree": {
"description": "The third item in a menu."
},
"demoMenuOne": "One",
"@demoMenuOne": {
"description": "The number one."
},
"demoMenuTwo": "Two",
"@demoMenuTwo": {
"description": "The number two."
},
"demoMenuThree": "Three",
"@demoMenuThree": {
"description": "The number three."
},
"demoMenuFour": "Four",
"@demoMenuFour": {
"description": "The number four."
},
"demoMenuAnItemWithAContextMenuButton": "An item with a context menu",
"@demoMenuAnItemWithAContextMenuButton": {
"description": "Label next to a button that opens a menu. A menu displays a list of choices on a temporary surface. Used as an example in a demo."
},
"demoMenuContextMenuItemOne": "Context menu item one",
"@demoMenuContextMenuItemOne": {
"description": "Text label for a context menu item. A menu displays a list of choices on a temporary surface. Used as an example in a demo."
},
"demoMenuADisabledMenuItem": "Disabled menu item",
"@demoMenuADisabledMenuItem": {
"description": "Text label for a disabled menu item. A menu displays a list of choices on a temporary surface. Used as an example in a demo."
},
"demoMenuContextMenuItemThree": "Context menu item three",
"@demoMenuContextMenuItemThree": {
"description": "Text label for a context menu item three. A menu displays a list of choices on a temporary surface. Used as an example in a demo."
},
"demoMenuAnItemWithASectionedMenu": "An item with a sectioned menu",
"@demoMenuAnItemWithASectionedMenu": {
"description": "Label next to a button that opens a sectioned menu . A menu displays a list of choices on a temporary surface. Used as an example in a demo."
},
"demoMenuPreview": "Preview",
"@demoMenuPreview": {
"description": "Button to preview content."
},
"demoMenuShare": "Share",
"@demoMenuShare": {
"description": "Button to share content."
},
"demoMenuGetLink": "Get link",
"@demoMenuGetLink": {
"description": "Button to get link for content."
},
"demoMenuRemove": "Remove",
"@demoMenuRemove": {
"description": "Button to remove content."
},
"demoMenuSelected": "Selected: {value}",
"@demoMenuSelected": {
"description": "A text to show what value was selected.",
"placeholders": {
"value": {
"example": "1"
}
}
},
"demoMenuChecked": "Checked: {value}",
"@demoMenuChecked": {
"description": "A text to show what value was checked.",
"placeholders": {
"value": {
"example": "1"
}
}
},
"demoNavigationDrawerTitle": "Navigation Drawer",
"@demoNavigationDrawerTitle": {
"description": "Title for the material drawer component demo."
},
"demoNavigationDrawerSubtitle": "Displaying a drawer within appbar",
"@demoNavigationDrawerSubtitle": {
"description": "Subtitle for the material drawer component demo."
},
"demoNavigationDrawerDescription": "A Material Design panel that slides in horizontally from the edge of the screen to show navigation links in an application.",
"@demoNavigationDrawerDescription": {
"description": "Description for the material drawer component demo."
},
"demoNavigationDrawerUserName": "User Name",
"@demoNavigationDrawerUserName": {
"description": "Demo username for navigation drawer."
},
"demoNavigationDrawerUserEmail": "[email protected]",
"@demoNavigationDrawerUserEmail": {
"description": "Demo email for navigation drawer."
},
"demoNavigationDrawerToPageOne": "Item One",
"@demoNavigationDrawerToPageOne": {
"description": "Drawer Item One."
},
"demoNavigationDrawerToPageTwo": "Item Two",
"@demoNavigationDrawerToPageTwo": {
"description": "Drawer Item Two."
},
"demoNavigationDrawerText": "Swipe from the edge or tap the upper-left icon to see the drawer",
"@demoNavigationDrawerText": {
"description": "Description to open navigation drawer."
},
"demoNavigationRailTitle": "Navigation Rail",
"@demoNavigationRailTitle": {
"description": "Title for the material Navigation Rail component demo."
},
"demoNavigationRailSubtitle": "Displaying a Navigation Rail within an app",
"@demoNavigationRailSubtitle": {
"description": "Subtitle for the material Navigation Rail component demo."
},
"demoNavigationRailDescription": "A material widget that is meant to be displayed at the left or right of an app to navigate between a small number of views, typically between three and five.",
"@demoNavigationRailDescription": {
"description": "Description for the material Navigation Rail component demo."
},
"demoNavigationRailFirst": "First",
"@demoNavigationRailFirst": {
"description": "Navigation Rail destination first label."
},
"demoNavigationRailSecond": "Second",
"@demoNavigationRailSecond": {
"description": "Navigation Rail destination second label."
},
"demoNavigationRailThird": "Third",
"@demoNavigationRailThird": {
"description": "Navigation Rail destination Third label."
},
"demoMenuAnItemWithASimpleMenu": "An item with a simple menu",
"@demoMenuAnItemWithASimpleMenu": {
"description": "Label next to a button that opens a simple menu. A menu displays a list of choices on a temporary surface. Used as an example in a demo."
},
"demoMenuAnItemWithAChecklistMenu": "An item with a checklist menu",
"@demoMenuAnItemWithAChecklistMenu": {
"description": "Label next to a button that opens a checklist menu. A menu displays a list of choices on a temporary surface. Used as an example in a demo."
},
"demoFullscreenDialogTitle": "Fullscreen",
"@demoFullscreenDialogTitle": {
"description": "Title for the fullscreen dialog component demo."
},
"demoFullscreenDialogDescription": "The fullscreenDialog property specifies whether the incoming page is a fullscreen modal dialog",
"@demoFullscreenDialogDescription": {
"description": "Description for the fullscreen dialog component demo."
},
"demoCupertinoActivityIndicatorTitle": "Activity indicator",
"@demoCupertinoActivityIndicatorTitle": {
"description": "Title for the cupertino activity indicator component demo."
},
"demoCupertinoActivityIndicatorSubtitle": "iOS-style activity indicators",
"@demoCupertinoActivityIndicatorSubtitle": {
"description": "Subtitle for the cupertino activity indicator component demo."
},
"demoCupertinoActivityIndicatorDescription": "An iOS-style activity indicator that spins clockwise.",
"@demoCupertinoActivityIndicatorDescription": {
"description": "Description for the cupertino activity indicator component demo."
},
"demoCupertinoButtonsTitle": "Buttons",
"@demoCupertinoButtonsTitle": {
"description": "Title for the cupertino buttons component demo."
},
"demoCupertinoButtonsSubtitle": "iOS-style buttons",
"@demoCupertinoButtonsSubtitle": {
"description": "Subtitle for the cupertino buttons component demo."
},
"demoCupertinoButtonsDescription": "An iOS-style button. It takes in text and/or an icon that fades out and in on touch. May optionally have a background.",
"@demoCupertinoButtonsDescription": {
"description": "Description for the cupertino buttons component demo."
},
"demoCupertinoContextMenuTitle": "Context Menu",
"@demoCupertinoContextMenuTitle": {
"description": "Title for the cupertino context menu component demo."
},
"demoCupertinoContextMenuSubtitle": "iOS-style context menu",
"@demoCupertinoContextMenuSubtitle": {
"description": "Subtitle for the cupertino context menu component demo."
},
"demoCupertinoContextMenuDescription": "An iOS-style full screen contextual menu that appears when an element is long-pressed.",
"@demoCupertinoContextMenuDescription": {
"description": "Description for the cupertino context menu component demo."
},
"demoCupertinoContextMenuActionOne": "Action one",
"@demoCupertinoContextMenuActionOne": {
"description": "Context menu list item one"
},
"demoCupertinoContextMenuActionTwo": "Action two",
"@demoCupertinoContextMenuActionTwo": {
"description": "Context menu list item two"
},
"demoCupertinoContextMenuActionText": "Tap and hold the Flutter logo to see the context menu.",
"@demoCupertinoContextMenuActionText": {
"description": "Context menu text."
},
"demoCupertinoAlertsTitle": "Alerts",
"@demoCupertinoAlertsTitle": {
"description": "Title for the cupertino alerts component demo."
},
"demoCupertinoAlertsSubtitle": "iOS-style alert dialogs",
"@demoCupertinoAlertsSubtitle": {
"description": "Subtitle for the cupertino alerts component demo."
},
"demoCupertinoAlertTitle": "Alert",
"@demoCupertinoAlertTitle": {
"description": "Title for the cupertino alert component demo."
},
"demoCupertinoAlertDescription": "An alert dialog informs the user about situations that require acknowledgement. An alert dialog has an optional title, optional content, and an optional list of actions. The title is displayed above the content and the actions are displayed below the content.",
"@demoCupertinoAlertDescription": {
"description": "Description for the cupertino alert component demo."
},
"demoCupertinoAlertWithTitleTitle": "Alert With Title",
"@demoCupertinoAlertWithTitleTitle": {
"description": "Title for the cupertino alert with title component demo."
},
"demoCupertinoAlertButtonsTitle": "Alert With Buttons",
"@demoCupertinoAlertButtonsTitle": {
"description": "Title for the cupertino alert with buttons component demo."
},
"demoCupertinoAlertButtonsOnlyTitle": "Alert Buttons Only",
"@demoCupertinoAlertButtonsOnlyTitle": {
"description": "Title for the cupertino alert buttons only component demo."
},
"demoCupertinoActionSheetTitle": "Action Sheet",
"@demoCupertinoActionSheetTitle": {
"description": "Title for the cupertino action sheet component demo."
},
"demoCupertinoActionSheetDescription": "An action sheet is a specific style of alert that presents the user with a set of two or more choices related to the current context. An action sheet can have a title, an additional message, and a list of actions.",
"@demoCupertinoActionSheetDescription": {
"description": "Description for the cupertino action sheet component demo."
},
"demoCupertinoNavigationBarTitle": "Navigation bar",
"@demoCupertinoNavigationBarTitle": {
"description": "Title for the cupertino navigation bar component demo."
},
"demoCupertinoNavigationBarSubtitle": "iOS-style navigation bar",
"@demoCupertinoNavigationBarSubtitle": {
"description": "Subtitle for the cupertino navigation bar component demo."
},
"demoCupertinoNavigationBarDescription": "An iOS-styled navigation bar. The navigation bar is a toolbar that minimally consists of a page title, in the middle of the toolbar.",
"@demoCupertinoNavigationBarDescription": {
"description": "Description for the cupertino navigation bar component demo."
},
"demoCupertinoPickerTitle": "Pickers",
"@demoCupertinoPickerTitle": {
"description": "Title for the cupertino pickers component demo."
},
"demoCupertinoPickerSubtitle": "iOS-style pickers",
"@demoCupertinoPickerSubtitle": {
"description": "Subtitle for the cupertino pickers component demo."
},
"demoCupertinoPickerDescription": "An iOS-style picker widget that can be used to select strings, dates, times, or both date and time.",
"@demoCupertinoPickerDescription": {
"description": "Description for the cupertino pickers component demo."
},
"demoCupertinoPickerTimer": "Timer",
"@demoCupertinoPickerTimer": {
"description": "Label to open a countdown timer picker."
},
"demoCupertinoPicker": "Picker",
"@demoCupertinoPicker": {
"description": "Label to open an iOS picker."
},
"demoCupertinoPickerDate": "Date",
"@demoCupertinoPickerDate": {
"description": "Label to open a date picker."
},
"demoCupertinoPickerTime": "Time",
"@demoCupertinoPickerTime": {
"description": "Label to open a time picker."
},
"demoCupertinoPickerDateTime": "Date and Time",
"@demoCupertinoPickerDateTime": {
"description": "Label to open a date and time picker."
},
"demoCupertinoPullToRefreshTitle": "Pull to refresh",
"@demoCupertinoPullToRefreshTitle": {
"description": "Title for the cupertino pull-to-refresh component demo."
},
"demoCupertinoPullToRefreshSubtitle": "iOS-style pull to refresh control",
"@demoCupertinoPullToRefreshSubtitle": {
"description": "Subtitle for the cupertino pull-to-refresh component demo."
},
"demoCupertinoPullToRefreshDescription": "A widget implementing the iOS-style pull to refresh content control.",
"@demoCupertinoPullToRefreshDescription": {
"description": "Description for the cupertino pull-to-refresh component demo."
},
"demoCupertinoSegmentedControlTitle": "Segmented control",
"@demoCupertinoSegmentedControlTitle": {
"description": "Title for the cupertino segmented control component demo."
},
"demoCupertinoSegmentedControlSubtitle": "iOS-style segmented control",
"@demoCupertinoSegmentedControlSubtitle": {
"description": "Subtitle for the cupertino segmented control component demo."
},
"demoCupertinoSegmentedControlDescription": "Used to select between a number of mutually exclusive options. When one option in the segmented control is selected, the other options in the segmented control cease to be selected.",
"@demoCupertinoSegmentedControlDescription": {
"description": "Description for the cupertino segmented control component demo."
},
"demoCupertinoSliderTitle": "Slider",
"@demoCupertinoSliderTitle": {
"description": "Title for the cupertino slider component demo."
},
"demoCupertinoSliderSubtitle": "iOS-style slider",
"@demoCupertinoSliderSubtitle": {
"description": "Subtitle for the cupertino slider component demo."
},
"demoCupertinoSliderDescription": "A slider can be used to select from either a continuous or a discrete set of values.",
"@demoCupertinoSliderDescription": {
"description": "Description for the cupertino slider component demo."
},
"demoCupertinoSliderContinuous": "Continuous: {value}",
"@demoCupertinoSliderContinuous": {
"description": "A label for a continuous slider that indicates what value it is set to.",
"placeholders": {
"value": {
"example": "1"
}
}
},
"demoCupertinoSliderDiscrete": "Discrete: {value}",
"@demoCupertinoSliderDiscrete": {
"description": "A label for a discrete slider that indicates what value it is set to.",
"placeholders": {
"value": {
"example": "1"
}
}
},
"demoCupertinoSwitchSubtitle": "iOS-style switch",
"@demoCupertinoSwitchSubtitle": {
"description": "Subtitle for the cupertino switch component demo."
},
"demoCupertinoSwitchDescription": "A switch is used to toggle the on/off state of a single setting.",
"@demoCupertinoSwitchDescription": {
"description": "Description for the cupertino switch component demo."
},
"demoCupertinoTabBarTitle": "Tab bar",
"@demoCupertinoTabBarTitle": {
"description": "Title for the cupertino bottom tab bar demo."
},
"demoCupertinoTabBarSubtitle": "iOS-style bottom tab bar",
"@demoCupertinoTabBarSubtitle": {
"description": "Subtitle for the cupertino bottom tab bar demo."
},
"demoCupertinoTabBarDescription": "An iOS-style bottom navigation tab bar. Displays multiple tabs with one tab being active, the first tab by default.",
"@demoCupertinoTabBarDescription": {
"description": "Description for the cupertino bottom tab bar demo."
},
"cupertinoTabBarHomeTab": "Home",
"@cupertinoTabBarHomeTab": {
"description": "Title for the home tab in the bottom tab bar demo."
},
"cupertinoTabBarChatTab": "Chat",
"@cupertinoTabBarChatTab": {
"description": "Title for the chat tab in the bottom tab bar demo."
},
"cupertinoTabBarProfileTab": "Profile",
"@cupertinoTabBarProfileTab": {
"description": "Title for the profile tab in the bottom tab bar demo."
},
"demoCupertinoTextFieldTitle": "Text fields",
"@demoCupertinoTextFieldTitle": {
"description": "Title for the cupertino text field demo."
},
"demoCupertinoTextFieldSubtitle": "iOS-style text fields",
"@demoCupertinoTextFieldSubtitle": {
"description": "Subtitle for the cupertino text field demo."
},
"demoCupertinoTextFieldDescription": "A text field lets the user enter text, either with a hardware keyboard or with an onscreen keyboard.",
"@demoCupertinoTextFieldDescription": {
"description": "Description for the cupertino text field demo."
},
"demoCupertinoTextFieldPIN": "PIN",
"@demoCupertinoTextFieldPIN": {
"description": "The placeholder for a text field where a user would enter their PIN number."
},
"demoCupertinoSearchTextFieldTitle": "Search text field",
"@demoCupertinoSearchTextFieldTitle": {
"description": "Title for the cupertino search text field demo."
},
"demoCupertinoSearchTextFieldSubtitle": "iOS-style search text field",
"@demoCupertinoSearchTextFieldSubtitle": {
"description": "Subtitle for the cupertino search text field demo."
},
"demoCupertinoSearchTextFieldDescription": "A search text field that lets the user search by entering text, and that can offer and filter suggestions.",
"@demoCupertinoSearchTextFieldDescription": {
"description": "Description for the cupertino search text field demo."
},
"demoCupertinoSearchTextFieldPlaceholder": "Enter some text",
"@demoCupertinoSearchTextFieldPlaceholder": {
"description": "The placeholder for a search text field demo."
},
"demoCupertinoScrollbarTitle": "Scrollbar",
"@demoCupertinoScrollbarTitle": {
"description": "Title for the cupertino scrollbar demo."
},
"demoCupertinoScrollbarSubtitle": "iOS-style scrollbar",
"@demoCupertinoScrollbarSubtitle": {
"description": "Subtitle for the cupertino scrollbar demo."
},
"demoCupertinoScrollbarDescription": "A scrollbar that wraps the given child",
"@demoCupertinoScrollbarDescription": {
"description": "Description for the cupertino scrollbar demo."
},
"demoMotionTitle": "Motion",
"@demoMotionTitle": {
"description": "Title for the motion demo."
},
"demoMotionSubtitle": "All of the predefined transition patterns",
"@demoMotionSubtitle": {
"description": "Subtitle for the motion demo."
},
"demoContainerTransformDemoInstructions": "Cards, Lists & FAB",
"@demoContainerTransformDemoInstructions": {
"description": "Instructions for the container transform demo located in the app bar."
},
"demoSharedXAxisDemoInstructions": "Next and Back Buttons",
"@demoSharedXAxisDemoInstructions": {
"description": "Instructions for the shared x axis demo located in the app bar."
},
"demoSharedYAxisDemoInstructions": "Sort by \"Recently Played\"",
"@demoSharedYAxisDemoInstructions": {
"description": "Instructions for the shared y axis demo located in the app bar."
},
"demoSharedZAxisDemoInstructions": "Settings icon button",
"@demoSharedZAxisDemoInstructions": {
"description": "Instructions for the shared z axis demo located in the app bar."
},
"demoFadeThroughDemoInstructions": "Bottom navigation",
"@demoFadeThroughDemoInstructions": {
"description": "Instructions for the fade through demo located in the app bar."
},
"demoFadeScaleDemoInstructions": "Modal and FAB",
"@demoFadeScaleDemoInstructions": {
"description": "Instructions for the fade scale demo located in the app bar."
},
"demoContainerTransformTitle": "Container Transform",
"@demoContainerTransformTitle": {
"description": "Title for the container transform demo."
},
"demoContainerTransformDescription": "The container transform pattern is designed for transitions between UI elements that include a container. This pattern creates a visible connection between two UI elements",
"@demoContainerTransformDescription": {
"description": "Description for the container transform demo."
},
"demoContainerTransformModalBottomSheetTitle": "Fade mode",
"@demoContainerTransformModalBottomSheetTitle": {
"description": "Title for the container transform modal bottom sheet."
},
"demoContainerTransformTypeFade": "FADE",
"@demoContainerTransformTypeFade": {
"description": "Description for container transform fade type setting."
},
"demoContainerTransformTypeFadeThrough": "FADE THROUGH",
"@demoContainerTransformTypeFadeThrough": {
"description": "Description for container transform fade through type setting."
},
"demoMotionPlaceholderTitle": "Title",
"@demoMotionPlaceholderTitle": {
"description": "The placeholder for the motion demos title properties."
},
"demoMotionPlaceholderSubtitle": "Secondary text",
"@demoMotionPlaceholderSubtitle": {
"description": "The placeholder for the motion demos subtitle properties."
},
"demoMotionSmallPlaceholderSubtitle": "Secondary",
"@demoMotionSmallPlaceholderSubtitle": {
"description": "The placeholder for the motion demos shortened subtitle properties."
},
"demoMotionDetailsPageTitle": "Details Page",
"@demoMotionDetailsPageTitle": {
"description": "The title for the details page in the motion demos."
},
"demoMotionListTileTitle": "List item",
"@demoMotionListTileTitle": {
"description": "The title for a list tile in the motion demos."
},
"demoSharedAxisDescription": "The shared axis pattern is used for transitions between the UI elements that have a spatial or navigational relationship. This pattern uses a shared transformation on the x, y, or z axis to reinforce the relationship between elements.",
"@demoSharedAxisDescription": {
"description": "Description for the shared y axis demo."
},
"demoSharedXAxisTitle": "Shared x-axis",
"@demoSharedXAxisTitle": {
"description": "Title for the shared x axis demo."
},
"demoSharedXAxisBackButtonText": "BACK",
"@demoSharedXAxisBackButtonText": {
"description": "Button text for back button in the shared x axis demo."
},
"demoSharedXAxisNextButtonText": "NEXT",
"@demoSharedXAxisNextButtonText": {
"description": "Button text for the next button in the shared x axis demo."
},
"demoSharedXAxisCoursePageTitle": "Streamline your courses",
"@demoSharedXAxisCoursePageTitle": {
"description": "Title for course selection page in the shared x axis demo."
},
"demoSharedXAxisCoursePageSubtitle": "Bundled categories appear as groups in your feed. You can always change this later.",
"@demoSharedXAxisCoursePageSubtitle": {
"description": "Subtitle for course selection page in the shared x axis demo."
},
"demoSharedXAxisArtsAndCraftsCourseTitle": "Arts & Crafts",
"@demoSharedXAxisArtsAndCraftsCourseTitle": {
"description": "Title for the Arts & Crafts course in the shared x axis demo."
},
"demoSharedXAxisBusinessCourseTitle": "Business",
"@demoSharedXAxisBusinessCourseTitle": {
"description": "Title for the Business course in the shared x axis demo."
},
"demoSharedXAxisIllustrationCourseTitle": "Illustration",
"@demoSharedXAxisIllustrationCourseTitle": {
"description": "Title for the Illustration course in the shared x axis demo."
},
"demoSharedXAxisDesignCourseTitle": "Design",
"@demoSharedXAxisDesignCourseTitle": {
"description": "Title for the Design course in the shared x axis demo."
},
"demoSharedXAxisCulinaryCourseTitle": "Culinary",
"@demoSharedXAxisCulinaryCourseTitle": {
"description": "Title for the Culinary course in the shared x axis demo."
},
"demoSharedXAxisBundledCourseSubtitle": "Bundled",
"@demoSharedXAxisBundledCourseSubtitle": {
"description": "Subtitle for a bundled course in the shared x axis demo."
},
"demoSharedXAxisIndividualCourseSubtitle": "Shown Individually",
"@demoSharedXAxisIndividualCourseSubtitle": {
"description": "Subtitle for a individual course in the shared x axis demo."
},
"demoSharedXAxisSignInWelcomeText": "Hi David Park",
"@demoSharedXAxisSignInWelcomeText": {
"description": "Welcome text for sign in page in the shared x axis demo. David Park is a name and does not need to be translated."
},
"demoSharedXAxisSignInSubtitleText": "Sign in with your account",
"@demoSharedXAxisSignInSubtitleText": {
"description": "Subtitle text for sign in page in the shared x axis demo."
},
"demoSharedXAxisSignInTextFieldLabel": "Email or phone number",
"@demoSharedXAxisSignInTextFieldLabel": {
"description": "Label text for the sign in text field in the shared x axis demo."
},
"demoSharedXAxisForgotEmailButtonText": "FORGOT EMAIL?",
"@demoSharedXAxisForgotEmailButtonText": {
"description": "Button text for the forgot email button in the shared x axis demo."
},
"demoSharedXAxisCreateAccountButtonText": "CREATE ACCOUNT",
"@demoSharedXAxisCreateAccountButtonText": {
"description": "Button text for the create account button in the shared x axis demo."
},
"demoSharedYAxisTitle": "Shared y-axis",
"@demoSharedYAxisTitle": {
"description": "Title for the shared y axis demo."
},
"demoSharedYAxisAlbumCount": "268 albums",
"@demoSharedYAxisAlbumCount": {
"description": "Text for album count in the shared y axis demo."
},
"demoSharedYAxisAlphabeticalSortTitle": "A-Z",
"@demoSharedYAxisAlphabeticalSortTitle": {
"description": "Title for alphabetical sorting type in the shared y axis demo."
},
"demoSharedYAxisRecentSortTitle": "Recently played",
"@demoSharedYAxisRecentSortTitle": {
"description": "Title for recently played sorting type in the shared y axis demo."
},
"demoSharedYAxisAlbumTileTitle": "Album",
"@demoSharedYAxisAlbumTileTitle": {
"description": "Title for an AlbumTile in the shared y axis demo."
},
"demoSharedYAxisAlbumTileSubtitle": "Artist",
"@demoSharedYAxisAlbumTileSubtitle": {
"description": "Subtitle for an AlbumTile in the shared y axis demo."
},
"demoSharedYAxisAlbumTileDurationUnit": "min",
"@demoSharedYAxisAlbumTileDurationUnit": {
"description": "Duration unit for an AlbumTile in the shared y axis demo."
},
"demoSharedZAxisTitle": "Shared z-axis",
"@demoSharedZAxisTitle": {
"description": "Title for the shared z axis demo."
},
"demoSharedZAxisSettingsPageTitle": "Settings",
"@demoSharedZAxisSettingsPageTitle": {
"description": "Title for the settings page in the shared z axis demo."
},
"demoSharedZAxisBurgerRecipeTitle": "Burger",
"@demoSharedZAxisBurgerRecipeTitle": {
"description": "Title for burger recipe tile in the shared z axis demo."
},
"demoSharedZAxisBurgerRecipeDescription": "Burger recipe",
"@demoSharedZAxisBurgerRecipeDescription": {
"description": "Subtitle for the burger recipe tile in the shared z axis demo."
},
"demoSharedZAxisSandwichRecipeTitle": "Sandwich",
"@demoSharedZAxisSandwichRecipeTitle": {
"description": "Title for sandwich recipe tile in the shared z axis demo."
},
"demoSharedZAxisSandwichRecipeDescription": "Sandwich recipe",
"@demoSharedZAxisSandwichRecipeDescription": {
"description": "Subtitle for the sandwich recipe tile in the shared z axis demo."
},
"demoSharedZAxisDessertRecipeTitle": "Dessert",
"@demoSharedZAxisDessertRecipeTitle": {
"description": "Title for dessert recipe tile in the shared z axis demo."
},
"demoSharedZAxisDessertRecipeDescription": "Dessert recipe",
"@demoSharedZAxisDessertRecipeDescription": {
"description": "Subtitle for the dessert recipe tile in the shared z axis demo."
},
"demoSharedZAxisShrimpPlateRecipeTitle": "Shrimp",
"@demoSharedZAxisShrimpPlateRecipeTitle": {
"description": "Title for shrimp plate recipe tile in the shared z axis demo."
},
"demoSharedZAxisShrimpPlateRecipeDescription": "Shrimp plate recipe",
"@demoSharedZAxisShrimpPlateRecipeDescription": {
"description": "Subtitle for the shrimp plate recipe tile in the shared z axis demo."
},
"demoSharedZAxisCrabPlateRecipeTitle": "Crab",
"@demoSharedZAxisCrabPlateRecipeTitle": {
"description": "Title for crab plate recipe tile in the shared z axis demo."
},
"demoSharedZAxisCrabPlateRecipeDescription": "Crab plate recipe",
"@demoSharedZAxisCrabPlateRecipeDescription": {
"description": "Subtitle for the crab plate recipe tile in the shared z axis demo."
},
"demoSharedZAxisBeefSandwichRecipeTitle": "Beef Sandwich",
"@demoSharedZAxisBeefSandwichRecipeTitle": {
"description": "Title for beef sandwich recipe tile in the shared z axis demo."
},
"demoSharedZAxisBeefSandwichRecipeDescription": "Beef Sandwich recipe",
"@demoSharedZAxisBeefSandwichRecipeDescription": {
"description": "Subtitle for the beef sandwich recipe tile in the shared z axis demo."
},
"demoSharedZAxisSavedRecipesListTitle": "Saved Recipes",
"@demoSharedZAxisSavedRecipesListTitle": {
"description": "Title for list of saved recipes in the shared z axis demo."
},
"demoSharedZAxisProfileSettingLabel": "Profile",
"@demoSharedZAxisProfileSettingLabel": {
"description": "Text label for profile setting tile in the shared z axis demo."
},
"demoSharedZAxisNotificationSettingLabel": "Notifications",
"@demoSharedZAxisNotificationSettingLabel": {
"description": "Text label for notifications setting tile in the shared z axis demo."
},
"demoSharedZAxisPrivacySettingLabel": "Privacy",
"@demoSharedZAxisPrivacySettingLabel": {
"description": "Text label for the privacy setting tile in the shared z axis demo."
},
"demoSharedZAxisHelpSettingLabel": "Help",
"@demoSharedZAxisHelpSettingLabel": {
"description": "Text label for the help setting tile in the shared z axis demo."
},
"demoFadeThroughTitle": "Fade through",
"@demoFadeThroughTitle": {
"description": "Title for the fade through demo."
},
"demoFadeThroughDescription": "The fade through pattern is used for transitions between UI elements that do not have a strong relationship to each other.",
"@demoFadeThroughDescription": {
"description": "Description for the fade through demo."
},
"demoFadeThroughAlbumsDestination": "Albums",
"@demoFadeThroughAlbumsDestination": {
"description": "Text for albums bottom navigation bar destination in the fade through demo."
},
"demoFadeThroughPhotosDestination": "Photos",
"@demoFadeThroughPhotosDestination": {
"description": "Text for photos bottom navigation bar destination in the fade through demo."
},
"demoFadeThroughSearchDestination": "Search",
"@demoFadeThroughSearchDestination": {
"description": "Text for search bottom navigation bar destination in the fade through demo."
},
"demoFadeThroughTextPlaceholder": "123 photos",
"@demoFadeThroughTextPlaceholder": {
"description": "Placeholder for example card title in the fade through demo."
},
"demoFadeScaleTitle": "Fade",
"@demoFadeScaleTitle": {
"description": "Title for the fade scale demo."
},
"demoFadeScaleDescription": "The fade pattern is used for UI elements that enter or exit within the bounds of the screen, such as a dialog that fades in the center of the screen.",
"@demoFadeScaleDescription": {
"description": "Description for the fade scale demo."
},
"demoFadeScaleShowAlertDialogButton": "SHOW MODAL",
"@demoFadeScaleShowAlertDialogButton": {
"description": "Button text to show alert dialog in the fade scale demo."
},
"demoFadeScaleShowFabButton": "SHOW FAB",
"@demoFadeScaleShowFabButton": {
"description": "Button text to show fab in the fade scale demo."
},
"demoFadeScaleHideFabButton": "HIDE FAB",
"@demoFadeScaleHideFabButton": {
"description": "Button text to hide fab in the fade scale demo."
},
"demoFadeScaleAlertDialogHeader": "Alert Dialog",
"@demoFadeScaleAlertDialogHeader": {
"description": "Generic header for alert dialog in the fade scale demo."
},
"demoFadeScaleAlertDialogCancelButton": "CANCEL",
"@demoFadeScaleAlertDialogCancelButton": {
"description": "Button text for alert dialog cancel button in the fade scale demo."
},
"demoFadeScaleAlertDialogDiscardButton": "DISCARD",
"@demoFadeScaleAlertDialogDiscardButton": {
"description": "Button text for alert dialog discard button in the fade scale demo."
},
"demoColorsTitle": "Colors",
"@demoColorsTitle": {
"description": "Title for the colors demo."
},
"demoColorsSubtitle": "All of the predefined colors",
"@demoColorsSubtitle": {
"description": "Subtitle for the colors demo."
},
"demoColorsDescription": "Color and color swatch constants which represent Material Design's color palette.",
"@demoColorsDescription": {
"description": "Description for the colors demo. Material Design should remain capitalized."
},
"demoTypographyTitle": "Typography",
"@demoTypographyTitle": {
"description": "Title for the typography demo."
},
"demoTypographySubtitle": "All of the predefined text styles",
"@demoTypographySubtitle": {
"description": "Subtitle for the typography demo."
},
"demoTypographyDescription": "Definitions for the various typographical styles found in Material Design.",
"@demoTypographyDescription": {
"description": "Description for the typography demo. Material Design should remain capitalized."
},
"demo2dTransformationsTitle": "2D transformations",
"@demo2dTransformationsTitle": {
"description": "Title for the 2D transformations demo."
},
"demo2dTransformationsSubtitle": "Pan and zoom",
"@demo2dTransformationsSubtitle": {
"description": "Subtitle for the 2D transformations demo."
},
"demo2dTransformationsDescription": "Tap to edit tiles, and use gestures to move around the scene. Drag to pan and pinch with two fingers to zoom. Press the reset button to return to the starting orientation.",
"@demo2dTransformationsDescription": {
"description": "Description for the 2D transformations demo."
},
"demo2dTransformationsResetTooltip": "Reset transformations",
"@demo2dTransformationsResetTooltip": {
"description": "Tooltip for a button to reset the transformations (scale, translation) for the 2D transformations demo."
},
"demo2dTransformationsEditTooltip": "Edit tile",
"@demo2dTransformationsEditTooltip": {
"description": "Tooltip for a button to edit a tile."
},
"buttonText": "BUTTON",
"@buttonText": {
"description": "Text for a generic button."
},
"demoBottomSheetTitle": "Bottom sheet",
"@demoBottomSheetTitle": {
"description": "Title for bottom sheet demo."
},
"demoBottomSheetSubtitle": "Persistent and modal bottom sheets",
"@demoBottomSheetSubtitle": {
"description": "Description for bottom sheet demo."
},
"demoBottomSheetPersistentTitle": "Persistent bottom sheet",
"@demoBottomSheetPersistentTitle": {
"description": "Title for persistent bottom sheet demo."
},
"demoBottomSheetPersistentDescription": "A persistent bottom sheet shows information that supplements the primary content of the app. A persistent bottom sheet remains visible even when the user interacts with other parts of the app.",
"@demoBottomSheetPersistentDescription": {
"description": "Description for persistent bottom sheet demo."
},
"demoBottomSheetModalTitle": "Modal bottom sheet",
"@demoBottomSheetModalTitle": {
"description": "Title for modal bottom sheet demo."
},
"demoBottomSheetModalDescription": "A modal bottom sheet is an alternative to a menu or a dialog and prevents the user from interacting with the rest of the app.",
"@demoBottomSheetModalDescription": {
"description": "Description for modal bottom sheet demo."
},
"demoBottomSheetAddLabel": "Add",
"@demoBottomSheetAddLabel": {
"description": "Semantic label for add icon."
},
"demoBottomSheetButtonText": "SHOW BOTTOM SHEET",
"@demoBottomSheetButtonText": {
"description": "Button text to show bottom sheet."
},
"demoBottomSheetHeader": "Header",
"@demoBottomSheetHeader": {
"description": "Generic header placeholder."
},
"demoBottomSheetItem": "Item {value}",
"@demoBottomSheetItem": {
"description": "Generic item placeholder.",
"placeholders": {
"value": {
"example": "1"
}
}
},
"demoListsTitle": "Lists",
"@demoListsTitle": {
"description": "Title for lists demo."
},
"demoListsSubtitle": "Scrolling list layouts",
"@demoListsSubtitle": {
"description": "Subtitle for lists demo."
},
"demoListsDescription": "A single fixed-height row that typically contains some text as well as a leading or trailing icon.",
"@demoListsDescription": {
"description": "Description for lists demo. This describes what a single row in a list consists of."
},
"demoOneLineListsTitle": "One Line",
"@demoOneLineListsTitle": {
"description": "Title for lists demo with only one line of text per row."
},
"demoTwoLineListsTitle": "Two Lines",
"@demoTwoLineListsTitle": {
"description": "Title for lists demo with two lines of text per row."
},
"demoListsSecondary": "Secondary text",
"@demoListsSecondary": {
"description": "Text that appears in the second line of a list item."
},
"demoProgressIndicatorTitle": "Progress indicators",
"@demoProgressIndicatorTitle": {
"description": "Title for progress indicators demo."
},
"demoProgressIndicatorSubtitle": "Linear, circular, indeterminate",
"@demoProgressIndicatorSubtitle": {
"description": "Subtitle for progress indicators demo."
},
"demoCircularProgressIndicatorTitle": "Circular Progress Indicator",
"@demoCircularProgressIndicatorTitle": {
"description": "Title for circular progress indicator demo."
},
"demoCircularProgressIndicatorDescription": "A Material Design circular progress indicator, which spins to indicate that the application is busy.",
"@demoCircularProgressIndicatorDescription": {
"description": "Description for circular progress indicator demo."
},
"demoLinearProgressIndicatorTitle": "Linear Progress Indicator",
"@demoLinearProgressIndicatorTitle": {
"description": "Title for linear progress indicator demo."
},
"demoLinearProgressIndicatorDescription": "A Material Design linear progress indicator, also known as a progress bar.",
"@demoLinearProgressIndicatorDescription": {
"description": "Description for linear progress indicator demo."
},
"demoPickersTitle": "Pickers",
"@demoPickersTitle": {
"description": "Title for pickers demo."
},
"demoPickersSubtitle": "Date and time selection",
"@demoPickersSubtitle": {
"description": "Subtitle for pickers demo."
},
"demoDatePickerTitle": "Date Picker",
"@demoDatePickerTitle": {
"description": "Title for date picker demo."
},
"demoDatePickerDescription": "Shows a dialog containing a Material Design date picker.",
"@demoDatePickerDescription": {
"description": "Description for date picker demo."
},
"demoTimePickerTitle": "Time Picker",
"@demoTimePickerTitle": {
"description": "Title for time picker demo."
},
"demoTimePickerDescription": "Shows a dialog containing a Material Design time picker.",
"@demoTimePickerDescription": {
"description": "Description for time picker demo."
},
"demoDateRangePickerTitle": "Date Range Picker",
"@demoDateRangePickerTitle": {
"description": "Title for date range picker demo."
},
"demoDateRangePickerDescription": "Shows a dialog containing a Material Design date range picker.",
"@demoDateRangePickerDescription": {
"description": "Description for date range picker demo."
},
"demoPickersShowPicker": "SHOW PICKER",
"@demoPickersShowPicker": {
"description": "Button text to show the date or time picker in the demo."
},
"demoTabsTitle": "Tabs",
"@demoTabsTitle": {
"description": "Title for tabs demo."
},
"demoTabsScrollingTitle": "Scrolling",
"@demoTabsScrollingTitle": {
"description": "Title for tabs demo with a tab bar that scrolls."
},
"demoTabsNonScrollingTitle": "Non-scrolling",
"@demoTabsNonScrollingTitle": {
"description": "Title for tabs demo with a tab bar that doesn't scroll."
},
"demoTabsSubtitle": "Tabs with independently scrollable views",
"@demoTabsSubtitle": {
"description": "Subtitle for tabs demo."
},
"demoTabsDescription": "Tabs organize content across different screens, data sets, and other interactions.",
"@demoTabsDescription": {
"description": "Description for tabs demo."
},
"demoSnackbarsTitle": "Snackbars",
"@demoSnackbarsTitle": {
"description": "Title for snackbars demo."
},
"demoSnackbarsSubtitle": "Snackbars show messages at the bottom of the screen",
"@demoSnackbarsSubtitle": {
"description": "Subtitle for snackbars demo."
},
"demoSnackbarsDescription": "Snackbars inform users of a process that an app has performed or will perform. They appear temporarily, towards the bottom of the screen. They shouldn't interrupt the user experience, and they don't require user input to disappear.",
"@demoSnackbarsDescription": {
"description": "Description for snackbars demo."
},
"demoSnackbarsButtonLabel": "SHOW A SNACKBAR",
"@demoSnackbarsButtonLabel": {
"description": "Label for button to show a snackbar."
},
"demoSnackbarsText": "This is a snackbar.",
"@demoSnackbarsText": {
"description": "Text to show on a snackbar."
},
"demoSnackbarsActionButtonLabel": "ACTION",
"@demoSnackbarsActionButtonLabel": {
"description": "Label for action button text on the snackbar."
},
"demoSnackbarsAction": "You pressed the snackbar action.",
"@demoSnackbarsAction": {
"description": "Text that appears when you press on a snackbars' action."
},
"demoSelectionControlsTitle": "Selection controls",
"@demoSelectionControlsTitle": {
"description": "Title for selection controls demo."
},
"demoSelectionControlsSubtitle": "Checkboxes, radio buttons, and switches",
"@demoSelectionControlsSubtitle": {
"description": "Subtitle for selection controls demo."
},
"demoSelectionControlsCheckboxTitle": "Checkbox",
"@demoSelectionControlsCheckboxTitle": {
"description": "Title for the checkbox (selection controls) demo."
},
"demoSelectionControlsCheckboxDescription": "Checkboxes allow the user to select multiple options from a set. A normal checkbox's value is true or false and a tristate checkbox's value can also be null.",
"@demoSelectionControlsCheckboxDescription": {
"description": "Description for the checkbox (selection controls) demo."
},
"demoSelectionControlsRadioTitle": "Radio",
"@demoSelectionControlsRadioTitle": {
"description": "Title for the radio button (selection controls) demo."
},
"demoSelectionControlsRadioDescription": "Radio buttons allow the user to select one option from a set. Use radio buttons for exclusive selection if you think that the user needs to see all available options side-by-side.",
"@demoSelectionControlsRadioDescription": {
"description": "Description for the radio button (selection controls) demo."
},
"demoSelectionControlsSwitchTitle": "Switch",
"@demoSelectionControlsSwitchTitle": {
"description": "Title for the switches (selection controls) demo."
},
"demoSelectionControlsSwitchDescription": "On/off switches toggle the state of a single settings option. The option that the switch controls, as well as the state it's in, should be made clear from the corresponding inline label.",
"@demoSelectionControlsSwitchDescription": {
"description": "Description for the switches (selection controls) demo."
},
"demoBottomTextFieldsTitle": "Text fields",
"@demoBottomTextFieldsTitle": {
"description": "Title for text fields demo."
},
"demoTextFieldTitle": "Text fields",
"@demoTextFieldTitle": {
"description": "Title for text fields demo."
},
"demoTextFieldSubtitle": "Single line of editable text and numbers",
"@demoTextFieldSubtitle": {
"description": "Description for text fields demo."
},
"demoTextFieldDescription": "Text fields allow users to enter text into a UI. They typically appear in forms and dialogs.",
"@demoTextFieldDescription": {
"description": "Description for text fields demo."
},
"demoTextFieldShowPasswordLabel": "Show password",
"@demoTextFieldShowPasswordLabel": {
"description": "Label for show password icon."
},
"demoTextFieldHidePasswordLabel": "Hide password",
"@demoTextFieldHidePasswordLabel": {
"description": "Label for hide password icon."
},
"demoTextFieldFormErrors": "Please fix the errors in red before submitting.",
"@demoTextFieldFormErrors": {
"description": "Text that shows up on form errors."
},
"demoTextFieldNameRequired": "Name is required.",
"@demoTextFieldNameRequired": {
"description": "Shows up as submission error if name is not given in the form."
},
"demoTextFieldOnlyAlphabeticalChars": "Please enter only alphabetical characters.",
"@demoTextFieldOnlyAlphabeticalChars": {
"description": "Error that shows if non-alphabetical characters are given."
},
"demoTextFieldEnterUSPhoneNumber": "(###) ###-#### - Enter a US phone number.",
"@demoTextFieldEnterUSPhoneNumber": {
"description": "Error that shows up if non-valid non-US phone number is given."
},
"demoTextFieldEnterPassword": "Please enter a password.",
"@demoTextFieldEnterPassword": {
"description": "Error that shows up if password is not given."
},
"demoTextFieldPasswordsDoNotMatch": "The passwords don't match",
"@demoTextFieldPasswordsDoNotMatch": {
"description": "Error that shows up, if the re-typed password does not match the already given password."
},
"demoTextFieldWhatDoPeopleCallYou": "What do people call you?",
"@demoTextFieldWhatDoPeopleCallYou": {
"description": "Placeholder for name field in form."
},
"demoTextFieldNameField": "Name*",
"@demoTextFieldNameField": {
"description": "The label for a name input field that is required (hence the star)."
},
"demoTextFieldWhereCanWeReachYou": "Where can we reach you?",
"@demoTextFieldWhereCanWeReachYou": {
"description": "Placeholder for when entering a phone number in a form."
},
"demoTextFieldPhoneNumber": "Phone number*",
"@demoTextFieldPhoneNumber": {
"description": "The label for a phone number input field that is required (hence the star)."
},
"demoTextFieldYourEmailAddress": "Your email address",
"@demoTextFieldYourEmailAddress": {
"description": "The label for an email address input field."
},
"demoTextFieldEmail": "Email",
"@demoTextFieldEmail": {
"description": "The label for an email address input field"
},
"demoTextFieldTellUsAboutYourself": "Tell us about yourself (e.g., write down what you do or what hobbies you have)",
"@demoTextFieldTellUsAboutYourself": {
"description": "The placeholder text for biography/life story input field."
},
"demoTextFieldKeepItShort": "Keep it short, this is just a demo.",
"@demoTextFieldKeepItShort": {
"description": "Helper text for biography/life story input field."
},
"demoTextFieldLifeStory": "Life story",
"@demoTextFieldLifeStory": {
"description": "The label for biography/life story input field."
},
"demoTextFieldSalary": "Salary",
"@demoTextFieldSalary": {
"description": "The label for salary input field."
},
"demoTextFieldUSD": "USD",
"@demoTextFieldUSD": {
"description": "US currency, used as suffix in input field for salary."
},
"demoTextFieldNoMoreThan": "No more than 8 characters.",
"@demoTextFieldNoMoreThan": {
"description": "Helper text for password input field."
},
"demoTextFieldPassword": "Password*",
"@demoTextFieldPassword": {
"description": "Label for password input field, that is required (hence the star)."
},
"demoTextFieldRetypePassword": "Re-type password*",
"@demoTextFieldRetypePassword": {
"description": "Label for repeat password input field."
},
"demoTextFieldSubmit": "SUBMIT",
"@demoTextFieldSubmit": {
"description": "The submit button text for form."
},
"demoTextFieldNameHasPhoneNumber": "{name} phone number is {phoneNumber}",
"@demoTextFieldNameHasPhoneNumber": {
"description": "Text that shows up when valid phone number and name is submitted in form.",
"placeholders": {
"name": {
"example": "Peter"
},
"phoneNumber": {
"phoneNumber": "+1 (000) 000-0000"
}
}
},
"demoTextFieldRequiredField": "* indicates required field",
"@demoTextFieldRequiredField": {
"description": "Helper text to indicate that * means that it is a required field."
},
"demoTooltipTitle": "Tooltips",
"@demoTooltipTitle": {
"description": "Title for tooltip demo."
},
"demoTooltipSubtitle": "Short message displayed on long press or hover",
"@demoTooltipSubtitle": {
"description": "Subtitle for tooltip demo."
},
"demoTooltipDescription": "Tooltips provide text labels that help explain the function of a button or other user interface action. Tooltips display informative text when users hover over, focus on, or long press an element.",
"@demoTooltipDescription": {
"description": "Description for tooltip demo."
},
"demoTooltipInstructions": "Long press or hover to display the tooltip.",
"@demoTooltipInstructions": {
"description": "Instructions for how to trigger a tooltip in the tooltip demo."
},
"bottomNavigationCommentsTab": "Comments",
"@bottomNavigationCommentsTab": {
"description": "Title for Comments tab of bottom navigation."
},
"bottomNavigationCalendarTab": "Calendar",
"@bottomNavigationCalendarTab": {
"description": "Title for Calendar tab of bottom navigation."
},
"bottomNavigationAccountTab": "Account",
"@bottomNavigationAccountTab": {
"description": "Title for Account tab of bottom navigation."
},
"bottomNavigationAlarmTab": "Alarm",
"@bottomNavigationAlarmTab": {
"description": "Title for Alarm tab of bottom navigation."
},
"bottomNavigationCameraTab": "Camera",
"@bottomNavigationCameraTab": {
"description": "Title for Camera tab of bottom navigation."
},
"bottomNavigationContentPlaceholder": "Placeholder for {title} tab",
"@bottomNavigationContentPlaceholder": {
"description": "Accessibility label for the content placeholder in the bottom navigation demo",
"placeholders": {
"title": {
"example": "Account"
}
}
},
"buttonTextCreate": "Create",
"@buttonTextCreate": {
"description": "Tooltip text for a create button."
},
"dialogSelectedOption": "You selected: \"{value}\"",
"@dialogSelectedOption": {
"description": "Message displayed after an option is selected from a dialog",
"placeholders": {
"value": {
"example": "AGREE"
}
}
},
"chipTurnOnLights": "Turn on lights",
"@chipTurnOnLights": {
"description": "A chip component to turn on the lights."
},
"chipSmall": "Small",
"@chipSmall": {
"description": "A chip component to select a small size."
},
"chipMedium": "Medium",
"@chipMedium": {
"description": "A chip component to select a medium size."
},
"chipLarge": "Large",
"@chipLarge": {
"description": "A chip component to select a large size."
},
"chipElevator": "Elevator",
"@chipElevator": {
"description": "A chip component to filter selection by elevators."
},
"chipWasher": "Washer",
"@chipWasher": {
"description": "A chip component to filter selection by washers."
},
"chipFireplace": "Fireplace",
"@chipFireplace": {
"description": "A chip component to filter selection by fireplaces."
},
"chipBiking": "Biking",
"@chipBiking": {
"description": "A chip component to that indicates a biking selection."
},
"demo": "Demo",
"@demo": {
"description": "Used in the title of the demos."
},
"bottomAppBar": "Bottom app bar",
"@bottomAppBar": {
"description": "Used as semantic label for a BottomAppBar."
},
"loading": "Loading",
"@loading": {
"description": "Indicates the loading process."
},
"dialogDiscardTitle": "Discard draft?",
"@dialogDiscardTitle": {
"description": "Alert dialog message to discard draft."
},
"dialogLocationTitle": "Use Google's location service?",
"@dialogLocationTitle": {
"description": "Alert dialog title to use location services."
},
"dialogLocationDescription": "Let Google help apps determine location. This means sending anonymous location data to Google, even when no apps are running.",
"@dialogLocationDescription": {
"description": "Alert dialog description to use location services."
},
"dialogCancel": "CANCEL",
"@dialogCancel": {
"description": "Alert dialog cancel option."
},
"dialogDiscard": "DISCARD",
"@dialogDiscard": {
"description": "Alert dialog discard option."
},
"dialogDisagree": "DISAGREE",
"@dialogDisagree": {
"description": "Alert dialog disagree option."
},
"dialogAgree": "AGREE",
"@dialogAgree": {
"description": "Alert dialog agree option."
},
"dialogSetBackup": "Set backup account",
"@dialogSetBackup": {
"description": "Alert dialog title for setting a backup account."
},
"dialogAddAccount": "Add account",
"@dialogAddAccount": {
"description": "Alert dialog option for adding an account."
},
"dialogShow": "SHOW DIALOG",
"@dialogShow": {
"description": "Button text to display a dialog."
},
"dialogFullscreenTitle": "Full Screen Dialog",
"@dialogFullscreenTitle": {
"description": "Title for full screen dialog demo."
},
"dialogFullscreenSave": "SAVE",
"@dialogFullscreenSave": {
"description": "Save button for full screen dialog demo."
},
"dialogFullscreenDescription": "A full screen dialog demo",
"@dialogFullscreenDescription": {
"description": "Description for full screen dialog demo."
},
"cupertinoButton": "Button",
"@cupertinoButton": {
"description": "Button text for a generic iOS-style button."
},
"cupertinoButtonWithBackground": "With Background",
"@cupertinoButtonWithBackground": {
"description": "Button text for a iOS-style button with a filled background."
},
"cupertinoAlertCancel": "Cancel",
"@cupertinoAlertCancel": {
"description": "iOS-style alert cancel option."
},
"cupertinoAlertDiscard": "Discard",
"@cupertinoAlertDiscard": {
"description": "iOS-style alert discard option."
},
"cupertinoAlertLocationTitle": "Allow \"Maps\" to access your location while you are using the app?",
"@cupertinoAlertLocationTitle": {
"description": "iOS-style alert title for location permission."
},
"cupertinoAlertLocationDescription": "Your current location will be displayed on the map and used for directions, nearby search results, and estimated travel times.",
"@cupertinoAlertLocationDescription": {
"description": "iOS-style alert description for location permission."
},
"cupertinoAlertAllow": "Allow",
"@cupertinoAlertAllow": {
"description": "iOS-style alert allow option."
},
"cupertinoAlertDontAllow": "Don't Allow",
"@cupertinoAlertDontAllow": {
"description": "iOS-style alert don't allow option."
},
"cupertinoAlertFavoriteDessert": "Select Favorite Dessert",
"@cupertinoAlertFavoriteDessert": {
"description": "iOS-style alert title for selecting favorite dessert."
},
"cupertinoAlertDessertDescription": "Please select your favorite type of dessert from the list below. Your selection will be used to customize the suggested list of eateries in your area.",
"@cupertinoAlertDessertDescription": {
"description": "iOS-style alert description for selecting favorite dessert."
},
"cupertinoAlertCheesecake": "Cheesecake",
"@cupertinoAlertCheesecake": {
"description": "iOS-style alert cheesecake option."
},
"cupertinoAlertTiramisu": "Tiramisu",
"@cupertinoAlertTiramisu": {
"description": "iOS-style alert tiramisu option."
},
"cupertinoAlertApplePie": "Apple Pie",
"@cupertinoAlertApplePie": {
"description": "iOS-style alert apple pie option."
},
"cupertinoAlertChocolateBrownie": "Chocolate Brownie",
"@cupertinoAlertChocolateBrownie": {
"description": "iOS-style alert chocolate brownie option."
},
"cupertinoShowAlert": "Show Alert",
"@cupertinoShowAlert": {
"description": "Button text to show iOS-style alert."
},
"colorsRed": "RED",
"@colorsRed": {
"description": "Tab title for the color red."
},
"colorsPink": "PINK",
"@colorsPink": {
"description": "Tab title for the color pink."
},
"colorsPurple": "PURPLE",
"@colorsPurple": {
"description": "Tab title for the color purple."
},
"colorsDeepPurple": "DEEP PURPLE",
"@colorsDeepPurple": {
"description": "Tab title for the color deep purple."
},
"colorsIndigo": "INDIGO",
"@colorsIndigo": {
"description": "Tab title for the color indigo."
},
"colorsBlue": "BLUE",
"@colorsBlue": {
"description": "Tab title for the color blue."
},
"colorsLightBlue": "LIGHT BLUE",
"@colorsLightBlue": {
"description": "Tab title for the color light blue."
},
"colorsCyan": "CYAN",
"@colorsCyan": {
"description": "Tab title for the color cyan."
},
"colorsTeal": "TEAL",
"@colorsTeal": {
"description": "Tab title for the color teal."
},
"colorsGreen": "GREEN",
"@colorsGreen": {
"description": "Tab title for the color green."
},
"colorsLightGreen": "LIGHT GREEN",
"@colorsLightGreen": {
"description": "Tab title for the color light green."
},
"colorsLime": "LIME",
"@colorsLime": {
"description": "Tab title for the color lime."
},
"colorsYellow": "YELLOW",
"@colorsYellow": {
"description": "Tab title for the color yellow."
},
"colorsAmber": "AMBER",
"@colorsAmber": {
"description": "Tab title for the color amber."
},
"colorsOrange": "ORANGE",
"@colorsOrange": {
"description": "Tab title for the color orange."
},
"colorsDeepOrange": "DEEP ORANGE",
"@colorsDeepOrange": {
"description": "Tab title for the color deep orange."
},
"colorsBrown": "BROWN",
"@colorsBrown": {
"description": "Tab title for the color brown."
},
"colorsGrey": "GREY",
"@colorsGrey": {
"description": "Tab title for the color grey."
},
"colorsBlueGrey": "BLUE GREY",
"@colorsBlueGrey": {
"description": "Tab title for the color blue grey."
},
"placeChennai": "Chennai",
"@placeChennai": {
"description": "Title for Chennai location."
},
"placeTanjore": "Tanjore",
"@placeTanjore": {
"description": "Title for Tanjore location."
},
"placeChettinad": "Chettinad",
"@placeChettinad": {
"description": "Title for Chettinad location."
},
"placePondicherry": "Pondicherry",
"@placePondicherry": {
"description": "Title for Pondicherry location."
},
"placeFlowerMarket": "Flower Market",
"@placeFlowerMarket": {
"description": "Title for Flower Market location."
},
"placeBronzeWorks": "Bronze Works",
"@placeBronzeWorks": {
"description": "Title for Bronze Works location."
},
"placeMarket": "Market",
"@placeMarket": {
"description": "Title for Market location."
},
"placeThanjavurTemple": "Thanjavur Temple",
"@placeThanjavurTemple": {
"description": "Title for Thanjavur Temple location."
},
"placeSaltFarm": "Salt Farm",
"@placeSaltFarm": {
"description": "Title for Salt Farm location."
},
"placeScooters": "Scooters",
"@placeScooters": {
"description": "Title for image of people riding on scooters."
},
"placeSilkMaker": "Silk Maker",
"@placeSilkMaker": {
"description": "Title for an image of a silk maker."
},
"placeLunchPrep": "Lunch Prep",
"@placeLunchPrep": {
"description": "Title for an image of preparing lunch."
},
"placeBeach": "Beach",
"@placeBeach": {
"description": "Title for Beach location."
},
"placeFisherman": "Fisherman",
"@placeFisherman": {
"description": "Title for an image of a fisherman."
},
"starterAppTitle": "Starter app",
"@starterAppTitle": {
"description": "The title and name for the starter app."
},
"starterAppDescription": "A responsive starter layout",
"@starterAppDescription": {
"description": "The description for the starter app."
},
"starterAppGenericButton": "BUTTON",
"@starterAppGenericButton": {
"description": "Generic placeholder for button."
},
"starterAppTooltipAdd": "Add",
"@starterAppTooltipAdd": {
"description": "Tooltip on add icon."
},
"starterAppTooltipFavorite": "Favorite",
"@starterAppTooltipFavorite": {
"description": "Tooltip on favorite icon."
},
"starterAppTooltipShare": "Share",
"@starterAppTooltipShare": {
"description": "Tooltip on share icon."
},
"starterAppTooltipSearch": "Search",
"@starterAppTooltipSearch": {
"description": "Tooltip on search icon."
},
"starterAppGenericTitle": "Title",
"@starterAppGenericTitle": {
"description": "Generic placeholder for title in app bar."
},
"starterAppGenericSubtitle": "Subtitle",
"@starterAppGenericSubtitle": {
"description": "Generic placeholder for subtitle in drawer."
},
"starterAppGenericHeadline": "Headline",
"@starterAppGenericHeadline": {
"description": "Generic placeholder for headline in drawer."
},
"starterAppGenericBody": "Body",
"@starterAppGenericBody": {
"description": "Generic placeholder for body text in drawer."
},
"starterAppDrawerItem": "Item {value}",
"@starterAppDrawerItem": {
"description": "Generic placeholder drawer item.",
"placeholders": {
"value": {
"example": "1"
}
}
},
"shrineMenuCaption": "MENU",
"@shrineMenuCaption": {
"description": "Caption for a menu page."
},
"shrineCategoryNameAll": "ALL",
"@shrineCategoryNameAll": {
"description": "A tab showing products from all categories."
},
"shrineCategoryNameAccessories": "ACCESSORIES",
"@shrineCategoryNameAccessories": {
"description": "A category of products consisting of accessories (clothing items)."
},
"shrineCategoryNameClothing": "CLOTHING",
"@shrineCategoryNameClothing": {
"description": "A category of products consisting of clothing."
},
"shrineCategoryNameHome": "HOME",
"@shrineCategoryNameHome": {
"description": "A category of products consisting of items used at home."
},
"shrineLogoutButtonCaption": "LOGOUT",
"@shrineLogoutButtonCaption": {
"description": "Label for a logout button."
},
"shrineLoginUsernameLabel": "Username",
"@shrineLoginUsernameLabel": {
"description": "On the login screen, a label for a textfield for the user to input their username."
},
"shrineLoginPasswordLabel": "Password",
"@shrineLoginPasswordLabel": {
"description": "On the login screen, a label for a textfield for the user to input their password."
},
"shrineCancelButtonCaption": "CANCEL",
"@shrineCancelButtonCaption": {
"description": "On the login screen, the caption for a button to cancel login."
},
"shrineNextButtonCaption": "NEXT",
"@shrineNextButtonCaption": {
"description": "On the login screen, the caption for a button to proceed login."
},
"shrineCartPageCaption": "CART",
"@shrineCartPageCaption": {
"description": "Caption for a shopping cart page."
},
"shrineProductQuantity": "Quantity: {quantity}",
"@shrineProductQuantity": {
"description": "A text showing the number of items for a specific product.",
"placeholders": {
"quantity": {
"example": "3"
}
}
},
"shrineProductPrice": "x {price}",
"@shrineProductPrice": {
"description": "A text showing the unit price of each product. Used as: 'Quantity: 3 x $129'. The currency will be handled by the formatter.",
"placeholders": {
"price": {
"example": "$129"
}
}
},
"shrineCartItemCount": "{quantity, plural, =0{NO ITEMS} =1{1 ITEM} other{{quantity} ITEMS}}",
"@shrineCartItemCount": {
"description": "A text showing the total number of items in the cart.",
"placeholders": {
"quantity": {
"example": "3"
}
}
},
"shrineCartClearButtonCaption": "CLEAR CART",
"@shrineCartClearButtonCaption": {
"description": "Caption for a button used to clear the cart."
},
"shrineCartTotalCaption": "TOTAL",
"@shrineCartTotalCaption": {
"description": "Label for a text showing total price of the items in the cart."
},
"shrineCartSubtotalCaption": "Subtotal:",
"@shrineCartSubtotalCaption": {
"description": "Label for a text showing the subtotal price of the items in the cart (excluding shipping and tax)."
},
"shrineCartShippingCaption": "Shipping:",
"@shrineCartShippingCaption": {
"description": "Label for a text showing the shipping cost for the items in the cart."
},
"shrineCartTaxCaption": "Tax:",
"@shrineCartTaxCaption": {
"description": "Label for a text showing the tax for the items in the cart."
},
"shrineProductVagabondSack": "Vagabond sack",
"@shrineProductVagabondSack": {
"description": "Name of the product 'Vagabond sack'."
},
"shrineProductStellaSunglasses": "Stella sunglasses",
"@shrineProductStellaSunglasses": {
"description": "Name of the product 'Stella sunglasses'."
},
"shrineProductWhitneyBelt": "Whitney belt",
"@shrineProductWhitneyBelt": {
"description": "Name of the product 'Whitney belt'."
},
"shrineProductGardenStrand": "Garden strand",
"@shrineProductGardenStrand": {
"description": "Name of the product 'Garden strand'."
},
"shrineProductStrutEarrings": "Strut earrings",
"@shrineProductStrutEarrings": {
"description": "Name of the product 'Strut earrings'."
},
"shrineProductVarsitySocks": "Varsity socks",
"@shrineProductVarsitySocks": {
"description": "Name of the product 'Varsity socks'."
},
"shrineProductWeaveKeyring": "Weave keyring",
"@shrineProductWeaveKeyring": {
"description": "Name of the product 'Weave keyring'."
},
"shrineProductGatsbyHat": "Gatsby hat",
"@shrineProductGatsbyHat": {
"description": "Name of the product 'Gatsby hat'."
},
"shrineProductShrugBag": "Shrug bag",
"@shrineProductShrugBag": {
"description": "Name of the product 'Shrug bag'."
},
"shrineProductGiltDeskTrio": "Gilt desk trio",
"@shrineProductGiltDeskTrio": {
"description": "Name of the product 'Gilt desk trio'."
},
"shrineProductCopperWireRack": "Copper wire rack",
"@shrineProductCopperWireRack": {
"description": "Name of the product 'Copper wire rack'."
},
"shrineProductSootheCeramicSet": "Soothe ceramic set",
"@shrineProductSootheCeramicSet": {
"description": "Name of the product 'Soothe ceramic set'."
},
"shrineProductHurrahsTeaSet": "Hurrahs tea set",
"@shrineProductHurrahsTeaSet": {
"description": "Name of the product 'Hurrahs tea set'."
},
"shrineProductBlueStoneMug": "Blue stone mug",
"@shrineProductBlueStoneMug": {
"description": "Name of the product 'Blue stone mug'."
},
"shrineProductRainwaterTray": "Rainwater tray",
"@shrineProductRainwaterTray": {
"description": "Name of the product 'Rainwater tray'."
},
"shrineProductChambrayNapkins": "Chambray napkins",
"@shrineProductChambrayNapkins": {
"description": "Name of the product 'Chambray napkins'."
},
"shrineProductSucculentPlanters": "Succulent planters",
"@shrineProductSucculentPlanters": {
"description": "Name of the product 'Succulent planters'."
},
"shrineProductQuartetTable": "Quartet table",
"@shrineProductQuartetTable": {
"description": "Name of the product 'Quartet table'."
},
"shrineProductKitchenQuattro": "Kitchen quattro",
"@shrineProductKitchenQuattro": {
"description": "Name of the product 'Kitchen quattro'."
},
"shrineProductClaySweater": "Clay sweater",
"@shrineProductClaySweater": {
"description": "Name of the product 'Clay sweater'."
},
"shrineProductSeaTunic": "Sea tunic",
"@shrineProductSeaTunic": {
"description": "Name of the product 'Sea tunic'."
},
"shrineProductPlasterTunic": "Plaster tunic",
"@shrineProductPlasterTunic": {
"description": "Name of the product 'Plaster tunic'."
},
"shrineProductWhitePinstripeShirt": "White pinstripe shirt",
"@shrineProductWhitePinstripeShirt": {
"description": "Name of the product 'White pinstripe shirt'."
},
"shrineProductChambrayShirt": "Chambray shirt",
"@shrineProductChambrayShirt": {
"description": "Name of the product 'Chambray shirt'."
},
"shrineProductSeabreezeSweater": "Seabreeze sweater",
"@shrineProductSeabreezeSweater": {
"description": "Name of the product 'Seabreeze sweater'."
},
"shrineProductGentryJacket": "Gentry jacket",
"@shrineProductGentryJacket": {
"description": "Name of the product 'Gentry jacket'."
},
"shrineProductNavyTrousers": "Navy trousers",
"@shrineProductNavyTrousers": {
"description": "Name of the product 'Navy trousers'."
},
"shrineProductWalterHenleyWhite": "Walter henley (white)",
"@shrineProductWalterHenleyWhite": {
"description": "Name of the product 'Walter henley (white)'."
},
"shrineProductSurfAndPerfShirt": "Surf and perf shirt",
"@shrineProductSurfAndPerfShirt": {
"description": "Name of the product 'Surf and perf shirt'."
},
"shrineProductGingerScarf": "Ginger scarf",
"@shrineProductGingerScarf": {
"description": "Name of the product 'Ginger scarf'."
},
"shrineProductRamonaCrossover": "Ramona crossover",
"@shrineProductRamonaCrossover": {
"description": "Name of the product 'Ramona crossover'."
},
"shrineProductChambrayShirt": "Chambray shirt",
"@shrineProductChambrayShirt": {
"description": "Name of the product 'Chambray shirt'."
},
"shrineProductClassicWhiteCollar": "Classic white collar",
"@shrineProductClassicWhiteCollar": {
"description": "Name of the product 'Classic white collar'."
},
"shrineProductCeriseScallopTee": "Cerise scallop tee",
"@shrineProductCeriseScallopTee": {
"description": "Name of the product 'Cerise scallop tee'."
},
"shrineProductShoulderRollsTee": "Shoulder rolls tee",
"@shrineProductShoulderRollsTee": {
"description": "Name of the product 'Shoulder rolls tee'."
},
"shrineProductGreySlouchTank": "Grey slouch tank",
"@shrineProductGreySlouchTank": {
"description": "Name of the product 'Grey slouch tank'."
},
"shrineProductSunshirtDress": "Sunshirt dress",
"@shrineProductSunshirtDress": {
"description": "Name of the product 'Sunshirt dress'."
},
"shrineProductFineLinesTee": "Fine lines tee",
"@shrineProductFineLinesTee": {
"description": "Name of the product 'Fine lines tee'."
},
"shrineTooltipSearch": "Search",
"@shrineTooltipSearch": {
"description": "The tooltip text for a search button. Also used as a semantic label, used by screen readers, such as TalkBack and VoiceOver."
},
"shrineTooltipSettings": "Settings",
"@shrineTooltipSettings": {
"description": "The tooltip text for a settings button. Also used as a semantic label, used by screen readers, such as TalkBack and VoiceOver."
},
"shrineTooltipOpenMenu": "Open menu",
"@shrineTooltipOpenMenu": {
"description": "The tooltip text for a menu button. Also used as a semantic label, used by screen readers, such as TalkBack and VoiceOver."
},
"shrineTooltipCloseMenu": "Close menu",
"@shrineTooltipCloseMenu": {
"description": "The tooltip text for a button to close a menu. Also used as a semantic label, used by screen readers, such as TalkBack and VoiceOver."
},
"shrineTooltipCloseCart": "Close cart",
"@shrineTooltipCloseCart": {
"description": "The tooltip text for a button to close the shopping cart page. Also used as a semantic label, used by screen readers, such as TalkBack and VoiceOver."
},
"shrineScreenReaderCart": "{quantity, plural, =0{Shopping cart, no items} =1{Shopping cart, 1 item} other{Shopping cart, {quantity} items}}",
"@shrineScreenReaderCart": {
"description": "The description of a shopping cart button containing some products. Used by screen readers, such as TalkBack and VoiceOver.",
"placeholders": {
"quantity": {
"example": "3"
}
}
},
"shrineScreenReaderProductAddToCart": "Add to cart",
"@shrineScreenReaderProductAddToCart": {
"description": "An announcement made by screen readers, such as TalkBack and VoiceOver to indicate the action of a button for adding a product to the cart."
},
"shrineScreenReaderRemoveProductButton": "Remove {product}",
"@shrineScreenReaderRemoveProductButton": {
"description": "A tooltip for a button to remove a product. This will be read by screen readers, such as TalkBack and VoiceOver when a product is added to the shopping cart.",
"placeholders": {
"product": {
"example": "Ginger scarf"
}
}
},
"shrineTooltipRemoveItem": "Remove item",
"@shrineTooltipRemoveItem": {
"description": "The tooltip text for a button to remove an item (a product) in a shopping cart. Also used as a semantic label, used by screen readers, such as TalkBack and VoiceOver."
},
"craneFormDiners": "Diners",
"@craneFormDiners": {
"description": "Form field label to enter the number of diners."
},
"craneFormDate": "Select Date",
"@craneFormDate": {
"description": "Form field label to select a date."
},
"craneFormTime": "Select Time",
"@craneFormTime": {
"description": "Form field label to select a time."
},
"craneFormLocation": "Select Location",
"@craneFormLocation": {
"description": "Form field label to select a location."
},
"craneFormTravelers": "Travelers",
"@craneFormTravelers": {
"description": "Form field label to select the number of travellers."
},
"craneFormOrigin": "Choose Origin",
"@craneFormOrigin": {
"description": "Form field label to choose a travel origin."
},
"craneFormDestination": "Choose Destination",
"@craneFormDestination": {
"description": "Form field label to choose a travel destination."
},
"craneFormDates": "Select Dates",
"@craneFormDates": {
"description": "Form field label to select multiple dates."
},
"craneHours": "{hours, plural, =1{1h} other{{hours}h}}",
"@craneHours": {
"description": "Generic text for an amount of hours, abbreviated to the shortest form. For example 1h. {hours} should remain untranslated.",
"placeholders": {
"hours": {
"example": "1"
}
}
},
"craneMinutes": "{minutes, plural, =1{1m} other{{minutes}m}}",
"@craneMinutes": {
"description": "Generic text for an amount of minutes, abbreviated to the shortest form. For example 15m. {minutes} should remain untranslated.",
"placeholders": {
"minutes": {
"example": "15"
}
}
},
"craneFlightDuration": "{hoursShortForm} {minutesShortForm}",
"@craneFlightDuration": {
"description": "A pattern to define the layout of a flight duration string. For example in English one might say 1h 15m. Translation should only rearrange the inputs. {hoursShortForm} would for example be replaced by 1h, already translated to the given locale. {minutesShortForm} would for example be replaced by 15m, already translated to the given locale.",
"placeholders": {
"hoursShortForm": {
"example": "1h"
},
"minutesShortForm": {
"example": "15m"
}
}
},
"craneFly": "FLY",
"@craneFly": {
"description": "Title for FLY tab."
},
"craneSleep": "SLEEP",
"@craneSleep": {
"description": "Title for SLEEP tab."
},
"craneEat": "EAT",
"@craneEat": {
"description": "Title for EAT tab."
},
"craneFlySubhead": "Explore Flights by Destination",
"@craneFlySubhead": {
"description": "Subhead for FLY tab."
},
"craneSleepSubhead": "Explore Properties by Destination",
"@craneSleepSubhead": {
"description": "Subhead for SLEEP tab."
},
"craneEatSubhead": "Explore Restaurants by Destination",
"@craneEatSubhead": {
"description": "Subhead for EAT tab."
},
"craneFlyStops": "{numberOfStops, plural, =0{Nonstop} =1{1 stop} other{{numberOfStops} stops}}",
"@craneFlyStops": {
"description": "Label indicating if a flight is nonstop or how many layovers it includes.",
"placeholders": {
"numberOfStops": {
"example": "2"
}
}
},
"craneSleepProperties": "{totalProperties, plural, =0{No Available Properties} =1{1 Available Properties} other{{totalProperties} Available Properties}}",
"@craneSleepProperties": {
"description": "Text indicating the number of available properties (temporary rentals). Always plural.",
"placeholders": {
"totalProperties": {
"example": "100"
}
}
},
"craneEatRestaurants": "{totalRestaurants, plural, =0{No Restaurants} =1{1 Restaurant} other{{totalRestaurants} Restaurants}}",
"@craneEatRestaurants": {
"description": "Text indicating the number of restaurants. Always plural.",
"placeholders": {
"totalRestaurants": {
"example": "100"
}
}
},
"craneFly0": "Aspen, United States",
"@craneFly0": {
"description": "Label for city."
},
"craneFly1": "Big Sur, United States",
"@craneFly1": {
"description": "Label for city."
},
"craneFly2": "Khumbu Valley, Nepal",
"@craneFly2": {
"description": "Label for city."
},
"craneFly3": "Machu Picchu, Peru",
"@craneFly3": {
"description": "Label for city."
},
"craneFly4": "Malé, Maldives",
"@craneFly4": {
"description": "Label for city."
},
"craneFly5": "Vitznau, Switzerland",
"@craneFly5": {
"description": "Label for city."
},
"craneFly6": "Mexico City, Mexico",
"@craneFly6": {
"description": "Label for city."
},
"craneFly7": "Mount Rushmore, United States",
"@craneFly7": {
"description": "Label for city."
},
"craneFly8": "Singapore",
"@craneFly8": {
"description": "Label for city."
},
"craneFly9": "Havana, Cuba",
"@craneFly9": {
"description": "Label for city."
},
"craneFly10": "Cairo, Egypt",
"@craneFly10": {
"description": "Label for city."
},
"craneFly11": "Lisbon, Portugal",
"@craneFly11": {
"description": "Label for city."
},
"craneFly12": "Napa, United States",
"@craneFly12": {
"description": "Label for city."
},
"craneFly13": "Bali, Indonesia",
"@craneFly13": {
"description": "Label for city."
},
"craneSleep0": "Malé, Maldives",
"@craneSleep0": {
"description": "Label for city."
},
"craneSleep1": "Aspen, United States",
"@craneSleep1": {
"description": "Label for city."
},
"craneSleep2": "Machu Picchu, Peru",
"@craneSleep2": {
"description": "Label for city."
},
"craneSleep3": "Havana, Cuba",
"@craneSleep3": {
"description": "Label for city."
},
"craneSleep4": "Vitznau, Switzerland",
"@craneSleep4": {
"description": "Label for city."
},
"craneSleep5": "Big Sur, United States",
"@craneSleep5": {
"description": "Label for city."
},
"craneSleep6": "Napa, United States",
"@craneSleep6": {
"description": "Label for city."
},
"craneSleep7": "Porto, Portugal",
"@craneSleep7": {
"description": "Label for city."
},
"craneSleep8": "Tulum, Mexico",
"@craneSleep8": {
"description": "Label for city."
},
"craneSleep9": "Lisbon, Portugal",
"@craneSleep9": {
"description": "Label for city."
},
"craneSleep10": "Cairo, Egypt",
"@craneSleep10": {
"description": "Label for city."
},
"craneSleep11": "Taipei, Taiwan",
"@craneSleep11": {
"description": "Label for city."
},
"craneEat0": "Naples, Italy",
"@craneEat0": {
"description": "Label for city."
},
"craneEat1": "Dallas, United States",
"@craneEat1": {
"description": "Label for city."
},
"craneEat2": "Córdoba, Argentina",
"@craneEat2": {
"description": "Label for city."
},
"craneEat3": "Portland, United States",
"@craneEat3": {
"description": "Label for city."
},
"craneEat4": "Paris, France",
"@craneEat4": {
"description": "Label for city."
},
"craneEat5": "Seoul, South Korea",
"@craneEat5": {
"description": "Label for city."
},
"craneEat6": "Seattle, United States",
"@craneEat6": {
"description": "Label for city."
},
"craneEat7": "Nashville, United States",
"@craneEat7": {
"description": "Label for city."
},
"craneEat8": "Atlanta, United States",
"@craneEat8": {
"description": "Label for city."
},
"craneEat9": "Madrid, Spain",
"@craneEat9": {
"description": "Label for city."
},
"craneEat10": "Lisbon, Portugal",
"@craneEat10": {
"description": "Label for city."
},
"craneFly0SemanticLabel": "Chalet in a snowy landscape with evergreen trees",
"@craneFly0SemanticLabel": {
"description": "Semantic label for an image."
},
"craneFly1SemanticLabel": "Tent in a field",
"@craneFly1SemanticLabel": {
"description": "Semantic label for an image."
},
"craneFly2SemanticLabel": "Prayer flags in front of snowy mountain",
"@craneFly2SemanticLabel": {
"description": "Semantic label for an image."
},
"craneFly3SemanticLabel": "Machu Picchu citadel",
"@craneFly3SemanticLabel": {
"description": "Semantic label for an image."
},
"craneFly4SemanticLabel": "Overwater bungalows",
"@craneFly4SemanticLabel": {
"description": "Semantic label for an image."
},
"craneFly5SemanticLabel": "Lake-side hotel in front of mountains",
"@craneFly5SemanticLabel": {
"description": "Semantic label for an image."
},
"craneFly6SemanticLabel": "Aerial view of Palacio de Bellas Artes",
"@craneFly6SemanticLabel": {
"description": "Semantic label for an image."
},
"craneFly7SemanticLabel": "Mount Rushmore",
"@craneFly7SemanticLabel": {
"description": "Semantic label for an image."
},
"craneFly8SemanticLabel": "Supertree Grove",
"@craneFly8SemanticLabel": {
"description": "Semantic label for an image."
},
"craneFly9SemanticLabel": "Man leaning on an antique blue car",
"@craneFly9SemanticLabel": {
"description": "Semantic label for an image."
},
"craneFly10SemanticLabel": "Al-Azhar Mosque towers during sunset",
"@craneFly10SemanticLabel": {
"description": "Semantic label for an image."
},
"craneFly11SemanticLabel": "Brick lighthouse at sea",
"@craneFly11SemanticLabel": {
"description": "Semantic label for an image."
},
"craneFly12SemanticLabel": "Pool with palm trees",
"@craneFly12SemanticLabel": {
"description": "Semantic label for an image."
},
"craneFly13SemanticLabel": "Sea-side pool with palm trees",
"@craneFly13SemanticLabel": {
"description": "Semantic label for an image."
},
"craneSleep0SemanticLabel": "Overwater bungalows",
"@craneSleep0SemanticLabel": {
"description": "Semantic label for an image."
},
"craneSleep1SemanticLabel": "Chalet in a snowy landscape with evergreen trees",
"@craneSleep1SemanticLabel": {
"description": "Semantic label for an image."
},
"craneSleep2SemanticLabel": "Machu Picchu citadel",
"@craneSleep2SemanticLabel": {
"description": "Semantic label for an image."
},
"craneSleep3SemanticLabel": "Man leaning on an antique blue car",
"@craneSleep3SemanticLabel": {
"description": "Semantic label for an image."
},
"craneSleep4SemanticLabel": "Lake-side hotel in front of mountains",
"@craneSleep4SemanticLabel": {
"description": "Semantic label for an image."
},
"craneSleep5SemanticLabel": "Tent in a field",
"@craneSleep5SemanticLabel": {
"description": "Semantic label for an image."
},
"craneSleep6SemanticLabel": "Pool with palm trees",
"@craneSleep6SemanticLabel": {
"description": "Semantic label for an image."
},
"craneSleep7SemanticLabel": "Colorful apartments at Riberia Square",
"@craneSleep7SemanticLabel": {
"description": "Semantic label for an image."
},
"craneSleep8SemanticLabel": "Mayan ruins on a cliff above a beach",
"@craneSleep8SemanticLabel": {
"description": "Semantic label for an image."
},
"craneSleep9SemanticLabel": "Brick lighthouse at sea",
"@craneSleep9SemanticLabel": {
"description": "Semantic label for an image."
},
"craneSleep10SemanticLabel": "Al-Azhar Mosque towers during sunset",
"@craneSleep10SemanticLabel": {
"description": "Semantic label for an image."
},
"craneSleep11SemanticLabel": "Taipei 101 skyscraper",
"@craneSleep11SemanticLabel": {
"description": "Semantic label for an image."
},
"craneEat0SemanticLabel": "Pizza in a wood-fired oven",
"@craneEat0SemanticLabel": {
"description": "Semantic label for an image."
},
"craneEat1SemanticLabel": "Empty bar with diner-style stools",
"@craneEat1SemanticLabel": {
"description": "Semantic label for an image."
},
"craneEat2SemanticLabel": "Burger",
"@craneEat2SemanticLabel": {
"description": "Semantic label for an image."
},
"craneEat3SemanticLabel": "Korean taco",
"@craneEat3SemanticLabel": {
"description": "Semantic label for an image."
},
"craneEat4SemanticLabel": "Chocolate dessert",
"@craneEat4SemanticLabel": {
"description": "Semantic label for an image."
},
"craneEat5SemanticLabel": "Artsy restaurant seating area",
"@craneEat5SemanticLabel": {
"description": "Semantic label for an image."
},
"craneEat6SemanticLabel": "Shrimp dish",
"@craneEat6SemanticLabel": {
"description": "Semantic label for an image."
},
"craneEat7SemanticLabel": "Bakery entrance",
"@craneEat7SemanticLabel": {
"description": "Semantic label for an image."
},
"craneEat8SemanticLabel": "Plate of crawfish",
"@craneEat8SemanticLabel": {
"description": "Semantic label for an image."
},
"craneEat9SemanticLabel": "Cafe counter with pastries",
"@craneEat9SemanticLabel": {
"description": "Semantic label for an image."
},
"craneEat10SemanticLabel": "Woman holding huge pastrami sandwich",
"@craneEat10SemanticLabel": {
"description": "Semantic label for an image."
},
"fortnightlyMenuFrontPage": "Front Page",
"@fortnightlyMenuFrontPage": {
"description": "Menu item for the front page of the news app."
},
"fortnightlyMenuWorld": "World",
"@fortnightlyMenuWorld": {
"description": "Menu item for the world news section of the news app."
},
"fortnightlyMenuUS": "US",
"@fortnightlyMenuUS": {
"description": "Menu item for the United States news section of the news app."
},
"fortnightlyMenuPolitics": "Politics",
"@fortnightlyMenuPolitics": {
"description": "Menu item for the political news section of the news app."
},
"fortnightlyMenuBusiness": "Business",
"@fortnightlyMenuBusiness": {
"description": "Menu item for the business news section of the news app."
},
"fortnightlyMenuTech": "Tech",
"@fortnightlyMenuTech": {
"description": "Menu item for the tech news section of the news app."
},
"fortnightlyMenuScience": "Science",
"@fortnightlyMenuScience": {
"description": "Menu item for the science news section of the news app."
},
"fortnightlyMenuSports": "Sports",
"@fortnightlyMenuSports": {
"description": "Menu item for the sports news section of the news app."
},
"fortnightlyMenuTravel": "Travel",
"@fortnightlyMenuTravel": {
"description": "Menu item for the travel news section of the news app."
},
"fortnightlyMenuCulture": "Culture",
"@fortnightlyMenuCulture": {
"description": "Menu item for the culture news section of the news app."
},
"fortnightlyTrendingTechDesign": "TechDesign",
"@fortnightlyTrendingTechDesign": {
"description": "Hashtag for the tech design trending topic of the news app."
},
"fortnightlyTrendingReform": "Reform",
"@fortnightlyTrendingReform": {
"description": "Hashtag for the reform trending topic of the news app."
},
"fortnightlyTrendingHealthcareRevolution": "HealthcareRevolution",
"@fortnightlyTrendingHealthcareRevolution": {
"description": "Hashtag for the healthcare revolution trending topic of the news app."
},
"fortnightlyTrendingGreenArmy": "GreenArmy",
"@fortnightlyTrendingGreenArmy": {
"description": "Hashtag for the green army trending topic of the news app."
},
"fortnightlyTrendingStocks": "Stocks",
"@fortnightlyTrendingStocks": {
"description": "Hashtag for the stocks trending topic of the news app."
},
"fortnightlyLatestUpdates": "Latest Updates",
"@fortnightlyLatestUpdates": {
"description": "Title for news section regarding the latest updates."
},
"fortnightlyHeadlineHealthcare": "The Quiet, Yet Powerful Healthcare Revolution",
"@fortnightlyHeadlineHealthcare": {
"description": "Headline for a news article about healthcare."
},
"fortnightlyHeadlineWar": "Divided American Lives During War",
"@fortnightlyHeadlineWar": {
"description": "Headline for a news article about war."
},
"fortnightlyHeadlineGasoline": "The Future of Gasoline",
"@fortnightlyHeadlineGasoline": {
"description": "Headline for a news article about gasoline."
},
"fortnightlyHeadlineArmy": "Reforming The Green Army From Within",
"@fortnightlyHeadlineArmy": {
"description": "Headline for a news article about the green army."
},
"fortnightlyHeadlineStocks": "As Stocks Stagnate, Many Look To Currency",
"@fortnightlyHeadlineStocks": {
"description": "Headline for a news article about stocks."
},
"fortnightlyHeadlineFabrics": "Designers Use Tech To Make Futuristic Fabrics",
"@fortnightlyHeadlineFabrics": {
"description": "Headline for a news article about fabric."
},
"fortnightlyHeadlineFeminists": "Feminists Take On Partisanship",
"@fortnightlyHeadlineFeminists": {
"description": "Headline for a news article about feminists and partisanship."
},
"fortnightlyHeadlineBees": "Farmland Bees In Short Supply",
"@fortnightlyHeadlineBees": {
"description": "Headline for a news article about bees."
},
"replyInboxLabel": "Inbox",
"@replyInboxLabel": {
"description": "Text label for Inbox destination."
},
"replyStarredLabel": "Starred",
"@replyStarredLabel": {
"description": "Text label for Starred destination."
},
"replySentLabel": "Sent",
"@replySentLabel": {
"description": "Text label for Sent destination."
},
"replyTrashLabel": "Trash",
"@replyTrashLabel": {
"description": "Text label for Trash destination."
},
"replySpamLabel": "Spam",
"@replySpamLabel": {
"description": "Text label for Spam destination."
},
"replyDraftsLabel": "Drafts",
"@replyDraftsLabel": {
"description": "Text label for Drafts destination."
},
"demoTwoPaneFoldableLabel": "Foldable",
"@demoTwoPaneFoldableLabel": {
"description": "Option title for TwoPane demo on foldable devices."
},
"demoTwoPaneFoldableDescription": "This is how TwoPane behaves on a foldable device.",
"@demoTwoPaneFoldableDescription": {
"description": "Description for the foldable option configuration on the TwoPane demo."
},
"demoTwoPaneSmallScreenLabel": "Small Screen",
"@demoTwoPaneSmallScreenLabel": {
"description": "Option title for TwoPane demo in small screen mode. Counterpart of the foldable option."
},
"demoTwoPaneSmallScreenDescription": "This is how TwoPane behaves on a small screen device.",
"@demoTwoPaneSmallScreenDescription": {
"description": "Description for the small screen option configuration on the TwoPane demo."
},
"demoTwoPaneTabletLabel": "Tablet / Desktop",
"@demoTwoPaneTabletLabel": {
"description": "Option title for TwoPane demo in tablet or desktop mode."
},
"demoTwoPaneTabletDescription": "This is how TwoPane behaves on a larger screen like a tablet or desktop.",
"@demoTwoPaneTabletDescription": {
"description": "Description for the tablet / desktop option configuration on the TwoPane demo."
},
"demoTwoPaneTitle": "TwoPane",
"@demoTwoPaneTitle": {
"description": "Title for the TwoPane widget demo."
},
"demoTwoPaneSubtitle": "Responsive layouts on foldable, large, and small screens",
"@demoTwoPaneSubtitle": {
"description": "Subtitle for the TwoPane widget demo."
},
"splashSelectDemo": "Select a demo",
"@splashSelectDemo": {
"description": "Tip for user, visible on the right side of the splash screen when Gallery runs on a foldable device."
},
"demoTwoPaneList": "List",
"@demoTwoPaneList": {
"description": "Title of one of the panes in the TwoPane demo. It sits on top of a list of items."
},
"demoTwoPaneDetails": "Details",
"@demoTwoPaneDetails": {
"description": "Title of one of the panes in the TwoPane demo, which shows details of the currently selected item."
},
"demoTwoPaneSelectItem": "Select an item",
"@demoTwoPaneSelectItem": {
"description": "Tip for user, visible on the right side of the TwoPane widget demo in the foldable configuration."
},
"demoTwoPaneItem": "Item {value}",
"@demoTwoPaneItem": {
"description": "Generic item placeholder visible in the TwoPane widget demo.",
"placeholders": {
"value": {
"example": "1"
}
}
},
"demoTwoPaneItemDetails": "Item {value} details",
"@demoTwoPaneItemDetails": {
"description": "Generic item description or details visible in the TwoPane widget demo.",
"placeholders": {
"value": {
"example": "1"
}
}
}
}
| flutter/dev/integration_tests/new_gallery/lib/l10n/intl_en.arb/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/l10n/intl_en.arb",
"repo_id": "flutter",
"token_count": 42913
} | 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 'dart:collection';
import 'package:flutter/material.dart';
// Common constants between SlowMotionSetting and SettingsListItem.
final BorderRadius settingItemBorderRadius = BorderRadius.circular(10);
const EdgeInsetsDirectional settingItemHeaderMargin = EdgeInsetsDirectional.fromSTEB(32, 0, 32, 8);
class DisplayOption {
DisplayOption(this.title, {this.subtitle});
final String title;
final String? subtitle;
}
class ToggleSetting extends StatelessWidget {
const ToggleSetting({
super.key,
required this.text,
required this.value,
required this.onChanged,
});
final String text;
final bool value;
final void Function(bool) onChanged;
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
final TextTheme textTheme = Theme.of(context).textTheme;
return Semantics(
container: true,
child: Container(
margin: settingItemHeaderMargin,
child: Material(
shape: RoundedRectangleBorder(borderRadius: settingItemBorderRadius),
color: colorScheme.secondary,
clipBehavior: Clip.antiAlias,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SelectableText(
text,
style: textTheme.titleMedium!.apply(
color: colorScheme.onSurface,
),
),
],
),
),
),
Padding(
padding: const EdgeInsetsDirectional.only(end: 8),
child: Switch(
activeColor: colorScheme.primary,
value: value,
onChanged: onChanged,
),
),
],
),
),
),
);
}
}
class SettingsListItem<T> extends StatefulWidget {
const SettingsListItem({
super.key,
required this.optionsMap,
required this.title,
required this.selectedOption,
required this.onOptionChanged,
required this.onTapSetting,
required this.isExpanded,
});
final LinkedHashMap<T, DisplayOption> optionsMap;
final String title;
final T selectedOption;
final ValueChanged<T> onOptionChanged;
final void Function() onTapSetting;
final bool isExpanded;
@override
State<SettingsListItem<T?>> createState() => _SettingsListItemState<T?>();
}
class _SettingsListItemState<T> extends State<SettingsListItem<T?>>
with SingleTickerProviderStateMixin {
static final Animatable<double> _easeInTween =
CurveTween(curve: Curves.easeIn);
static const Duration _expandDuration = Duration(milliseconds: 150);
late AnimationController _controller;
late Animation<double> _childrenHeightFactor;
late Animation<double> _headerChevronRotation;
late Animation<double> _headerSubtitleHeight;
late Animation<EdgeInsetsGeometry> _headerMargin;
late Animation<EdgeInsetsGeometry> _headerPadding;
late Animation<EdgeInsetsGeometry> _childrenPadding;
late Animation<BorderRadius?> _headerBorderRadius;
// For ease of use. Correspond to the keys and values of `widget.optionsMap`.
late Iterable<T?> _options;
late Iterable<DisplayOption> _displayOptions;
@override
void initState() {
super.initState();
_controller = AnimationController(duration: _expandDuration, vsync: this);
_childrenHeightFactor = _controller.drive(_easeInTween);
_headerChevronRotation =
Tween<double>(begin: 0, end: 0.5).animate(_controller);
_headerMargin = EdgeInsetsGeometryTween(
begin: settingItemHeaderMargin,
end: EdgeInsets.zero,
).animate(_controller);
_headerPadding = EdgeInsetsGeometryTween(
begin: const EdgeInsetsDirectional.fromSTEB(16, 10, 0, 10),
end: const EdgeInsetsDirectional.fromSTEB(32, 18, 32, 20),
).animate(_controller);
_headerSubtitleHeight =
_controller.drive(Tween<double>(begin: 1.0, end: 0.0));
_childrenPadding = EdgeInsetsGeometryTween(
begin: const EdgeInsets.symmetric(horizontal: 32),
end: EdgeInsets.zero,
).animate(_controller);
_headerBorderRadius = BorderRadiusTween(
begin: settingItemBorderRadius,
end: BorderRadius.zero,
).animate(_controller);
if (widget.isExpanded) {
_controller.value = 1.0;
}
_options = widget.optionsMap.keys;
_displayOptions = widget.optionsMap.values;
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _handleExpansion() {
if (widget.isExpanded) {
_controller.forward();
} else {
_controller.reverse().then<void>((void value) {
if (!mounted) {
return;
}
});
}
}
Widget _buildHeaderWithChildren(BuildContext context, Widget? child) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
_CategoryHeader(
margin: _headerMargin.value,
padding: _headerPadding.value,
borderRadius: _headerBorderRadius.value!,
subtitleHeight: _headerSubtitleHeight,
chevronRotation: _headerChevronRotation,
title: widget.title,
subtitle: widget.optionsMap[widget.selectedOption]?.title ?? '',
onTap: () => widget.onTapSetting(),
),
Padding(
padding: _childrenPadding.value,
child: ClipRect(
child: Align(
heightFactor: _childrenHeightFactor.value,
child: child,
),
),
),
],
);
}
@override
Widget build(BuildContext context) {
_handleExpansion();
final ThemeData theme = Theme.of(context);
return AnimatedBuilder(
animation: _controller.view,
builder: _buildHeaderWithChildren,
child: Container(
constraints: const BoxConstraints(maxHeight: 384),
margin: const EdgeInsetsDirectional.only(start: 24, bottom: 40),
decoration: BoxDecoration(
border: BorderDirectional(
start: BorderSide(
width: 2,
color: theme.colorScheme.background,
),
),
),
child: ListView.builder(
shrinkWrap: true,
itemCount: widget.isExpanded ? _options.length : 0,
itemBuilder: (BuildContext context, int index) {
final DisplayOption displayOption = _displayOptions.elementAt(index);
return RadioListTile<T?>(
value: _options.elementAt(index),
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
displayOption.title,
style: theme.textTheme.bodyLarge!.copyWith(
color: Theme.of(context).colorScheme.onPrimary,
),
),
if (displayOption.subtitle != null)
Text(
displayOption.subtitle!,
style: theme.textTheme.bodyLarge!.copyWith(
fontSize: 12,
color: Theme.of(context)
.colorScheme
.onPrimary
.withOpacity(0.8),
),
),
],
),
groupValue: widget.selectedOption,
onChanged: (T? newOption) => widget.onOptionChanged(newOption),
activeColor: Theme.of(context).colorScheme.primary,
dense: true,
);
},
),
),
);
}
}
class _CategoryHeader extends StatelessWidget {
const _CategoryHeader({
this.margin,
required this.padding,
required this.borderRadius,
required this.subtitleHeight,
required this.chevronRotation,
required this.title,
required this.subtitle,
this.onTap,
});
final EdgeInsetsGeometry? margin;
final EdgeInsetsGeometry padding;
final BorderRadiusGeometry borderRadius;
final String title;
final String subtitle;
final Animation<double> subtitleHeight;
final Animation<double> chevronRotation;
final GestureTapCallback? onTap;
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
final TextTheme textTheme = Theme.of(context).textTheme;
return Container(
margin: margin,
child: Material(
shape: RoundedRectangleBorder(borderRadius: borderRadius),
color: colorScheme.secondary,
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Padding(
padding: padding,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
title,
style: textTheme.titleMedium!.apply(
color: colorScheme.onSurface,
),
),
SizeTransition(
sizeFactor: subtitleHeight,
child: Text(
subtitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: textTheme.labelSmall!.apply(
color: colorScheme.primary,
),
),
)
],
),
),
),
Padding(
padding: const EdgeInsetsDirectional.only(
start: 8,
end: 24,
),
child: RotationTransition(
turns: chevronRotation,
child: const Icon(Icons.arrow_drop_down),
),
)
],
),
),
),
);
}
}
| flutter/dev/integration_tests/new_gallery/lib/pages/settings_list_item.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/pages/settings_list_item.dart",
"repo_id": "flutter",
"token_count": 5108
} | 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_localizations.dart';
import 'backlayer.dart';
import 'header_form.dart';
class SleepForm extends BackLayerItem {
const SleepForm({super.key}) : super(index: 1);
@override
State<SleepForm> createState() => _SleepFormState();
}
class _SleepFormState extends State<SleepForm> with RestorationMixin {
final RestorableTextEditingController travelerController = RestorableTextEditingController();
final RestorableTextEditingController dateController = RestorableTextEditingController();
final RestorableTextEditingController locationController = RestorableTextEditingController();
@override
String get restorationId => 'sleep_form';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(travelerController, 'diner_controller');
registerForRestoration(dateController, 'date_controller');
registerForRestoration(locationController, 'time_controller');
}
@override
void dispose() {
travelerController.dispose();
dateController.dispose();
locationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
return HeaderForm(
fields: <HeaderFormField>[
HeaderFormField(
index: 0,
iconData: Icons.person,
title: localizations.craneFormTravelers,
textController: travelerController.value,
),
HeaderFormField(
index: 1,
iconData: Icons.date_range,
title: localizations.craneFormDates,
textController: dateController.value,
),
HeaderFormField(
index: 2,
iconData: Icons.hotel,
title: localizations.craneFormLocation,
textController: locationController.value,
),
],
);
}
}
| flutter/dev/integration_tests/new_gallery/lib/studies/crane/sleep_form.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/crane/sleep_form.dart",
"repo_id": "flutter",
"token_count": 717
} | 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 '../../../gallery_localizations.dart';
import '../charts/pie_chart.dart';
import '../data.dart';
import '../finance.dart';
import 'sidebar.dart';
/// A page that shows a summary of accounts.
class AccountsView extends StatelessWidget {
const AccountsView({super.key});
@override
Widget build(BuildContext context) {
final List<AccountData> items = DummyDataService.getAccountDataList(context);
final List<UserDetailData> detailItems = DummyDataService.getAccountDetailList(context);
final double balanceTotal = sumAccountDataPrimaryAmount(items);
return TabWithSidebar(
restorationId: 'accounts_view',
mainView: FinancialEntityView(
heroLabel: GalleryLocalizations.of(context)!.rallyAccountTotal,
heroAmount: balanceTotal,
segments: buildSegmentsFromAccountItems(items),
wholeAmount: balanceTotal,
financialEntityCards: buildAccountDataListViews(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/accounts.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/rally/tabs/accounts.dart",
"repo_id": "flutter",
"token_count": 444
} | 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';
class ProfileAvatar extends StatelessWidget {
const ProfileAvatar({
super.key,
required this.avatar,
this.radius = 20,
});
final String avatar;
final double radius;
@override
Widget build(BuildContext context) {
return Material(
color: Colors.transparent,
child: CircleAvatar(
radius: radius,
backgroundColor: Theme.of(context).cardColor,
child: ClipOval(
child: Image.asset(
avatar,
gaplessPlayback: true,
package: 'flutter_gallery_assets',
height: 42,
width: 42,
fit: BoxFit.cover,
),
),
),
);
}
}
| flutter/dev/integration_tests/new_gallery/lib/studies/reply/profile_avatar.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/reply/profile_avatar.dart",
"repo_id": "flutter",
"token_count": 370
} | 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';
class Scrim extends StatelessWidget {
const Scrim({super.key, required this.controller});
final AnimationController controller;
@override
Widget build(BuildContext context) {
final Size deviceSize = MediaQuery.of(context).size;
return ExcludeSemantics(
child: AnimatedBuilder(
animation: controller,
builder: (BuildContext context, Widget? child) {
final Color color =
const Color(0xFFFFF0EA).withOpacity(controller.value * 0.87);
final Widget scrimRectangle = Container(
width: deviceSize.width, height: deviceSize.height, color: color);
final bool ignorePointer =
(controller.status == AnimationStatus.dismissed);
final bool tapToRevert = (controller.status == AnimationStatus.completed);
if (tapToRevert) {
return MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () {
controller.reverse();
},
child: scrimRectangle,
),
);
} else if (ignorePointer) {
return IgnorePointer(child: scrimRectangle);
} else {
return scrimRectangle;
}
},
),
);
}
}
| flutter/dev/integration_tests/new_gallery/lib/studies/shrine/scrim.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/shrine/scrim.dart",
"repo_id": "flutter",
"token_count": 647
} | 532 |
name: gallery
description: A resource to help developers evaluate and use Flutter.
repository: https://github.com/flutter/flutter/dev/integration_tests/new_gallery
version: 2.10.2+021002 # See README.md for details on versioning.
environment:
flutter: ^3.13.0
sdk: ^3.1.0
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
adaptive_breakpoints: 0.1.7
animations: 2.0.11
collection: 1.18.0
cupertino_icons: 1.0.6
dual_screen: 1.0.4
flutter_gallery_assets: 1.0.2
flutter_localized_locales: 2.0.5
flutter_staggered_grid_view: 0.7.0
google_fonts: 4.0.4
intl: 0.19.0
meta: 1.12.0
provider: 6.1.2
rally_assets: 3.0.1
scoped_model: 2.0.0
shrine_images: 2.0.2
url_launcher: 6.2.5
vector_math: 2.1.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"
clock: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
crypto: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
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"
nested: 1.0.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"
url_launcher_android: 6.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
url_launcher_ios: 6.2.5 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
url_launcher_linux: 3.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
url_launcher_macos: 3.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
url_launcher_platform_interface: 2.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
url_launcher_web: 2.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
url_launcher_windows: 3.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
web: 0.5.1 # 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"
dev_dependencies:
flutter_test:
sdk: flutter
flutter_driver:
sdk: flutter
test: 1.25.2
_fe_analyzer_shared: 67.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
analyzer: 6.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
args: 2.4.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
convert: 3.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
coverage: 1.7.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
fake_async: 1.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
file: 7.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
frontend_server_client: 3.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
glob: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
http_multi_server: 3.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
io: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
js: 0.7.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
leak_tracker: 10.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
leak_tracker_flutter_testing: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
leak_tracker_testing: 3.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
logging: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
mime: 1.0.5 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
node_preamble: 2.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
package_config: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
pool: 1.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
pub_semver: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf_packages_handler: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf_static: 1.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf_web_socket: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_map_stack_trace: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_maps: 0.10.12 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
stack_trace: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
stream_channel: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
sync_http: 0.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
test_api: 0.7.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
test_core: 0.6.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
vm_service: 14.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
watcher: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
web_socket_channel: 2.4.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
webdriver: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
webkit_inspection_protocol: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
yaml: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
flutter:
uses-material-design: true
assets:
- packages/flutter_gallery_assets/crane/destinations/eat_0.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_1.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_2.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_3.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_4.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_5.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_6.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_7.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_8.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_9.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_10.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_0.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_1.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_2.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_3.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_4.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_5.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_6.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_7.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_8.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_9.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_10.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_11.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_12.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_13.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_0.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_1.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_2.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_3.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_4.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_5.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_6.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_7.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_8.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_9.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_10.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_11.jpg
- packages/flutter_gallery_assets/crane/logo/logo.png
- packages/flutter_gallery_assets/fonts/google_fonts/Raleway-Medium.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Raleway-SemiBold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Raleway-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Raleway-Light.ttf
- packages/flutter_gallery_assets/assets/studies/shrine_card_dark.png
- packages/flutter_gallery_assets/assets/studies/starter_card.png
- packages/flutter_gallery_assets/assets/studies/starter_card_dark.png
- packages/flutter_gallery_assets/assets/studies/fortnightly_card_dark.png
- packages/flutter_gallery_assets/assets/studies/rally_card_dark.png
- packages/flutter_gallery_assets/assets/studies/reply_card_dark.png
- packages/flutter_gallery_assets/assets/studies/fortnightly_card.png
- packages/flutter_gallery_assets/assets/studies/crane_card.png
- packages/flutter_gallery_assets/assets/studies/shrine_card.png
- packages/flutter_gallery_assets/assets/studies/crane_card_dark.png
- packages/flutter_gallery_assets/assets/studies/rally_card.png
- packages/flutter_gallery_assets/assets/studies/reply_card.png
- packages/flutter_gallery_assets/assets/logo/flutter_logo.png
- packages/flutter_gallery_assets/assets/logo/flutter_logo_color.png
- packages/flutter_gallery_assets/assets/icons/cupertino/cupertino.png
- packages/flutter_gallery_assets/assets/icons/material/material.png
- packages/flutter_gallery_assets/assets/icons/reference/reference.png
- packages/flutter_gallery_assets/assets/demos/bottom_navigation_background.png
- packages/flutter_gallery_assets/fonts/GalleryIcons.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Merriweather-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Eczar-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Montserrat-Medium.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Rubik-Bold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Merriweather-Light.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/RobotoCondensed-Bold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/LibreFranklin-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/RobotoMono-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/LibreFranklin-ExtraBold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/LibreFranklin-Bold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Oswald-SemiBold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Oswald-Medium.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/LibreFranklin-SemiBold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Montserrat-Bold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Merriweather-BoldItalic.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Rubik-Medium.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Montserrat-SemiBold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/RobotoCondensed-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/LibreFranklin-Medium.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Montserrat-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Rubik-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Eczar-SemiBold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/WorkSans-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/WorkSans-Medium.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/WorkSans-Bold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/WorkSans-Thin.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/WorkSans-SemiBold.ttf
- packages/flutter_gallery_assets/fortnightly/fortnightly_army.png
- packages/flutter_gallery_assets/fortnightly/fortnightly_bees.jpg
- packages/flutter_gallery_assets/fortnightly/fortnightly_chart.png
- packages/flutter_gallery_assets/fortnightly/fortnightly_fabrics.png
- packages/flutter_gallery_assets/fortnightly/fortnightly_feminists.jpg
- packages/flutter_gallery_assets/fortnightly/fortnightly_gas.png
- packages/flutter_gallery_assets/fortnightly/fortnightly_healthcare.jpg
- packages/flutter_gallery_assets/fortnightly/fortnightly_stocks.png
- packages/flutter_gallery_assets/fortnightly/fortnightly_title.png
- packages/flutter_gallery_assets/fortnightly/fortnightly_war.png
- packages/flutter_gallery_assets/reply/attachments/paris_1.jpg
- packages/flutter_gallery_assets/reply/attachments/paris_2.jpg
- packages/flutter_gallery_assets/reply/attachments/paris_3.jpg
- packages/flutter_gallery_assets/reply/attachments/paris_4.jpg
- packages/flutter_gallery_assets/reply/avatars/avatar_0.jpg
- packages/flutter_gallery_assets/reply/avatars/avatar_1.jpg
- packages/flutter_gallery_assets/reply/avatars/avatar_2.jpg
- packages/flutter_gallery_assets/reply/avatars/avatar_3.jpg
- packages/flutter_gallery_assets/reply/avatars/avatar_4.jpg
- packages/flutter_gallery_assets/reply/avatars/avatar_5.jpg
- packages/flutter_gallery_assets/reply/avatars/avatar_6.jpg
- packages/flutter_gallery_assets/reply/avatars/avatar_7.jpg
- packages/flutter_gallery_assets/reply/avatars/avatar_8.jpg
- packages/flutter_gallery_assets/reply/avatars/avatar_9.jpg
- packages/flutter_gallery_assets/reply/avatars/avatar_10.jpg
- packages/flutter_gallery_assets/reply/avatars/avatar_express.png
- packages/flutter_gallery_assets/reply/icons/twotone_add_circle_outline.png
- packages/flutter_gallery_assets/reply/icons/twotone_delete.png
- packages/flutter_gallery_assets/reply/icons/twotone_drafts.png
- packages/flutter_gallery_assets/reply/icons/twotone_error.png
- packages/flutter_gallery_assets/reply/icons/twotone_folder.png
- packages/flutter_gallery_assets/reply/icons/twotone_forward.png
- packages/flutter_gallery_assets/reply/icons/twotone_inbox.png
- packages/flutter_gallery_assets/reply/icons/twotone_send.png
- packages/flutter_gallery_assets/reply/icons/twotone_star_on_background.png
- packages/flutter_gallery_assets/reply/icons/twotone_star.png
- packages/flutter_gallery_assets/reply/icons/twotone_stars.png
- packages/flutter_gallery_assets/reply/reply_logo.png
- packages/flutter_gallery_assets/places/india_chennai_flower_market.png
- packages/flutter_gallery_assets/places/india_thanjavur_market.png
- packages/flutter_gallery_assets/places/india_tanjore_bronze_works.png
- packages/flutter_gallery_assets/places/india_tanjore_market_merchant.png
- packages/flutter_gallery_assets/places/india_tanjore_thanjavur_temple.png
- packages/flutter_gallery_assets/places/india_pondicherry_salt_farm.png
- packages/flutter_gallery_assets/places/india_chennai_highway.png
- packages/flutter_gallery_assets/places/india_chettinad_silk_maker.png
- packages/flutter_gallery_assets/places/india_tanjore_thanjavur_temple_carvings.png
- packages/flutter_gallery_assets/places/india_chettinad_produce.png
- packages/flutter_gallery_assets/places/india_tanjore_market_technology.png
- packages/flutter_gallery_assets/places/india_pondicherry_beach.png
- packages/flutter_gallery_assets/places/india_pondicherry_fisherman.png
- packages/flutter_gallery_assets/placeholders/avatar_logo.png
- packages/flutter_gallery_assets/placeholders/placeholder_image.png
- packages/flutter_gallery_assets/splash_effects/splash_effect_1.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_2.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_3.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_4.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_5.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_6.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_7.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_8.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_9.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_10.gif
- packages/rally_assets/logo.png
- packages/rally_assets/thumb.png
- packages/shrine_images/diamond.png
- packages/shrine_images/slanted_menu.png
- packages/shrine_images/0-0.jpg
- packages/shrine_images/1-0.jpg
- packages/shrine_images/2-0.jpg
- packages/shrine_images/3-0.jpg
- packages/shrine_images/4-0.jpg
- packages/shrine_images/5-0.jpg
- packages/shrine_images/6-0.jpg
- packages/shrine_images/7-0.jpg
- packages/shrine_images/8-0.jpg
- packages/shrine_images/9-0.jpg
- packages/shrine_images/10-0.jpg
- packages/shrine_images/11-0.jpg
- packages/shrine_images/12-0.jpg
- packages/shrine_images/13-0.jpg
- packages/shrine_images/14-0.jpg
- packages/shrine_images/15-0.jpg
- packages/shrine_images/16-0.jpg
- packages/shrine_images/17-0.jpg
- packages/shrine_images/18-0.jpg
- packages/shrine_images/19-0.jpg
- packages/shrine_images/20-0.jpg
- packages/shrine_images/21-0.jpg
- packages/shrine_images/22-0.jpg
- packages/shrine_images/23-0.jpg
- packages/shrine_images/24-0.jpg
- packages/shrine_images/25-0.jpg
- packages/shrine_images/26-0.jpg
- packages/shrine_images/27-0.jpg
- packages/shrine_images/28-0.jpg
- packages/shrine_images/29-0.jpg
- packages/shrine_images/30-0.jpg
- packages/shrine_images/31-0.jpg
- packages/shrine_images/32-0.jpg
- packages/shrine_images/33-0.jpg
- packages/shrine_images/34-0.jpg
- packages/shrine_images/35-0.jpg
- packages/shrine_images/36-0.jpg
- packages/shrine_images/37-0.jpg
fonts:
- family: GalleryIcons
fonts:
- asset: packages/flutter_gallery_assets/fonts/GalleryIcons.ttf
# PUBSPEC CHECKSUM: 8331
| flutter/dev/integration_tests/new_gallery/pubspec.yaml/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/pubspec.yaml",
"repo_id": "flutter",
"token_count": 7870
} | 533 |
#include "Generated.xcconfig"
| flutter/dev/integration_tests/non_nullable/ios/Flutter/Release.xcconfig/0 | {
"file_path": "flutter/dev/integration_tests/non_nullable/ios/Flutter/Release.xcconfig",
"repo_id": "flutter",
"token_count": 12
} | 534 |
// 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('channel suite', () {
late FlutterDriver driver;
setUpAll(() async {
driver = await FlutterDriver.connect(printCommunication: true);
});
test('step through', () async {
final SerializableFinder stepButton = find.byValueKey('step');
final SerializableFinder statusField = find.byValueKey('status');
int step = 0;
while (await driver.getText(statusField) == 'ok') {
await driver.tap(stepButton);
step++;
}
final String status = await driver.getText(statusField);
if (status != 'complete') {
fail('Failed at step $step with status $status');
}
}, timeout: Timeout.none);
tearDownAll(() async {
driver.close();
});
});
}
| flutter/dev/integration_tests/platform_interaction/test_driver/main_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/platform_interaction/test_driver/main_test.dart",
"repo_id": "flutter",
"token_count": 370
} | 535 |
// 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(handler: (String? message) async {
// TODO(cbernaschina): remove when test flakiness is resolved
return 'keyboard_resize';
});
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Text Editing',
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 TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
final TextField textField = TextField(
key: const Key(keys.kDefaultTextField),
controller: _controller,
focusNode: FocusNode(),
);
return Scaffold(
body: Stack(
fit: StackFit.expand,
alignment: Alignment.bottomCenter,
children: <Widget>[
LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return Center(child: Text('${constraints.biggest.height}', key: const Key(keys.kHeightText)));
}
),
textField,
],
),
floatingActionButton: FloatingActionButton(
key: const Key(keys.kUnfocusButton),
onPressed: () { textField.focusNode!.unfocus(); },
tooltip: 'Unfocus',
child: const Icon(Icons.done),
),
);
}
}
| flutter/dev/integration_tests/ui/lib/keyboard_resize.dart/0 | {
"file_path": "flutter/dev/integration_tests/ui/lib/keyboard_resize.dart",
"repo_id": "flutter",
"token_count": 715
} | 536 |
// 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';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
key: Key('mainapp'),
title: 'Integration Test App',
home: MyHomePage(title: 'Integration Test App'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: const Center(
child: Text('TreeshakingThings'),
),
);
}
}
| flutter/dev/integration_tests/web_e2e_tests/lib/treeshaking_main.dart/0 | {
"file_path": "flutter/dev/integration_tests/web_e2e_tests/lib/treeshaking_main.dart",
"repo_id": "flutter",
"token_count": 344
} | 537 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart' show timeDilation;
final Map<int, Color> m2SwatchColors = <int, Color>{
50: const Color(0xfff2e7fe),
100: const Color(0xffd7b7fd),
200: const Color(0xffbb86fc),
300: const Color(0xff9e55fc),
400: const Color(0xff7f22fd),
500: const Color(0xff6200ee),
600: const Color(0xff4b00d1),
700: const Color(0xff3700b3),
800: const Color(0xff270096),
900: const Color(0xff270096),
};
final MaterialColor m2Swatch = MaterialColor(m2SwatchColors[500]!.value, m2SwatchColors);
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Density Test';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class OptionModel extends ChangeNotifier {
double get size => _size;
double _size = 1.0;
set size(double size) {
if (size != _size) {
_size = size;
notifyListeners();
}
}
VisualDensity get density => _density;
VisualDensity _density = VisualDensity.standard;
set density(VisualDensity density) {
if (density != _density) {
_density = density;
notifyListeners();
}
}
bool get enable => _enable;
bool _enable = true;
set enable(bool enable) {
if (enable != _enable) {
_enable = enable;
notifyListeners();
}
}
bool get slowAnimations => _slowAnimations;
bool _slowAnimations = false;
set slowAnimations(bool slowAnimations) {
if (slowAnimations != _slowAnimations) {
_slowAnimations = slowAnimations;
notifyListeners();
}
}
bool get rtl => _rtl;
bool _rtl = false;
set rtl(bool rtl) {
if (rtl != _rtl) {
_rtl = rtl;
notifyListeners();
}
}
bool get longText => _longText;
bool _longText = false;
void reset() {
final OptionModel defaultModel = OptionModel();
_size = defaultModel.size;
_enable = defaultModel.enable;
_slowAnimations = defaultModel.slowAnimations;
_longText = defaultModel.longText;
_density = defaultModel.density;
_rtl = defaultModel.rtl;
notifyListeners();
}
}
class LabeledCheckbox extends StatelessWidget {
const LabeledCheckbox({super.key, required this.label, this.onChanged, this.value});
final String label;
final ValueChanged<bool?>? onChanged;
final bool? value;
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Checkbox(
onChanged: onChanged,
value: value,
),
Text(label),
],
);
}
}
class Options extends StatefulWidget {
const Options(this.model, {super.key});
final OptionModel model;
@override
State<Options> createState() => _OptionsState();
}
class _OptionsState extends State<Options> {
@override
void initState() {
super.initState();
widget.model.addListener(_modelChanged);
}
@override
void didUpdateWidget(Options oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.model != oldWidget.model) {
oldWidget.model.removeListener(_modelChanged);
widget.model.addListener(_modelChanged);
}
}
@override
void dispose() {
super.dispose();
widget.model.removeListener(_modelChanged);
}
void _modelChanged() {
setState(() {});
}
double sliderValue = 0.0;
String _densityToProfile(VisualDensity density) {
if (density == VisualDensity.standard) {
return 'standard';
} else if (density == VisualDensity.compact) {
return 'compact';
} else if (density == VisualDensity.comfortable) {
return 'comfortable';
}
return 'custom';
}
VisualDensity _profileToDensity(String? profile) {
return switch (profile) {
'standard' => VisualDensity.standard,
'comfortable' => VisualDensity.comfortable,
'compact' => VisualDensity.compact,
'custom' || _ => widget.model.density,
};
}
@override
Widget build(BuildContext context) {
final SliderThemeData controlTheme = SliderTheme.of(context).copyWith(
thumbColor: Colors.grey[50],
activeTickMarkColor: Colors.deepPurple[200],
activeTrackColor: Colors.deepPurple[300],
inactiveTrackColor: Colors.grey[50],
);
return Padding(
padding: const EdgeInsets.fromLTRB(5.0, 0.0, 5.0, 10.0),
child: Builder(builder: (BuildContext context) {
return DefaultTextStyle(
style: TextStyle(color: Colors.grey[50]),
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
const Text('Text Scale'),
Expanded(
child: SliderTheme(
data: controlTheme,
child: Slider(
label: '${widget.model.size}',
min: 0.5,
max: 3.0,
onChanged: (double value) {
widget.model.size = value;
},
value: widget.model.size,
),
),
),
Text(
widget.model.size.toStringAsFixed(3),
style: TextStyle(color: Colors.grey[50]),
),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
const Text('X Density'),
Expanded(
child: SliderTheme(
data: controlTheme,
child: Slider(
label: widget.model.density.horizontal.toStringAsFixed(1),
min: VisualDensity.minimumDensity,
max: VisualDensity.maximumDensity,
onChanged: (double value) {
widget.model.density = widget.model.density.copyWith(
horizontal: value,
vertical: widget.model.density.vertical,
);
},
value: widget.model.density.horizontal,
),
),
),
Text(
widget.model.density.horizontal.toStringAsFixed(3),
style: TextStyle(color: Colors.grey[50]),
),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
const Text('Y Density'),
Expanded(
child: SliderTheme(
data: controlTheme,
child: Slider(
label: widget.model.density.vertical.toStringAsFixed(1),
min: VisualDensity.minimumDensity,
max: VisualDensity.maximumDensity,
onChanged: (double value) {
widget.model.density = widget.model.density.copyWith(
horizontal: widget.model.density.horizontal,
vertical: value,
);
},
value: widget.model.density.vertical,
),
),
),
Text(
widget.model.density.vertical.toStringAsFixed(3),
style: TextStyle(color: Colors.grey[50]),
),
],
),
),
Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
children: <Widget>[
Theme(
data: Theme.of(context).copyWith(canvasColor: Colors.grey[600]),
child: DropdownButton<String>(
style: TextStyle(color: Colors.grey[50]),
isDense: true,
onChanged: (String? value) {
widget.model.density = _profileToDensity(value);
},
items: const <DropdownMenuItem<String>>[
DropdownMenuItem<String>(
value: 'standard',
child: Text('Standard'),
),
DropdownMenuItem<String>(value: 'comfortable', child: Text('Comfortable')),
DropdownMenuItem<String>(value: 'compact', child: Text('Compact')),
DropdownMenuItem<String>(value: 'custom', child: Text('Custom')),
],
value: _densityToProfile(widget.model.density),
),
),
LabeledCheckbox(
label: 'Enabled',
onChanged: (bool? checked) {
widget.model.enable = checked ?? false;
},
value: widget.model.enable,
),
LabeledCheckbox(
label: 'Slow',
onChanged: (bool? checked) {
widget.model.slowAnimations = checked ?? false;
Future<void>.delayed(const Duration(milliseconds: 150)).then((_) {
if (widget.model.slowAnimations) {
timeDilation = 20.0;
} else {
timeDilation = 1.0;
}
});
},
value: widget.model.slowAnimations,
),
LabeledCheckbox(
label: 'RTL',
onChanged: (bool? checked) {
widget.model.rtl = checked ?? false;
},
value: widget.model.rtl,
),
MaterialButton(
onPressed: () {
widget.model.reset();
sliderValue = 0.0;
},
child: Text('Reset', style: TextStyle(color: Colors.grey[50])),
),
],
),
],
),
);
}),
);
}
}
class _ControlTile extends StatelessWidget {
const _ControlTile({required this.label, required this.child});
final String label;
final Widget child;
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Align(
alignment: AlignmentDirectional.topStart,
child: Text(
label,
textAlign: TextAlign.start,
),
),
child,
],
),
),
);
}
}
class _MyHomePageState extends State<MyHomePage> {
static final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
final OptionModel _model = OptionModel();
final TextEditingController textController = TextEditingController();
@override
void initState() {
super.initState();
_model.addListener(_modelChanged);
}
@override
void dispose() {
super.dispose();
_model.removeListener(_modelChanged);
}
void _modelChanged() {
setState(() {});
}
double sliderValue = 0.0;
List<bool> checkboxValues = <bool>[false, false, false, false];
List<IconData> iconValues = <IconData>[Icons.arrow_back, Icons.play_arrow, Icons.arrow_forward];
List<String> chipValues = <String>['Potato', 'Computer'];
int radioValue = 0;
@override
Widget build(BuildContext context) {
final ThemeData theme = ThemeData(
primarySwatch: m2Swatch,
);
final Widget label = Text(_model.rtl ? 'اضغط علي' : 'Press Me');
textController.text = _model.rtl
? 'يعتمد القرار الجيد على المعرفة وليس على الأرقام.'
: 'A good decision is based on knowledge and not on numbers.';
final List<Widget> tiles = <Widget>[
_ControlTile(
label: _model.rtl ? 'حقل النص' : 'List Tile',
child: SizedBox(
width: 400,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ListTile(
title: Text(_model.rtl ? 'هذا عنوان طويل نسبيا' : 'This is a relatively long title'),
onTap: () {},
),
ListTile(
title: Text(_model.rtl ? 'هذا عنوان قصير' : 'This is a short title'),
subtitle:
Text(_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.'),
trailing: const Icon(Icons.check_box),
onTap: () {},
),
ListTile(
title: Text(_model.rtl ? 'هذا عنوان قصير' : 'This is a short title'),
subtitle:
Text(_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.'),
leading: const Icon(Icons.check_box),
dense: true,
onTap: () {},
),
ListTile(
title: Text(_model.rtl ? 'هذا عنوان قصير' : 'This is a short title'),
subtitle:
Text(_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.'),
dense: true,
leading: const Icon(Icons.add_box),
trailing: const Icon(Icons.check_box),
onTap: () {},
),
ListTile(
title: Text(_model.rtl ? 'هذا عنوان قصير' : 'This is a short title'),
subtitle:
Text(_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.'),
isThreeLine: true,
leading: const Icon(Icons.add_box),
trailing: const Icon(Icons.check_box),
onTap: () {},
),
],
),
),
),
_ControlTile(
label: _model.rtl ? 'حقل النص' : 'Text Field',
child: SizedBox(
width: 300,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: textController,
decoration: const InputDecoration(
hintText: 'Hint',
helperText: 'Helper',
labelText: 'Label',
border: OutlineInputBorder(),
),
),
TextField(
controller: textController,
),
TextField(
controller: textController,
maxLines: 3,
),
],
),
),
),
_ControlTile(
label: _model.rtl ? 'رقائق' : 'Chips',
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: List<Widget>.generate(chipValues.length, (int index) {
return InputChip(
onPressed: _model.enable ? () {} : null,
onDeleted: _model.enable ? () {} : null,
label: Text(chipValues[index]),
deleteIcon: const Icon(Icons.delete),
avatar: const Icon(Icons.play_arrow),
);
}),
),
),
_ControlTile(
label: _model.rtl ? 'زر المواد' : 'Material Button',
child: MaterialButton(
color: m2Swatch[200],
onPressed: _model.enable ? () {} : null,
child: label,
),
),
_ControlTile(
label: _model.rtl ? 'زر مسطح' : 'Text Button',
child: TextButton(
style: TextButton.styleFrom(
foregroundColor: Colors.white,
backgroundColor: m2Swatch[200]
),
onPressed: _model.enable ? () {} : null,
child: label,
),
),
_ControlTile(
label: _model.rtl ? 'أثارت زر' : 'Elevated Button',
child: ElevatedButton(
style: TextButton.styleFrom(backgroundColor: m2Swatch[200]),
onPressed: _model.enable ? () {} : null,
child: label,
),
),
_ControlTile(
label: _model.rtl ? 'زر المخطط التفصيلي' : 'Outlined Button',
child: OutlinedButton(
onPressed: _model.enable ? () {} : null,
child: label,
),
),
_ControlTile(
label: _model.rtl ? 'خانات الاختيار' : 'Checkboxes',
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List<Widget>.generate(checkboxValues.length, (int index) {
return Checkbox(
onChanged: _model.enable
? (bool? value) {
setState(() {
checkboxValues[index] = value ?? false;
});
}
: null,
value: checkboxValues[index],
);
}),
),
),
_ControlTile(
label: _model.rtl ? 'زر الراديو' : 'Radio Button',
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List<Widget>.generate(4, (int index) {
return Radio<int>(
onChanged: _model.enable
? (int? value) {
setState(() {
radioValue = value!;
});
}
: null,
groupValue: radioValue,
value: index,
);
}),
),
),
_ControlTile(
label: _model.rtl ? 'زر الأيقونة' : 'Icon Button',
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List<Widget>.generate(iconValues.length, (int index) {
return IconButton(
onPressed: _model.enable ? () {} : null,
icon: Icon(iconValues[index]),
);
}),
),
),
];
return SafeArea(
child: Theme(
data: theme,
child: Scaffold(
key: scaffoldKey,
appBar: AppBar(
title: const Text('Density'),
bottom: PreferredSize(
preferredSize: const Size.fromHeight(220.0),
child: Options(_model),
),
backgroundColor: const Color(0xff323232),
),
body: DefaultTextStyle(
style: const TextStyle(
color: Colors.black,
fontSize: 14.0,
fontFamily: 'Roboto',
fontStyle: FontStyle.normal,
),
child: Theme(
data: Theme.of(context).copyWith(visualDensity: _model.density),
child: Directionality(
textDirection: _model.rtl ? TextDirection.rtl : TextDirection.ltr,
child: Builder(builder: (BuildContext context) {
final MediaQueryData mediaQueryData = MediaQuery.of(context);
return MediaQuery(
data: mediaQueryData.copyWith(textScaler: TextScaler.linear(_model.size)),
child: SizedBox.expand(
child: ListView(
children: tiles,
),
),
);
}),
),
),
),
),
),
);
}
}
| flutter/dev/manual_tests/lib/density.dart/0 | {
"file_path": "flutter/dev/manual_tests/lib/density.dart",
"repo_id": "flutter",
"token_count": 11013
} | 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 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:manual_tests/overlay_geometry.dart' as overlay_geometry;
void main() {
testWidgets('Overlay geometry smoke test', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: overlay_geometry.OverlayGeometryApp()));
expect(find.byType(overlay_geometry.Marker), findsNothing);
await tester.tap(find.text('Card 3'));
await tester.pump();
expect(find.byType(overlay_geometry.Marker), findsNWidgets(3));
final double y = tester.getTopLeft(find.byType(overlay_geometry.Marker).first).dy;
await tester.fling(find.text('Card 3'), const Offset(0.0, -100.0), 100.0);
await tester.pump();
expect(find.byType(overlay_geometry.Marker), findsNWidgets(3));
expect(tester.getTopLeft(find.byType(overlay_geometry.Marker).first).dy, lessThan(y));
});
}
| flutter/dev/manual_tests/test/overlay_geometry_test.dart/0 | {
"file_path": "flutter/dev/manual_tests/test/overlay_geometry_test.dart",
"repo_id": "flutter",
"token_count": 383
} | 539 |
{@inject-html}
<a name="{{id}}"></a>
<div class="snippet snippet-container anchor-container">
{{description}}
<a class="anchor-button-overlay anchor-button" title="Copy link to clipboard"
onmouseenter="fixHref(this, '{{id}}');" onclick="fixHref(this, '{{id}}'); copyStringToClipboard(this.href);"
href="#">
<i class="material-icons anchor-image">link</i>
</a>
<div class="copyable-container">
<button class="copy-button-overlay copy-button" title="Copy to clipboard"
onclick="copyTextToClipboard(findSiblingWithId(this, 'sample-code'));">
<i class="material-icons copy-image">content_copy</i>
</button>
<pre class="language-{{language}}" id="sample-code"><code class="language-{{language}}">{{code}}</code></pre>
</div>
</div>
{@end-inject-html} | flutter/dev/snippets/config/skeletons/snippet.html/0 | {
"file_path": "flutter/dev/snippets/config/skeletons/snippet.html",
"repo_id": "flutter",
"token_count": 291
} | 540 |
{
"version": "v0_206",
"md.comp.filled-tonal-button.container.color": "secondaryContainer",
"md.comp.filled-tonal-button.container.elevation": "md.sys.elevation.level0",
"md.comp.filled-tonal-button.container.height": 40.0,
"md.comp.filled-tonal-button.container.shadow-color": "shadow",
"md.comp.filled-tonal-button.container.shape": "md.sys.shape.corner.full",
"md.comp.filled-tonal-button.disabled.container.color": "onSurface",
"md.comp.filled-tonal-button.disabled.container.elevation": "md.sys.elevation.level0",
"md.comp.filled-tonal-button.disabled.container.opacity": 0.12,
"md.comp.filled-tonal-button.disabled.label-text.color": "onSurface",
"md.comp.filled-tonal-button.disabled.label-text.opacity": 0.38,
"md.comp.filled-tonal-button.focus.container.elevation": "md.sys.elevation.level0",
"md.comp.filled-tonal-button.focus.indicator.color": "secondary",
"md.comp.filled-tonal-button.focus.indicator.outline.offset": "md.sys.state.focus-indicator.outer-offset",
"md.comp.filled-tonal-button.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness",
"md.comp.filled-tonal-button.focus.label-text.color": "onSecondaryContainer",
"md.comp.filled-tonal-button.focus.state-layer.color": "onSecondaryContainer",
"md.comp.filled-tonal-button.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.filled-tonal-button.hover.container.elevation": "md.sys.elevation.level1",
"md.comp.filled-tonal-button.hover.label-text.color": "onSecondaryContainer",
"md.comp.filled-tonal-button.hover.state-layer.color": "onSecondaryContainer",
"md.comp.filled-tonal-button.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.filled-tonal-button.label-text.color": "onSecondaryContainer",
"md.comp.filled-tonal-button.label-text.text-style": "labelLarge",
"md.comp.filled-tonal-button.pressed.container.elevation": "md.sys.elevation.level0",
"md.comp.filled-tonal-button.pressed.label-text.color": "onSecondaryContainer",
"md.comp.filled-tonal-button.pressed.state-layer.color": "onSecondaryContainer",
"md.comp.filled-tonal-button.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.filled-tonal-button.with-icon.disabled.icon.color": "onSurface",
"md.comp.filled-tonal-button.with-icon.disabled.icon.opacity": 0.38,
"md.comp.filled-tonal-button.with-icon.focus.icon.color": "onSecondaryContainer",
"md.comp.filled-tonal-button.with-icon.hover.icon.color": "onSecondaryContainer",
"md.comp.filled-tonal-button.with-icon.icon.color": "onSecondaryContainer",
"md.comp.filled-tonal-button.with-icon.icon.size": 18.0,
"md.comp.filled-tonal-button.with-icon.pressed.icon.color": "onSecondaryContainer"
}
| flutter/dev/tools/gen_defaults/data/button_filled_tonal.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/button_filled_tonal.json",
"repo_id": "flutter",
"token_count": 1026
} | 541 |
{
"version": "v0_206",
"md.comp.date-picker.modal.container.color": "surfaceContainerHigh",
"md.comp.date-picker.modal.container.elevation": "md.sys.elevation.level3",
"md.comp.date-picker.modal.container.height": 568.0,
"md.comp.date-picker.modal.container.shape": "md.sys.shape.corner.extra-large",
"md.comp.date-picker.modal.container.width": 360.0,
"md.comp.date-picker.modal.date.container.height": 40.0,
"md.comp.date-picker.modal.date.container.shape": "md.sys.shape.corner.full",
"md.comp.date-picker.modal.date.container.width": 40.0,
"md.comp.date-picker.modal.date.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.date-picker.modal.date.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.date-picker.modal.date.label-text.text-style": "bodyLarge",
"md.comp.date-picker.modal.date.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.date-picker.modal.date.selected.container.color": "primary",
"md.comp.date-picker.modal.date.selected.focus.state-layer.color": "onPrimary",
"md.comp.date-picker.modal.date.selected.hover.state-layer.color": "onPrimary",
"md.comp.date-picker.modal.date.selected.label-text.color": "onPrimary",
"md.comp.date-picker.modal.date.selected.pressed.state-layer.color": "onPrimary",
"md.comp.date-picker.modal.date.state-layer.height": 40.0,
"md.comp.date-picker.modal.date.state-layer.shape": "md.sys.shape.corner.full",
"md.comp.date-picker.modal.date.state-layer.width": 40.0,
"md.comp.date-picker.modal.date.today.container.outline.color": "primary",
"md.comp.date-picker.modal.date.today.container.outline.width": 1.0,
"md.comp.date-picker.modal.date.today.focus.state-layer.color": "primary",
"md.comp.date-picker.modal.date.today.hover.state-layer.color": "primary",
"md.comp.date-picker.modal.date.today.label-text.color": "primary",
"md.comp.date-picker.modal.date.today.pressed.state-layer.color": "primary",
"md.comp.date-picker.modal.date.unselected.focus.state-layer.color": "onSurfaceVariant",
"md.comp.date-picker.modal.date.unselected.hover.state-layer.color": "onSurfaceVariant",
"md.comp.date-picker.modal.date.unselected.label-text.color": "onSurface",
"md.comp.date-picker.modal.date.unselected.pressed.state-layer.color": "onSurfaceVariant",
"md.comp.date-picker.modal.header.container.height": 120.0,
"md.comp.date-picker.modal.header.container.width": 360.0,
"md.comp.date-picker.modal.header.headline.color": "onSurfaceVariant",
"md.comp.date-picker.modal.header.headline.text-style": "headlineLarge",
"md.comp.date-picker.modal.header.supporting-text.color": "onSurfaceVariant",
"md.comp.date-picker.modal.header.supporting-text.text-style": "labelLarge",
"md.comp.date-picker.modal.range-selection.active-indicator.container.color": "secondaryContainer",
"md.comp.date-picker.modal.range-selection.active-indicator.container.height": 40.0,
"md.comp.date-picker.modal.range-selection.active-indicator.container.shape": "md.sys.shape.corner.full",
"md.comp.date-picker.modal.range-selection.container.elevation": "md.sys.elevation.level0",
"md.comp.date-picker.modal.range-selection.container.shape": "md.sys.shape.corner.none",
"md.comp.date-picker.modal.range-selection.date.in-range.focus.state-layer.color": "onPrimaryContainer",
"md.comp.date-picker.modal.range-selection.date.in-range.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.date-picker.modal.range-selection.date.in-range.hover.state-layer.color": "onPrimaryContainer",
"md.comp.date-picker.modal.range-selection.date.in-range.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.date-picker.modal.range-selection.date.in-range.label-text.color": "onSecondaryContainer",
"md.comp.date-picker.modal.range-selection.date.in-range.pressed.state-layer.color": "onPrimaryContainer",
"md.comp.date-picker.modal.range-selection.date.in-range.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.date-picker.modal.range-selection.header.container.height": 128.0,
"md.comp.date-picker.modal.range-selection.header.headline.text-style": "titleLarge",
"md.comp.date-picker.modal.range-selection.month.subhead.color": "onSurfaceVariant",
"md.comp.date-picker.modal.range-selection.month.subhead.text-style": "titleSmall",
"md.comp.date-picker.modal.weekdays.label-text.color": "onSurface",
"md.comp.date-picker.modal.weekdays.label-text.text-style": "bodyLarge",
"md.comp.date-picker.modal.year-selection.year.container.height": 36.0,
"md.comp.date-picker.modal.year-selection.year.container.width": 72.0,
"md.comp.date-picker.modal.year-selection.year.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.date-picker.modal.year-selection.year.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.date-picker.modal.year-selection.year.label-text.text-style": "bodyLarge",
"md.comp.date-picker.modal.year-selection.year.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.date-picker.modal.year-selection.year.selected.container.color": "primary",
"md.comp.date-picker.modal.year-selection.year.selected.focus.state-layer.color": "onPrimary",
"md.comp.date-picker.modal.year-selection.year.selected.hover.state-layer.color": "onPrimary",
"md.comp.date-picker.modal.year-selection.year.selected.label-text.color": "onPrimary",
"md.comp.date-picker.modal.year-selection.year.selected.pressed.state-layer.color": "onPrimary",
"md.comp.date-picker.modal.year-selection.year.state-layer.height": 36.0,
"md.comp.date-picker.modal.year-selection.year.state-layer.shape": "md.sys.shape.corner.full",
"md.comp.date-picker.modal.year-selection.year.state-layer.width": 72.0,
"md.comp.date-picker.modal.year-selection.year.unselected.focus.state-layer.color": "onSurfaceVariant",
"md.comp.date-picker.modal.year-selection.year.unselected.hover.state-layer.color": "onSurfaceVariant",
"md.comp.date-picker.modal.year-selection.year.unselected.label-text.color": "onSurfaceVariant",
"md.comp.date-picker.modal.year-selection.year.unselected.pressed.state-layer.color": "onSurfaceVariant"
}
| flutter/dev/tools/gen_defaults/data/date_picker_modal.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/date_picker_modal.json",
"repo_id": "flutter",
"token_count": 2423
} | 542 |
{
"version": "v0_206",
"md.comp.navigation-bar.active.focus.icon.color": "onSecondaryContainer",
"md.comp.navigation-bar.active.focus.label-text.color": "onSurface",
"md.comp.navigation-bar.active.focus.state-layer.color": "onSurface",
"md.comp.navigation-bar.active.hover.icon.color": "onSecondaryContainer",
"md.comp.navigation-bar.active.hover.label-text.color": "onSurface",
"md.comp.navigation-bar.active.hover.state-layer.color": "onSurface",
"md.comp.navigation-bar.active.icon.color": "onSecondaryContainer",
"md.comp.navigation-bar.active-indicator.color": "secondaryContainer",
"md.comp.navigation-bar.active-indicator.height": 32.0,
"md.comp.navigation-bar.active-indicator.shape": "md.sys.shape.corner.full",
"md.comp.navigation-bar.active-indicator.width": 64.0,
"md.comp.navigation-bar.active.label-text.color": "onSurface",
"md.comp.navigation-bar.active.pressed.icon.color": "onSecondaryContainer",
"md.comp.navigation-bar.active.pressed.label-text.color": "onSurface",
"md.comp.navigation-bar.active.pressed.state-layer.color": "onSurface",
"md.comp.navigation-bar.container.color": "surfaceContainer",
"md.comp.navigation-bar.container.elevation": "md.sys.elevation.level2",
"md.comp.navigation-bar.container.height": 80.0,
"md.comp.navigation-bar.container.shape": "md.sys.shape.corner.none",
"md.comp.navigation-bar.focus.indicator.color": "secondary",
"md.comp.navigation-bar.focus.indicator.outline.offset": "md.sys.state.focus-indicator.inner-offset",
"md.comp.navigation-bar.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness",
"md.comp.navigation-bar.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.navigation-bar.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.navigation-bar.icon.size": 24.0,
"md.comp.navigation-bar.inactive.focus.icon.color": "onSurface",
"md.comp.navigation-bar.inactive.focus.label-text.color": "onSurface",
"md.comp.navigation-bar.inactive.focus.state-layer.color": "onSurface",
"md.comp.navigation-bar.inactive.hover.icon.color": "onSurface",
"md.comp.navigation-bar.inactive.hover.label-text.color": "onSurface",
"md.comp.navigation-bar.inactive.hover.state-layer.color": "onSurface",
"md.comp.navigation-bar.inactive.icon.color": "onSurfaceVariant",
"md.comp.navigation-bar.inactive.label-text.color": "onSurfaceVariant",
"md.comp.navigation-bar.inactive.pressed.icon.color": "onSurface",
"md.comp.navigation-bar.inactive.pressed.label-text.color": "onSurface",
"md.comp.navigation-bar.inactive.pressed.state-layer.color": "onSurface",
"md.comp.navigation-bar.label-text.text-style": "labelMedium",
"md.comp.navigation-bar.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity"
}
| flutter/dev/tools/gen_defaults/data/navigation_bar.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/navigation_bar.json",
"repo_id": "flutter",
"token_count": 1054
} | 543 |
{
"version": "v0_206",
"md.sys.state.dragged.state-layer-opacity": 0.16,
"md.sys.state.focus.state-layer-opacity": 0.1,
"md.sys.state.hover.state-layer-opacity": 0.08,
"md.sys.state.pressed.state-layer-opacity": 0.1
}
| flutter/dev/tools/gen_defaults/data/state.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/state.json",
"repo_id": "flutter",
"token_count": 103
} | 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 'template.dart';
class BottomSheetTemplate extends TokenTemplate {
const BottomSheetTemplate(
super.blockName,
super.fileName,
super.tokens, {
super.colorSchemePrefix = '_colors.',
});
@override
String generate() => '''
class _${blockName}DefaultsM3 extends BottomSheetThemeData {
_${blockName}DefaultsM3(this.context)
: super(
elevation: ${elevation("md.comp.sheet.bottom.docked.standard.container")},
modalElevation: ${elevation("md.comp.sheet.bottom.docked.modal.container")},
shape: ${shape("md.comp.sheet.bottom.docked.container")},
constraints: const BoxConstraints(maxWidth: 640),
);
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
@override
Color? get backgroundColor => ${componentColor("md.comp.sheet.bottom.docked.container")};
@override
Color? get surfaceTintColor => ${colorOrTransparent("md.comp.sheet.bottom.docked.container.surface-tint-layer")};
@override
Color? get shadowColor => Colors.transparent;
@override
Color? get dragHandleColor => ${componentColor("md.comp.sheet.bottom.docked.drag-handle")};
@override
Size? get dragHandleSize => ${size("md.comp.sheet.bottom.docked.drag-handle")};
@override
BoxConstraints? get constraints => const BoxConstraints(maxWidth: 640.0);
}
''';
}
| flutter/dev/tools/gen_defaults/lib/bottom_sheet_template.dart/0 | {
"file_path": "flutter/dev/tools/gen_defaults/lib/bottom_sheet_template.dart",
"repo_id": "flutter",
"token_count": 508
} | 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 'template.dart';
class ListTileTemplate extends TokenTemplate {
const ListTileTemplate(super.blockName, super.fileName, super.tokens, {
super.colorSchemePrefix = '_colors.',
super.textThemePrefix = '_textTheme.',
});
static const String tokenGroup = 'md.comp.list.list-item';
@override
String generate() => '''
class _${blockName}DefaultsM3 extends ListTileThemeData {
_${blockName}DefaultsM3(this.context)
: super(
contentPadding: const EdgeInsetsDirectional.only(start: 16.0, end: 24.0),
minLeadingWidth: 24,
minVerticalPadding: 8,
shape: ${shape("$tokenGroup.container")},
);
final BuildContext context;
late final ThemeData _theme = Theme.of(context);
late final ColorScheme _colors = _theme.colorScheme;
late final TextTheme _textTheme = _theme.textTheme;
@override
Color? get tileColor => Colors.transparent;
@override
TextStyle? get titleTextStyle => ${textStyle("$tokenGroup.label-text")}!.copyWith(color: ${componentColor('$tokenGroup.label-text')});
@override
TextStyle? get subtitleTextStyle => ${textStyle("$tokenGroup.supporting-text")}!.copyWith(color: ${componentColor('$tokenGroup.supporting-text')});
@override
TextStyle? get leadingAndTrailingTextStyle => ${textStyle("$tokenGroup.trailing-supporting-text")}!.copyWith(color: ${componentColor('$tokenGroup.trailing-supporting-text')});
@override
Color? get selectedColor => ${componentColor('$tokenGroup.selected.trailing-icon')};
@override
Color? get iconColor => ${componentColor('$tokenGroup.trailing-icon')};
}
''';
}
| flutter/dev/tools/gen_defaults/lib/list_tile_template.dart/0 | {
"file_path": "flutter/dev/tools/gen_defaults/lib/list_tile_template.dart",
"repo_id": "flutter",
"token_count": 578
} | 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 'template.dart';
class TabsTemplate extends TokenTemplate {
const TabsTemplate(super.blockName, super.fileName, super.tokens, {
super.colorSchemePrefix = '_colors.',
super.textThemePrefix = '_textTheme.',
});
@override
String generate() => '''
class _${blockName}PrimaryDefaultsM3 extends TabBarTheme {
_${blockName}PrimaryDefaultsM3(this.context, this.isScrollable)
: super(indicatorSize: TabBarIndicatorSize.label);
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
late final TextTheme _textTheme = Theme.of(context).textTheme;
final bool isScrollable;
// This value comes from Divider widget defaults. Token db deprecated 'primary-navigation-tab.divider.color' token.
@override
Color? get dividerColor => ${componentColor("md.comp.divider")};
// This value comes from Divider widget defaults. Token db deprecated 'primary-navigation-tab.divider.height' token.
@override
double? get dividerHeight => ${getToken("md.comp.divider.thickness")};
@override
Color? get indicatorColor => ${componentColor("md.comp.primary-navigation-tab.active-indicator")};
@override
Color? get labelColor => ${componentColor("md.comp.primary-navigation-tab.with-label-text.active.label-text")};
@override
TextStyle? get labelStyle => ${textStyle("md.comp.primary-navigation-tab.with-label-text.label-text")};
@override
Color? get unselectedLabelColor => ${componentColor("md.comp.primary-navigation-tab.with-label-text.inactive.label-text")};
@override
TextStyle? get unselectedLabelStyle => ${textStyle("md.comp.primary-navigation-tab.with-label-text.label-text")};
@override
MaterialStateProperty<Color?> get overlayColor {
return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
if (states.contains(MaterialState.pressed)) {
return ${componentColor('md.comp.primary-navigation-tab.active.pressed.state-layer')};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor('md.comp.primary-navigation-tab.active.hover.state-layer')};
}
if (states.contains(MaterialState.focused)) {
return ${componentColor('md.comp.primary-navigation-tab.active.focus.state-layer')};
}
return null;
}
if (states.contains(MaterialState.pressed)) {
return ${componentColor('md.comp.primary-navigation-tab.inactive.pressed.state-layer')};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor('md.comp.primary-navigation-tab.inactive.hover.state-layer')};
}
if (states.contains(MaterialState.focused)) {
return ${componentColor('md.comp.primary-navigation-tab.inactive.focus.state-layer')};
}
return null;
});
}
@override
InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory;
@override
TabAlignment? get tabAlignment => isScrollable ? TabAlignment.startOffset : TabAlignment.fill;
static double indicatorWeight = ${getToken('md.comp.primary-navigation-tab.active-indicator.height')};
// TODO(davidmartos96): This value doesn't currently exist in
// https://m3.material.io/components/tabs/specs
// Update this when the token is available.
static const EdgeInsetsGeometry iconMargin = EdgeInsets.only(bottom: 2);
}
class _${blockName}SecondaryDefaultsM3 extends TabBarTheme {
_${blockName}SecondaryDefaultsM3(this.context, this.isScrollable)
: super(indicatorSize: TabBarIndicatorSize.tab);
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
late final TextTheme _textTheme = Theme.of(context).textTheme;
final bool isScrollable;
// This value comes from Divider widget defaults. Token db deprecated 'secondary-navigation-tab.divider.color' token.
@override
Color? get dividerColor => ${componentColor("md.comp.divider")};
// This value comes from Divider widget defaults. Token db deprecated 'secondary-navigation-tab.divider.height' token.
@override
double? get dividerHeight => ${getToken("md.comp.divider.thickness")};
@override
Color? get indicatorColor => ${componentColor("md.comp.primary-navigation-tab.active-indicator")};
@override
Color? get labelColor => ${componentColor("md.comp.secondary-navigation-tab.active.label-text")};
@override
TextStyle? get labelStyle => ${textStyle("md.comp.secondary-navigation-tab.label-text")};
@override
Color? get unselectedLabelColor => ${componentColor("md.comp.secondary-navigation-tab.inactive.label-text")};
@override
TextStyle? get unselectedLabelStyle => ${textStyle("md.comp.secondary-navigation-tab.label-text")};
@override
MaterialStateProperty<Color?> get overlayColor {
return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
if (states.contains(MaterialState.pressed)) {
return ${componentColor('md.comp.secondary-navigation-tab.pressed.state-layer')};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor('md.comp.secondary-navigation-tab.hover.state-layer')};
}
if (states.contains(MaterialState.focused)) {
return ${componentColor('md.comp.secondary-navigation-tab.focus.state-layer')};
}
return null;
}
if (states.contains(MaterialState.pressed)) {
return ${componentColor('md.comp.secondary-navigation-tab.pressed.state-layer')};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor('md.comp.secondary-navigation-tab.hover.state-layer')};
}
if (states.contains(MaterialState.focused)) {
return ${componentColor('md.comp.secondary-navigation-tab.focus.state-layer')};
}
return null;
});
}
@override
InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory;
@override
TabAlignment? get tabAlignment => isScrollable ? TabAlignment.startOffset : TabAlignment.fill;
}
''';
}
| flutter/dev/tools/gen_defaults/lib/tabs_template.dart/0 | {
"file_path": "flutter/dev/tools/gen_defaults/lib/tabs_template.dart",
"repo_id": "flutter",
"token_count": 2134
} | 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.
#include <map>
// DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT
// This file is generated by
// flutter/flutter:dev/tools/gen_keycodes/bin/gen_keycodes.dart and should not
// be edited directly.
//
// Edit the template
// flutter/flutter:dev/tools/gen_keycodes/data/fuchsia_keyboard_map_cc.tmpl
// instead.
//
// See flutter/flutter:dev/tools/gen_keycodes/README.md for more information.
/// Maps Fuchsia-specific IDs to the matching LogicalKeyboardKey.
const std::map<int, int> g_fuchsia_to_logical_key = {
@@@FUCHSIA_KEY_CODE_MAP@@@
};
/// Maps Fuchsia-specific USB HID Usage IDs to the matching
/// [PhysicalKeyboardKey].
const std::map<int, int> g_fuchsia_to_physical_key = {
@@@FUCHSIA_SCAN_CODE_MAP@@@
};
| flutter/dev/tools/gen_keycodes/data/fuchsia_keyboard_map_cc.tmpl/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/data/fuchsia_keyboard_map_cc.tmpl",
"repo_id": "flutter",
"token_count": 303
} | 548 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
#import <Foundation/Foundation.h>
#include "./KeyCodeMap_Internal.h"
// DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT
// This file is generated by
// flutter/flutter:dev/tools/gen_keycodes/bin/gen_keycodes.dart and should not
// be edited directly.
//
// Edit the template
// flutter/flutter:dev/tools/gen_keycodes/data/keyboard_map_macos_cc.tmpl
// instead.
//
// See flutter/flutter:dev/tools/gen_keycodes/README.md for more information.
namespace flutter {
@@@MASK_CONSTANTS@@@
const NSDictionary* keyCodeToPhysicalKey = @{
@@@MACOS_SCAN_CODE_MAP@@@
};
const NSDictionary* keyCodeToLogicalKey = @{
@@@MACOS_KEYCODE_LOGICAL_MAP@@@
};
const NSDictionary* keyCodeToModifierFlag = @{
@@@KEYCODE_TO_MODIFIER_FLAG_MAP@@@
};
const NSDictionary* modifierFlagToKeyCode = @{
@@@MODIFIER_FLAG_TO_KEYCODE_MAP@@@
};
@@@SPECIAL_KEY_CONSTANTS@@@
const std::vector<LayoutGoal> kLayoutGoals = {
@@@LAYOUT_GOALS@@@
};
} // namespace flutter
| flutter/dev/tools/gen_keycodes/data/macos_key_code_map_cc.tmpl/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/data/macos_key_code_map_cc.tmpl",
"repo_id": "flutter",
"token_count": 416
} | 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:path/path.dart' as path;
import 'base_code_gen.dart';
import 'constants.dart';
import 'logical_key_data.dart';
import 'physical_key_data.dart';
import 'utils.dart';
/// Generates the key mapping for GTK, based on the information in the key
/// data structure given to it.
class GtkCodeGenerator extends PlatformCodeGenerator {
GtkCodeGenerator(
super.keyData,
super.logicalData,
String modifierBitMapping,
String lockBitMapping,
this._layoutGoals,
) : _modifierBitMapping = parseMapOfListOfString(modifierBitMapping),
_lockBitMapping = parseMapOfListOfString(lockBitMapping);
/// This generates the map of XKB scan codes to Flutter physical keys.
String get _xkbScanCodeMap {
final OutputLines<int> lines = OutputLines<int>('GTK scancode map');
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.xKbScanCode != null) {
lines.add(entry.xKbScanCode!,
' {${toHex(entry.xKbScanCode)}, ${toHex(entry.usbHidCode)}}, // ${entry.constantName}');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of GTK keyval codes to Flutter logical keys.
String get _gtkKeyvalCodeMap {
final OutputLines<int> lines = OutputLines<int>('GTK keyval map');
for (final LogicalKeyEntry entry in logicalData.entries) {
zipStrict(entry.gtkValues, entry.gtkNames, (int value, String name) {
lines.add(value,
' {${toHex(value)}, ${toHex(entry.value, digits: 11)}}, // $name');
});
}
return lines.sortedJoin().trimRight();
}
static String constructMapFromModToKeys(
Map<String, List<String>> source,
PhysicalKeyData physicalData,
LogicalKeyData logicalData,
String debugFunctionName,
) {
final StringBuffer result = StringBuffer();
source.forEach((String modifierBitName, List<String> keyNames) {
assert(keyNames.length == 2 || keyNames.length == 3);
final String primaryPhysicalName = keyNames[0];
final String primaryLogicalName = keyNames[1];
final String? secondaryLogicalName = keyNames.length == 3 ? keyNames[2] : null;
final PhysicalKeyEntry primaryPhysical = physicalData.entryByName(primaryPhysicalName);
final LogicalKeyEntry primaryLogical = logicalData.entryByName(primaryLogicalName);
final LogicalKeyEntry? secondaryLogical = secondaryLogicalName == null ? null : logicalData.entryByName(secondaryLogicalName);
if (secondaryLogical == null && secondaryLogicalName != null) {
print('Unrecognized secondary logical key $secondaryLogicalName specified for $debugFunctionName.');
return;
}
final String pad = secondaryLogical == null ? '' : ' ';
result.writeln('''
data = g_new(FlKeyEmbedderCheckedKey, 1);
g_hash_table_insert(table, GUINT_TO_POINTER(GDK_${modifierBitName}_MASK), data);
data->is_caps_lock = ${primaryPhysicalName == 'CapsLock' ? 'true' : 'false'};
data->primary_physical_key = ${toHex(primaryPhysical.usbHidCode, digits: 9)};$pad // ${primaryPhysical.constantName}
data->primary_logical_key = ${toHex(primaryLogical.value, digits: 11)};$pad // ${primaryLogical.constantName}''');
if (secondaryLogical != null) {
result.writeln('''
data->secondary_logical_key = ${toHex(secondaryLogical.value, digits: 11)}; // ${secondaryLogical.constantName}''');
}
});
return result.toString().trimRight();
}
String get _gtkModifierBitMap {
return constructMapFromModToKeys(_modifierBitMapping, keyData, logicalData, 'gtkModifierBitMap');
}
final Map<String, List<String>> _modifierBitMapping;
String get _gtkModeBitMap {
return constructMapFromModToKeys(_lockBitMapping, keyData, logicalData, 'gtkModeBitMap');
}
final Map<String, List<String>> _lockBitMapping;
final Map<String, bool> _layoutGoals;
String get _layoutGoalsString {
final OutputLines<int> lines = OutputLines<int>('GTK layout goals');
_layoutGoals.forEach((String name, bool mandatory) {
final PhysicalKeyEntry physicalEntry = keyData.entryByName(name);
final LogicalKeyEntry logicalEntry = logicalData.entryByName(name);
final String line = 'LayoutGoal{'
'${toHex(physicalEntry.xKbScanCode, digits: 2)}, '
'${toHex(logicalEntry.value, digits: 2)}, '
'${mandatory ? 'true' : 'false'}'
'},';
lines.add(logicalEntry.value,
' ${line.padRight(39)}'
'// ${logicalEntry.name}');
});
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,
kGtkPlane,
];
for (final MaskConstant constant in maskConstants) {
buffer.writeln('const uint64_t k${constant.upperCamelName} = ${toHex(constant.value, digits: 11)};');
}
return buffer.toString().trimRight();
}
@override
String get templatePath => path.join(dataRoot, 'gtk_key_mapping_cc.tmpl');
@override
String outputPath(String platform) => path.join(PlatformCodeGenerator.engineRoot,
'shell', 'platform', 'linux', 'key_mapping.g.cc');
@override
Map<String, String> mappings() {
return <String, String>{
'XKB_SCAN_CODE_MAP': _xkbScanCodeMap,
'GTK_KEYVAL_CODE_MAP': _gtkKeyvalCodeMap,
'GTK_MODIFIER_BIT_MAP': _gtkModifierBitMap,
'GTK_MODE_BIT_MAP': _gtkModeBitMap,
'MASK_CONSTANTS': _maskConstants,
'LAYOUT_GOALS': _layoutGoalsString,
};
}
}
| flutter/dev/tools/gen_keycodes/lib/gtk_code_gen.dart/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/lib/gtk_code_gen.dart",
"repo_id": "flutter",
"token_count": 2168
} | 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.
// This program generates getMaterialTranslation(), getCupertinoTranslation(),
// and getWidgetsTranslation() functions that look up the translations provided by
// the arb files. The returned value is a generated instance of a
// GlobalMaterialLocalizations, GlobalCupertinoLocalizations, or
// GlobalWidgetsLocalizations object that corresponds to a single locale.
//
// The *.arb files are in packages/flutter_localizations/lib/src/l10n.
//
// The arb (JSON) format files must contain a single map indexed by locale.
// Each map value is itself a map with resource identifier keys and localized
// resource string values.
//
// The arb filenames are expected to have the form "material_(\w+)\.arb" or
// "cupertino_(\w+)\.arb" where the group following "_" identifies the language
// code and the country code, e.g. "material_en.arb" or "material_en_GB.arb".
// In most cases both codes are just two characters.
//
// This app is typically run by hand when a module's .arb files have been
// updated.
//
// ## Usage
//
// Run this program from the root of the git repository.
//
// The following outputs the generated Dart code to the console as a dry run:
//
// ```
// dart dev/tools/localization/bin/gen_localizations.dart
// ```
//
// If you have removed localizations from the canonical localizations, then
// add the '--remove-undefined' flag to also remove them from the other files.
//
// ```
// dart dev/tools/localization/bin/gen_localizations.dart --remove-undefined
// ```
//
// If the data looks good, use the `-w` or `--overwrite` option to overwrite the
// generated_material_localizations.dart, generated_cupertino_localizations.dart,
// and generated_widgets_localizations.dart files in packages/flutter_localizations/lib/src/l10n/:
//
// ```
// dart dev/tools/localization/bin/gen_localizations.dart --overwrite
// ```
import 'dart:io';
import 'package:path/path.dart' as path;
import '../gen_cupertino_localizations.dart';
import '../gen_material_localizations.dart';
import '../gen_widgets_localizations.dart';
import '../localizations_utils.dart';
import '../localizations_validator.dart';
import 'encode_kn_arb_files.dart';
/// This is the core of this script; it generates the code used for translations.
String generateArbBasedLocalizationSubclasses({
required Map<LocaleInfo, Map<String, String>> localeToResources,
required Map<LocaleInfo, Map<String, dynamic>> localeToResourceAttributes,
required String generatedClassPrefix,
required String baseClass,
required HeaderGenerator generateHeader,
required ConstructorGenerator generateConstructor,
ConstructorGenerator? generateConstructorForCountrySubClass,
required String factoryName,
required String factoryDeclaration,
required bool callsFactoryWithConst,
required String factoryArguments,
required String supportedLanguagesConstant,
required String supportedLanguagesDocMacro,
}) {
assert(generatedClassPrefix.isNotEmpty);
assert(baseClass.isNotEmpty);
assert(factoryName.isNotEmpty);
assert(factoryDeclaration.isNotEmpty);
assert(factoryArguments.isNotEmpty);
assert(supportedLanguagesConstant.isNotEmpty);
assert(supportedLanguagesDocMacro.isNotEmpty);
generateConstructorForCountrySubClass ??= generateConstructor;
final StringBuffer output = StringBuffer();
output.writeln(generateHeader('dart dev/tools/localization/bin/gen_localizations.dart --overwrite'));
final StringBuffer supportedLocales = StringBuffer();
final Map<String, List<LocaleInfo>> languageToLocales = <String, List<LocaleInfo>>{};
final Map<String, Set<String>> languageToScriptCodes = <String, Set<String>>{};
// Used to calculate if there are any corresponding countries for a given language and script.
final Map<LocaleInfo, Set<String>> languageAndScriptToCountryCodes = <LocaleInfo, Set<String>>{};
final Set<String> allResourceIdentifiers = <String>{};
for (final LocaleInfo locale in localeToResources.keys.toList()..sort()) {
if (locale.scriptCode != null) {
languageToScriptCodes[locale.languageCode] ??= <String>{};
languageToScriptCodes[locale.languageCode]!.add(locale.scriptCode!);
}
if (locale.countryCode != null && locale.scriptCode != null) {
final LocaleInfo key = LocaleInfo.fromString('${locale.languageCode}_${locale.scriptCode}');
languageAndScriptToCountryCodes[key] ??= <String>{};
languageAndScriptToCountryCodes[key]!.add(locale.countryCode!);
}
languageToLocales[locale.languageCode] ??= <LocaleInfo>[];
languageToLocales[locale.languageCode]!.add(locale);
allResourceIdentifiers.addAll(localeToResources[locale]!.keys.toList()..sort());
}
// We generate one class per supported language (e.g.
// `MaterialLocalizationEn`). These implement everything that is needed by the
// superclass (e.g. GlobalMaterialLocalizations).
// We also generate one subclass for each locale with a script code (e.g.
// `MaterialLocalizationZhHant`). Their superclasses are the aforementioned
// language classes for the same locale but without a script code (e.g.
// `MaterialLocalizationZh`).
// We also generate one subclass for each locale with a country code (e.g.
// `MaterialLocalizationEnGb`). Their superclasses are the aforementioned
// language classes for the same locale but without a country code (e.g.
// `MaterialLocalizationEn`).
// If scriptCodes for a language are defined, we expect a scriptCode to be
// defined for locales that contain a countryCode. The superclass becomes
// the script subclass (e.g. `MaterialLocalizationZhHant`) and the generated
// subclass will also contain the script code (e.g. `MaterialLocalizationZhHantTW`).
// When scriptCodes are not defined for languages that use scriptCodes to distinguish
// between significantly differing scripts, we assume the scriptCodes in the
// [LocaleInfo.fromString] factory and add it to the [LocaleInfo]. We then generate
// the script classes based on the first locale that we assume to use the script.
final List<String> allKeys = allResourceIdentifiers.toList()..sort();
final List<String> languageCodes = languageToLocales.keys.toList()..sort();
final LocaleInfo canonicalLocale = LocaleInfo.fromString('en');
for (final String languageName in languageCodes) {
final LocaleInfo languageLocale = LocaleInfo.fromString(languageName);
output.writeln(generateClassDeclaration(languageLocale, generatedClassPrefix, baseClass));
output.writeln(generateConstructor(languageLocale));
final Map<String, String> languageResources = localeToResources[languageLocale]!;
for (final String key in allKeys) {
final Map<String, dynamic>? attributes = localeToResourceAttributes[canonicalLocale]![key] as Map<String, dynamic>?;
output.writeln(generateGetter(key, languageResources[key], attributes, languageLocale));
}
output.writeln('}');
int countryCodeCount = 0;
int scriptCodeCount = 0;
if (languageToScriptCodes.containsKey(languageName)) {
scriptCodeCount = languageToScriptCodes[languageName]!.length;
// Language has scriptCodes, so we need to properly fallback countries to corresponding
// script default values before language default values.
for (final String scriptCode in languageToScriptCodes[languageName]!) {
final LocaleInfo scriptBaseLocale = LocaleInfo.fromString('${languageName}_$scriptCode');
output.writeln(generateClassDeclaration(
scriptBaseLocale,
generatedClassPrefix,
'$generatedClassPrefix${languageLocale.camelCase()}',
));
output.writeln(generateConstructorForCountrySubClass(scriptBaseLocale));
final Map<String, String> scriptResources = localeToResources[scriptBaseLocale]!;
for (final String key in scriptResources.keys.toList()..sort()) {
if (languageResources[key] == scriptResources[key]) {
continue;
}
final Map<String, dynamic>? attributes = localeToResourceAttributes[canonicalLocale]![key] as Map<String, dynamic>?;
output.writeln(generateGetter(key, scriptResources[key], attributes, languageLocale));
}
output.writeln('}');
final List<LocaleInfo> localeCodes = languageToLocales[languageName]!..sort();
for (final LocaleInfo locale in localeCodes) {
if (locale.originalString == languageName) {
continue;
}
if (locale.originalString == '${languageName}_$scriptCode') {
continue;
}
if (locale.scriptCode != scriptCode) {
continue;
}
countryCodeCount += 1;
output.writeln(generateClassDeclaration(
locale,
generatedClassPrefix,
'$generatedClassPrefix${scriptBaseLocale.camelCase()}',
));
output.writeln(generateConstructorForCountrySubClass(locale));
final Map<String, String> localeResources = localeToResources[locale]!;
for (final String key in localeResources.keys) {
// When script fallback contains the key, we compare to it instead of language fallback.
if (scriptResources.containsKey(key) ? scriptResources[key] == localeResources[key] : languageResources[key] == localeResources[key]) {
continue;
}
final Map<String, dynamic>? attributes = localeToResourceAttributes[canonicalLocale]![key] as Map<String, dynamic>?;
output.writeln(generateGetter(key, localeResources[key], attributes, languageLocale));
}
output.writeln('}');
}
}
} else {
// No scriptCode. Here, we do not compare against script default (because it
// doesn't exist).
final List<LocaleInfo> localeCodes = languageToLocales[languageName]!..sort();
for (final LocaleInfo locale in localeCodes) {
if (locale.originalString == languageName) {
continue;
}
countryCodeCount += 1;
final Map<String, String> localeResources = localeToResources[locale]!;
output.writeln(generateClassDeclaration(
locale,
generatedClassPrefix,
'$generatedClassPrefix${languageLocale.camelCase()}',
));
output.writeln(generateConstructorForCountrySubClass(locale));
for (final String key in localeResources.keys) {
if (languageResources[key] == localeResources[key]) {
continue;
}
final Map<String, dynamic>? attributes = localeToResourceAttributes[canonicalLocale]![key] as Map<String, dynamic>?;
output.writeln(generateGetter(key, localeResources[key], attributes, languageLocale));
}
output.writeln('}');
}
}
final String scriptCodeMessage = scriptCodeCount == 0 ? '' : ' and $scriptCodeCount script${scriptCodeCount == 1 ? '' : 's'}';
if (countryCodeCount == 0) {
if (scriptCodeCount == 0) {
supportedLocales.writeln('/// * `$languageName` - ${describeLocale(languageName)}');
} else {
supportedLocales.writeln('/// * `$languageName` - ${describeLocale(languageName)} (plus $scriptCodeCount script${scriptCodeCount == 1 ? '' : 's'})');
}
} else if (countryCodeCount == 1) {
supportedLocales.writeln('/// * `$languageName` - ${describeLocale(languageName)} (plus one country variation$scriptCodeMessage)');
} else {
supportedLocales.writeln('/// * `$languageName` - ${describeLocale(languageName)} (plus $countryCodeCount country variations$scriptCodeMessage)');
}
}
// Generate the factory function. Given a Locale it returns the corresponding
// base class implementation.
output.writeln('''
/// The set of supported languages, as language code strings.
///
/// The [$baseClass.delegate] can generate localizations for
/// any [Locale] with a language code from this set, regardless of the region.
/// Some regions have specific support (e.g. `de` covers all forms of German,
/// but there is support for `de-CH` specifically to override some of the
/// translations for Switzerland).
///
/// See also:
///
/// * [$factoryName], whose documentation describes these values.
final Set<String> $supportedLanguagesConstant = HashSet<String>.from(const <String>[
${languageCodes.map<String>((String value) => " '$value', // ${describeLocale(value)}").toList().join('\n')}
]);
/// Creates a [$baseClass] instance for the given `locale`.
///
/// All of the function's arguments except `locale` will be passed to the [
/// $baseClass] constructor. (The `localeName` argument of that
/// constructor is specified by the actual subclass constructor by this
/// function.)
///
/// The following locales are supported by this package:
///
/// {@template $supportedLanguagesDocMacro}
$supportedLocales/// {@endtemplate}
///
/// Generally speaking, this method is only intended to be used by
/// [$baseClass.delegate].
$factoryDeclaration
switch (locale.languageCode) {''');
for (final String language in languageToLocales.keys) {
// Only one instance of the language.
if (languageToLocales[language]!.length == 1) {
output.writeln('''
case '$language':
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${languageToLocales[language]![0].camelCase()}($factoryArguments);''');
} else if (!languageToScriptCodes.containsKey(language)) { // Does not distinguish between scripts. Switch on countryCode directly.
output.writeln('''
case '$language': {
switch (locale.countryCode) {''');
for (final LocaleInfo locale in languageToLocales[language]!) {
if (locale.originalString == language) {
continue;
}
assert(locale.length > 1);
final String countryCode = locale.countryCode!;
output.writeln('''
case '$countryCode':
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${locale.camelCase()}($factoryArguments);''');
}
output.writeln('''
}
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${LocaleInfo.fromString(language).camelCase()}($factoryArguments);
}''');
} else { // Language has scriptCode, add additional switch logic.
bool hasCountryCode = false;
output.writeln('''
case '$language': {
switch (locale.scriptCode) {''');
for (final String scriptCode in languageToScriptCodes[language]!) {
final LocaleInfo scriptLocale = LocaleInfo.fromString('${language}_$scriptCode');
output.writeln('''
case '$scriptCode': {''');
if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) {
output.writeln('''
switch (locale.countryCode) {''');
for (final LocaleInfo locale in languageToLocales[language]!) {
if (locale.countryCode == null) {
continue;
} else {
hasCountryCode = true;
}
if (locale.originalString == language) {
continue;
}
if (locale.scriptCode != scriptCode && locale.scriptCode != null) {
continue;
}
final String countryCode = locale.countryCode!;
output.writeln('''
case '$countryCode':
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${locale.camelCase()}($factoryArguments);''');
}
}
// Return a fallback locale that matches scriptCode, but not countryCode.
//
// Explicitly defined scriptCode fallback:
if (languageToLocales[language]!.contains(scriptLocale)) {
if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) {
output.writeln('''
}''');
}
output.writeln('''
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${scriptLocale.camelCase()}($factoryArguments);
}''');
} else {
// Not Explicitly defined, fallback to first locale with the same language and
// script:
for (final LocaleInfo locale in languageToLocales[language]!) {
if (locale.scriptCode != scriptCode) {
continue;
}
if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) {
output.writeln('''
}''');
}
output.writeln('''
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${scriptLocale.camelCase()}($factoryArguments);
}''');
break;
}
}
}
output.writeln('''
}''');
if (hasCountryCode) {
output.writeln('''
switch (locale.countryCode) {''');
for (final LocaleInfo locale in languageToLocales[language]!) {
if (locale.originalString == language) {
continue;
}
assert(locale.length > 1);
if (locale.countryCode == null) {
continue;
}
final String countryCode = locale.countryCode!;
output.writeln('''
case '$countryCode':
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${locale.camelCase()}($factoryArguments);''');
}
output.writeln('''
}''');
}
output.writeln('''
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${LocaleInfo.fromString(language).camelCase()}($factoryArguments);
}''');
}
}
output.writeln('''
}
assert(false, '$factoryName() called for unsupported locale "\$locale"');
return null;
}''');
return output.toString();
}
/// Returns the appropriate type for getters with the given attributes.
///
/// Typically "String", but some (e.g. "timeOfDayFormat") return enums.
///
/// Used by [generateGetter] below.
String generateType(Map<String, dynamic>? attributes) {
bool optional = false;
String type = 'String';
if (attributes != null) {
optional = attributes.containsKey('optional');
switch (attributes['x-flutter-type'] as String?) {
case 'icuShortTimePattern':
type = 'TimeOfDayFormat';
case 'scriptCategory':
type = 'ScriptCategory';
}
}
return type + (optional ? '?' : '');
}
/// Returns the appropriate name for getters with the given attributes.
///
/// Typically this is the key unmodified, but some have parameters, and
/// the GlobalMaterialLocalizations class does the substitution, and for
/// those we have to therefore provide an alternate name.
///
/// Used by [generateGetter] below.
String generateKey(String key, Map<String, dynamic>? attributes) {
if (attributes != null) {
if (attributes.containsKey('parameters')) {
return '${key}Raw';
}
switch (attributes['x-flutter-type'] as String?) {
case 'icuShortTimePattern':
return '${key}Raw';
}
}
if (key == 'datePickerDateOrder') {
return 'datePickerDateOrderString';
}
if (key == 'datePickerDateTimeOrder') {
return 'datePickerDateTimeOrderString';
}
return key;
}
const Map<String, String> _icuTimeOfDayToEnum = <String, String>{
'HH:mm': 'TimeOfDayFormat.HH_colon_mm',
'HH.mm': 'TimeOfDayFormat.HH_dot_mm',
"HH 'h' mm": 'TimeOfDayFormat.frenchCanadian',
'HH:mm น.': 'TimeOfDayFormat.HH_colon_mm',
'H:mm': 'TimeOfDayFormat.H_colon_mm',
'h:mm a': 'TimeOfDayFormat.h_colon_mm_space_a',
'a h:mm': 'TimeOfDayFormat.a_space_h_colon_mm',
'ah:mm': 'TimeOfDayFormat.a_space_h_colon_mm',
};
const Map<String, String> _scriptCategoryToEnum = <String, String>{
'English-like': 'ScriptCategory.englishLike',
'dense': 'ScriptCategory.dense',
'tall': 'ScriptCategory.tall',
};
/// Returns the literal that describes the value returned by getters
/// with the given attributes.
///
/// This handles cases like the value being a literal `null`, an enum, and so
/// on. The default is to treat the value as a string and escape it and quote
/// it.
///
/// Used by [generateGetter] below.
String? generateValue(String? value, Map<String, dynamic>? attributes, LocaleInfo locale) {
if (value == null) {
return null;
}
// cupertino_en.arb doesn't use x-flutter-type.
if (attributes != null) {
switch (attributes['x-flutter-type'] as String?) {
case 'icuShortTimePattern':
if (!_icuTimeOfDayToEnum.containsKey(value)) {
throw Exception(
'"$value" is not one of the ICU short time patterns supported '
'by the material library. Here is the list of supported '
'patterns:\n ${_icuTimeOfDayToEnum.keys.join('\n ')}'
);
}
return _icuTimeOfDayToEnum[value];
case 'scriptCategory':
if (!_scriptCategoryToEnum.containsKey(value)) {
throw Exception(
'"$value" is not one of the scriptCategory values supported '
'by the material library. Here is the list of supported '
'values:\n ${_scriptCategoryToEnum.keys.join('\n ')}'
);
}
return _scriptCategoryToEnum[value];
}
}
return generateEncodedString(locale.languageCode, value);
}
/// Combines [generateType], [generateKey], and [generateValue] to return
/// the source of getters for the GlobalMaterialLocalizations subclass.
/// The locale is the locale for which the getter is being generated.
String generateGetter(String key, String? value, Map<String, dynamic>? attributes, LocaleInfo locale) {
final String type = generateType(attributes);
key = generateKey(key, attributes);
final String? generatedValue = generateValue(value, attributes, locale);
return '''
@override
$type get $key => $generatedValue;''';
}
void main(List<String> rawArgs) {
checkCwdIsRepoRoot('gen_localizations');
final GeneratorOptions options = parseArgs(rawArgs);
// filenames are assumed to end in "prefix_lc.arb" or "prefix_lc_cc.arb", where prefix
// is the 2nd command line argument, lc is a language code and cc is the country
// code. In most cases both codes are just two characters.
final Directory directory = Directory(path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n'));
final RegExp widgetsFilenameRE = RegExp(r'widgets_(\w+)\.arb$');
final RegExp materialFilenameRE = RegExp(r'material_(\w+)\.arb$');
final RegExp cupertinoFilenameRE = RegExp(r'cupertino_(\w+)\.arb$');
try {
validateEnglishLocalizations(File(path.join(directory.path, 'widgets_en.arb')));
validateEnglishLocalizations(File(path.join(directory.path, 'material_en.arb')));
validateEnglishLocalizations(File(path.join(directory.path, 'cupertino_en.arb')));
} on ValidationError catch (exception) {
exitWithError('$exception');
}
// Only rewrite material_kn.arb and cupertino_en.arb if overwriting the
// Material and Cupertino localizations files.
if (options.writeToFile) {
// Encodes the material_kn.arb file and the cupertino_en.arb files before
// generating localizations. This prevents a subset of Emacs users from
// crashing when opening up the Flutter source code.
// See https://github.com/flutter/flutter/issues/36704 for more context.
encodeKnArbFiles(directory);
}
precacheLanguageAndRegionTags();
// Maps of locales to resource key/value pairs for Widgets ARBs.
final Map<LocaleInfo, Map<String, String>> widgetsLocaleToResources = <LocaleInfo, Map<String, String>>{};
// Maps of locales to resource key/attributes pairs for Widgets ARBs.
// https://github.com/googlei18n/app-resource-bundle/wiki/ApplicationResourceBundleSpecification#resource-attributes
final Map<LocaleInfo, Map<String, dynamic>> widgetsLocaleToResourceAttributes = <LocaleInfo, Map<String, dynamic>>{};
// Maps of locales to resource key/value pairs for Material ARBs.
final Map<LocaleInfo, Map<String, String>> materialLocaleToResources = <LocaleInfo, Map<String, String>>{};
// Maps of locales to resource key/attributes pairs for Material ARBs.
// https://github.com/googlei18n/app-resource-bundle/wiki/ApplicationResourceBundleSpecification#resource-attributes
final Map<LocaleInfo, Map<String, dynamic>> materialLocaleToResourceAttributes = <LocaleInfo, Map<String, dynamic>>{};
// Maps of locales to resource key/value pairs for Cupertino ARBs.
final Map<LocaleInfo, Map<String, String>> cupertinoLocaleToResources = <LocaleInfo, Map<String, String>>{};
// Maps of locales to resource key/attributes pairs for Cupertino ARBs.
// https://github.com/googlei18n/app-resource-bundle/wiki/ApplicationResourceBundleSpecification#resource-attributes
final Map<LocaleInfo, Map<String, dynamic>> cupertinoLocaleToResourceAttributes = <LocaleInfo, Map<String, dynamic>>{};
loadMatchingArbsIntoBundleMaps(
directory: directory,
filenamePattern: widgetsFilenameRE,
localeToResources: widgetsLocaleToResources,
localeToResourceAttributes: widgetsLocaleToResourceAttributes,
);
loadMatchingArbsIntoBundleMaps(
directory: directory,
filenamePattern: materialFilenameRE,
localeToResources: materialLocaleToResources,
localeToResourceAttributes: materialLocaleToResourceAttributes,
);
loadMatchingArbsIntoBundleMaps(
directory: directory,
filenamePattern: cupertinoFilenameRE,
localeToResources: cupertinoLocaleToResources,
localeToResourceAttributes: cupertinoLocaleToResourceAttributes,
);
try {
validateLocalizations(widgetsLocaleToResources, widgetsLocaleToResourceAttributes, removeUndefined: options.removeUndefined);
validateLocalizations(materialLocaleToResources, materialLocaleToResourceAttributes, removeUndefined: options.removeUndefined);
validateLocalizations(cupertinoLocaleToResources, cupertinoLocaleToResourceAttributes, removeUndefined: options.removeUndefined);
} on ValidationError catch (exception) {
exitWithError('$exception');
}
if (options.removeUndefined) {
removeUndefinedLocalizations(widgetsLocaleToResources);
removeUndefinedLocalizations(materialLocaleToResources);
removeUndefinedLocalizations(cupertinoLocaleToResources);
}
final String? widgetsLocalizations = options.writeToFile || !options.cupertinoOnly
? generateArbBasedLocalizationSubclasses(
localeToResources: widgetsLocaleToResources,
localeToResourceAttributes: widgetsLocaleToResourceAttributes,
generatedClassPrefix: 'WidgetsLocalization',
baseClass: 'GlobalWidgetsLocalizations',
generateHeader: generateWidgetsHeader,
generateConstructor: generateWidgetsConstructor,
generateConstructorForCountrySubClass: generateWidgetsConstructorForCountrySubclass,
factoryName: widgetsFactoryName,
factoryDeclaration: widgetsFactoryDeclaration,
callsFactoryWithConst: true,
factoryArguments: widgetsFactoryArguments,
supportedLanguagesConstant: widgetsSupportedLanguagesConstant,
supportedLanguagesDocMacro: widgetsSupportedLanguagesDocMacro,
)
: null;
final String? materialLocalizations = options.writeToFile || !options.cupertinoOnly
? generateArbBasedLocalizationSubclasses(
localeToResources: materialLocaleToResources,
localeToResourceAttributes: materialLocaleToResourceAttributes,
generatedClassPrefix: 'MaterialLocalization',
baseClass: 'GlobalMaterialLocalizations',
generateHeader: generateMaterialHeader,
generateConstructor: generateMaterialConstructor,
factoryName: materialFactoryName,
factoryDeclaration: materialFactoryDeclaration,
callsFactoryWithConst: false,
factoryArguments: materialFactoryArguments,
supportedLanguagesConstant: materialSupportedLanguagesConstant,
supportedLanguagesDocMacro: materialSupportedLanguagesDocMacro,
)
: null;
final String? cupertinoLocalizations = options.writeToFile || !options.materialOnly
? generateArbBasedLocalizationSubclasses(
localeToResources: cupertinoLocaleToResources,
localeToResourceAttributes: cupertinoLocaleToResourceAttributes,
generatedClassPrefix: 'CupertinoLocalization',
baseClass: 'GlobalCupertinoLocalizations',
generateHeader: generateCupertinoHeader,
generateConstructor: generateCupertinoConstructor,
factoryName: cupertinoFactoryName,
factoryDeclaration: cupertinoFactoryDeclaration,
callsFactoryWithConst: false,
factoryArguments: cupertinoFactoryArguments,
supportedLanguagesConstant: cupertinoSupportedLanguagesConstant,
supportedLanguagesDocMacro: cupertinoSupportedLanguagesDocMacro,
)
: null;
if (options.writeToFile) {
final File widgetsLocalizationsFile = File(path.join(directory.path, 'generated_widgets_localizations.dart'));
widgetsLocalizationsFile.writeAsStringSync(widgetsLocalizations!, flush: true);
final File materialLocalizationsFile = File(path.join(directory.path, 'generated_material_localizations.dart'));
materialLocalizationsFile.writeAsStringSync(materialLocalizations!, flush: true);
final File cupertinoLocalizationsFile = File(path.join(directory.path, 'generated_cupertino_localizations.dart'));
cupertinoLocalizationsFile.writeAsStringSync(cupertinoLocalizations!, flush: true);
} else {
if (options.cupertinoOnly) {
stdout.write(cupertinoLocalizations);
} else if (options.materialOnly) {
stdout.write(materialLocalizations);
} else if (options.widgetsOnly) {
stdout.write(widgetsLocalizations);
} else {
stdout.write(widgetsLocalizations);
stdout.write(materialLocalizations);
stdout.write(cupertinoLocalizations);
}
}
}
| flutter/dev/tools/localization/bin/gen_localizations.dart/0 | {
"file_path": "flutter/dev/tools/localization/bin/gen_localizations.dart",
"repo_id": "flutter",
"token_count": 10248
} | 551 |
# vitool
This tool generates Dart files from frames described in SVG files that follow
the small subset of SVG described below.
This tool was crafted specifically to handle the assets for certain Material
design animations as created by the Google Material Design team, and is not
intended to be a general-purpose tool.
## Supported SVG features
- groups
- group transforms
- group opacities
- paths (strokes are not supported, only fills, elliptical arc curve commands are not supported)
| flutter/dev/tools/vitool/README.md/0 | {
"file_path": "flutter/dev/tools/vitool/README.md",
"repo_id": "flutter",
"token_count": 112
} | 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/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_test/flutter_test.dart';
import 'common.dart';
final Set<String> interestingLabels = <String>{
'BUILD',
'LAYOUT',
'UPDATING COMPOSITING BITS',
'PAINT',
'COMPOSITING',
'FINALIZE TREE',
'$Placeholder',
'$CustomPaint',
'$RenderCustomPaint',
};
class TestRoot extends StatefulWidget {
const TestRoot({ super.key });
static late final TestRootState state;
@override
State<TestRoot> createState() => TestRootState();
}
class TestRootState extends State<TestRoot> {
@override
void initState() {
super.initState();
TestRoot.state = this;
}
Widget _widget = const Placeholder();
void updateWidget(Widget newWidget) {
setState(() {
_widget = newWidget;
});
}
void rebuild() {
setState(() {
// no change, just force a rebuild
});
}
@override
Widget build(BuildContext context) {
return _widget;
}
}
void main() {
ZoneIgnoringTestBinding.ensureInitialized();
initTimelineTests();
test('Timeline', () async {
// We don't have expectations around the first frame because there's a race around
// the warm-up frame that we don't want to get involved in here.
await runFrame(() { runApp(const TestRoot()); });
await SchedulerBinding.instance.endOfFrame;
await fetchInterestingEvents(interestingLabels);
// The next few cases build the exact same tree so should have no effect.
debugProfileBuildsEnabled = true;
await runFrame(() { TestRoot.state.rebuild(); });
expect(
await fetchInterestingEventNames(interestingLabels),
<String>['BUILD', 'LAYOUT', 'UPDATING COMPOSITING BITS', 'PAINT', 'COMPOSITING', 'FINALIZE TREE'],
);
debugProfileBuildsEnabled = false;
debugProfileLayoutsEnabled = true;
await runFrame(() { TestRoot.state.rebuild(); });
expect(
await fetchInterestingEventNames(interestingLabels),
<String>['BUILD', 'LAYOUT', 'UPDATING COMPOSITING BITS', 'PAINT', 'COMPOSITING', 'FINALIZE TREE'],
);
debugProfileLayoutsEnabled = false;
debugProfilePaintsEnabled = true;
await runFrame(() { TestRoot.state.rebuild(); });
expect(
await fetchInterestingEventNames(interestingLabels),
<String>['BUILD', 'LAYOUT', 'UPDATING COMPOSITING BITS', 'PAINT', 'COMPOSITING', 'FINALIZE TREE'],
);
debugProfilePaintsEnabled = false;
// Now we replace the widgets each time to cause a rebuild.
List<TimelineEvent> events;
Map<String, String> args;
debugProfileBuildsEnabled = true;
debugEnhanceBuildTimelineArguments = true;
await runFrame(() { TestRoot.state.updateWidget(Placeholder(key: UniqueKey(), color: const Color(0xFFFFFFFF))); });
events = await fetchInterestingEvents(interestingLabels);
expect(
events.map<String>(eventToName),
<String>['BUILD', 'Placeholder', 'CustomPaint', 'LAYOUT', 'UPDATING COMPOSITING BITS', 'PAINT', 'COMPOSITING', 'FINALIZE TREE'],
);
args = (events.where((TimelineEvent event) => event.json!['name'] == '$Placeholder').single.json!['args'] as Map<String, Object?>).cast<String, String>();
expect(args['color'], 'Color(0xffffffff)');
debugProfileBuildsEnabled = false;
debugEnhanceBuildTimelineArguments = false;
debugProfileBuildsEnabledUserWidgets = true;
debugEnhanceBuildTimelineArguments = true;
await runFrame(() { TestRoot.state.updateWidget(Placeholder(key: UniqueKey(), color: const Color(0xFFFFFFFF))); });
events = await fetchInterestingEvents(interestingLabels);
expect(
events.map<String>(eventToName),
<String>['BUILD', 'Placeholder', 'LAYOUT', 'UPDATING COMPOSITING BITS', 'PAINT', 'COMPOSITING', 'FINALIZE TREE'],
);
args = (events.where((TimelineEvent event) => event.json!['name'] == '$Placeholder').single.json!['args'] as Map<String, Object?>).cast<String, String>();
expect(args['color'], 'Color(0xffffffff)');
debugProfileBuildsEnabledUserWidgets = false;
debugEnhanceBuildTimelineArguments = false;
debugProfileLayoutsEnabled = true;
debugEnhanceLayoutTimelineArguments = true;
await runFrame(() { TestRoot.state.updateWidget(Placeholder(key: UniqueKey())); });
events = await fetchInterestingEvents(interestingLabels);
expect(
events.map<String>(eventToName),
<String>['BUILD', 'LAYOUT', 'RenderCustomPaint', 'UPDATING COMPOSITING BITS', 'PAINT', 'COMPOSITING', 'FINALIZE TREE'],
);
args = (events.where((TimelineEvent event) => event.json!['name'] == '$RenderCustomPaint').single.json!['args'] as Map<String, Object?>).cast<String, String>();
expect(args['creator'], startsWith('CustomPaint'));
expect(args['creator'], contains('Placeholder'));
expect(args['painter'], startsWith('_PlaceholderPainter#'));
debugProfileLayoutsEnabled = false;
debugEnhanceLayoutTimelineArguments = false;
debugProfilePaintsEnabled = true;
debugEnhancePaintTimelineArguments = true;
await runFrame(() { TestRoot.state.updateWidget(Placeholder(key: UniqueKey())); });
events = await fetchInterestingEvents(interestingLabels);
expect(
events.map<String>(eventToName),
<String>['BUILD', 'LAYOUT', 'UPDATING COMPOSITING BITS', 'PAINT', 'RenderCustomPaint', 'COMPOSITING', 'FINALIZE TREE'],
);
args = (events.where((TimelineEvent event) => event.json!['name'] == '$RenderCustomPaint').single.json!['args'] as Map<String, Object?>).cast<String, String>();
expect(args['creator'], startsWith('CustomPaint'));
expect(args['creator'], contains('Placeholder'));
expect(args['painter'], startsWith('_PlaceholderPainter#'));
debugProfilePaintsEnabled = false;
debugEnhancePaintTimelineArguments = false;
}, skip: isBrowser); // [intended] uses dart:isolate and io.
}
| flutter/dev/tracing_tests/test/timeline_test.dart/0 | {
"file_path": "flutter/dev/tracing_tests/test/timeline_test.dart",
"repo_id": "flutter",
"token_count": 2100
} | 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 'package:flutter/cupertino.dart';
/// Flutter code sample for [CupertinoTabBar].
void main() => runApp(const CupertinoTabBarApp());
class CupertinoTabBarApp extends StatelessWidget {
const CupertinoTabBarApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
theme: CupertinoThemeData(brightness: Brightness.light),
home: CupertinoTabBarExample(),
);
}
}
class CupertinoTabBarExample extends StatelessWidget {
const CupertinoTabBarExample({super.key});
@override
Widget build(BuildContext context) {
return CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.star_fill),
label: 'Favorites',
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.clock_solid),
label: 'Recents',
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.person_alt_circle_fill),
label: 'Contacts',
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.circle_grid_3x3_fill),
label: 'Keypad',
),
],
),
tabBuilder: (BuildContext context, int index) {
return CupertinoTabView(
builder: (BuildContext context) {
return Center(
child: Text('Content of tab $index'),
);
},
);
},
);
}
}
| flutter/examples/api/lib/cupertino/bottom_tab_bar/cupertino_tab_bar.0.dart/0 | {
"file_path": "flutter/examples/api/lib/cupertino/bottom_tab_bar/cupertino_tab_bar.0.dart",
"repo_id": "flutter",
"token_count": 732
} | 554 |
// 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 [CupertinoRadio.toggleable].
void main() => runApp(const CupertinoRadioApp());
class CupertinoRadioApp extends StatelessWidget {
const CupertinoRadioApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
home: CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('CupertinoRadio Toggleable Example'),
),
child: SafeArea(
child: CupertinoRadioExample(),
),
),
);
}
}
enum SingingCharacter { mulligan, hamilton }
class CupertinoRadioExample extends StatefulWidget {
const CupertinoRadioExample({super.key});
@override
State<CupertinoRadioExample> createState() => _CupertinoRadioExampleState();
}
class _CupertinoRadioExampleState extends State<CupertinoRadioExample> {
SingingCharacter? _character = SingingCharacter.mulligan;
@override
Widget build(BuildContext context) {
return CupertinoListSection(
children: <Widget>[
CupertinoListTile(
title: const Text('Hercules Mulligan'),
leading: CupertinoRadio<SingingCharacter>(
value: SingingCharacter.mulligan,
groupValue: _character,
// TRY THIS: Try setting the toggleable value to false and
// see how that changes the behavior of the widget.
toggleable: true,
onChanged: (SingingCharacter? value) {
setState(() {
_character = value;
});
},
),
),
CupertinoListTile(
title: const Text('Eliza Hamilton'),
leading: CupertinoRadio<SingingCharacter>(
value: SingingCharacter.hamilton,
groupValue: _character,
toggleable: true,
onChanged: (SingingCharacter? value) {
setState(() {
_character = value;
});
},
),
),
],
);
}
}
| flutter/examples/api/lib/cupertino/radio/cupertino_radio.toggleable.0.dart/0 | {
"file_path": "flutter/examples/api/lib/cupertino/radio/cupertino_radio.toggleable.0.dart",
"repo_id": "flutter",
"token_count": 919
} | 555 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
/// Flutter code sample for [PointerSignalResolver].
void main() => runApp(const PointerSignalResolverExampleApp());
class PointerSignalResolverExampleApp extends StatelessWidget {
const PointerSignalResolverExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: PointerSignalResolverExample(),
);
}
}
class ColorChanger extends StatefulWidget {
const ColorChanger({
super.key,
required this.initialColor,
required this.useResolver,
this.child,
});
final HSVColor initialColor;
final bool useResolver;
final Widget? child;
@override
State<ColorChanger> createState() => _ColorChangerState();
}
class _ColorChangerState extends State<ColorChanger> {
late HSVColor color;
void rotateColor() {
setState(() {
color = color.withHue((color.hue + 3) % 360.0);
});
}
@override
void initState() {
super.initState();
color = widget.initialColor;
}
@override
Widget build(BuildContext context) {
return DecoratedBox(
decoration: BoxDecoration(
border: const Border.fromBorderSide(BorderSide()),
color: color.toColor(),
),
child: Listener(
onPointerSignal: (PointerSignalEvent event) {
if (widget.useResolver) {
GestureBinding.instance.pointerSignalResolver.register(event, (PointerSignalEvent event) {
rotateColor();
});
} else {
rotateColor();
}
},
child: Stack(
fit: StackFit.expand,
children: <Widget>[
const AbsorbPointer(),
if (widget.child != null) widget.child!,
],
),
),
);
}
}
class PointerSignalResolverExample extends StatefulWidget {
const PointerSignalResolverExample({super.key});
@override
State<PointerSignalResolverExample> createState() => _PointerSignalResolverExampleState();
}
class _PointerSignalResolverExampleState extends State<PointerSignalResolverExample> {
bool useResolver = false;
@override
Widget build(BuildContext context) {
return Material(
child: Stack(
fit: StackFit.expand,
children: <Widget>[
ColorChanger(
initialColor: const HSVColor.fromAHSV(0.2, 120.0, 1, 1),
useResolver: useResolver,
child: FractionallySizedBox(
widthFactor: 0.5,
heightFactor: 0.5,
child: ColorChanger(
initialColor: const HSVColor.fromAHSV(1, 60.0, 1, 1),
useResolver: useResolver,
),
),
),
Align(
alignment: Alignment.topLeft,
child: Row(
children: <Widget>[
Switch(
value: useResolver,
onChanged: (bool value) {
setState(() {
useResolver = value;
});
},
),
const Text(
'Use the PointerSignalResolver?',
style: TextStyle(fontWeight: FontWeight.bold),
),
],
),
),
],
),
);
}
}
| flutter/examples/api/lib/gestures/pointer_signal_resolver/pointer_signal_resolver.0.dart/0 | {
"file_path": "flutter/examples/api/lib/gestures/pointer_signal_resolver/pointer_signal_resolver.0.dart",
"repo_id": "flutter",
"token_count": 1600
} | 556 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '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'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Type below to autocomplete the following possible results: ${AutocompleteBasicExample._kOptions}.'),
const AutocompleteBasicExample(),
],
),
),
),
);
}
}
class AutocompleteBasicExample extends StatelessWidget {
const AutocompleteBasicExample({super.key});
static const List<String> _kOptions = <String>[
'aardvark',
'bobcat',
'chameleon',
];
@override
Widget build(BuildContext context) {
return Autocomplete<String>(
optionsBuilder: (TextEditingValue textEditingValue) {
if (textEditingValue.text == '') {
return const Iterable<String>.empty();
}
return _kOptions.where((String option) {
return option.contains(textEditingValue.text.toLowerCase());
});
},
onSelected: (String selection) {
debugPrint('You just selected $selection');
},
);
}
}
| flutter/examples/api/lib/material/autocomplete/autocomplete.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/autocomplete/autocomplete.0.dart",
"repo_id": "flutter",
"token_count": 646
} | 557 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '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(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
leading: Icon(Icons.album),
title: Text('The Enchanted Nightingale'),
subtitle: Text('Music by Julie Gable. Lyrics by Sidney Stein.'),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TextButton(
child: const Text('BUY TICKETS'),
onPressed: () {/* ... */},
),
const SizedBox(width: 8),
TextButton(
child: const Text('LISTEN'),
onPressed: () {/* ... */},
),
const SizedBox(width: 8),
],
),
],
),
),
);
}
}
| flutter/examples/api/lib/material/card/card.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/card/card.0.dart",
"repo_id": "flutter",
"token_count": 761
} | 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.
// This example demonstrates showing the default buttons, but customizing their
// appearance.
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const EditableTextToolbarBuilderExampleApp());
class EditableTextToolbarBuilderExampleApp extends StatefulWidget {
const EditableTextToolbarBuilderExampleApp({super.key});
@override
State<EditableTextToolbarBuilderExampleApp> createState() => _EditableTextToolbarBuilderExampleAppState();
}
class _EditableTextToolbarBuilderExampleAppState extends State<EditableTextToolbarBuilderExampleApp> {
final TextEditingController _controller = TextEditingController(
text: 'Right click (desktop) or long press (mobile) to see the menu with custom buttons.',
);
@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 appearance'),
),
body: Center(
child: Column(
children: <Widget>[
const SizedBox(height: 20.0),
TextField(
controller: _controller,
contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) {
return AdaptiveTextSelectionToolbar(
anchors: editableTextState.contextMenuAnchors,
// Build the default buttons, but make them look custom.
// In a real project you may want to build different
// buttons depending on the platform.
children: editableTextState.contextMenuButtonItems.map((ContextMenuButtonItem buttonItem) {
return CupertinoButton(
borderRadius: null,
color: const Color(0xffaaaa00),
disabledColor: const Color(0xffaaaaff),
onPressed: buttonItem.onPressed,
padding: const EdgeInsets.all(10.0),
pressedOpacity: 0.7,
child: SizedBox(
width: 200.0,
child: Text(
CupertinoTextSelectionToolbarButton.getButtonLabel(context, buttonItem),
),
),
);
}).toList(),
);
},
),
],
),
),
),
);
}
}
| flutter/examples/api/lib/material/context_menu/editable_text_toolbar_builder.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/context_menu/editable_text_toolbar_builder.0.dart",
"repo_id": "flutter",
"token_count": 1393
} | 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 '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(
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 Center(
child: Column(
children: <Widget>[
const Expanded(
child: ColoredBox(
color: Colors.amber,
child: Center(
child: Text('Above'),
),
),
),
const Divider(
height: 20,
thickness: 5,
indent: 20,
endIndent: 0,
color: Colors.black,
),
// Subheader example from Material spec.
// https://material.io/components/dividers#types
Container(
padding: const EdgeInsets.only(left: 20),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: Text(
'Subheader',
style: Theme.of(context).textTheme.bodySmall,
textAlign: TextAlign.start,
),
),
),
Expanded(
child: ColoredBox(
color: Theme.of(context).colorScheme.primary,
child: const Center(
child: Text('Below'),
),
),
),
],
),
);
}
}
| flutter/examples/api/lib/material/divider/divider.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/divider/divider.0.dart",
"repo_id": "flutter",
"token_count": 926
} | 560 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [ExpansionTile] and [AnimationStyle].
void main() {
runApp(const ExpansionTileAnimationStyleApp());
}
enum AnimationStyles { defaultStyle, custom, none }
const List<(AnimationStyles, String)> animationStyleSegments = <(AnimationStyles, String)>[
(AnimationStyles.defaultStyle, 'Default'),
(AnimationStyles.custom, 'Custom'),
(AnimationStyles.none, 'None'),
];
class ExpansionTileAnimationStyleApp extends StatefulWidget {
const ExpansionTileAnimationStyleApp({super.key});
@override
State<ExpansionTileAnimationStyleApp> createState() => _ExpansionTileAnimationStyleAppState();
}
class _ExpansionTileAnimationStyleAppState extends State<ExpansionTileAnimationStyleApp> {
Set<AnimationStyles> _animationStyleSelection = <AnimationStyles>{AnimationStyles.defaultStyle};
AnimationStyle? _animationStyle;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Column(
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.emphasizedAccelerate,
duration: Durations.extralong1,
);
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: 20),
ExpansionTile(
expansionAnimationStyle: _animationStyle,
title: const Text('ExpansionTile'),
children: const <Widget>[
ListTile(title: Text('Expanded Item 1')),
ListTile(title: Text('Expanded Item 2')),
],
)
],
),
),
),
);
}
}
| flutter/examples/api/lib/material/expansion_tile/expansion_tile.2.dart/0 | {
"file_path": "flutter/examples/api/lib/material/expansion_tile/expansion_tile.2.dart",
"repo_id": "flutter",
"token_count": 1312
} | 561 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/material.dart';
const List<String> _pizzaToppings = <String>[
'Olives',
'Tomato',
'Cheese',
'Pepperoni',
'Bacon',
'Onion',
'Jalapeno',
'Mushrooms',
'Pineapple',
];
void main() => runApp(const EditableChipFieldApp());
class EditableChipFieldApp extends StatelessWidget {
const EditableChipFieldApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: const EditableChipFieldExample(),
);
}
}
class EditableChipFieldExample extends StatefulWidget {
const EditableChipFieldExample({super.key});
@override
EditableChipFieldExampleState createState() {
return EditableChipFieldExampleState();
}
}
class EditableChipFieldExampleState extends State<EditableChipFieldExample> {
final FocusNode _chipFocusNode = FocusNode();
List<String> _toppings = <String>[_pizzaToppings.first];
List<String> _suggestions = <String>[];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Editable Chip Field Sample'),
),
body: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: ChipsInput<String>(
values: _toppings,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.local_pizza_rounded),
hintText: 'Search for toppings',
),
strutStyle: const StrutStyle(fontSize: 15),
onChanged: _onChanged,
onSubmitted: _onSubmitted,
chipBuilder: _chipBuilder,
onTextChanged: _onSearchChanged,
),
),
if (_suggestions.isNotEmpty)
Expanded(
child: ListView.builder(
itemCount: _suggestions.length,
itemBuilder: (BuildContext context, int index) {
return ToppingSuggestion(
_suggestions[index],
onTap: _selectSuggestion,
);
},
),
),
],
),
);
}
Future<void> _onSearchChanged(String value) async {
final List<String> results = await _suggestionCallback(value);
setState(() {
_suggestions = results
.where((String topping) => !_toppings.contains(topping))
.toList();
});
}
Widget _chipBuilder(BuildContext context, String topping) {
return ToppingInputChip(
topping: topping,
onDeleted: _onChipDeleted,
onSelected: _onChipTapped,
);
}
void _selectSuggestion(String topping) {
setState(() {
_toppings.add(topping);
_suggestions = <String>[];
});
}
void _onChipTapped(String topping) {}
void _onChipDeleted(String topping) {
setState(() {
_toppings.remove(topping);
_suggestions = <String>[];
});
}
void _onSubmitted(String text) {
if (text.trim().isNotEmpty) {
setState(() {
_toppings = <String>[..._toppings, text.trim()];
});
} else {
_chipFocusNode.unfocus();
setState(() {
_toppings = <String>[];
});
}
}
void _onChanged(List<String> data) {
setState(() {
_toppings = data;
});
}
FutureOr<List<String>> _suggestionCallback(String text) {
if (text.isNotEmpty) {
return _pizzaToppings.where((String topping) {
return topping.toLowerCase().contains(text.toLowerCase());
}).toList();
}
return const <String>[];
}
}
class ChipsInput<T> extends StatefulWidget {
const ChipsInput({
super.key,
required this.values,
this.decoration = const InputDecoration(),
this.style,
this.strutStyle,
required this.chipBuilder,
required this.onChanged,
this.onChipTapped,
this.onSubmitted,
this.onTextChanged,
});
final List<T> values;
final InputDecoration decoration;
final TextStyle? style;
final StrutStyle? strutStyle;
final ValueChanged<List<T>> onChanged;
final ValueChanged<T>? onChipTapped;
final ValueChanged<String>? onSubmitted;
final ValueChanged<String>? onTextChanged;
final Widget Function(BuildContext context, T data) chipBuilder;
@override
ChipsInputState<T> createState() => ChipsInputState<T>();
}
class ChipsInputState<T> extends State<ChipsInput<T>> {
@visibleForTesting
late final ChipsInputEditingController<T> controller;
String _previousText = '';
TextSelection? _previousSelection;
@override
void initState() {
super.initState();
controller = ChipsInputEditingController<T>(
<T>[...widget.values],
widget.chipBuilder,
);
controller.addListener(_textListener);
}
@override
void dispose() {
controller.removeListener(_textListener);
controller.dispose();
super.dispose();
}
void _textListener() {
final String currentText = controller.text;
if (_previousSelection != null) {
final int currentNumber = countReplacements(currentText);
final int previousNumber = countReplacements(_previousText);
final int cursorEnd = _previousSelection!.extentOffset;
final int cursorStart = _previousSelection!.baseOffset;
final List<T> values = <T>[...widget.values];
// If the current number and the previous number of replacements are different, then
// the user has deleted the InputChip using the keyboard. In this case, we trigger
// the onChanged callback. We need to be sure also that the current number of
// replacements is different from the input chip to avoid double-deletion.
if (currentNumber < previousNumber && currentNumber != values.length) {
if (cursorStart == cursorEnd) {
values.removeRange(cursorStart - 1, cursorEnd);
} else {
if (cursorStart > cursorEnd) {
values.removeRange(cursorEnd, cursorStart);
} else {
values.removeRange(cursorStart, cursorEnd);
}
}
widget.onChanged(values);
}
}
_previousText = currentText;
_previousSelection = controller.selection;
}
static int countReplacements(String text) {
return text.codeUnits
.where((int u) => u == ChipsInputEditingController.kObjectReplacementChar)
.length;
}
@override
Widget build(BuildContext context) {
controller.updateValues(<T>[...widget.values]);
return TextField(
minLines: 1,
maxLines: 3,
textInputAction: TextInputAction.done,
style: widget.style,
strutStyle: widget.strutStyle,
controller: controller,
onChanged: (String value) =>
widget.onTextChanged?.call(controller.textWithoutReplacements),
onSubmitted: (String value) =>
widget.onSubmitted?.call(controller.textWithoutReplacements),
);
}
}
class ChipsInputEditingController<T> extends TextEditingController {
ChipsInputEditingController(this.values, this.chipBuilder)
: super(
text: String.fromCharCode(kObjectReplacementChar) * values.length,
);
// This constant character acts as a placeholder in the TextField text value.
// There will be one character for each of the InputChip displayed.
static const int kObjectReplacementChar = 0xFFFE;
List<T> values;
final Widget Function(BuildContext context, T data) chipBuilder;
/// Called whenever chip is either added or removed
/// from the outside the context of the text field.
void updateValues(List<T> values) {
if (values.length != this.values.length) {
final String char = String.fromCharCode(kObjectReplacementChar);
final int length = values.length;
value = TextEditingValue(
text: char * length,
selection: TextSelection.collapsed(offset: length),
);
this.values = values;
}
}
String get textWithoutReplacements {
final String char = String.fromCharCode(kObjectReplacementChar);
return text.replaceAll(RegExp(char), '');
}
String get textWithReplacements => text;
@override
TextSpan buildTextSpan(
{required BuildContext context, TextStyle? style, required bool withComposing}) {
final Iterable<WidgetSpan> chipWidgets =
values.map((T v) => WidgetSpan(child: chipBuilder(context, v)));
return TextSpan(
style: style,
children: <InlineSpan>[
...chipWidgets,
if (textWithoutReplacements.isNotEmpty)
TextSpan(text: textWithoutReplacements)
],
);
}
}
class ToppingSuggestion extends StatelessWidget {
const ToppingSuggestion(this.topping, {super.key, this.onTap});
final String topping;
final ValueChanged<String>? onTap;
@override
Widget build(BuildContext context) {
return ListTile(
key: ObjectKey(topping),
leading: CircleAvatar(
child: Text(
topping[0].toUpperCase(),
),
),
title: Text(topping),
onTap: () => onTap?.call(topping),
);
}
}
class ToppingInputChip extends StatelessWidget {
const ToppingInputChip({
super.key,
required this.topping,
required this.onDeleted,
required this.onSelected,
});
final String topping;
final ValueChanged<String> onDeleted;
final ValueChanged<String> onSelected;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(right: 3),
child: InputChip(
key: ObjectKey(topping),
label: Text(topping),
avatar: CircleAvatar(
child: Text(topping[0].toUpperCase()),
),
onDeleted: () => onDeleted(topping),
onSelected: (bool value) => onSelected(topping),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
padding: const EdgeInsets.all(2),
),
);
}
}
| flutter/examples/api/lib/material/input_chip/input_chip.1.dart/0 | {
"file_path": "flutter/examples/api/lib/material/input_chip/input_chip.1.dart",
"repo_id": "flutter",
"token_count": 3899
} | 562 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for custom list items.
void main() => runApp(const CustomListItemApp());
class CustomListItemApp extends StatelessWidget {
const CustomListItemApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: const CustomListItemExample(),
);
}
}
class _ArticleDescription extends StatelessWidget {
const _ArticleDescription({
required this.title,
required this.subtitle,
required this.author,
required this.publishDate,
required this.readDuration,
});
final String title;
final String subtitle;
final String author;
final String publishDate;
final String readDuration;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
const Padding(padding: EdgeInsets.only(bottom: 2.0)),
Expanded(
child: Text(
subtitle,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12.0,
color: Colors.black54,
),
),
),
Text(
author,
style: const TextStyle(
fontSize: 12.0,
color: Colors.black87,
),
),
Text(
'$publishDate - $readDuration',
style: const TextStyle(
fontSize: 12.0,
color: Colors.black54,
),
),
],
);
}
}
class CustomListItemTwo extends StatelessWidget {
const CustomListItemTwo({
super.key,
required this.thumbnail,
required this.title,
required this.subtitle,
required this.author,
required this.publishDate,
required this.readDuration,
});
final Widget thumbnail;
final String title;
final String subtitle;
final String author;
final String publishDate;
final String readDuration;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 10.0),
child: SizedBox(
height: 100,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
AspectRatio(
aspectRatio: 1.0,
child: thumbnail,
),
Expanded(
child: Padding(
padding: const EdgeInsets.fromLTRB(20.0, 0.0, 2.0, 0.0),
child: _ArticleDescription(
title: title,
subtitle: subtitle,
author: author,
publishDate: publishDate,
readDuration: readDuration,
),
),
),
],
),
),
);
}
}
class CustomListItemExample extends StatelessWidget {
const CustomListItemExample({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Custom List Item Sample')),
body: ListView(
padding: const EdgeInsets.all(10.0),
children: <Widget>[
CustomListItemTwo(
thumbnail: Container(
decoration: const BoxDecoration(color: Colors.pink),
),
title: 'Flutter 1.0 Launch',
subtitle: 'Flutter continues to improve and expand its horizons. '
'This text should max out at two lines and clip',
author: 'Dash',
publishDate: 'Dec 28',
readDuration: '5 mins',
),
CustomListItemTwo(
thumbnail: Container(
decoration: const BoxDecoration(color: Colors.blue),
),
title: 'Flutter 1.2 Release - Continual updates to the framework',
subtitle: 'Flutter once again improves and makes updates.',
author: 'Flutter',
publishDate: 'Feb 26',
readDuration: '12 mins',
),
],
),
);
}
}
| flutter/examples/api/lib/material/list_tile/custom_list_item.1.dart/0 | {
"file_path": "flutter/examples/api/lib/material/list_tile/custom_list_item.1.dart",
"repo_id": "flutter",
"token_count": 2024
} | 563 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Flutter code sample for [MenuBar].
void main() => runApp(const MenuBarApp());
/// A class for consolidating the definition of menu entries.
///
/// This sort of class is not required, but illustrates one way that defining
/// menus could be done.
class MenuEntry {
const MenuEntry({required this.label, this.shortcut, this.onPressed, this.menuChildren})
: assert(menuChildren == null || onPressed == null, 'onPressed is ignored if menuChildren are provided');
final String label;
final MenuSerializableShortcut? shortcut;
final VoidCallback? onPressed;
final List<MenuEntry>? menuChildren;
static List<Widget> build(List<MenuEntry> selections) {
Widget buildSelection(MenuEntry selection) {
if (selection.menuChildren != null) {
return SubmenuButton(
menuChildren: MenuEntry.build(selection.menuChildren!),
child: Text(selection.label),
);
}
return MenuItemButton(
shortcut: selection.shortcut,
onPressed: selection.onPressed,
child: Text(selection.label),
);
}
return selections.map<Widget>(buildSelection).toList();
}
static Map<MenuSerializableShortcut, Intent> shortcuts(List<MenuEntry> selections) {
final Map<MenuSerializableShortcut, Intent> result = <MenuSerializableShortcut, Intent>{};
for (final MenuEntry selection in selections) {
if (selection.menuChildren != null) {
result.addAll(MenuEntry.shortcuts(selection.menuChildren!));
} else {
if (selection.shortcut != null && selection.onPressed != null) {
result[selection.shortcut!] = VoidCallbackIntent(selection.onPressed!);
}
}
}
return result;
}
}
class MyMenuBar extends StatefulWidget {
const MyMenuBar({
super.key,
required this.message,
});
final String message;
@override
State<MyMenuBar> createState() => _MyMenuBarState();
}
class _MyMenuBarState extends State<MyMenuBar> {
ShortcutRegistryEntry? _shortcutsEntry;
String? _lastSelection;
Color get backgroundColor => _backgroundColor;
Color _backgroundColor = Colors.red;
set backgroundColor(Color value) {
if (_backgroundColor != value) {
setState(() {
_backgroundColor = value;
});
}
}
bool get showingMessage => _showMessage;
bool _showMessage = false;
set showingMessage(bool value) {
if (_showMessage != value) {
setState(() {
_showMessage = value;
});
}
}
@override
void dispose() {
_shortcutsEntry?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Expanded(
child: MenuBar(
children: MenuEntry.build(_getMenus()),
),
),
],
),
Expanded(
child: Container(
alignment: Alignment.center,
color: backgroundColor,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(12.0),
child: Text(
showingMessage ? widget.message : '',
style: Theme.of(context).textTheme.headlineSmall,
),
),
Text(_lastSelection != null ? 'Last Selected: $_lastSelection' : ''),
],
),
),
),
],
);
}
List<MenuEntry> _getMenus() {
final List<MenuEntry> result = <MenuEntry>[
MenuEntry(
label: 'Menu Demo',
menuChildren: <MenuEntry>[
MenuEntry(
label: 'About',
onPressed: () {
showAboutDialog(
context: context,
applicationName: 'MenuBar Sample',
applicationVersion: '1.0.0',
);
setState(() {
_lastSelection = 'About';
});
},
),
MenuEntry(
label: showingMessage ? 'Hide Message' : 'Show Message',
onPressed: () {
setState(() {
_lastSelection = showingMessage ? 'Hide Message' : 'Show Message';
showingMessage = !showingMessage;
});
},
shortcut: const SingleActivator(LogicalKeyboardKey.keyS, control: true),
),
// Hides the message, but is only enabled if the message isn't
// already hidden.
MenuEntry(
label: 'Reset Message',
onPressed: showingMessage
? () {
setState(() {
_lastSelection = 'Reset Message';
showingMessage = false;
});
}
: null,
shortcut: const SingleActivator(LogicalKeyboardKey.escape),
),
MenuEntry(
label: 'Background Color',
menuChildren: <MenuEntry>[
MenuEntry(
label: 'Red Background',
onPressed: () {
setState(() {
_lastSelection = 'Red Background';
backgroundColor = Colors.red;
});
},
shortcut: const SingleActivator(LogicalKeyboardKey.keyR, control: true),
),
MenuEntry(
label: 'Green Background',
onPressed: () {
setState(() {
_lastSelection = 'Green Background';
backgroundColor = Colors.green;
});
},
shortcut: const SingleActivator(LogicalKeyboardKey.keyG, control: true),
),
MenuEntry(
label: 'Blue Background',
onPressed: () {
setState(() {
_lastSelection = 'Blue Background';
backgroundColor = Colors.blue;
});
},
shortcut: const SingleActivator(LogicalKeyboardKey.keyB, control: true),
),
],
),
],
),
];
// (Re-)register the shortcuts with the ShortcutRegistry so that they are
// available to the entire application, and update them if they've changed.
_shortcutsEntry?.dispose();
_shortcutsEntry = ShortcutRegistry.of(context).addAll(MenuEntry.shortcuts(result));
return result;
}
}
class MenuBarApp extends StatelessWidget {
const MenuBarApp({super.key});
static const String kMessage = '"Talk less. Smile more." - A. Burr';
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(body: SafeArea(child: MyMenuBar(message: kMessage))),
);
}
}
| flutter/examples/api/lib/material/menu_anchor/menu_bar.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/menu_anchor/menu_bar.0.dart",
"repo_id": "flutter",
"token_count": 3316
} | 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 'package:flutter/material.dart';
/// Flutter code sample for [ReorderableListView].
void main() => runApp(const ReorderableApp());
class ReorderableApp extends StatelessWidget {
const ReorderableApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('ReorderableListView Sample')),
body: const ReorderableExample(),
),
);
}
}
class ReorderableExample extends StatefulWidget {
const ReorderableExample({super.key});
@override
State<ReorderableExample> createState() => _ReorderableListViewExampleState();
}
class _ReorderableListViewExampleState extends State<ReorderableExample> {
final List<int> _items = List<int>.generate(50, (int index) => index);
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
final Color oddItemColor = colorScheme.primary.withOpacity(0.05);
final Color evenItemColor = colorScheme.primary.withOpacity(0.15);
return ReorderableListView(
padding: const EdgeInsets.symmetric(horizontal: 40),
children: <Widget>[
for (int index = 0; index < _items.length; index += 1)
ListTile(
key: Key('$index'),
tileColor: _items[index].isOdd ? oddItemColor : evenItemColor,
title: Text('Item ${_items[index]}'),
),
],
onReorder: (int oldIndex, int newIndex) {
setState(() {
if (oldIndex < newIndex) {
newIndex -= 1;
}
final int item = _items.removeAt(oldIndex);
_items.insert(newIndex, item);
});
},
);
}
}
| flutter/examples/api/lib/material/reorderable_list/reorderable_list_view.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/reorderable_list/reorderable_list_view.0.dart",
"repo_id": "flutter",
"token_count": 715
} | 565 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [ScaffoldMessengerState.showSnackBar].
void main() => runApp(const ShowSnackBarExampleApp());
class ShowSnackBarExampleApp extends StatelessWidget {
const ShowSnackBarExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('ScaffoldMessengerState Sample')),
body: const Center(
child: ShowSnackBarExample(),
),
),
);
}
}
class ShowSnackBarExample extends StatelessWidget {
const ShowSnackBarExample({super.key});
@override
Widget build(BuildContext context) {
return OutlinedButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('A SnackBar has been shown.'),
),
);
},
child: const Text('Show SnackBar'),
);
}
}
| flutter/examples/api/lib/material/scaffold/scaffold_messenger_state.show_snack_bar.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/scaffold/scaffold_messenger_state.show_snack_bar.0.dart",
"repo_id": "flutter",
"token_count": 421
} | 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/material.dart';
import 'package:flutter/rendering.dart';
/// Flutter code sample for [SelectionContainer].
void main() => runApp(const SelectionContainerExampleApp());
class SelectionContainerExampleApp extends StatelessWidget {
const SelectionContainerExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SelectionArea(
child: Scaffold(
appBar: AppBar(title: const Text('SelectionContainer Sample')),
body: const Center(
child: SelectionAllOrNoneContainer(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Row 1'),
Text('Row 2'),
Text('Row 3'),
],
),
),
),
),
),
);
}
}
class SelectionAllOrNoneContainer extends StatefulWidget {
const SelectionAllOrNoneContainer({super.key, required this.child});
final Widget child;
@override
State<StatefulWidget> createState() => _SelectionAllOrNoneContainerState();
}
class _SelectionAllOrNoneContainerState extends State<SelectionAllOrNoneContainer> {
final SelectAllOrNoneContainerDelegate delegate = SelectAllOrNoneContainerDelegate();
@override
void dispose() {
delegate.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SelectionContainer(
delegate: delegate,
child: widget.child,
);
}
}
class SelectAllOrNoneContainerDelegate extends MultiSelectableSelectionContainerDelegate {
Offset? _adjustedStartEdge;
Offset? _adjustedEndEdge;
bool _isSelected = false;
// This method is called when newly added selectable is in the current
// selected range.
@override
void ensureChildUpdated(Selectable selectable) {
if (_isSelected) {
dispatchSelectionEventToChild(selectable, const SelectAllSelectionEvent());
}
}
@override
SelectionResult handleSelectWord(SelectWordSelectionEvent event) {
// Treat select word as select all.
return handleSelectAll(const SelectAllSelectionEvent());
}
@override
SelectionResult handleSelectionEdgeUpdate(SelectionEdgeUpdateEvent event) {
final Rect containerRect = Rect.fromLTWH(0, 0, containerSize.width, containerSize.height);
final Matrix4 globalToLocal = getTransformTo(null)..invert();
final Offset localOffset = MatrixUtils.transformPoint(globalToLocal, event.globalPosition);
final Offset adjustOffset = SelectionUtils.adjustDragOffset(containerRect, localOffset);
if (event.type == SelectionEventType.startEdgeUpdate) {
_adjustedStartEdge = adjustOffset;
} else {
_adjustedEndEdge = adjustOffset;
}
// Select all content if the selection rect intercepts with the rect.
if (_adjustedStartEdge != null && _adjustedEndEdge != null) {
final Rect selectionRect = Rect.fromPoints(_adjustedStartEdge!, _adjustedEndEdge!);
if (!selectionRect.intersect(containerRect).isEmpty) {
handleSelectAll(const SelectAllSelectionEvent());
} else {
super.handleClearSelection(const ClearSelectionEvent());
}
} else {
super.handleClearSelection(const ClearSelectionEvent());
}
return SelectionUtils.getResultBasedOnRect(containerRect, localOffset);
}
@override
SelectionResult handleClearSelection(ClearSelectionEvent event) {
_adjustedStartEdge = null;
_adjustedEndEdge = null;
_isSelected = false;
return super.handleClearSelection(event);
}
@override
SelectionResult handleSelectAll(SelectAllSelectionEvent event) {
_isSelected = true;
return super.handleSelectAll(event);
}
}
| flutter/examples/api/lib/material/selection_container/selection_container.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/selection_container/selection_container.0.dart",
"repo_id": "flutter",
"token_count": 1331
} | 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/gestures.dart';
import 'package:flutter/material.dart';
/// Flutter code sample for custom labeled switch.
void main() => runApp(const LabeledSwitchApp());
class LabeledSwitchApp extends StatelessWidget {
const LabeledSwitchApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
appBar: AppBar(title: const Text('Custom Labeled Switch Sample')),
body: const Center(
child: LabeledSwitchExample(),
),
),
);
}
}
class LinkedLabelSwitch extends StatelessWidget {
const LinkedLabelSwitch({
super.key,
required this.label,
required this.padding,
required this.value,
required this.onChanged,
});
final String label;
final EdgeInsets padding;
final bool value;
final ValueChanged<bool> onChanged;
@override
Widget build(BuildContext context) {
return Padding(
padding: padding,
child: Row(
children: <Widget>[
Expanded(
child: RichText(
text: TextSpan(
text: label,
style: TextStyle(
color: Theme.of(context).colorScheme.primary,
decoration: TextDecoration.underline,
),
recognizer: TapGestureRecognizer()
..onTap = () {
debugPrint('Label has been tapped.');
},
),
),
),
Switch(
value: value,
onChanged: (bool newValue) {
onChanged(newValue);
},
),
],
),
);
}
}
class LabeledSwitchExample extends StatefulWidget {
const LabeledSwitchExample({super.key});
@override
State<LabeledSwitchExample> createState() => _LabeledSwitchExampleState();
}
class _LabeledSwitchExampleState extends State<LabeledSwitchExample> {
bool _isSelected = false;
@override
Widget build(BuildContext context) {
return LinkedLabelSwitch(
label: 'Linked, tappable label text',
padding: const EdgeInsets.symmetric(horizontal: 20.0),
value: _isSelected,
onChanged: (bool newValue) {
setState(() {
_isSelected = newValue;
});
},
);
}
}
| flutter/examples/api/lib/material/switch_list_tile/custom_labeled_switch.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/switch_list_tile/custom_labeled_switch.0.dart",
"repo_id": "flutter",
"token_count": 1068
} | 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/material.dart';
/// Flutter code sample for [showTimePicker].
void main() {
runApp(const ShowTimePickerApp());
}
class ShowTimePickerApp extends StatefulWidget {
const ShowTimePickerApp({super.key});
@override
State<ShowTimePickerApp> createState() => _ShowTimePickerAppState();
}
class _ShowTimePickerAppState extends State<ShowTimePickerApp> {
ThemeMode themeMode = ThemeMode.dark;
bool useMaterial3 = true;
void setThemeMode(ThemeMode mode) {
setState(() {
themeMode = mode;
});
}
void setUseMaterial3(bool? value) {
setState(() {
useMaterial3 = value!;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light(useMaterial3: useMaterial3),
darkTheme: ThemeData.dark(useMaterial3: useMaterial3),
themeMode: themeMode,
home: TimePickerOptions(
themeMode: themeMode,
useMaterial3: useMaterial3,
setThemeMode: setThemeMode,
setUseMaterial3: setUseMaterial3,
),
);
}
}
class TimePickerOptions extends StatefulWidget {
const TimePickerOptions({
super.key,
required this.themeMode,
required this.useMaterial3,
required this.setThemeMode,
required this.setUseMaterial3,
});
final ThemeMode themeMode;
final bool useMaterial3;
final ValueChanged<ThemeMode> setThemeMode;
final ValueChanged<bool?> setUseMaterial3;
@override
State<TimePickerOptions> createState() => _TimePickerOptionsState();
}
class _TimePickerOptionsState extends State<TimePickerOptions> {
TimeOfDay? selectedTime;
TimePickerEntryMode entryMode = TimePickerEntryMode.dial;
Orientation? orientation;
TextDirection textDirection = TextDirection.ltr;
MaterialTapTargetSize tapTargetSize = MaterialTapTargetSize.padded;
bool use24HourTime = false;
void _entryModeChanged(TimePickerEntryMode? value) {
if (value != entryMode) {
setState(() {
entryMode = value!;
});
}
}
void _orientationChanged(Orientation? value) {
if (value != orientation) {
setState(() {
orientation = value;
});
}
}
void _textDirectionChanged(TextDirection? value) {
if (value != textDirection) {
setState(() {
textDirection = value!;
});
}
}
void _tapTargetSizeChanged(MaterialTapTargetSize? value) {
if (value != tapTargetSize) {
setState(() {
tapTargetSize = value!;
});
}
}
void _use24HourTimeChanged(bool? value) {
if (value != use24HourTime) {
setState(() {
use24HourTime = value!;
});
}
}
void _themeModeChanged(ThemeMode? value) {
widget.setThemeMode(value!);
}
@override
Widget build(BuildContext context) {
return Material(
child: Column(
children: <Widget>[
Expanded(
child: GridView(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 350,
mainAxisSpacing: 4,
mainAxisExtent: 200,
crossAxisSpacing: 4,
),
children: <Widget>[
EnumCard<TimePickerEntryMode>(
choices: TimePickerEntryMode.values,
value: entryMode,
onChanged: _entryModeChanged,
),
EnumCard<ThemeMode>(
choices: ThemeMode.values,
value: widget.themeMode,
onChanged: _themeModeChanged,
),
EnumCard<TextDirection>(
choices: TextDirection.values,
value: textDirection,
onChanged: _textDirectionChanged,
),
EnumCard<MaterialTapTargetSize>(
choices: MaterialTapTargetSize.values,
value: tapTargetSize,
onChanged: _tapTargetSizeChanged,
),
ChoiceCard<Orientation?>(
choices: const <Orientation?>[...Orientation.values, null],
value: orientation,
title: '$Orientation',
choiceLabels: <Orientation?, String>{
for (final Orientation choice in Orientation.values) choice: choice.name,
null: 'from MediaQuery',
},
onChanged: _orientationChanged,
),
ChoiceCard<bool>(
choices: const <bool>[false, true],
value: use24HourTime,
onChanged: _use24HourTimeChanged,
title: 'Time Mode',
choiceLabels: const <bool, String>{
false: '12-hour am/pm time',
true: '24-hour time',
},
),
ChoiceCard<bool>(
choices: const <bool>[false, true],
value: widget.useMaterial3,
onChanged: widget.setUseMaterial3,
title: 'Material Version',
choiceLabels: const <bool, String>{
false: 'Material 2',
true: 'Material 3',
},
),
],
),
),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(12.0),
child: ElevatedButton(
child: const Text('Open time picker'),
onPressed: () async {
final TimeOfDay? time = await showTimePicker(
context: context,
initialTime: selectedTime ?? TimeOfDay.now(),
initialEntryMode: entryMode,
orientation: orientation,
builder: (BuildContext context, Widget? child) {
// We just wrap these environmental changes around the
// child in this builder so that we can apply the
// options selected above. In regular usage, this is
// rarely necessary, because the default values are
// usually used as-is.
return Theme(
data: Theme.of(context).copyWith(
materialTapTargetSize: tapTargetSize,
),
child: Directionality(
textDirection: textDirection,
child: MediaQuery(
data: MediaQuery.of(context).copyWith(
alwaysUse24HourFormat: use24HourTime,
),
child: child!,
),
),
);
},
);
setState(() {
selectedTime = time;
});
},
),
),
if (selectedTime != null) Text('Selected time: ${selectedTime!.format(context)}'),
],
),
),
],
),
);
}
}
// This is a simple card that presents a set of radio buttons (inside of a
// RadioSelection, defined below) for the user to select from.
class ChoiceCard<T extends Object?> extends StatelessWidget {
const ChoiceCard({
super.key,
required this.value,
required this.choices,
required this.onChanged,
required this.choiceLabels,
required this.title,
});
final T value;
final Iterable<T> choices;
final Map<T, String> choiceLabels;
final String title;
final ValueChanged<T?> onChanged;
@override
Widget build(BuildContext context) {
return Card(
// If the card gets too small, let it scroll both directions.
child: SingleChildScrollView(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(title),
),
for (final T choice in choices)
RadioSelection<T>(
value: choice,
groupValue: value,
onChanged: onChanged,
child: Text(choiceLabels[choice]!),
),
],
),
),
),
),
);
}
}
// This aggregates a ChoiceCard so that it presents a set of radio buttons for
// the allowed enum values for the user to select from.
class EnumCard<T extends Enum> extends StatelessWidget {
const EnumCard({
super.key,
required this.value,
required this.choices,
required this.onChanged,
});
final T value;
final Iterable<T> choices;
final ValueChanged<T?> onChanged;
@override
Widget build(BuildContext context) {
return ChoiceCard<T>(
value: value,
choices: choices,
onChanged: onChanged,
choiceLabels: <T, String>{
for (final T choice in choices) choice: choice.name,
},
title: value.runtimeType.toString());
}
}
// A button that has a radio button on one side and a label child. Tapping on
// the label or the radio button selects the item.
class RadioSelection<T extends Object?> extends StatefulWidget {
const RadioSelection({
super.key,
required this.value,
required this.groupValue,
required this.onChanged,
required this.child,
});
final T value;
final T? groupValue;
final ValueChanged<T?> onChanged;
final Widget child;
@override
State<RadioSelection<T>> createState() => _RadioSelectionState<T>();
}
class _RadioSelectionState<T extends Object?> extends State<RadioSelection<T>> {
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Padding(
padding: const EdgeInsetsDirectional.only(end: 8),
child: Radio<T>(
groupValue: widget.groupValue,
value: widget.value,
onChanged: widget.onChanged,
),
),
GestureDetector(onTap: () => widget.onChanged(widget.value), child: widget.child),
],
);
}
}
| flutter/examples/api/lib/material/time_picker/show_time_picker.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/time_picker/show_time_picker.0.dart",
"repo_id": "flutter",
"token_count": 5315
} | 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 [SliverGridDelegateWithFixedCrossAxisCount].
void main() => runApp(const SliverGridDelegateWithFixedCrossAxisCountExampleApp());
class SliverGridDelegateWithFixedCrossAxisCountExampleApp extends StatelessWidget {
const SliverGridDelegateWithFixedCrossAxisCountExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('SliverGridDelegateWithFixedCrossAxisCount Sample')),
body: const SliverGridDelegateWithFixedCrossAxisCountExample(),
),
);
}
}
class SliverGridDelegateWithFixedCrossAxisCountExample extends StatelessWidget {
const SliverGridDelegateWithFixedCrossAxisCountExample({super.key});
@override
Widget build(BuildContext context) {
return GridView(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 4,
childAspectRatio: 0.5,
),
children: List<Widget>.generate(20, (int i) {
return Builder(builder: (BuildContext context) {
return Text('$i');
});
}),
);
}
}
| flutter/examples/api/lib/rendering/sliver_grid/sliver_grid_delegate_with_fixed_cross_axis_count.0.dart/0 | {
"file_path": "flutter/examples/api/lib/rendering/sliver_grid/sliver_grid_delegate_with_fixed_cross_axis_count.0.dart",
"repo_id": "flutter",
"token_count": 463
} | 570 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.