text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
/*
* Copyright 2016 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.sdk;
import com.intellij.execution.ExecutionException;
import com.jetbrains.lang.dart.sdk.DartSdk;
import io.flutter.dart.DartPlugin;
import io.flutter.testing.FlutterModuleFixture;
import io.flutter.testing.ProjectFixture;
import io.flutter.testing.Testing;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.*;
public class FlutterSdkUtilTest {
@Rule
public ProjectFixture projectFixture = Testing.makeCodeInsightModule();
@Rule
public FlutterModuleFixture flutterFixture = new FlutterModuleFixture(projectFixture);
@Test
public void shouldInstallFlutterSDK() throws ExecutionException {
// All of FlutterTestUtils is exercised before getting here.
assertTrue("Test jig setup failed", true);
// Verify Flutter SDK is installed correctly.
final FlutterSdk flutterSdk = FlutterSdk.getFlutterSdk(projectFixture.getProject());
assertNotNull(flutterSdk);
final String path = System.getProperty("flutter.sdk");
assertEquals("Incorrect Flutter SDK path", flutterSdk.getHomePath(), path);
// Verify Dart SDK is the one distributed with Flutter.
final DartSdk dartSdk = DartPlugin.getDartSdk(projectFixture.getProject());
assertNotNull(dartSdk);
assertTrue("Dart SDK not found in Flutter SDK installation", dartSdk.getHomePath().startsWith(flutterSdk.getHomePath()));
// Check SDK utilities.
final String toolPath = FlutterSdkUtil.pathToFlutterTool(flutterSdk.getHomePath());
assertEquals("Incorrect path to flutter command", toolPath, path + "/bin/flutter");
assertTrue(FlutterSdkUtil.isFlutterSdkHome(path));
}
}
| flutter-intellij/flutter-idea/testSrc/integration/io/flutter/sdk/FlutterSdkUtilTest.java/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/integration/io/flutter/sdk/FlutterSdkUtilTest.java",
"repo_id": "flutter-intellij",
"token_count": 585
} | 512 |
/*
* Copyright 2021 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.coverage;
import com.intellij.rt.coverage.data.ProjectData;
import io.flutter.run.coverage.LcovInfo;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class LcovInfoTest {
@Test
public void testReadData() throws IOException {
final File sessionDataFile = new File("testData/coverage", "lcov.info");
final ProjectData projectData = new ProjectData();
LcovInfo.readInto(projectData, sessionDataFile);
// The file contains data for one class, with 110 lines, but we don't know the class name.
projectData.getClasses().entrySet().iterator().forEachRemaining(entry -> {
assertEquals(110, entry.getValue().getLines().length);
});
}
}
| flutter-intellij/flutter-idea/testSrc/unit/io/flutter/coverage/LcovInfoTest.java/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/coverage/LcovInfoTest.java",
"repo_id": "flutter-intellij",
"token_count": 302
} | 513 |
{
"type": "Event",
"kind": "Logging",
"isolate": {
"type": "@Isolate",
"id": "isolates/170696135467167",
"name": "main",
"number": "170696135467167"
},
"timestamp": 1562619110758,
"logRecord": {
"type": "LogRecord",
"sequenceNumber": 5,
"time": 1562619110758,
"level": 0,
"loggerName": {
"type": "@Instance",
"_vmType": "String",
"class": {
"type": "@Class",
"fixedId": true,
"id": "classes/76",
"name": "_OneByteString",
"_vmName": "_OneByteString@0150898"
},
"kind": "String",
"id": "objects/20",
"length": 0,
"valueAsString": ""
},
"message": {
"type": "@Instance",
"_vmType": "String",
"class": {
"type": "@Class",
"fixedId": true,
"id": "classes/76",
"name": "_OneByteString",
"_vmName": "_OneByteString@0150898"
},
"kind": "String",
"id": "objects/21",
"length": 11,
"valueAsString": "hello world"
},
"zone": {
"type": "@Instance",
"class": {
"type": "@Class",
"fixedId": true,
"id": "classes/141",
"name": "Null"
},
"kind": "Null",
"fixedId": true,
"id": "objects/null",
"valueAsString": "null"
},
"error": {
"type": "@Instance",
"_vmType": "String",
"class": {
"type": "@Class",
"fixedId": true,
"id": "classes/76",
"name": "_OneByteString",
"_vmName": "_OneByteString@0150898"
},
"kind": "String",
"id": "objects/22",
"length": 15,
"valueAsString": "my sample error"
},
"stackTrace": {
"type": "@Instance",
"class": {
"type": "@Class",
"fixedId": true,
"id": "classes/141",
"name": "Null"
},
"kind": "Null",
"fixedId": true,
"id": "objects/null",
"valueAsString": "null"
}
}
}
| flutter-intellij/flutter-idea/testSrc/unit/io/flutter/logging/console_log_3.json/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/logging/console_log_3.json",
"repo_id": "flutter-intellij",
"token_count": 1022
} | 514 |
/*
* Copyright 2019 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.run.common;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.impl.source.tree.LeafPsiElement;
import com.jetbrains.lang.dart.psi.DartCallExpression;
import io.flutter.AbstractDartElementTest;
import io.flutter.dart.DartSyntax;
import io.flutter.editor.ActiveEditorsOutlineService;
import io.flutter.testing.FakeActiveEditorsOutlineService;
import org.jetbrains.annotations.NotNull;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Verifies that named test targets can be identified correctly as part of a group or as an individual test target.
*/
public class CommonTestConfigUtilsTest extends AbstractDartElementTest {
/**
* The contents of data/test_file.dart.
*/
private Map<String, String> fileContents = new HashMap<>();
CommonTestConfigUtils utils;
FakeActiveEditorsOutlineService service;
static final String CUSTOM_TEST_LOCAL_PATH = "test/custom_test.dart";
static final String SIMPLE_TEST_LOCAL_PATH = "test/simple_test.dart";
@Before
public void setUp() throws Exception {
fileContents.put(
CUSTOM_TEST_LOCAL_PATH,
new String(Files.readAllBytes(Paths.get(FakeActiveEditorsOutlineService.CUSTOM_TEST_PATH)))
);
service = new FakeActiveEditorsOutlineService(fixture.getProject(), "/" + CUSTOM_TEST_LOCAL_PATH, FakeActiveEditorsOutlineService.CUSTOM_OUTLINE_PATH);
utils = new CommonTestConfigUtils() {
@Override
protected ActiveEditorsOutlineService getActiveEditorsOutlineService(@NotNull Project project) {
return service;
}
};
}
@Test @Ignore
public void shouldMatchGroup() throws Exception {
run(() -> {
final PsiElement group0 = getTestCallWithName("group", "group 0");
assertThat(utils.asTestCall(group0), equalTo(TestType.GROUP));
assertThat(utils.findTestName(group0), equalTo("group 0"));
});
}
@Test @Ignore
public void shouldMatchTest0() throws Exception {
run(() -> {
final PsiElement test0 = getTestCallWithName("test", "test 0");
assertThat(utils.asTestCall(test0), equalTo(TestType.SINGLE));
assertThat(utils.findTestName(test0), equalTo("test 0"));
});
}
@Test @Ignore
public void shouldMatchTestWidgets0() throws Exception {
run(() -> {
final PsiElement testWidgets0 = getTestCallWithName("testWidgets", "test widgets 0");
assertThat(utils.asTestCall(testWidgets0), equalTo(TestType.SINGLE));
assertThat(utils.findTestName(testWidgets0), equalTo("test widgets 0"));
});
}
@Test @Ignore
public void shouldMatchTest1() throws Exception {
run(() -> {
final PsiElement test1 = getTestCallWithName("test", "test 1");
assertThat(utils.asTestCall(test1), equalTo(TestType.SINGLE));
assertThat(utils.findTestName(test1), equalTo("test 1"));
});
}
@Test @Ignore
public void shouldNotMatchNonTest() throws Exception {
run(() -> {
final PsiElement nonTest = getTestCallWithName("nonTest", "not a test");
// The test call site of nonTest is not a runnable test, so asTestCall should return null.
assertThat(utils.asTestCall(nonTest), equalTo(null));
// Looking for the test that contains nonTest will find the test name of the enclosing group.
// findTestName is supposed to get the name of the enclosing runnable test, so we allow it to look farther up the tree to find
// the runnable test group.
assertThat(utils.findTestName(nonTest), equalTo("group 0"));
});
}
@Test @Ignore
public void shouldNotMatchNonGroup() throws Exception {
run(() -> {
final PsiElement nonGroup = getTestCallWithName("nonGroup", "not a group");
assertThat(utils.asTestCall(nonGroup), equalTo(null));
assertThat(utils.findTestName(nonGroup), equalTo(null));
});
}
@Test @Ignore
public void shouldMatchCustomGroup() throws Exception {
run(() -> {
final PsiElement customGroup = getTestCallWithName("g", "custom group");
assertThat(utils.asTestCall(customGroup), equalTo(TestType.GROUP));
assertThat(utils.findTestName(customGroup), equalTo("custom group"));
});
}
@Test @Ignore
public void shouldMatchCustomTest() throws Exception {
run(() -> {
final PsiElement customTest = getTestCallWithName("t", "custom test");
assertThat(utils.asTestCall(customTest), equalTo(TestType.SINGLE));
assertThat(utils.findTestName(customTest), equalTo("custom test"));
});
}
@Test @Ignore
public void shouldMatchWhenMultipleFilesLoad() throws Exception {
run(() -> {
fileContents.put(
SIMPLE_TEST_LOCAL_PATH,
new String(Files.readAllBytes(Paths.get(FakeActiveEditorsOutlineService.SIMPLE_TEST_PATH)))
);
service.loadOutline("/" + SIMPLE_TEST_LOCAL_PATH, FakeActiveEditorsOutlineService.SIMPLE_OUTLINE_PATH);
final PsiElement singleTest = getTestCallWithName("test", "test 1", SIMPLE_TEST_LOCAL_PATH);
assertThat(utils.asTestCall(singleTest), equalTo(TestType.SINGLE));
assertThat(utils.findTestName(singleTest), equalTo("test 1"));
final PsiElement customTest = getTestCallWithName("t", "custom test", CUSTOM_TEST_LOCAL_PATH);
assertThat(utils.asTestCall(customTest), equalTo(TestType.SINGLE));
assertThat(utils.findTestName(customTest), equalTo("custom test"));
});
}
@Test @Ignore
public void shouldNotMatchWhenAOutlineIsOutOfDate() throws Exception {
run(() -> {
// We'll replace the correct outline with an incorrect outline, which will flag the outline as invalid.
// Results should be null.
service.loadOutline("/" + CUSTOM_TEST_LOCAL_PATH, FakeActiveEditorsOutlineService.SIMPLE_OUTLINE_PATH);
final PsiElement customTest = getTestCallWithName("t", "custom test", CUSTOM_TEST_LOCAL_PATH);
assertThat(utils.asTestCall(customTest), equalTo(null));
assertThat(utils.findTestName(customTest), equalTo(null));
});
}
/**
* Gets a specific test or test group call.
*
* @param functionName The name of the function being called, eg test() or testWidgets()
* @param testName The name of the test desired, such as 'test 0' or 'test widgets 0'
* @param filePath The file containing the desired test.
*/
@NotNull
private DartCallExpression getTestCallWithName(String functionName, String testName, String filePath) {
final PsiElement testIdentifier = setUpDartElement(filePath,
fileContents.get(filePath), testName, LeafPsiElement.class);
assertThat(testIdentifier, not(equalTo(null)));
final DartCallExpression result = DartSyntax.findClosestEnclosingFunctionCall(testIdentifier);
assertThat(result, not(equalTo(null)));
return result;
}
/**
* Gets a specific test or test group call from {@code CUSTOM_TEST_LOCAL_PATH}.
*
* @param functionName The name of the function being called, eg test() or testWidgets()
* @param testName The name of the test desired, such as 'test 0' or 'test widgets 0'
*/
@NotNull
private DartCallExpression getTestCallWithName(String functionName, String testName) {
return getTestCallWithName(functionName, testName, CUSTOM_TEST_LOCAL_PATH);
}
}
| flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/common/CommonTestConfigUtilsTest.java/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/common/CommonTestConfigUtilsTest.java",
"repo_id": "flutter-intellij",
"token_count": 2719
} | 515 |
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.utils;
import com.google.common.collect.ImmutableList;
import com.intellij.openapi.CompositeDisposable;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import javax.swing.*;
import java.time.Clock;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import static java.util.concurrent.CompletableFuture.supplyAsync;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.*;
public class AsyncRateLimiterTest {
private static final double TEST_FRAMES_PER_SECOND = 10.0;
private static final long MS_PER_EVENT = (long)(1000.0 / TEST_FRAMES_PER_SECOND);
final Clock clock = Clock.systemUTC();
private final List<String> logEntries = new ArrayList<>();
private AsyncRateLimiter rateLimiter;
private Computable<CompletableFuture<?>> callback;
private CompletableFuture<Void> callbacksDone;
private CompositeDisposable disposable;
private int expectedEvents;
private volatile int numEvents;
@Before
public void setUp() {
callback = null;
numEvents = 0;
callbacksDone = new CompletableFuture<>();
disposable = new CompositeDisposable();
rateLimiter = new AsyncRateLimiter(TEST_FRAMES_PER_SECOND, () -> {
if (!SwingUtilities.isEventDispatchThread()) {
log("subscriber should be called on Swing thread");
callbacksDone.complete(null);
return null;
}
log("EVENT");
CompletableFuture<?> ret = null;
if (callback != null) {
ret = callback.compute();
}
if (ret == null) {
ret = new CompletableFuture<>();
ret.complete(null);
}
numEvents++;
if (numEvents == expectedEvents) {
log("DONE");
callbacksDone.complete(null);
}
else if (numEvents > expectedEvents) {
log("unexpected number of events fired");
}
return ret;
}, disposable);
}
@After
public void tearDown() {
Disposer.dispose(disposable);
}
void scheduleRequest() {
rateLimiter.scheduleRequest();
}
@Test
@Ignore("generally flaky")
public void rateLimited() {
final long start = clock.millis();
expectedEvents = 4;
callback = null;
while (!callbacksDone.isDone()) {
// Schedule requests at many times the rate limit.
SwingUtilities.invokeLater(() -> {
if (!callbacksDone.isDone()) {
rateLimiter.scheduleRequest();
}
});
try {
Thread.sleep(1);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
final long current = clock.millis();
final long delta = current - start;
checkLog("EVENT", "EVENT", "EVENT", "EVENT", "DONE");
// First event should occur immediately so don't count it.
// The last event just fired so add in MS_PER_EVENT to factor in that it
// will be that long before the next event fires.
final double requestsPerSecond = (numEvents - 1) / ((delta + MS_PER_EVENT) * 0.001);
assertTrue("Requests per second does not exceed limit. Actual: " + requestsPerSecond,
requestsPerSecond <= TEST_FRAMES_PER_SECOND);
// We use a large delta so that tests run under load do not result in flakes.
assertTrue("Requests per second within 3 fps of rate limit:", requestsPerSecond + 3.0 > TEST_FRAMES_PER_SECOND);
}
@Test
public void rateLimitedSlowNetwork() {
// In this test we simulate the network requests triggered for each
// request being slow resulting in a lower frame rate as the network
// now becomes the limiting factor instead of the rate limiter
// as the rate limiter should never issue a request before the
// previous request completed.
final long start = clock.millis();
expectedEvents = 3;
callback = () -> {
// Delay 10 times the typical time between events before returning.
return supplyAsync(() -> {
try {
Thread.sleep(MS_PER_EVENT * 10);
}
catch (InterruptedException e) {
reportFailure(e);
}
return null;
});
};
while (!callbacksDone.isDone()) {
// Schedule requests at many times the rate limit.
scheduleRequest();
try {
Thread.sleep(1);
}
catch (InterruptedException e) {
reportFailure(e);
}
}
final long current = clock.millis();
final long delta = current - start;
checkLog("EVENT", "EVENT", "EVENT", "DONE");
// First event should occur immediately so don't count it.
// The last event just fired so add in MS_PER_EVENT to factor in that it
// will be that long before the next event fires.
final double requestsPerSecond = (expectedEvents - 1) / ((delta + MS_PER_EVENT) * 0.001);
assertTrue("Requests per second less than 10 times limit. Actual: " + requestsPerSecond,
requestsPerSecond * 10 < TEST_FRAMES_PER_SECOND);
// We use a large delta so that tests run under load do not result in flakes.
assertTrue("Requests per second within 5 fps of rate limit. ACTUAL: " + requestsPerSecond,
requestsPerSecond * 10 + 5.0 > TEST_FRAMES_PER_SECOND);
}
@Test @Ignore("flakey")
public void avoidUnneededRequests() {
// In this test we verify that we don't accidentally schedule unneeded
final long start = clock.millis();
expectedEvents = 1;
callback = () -> {
// Make the first event slow but other events instant.
// This will make it easier to catch if we accidentally schedule a second
// request when we shouldn't.
if (numEvents == 0) {
try {
Thread.sleep(MS_PER_EVENT);
}
catch (InterruptedException e) {
reportFailure(e);
}
}
return null;
};
// Schedule 4 requests immediatelly one after each other and verify that
// only one is actually triggered.
scheduleRequest();
scheduleRequest();
scheduleRequest();
scheduleRequest();
// Extra sleep to ensure no unexpected events fire.
try {
Thread.sleep(MS_PER_EVENT * 10);
}
catch (InterruptedException e) {
reportFailure(e);
}
assertEquals(numEvents, expectedEvents);
}
private synchronized void log(String message) {
logEntries.add(message);
}
private synchronized List<String> getLogEntries() {
return ImmutableList.copyOf(logEntries);
}
private void reportFailure(Exception e) {
fail("Exception: " + e + "\nLog: " + getLogEntries());
}
private void checkLog(String... expectedEntries) {
assertThat("logEntries entries are different", getLogEntries(), is(ImmutableList.copyOf(expectedEntries)));
logEntries.clear();
}
}
| flutter-intellij/flutter-idea/testSrc/unit/io/flutter/utils/AsyncRateLimiterTest.java/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/utils/AsyncRateLimiterTest.java",
"repo_id": "flutter-intellij",
"token_count": 2524
} | 516 |
/*
* Copyright (c) 2015, the Dart project authors.
*
* Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.dartlang.vm.service;
// This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk.
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import java.util.List;
import java.util.Map;
import org.dartlang.vm.service.consumer.*;
import org.dartlang.vm.service.element.*;
/**
* {@link VmService} allows control of and access to information in a running
* Dart VM instance.
* <br/>
* Launch the Dart VM with the arguments:
* <pre>
* --pause_isolates_on_start
* --observe
* --enable-vm-service=some-port
* </pre>
* where <strong>some-port</strong> is a port number of your choice
* which this client will use to communicate with the Dart VM.
* See https://dart.dev/tools/dart-vm for more details.
* Once the VM is running, instantiate a new {@link VmService}
* to connect to that VM via {@link VmService#connect(String)}
* or {@link VmService#localConnect(int)}.
* <br/>
* {@link VmService} is not thread safe and should only be accessed from
* a single thread. In addition, a given VM should only be accessed from
* a single instance of {@link VmService}.
* <br/>
* Calls to {@link VmService} should not be nested.
* More specifically, you should not make any calls to {@link VmService}
* from within any {@link Consumer} method.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class VmService extends VmServiceBase {
public static final String DEBUG_STREAM_ID = "Debug";
public static final String EXTENSION_STREAM_ID = "Extension";
public static final String GC_STREAM_ID = "GC";
public static final String HEAPSNAPSHOT_STREAM_ID = "HeapSnapshot";
public static final String ISOLATE_STREAM_ID = "Isolate";
public static final String LOGGING_STREAM_ID = "Logging";
public static final String PROFILER_STREAM_ID = "Profiler";
public static final String SERVICE_STREAM_ID = "Service";
public static final String STDERR_STREAM_ID = "Stderr";
public static final String STDOUT_STREAM_ID = "Stdout";
public static final String TIMELINE_STREAM_ID = "Timeline";
public static final String VM_STREAM_ID = "VM";
/**
* The major version number of the protocol supported by this client.
*/
public static final int versionMajor = 4;
/**
* The minor version number of the protocol supported by this client.
*/
public static final int versionMinor = 3;
/**
* The [addBreakpoint] RPC is used to add a breakpoint at a specific line of some script.
*/
public void addBreakpoint(String isolateId, String scriptId, int line, AddBreakpointConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("scriptId", scriptId);
params.addProperty("line", line);
request("addBreakpoint", params, consumer);
}
/**
* The [addBreakpoint] RPC is used to add a breakpoint at a specific line of some script.
* @param column This parameter is optional and may be null.
*/
public void addBreakpoint(String isolateId, String scriptId, int line, Integer column, AddBreakpointConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("scriptId", scriptId);
params.addProperty("line", line);
if (column != null) params.addProperty("column", column);
request("addBreakpoint", params, consumer);
}
/**
* The [addBreakpointAtEntry] RPC is used to add a breakpoint at the entrypoint of some function.
*/
public void addBreakpointAtEntry(String isolateId, String functionId, AddBreakpointAtEntryConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("functionId", functionId);
request("addBreakpointAtEntry", params, consumer);
}
/**
* The [addBreakpoint] RPC is used to add a breakpoint at a specific line of some script. This
* RPC is useful when a script has not yet been assigned an id, for example, if a script is in a
* deferred library which has not yet been loaded.
*/
public void addBreakpointWithScriptUri(String isolateId, String scriptUri, int line, AddBreakpointWithScriptUriConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("scriptUri", scriptUri);
params.addProperty("line", line);
request("addBreakpointWithScriptUri", params, consumer);
}
/**
* The [addBreakpoint] RPC is used to add a breakpoint at a specific line of some script. This
* RPC is useful when a script has not yet been assigned an id, for example, if a script is in a
* deferred library which has not yet been loaded.
* @param column This parameter is optional and may be null.
*/
public void addBreakpointWithScriptUri(String isolateId, String scriptUri, int line, Integer column, AddBreakpointWithScriptUriConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("scriptUri", scriptUri);
params.addProperty("line", line);
if (column != null) params.addProperty("column", column);
request("addBreakpointWithScriptUri", params, consumer);
}
/**
* Clears all CPU profiling samples.
*/
public void clearCpuSamples(String isolateId, ClearCpuSamplesConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
request("clearCpuSamples", params, consumer);
}
/**
* Clears all VM timeline events.
*/
public void clearVMTimeline(SuccessConsumer consumer) {
final JsonObject params = new JsonObject();
request("clearVMTimeline", params, consumer);
}
/**
* The [evaluate] RPC is used to evaluate an expression in the context of some target.
*/
public void evaluate(String isolateId, String targetId, String expression, EvaluateConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("targetId", targetId);
params.addProperty("expression", removeNewLines(expression));
request("evaluate", params, consumer);
}
/**
* The [evaluate] RPC is used to evaluate an expression in the context of some target.
* @param scope This parameter is optional and may be null.
* @param disableBreakpoints This parameter is optional and may be null.
*/
public void evaluate(String isolateId, String targetId, String expression, Map<String, String> scope, Boolean disableBreakpoints, EvaluateConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("targetId", targetId);
params.addProperty("expression", removeNewLines(expression));
if (scope != null) params.add("scope", convertMapToJsonObject(scope));
if (disableBreakpoints != null) params.addProperty("disableBreakpoints", disableBreakpoints);
request("evaluate", params, consumer);
}
/**
* The [evaluateInFrame] RPC is used to evaluate an expression in the context of a particular
* stack frame. [frameIndex] is the index of the desired Frame, with an index of [0] indicating
* the top (most recent) frame.
*/
public void evaluateInFrame(String isolateId, int frameIndex, String expression, EvaluateInFrameConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("frameIndex", frameIndex);
params.addProperty("expression", removeNewLines(expression));
request("evaluateInFrame", params, consumer);
}
/**
* The [evaluateInFrame] RPC is used to evaluate an expression in the context of a particular
* stack frame. [frameIndex] is the index of the desired Frame, with an index of [0] indicating
* the top (most recent) frame.
* @param scope This parameter is optional and may be null.
* @param disableBreakpoints This parameter is optional and may be null.
*/
public void evaluateInFrame(String isolateId, int frameIndex, String expression, Map<String, String> scope, Boolean disableBreakpoints, EvaluateInFrameConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("frameIndex", frameIndex);
params.addProperty("expression", removeNewLines(expression));
if (scope != null) params.add("scope", convertMapToJsonObject(scope));
if (disableBreakpoints != null) params.addProperty("disableBreakpoints", disableBreakpoints);
request("evaluateInFrame", params, consumer);
}
/**
* The [getAllocationProfile] RPC is used to retrieve allocation information for a given isolate.
* @param reset This parameter is optional and may be null.
* @param gc This parameter is optional and may be null.
*/
public void getAllocationProfile(String isolateId, Boolean reset, Boolean gc, GetAllocationProfileConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
if (reset != null) params.addProperty("reset", reset);
if (gc != null) params.addProperty("gc", gc);
request("getAllocationProfile", params, consumer);
}
/**
* The [getAllocationProfile] RPC is used to retrieve allocation information for a given isolate.
*/
public void getAllocationProfile(String isolateId, GetAllocationProfileConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
request("getAllocationProfile", params, consumer);
}
/**
* The [getAllocationTraces] RPC allows for the retrieval of allocation traces for objects of a
* specific set of types (see setTraceClassAllocation). Only samples collected in the time range
* <code>[timeOriginMicros, timeOriginMicros + timeExtentMicros]</code>[timeOriginMicros,
* timeOriginMicros + timeExtentMicros] will be reported.
*/
public void getAllocationTraces(String isolateId, CpuSamplesConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
request("getAllocationTraces", params, consumer);
}
/**
* The [getAllocationTraces] RPC allows for the retrieval of allocation traces for objects of a
* specific set of types (see setTraceClassAllocation). Only samples collected in the time range
* <code>[timeOriginMicros, timeOriginMicros + timeExtentMicros]</code>[timeOriginMicros,
* timeOriginMicros + timeExtentMicros] will be reported.
* @param timeOriginMicros This parameter is optional and may be null.
* @param timeExtentMicros This parameter is optional and may be null.
* @param classId This parameter is optional and may be null.
*/
public void getAllocationTraces(String isolateId, Integer timeOriginMicros, Integer timeExtentMicros, String classId, CpuSamplesConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
if (timeOriginMicros != null) params.addProperty("timeOriginMicros", timeOriginMicros);
if (timeExtentMicros != null) params.addProperty("timeExtentMicros", timeExtentMicros);
if (classId != null) params.addProperty("classId", classId);
request("getAllocationTraces", params, consumer);
}
/**
* The [getClassList] RPC is used to retrieve a [ClassList] containing all classes for an isolate
* based on the isolate's [isolateId].
*/
public void getClassList(String isolateId, GetClassListConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
request("getClassList", params, consumer);
}
/**
* The [getCpuSamples] RPC is used to retrieve samples collected by the CPU profiler. Only
* samples collected in the time range <code>[timeOriginMicros, timeOriginMicros +
* timeExtentMicros]</code>[timeOriginMicros, timeOriginMicros + timeExtentMicros] will be
* reported.
*/
public void getCpuSamples(String isolateId, int timeOriginMicros, int timeExtentMicros, GetCpuSamplesConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("timeOriginMicros", timeOriginMicros);
params.addProperty("timeExtentMicros", timeExtentMicros);
request("getCpuSamples", params, consumer);
}
/**
* The [getFlagList] RPC returns a list of all command line flags in the VM along with their
* current values.
*/
public void getFlagList(FlagListConsumer consumer) {
final JsonObject params = new JsonObject();
request("getFlagList", params, consumer);
}
/**
* Returns a set of inbound references to the object specified by [targetId]. Up to [limit]
* references will be returned.
*/
public void getInboundReferences(String isolateId, String targetId, int limit, GetInboundReferencesConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("targetId", targetId);
params.addProperty("limit", limit);
request("getInboundReferences", params, consumer);
}
/**
* The [getInstances] RPC is used to retrieve a set of instances which are of a specific class.
* @param includeSubclasses This parameter is optional and may be null.
* @param includeImplementers This parameter is optional and may be null.
*/
public void getInstances(String isolateId, String objectId, int limit, Boolean includeSubclasses, Boolean includeImplementers, GetInstancesConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("objectId", objectId);
params.addProperty("limit", limit);
if (includeSubclasses != null) params.addProperty("includeSubclasses", includeSubclasses);
if (includeImplementers != null) params.addProperty("includeImplementers", includeImplementers);
request("getInstances", params, consumer);
}
/**
* The [getInstances] RPC is used to retrieve a set of instances which are of a specific class.
*/
public void getInstances(String isolateId, String objectId, int limit, GetInstancesConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("objectId", objectId);
params.addProperty("limit", limit);
request("getInstances", params, consumer);
}
/**
* The [getInstancesAsList] RPC is used to retrieve a set of instances which are of a specific
* class. This RPC returns an <code>@Instance</code>@Instance corresponding to a Dart
* <code>List<dynamic></code>List<dynamic> that contains the requested instances. This
* <code>List</code>List is not growable, but it is otherwise mutable. The response type is what
* distinguishes this RPC from <code>getInstances</code>getInstances, which returns an
* <code>InstanceSet</code>InstanceSet.
* @param includeSubclasses This parameter is optional and may be null.
* @param includeImplementers This parameter is optional and may be null.
*/
public void getInstancesAsList(String isolateId, String objectId, Boolean includeSubclasses, Boolean includeImplementers, GetInstancesAsListConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("objectId", objectId);
if (includeSubclasses != null) params.addProperty("includeSubclasses", includeSubclasses);
if (includeImplementers != null) params.addProperty("includeImplementers", includeImplementers);
request("getInstancesAsList", params, consumer);
}
/**
* The [getInstancesAsList] RPC is used to retrieve a set of instances which are of a specific
* class. This RPC returns an <code>@Instance</code>@Instance corresponding to a Dart
* <code>List<dynamic></code>List<dynamic> that contains the requested instances. This
* <code>List</code>List is not growable, but it is otherwise mutable. The response type is what
* distinguishes this RPC from <code>getInstances</code>getInstances, which returns an
* <code>InstanceSet</code>InstanceSet.
*/
public void getInstancesAsList(String isolateId, String objectId, GetInstancesAsListConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("objectId", objectId);
request("getInstancesAsList", params, consumer);
}
/**
* The [getIsolate] RPC is used to lookup an [Isolate] object by its [id].
*/
public void getIsolate(String isolateId, GetIsolateConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
request("getIsolate", params, consumer);
}
/**
* The [getIsolateGroup] RPC is used to lookup an [IsolateGroup] object by its [id].
*/
public void getIsolateGroup(String isolateGroupId, GetIsolateGroupConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateGroupId", isolateGroupId);
request("getIsolateGroup", params, consumer);
}
/**
* The [getIsolateGroupMemoryUsage] RPC is used to lookup an isolate group's memory usage
* statistics by its [id].
*/
public void getIsolateGroupMemoryUsage(String isolateGroupId, GetIsolateGroupMemoryUsageConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateGroupId", isolateGroupId);
request("getIsolateGroupMemoryUsage", params, consumer);
}
/**
* The [getMemoryUsage] RPC is used to lookup an isolate's memory usage statistics by its [id].
*/
public void getMemoryUsage(String isolateId, GetMemoryUsageConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
request("getMemoryUsage", params, consumer);
}
/**
* The [getObject] RPC is used to lookup an [object] from some isolate by its [id].
*/
public void getObject(String isolateId, String objectId, GetObjectConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("objectId", objectId);
request("getObject", params, consumer);
}
/**
* The [getObject] RPC is used to lookup an [object] from some isolate by its [id].
* @param offset This parameter is optional and may be null.
* @param count This parameter is optional and may be null.
*/
public void getObject(String isolateId, String objectId, Integer offset, Integer count, GetObjectConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("objectId", objectId);
if (offset != null) params.addProperty("offset", offset);
if (count != null) params.addProperty("count", count);
request("getObject", params, consumer);
}
/**
* The [getPorts] RPC is used to retrieve the list of <code>ReceivePort</code>ReceivePort
* instances for a given isolate.
*/
public void getPorts(String isolateId, PortListConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
request("getPorts", params, consumer);
}
/**
* Returns a description of major uses of memory known to the VM.
*/
public void getProcessMemoryUsage(ProcessMemoryUsageConsumer consumer) {
final JsonObject params = new JsonObject();
request("getProcessMemoryUsage", params, consumer);
}
/**
* The [getRetainingPath] RPC is used to lookup a path from an object specified by [targetId] to
* a GC root (i.e., the object which is preventing this object from being garbage collected).
*/
public void getRetainingPath(String isolateId, String targetId, int limit, GetRetainingPathConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("targetId", targetId);
params.addProperty("limit", limit);
request("getRetainingPath", params, consumer);
}
/**
* The [getScripts] RPC is used to retrieve a [ScriptList] containing all scripts for an isolate
* based on the isolate's [isolateId].
*/
public void getScripts(String isolateId, GetScriptsConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
request("getScripts", params, consumer);
}
/**
* The [getSourceReport] RPC is used to generate a set of reports tied to source locations in an
* isolate.
*/
public void getSourceReport(String isolateId, List<SourceReportKind> reports, GetSourceReportConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.add("reports", convertIterableToJsonArray(reports));
request("getSourceReport", params, consumer);
}
/**
* The [getSourceReport] RPC is used to generate a set of reports tied to source locations in an
* isolate.
* @param scriptId This parameter is optional and may be null.
* @param tokenPos This parameter is optional and may be null.
* @param endTokenPos This parameter is optional and may be null.
* @param forceCompile This parameter is optional and may be null.
* @param reportLines This parameter is optional and may be null.
* @param libraryFilters This parameter is optional and may be null.
*/
public void getSourceReport(String isolateId, List<SourceReportKind> reports, String scriptId, Integer tokenPos, Integer endTokenPos, Boolean forceCompile, Boolean reportLines, List<String> libraryFilters, GetSourceReportConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.add("reports", convertIterableToJsonArray(reports));
if (scriptId != null) params.addProperty("scriptId", scriptId);
if (tokenPos != null) params.addProperty("tokenPos", tokenPos);
if (endTokenPos != null) params.addProperty("endTokenPos", endTokenPos);
if (forceCompile != null) params.addProperty("forceCompile", forceCompile);
if (reportLines != null) params.addProperty("reportLines", reportLines);
if (libraryFilters != null) params.add("libraryFilters", convertIterableToJsonArray(libraryFilters));
request("getSourceReport", params, consumer);
}
/**
* The [getStack] RPC is used to retrieve the current execution stack and message queue for an
* isolate. The isolate does not need to be paused.
*/
public void getStack(String isolateId, GetStackConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
request("getStack", params, consumer);
}
/**
* The [getStack] RPC is used to retrieve the current execution stack and message queue for an
* isolate. The isolate does not need to be paused.
* @param limit This parameter is optional and may be null.
*/
public void getStack(String isolateId, Integer limit, GetStackConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
if (limit != null) params.addProperty("limit", limit);
request("getStack", params, consumer);
}
/**
* The [getSupportedProtocols] RPC is used to determine which protocols are supported by the
* current server.
*/
public void getSupportedProtocols(ProtocolListConsumer consumer) {
final JsonObject params = new JsonObject();
request("getSupportedProtocols", params, consumer);
}
/**
* The [getVM] RPC returns global information about a Dart virtual machine.
*/
public void getVM(VMConsumer consumer) {
final JsonObject params = new JsonObject();
request("getVM", params, consumer);
}
/**
* The [getVMTimeline] RPC is used to retrieve an object which contains VM timeline events.
* @param timeOriginMicros This parameter is optional and may be null.
* @param timeExtentMicros This parameter is optional and may be null.
*/
public void getVMTimeline(Integer timeOriginMicros, Integer timeExtentMicros, TimelineConsumer consumer) {
final JsonObject params = new JsonObject();
if (timeOriginMicros != null) params.addProperty("timeOriginMicros", timeOriginMicros);
if (timeExtentMicros != null) params.addProperty("timeExtentMicros", timeExtentMicros);
request("getVMTimeline", params, consumer);
}
/**
* The [getVMTimeline] RPC is used to retrieve an object which contains VM timeline events.
*/
public void getVMTimeline(TimelineConsumer consumer) {
final JsonObject params = new JsonObject();
request("getVMTimeline", params, consumer);
}
/**
* The [getVMTimelineFlags] RPC returns information about the current VM timeline configuration.
*/
public void getVMTimelineFlags(TimelineFlagsConsumer consumer) {
final JsonObject params = new JsonObject();
request("getVMTimelineFlags", params, consumer);
}
/**
* The [getVMTimelineMicros] RPC returns the current time stamp from the clock used by the
* timeline, similar to <code>Timeline.now</code>Timeline.now in
* <code>dart:developer</code>dart:developer and
* <code>Dart_TimelineGetMicros</code>Dart_TimelineGetMicros in the VM embedding API.
*/
public void getVMTimelineMicros(TimestampConsumer consumer) {
final JsonObject params = new JsonObject();
request("getVMTimelineMicros", params, consumer);
}
/**
* The [getVersion] RPC is used to determine what version of the Service Protocol is served by a
* VM.
*/
public void getVersion(VersionConsumer consumer) {
final JsonObject params = new JsonObject();
request("getVersion", params, consumer);
}
/**
* The [invoke] RPC is used to perform regular method invocation on some receiver, as if by
* dart:mirror's ObjectMirror.invoke. Note this does not provide a way to perform getter, setter
* or constructor invocation.
* @param disableBreakpoints This parameter is optional and may be null.
*/
public void invoke(String isolateId, String targetId, String selector, List<String> argumentIds, Boolean disableBreakpoints, InvokeConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("targetId", targetId);
params.addProperty("selector", selector);
params.add("argumentIds", convertIterableToJsonArray(argumentIds));
if (disableBreakpoints != null) params.addProperty("disableBreakpoints", disableBreakpoints);
request("invoke", params, consumer);
}
/**
* The [invoke] RPC is used to perform regular method invocation on some receiver, as if by
* dart:mirror's ObjectMirror.invoke. Note this does not provide a way to perform getter, setter
* or constructor invocation.
*/
public void invoke(String isolateId, String targetId, String selector, List<String> argumentIds, InvokeConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("targetId", targetId);
params.addProperty("selector", selector);
params.add("argumentIds", convertIterableToJsonArray(argumentIds));
request("invoke", params, consumer);
}
/**
* The [kill] RPC is used to kill an isolate as if by dart:isolate's
* <code>Isolate.kill(IMMEDIATE)</code>Isolate.kill(IMMEDIATE).
*/
public void kill(String isolateId, KillConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
request("kill", params, consumer);
}
/**
* The [lookupPackageUris] RPC is used to convert a list of URIs to their unresolved paths. For
* example, URIs passed to this RPC are mapped in the following ways:
*/
public void lookupPackageUris(String isolateId, List<String> uris, UriListConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.add("uris", convertIterableToJsonArray(uris));
request("lookupPackageUris", params, consumer);
}
/**
* The [lookupResolvedPackageUris] RPC is used to convert a list of URIs to their resolved (or
* absolute) paths. For example, URIs passed to this RPC are mapped in the following ways:
* @param local This parameter is optional and may be null.
*/
public void lookupResolvedPackageUris(String isolateId, List<String> uris, Boolean local, UriListConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.add("uris", convertIterableToJsonArray(uris));
if (local != null) params.addProperty("local", local);
request("lookupResolvedPackageUris", params, consumer);
}
/**
* The [lookupResolvedPackageUris] RPC is used to convert a list of URIs to their resolved (or
* absolute) paths. For example, URIs passed to this RPC are mapped in the following ways:
*/
public void lookupResolvedPackageUris(String isolateId, List<String> uris, UriListConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.add("uris", convertIterableToJsonArray(uris));
request("lookupResolvedPackageUris", params, consumer);
}
/**
* The [pause] RPC is used to interrupt a running isolate. The RPC enqueues the interrupt request
* and potentially returns before the isolate is paused.
*/
public void pause(String isolateId, PauseConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
request("pause", params, consumer);
}
/**
* Registers a service that can be invoked by other VM service clients, where
* <code>service</code>service is the name of the service to advertise and
* <code>alias</code>alias is an alternative name for the registered service.
*/
public void registerService(String service, String alias, SuccessConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("service", service);
params.addProperty("alias", alias);
request("registerService", params, consumer);
}
/**
* The [reloadSources] RPC is used to perform a hot reload of an Isolate's sources.
* @param force This parameter is optional and may be null.
* @param pause This parameter is optional and may be null.
* @param rootLibUri This parameter is optional and may be null.
* @param packagesUri This parameter is optional and may be null.
*/
public void reloadSources(String isolateId, Boolean force, Boolean pause, String rootLibUri, String packagesUri, ReloadSourcesConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
if (force != null) params.addProperty("force", force);
if (pause != null) params.addProperty("pause", pause);
if (rootLibUri != null) params.addProperty("rootLibUri", rootLibUri);
if (packagesUri != null) params.addProperty("packagesUri", packagesUri);
request("reloadSources", params, consumer);
}
/**
* The [reloadSources] RPC is used to perform a hot reload of an Isolate's sources.
*/
public void reloadSources(String isolateId, ReloadSourcesConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
request("reloadSources", params, consumer);
}
/**
* The [removeBreakpoint] RPC is used to remove a breakpoint by its [id].
*/
public void removeBreakpoint(String isolateId, String breakpointId, RemoveBreakpointConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("breakpointId", breakpointId);
request("removeBreakpoint", params, consumer);
}
/**
* Requests a dump of the Dart heap of the given isolate.
*/
public void requestHeapSnapshot(String isolateId, RequestHeapSnapshotConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
request("requestHeapSnapshot", params, consumer);
}
/**
* The [resume] RPC is used to resume execution of a paused isolate.
*/
public void resume(String isolateId, ResumeConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
request("resume", params, consumer);
}
/**
* The [resume] RPC is used to resume execution of a paused isolate.
* @param step A [StepOption] indicates which form of stepping is requested in a resume RPC. This
* parameter is optional and may be null.
* @param frameIndex This parameter is optional and may be null.
*/
public void resume(String isolateId, StepOption step, Integer frameIndex, ResumeConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
if (step != null) params.addProperty("step", step.name());
if (frameIndex != null) params.addProperty("frameIndex", frameIndex);
request("resume", params, consumer);
}
/**
* The [setBreakpointState] RPC allows for breakpoints to be enabled or disabled, without
* requiring for the breakpoint to be completely removed.
*/
public void setBreakpointState(String isolateId, String breakpointId, boolean enable, BreakpointConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("breakpointId", breakpointId);
params.addProperty("enable", enable);
request("setBreakpointState", params, consumer);
}
/**
* The [setExceptionPauseMode] RPC is used to control if an isolate pauses when an exception is
* thrown.
* @param mode An [ExceptionPauseMode] indicates how the isolate pauses when an exception is
* thrown.
*/
@Deprecated
public void setExceptionPauseMode(String isolateId, ExceptionPauseMode mode, SetExceptionPauseModeConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("mode", mode.name());
request("setExceptionPauseMode", params, consumer);
}
/**
* The [setFlag] RPC is used to set a VM flag at runtime. Returns an error if the named flag does
* not exist, the flag may not be set at runtime, or the value is of the wrong type for the flag.
*/
public void setFlag(String name, String value, SetFlagConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("name", name);
params.addProperty("value", value);
request("setFlag", params, consumer);
}
/**
* The [setIsolatePauseMode] RPC is used to control if or when an isolate will pause due to a
* change in execution state.
* @param exceptionPauseMode An [ExceptionPauseMode] indicates how the isolate pauses when an
* exception is thrown. This parameter is optional and may be null.
* @param shouldPauseOnExit This parameter is optional and may be null.
*/
public void setIsolatePauseMode(String isolateId, ExceptionPauseMode exceptionPauseMode, Boolean shouldPauseOnExit, SetIsolatePauseModeConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
if (exceptionPauseMode != null) params.addProperty("exceptionPauseMode", exceptionPauseMode.name());
if (shouldPauseOnExit != null) params.addProperty("shouldPauseOnExit", shouldPauseOnExit);
request("setIsolatePauseMode", params, consumer);
}
/**
* The [setIsolatePauseMode] RPC is used to control if or when an isolate will pause due to a
* change in execution state.
*/
public void setIsolatePauseMode(String isolateId, SetIsolatePauseModeConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
request("setIsolatePauseMode", params, consumer);
}
/**
* The [setLibraryDebuggable] RPC is used to enable or disable whether breakpoints and stepping
* work for a given library.
*/
public void setLibraryDebuggable(String isolateId, String libraryId, boolean isDebuggable, SetLibraryDebuggableConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("libraryId", libraryId);
params.addProperty("isDebuggable", isDebuggable);
request("setLibraryDebuggable", params, consumer);
}
/**
* The [setName] RPC is used to change the debugging name for an isolate.
*/
public void setName(String isolateId, String name, SetNameConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("name", name);
request("setName", params, consumer);
}
/**
* The [setTraceClassAllocation] RPC allows for enabling or disabling allocation tracing for a
* specific type of object. Allocation traces can be retrieved with the [getAllocationTraces]
* RPC.
*/
public void setTraceClassAllocation(String isolateId, String classId, boolean enable, SetTraceClassAllocationConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("isolateId", isolateId);
params.addProperty("classId", classId);
params.addProperty("enable", enable);
request("setTraceClassAllocation", params, consumer);
}
/**
* The [setVMName] RPC is used to change the debugging name for the vm.
*/
public void setVMName(String name, SuccessConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("name", name);
request("setVMName", params, consumer);
}
/**
* The [setVMTimelineFlags] RPC is used to set which timeline streams are enabled.
*/
public void setVMTimelineFlags(List<String> recordedStreams, SuccessConsumer consumer) {
final JsonObject params = new JsonObject();
params.add("recordedStreams", convertIterableToJsonArray(recordedStreams));
request("setVMTimelineFlags", params, consumer);
}
/**
* The [streamCancel] RPC cancels a stream subscription in the VM.
*/
public void streamCancel(String streamId, SuccessConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("streamId", streamId);
request("streamCancel", params, consumer);
}
/**
* The [streamCpuSamplesWithUserTag] RPC allows for clients to specify which CPU samples
* collected by the profiler should be sent over the <code>Profiler</code>Profiler stream. When
* called, the VM will stream <code>CpuSamples</code>CpuSamples events containing
* <code>CpuSample</code>CpuSample's collected while a user tag contained in
* <code>userTags</code>userTags was active.
*/
public void streamCpuSamplesWithUserTag(List<String> userTags, SuccessConsumer consumer) {
final JsonObject params = new JsonObject();
params.add("userTags", convertIterableToJsonArray(userTags));
request("streamCpuSamplesWithUserTag", params, consumer);
}
/**
* The [streamListen] RPC subscribes to a stream in the VM. Once subscribed, the client will
* begin receiving events from the stream.
*/
public void streamListen(String streamId, SuccessConsumer consumer) {
final JsonObject params = new JsonObject();
params.addProperty("streamId", streamId);
request("streamListen", params, consumer);
}
private JsonArray convertIterableToJsonArray(Iterable list) {
JsonArray arr = new JsonArray();
for (Object element : list) {
arr.add(new JsonPrimitive(element.toString()));
}
return arr;
}
private JsonObject convertMapToJsonObject(Map<String, String> map) {
JsonObject obj = new JsonObject();
for (String key : map.keySet()) {
obj.addProperty(key, map.get(key));
}
return obj;
}
@Override
void forwardResponse(Consumer consumer, String responseType, JsonObject json) {
if (consumer instanceof AddBreakpointAtEntryConsumer) {
if (responseType.equals("Breakpoint")) {
((AddBreakpointAtEntryConsumer) consumer).received(new Breakpoint(json));
return;
}
if (responseType.equals("Sentinel")) {
((AddBreakpointAtEntryConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof AddBreakpointConsumer) {
if (responseType.equals("Breakpoint")) {
((AddBreakpointConsumer) consumer).received(new Breakpoint(json));
return;
}
if (responseType.equals("Sentinel")) {
((AddBreakpointConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof AddBreakpointWithScriptUriConsumer) {
if (responseType.equals("Breakpoint")) {
((AddBreakpointWithScriptUriConsumer) consumer).received(new Breakpoint(json));
return;
}
if (responseType.equals("Sentinel")) {
((AddBreakpointWithScriptUriConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof BreakpointConsumer) {
if (responseType.equals("Breakpoint")) {
((BreakpointConsumer) consumer).received(new Breakpoint(json));
return;
}
}
if (consumer instanceof ClearCpuSamplesConsumer) {
if (responseType.equals("Sentinel")) {
((ClearCpuSamplesConsumer) consumer).received(new Sentinel(json));
return;
}
if (responseType.equals("Success")) {
((ClearCpuSamplesConsumer) consumer).received(new Success(json));
return;
}
}
if (consumer instanceof CpuSamplesConsumer) {
if (responseType.equals("CpuSamples")) {
((CpuSamplesConsumer) consumer).received(new CpuSamples(json));
return;
}
}
if (consumer instanceof EvaluateConsumer) {
if (responseType.equals("@Error")) {
((EvaluateConsumer) consumer).received(new ErrorRef(json));
return;
}
if (responseType.equals("@Instance")) {
((EvaluateConsumer) consumer).received(new InstanceRef(json));
return;
}
if (responseType.equals("@Null")) {
((EvaluateConsumer) consumer).received(new NullRef(json));
return;
}
if (responseType.equals("Sentinel")) {
((EvaluateConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof EvaluateInFrameConsumer) {
if (responseType.equals("@Error")) {
((EvaluateInFrameConsumer) consumer).received(new ErrorRef(json));
return;
}
if (responseType.equals("@Instance")) {
((EvaluateInFrameConsumer) consumer).received(new InstanceRef(json));
return;
}
if (responseType.equals("@Null")) {
((EvaluateInFrameConsumer) consumer).received(new NullRef(json));
return;
}
if (responseType.equals("Sentinel")) {
((EvaluateInFrameConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof FlagListConsumer) {
if (responseType.equals("FlagList")) {
((FlagListConsumer) consumer).received(new FlagList(json));
return;
}
}
if (consumer instanceof GetAllocationProfileConsumer) {
if (responseType.equals("AllocationProfile")) {
((GetAllocationProfileConsumer) consumer).received(new AllocationProfile(json));
return;
}
if (responseType.equals("Sentinel")) {
((GetAllocationProfileConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof GetClassListConsumer) {
if (responseType.equals("ClassList")) {
((GetClassListConsumer) consumer).received(new ClassList(json));
return;
}
if (responseType.equals("Sentinel")) {
((GetClassListConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof GetCpuSamplesConsumer) {
if (responseType.equals("CpuSamples")) {
((GetCpuSamplesConsumer) consumer).received(new CpuSamples(json));
return;
}
if (responseType.equals("Sentinel")) {
((GetCpuSamplesConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof GetInboundReferencesConsumer) {
if (responseType.equals("InboundReferences")) {
((GetInboundReferencesConsumer) consumer).received(new InboundReferences(json));
return;
}
if (responseType.equals("Sentinel")) {
((GetInboundReferencesConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof GetInstancesAsListConsumer) {
if (responseType.equals("@Instance")) {
((GetInstancesAsListConsumer) consumer).received(new InstanceRef(json));
return;
}
if (responseType.equals("@Null")) {
((GetInstancesAsListConsumer) consumer).received(new NullRef(json));
return;
}
if (responseType.equals("Sentinel")) {
((GetInstancesAsListConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof GetInstancesConsumer) {
if (responseType.equals("InstanceSet")) {
((GetInstancesConsumer) consumer).received(new InstanceSet(json));
return;
}
if (responseType.equals("Sentinel")) {
((GetInstancesConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof GetIsolateConsumer) {
if (responseType.equals("Isolate")) {
((GetIsolateConsumer) consumer).received(new Isolate(json));
return;
}
if (responseType.equals("Sentinel")) {
((GetIsolateConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof GetIsolateGroupConsumer) {
if (responseType.equals("IsolateGroup")) {
((GetIsolateGroupConsumer) consumer).received(new IsolateGroup(json));
return;
}
if (responseType.equals("Sentinel")) {
((GetIsolateGroupConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof GetIsolateGroupMemoryUsageConsumer) {
if (responseType.equals("MemoryUsage")) {
((GetIsolateGroupMemoryUsageConsumer) consumer).received(new MemoryUsage(json));
return;
}
if (responseType.equals("Sentinel")) {
((GetIsolateGroupMemoryUsageConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof GetMemoryUsageConsumer) {
if (responseType.equals("MemoryUsage")) {
((GetMemoryUsageConsumer) consumer).received(new MemoryUsage(json));
return;
}
if (responseType.equals("Sentinel")) {
((GetMemoryUsageConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof GetObjectConsumer) {
if (responseType.equals("Breakpoint")) {
((GetObjectConsumer) consumer).received(new Breakpoint(json));
return;
}
if (responseType.equals("Class")) {
((GetObjectConsumer) consumer).received(new ClassObj(json));
return;
}
if (responseType.equals("Code")) {
((GetObjectConsumer) consumer).received(new Code(json));
return;
}
if (responseType.equals("Context")) {
((GetObjectConsumer) consumer).received(new Context(json));
return;
}
if (responseType.equals("Error")) {
((GetObjectConsumer) consumer).received(new ErrorObj(json));
return;
}
if (responseType.equals("Field")) {
((GetObjectConsumer) consumer).received(new Field(json));
return;
}
if (responseType.equals("Function")) {
((GetObjectConsumer) consumer).received(new Func(json));
return;
}
if (responseType.equals("Instance")) {
((GetObjectConsumer) consumer).received(new Instance(json));
return;
}
if (responseType.equals("Library")) {
((GetObjectConsumer) consumer).received(new Library(json));
return;
}
if (responseType.equals("Null")) {
((GetObjectConsumer) consumer).received(new Null(json));
return;
}
if (responseType.equals("Object")) {
((GetObjectConsumer) consumer).received(new Obj(json));
return;
}
if (responseType.equals("Script")) {
((GetObjectConsumer) consumer).received(new Script(json));
return;
}
if (responseType.equals("Sentinel")) {
((GetObjectConsumer) consumer).received(new Sentinel(json));
return;
}
if (responseType.equals("TypeArguments")) {
((GetObjectConsumer) consumer).received(new TypeArguments(json));
return;
}
}
if (consumer instanceof GetRetainingPathConsumer) {
if (responseType.equals("RetainingPath")) {
((GetRetainingPathConsumer) consumer).received(new RetainingPath(json));
return;
}
if (responseType.equals("Sentinel")) {
((GetRetainingPathConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof GetScriptsConsumer) {
if (responseType.equals("ScriptList")) {
((GetScriptsConsumer) consumer).received(new ScriptList(json));
return;
}
if (responseType.equals("Sentinel")) {
((GetScriptsConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof GetSourceReportConsumer) {
if (responseType.equals("Sentinel")) {
((GetSourceReportConsumer) consumer).received(new Sentinel(json));
return;
}
if (responseType.equals("SourceReport")) {
((GetSourceReportConsumer) consumer).received(new SourceReport(json));
return;
}
}
if (consumer instanceof GetStackConsumer) {
if (responseType.equals("Sentinel")) {
((GetStackConsumer) consumer).received(new Sentinel(json));
return;
}
if (responseType.equals("Stack")) {
((GetStackConsumer) consumer).received(new Stack(json));
return;
}
}
if (consumer instanceof InvokeConsumer) {
if (responseType.equals("@Error")) {
((InvokeConsumer) consumer).received(new ErrorRef(json));
return;
}
if (responseType.equals("@Instance")) {
((InvokeConsumer) consumer).received(new InstanceRef(json));
return;
}
if (responseType.equals("@Null")) {
((InvokeConsumer) consumer).received(new NullRef(json));
return;
}
if (responseType.equals("Sentinel")) {
((InvokeConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof KillConsumer) {
if (responseType.equals("Sentinel")) {
((KillConsumer) consumer).received(new Sentinel(json));
return;
}
if (responseType.equals("Success")) {
((KillConsumer) consumer).received(new Success(json));
return;
}
}
if (consumer instanceof PauseConsumer) {
if (responseType.equals("Sentinel")) {
((PauseConsumer) consumer).received(new Sentinel(json));
return;
}
if (responseType.equals("Success")) {
((PauseConsumer) consumer).received(new Success(json));
return;
}
}
if (consumer instanceof PortListConsumer) {
if (responseType.equals("PortList")) {
((PortListConsumer) consumer).received(new PortList(json));
return;
}
}
if (consumer instanceof ProcessMemoryUsageConsumer) {
if (responseType.equals("ProcessMemoryUsage")) {
((ProcessMemoryUsageConsumer) consumer).received(new ProcessMemoryUsage(json));
return;
}
}
if (consumer instanceof ProtocolListConsumer) {
if (responseType.equals("ProtocolList")) {
((ProtocolListConsumer) consumer).received(new ProtocolList(json));
return;
}
}
if (consumer instanceof ReloadSourcesConsumer) {
if (responseType.equals("ReloadReport")) {
((ReloadSourcesConsumer) consumer).received(new ReloadReport(json));
return;
}
if (responseType.equals("Sentinel")) {
((ReloadSourcesConsumer) consumer).received(new Sentinel(json));
return;
}
}
if (consumer instanceof RemoveBreakpointConsumer) {
if (responseType.equals("Sentinel")) {
((RemoveBreakpointConsumer) consumer).received(new Sentinel(json));
return;
}
if (responseType.equals("Success")) {
((RemoveBreakpointConsumer) consumer).received(new Success(json));
return;
}
}
if (consumer instanceof RequestHeapSnapshotConsumer) {
if (responseType.equals("Sentinel")) {
((RequestHeapSnapshotConsumer) consumer).received(new Sentinel(json));
return;
}
if (responseType.equals("Success")) {
((RequestHeapSnapshotConsumer) consumer).received(new Success(json));
return;
}
}
if (consumer instanceof ResumeConsumer) {
if (responseType.equals("Sentinel")) {
((ResumeConsumer) consumer).received(new Sentinel(json));
return;
}
if (responseType.equals("Success")) {
((ResumeConsumer) consumer).received(new Success(json));
return;
}
}
if (consumer instanceof SetExceptionPauseModeConsumer) {
if (responseType.equals("Sentinel")) {
((SetExceptionPauseModeConsumer) consumer).received(new Sentinel(json));
return;
}
if (responseType.equals("Success")) {
((SetExceptionPauseModeConsumer) consumer).received(new Success(json));
return;
}
}
if (consumer instanceof SetFlagConsumer) {
if (responseType.equals("Error")) {
((SetFlagConsumer) consumer).received(new ErrorObj(json));
return;
}
if (responseType.equals("Success")) {
((SetFlagConsumer) consumer).received(new Success(json));
return;
}
}
if (consumer instanceof SetIsolatePauseModeConsumer) {
if (responseType.equals("Sentinel")) {
((SetIsolatePauseModeConsumer) consumer).received(new Sentinel(json));
return;
}
if (responseType.equals("Success")) {
((SetIsolatePauseModeConsumer) consumer).received(new Success(json));
return;
}
}
if (consumer instanceof SetLibraryDebuggableConsumer) {
if (responseType.equals("Sentinel")) {
((SetLibraryDebuggableConsumer) consumer).received(new Sentinel(json));
return;
}
if (responseType.equals("Success")) {
((SetLibraryDebuggableConsumer) consumer).received(new Success(json));
return;
}
}
if (consumer instanceof SetNameConsumer) {
if (responseType.equals("Sentinel")) {
((SetNameConsumer) consumer).received(new Sentinel(json));
return;
}
if (responseType.equals("Success")) {
((SetNameConsumer) consumer).received(new Success(json));
return;
}
}
if (consumer instanceof SetTraceClassAllocationConsumer) {
if (responseType.equals("Sentinel")) {
((SetTraceClassAllocationConsumer) consumer).received(new Sentinel(json));
return;
}
if (responseType.equals("Success")) {
((SetTraceClassAllocationConsumer) consumer).received(new Success(json));
return;
}
}
if (consumer instanceof SuccessConsumer) {
if (responseType.equals("Success")) {
((SuccessConsumer) consumer).received(new Success(json));
return;
}
}
if (consumer instanceof TimelineConsumer) {
if (responseType.equals("Timeline")) {
((TimelineConsumer) consumer).received(new Timeline(json));
return;
}
}
if (consumer instanceof TimelineFlagsConsumer) {
if (responseType.equals("TimelineFlags")) {
((TimelineFlagsConsumer) consumer).received(new TimelineFlags(json));
return;
}
}
if (consumer instanceof TimestampConsumer) {
if (responseType.equals("Timestamp")) {
((TimestampConsumer) consumer).received(new Timestamp(json));
return;
}
}
if (consumer instanceof UriListConsumer) {
if (responseType.equals("UriList")) {
((UriListConsumer) consumer).received(new UriList(json));
return;
}
}
if (consumer instanceof VMConsumer) {
if (responseType.equals("VM")) {
((VMConsumer) consumer).received(new VM(json));
return;
}
}
if (consumer instanceof VersionConsumer) {
if (responseType.equals("Version")) {
((VersionConsumer) consumer).received(new Version(json));
return;
}
}
if (consumer instanceof ServiceExtensionConsumer) {
((ServiceExtensionConsumer) consumer).received(json);
return;
}
logUnknownResponse(consumer, json);
}
}
| flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/VmService.java/0 | {
"file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/VmService.java",
"repo_id": "flutter-intellij",
"token_count": 18919
} | 517 |
/*
* Copyright (c) 2015, the Dart project authors.
*
* Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.dartlang.vm.service.element;
// This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk.
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/**
* A {@link Library} provides information about a Dart language library.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class Library extends Obj {
public Library(JsonObject json) {
super(json);
}
/**
* A list of all classes in this library.
*/
public ElementList<ClassRef> getClasses() {
return new ElementList<ClassRef>(json.get("classes").getAsJsonArray()) {
@Override
protected ClassRef basicGet(JsonArray array, int index) {
return new ClassRef(array.get(index).getAsJsonObject());
}
};
}
/**
* Is this library debuggable? Default true.
*/
public boolean getDebuggable() {
return getAsBoolean("debuggable");
}
/**
* A list of the imports for this library.
*/
public ElementList<LibraryDependency> getDependencies() {
return new ElementList<LibraryDependency>(json.get("dependencies").getAsJsonArray()) {
@Override
protected LibraryDependency basicGet(JsonArray array, int index) {
return new LibraryDependency(array.get(index).getAsJsonObject());
}
};
}
/**
* A list of the top-level functions in this library.
*/
public ElementList<FuncRef> getFunctions() {
return new ElementList<FuncRef>(json.get("functions").getAsJsonArray()) {
@Override
protected FuncRef basicGet(JsonArray array, int index) {
return new FuncRef(array.get(index).getAsJsonObject());
}
};
}
/**
* The name of this library.
*/
public String getName() {
return getAsString("name");
}
/**
* A list of the scripts which constitute this library.
*/
public ElementList<ScriptRef> getScripts() {
return new ElementList<ScriptRef>(json.get("scripts").getAsJsonArray()) {
@Override
protected ScriptRef basicGet(JsonArray array, int index) {
return new ScriptRef(array.get(index).getAsJsonObject());
}
};
}
/**
* The uri of this library.
*/
public String getUri() {
return getAsString("uri");
}
/**
* A list of the top-level variables in this library.
*/
public ElementList<FieldRef> getVariables() {
return new ElementList<FieldRef>(json.get("variables").getAsJsonArray()) {
@Override
protected FieldRef basicGet(JsonArray array, int index) {
return new FieldRef(array.get(index).getAsJsonObject());
}
};
}
}
| flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Library.java/0 | {
"file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Library.java",
"repo_id": "flutter-intellij",
"token_count": 1086
} | 518 |
/*
* Copyright (c) 2015, the Dart project authors.
*
* Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.dartlang.vm.service.element;
// This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk.
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/**
* A {@link ProfileFunction} contains profiling information about a Dart or native function.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class ProfileFunction extends Element {
public ProfileFunction(JsonObject json) {
super(json);
}
/**
* The number of times function appeared on the top of the stack during sampling events.
*/
public int getExclusiveTicks() {
return getAsInt("exclusiveTicks");
}
/**
* The function captured during profiling.
*
* @return one of <code>FuncRef</code> or <code>NativeFunction</code>
*/
public Object getFunction() {
final JsonElement elem = json.get("function");
if (elem == null) return null;
if (elem.isJsonObject()) {
final JsonObject o = (JsonObject) elem;
if (o.get("type").getAsString().equals("@Func")) return new FuncRef(o);
if (o.get("type").getAsString().equals("NativeFunction")) return new NativeFunction(o);
}
return null;
}
/**
* The number of times function appeared on the stack during sampling events.
*/
public int getInclusiveTicks() {
return getAsInt("inclusiveTicks");
}
/**
* The kind of function this object represents.
*/
public String getKind() {
return getAsString("kind");
}
/**
* The resolved URL for the script containing function.
*/
public String getResolvedUrl() {
return getAsString("resolvedUrl");
}
}
| flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ProfileFunction.java/0 | {
"file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ProfileFunction.java",
"repo_id": "flutter-intellij",
"token_count": 687
} | 519 |
/*
* Copyright (c) 2015, the Dart project authors.
*
* Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.dartlang.vm.service.element;
// This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk.
import com.google.gson.JsonObject;
import java.util.List;
/**
* The {@link SourceReportCoverage} class represents coverage information for one
* SourceReportRange.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class SourceReportCoverage extends Element {
public SourceReportCoverage(JsonObject json) {
super(json);
}
/**
* A list of token positions (or line numbers if reportLines was enabled) in a SourceReportRange
* which have been executed. The list is sorted.
*/
public List<Integer> getHits() {
return getListInt("hits");
}
/**
* A list of token positions (or line numbers if reportLines was enabled) in a SourceReportRange
* which have not been executed. The list is sorted.
*/
public List<Integer> getMisses() {
return getListInt("misses");
}
}
| flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/SourceReportCoverage.java/0 | {
"file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/SourceReportCoverage.java",
"repo_id": "flutter-intellij",
"token_count": 452
} | 520 |
package io.flutter.project;
import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.ide.util.projectWizard.SettingsStep;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.Disposable;
import io.flutter.FlutterBundle;
import io.flutter.module.FlutterModuleBuilder;
import io.flutter.module.FlutterProjectType;
import org.jetbrains.annotations.NotNull;
// Define a group of Flutter project types for use in Android Studio 4.2 and later.
// TODO (messick) DO NOT delete this during post-4.2 clean-up.
public abstract class FlutterModuleGroup extends FlutterModuleBuilder {
abstract public FlutterProjectType getFlutterProjectType();
abstract public String getDescription();
@Override
public String getBuilderId() {
return super.getBuilderId() + getFlutterProjectType().arg;
}
@Override
public ModuleWizardStep getCustomOptionsStep(final WizardContext context, final Disposable parentDisposable) {
// This runs each time the project type selection changes.
FlutterModuleWizardStep step = (FlutterModuleWizardStep)super.getCustomOptionsStep(context, parentDisposable);
assert step!= null;
getSettingsField().linkHelpForm(step.getHelpForm());
setProjectTypeInSettings();
return step;
}
@Override
public ModuleWizardStep modifySettingsStep(@NotNull SettingsStep settingsStep) {
// This runs when the Next button takes the wizard to the second page.
ModuleWizardStep wizard = super.modifySettingsStep(settingsStep);
setProjectTypeInSettings(); // TODO (messick) Remove this if possible (needs testing).
return wizard;
}
// Using a parent group ensures there are no separators. The getWeight() in each subclass method controls sort order.
@Override
public String getParentGroup() {
return "Flutter";
}
protected void setProjectTypeInSettings() {
getSettingsField().updateProjectType(getFlutterProjectType());
}
public static class App extends FlutterModuleGroup {
@NotNull
public FlutterProjectType getFlutterProjectType() {
return FlutterProjectType.APP;
}
@Override
public String getPresentableName() {
return FlutterBundle.message("module.wizard.app_title_short");
}
public String getDescription() {
return FlutterBundle.message("flutter.module.create.settings.help.project_type.description.app");
}
public int getWeight() {
return 4;
}
}
public static class Mod extends FlutterModuleGroup {
@NotNull
public FlutterProjectType getFlutterProjectType() {
return FlutterProjectType.MODULE;
}
@Override
public String getPresentableName() {
return FlutterBundle.message("module.wizard.module_title");
}
public String getDescription() {
return FlutterBundle.message("flutter.module.create.settings.help.project_type.description.module");
}
public int getWeight() {
return 3;
}
}
public static class Plugin extends FlutterModuleGroup {
@NotNull
public FlutterProjectType getFlutterProjectType() {
return FlutterProjectType.PLUGIN;
}
@Override
public String getPresentableName() {
return FlutterBundle.message("module.wizard.plugin_title");
}
public String getDescription() {
return FlutterBundle.message("flutter.module.create.settings.help.project_type.description.plugin");
}
public int getWeight() {
return 2;
}
}
public static class Package extends FlutterModuleGroup {
@NotNull
public FlutterProjectType getFlutterProjectType() {
return FlutterProjectType.PACKAGE;
}
@Override
public String getPresentableName() {
return FlutterBundle.message("module.wizard.package_title");
}
public String getDescription() {
return FlutterBundle.message("flutter.module.create.settings.help.project_type.description.package");
}
public int getWeight() {
return 1;
}
}
}
| flutter-intellij/flutter-studio/src/io/flutter/project/FlutterModuleGroup.java/0 | {
"file_path": "flutter-intellij/flutter-studio/src/io/flutter/project/FlutterModuleGroup.java",
"repo_id": "flutter-intellij",
"token_count": 1274
} | 521 |
/*
* Copyright 2017 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package com.android.tools.idea.tests.gui.framework.fixture.newProjectWizard;
import com.android.tools.idea.tests.gui.framework.fixture.wizard.AbstractWizardFixture;
import com.android.tools.idea.tests.gui.framework.fixture.wizard.AbstractWizardStepFixture;
import io.flutter.FlutterBundle;
import javax.swing.JCheckBox;
import javax.swing.JRootPane;
import javax.swing.text.JTextComponent;
import org.fest.swing.fixture.JCheckBoxFixture;
import org.jetbrains.annotations.NotNull;
@SuppressWarnings({"UnusedReturnValue", "unused"})
public class FlutterSettingsStepFixture<W extends AbstractWizardFixture>
extends AbstractWizardStepFixture<FlutterSettingsStepFixture, W> {
protected FlutterSettingsStepFixture(@NotNull W wizard, @NotNull JRootPane target) {
super(FlutterSettingsStepFixture.class, wizard, target);
}
@NotNull
public FlutterSettingsStepFixture enterPackageName(@NotNull String text) {
JTextComponent textField = findTextFieldWithLabel("Package name");
replaceText(textField, text);
return this;
}
public String getPackageName() {
return findTextFieldWithLabel("Package name").getText();
}
public JCheckBoxFixture getKotlinFixture() {
return findCheckBoxWithText(FlutterBundle.message("module.wizard.language.name_kotlin"));
}
public JCheckBoxFixture getSwiftFixture() {
return findCheckBoxWithText(FlutterBundle.message("module.wizard.language.name_swift"));
}
@NotNull
public FlutterSettingsStepFixture setKotlinSupport(boolean select) {
selectCheckBoxWithText(FlutterBundle.message("module.wizard.language.name_kotlin"), select);
return this;
}
@NotNull
public FlutterSettingsStepFixture setSwiftSupport(boolean select) {
selectCheckBoxWithText(FlutterBundle.message("module.wizard.language.name_swift"), select);
return this;
}
protected JCheckBoxFixture findCheckBoxWithText(@NotNull String text) {
JCheckBox cb =
(JCheckBox)robot().finder().find((c) -> c instanceof JCheckBox && c.isShowing() && ((JCheckBox)c).getText().equals(text));
return new JCheckBoxFixture(robot(), cb);
}
@Override
@NotNull
protected JCheckBoxFixture selectCheckBoxWithText(@NotNull String text, boolean select) {
JCheckBoxFixture checkBox = findCheckBoxWithText(text);
if (select) {
checkBox.select();
}
else {
checkBox.deselect();
}
return checkBox;
}
}
| flutter-intellij/flutter-studio/testSrc/com/android/tools/idea/tests/gui/framework/fixture/newProjectWizard/FlutterSettingsStepFixture.java/0 | {
"file_path": "flutter-intellij/flutter-studio/testSrc/com/android/tools/idea/tests/gui/framework/fixture/newProjectWizard/FlutterSettingsStepFixture.java",
"repo_id": "flutter-intellij",
"token_count": 862
} | 522 |
# Location of the bash script.
build_file: "flutter-intellij-kokoro/kokoro/macos_external/kokoro_release.sh"
action {
define_artifacts {
regex: "github/flutter-intellij-kokoro/releases/release_dev/**"
strip_prefix: "github/flutter-intellij-kokoro/releases"
}
}
before_action {
fetch_keystore {
keystore_resource {
keystore_config_id: 74840
keyname: "flutter-intellij-plugin-auth-token"
}
keystore_resource {
keystore_config_id: 74840
keyname: "flutter-intellij-plugin-jxbrowser-license-key"
}
}
}
| flutter-intellij/kokoro/macos_external/release.cfg/0 | {
"file_path": "flutter-intellij/kokoro/macos_external/release.cfg",
"repo_id": "flutter-intellij",
"token_count": 233
} | 523 |
# Generated file - do not edit.
# suppress inspection "UnusedProperty" for whole file
aliceBlue=fff0f8ff
antiqueWhite=fffaebd7
aqua=ff00ffff
aquamarine=ff7fffd4
azure=fff0ffff
beige=fff5f5dc
bisque=ffffe4c4
black=ff000000
blanchedAlmond=ffffebcd
blue=ff0000ff
blueViolet=ff8a2be2
brown=ffa52a2a
burlyWood=ffdeb887
cadetBlue=ff5f9ea0
chartreuse=ff7fff00
chocolate=ffd2691e
coral=ffff7f50
cornflowerBlue=ff6495ed
cornsilk=fffff8dc
crimson=ffdc143c
cyan=ff00ffff
darkBlue=ff00008b
darkCyan=ff008b8b
darkGoldenRod=ffb8860b
darkGray=ffa9a9a9
darkGreen=ff006400
darkGrey=ffa9a9a9
darkKhaki=ffbdb76b
darkMagenta=ff8b008b
darkOliveGreen=ff556b2f
darkOrange=ffff8c00
darkOrchid=ff9932cc
darkRed=ff8b0000
darkSalmon=ffe9967a
darkSeaGreen=ff8fbc8f
darkSlateBlue=ff483d8b
darkSlateGray=ff2f4f4f
darkSlateGrey=ff2f4f4f
darkTurquoise=ff00ced1
darkViolet=ff9400d3
deepPink=ffff1493
deepSkyBlue=ff00bfff
dimGray=ff696969
dimGrey=ff696969
dodgerBlue=ff1e90ff
fireBrick=ffb22222
floralWhite=fffffaf0
forestGreen=ff228b22
fuchsia=ffff00ff
gainsboro=ffdcdcdc
ghostWhite=fff8f8ff
gold=ffffd700
goldenRod=ffdaa520
gray=ff808080
green=ff008000
greenYellow=ffadff2f
grey=ff808080
honeyDew=fff0fff0
hotPink=ffff69b4
indianRed=ffcd5c5c
indigo=ff4b0082
ivory=fffffff0
khaki=fff0e68c
lavender=ffe6e6fa
lavenderBlush=fffff0f5
lawnGreen=ff7cfc00
lemonChiffon=fffffacd
lightBlue=ffadd8e6
lightCoral=fff08080
lightCyan=ffe0ffff
lightGoldenRodYellow=fffafad2
lightGray=ffd3d3d3
lightGreen=ff90ee90
lightGrey=ffd3d3d3
lightPink=ffffb6c1
lightSalmon=ffffa07a
lightSeaGreen=ff20b2aa
lightSkyBlue=ff87cefa
lightSlateGray=ff778899
lightSlateGrey=ff778899
lightSteelBlue=ffb0c4de
lightYellow=ffffffe0
lime=ff00ff00
limeGreen=ff32cd32
linen=fffaf0e6
magenta=ffff00ff
maroon=ff800000
mediumAquaMarine=ff66cdaa
mediumBlue=ff0000cd
mediumOrchid=ffba55d3
mediumPurple=ff9370db
mediumSeaGreen=ff3cb371
mediumSlateBlue=ff7b68ee
mediumSpringGreen=ff00fa9a
mediumTurquoise=ff48d1cc
mediumVioletRed=ffc71585
midnightBlue=ff191970
mintCream=fff5fffa
mistyRose=ffffe4e1
moccasin=ffffe4b5
navajoWhite=ffffdead
navy=ff000080
oldLace=fffdf5e6
olive=ff808000
oliveDrab=ff6b8e23
orange=ffffa500
orangeRed=ffff4500
orchid=ffda70d6
paleGoldenRod=ffeee8aa
paleGreen=ff98fb98
paleTurquoise=ffafeeee
paleVioletRed=ffdb7093
papayaWhip=ffffefd5
peachPuff=ffffdab9
peru=ffcd853f
pink=ffffc0cb
plum=ffdda0dd
powderBlue=ffb0e0e6
purple=ff800080
rebeccaPurple=ff663399
red=ffff0000
rosyBrown=ffbc8f8f
royalBlue=ff4169e1
saddleBrown=ff8b4513
salmon=fffa8072
sandyBrown=fff4a460
seaGreen=ff2e8b57
seaShell=fffff5ee
sienna=ffa0522d
silver=ffc0c0c0
skyBlue=ff87ceeb
slateBlue=ff6a5acd
slateGray=ff708090
slateGrey=ff708090
snow=fffffafa
springGreen=ff00ff7f
steelBlue=ff4682b4
tan=ffd2b48c
teal=ff008080
thistle=ffd8bfd8
tomato=ffff6347
turquoise=ff40e0d0
violet=ffee82ee
wheat=fff5deb3
white=ffffffff
whiteSmoke=fff5f5f5
yellow=ffffff00
yellowGreen=ff9acd32
| flutter-intellij/resources/flutter/colors/css.properties/0 | {
"file_path": "flutter-intellij/resources/flutter/colors/css.properties",
"repo_id": "flutter-intellij",
"token_count": 1359
} | 524 |
/*
* Copyright 2020 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
pluginManagement {
repositories {
maven("https://oss.sonatype.org/content/repositories/snapshots/")
gradlePluginPortal()
}
}
val ide: String by settings
include("flutter-idea")
if ("$ide" == "android-studio") {
include("flutter-studio")
}
| flutter-intellij/settings.gradle.kts/0 | {
"file_path": "flutter-intellij/settings.gradle.kts",
"repo_id": "flutter-intellij",
"token_count": 141
} | 525 |
rem @echo off
set DART_VERSION=2.7.1
set ANT_VERSION=1.10.7
echo "install dart"
md ..\dart
cd ..\dart
curl https://storage.googleapis.com/dart-archive/channels/stable/release/%DART_VERSION%/sdk/dartsdk-windows-ia32-release.zip > dart.zip
unzip -q dart.zip
REM "%~dp0" is the directory of this file including trailing backslash
cd %~dp0..\..
set PATH=%PATH%;%~dp0..\..\..\dart\dart-sdk\bin
dart --version || goto :error
java -version
echo "JAVA_HOME=%JAVA_HOME%"
echo "install ant"
md ..\ant
cd ..\ant
curl https://www-us.apache.org/dist/ant/binaries/apache-ant-%ANT_VERSION%-bin.zip > ant.zip
unzip -q ant.zip
cd %~dp0..\..
set PATH=%PATH%;%~dp0..\..\..ant\apache-ant-1.10.7\bin
rem ant -version
set FLUTTER_KEYSTORE_ID=74840
set FLUTTER_KEYSTORE_NAME=flutter-intellij-plugin-auth-token
cd tool\plugin
rem dir /s/o ..\..\..
echo "dart pub get"
cmd /c "dart pub get --no-precompile"
cd ..\..
dart tool\plugin\bin\main.dart test > test.log || goto :error
type test.log
:; exit 0
exit /b 0
:error
exit /b %errorlevel% | flutter-intellij/tool/kokoro/test.bat/0 | {
"file_path": "flutter-intellij/tool/kokoro/test.bat",
"repo_id": "flutter-intellij",
"token_count": 433
} | 526 |
// 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:plugin_tool/plugin.dart';
import 'package:plugin_tool/runner.dart';
import 'package:plugin_tool/util.dart';
import 'package:test/test.dart';
void main() {
group("create", () {
test('build', () {
expect(AntBuildCommand(BuildCommandRunner()).name, "build");
});
test('make', () {
expect(GradleBuildCommand(BuildCommandRunner()).name, "make");
});
test('test', () {
expect(TestCommand(BuildCommandRunner()).name, "test");
});
test('deploy', () {
expect(DeployCommand(BuildCommandRunner()).name, "deploy");
});
test('generate', () {
expect(GenerateCommand(BuildCommandRunner()).name, "generate");
});
});
group("spec", () {
test('build', () async {
var runner = makeTestRunner();
await runner.run(["-r=19", "-d../..", "build"]).whenComplete(() {
var specs = (runner.commands['build'] as ProductCommand).specs;
expect(specs, isNotNull);
expect(
specs.map((spec) => spec.ideaProduct).toList(),
orderedEquals([
'android-studio',
'android-studio'
]));
});
});
test('test', () async {
var runner = makeTestRunner();
await runner.run(["-r=19", "-d../..", "test"]).whenComplete(() {
var specs = (runner.commands['test'] as ProductCommand).specs;
expect(specs, isNotNull);
expect(
specs.map((spec) => spec.ideaProduct).toList(),
orderedEquals([
'android-studio',
'android-studio'
]));
});
});
test('deploy', () async {
var runner = makeTestRunner();
await runner.run(["-r19", "-d../..", "deploy"]).whenComplete(() {
var specs = (runner.commands['deploy'] as ProductCommand).specs;
expect(specs, isNotNull);
expect(
specs.map((spec) => spec.ideaProduct).toList(),
orderedEquals([
'android-studio',
'android-studio'
]));
});
});
});
group('release', () {
test('simple', () async {
var runner = makeTestRunner();
late TestDeployCommand cmd;
await runner.run(["-r19", "-d../..", "deploy"]).whenComplete(() {
cmd = (runner.commands['deploy'] as TestDeployCommand);
});
expect(cmd.isReleaseValid, true);
});
test('minor', () async {
var runner = makeTestRunner();
late TestDeployCommand cmd;
await runner.run(["-r19.2", "-d../..", "deploy"]).whenComplete(() {
cmd = (runner.commands['deploy'] as TestDeployCommand);
});
expect(cmd.isReleaseValid, true);
});
test('patch invalid', () async {
var runner = makeTestRunner();
late TestDeployCommand cmd;
await runner.run(["-r19.2.1", "-d../..", "deploy"]).whenComplete(() {
cmd = (runner.commands['deploy'] as TestDeployCommand);
});
expect(cmd.isReleaseValid, false);
});
test('non-numeric', () async {
var runner = makeTestRunner();
late TestDeployCommand cmd;
await runner.run(["-rx19.2", "-d../..", "deploy"]).whenComplete(() {
cmd = (runner.commands['deploy'] as TestDeployCommand);
});
expect(cmd.isReleaseValid, false);
});
});
group('deploy', () {
test('clean', () async {
var dir = Directory.current;
var runner = makeTestRunner();
await runner.run([
"-r=19",
"-d../..",
"deploy",
"--no-as",
"--no-ij"
]).whenComplete(() {
expect(Directory.current.path, equals(dir.path));
});
});
test('without --release', () async {
var runner = makeTestRunner();
late TestDeployCommand cmd;
await runner.run(["-d../..", "deploy"]).whenComplete(() {
cmd = (runner.commands['deploy'] as TestDeployCommand);
});
expect(cmd.paths, orderedEquals([]));
});
test('release paths', () async {
var runner = makeTestRunner();
late TestDeployCommand cmd;
await runner.run(["--release=19", "-d../..", "deploy"]).whenComplete(() {
cmd = (runner.commands['deploy'] as TestDeployCommand);
});
var specs = cmd.specs.where((s) => s.isStableChannel).toList();
expect(cmd.paths.length, specs.length);
});
});
group('build', () {
test('plugin.xml', () async {
var runner = makeTestRunner();
late TestBuildCommand cmd;
await runner.run(["-d../..", "build"]).whenComplete(() {
cmd = (runner.commands['build'] as TestBuildCommand);
});
var spec = cmd.specs[0];
await removeAll('../../build/classes');
await genPluginFiles(spec, 'build/classes');
var file = File("../../build/classes/META-INF/plugin.xml");
expect(file.existsSync(), isTrue);
var content = file.readAsStringSync();
expect(content.length, greaterThan(10000));
var loc = content.indexOf('@');
expect(loc, -1);
});
test('only-version', () async {
ProductCommand command =
makeTestRunner().commands['build'] as ProductCommand;
var results = command.argParser.parse(['--only-version=2023.1']);
expect(results['only-version'], '2023.1');
});
});
group('ProductCommand', () {
test('parses release', () async {
var runner = makeTestRunner();
late ProductCommand command;
await runner.run(["-d../..", '-r22.0', "build"]).whenComplete(() {
command = (runner.commands['build'] as ProductCommand);
});
expect(command.release, '22.0');
});
test('parses release partial number', () async {
var runner = makeTestRunner();
late ProductCommand command;
await runner.run(["-d../..", '-r22', "build"]).whenComplete(() {
command = (runner.commands['build'] as ProductCommand);
});
expect(command.release, '22.0');
});
test('isReleaseValid', () async {
var runner = makeTestRunner();
late ProductCommand command;
await runner.run(["-d../..", '-r22.0', "build"]).whenComplete(() {
command = (runner.commands['build'] as ProductCommand);
});
expect(command.isReleaseValid, true);
});
test('isReleaseValid partial version', () async {
var runner = makeTestRunner();
late ProductCommand command;
await runner.run(["-d../..", '-r22', "build"]).whenComplete(() {
command = (runner.commands['build'] as ProductCommand);
});
expect(command.isReleaseValid, true);
});
test('isReleaseValid bad version', () async {
var runner = makeTestRunner();
late ProductCommand command;
await runner.run(["-d../..", '-r22.0.0', "build"]).whenComplete(() {
command = (runner.commands['build'] as ProductCommand);
});
expect(command.isReleaseValid, false);
});
});
}
BuildCommandRunner makeTestRunner() {
var runner = BuildCommandRunner();
runner.addCommand(TestBuildCommand(runner));
runner.addCommand(TestMakeCommand(runner));
runner.addCommand(TestTestCommand(runner));
runner.addCommand(TestDeployCommand(runner));
runner.addCommand(TestGenCommand(runner));
return runner;
}
class TestBuildCommand extends AntBuildCommand {
TestBuildCommand(super.runner);
@override
bool get isTesting => true;
@override
Future<int> doit() async => Future(() => 0);
}
class TestMakeCommand extends GradleBuildCommand {
TestMakeCommand(super.runner);
@override
bool get isTesting => true;
@override
Future<int> doit() async => Future(() => 0);
}
class TestDeployCommand extends DeployCommand {
List<String> paths = <String>[];
List<String> plugins = <String>[];
TestDeployCommand(super.runner);
@override
bool get isTesting => true;
String readTokenFile() {
return "token";
}
@override
void changeDirectory(Directory dir) {}
@override
Future<int> upload(
String filePath, String pluginNumber, String token, String channel) {
paths.add(filePath);
plugins.add(pluginNumber);
return Future(() => 0);
}
}
class TestGenCommand extends GenerateCommand {
TestGenCommand(super.runner);
@override
bool get isTesting => true;
@override
Future<int> doit() async => Future(() => 0);
}
class TestTestCommand extends TestCommand {
TestTestCommand(super.runner);
@override
bool get isTesting => true;
@override
Future<int> doit() async => Future(() => 0);
}
| flutter-intellij/tool/plugin/test/plugin_test.dart/0 | {
"file_path": "flutter-intellij/tool/plugin/test/plugin_test.dart",
"repo_id": "flutter-intellij",
"token_count": 3410
} | 527 |
#!/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.
# ---------------------------------- NOTE ---------------------------------- #
#
# Please keep the logic in this file consistent with the logic in the
# `dart.bat` script in the same directory to ensure that Flutter & Dart continue
# to work across all platforms!
#
# -------------------------------------------------------------------------- #
set -e
# Needed because if it is set, cd may print the path it changed to.
unset CDPATH
# On Mac OS, readlink -f doesn't work, so follow_links traverses the path one
# link at a time, and then cds into the link destination and find out where it
# ends up.
#
# The returned filesystem path must be a format usable by Dart's URI parser,
# since the Dart command line tool treats its argument as a file URI, not a
# filename. For instance, multiple consecutive slashes should be reduced to a
# single slash, since double-slashes indicate a URI "authority", and these are
# supposed to be filenames. There is an edge case where this will return
# multiple slashes: when the input resolves to the root directory. However, if
# that were the case, we wouldn't be running this shell, so we don't do anything
# about it.
#
# The function is enclosed in a subshell to avoid changing the working directory
# of the caller.
function follow_links() (
cd -P "$(dirname -- "$1")"
file="$PWD/$(basename -- "$1")"
while [[ -h "$file" ]]; do
cd -P "$(dirname -- "$file")"
file="$(readlink -- "$file")"
cd -P "$(dirname -- "$file")"
file="$PWD/$(basename -- "$file")"
done
echo "$file"
)
PROG_NAME="$(follow_links "${BASH_SOURCE[0]}")"
BIN_DIR="$(cd "${PROG_NAME%/*}" ; pwd -P)"
SHARED_NAME="$BIN_DIR/internal/shared.sh"
OS="$(uname -s)"
# If we're on Windows, invoke the batch script instead to get proper locking.
if [[ $OS =~ MINGW.* || $OS =~ CYGWIN.* || $OS =~ MSYS.* ]]; then
exec "${BIN_DIR}/dart.bat" "$@"
fi
# To define `shared::execute()` function
source "$SHARED_NAME"
shared::execute "$@"
| flutter/bin/dart/0 | {
"file_path": "flutter/bin/dart",
"repo_id": "flutter",
"token_count": 652
} | 528 |
8fb14f99a8854d4e2b16559c0eb48e7c297065ce
| flutter/bin/internal/libzip.version/0 | {
"file_path": "flutter/bin/internal/libzip.version",
"repo_id": "flutter",
"token_count": 27
} | 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 'use_cases.dart';
class NavigationBarUseCase extends UseCase {
@override
String get name => 'NavigationBar';
@override
String get route => '/navigation-bar';
@override
Widget build(BuildContext context) => const MainWidget();
}
class MainWidget extends StatefulWidget {
const MainWidget({super.key});
@override
State<MainWidget> createState() => MainWidgetState();
}
class MainWidgetState extends State<MainWidget> {
int currentPageIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: const Text('NavigationBar'),
),
bottomNavigationBar: NavigationBar(
onDestinationSelected: (int index) {
setState(() {
currentPageIndex = index;
});
},
indicatorColor: Colors.amber[800],
selectedIndex: currentPageIndex,
destinations: const <Widget>[
NavigationDestination(
selectedIcon: Icon(Icons.home),
icon: Icon(Icons.home_outlined),
label: 'Home',
),
NavigationDestination(
icon: Icon(Icons.business),
label: 'Business',
),
NavigationDestination(
selectedIcon: Icon(Icons.school),
icon: Icon(Icons.school_outlined),
label: 'School',
),
],
),
body: <Widget>[
Container(
alignment: Alignment.center,
child: const Text('Page 1'),
),
Container(
alignment: Alignment.center,
child: const Text('Page 2'),
),
Container(
alignment: Alignment.center,
child: const Text('Page 3'),
),
][currentPageIndex],
);
}
}
| flutter/dev/a11y_assessments/lib/use_cases/navigation_bar.dart/0 | {
"file_path": "flutter/dev/a11y_assessments/lib/use_cases/navigation_bar.dart",
"repo_id": "flutter",
"token_count": 863
} | 530 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| flutter/dev/a11y_assessments/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "flutter/dev/a11y_assessments/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "flutter",
"token_count": 32
} | 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:a11y_assessments/use_cases/navigation_bar.dart';
import 'package:flutter_test/flutter_test.dart';
import 'test_utils.dart';
void main() {
testWidgets('navigation bar can run', (WidgetTester tester) async {
await pumpsUseCase(tester, NavigationBarUseCase());
expect(find.text('Page 1'), findsOneWidget);
await tester.tap(find.text('Business'));
await tester.pumpAndSettle();
expect(find.text('Page 2'), findsOneWidget);
await tester.tap(find.text('School'));
await tester.pumpAndSettle();
expect(find.text('Page 3'), findsOneWidget);
});
}
| flutter/dev/a11y_assessments/test/navigation_bar_test.dart/0 | {
"file_path": "flutter/dev/a11y_assessments/test/navigation_bar_test.dart",
"repo_id": "flutter",
"token_count": 259
} | 532 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
class ColorFilterWithUnstableChildPage extends StatefulWidget {
const ColorFilterWithUnstableChildPage({super.key});
@override
State<StatefulWidget> createState() => _ColorFilterWithUnstableChildPageState();
}
class _ColorFilterWithUnstableChildPageState extends State<ColorFilterWithUnstableChildPage> with SingleTickerProviderStateMixin {
late Animation<double> _offsetY;
late AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(vsync: this, duration: const Duration(seconds: 2));
_offsetY = Tween<double>(begin: 0, end: -1000.0).animate(_controller);
_controller.repeat();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _offsetY,
builder: (BuildContext context, Widget? child) {
return Stack(children: List<Widget>.generate(50, (int i) => Positioned(
left: 0,
top: (200 * i).toDouble() + _offsetY.value,
child: ColorFiltered(
colorFilter: ColorFilter.mode(Colors.green[300]!, BlendMode.luminosity),
child: RepaintBoundary(
child: Container(
// Slightly change width to invalidate raster cache.
width: 1000 - (_offsetY.value / 100),
height: 100, color: Colors.red,
),
),
),
)));
}
);
}
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/color_filter_with_unstable_child.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/color_filter_with_unstable_child.dart",
"repo_id": "flutter",
"token_count": 664
} | 533 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
class PictureCachePage extends StatelessWidget {
const PictureCachePage({super.key});
static const List<String> kTabNames = <String>['1', '2', '3', '4', '5'];
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: kTabNames.length, // This is the number of tabs.
child: Scaffold(
appBar: AppBar(
title: const Text('Picture Cache'),
// pinned: true,
// expandedHeight: 50.0,
// forceElevated: innerBoxIsScrolled,
bottom: TabBar(
tabs: kTabNames.map((String name) => Tab(text: name)).toList(),
),
),
body: TabBarView(
key: const Key('tabbar_view'), // this key is used by the driver test
children: kTabNames.map((String name) {
return SafeArea(
top: false,
bottom: false,
child: Builder(
builder: (BuildContext context) {
return ListView.builder(
itemBuilder: (BuildContext context, int index) => ListItem(index: index),
);
},
),
);
}).toList(),
),
),
);
}
}
class ListItem extends StatelessWidget {
const ListItem({super.key, required this.index});
final int index;
static const String kMockChineseTitle = '复杂的中文标题?复杂的中文标题!';
static const String kMockName = '李耳123456';
static const int kMockCount = 999;
@override
Widget build(BuildContext context) {
final List<Widget> contents = <Widget>[
const SizedBox(
height: 15,
),
_buildUserInfo(),
const SizedBox(
height: 10,
),
];
if (index % 3 != 0) {
contents.add(_buildImageContent());
} else {
contents.addAll(<Widget>[
Padding(
padding: const EdgeInsets.only(left: 40, right: 15),
child: _buildContentText(),
),
const SizedBox(
height: 10,
),
Padding(
padding: const EdgeInsets.only(left: 40, right: 15),
child: _buildBottomRow(),
),
]);
}
contents.addAll(<Widget>[
const SizedBox(
height: 13,
),
buildDivider(0.5, const EdgeInsets.only(left: 40, right: 15)),
]);
return MaterialButton(
onPressed: () {},
padding: EdgeInsets.zero,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: contents,
),
);
}
Text _buildRankText() {
return Text(
(index + 1).toString(),
style: TextStyle(
fontSize: 15,
color: index + 1 <= 3 ? const Color(0xFFE5645F) : Colors.black,
fontWeight: FontWeight.bold,
),
);
}
Widget _buildImageContent() {
return Row(
children: <Widget>[
const SizedBox(
width: 40,
),
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 30),
child: _buildContentText(),
),
const SizedBox(
height: 10,
),
_buildBottomRow(),
],
),
),
Image.asset(
index.isEven ? 'food/butternut_squash_soup.png' : 'food/cherry_pie.png',
package: 'flutter_gallery_assets',
fit: BoxFit.cover,
width: 110,
height: 70,
),
const SizedBox(
width: 15,
),
],
);
}
Widget _buildContentText() {
return const Text(
kMockChineseTitle,
style: TextStyle(
fontSize: 16,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
);
}
Widget _buildBottomRow() {
return Row(
children: <Widget>[
Container(
padding: const EdgeInsets.symmetric(
horizontal: 7,
),
height: 16,
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: const Color(0xFFFBEEEE),
),
child: Row(
children: <Widget>[
const SizedBox(
width: 3,
),
Text(
'hot:${_convertCountToStr(kMockCount)}',
style: const TextStyle(
color: Color(0xFFE5645F),
fontSize: 11,
),
),
],
),
),
const SizedBox(
width: 9,
),
const Text(
'ans:$kMockCount',
style: TextStyle(
color: Color(0xFF999999),
fontSize: 11,
),
),
const SizedBox(
width: 9,
),
const Text(
'like:$kMockCount',
style: TextStyle(
color: Color(0xFF999999),
fontSize: 11,
),
),
],
);
}
String _convertCountToStr(int count) {
if (count < 10000) {
return count.toString();
} else if (count < 100000) {
return '${(count / 10000).toStringAsPrecision(2)}w';
} else {
return '${(count / 10000).floor()}w';
}
}
Widget _buildUserInfo() {
return GestureDetector(
onTap: () {},
child: Row(
children: <Widget>[
Container(
width: 40, alignment: Alignment.center, child: _buildRankText()),
const CircleAvatar(
radius: 11.5,
),
const SizedBox(
width: 6,
),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 250),
child: const Text(
kMockName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(
width: 4,
),
const SizedBox(
width: 15,
),
],
),
);
}
Widget buildDivider(double height, EdgeInsets padding) {
return Container(
padding: padding,
height: height,
color: const Color(0xFFF5F5F5),
);
}
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/picture_cache.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/picture_cache.dart",
"repo_id": "flutter",
"token_count": 3478
} | 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/foundation.dart';
import 'recorder.dart';
/// Benchmarks the performance of the [defaultTargetPlatform] getter.
///
/// The getter relies on the expensive `window.matchMedia` and if not properly
/// cached can cause performance issues.
class BenchDefaultTargetPlatform extends RawRecorder {
BenchDefaultTargetPlatform() : super(name: benchmarkName);
static const String benchmarkName = 'default_target_platform';
/// A dummy counter just to make sure the compiler doesn't inline the
/// benchmark and make it a no-op.
int counter = 0;
@override
void body(Profile profile) {
profile.record('runtime', () {
for (int i = 0; i < 10000; i++) {
counter += defaultTargetPlatform.index;
}
}, reported: true);
}
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_default_target_platform.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_default_target_platform.dart",
"repo_id": "flutter",
"token_count": 270
} | 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 'dart:math';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'recorder.dart';
const String chars = '1234567890'
'abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'!@#%^&()[]{}<>,./?;:"`~-_=+|';
String _randomize(String text) {
return text.replaceAllMapped(
'*',
// Passing a seed so the results are reproducible.
(_) => chars[Random(0).nextInt(chars.length)],
);
}
class ParagraphGenerator {
int _counter = 0;
/// Randomizes the given [text] and creates a paragraph with a unique
/// font-size so that the engine doesn't reuse a cached ruler.
ui.Paragraph generate(
String text, {
int? maxLines,
bool hasEllipsis = false,
}) {
final ui.ParagraphBuilder builder = ui.ParagraphBuilder(ui.ParagraphStyle(
fontFamily: 'sans-serif',
maxLines: maxLines,
ellipsis: hasEllipsis ? '...' : null,
))
// Start from a font-size of 8.0 and go up by 0.01 each time.
..pushStyle(ui.TextStyle(fontSize: 8.0 + _counter * 0.01))
..addText(_randomize(text));
_counter++;
return builder.build();
}
}
/// Which mode to run [BenchBuildColorsGrid] in.
enum _TestMode {
/// Uses the HTML rendering backend with the canvas 2D text layout.
useCanvasTextLayout,
/// Uses CanvasKit for everything.
useCanvasKit,
}
/// Repeatedly lays out a paragraph.
///
/// Creates a different paragraph each time in order to avoid hitting the cache.
class BenchTextLayout extends RawRecorder {
BenchTextLayout.canvas()
: super(name: canvasBenchmarkName);
BenchTextLayout.canvasKit()
: super(name: canvasKitBenchmarkName);
static const String canvasBenchmarkName = 'text_canvas_layout';
static const String canvasKitBenchmarkName = 'text_canvaskit_layout';
final ParagraphGenerator generator = ParagraphGenerator();
static const String singleLineText = '*** ** ****';
static const String multiLineText = '*** ****** **** *** ******** * *** '
'******* **** ********** *** ******* '
'**** ***** *** ******** *** ********* '
'** * *** ******* ***********';
@override
void body(Profile profile) {
recordParagraphOperations(
profile: profile,
paragraph: generator.generate(singleLineText),
text: singleLineText,
keyPrefix: 'single_line',
maxWidth: 800.0,
);
recordParagraphOperations(
profile: profile,
paragraph: generator.generate(multiLineText),
text: multiLineText,
keyPrefix: 'multi_line',
maxWidth: 200.0,
);
recordParagraphOperations(
profile: profile,
paragraph: generator.generate(multiLineText, maxLines: 2),
text: multiLineText,
keyPrefix: 'max_lines',
maxWidth: 200.0,
);
recordParagraphOperations(
profile: profile,
paragraph: generator.generate(multiLineText, hasEllipsis: true),
text: multiLineText,
keyPrefix: 'ellipsis',
maxWidth: 200.0,
);
}
void recordParagraphOperations({
required Profile profile,
required ui.Paragraph paragraph,
required String text,
required String keyPrefix,
required double maxWidth,
}) {
profile.record('$keyPrefix.layout', () {
paragraph.layout(ui.ParagraphConstraints(width: maxWidth));
}, reported: true);
profile.record('$keyPrefix.getBoxesForRange', () {
for (int start = 0; start < text.length; start += 3) {
for (int end = start + 1; end < text.length; end *= 2) {
paragraph.getBoxesForRange(start, end);
}
}
}, reported: true);
profile.record('$keyPrefix.getPositionForOffset', () {
for (double dx = 0.0; dx < paragraph.width; dx += 10.0) {
for (double dy = 0.0; dy < paragraph.height; dy += 10.0) {
paragraph.getPositionForOffset(Offset(dx, dy));
}
}
}, reported: true);
}
}
/// Repeatedly lays out the same paragraph.
///
/// Uses the same paragraph content to make sure we hit the cache. It doesn't
/// use the same paragraph instance because the layout method will shortcircuit
/// in that case.
class BenchTextCachedLayout extends RawRecorder {
BenchTextCachedLayout.canvas()
: super(name: canvasBenchmarkName);
BenchTextCachedLayout.canvasKit()
: super(name: canvasKitBenchmarkName);
static const String canvasBenchmarkName = 'text_canvas_cached_layout';
static const String canvasKitBenchmarkName = 'text_canvas_kit_cached_layout';
@override
void body(Profile profile) {
final ui.ParagraphBuilder builder = ui.ParagraphBuilder(ui.ParagraphStyle(fontFamily: 'sans-serif'))
..pushStyle(ui.TextStyle(fontSize: 12.0))
..addText(
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, '
'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
);
final ui.Paragraph paragraph = builder.build();
profile.record('layout', () {
paragraph.layout(const ui.ParagraphConstraints(width: double.infinity));
}, reported: true);
}
}
/// Global counter incremented every time the benchmark is asked to
/// [createWidget].
///
/// The purpose of this counter is to make sure the rendered paragraphs on each
/// build are unique.
int _counter = 0;
/// Measures how expensive it is to construct a realistic text-heavy piece of UI.
///
/// The benchmark constructs a tabbed view, where each tab displays a list of
/// colors. Each color's description is made of several [Text] nodes.
class BenchBuildColorsGrid extends WidgetBuildRecorder {
BenchBuildColorsGrid.canvas()
: _mode = _TestMode.useCanvasTextLayout, super(name: canvasBenchmarkName);
BenchBuildColorsGrid.canvasKit()
: _mode = _TestMode.useCanvasKit, super(name: canvasKitBenchmarkName);
/// Disables tracing for this benchmark.
///
/// When tracing is enabled, DOM layout takes longer to complete. This has a
/// significant effect on the benchmark since we do a lot of text layout
/// operations that trigger synchronous DOM layout.
@override
bool get isTracingEnabled => false;
static const String canvasBenchmarkName = 'text_canvas_color_grid';
static const String canvasKitBenchmarkName = 'text_canvas_kit_color_grid';
/// Whether to use the new canvas-based text measurement implementation.
final _TestMode _mode;
num _textLayoutMicros = 0;
@override
Future<void> setUpAll() async {
super.setUpAll();
registerEngineBenchmarkValueListener('text_layout', (num value) {
_textLayoutMicros += value;
});
}
@override
Future<void> tearDownAll() async {
stopListeningToEngineBenchmarkValues('text_layout');
}
@override
void frameWillDraw() {
super.frameWillDraw();
_textLayoutMicros = 0;
}
@override
void frameDidDraw() {
// We need to do this before calling [super.frameDidDraw] because the latter
// updates the value of [showWidget] in preparation for the next frame.
// TODO(yjbanov): https://github.com/flutter/flutter/issues/53877
if (showWidget && _mode != _TestMode.useCanvasKit) {
profile!.addDataPoint(
'text_layout',
Duration(microseconds: _textLayoutMicros.toInt()),
reported: true,
);
}
super.frameDidDraw();
}
@override
Widget createWidget() {
_counter++;
return const MaterialApp(home: ColorsDemo());
}
}
// The code below was copied from `colors_demo.dart` in the `flutter_gallery`
// example.
const double kColorItemHeight = 48.0;
class Palette {
Palette({required this.name, required this.primary, this.accent, this.threshold = 900});
final String name;
final MaterialColor primary;
final MaterialAccentColor? accent;
final int
threshold; // titles for indices > threshold are white, otherwise black
}
final List<Palette> allPalettes = <Palette>[
Palette(
name: 'RED',
primary: Colors.red,
accent: Colors.redAccent,
threshold: 300),
Palette(
name: 'PINK',
primary: Colors.pink,
accent: Colors.pinkAccent,
threshold: 200),
Palette(
name: 'PURPLE',
primary: Colors.purple,
accent: Colors.purpleAccent,
threshold: 200),
Palette(
name: 'DEEP PURPLE',
primary: Colors.deepPurple,
accent: Colors.deepPurpleAccent,
threshold: 200),
Palette(
name: 'INDIGO',
primary: Colors.indigo,
accent: Colors.indigoAccent,
threshold: 200),
Palette(
name: 'BLUE',
primary: Colors.blue,
accent: Colors.blueAccent,
threshold: 400),
Palette(
name: 'LIGHT BLUE',
primary: Colors.lightBlue,
accent: Colors.lightBlueAccent,
threshold: 500),
Palette(
name: 'CYAN',
primary: Colors.cyan,
accent: Colors.cyanAccent,
threshold: 600),
Palette(
name: 'TEAL',
primary: Colors.teal,
accent: Colors.tealAccent,
threshold: 400),
Palette(
name: 'GREEN',
primary: Colors.green,
accent: Colors.greenAccent,
threshold: 500),
Palette(
name: 'LIGHT GREEN',
primary: Colors.lightGreen,
accent: Colors.lightGreenAccent,
threshold: 600),
Palette(
name: 'LIME',
primary: Colors.lime,
accent: Colors.limeAccent,
threshold: 800),
Palette(name: 'YELLOW', primary: Colors.yellow, accent: Colors.yellowAccent),
Palette(name: 'AMBER', primary: Colors.amber, accent: Colors.amberAccent),
Palette(
name: 'ORANGE',
primary: Colors.orange,
accent: Colors.orangeAccent,
threshold: 700),
Palette(
name: 'DEEP ORANGE',
primary: Colors.deepOrange,
accent: Colors.deepOrangeAccent,
threshold: 400),
Palette(name: 'BROWN', primary: Colors.brown, threshold: 200),
Palette(name: 'GREY', primary: Colors.grey, threshold: 500),
Palette(name: 'BLUE GREY', primary: Colors.blueGrey, threshold: 500),
];
class ColorItem extends StatelessWidget {
const ColorItem({
super.key,
required this.index,
required this.color,
this.prefix = '',
});
final int index;
final Color color;
final String prefix;
String colorString() =>
"$_counter:#${color.value.toRadixString(16).padLeft(8, '0').toUpperCase()}";
@override
Widget build(BuildContext context) {
return Semantics(
container: true,
child: Container(
height: kColorItemHeight,
padding: const EdgeInsets.symmetric(horizontal: 16.0),
color: color,
child: SafeArea(
top: false,
bottom: false,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('$_counter:$prefix$index'),
Text(colorString()),
],
),
),
),
);
}
}
class PaletteTabView extends StatelessWidget {
const PaletteTabView({
super.key,
required this.colors,
});
final Palette colors;
static const List<int> primaryKeys = <int>[
50,
100,
200,
300,
400,
500,
600,
700,
800,
900,
];
static const List<int> accentKeys = <int>[100, 200, 400, 700];
@override
Widget build(BuildContext context) {
final TextTheme textTheme = Theme.of(context).textTheme;
final TextStyle whiteTextStyle =
textTheme.bodyMedium!.copyWith(color: Colors.white);
final TextStyle blackTextStyle =
textTheme.bodyMedium!.copyWith(color: Colors.black);
return Scrollbar(
child: ListView(
itemExtent: kColorItemHeight,
children: <Widget>[
...primaryKeys.map<Widget>((int index) {
return DefaultTextStyle(
style: index > colors.threshold ? whiteTextStyle : blackTextStyle,
child: ColorItem(index: index, color: colors.primary[index]!),
);
}),
if (colors.accent != null)
...accentKeys.map<Widget>((int index) {
return DefaultTextStyle(
style:
index > colors.threshold ? whiteTextStyle : blackTextStyle,
child: ColorItem(
index: index, color: colors.accent![index]!, prefix: 'A'),
);
}),
],
),
);
}
}
class ColorsDemo extends StatelessWidget {
const ColorsDemo({super.key});
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: allPalettes.length,
child: Scaffold(
appBar: AppBar(
elevation: 0.0,
title: const Text('Colors'),
bottom: TabBar(
isScrollable: true,
tabs: allPalettes
.map<Widget>(
(Palette swatch) => Tab(text: '$_counter:${swatch.name}'))
.toList(),
),
),
body: TabBarView(
children: allPalettes.map<Widget>((Palette colors) {
return PaletteTabView(colors: colors);
}).toList(),
),
),
);
}
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_text_layout.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_text_layout.dart",
"repo_id": "flutter",
"token_count": 5125
} | 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_driver/flutter_driver.dart';
import 'package:macrobenchmarks/common.dart';
import 'util.dart';
void main() {
macroPerfTest(
'tessellation_perf_static',
kPathTessellationRouteName,
pageDelay: const Duration(seconds: 1),
driverOps: (FlutterDriver driver) async {
final SerializableFinder listView = find.byValueKey('list_view');
Future<void> scrollOnce(double offset) async {
await driver.scroll(
listView, 0.0, offset, const Duration(milliseconds: 450));
await Future<void>.delayed(const Duration(milliseconds: 500));
}
for (int i = 0; i < 3; i += 1) {
await scrollOnce(-600.0);
await scrollOnce(-600.0);
await scrollOnce(600.0);
await scrollOnce(600.0);
}
},
);
}
| flutter/dev/benchmarks/macrobenchmarks/test_driver/path_tessellation_static_perf_test.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/test_driver/path_tessellation_static_perf_test.dart",
"repo_id": "flutter",
"token_count": 373
} | 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. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<application android:name="${applicationName}" android:label="microbenchmarks" android:icon="@mipmap/ic_launcher">
<activity android:name="io.flutter.embedding.android.FlutterActivity"
android:launchMode="singleTop"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
| flutter/dev/benchmarks/microbenchmarks/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "flutter/dev/benchmarks/microbenchmarks/android/app/src/main/AndroidManifest.xml",
"repo_id": "flutter",
"token_count": 573
} | 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/services.dart';
import '../common.dart';
const int _kNumIterations = 100000;
void main() {
assert(false,
"Don't run benchmarks in debug mode! Use 'flutter run --release'.");
final BenchmarkResultPrinter printer = BenchmarkResultPrinter();
const StandardMethodCodec codec = StandardMethodCodec();
final Stopwatch watch = Stopwatch();
const String methodName = 'something';
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMethodCall(const MethodCall(methodName));
}
watch.stop();
printer.addResult(
description: 'StandardMethodCodec null',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMethodCodec_null',
);
watch.reset();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMethodCall(const MethodCall(methodName, 12345));
}
watch.stop();
printer.addResult(
description: 'StandardMethodCodec int',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMethodCodec_int',
);
watch.reset();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMethodCall(
const MethodCall(methodName, 'This is a performance test.'));
}
watch.stop();
printer.addResult(
description: 'StandardMethodCodec string',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMethodCodec_string',
);
watch.reset();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMethodCall(const MethodCall(
methodName, <Object>[1234, 'This is a performance test.', 1.25, true]));
}
watch.stop();
printer.addResult(
description: 'StandardMethodCodec heterogenous list',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMethodCodec_heterogenous_list',
);
watch.reset();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMethodCall(const MethodCall(methodName, <String, Object>{
'integer': 1234,
'string': 'This is a performance test.',
'float': 1.25,
'boolean': true,
}));
}
watch.stop();
printer.addResult(
description: 'StandardMethodCodec heterogenous map',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMethodCodec_heterogenous_map',
);
watch.reset();
printer.printToStdout();
}
| flutter/dev/benchmarks/microbenchmarks/lib/foundation/standard_method_codec_bench.dart/0 | {
"file_path": "flutter/dev/benchmarks/microbenchmarks/lib/foundation/standard_method_codec_bench.dart",
"repo_id": "flutter",
"token_count": 960
} | 539 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:stocks/main.dart' as stocks;
import 'package:stocks/stock_data.dart' as stock_data;
import '../common.dart';
const Duration kBenchmarkTime = Duration(seconds: 15);
Future<void> main() async {
assert(false, "Don't run benchmarks in debug mode! Use 'flutter run --release'.");
stock_data.StockData.actuallyFetchData = false;
// We control the framePolicy below to prevent us from scheduling frames in
// the engine, so that the engine does not interfere with our timings.
final LiveTestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized() as LiveTestWidgetsFlutterBinding;
final Stopwatch watch = Stopwatch();
int iterations = 0;
await benchmarkWidgets((WidgetTester tester) async {
stocks.main();
await tester.pump(); // Start startup animation
await tester.pump(const Duration(seconds: 1)); // Complete startup animation
await tester.tapAt(const Offset(20.0, 40.0)); // Open drawer
await tester.pump(); // Start drawer animation
await tester.pump(const Duration(seconds: 1)); // Complete drawer animation
final TestViewConfiguration big = TestViewConfiguration.fromView(
size: const Size(360.0, 640.0),
view: tester.view,
);
final TestViewConfiguration small = TestViewConfiguration.fromView(
size: const Size(355.0, 635.0),
view: tester.view,
);
final RenderView renderView = WidgetsBinding.instance.renderViews.single;
binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.benchmark;
watch.start();
while (watch.elapsed < kBenchmarkTime) {
renderView.configuration = iterations.isEven ? big : small;
await tester.pumpBenchmark(Duration(milliseconds: iterations * 16));
iterations += 1;
}
watch.stop();
});
final BenchmarkResultPrinter printer = BenchmarkResultPrinter();
printer.addResult(
description: 'Stock layout',
value: watch.elapsedMicroseconds / iterations,
unit: 'µs per iteration',
name: 'stock_layout_iteration',
);
printer.printToStdout();
}
| flutter/dev/benchmarks/microbenchmarks/lib/stocks/layout_bench.dart/0 | {
"file_path": "flutter/dev/benchmarks/microbenchmarks/lib/stocks/layout_bench.dart",
"repo_id": "flutter",
"token_count": 752
} | 540 |
<!-- Copyright 2014 The Flutter Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file. -->
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.MultipleFlutters" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources> | flutter/dev/benchmarks/multiple_flutters/android/app/src/main/res/values/themes.xml/0 | {
"file_path": "flutter/dev/benchmarks/multiple_flutters/android/app/src/main/res/values/themes.xml",
"repo_id": "flutter",
"token_count": 358
} | 541 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/foundation.dart' show kDebugMode;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:microbenchmarks/common.dart';
List<Object?> _makeTestBuffer(int size) {
final List<Object?> answer = <Object?>[];
for (int i = 0; i < size; ++i) {
switch (i % 9) {
case 0:
answer.add(1);
case 1:
answer.add(math.pow(2, 65));
case 2:
answer.add(1234.0);
case 3:
answer.add(null);
case 4:
answer.add(<int>[1234]);
case 5:
answer.add(<String, int>{'hello': 1234});
case 6:
answer.add('this is a test');
case 7:
answer.add(true);
case 8:
answer.add(Uint8List(64));
}
}
return answer;
}
Future<double> _runBasicStandardSmall(
BasicMessageChannel<Object?> basicStandard,
int count,
) async {
final Stopwatch watch = Stopwatch();
watch.start();
for (int i = 0; i < count; ++i) {
await basicStandard.send(1234);
}
watch.stop();
return watch.elapsedMicroseconds / count;
}
class _Counter {
int count = 0;
}
void _runBasicStandardParallelRecurse(
BasicMessageChannel<Object?> basicStandard,
_Counter counter,
int count,
Completer<int> completer,
Object? payload,
) {
counter.count += 1;
if (counter.count == count) {
completer.complete(counter.count);
} else if (counter.count < count) {
basicStandard.send(payload).then((Object? result) {
_runBasicStandardParallelRecurse(
basicStandard, counter, count, completer, payload);
});
}
}
Future<double> _runBasicStandardParallel(
BasicMessageChannel<Object?> basicStandard,
int count,
Object? payload,
int parallel,
) async {
final Stopwatch watch = Stopwatch();
final Completer<int> completer = Completer<int>();
final _Counter counter = _Counter();
watch.start();
for (int i = 0; i < parallel; ++i) {
basicStandard.send(payload).then((Object? result) {
_runBasicStandardParallelRecurse(
basicStandard, counter, count, completer, payload);
});
}
await completer.future;
watch.stop();
return watch.elapsedMicroseconds / count;
}
Future<double> _runBasicStandardLarge(
BasicMessageChannel<Object?> basicStandard,
List<Object?> largeBuffer,
int count,
) async {
int size = 0;
final Stopwatch watch = Stopwatch();
watch.start();
for (int i = 0; i < count; ++i) {
final List<Object?>? result =
await basicStandard.send(largeBuffer) as List<Object?>?;
// This check should be tiny compared to the actual channel send/receive.
size += (result == null) ? 0 : result.length;
}
watch.stop();
if (size != largeBuffer.length * count) {
throw Exception(
"There is an error with the echo channel, the results don't add up: $size",
);
}
return watch.elapsedMicroseconds / count;
}
Future<double> _runBasicBinary(
BasicMessageChannel<ByteData> basicBinary,
ByteData buffer,
int count,
) async {
int size = 0;
final Stopwatch watch = Stopwatch();
watch.start();
for (int i = 0; i < count; ++i) {
final ByteData? result = await basicBinary.send(buffer);
// This check should be tiny compared to the actual channel send/receive.
size += (result == null) ? 0 : result.lengthInBytes;
}
watch.stop();
if (size != buffer.lengthInBytes * count) {
throw Exception(
"There is an error with the echo channel, the results don't add up: $size",
);
}
return watch.elapsedMicroseconds / count;
}
Future<void> _runTest({
required Future<double> Function(int) test,
required BasicMessageChannel<Object?> resetChannel,
required BenchmarkResultPrinter printer,
required String description,
required String name,
required int numMessages,
}) async {
print('running $name');
resetChannel.send(true);
// Prime test.
await test(1);
printer.addResult(
description: description,
value: await test(numMessages),
unit: 'µs',
name: name,
);
}
Future<void> _runTests() async {
if (kDebugMode) {
throw Exception(
"Must be run in profile mode! Use 'flutter run --profile'.",
);
}
const BasicMessageChannel<Object?> resetChannel =
BasicMessageChannel<Object?>(
'dev.flutter.echo.reset',
StandardMessageCodec(),
);
const BasicMessageChannel<Object?> basicStandard =
BasicMessageChannel<Object?>(
'dev.flutter.echo.basic.standard',
StandardMessageCodec(),
);
const BasicMessageChannel<ByteData> basicBinary =
BasicMessageChannel<ByteData>(
'dev.flutter.echo.basic.binary',
BinaryCodec(),
);
/// WARNING: Don't change the following line of code, it will invalidate
/// `Large` tests. Instead make a different test. The size of largeBuffer
/// serialized is 14214 bytes.
final List<Object?> largeBuffer = _makeTestBuffer(1000);
final ByteData largeBufferBytes =
const StandardMessageCodec().encodeMessage(largeBuffer)!;
final ByteData oneMB = ByteData(1024 * 1024);
const int numMessages = 2500;
final BenchmarkResultPrinter printer = BenchmarkResultPrinter();
await _runTest(
test: (int x) => _runBasicStandardSmall(basicStandard, x),
resetChannel: resetChannel,
printer: printer,
description: 'BasicMessageChannel/StandardMessageCodec/Flutter->Host/Small',
name: 'platform_channel_basic_standard_2host_small',
numMessages: numMessages,
);
await _runTest(
test: (int x) => _runBasicStandardLarge(basicStandard, largeBuffer, x),
resetChannel: resetChannel,
printer: printer,
description: 'BasicMessageChannel/StandardMessageCodec/Flutter->Host/Large',
name: 'platform_channel_basic_standard_2host_large',
numMessages: numMessages,
);
await _runTest(
test: (int x) => _runBasicBinary(basicBinary, largeBufferBytes, x),
resetChannel: resetChannel,
printer: printer,
description: 'BasicMessageChannel/BinaryCodec/Flutter->Host/Large',
name: 'platform_channel_basic_binary_2host_large',
numMessages: numMessages,
);
await _runTest(
test: (int x) => _runBasicBinary(basicBinary, oneMB, x),
resetChannel: resetChannel,
printer: printer,
description: 'BasicMessageChannel/BinaryCodec/Flutter->Host/1MB',
name: 'platform_channel_basic_binary_2host_1MB',
numMessages: numMessages,
);
await _runTest(
test: (int x) => _runBasicStandardParallel(basicStandard, x, 1234, 3),
resetChannel: resetChannel,
printer: printer,
description:
'BasicMessageChannel/StandardMessageCodec/Flutter->Host/SmallParallel3',
name: 'platform_channel_basic_standard_2host_small_parallel_3',
numMessages: numMessages,
);
// Background platform channels aren't yet implemented for iOS.
const BasicMessageChannel<Object?> backgroundStandard =
BasicMessageChannel<Object?>(
'dev.flutter.echo.background.standard',
StandardMessageCodec(),
);
await _runTest(
test: (int x) => _runBasicStandardSmall(backgroundStandard, x),
resetChannel: resetChannel,
printer: printer,
description:
'BasicMessageChannel/StandardMessageCodec/Flutter->Host (background)/Small',
name: 'platform_channel_basic_standard_2hostbackground_small',
numMessages: numMessages,
);
await _runTest(
test: (int x) => _runBasicStandardParallel(backgroundStandard, x, 1234, 3),
resetChannel: resetChannel,
printer: printer,
description:
'BasicMessageChannel/StandardMessageCodec/Flutter->Host (background)/SmallParallel3',
name: 'platform_channel_basic_standard_2hostbackground_small_parallel_3',
numMessages: numMessages,
);
printer.printToStdout();
}
class _BenchmarkWidget extends StatefulWidget {
const _BenchmarkWidget(this.tests);
final Future<void> Function() tests;
@override
_BenchmarkWidgetState createState() => _BenchmarkWidgetState();
}
class _BenchmarkWidgetState extends State<_BenchmarkWidget> {
@override
void initState() {
widget.tests();
super.initState();
}
@override
Widget build(BuildContext context) => Container();
}
void main() {
runApp(const _BenchmarkWidget(_runTests));
}
| flutter/dev/benchmarks/platform_channels_benchmarks/lib/main.dart/0 | {
"file_path": "flutter/dev/benchmarks/platform_channels_benchmarks/lib/main.dart",
"repo_id": "flutter",
"token_count": 2915
} | 542 |
#include "Generated.xcconfig"
| flutter/dev/benchmarks/platform_views_layout_hybrid_composition/ios/Flutter/Release.xcconfig/0 | {
"file_path": "flutter/dev/benchmarks/platform_views_layout_hybrid_composition/ios/Flutter/Release.xcconfig",
"repo_id": "flutter",
"token_count": 12
} | 543 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>com.yourcompany.platformViewsLayoutHybridComposition</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>complex_layout</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>io.flutter.embedded_views_preview</key>
<true/>
<key>io.flutter.metal_preview</key>
<true/>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
</dict>
</plist>
| flutter/dev/benchmarks/platform_views_layout_hybrid_composition/ios/Runner/Info.plist/0 | {
"file_path": "flutter/dev/benchmarks/platform_views_layout_hybrid_composition/ios/Runner/Info.plist",
"repo_id": "flutter",
"token_count": 654
} | 544 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart' show DragStartBehavior;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show debugDumpLayerTree, debugDumpRenderTree, debugDumpSemanticsTree;
import 'package:flutter/scheduler.dart' show timeDilation;
import 'i18n/stock_strings.dart';
import 'stock_data.dart';
import 'stock_list.dart';
import 'stock_symbol_viewer.dart';
import 'stock_types.dart';
typedef ModeUpdater = void Function(StockMode mode);
enum _StockMenuItem { autorefresh, refresh, speedUp, speedDown }
enum StockHomeTab { market, portfolio }
class _NotImplementedDialog extends StatelessWidget {
const _NotImplementedDialog();
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Not Implemented'),
content: const Text('This feature has not yet been implemented.'),
actions: <Widget>[
TextButton(
onPressed: debugDumpApp,
child: Row(
children: <Widget>[
const Icon(
Icons.dvr,
size: 18.0,
),
Container(
width: 8.0,
),
const Text('DUMP APP TO CONSOLE'),
],
),
),
TextButton(
onPressed: () {
Navigator.pop(context, false);
},
child: const Text('OH WELL'),
),
],
);
}
}
class StockHome extends StatefulWidget {
const StockHome(this.stocks, this.configuration, this.updater, {super.key});
final StockData stocks;
final StockConfiguration configuration;
final ValueChanged<StockConfiguration> updater;
@override
StockHomeState createState() => StockHomeState();
}
class StockHomeState extends State<StockHome> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
final TextEditingController _searchQuery = TextEditingController();
bool _isSearching = false;
bool _autorefresh = false;
void _handleSearchBegin() {
ModalRoute.of(context)!.addLocalHistoryEntry(LocalHistoryEntry(
onRemove: () {
setState(() {
_isSearching = false;
_searchQuery.clear();
});
},
));
setState(() {
_isSearching = true;
});
}
void _handleStockModeChange(StockMode? value) {
widget.updater(widget.configuration.copyWith(stockMode: value));
}
void _handleStockMenu(BuildContext context, _StockMenuItem value) {
switch (value) {
case _StockMenuItem.autorefresh:
setState(() {
_autorefresh = !_autorefresh;
});
case _StockMenuItem.refresh:
showDialog<void>(
context: context,
builder: (BuildContext context) => const _NotImplementedDialog(),
);
case _StockMenuItem.speedUp:
timeDilation /= 5.0;
case _StockMenuItem.speedDown:
timeDilation *= 5.0;
}
}
Widget _buildDrawer(BuildContext context) {
return Drawer(
child: ListView(
dragStartBehavior: DragStartBehavior.down,
children: <Widget>[
const DrawerHeader(child: Center(child: Text('Stocks'))),
const ListTile(
leading: Icon(Icons.assessment),
title: Text('Stock List'),
selected: true,
),
const ListTile(
leading: Icon(Icons.account_balance),
title: Text('Account Balance'),
enabled: false,
),
ListTile(
leading: const Icon(Icons.dvr),
title: const Text('Dump App to Console'),
onTap: () {
try {
debugDumpApp();
debugDumpRenderTree();
debugDumpLayerTree();
debugDumpSemanticsTree();
} catch (e, stack) {
debugPrint('Exception while dumping app:\n$e\n$stack');
}
},
),
const Divider(),
ListTile(
leading: const Icon(Icons.thumb_up),
title: const Text('Optimistic'),
trailing: Radio<StockMode>(
value: StockMode.optimistic,
groupValue: widget.configuration.stockMode,
onChanged: _handleStockModeChange,
),
onTap: () {
_handleStockModeChange(StockMode.optimistic);
},
),
ListTile(
leading: const Icon(Icons.thumb_down),
title: const Text('Pessimistic'),
trailing: Radio<StockMode>(
value: StockMode.pessimistic,
groupValue: widget.configuration.stockMode,
onChanged: _handleStockModeChange,
),
onTap: () {
_handleStockModeChange(StockMode.pessimistic);
},
),
const Divider(),
ListTile(
leading: const Icon(Icons.settings),
title: const Text('Settings'),
onTap: _handleShowSettings,
),
ListTile(
leading: const Icon(Icons.help),
title: const Text('About'),
onTap: _handleShowAbout,
),
],
),
);
}
void _handleShowSettings() {
Navigator.popAndPushNamed(context, '/settings');
}
void _handleShowAbout() {
showAboutDialog(context: context);
}
AppBar buildAppBar() {
return AppBar(
elevation: 0.0,
title: Text(StockStrings.of(context).title),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.search),
onPressed: _handleSearchBegin,
tooltip: 'Search',
),
PopupMenuButton<_StockMenuItem>(
onSelected: (_StockMenuItem value) { _handleStockMenu(context, value); },
itemBuilder: (BuildContext context) => <PopupMenuItem<_StockMenuItem>>[
CheckedPopupMenuItem<_StockMenuItem>(
value: _StockMenuItem.autorefresh,
checked: _autorefresh,
child: const Text('Autorefresh'),
),
const PopupMenuItem<_StockMenuItem>(
value: _StockMenuItem.refresh,
child: Text('Refresh'),
),
const PopupMenuItem<_StockMenuItem>(
value: _StockMenuItem.speedUp,
child: Text('Increase animation speed'),
),
const PopupMenuItem<_StockMenuItem>(
value: _StockMenuItem.speedDown,
child: Text('Decrease animation speed'),
),
],
),
],
bottom: TabBar(
tabs: <Widget>[
Tab(text: StockStrings.of(context).market),
Tab(text: StockStrings.of(context).portfolio),
],
),
);
}
static Iterable<Stock> _getStockList(StockData stocks, Iterable<String> symbols) {
return symbols.map<Stock?>((String symbol) => stocks[symbol])
.where((Stock? stock) => stock != null)
.cast<Stock>();
}
Iterable<Stock> _filterBySearchQuery(Iterable<Stock> stocks) {
if (_searchQuery.text.isEmpty) {
return stocks;
}
final RegExp regexp = RegExp(_searchQuery.text, caseSensitive: false);
return stocks.where((Stock stock) => stock.symbol.contains(regexp));
}
void _buyStock(Stock stock) {
setState(() {
stock.percentChange = 100.0 * (1.0 / stock.lastSale);
stock.lastSale += 1.0;
});
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Purchased ${stock.symbol} for ${stock.lastSale}'),
action: SnackBarAction(
label: 'BUY MORE',
onPressed: () {
_buyStock(stock);
},
),
));
}
Widget _buildStockList(BuildContext context, Iterable<Stock> stocks, StockHomeTab tab) {
return StockList(
stocks: stocks.toList(),
onAction: _buyStock,
onOpen: (Stock stock) {
Navigator.pushNamed(context, '/stock', arguments: stock.symbol);
},
onShow: (Stock stock) {
_scaffoldKey.currentState!.showBottomSheet((BuildContext context) => StockSymbolBottomSheet(stock: stock));
},
);
}
Widget _buildStockTab(BuildContext context, StockHomeTab tab, List<String> stockSymbols) {
return AnimatedBuilder(
key: ValueKey<StockHomeTab>(tab),
animation: Listenable.merge(<Listenable>[_searchQuery, widget.stocks]),
builder: (BuildContext context, Widget? child) {
return _buildStockList(context, _filterBySearchQuery(_getStockList(widget.stocks, stockSymbols)).toList(), tab);
},
);
}
static const List<String> portfolioSymbols = <String>['AAPL','FIZZ', 'FIVE', 'FLAT', 'ZINC', 'ZNGA'];
AppBar buildSearchBar() {
return AppBar(
leading: BackButton(
color: Theme.of(context).colorScheme.secondary,
),
title: TextField(
controller: _searchQuery,
autofocus: true,
decoration: const InputDecoration(
hintText: 'Search stocks',
),
),
backgroundColor: Theme.of(context).canvasColor,
);
}
void _handleCreateCompany() {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) => const _CreateCompanySheet(),
);
}
Widget buildFloatingActionButton() {
return FloatingActionButton(
tooltip: 'Create company',
backgroundColor: Theme.of(context).colorScheme.secondary,
onPressed: _handleCreateCompany,
child: const Icon(Icons.add),
);
}
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
drawerDragStartBehavior: DragStartBehavior.down,
key: _scaffoldKey,
appBar: _isSearching ? buildSearchBar() : buildAppBar(),
floatingActionButton: buildFloatingActionButton(),
drawer: _buildDrawer(context),
body: TabBarView(
dragStartBehavior: DragStartBehavior.down,
children: <Widget>[
_buildStockTab(context, StockHomeTab.market, widget.stocks.allSymbols),
_buildStockTab(context, StockHomeTab.portfolio, portfolioSymbols),
],
),
),
);
}
}
class _CreateCompanySheet extends StatelessWidget {
const _CreateCompanySheet();
@override
Widget build(BuildContext context) {
return const Column(
children: <Widget>[
TextField(
autofocus: true,
decoration: InputDecoration(
hintText: 'Company Name',
),
),
Text('(This demo is not yet complete.)'),
// For example, we could add a button that actually updates the list
// and then contacts the server, etc.
],
);
}
}
| flutter/dev/benchmarks/test_apps/stocks/lib/stock_home.dart/0 | {
"file_path": "flutter/dev/benchmarks/test_apps/stocks/lib/stock_home.dart",
"repo_id": "flutter",
"token_count": 4798
} | 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.
/// The SDK package allowlist for the flutter, flutter_test, flutter_driver, flutter_localizations,
/// and integration_test packages.
///
/// The goal of the allowlist is to make it more difficult to accidentally add new dependencies
/// to the core SDK packages that users depend on. Any dependencies added to this set can have a
/// large impact on the allowed version solving of a given flutter application because of how
/// the SDK pins to an exact version.
///
/// Before adding a new Dart Team owned dependency to this set, please clear with natebosch@
/// or jakemac53@. For other packages please contact hixie@ or zanderso@.
///
/// You may remove entries from this list at any time, but once removed they must stay removed
/// unless the additions are cleared as described above.
const Set<String> kCorePackageAllowList = <String>{
// Please keep this list in alphabetical order.
'async',
'boolean_selector',
'characters',
'clock',
'collection',
'fake_async',
'file',
'flutter',
'flutter_driver',
'flutter_localizations',
'flutter_test',
'fuchsia_remote_debug_protocol',
'integration_test',
'intl',
'leak_tracker',
'leak_tracker_flutter_testing',
'leak_tracker_testing',
'matcher',
'material_color_utilities',
'meta',
'path',
'platform',
'process',
'sky_engine',
'source_span',
'stack_trace',
'stream_channel',
'string_scanner',
'sync_http',
'term_glyph',
'test_api',
'vector_math',
'vm_service',
'webdriver',
};
| flutter/dev/bots/allowlist.dart/0 | {
"file_path": "flutter/dev/bots/allowlist.dart",
"repo_id": "flutter",
"token_count": 509
} | 546 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' hide Platform;
const String gobMirror = 'https://flutter.googlesource.com/mirrors/flutter';
const String githubRepo = 'https://github.com/flutter/flutter.git';
const String mingitForWindowsUrl = 'https://storage.googleapis.com/flutter_infra_release/mingit/'
'603511c649b00bbef0a6122a827ac419b656bc19/mingit.zip';
const String releaseFolder = '/releases';
const String gsBase = 'gs://flutter_infra_release';
const String gsReleaseFolder = '$gsBase$releaseFolder';
const String baseUrl = 'https://storage.googleapis.com/flutter_infra_release';
const int shortCacheSeconds = 60;
const String frameworkVersionTag = 'frameworkVersionFromGit';
const String dartVersionTag = 'dartSdkVersion';
const String dartTargetArchTag = 'dartTargetArch';
enum Branch {
beta,
stable,
master,
main;
}
/// Exception class for when a process fails to run, so we can catch
/// it and provide something more readable than a stack trace.
class PreparePackageException implements Exception {
PreparePackageException(this.message, [this.result]);
final String message;
final ProcessResult? result;
int get exitCode => result?.exitCode ?? -1;
@override
String toString() {
String output = runtimeType.toString();
output += ': $message';
final String stderr = result?.stderr as String? ?? '';
if (stderr.isNotEmpty) {
output += ':\n$stderr';
}
return output;
}
}
| flutter/dev/bots/prepare_package/common.dart/0 | {
"file_path": "flutter/dev/bots/prepare_package/common.dart",
"repo_id": "flutter",
"token_count": 500
} | 547 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:test/test.dart';
export 'package:test/test.dart' hide isInstanceOf;
/// A matcher that compares the type of the actual value to the type argument T.
TypeMatcher<T> isInstanceOf<T>() => isA<T>();
void tryToDelete(Directory directory) {
// 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 {
directory.deleteSync(recursive: true);
} on FileSystemException catch (error) {
print('Failed to delete ${directory.path}: $error');
}
}
Matcher throwsExceptionWith(String messageSubString) {
return throwsA(
isA<Exception>().having(
(Exception e) => e.toString(),
'description',
contains(messageSubString),
),
);
}
| flutter/dev/bots/test/common.dart/0 | {
"file_path": "flutter/dev/bots/test/common.dart",
"repo_id": "flutter",
"token_count": 324
} | 548 |
# codesign_integration_test takes longer than the default timeout which is 30s
# since it has to clone both the engine and framework repos, and that test is running
# asynchronously. The async function is being awaited more than 30s which counts as inactivity
# The default timeout needs to be extended to accommodate codesign_integration_test
timeout: 5m
| flutter/dev/conductor/core/dart_test.yaml/0 | {
"file_path": "flutter/dev/conductor/core/dart_test.yaml",
"repo_id": "flutter",
"token_count": 84
} | 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:conductor_core/src/repository.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.dart';
import './common.dart';
void main() {
group('repository', () {
late FakePlatform platform;
const String rootDir = '/';
const String revision = 'deadbeef';
late MemoryFileSystem fileSystem;
late FakeProcessManager processManager;
late TestStdio stdio;
setUp(() {
final String pathSeparator = const LocalPlatform().pathSeparator;
fileSystem = MemoryFileSystem.test();
platform = FakePlatform(
environment: <String, String>{
'HOME': <String>['path', 'to', 'home'].join(pathSeparator),
},
pathSeparator: pathSeparator,
);
processManager = FakeProcessManager.empty();
stdio = TestStdio();
});
test('updateDartRevision() updates the DEPS file', () async {
const String previousDartRevision = '171876a4e6cf56ee6da1f97d203926bd7afda7ef';
const String nextDartRevision = 'f6c91128be6b77aef8351e1e3a9d07c85bc2e46e';
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final EngineRepository repo = EngineRepository(checkouts);
final File depsFile = fileSystem.file('/DEPS');
depsFile.writeAsStringSync(generateMockDeps(previousDartRevision));
await repo.updateDartRevision(nextDartRevision, depsFile: depsFile);
final String updatedDepsFileContent = depsFile.readAsStringSync();
expect(updatedDepsFileContent, generateMockDeps(nextDartRevision));
});
test('updateDartRevision() throws exception on malformed DEPS file', () {
const String nextDartRevision = 'f6c91128be6b77aef8351e1e3a9d07c85bc2e46e';
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final EngineRepository repo = EngineRepository(checkouts);
final File depsFile = fileSystem.file('/DEPS');
depsFile.writeAsStringSync('''
vars = {
}''');
expect(
() async => repo.updateDartRevision(nextDartRevision, depsFile: depsFile),
throwsExceptionWith('Unexpected content in the DEPS file at'),
);
});
test('commit() throws if there are no local changes to commit', () {
const String commit1 = 'abc123';
const String commit2 = 'def456';
const String message = 'This is a commit message.';
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
EngineRepository.defaultUpstream,
fileSystem.path
.join(rootDir, 'flutter_conductor_checkouts', 'engine'),
]),
const FakeCommand(command: <String>[
'git',
'checkout',
EngineRepository.defaultBranch,
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit1),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
]),
const FakeCommand(command: <String>[
'git',
'commit',
'--message',
message,
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit2),
]);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final EngineRepository repo = EngineRepository(checkouts);
expect(
() async => repo.commit(message),
throwsExceptionWith('Tried to commit with message $message but no changes were present'),
);
});
test('commit() passes correct commit message', () async {
const String commit1 = 'abc123';
const String commit2 = 'def456';
const String message = 'This is a commit message.';
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
EngineRepository.defaultUpstream,
fileSystem.path
.join(rootDir, 'flutter_conductor_checkouts', 'engine'),
]),
const FakeCommand(command: <String>[
'git',
'checkout',
EngineRepository.defaultBranch,
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit1),
const FakeCommand(
command: <String>['git', 'status', '--porcelain'],
stdout: 'MM path/to/file.txt',
),
const FakeCommand(command: <String>[
'git',
'commit',
'--message',
message,
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit2),
]);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final EngineRepository repo = EngineRepository(checkouts);
await repo.commit(message);
expect(processManager.hasRemainingExpectations, false);
});
test('updateCandidateBranchVersion() returns false if branch is the same as version file', () async {
const String branch = 'flutter-2.15-candidate.3';
final File versionFile = fileSystem.file('/release-candidate-branch.version')..writeAsStringSync(branch);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final FrameworkRepository repo = FrameworkRepository(checkouts);
final bool didUpdate = await repo.updateCandidateBranchVersion(branch, versionFile: versionFile);
expect(didUpdate, false);
});
test('updateEngineRevision() returns false if newCommit is the same as version file', () async {
const String commit1 = 'abc123';
const String commit2 = 'def456';
final File engineVersionFile = fileSystem.file('/engine.version')..writeAsStringSync(commit2);
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
FrameworkRepository.defaultUpstream,
fileSystem.path
.join(rootDir, 'flutter_conductor_checkouts', 'framework'),
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit1),
]);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final FrameworkRepository repo = FrameworkRepository(checkouts);
final bool didUpdate = await repo.updateEngineRevision(commit2, engineVersionFile: engineVersionFile);
expect(didUpdate, false);
});
test('framework repo set as localUpstream ensures requiredLocalBranches exist locally', () async {
const String commit = 'deadbeef';
const String candidateBranch = 'flutter-1.2-candidate.3';
bool createdCandidateBranch = false;
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
FrameworkRepository.defaultUpstream,
fileSystem.path.join(rootDir, 'flutter_conductor_checkouts', 'framework'),
]),
FakeCommand(
command: const <String>['git', 'checkout', candidateBranch, '--'],
onRun: (_) => createdCandidateBranch = true,
),
const FakeCommand(
command: <String>['git', 'checkout', 'stable', '--'],
),
const FakeCommand(
command: <String>['git', 'checkout', 'beta', '--'],
),
const FakeCommand(
command: <String>['git', 'checkout', FrameworkRepository.defaultBranch, '--'],
),
const FakeCommand(
command: <String>['git', 'checkout', FrameworkRepository.defaultBranch],
),
const FakeCommand(
command: <String>['git', 'rev-parse', 'HEAD'],
stdout: commit,
),
]);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final Repository repo = FrameworkRepository(
checkouts,
additionalRequiredLocalBranches: <String>[candidateBranch],
localUpstream: true,
);
// call this so that repo.lazilyInitialize() is called.
await repo.checkoutDirectory;
expect(processManager.hasRemainingExpectations, false);
expect(createdCandidateBranch, true);
});
test('engine repo set as localUpstream ensures requiredLocalBranches exist locally', () async {
const String commit = 'deadbeef';
const String candidateBranch = 'flutter-1.2-candidate.3';
bool createdCandidateBranch = false;
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
EngineRepository.defaultUpstream,
fileSystem.path.join(rootDir, 'flutter_conductor_checkouts', 'engine'),
]),
FakeCommand(
command: const <String>['git', 'checkout', candidateBranch, '--'],
onRun: (_) => createdCandidateBranch = true,
),
const FakeCommand(
command: <String>['git', 'checkout', EngineRepository.defaultBranch],
),
const FakeCommand(
command: <String>['git', 'rev-parse', 'HEAD'],
stdout: commit,
),
]);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final Repository repo = EngineRepository(
checkouts,
additionalRequiredLocalBranches: <String>[candidateBranch],
localUpstream: true,
);
// call this so that repo.lazilyInitialize() is called.
await repo.checkoutDirectory;
expect(processManager.hasRemainingExpectations, false);
expect(createdCandidateBranch, true);
});
test('.listRemoteBranches() parses git output', () async {
const String remoteName = 'mirror';
const String lsRemoteOutput = '''
Extraneous debug information that should be ignored.
4d44dca340603e25d4918c6ef070821181202e69 refs/heads/experiment
35185330c6af3a435f615ee8ac2fed8b8bb7d9d4 refs/heads/feature-a
6f60a1e7b2f3d2c2460c9dc20fe54d0e9654b131 refs/heads/feature-b
c1436c42c0f3f98808ae767e390c3407787f1a67 refs/heads/fix_bug_1234
bbbcae73699263764ad4421a4b2ca3952a6f96cb refs/heads/stable
Extraneous debug information that should be ignored.
''';
processManager.addCommands(const <FakeCommand>[
FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
EngineRepository.defaultUpstream,
'${rootDir}flutter_conductor_checkouts/engine',
]),
FakeCommand(command: <String>[
'git',
'checkout',
'main',
]),
FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: revision),
FakeCommand(
command: <String>['git', 'ls-remote', '--heads', remoteName],
stdout: lsRemoteOutput,
),
]);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final Repository repo = EngineRepository(
checkouts,
localUpstream: true,
);
final List<String> branchNames = await repo.listRemoteBranches(remoteName);
expect(branchNames, equals(<String>[
'experiment',
'feature-a',
'feature-b',
'fix_bug_1234',
'stable',
]));
});
});
}
String generateMockDeps(String dartRevision) {
return '''
vars = {
'chromium_git': 'https://chromium.googlesource.com',
'swiftshader_git': 'https://swiftshader.googlesource.com',
'dart_git': 'https://dart.googlesource.com',
'flutter_git': 'https://flutter.googlesource.com',
'fuchsia_git': 'https://fuchsia.googlesource.com',
'github_git': 'https://github.com',
'skia_git': 'https://skia.googlesource.com',
'ocmock_git': 'https://github.com/erikdoe/ocmock.git',
'skia_revision': '4e9d5e2bdf04c58bc0bff57be7171e469e5d7175',
'dart_revision': '$dartRevision',
'dart_boringssl_gen_rev': '7322fc15cc065d8d2957fccce6b62a509dc4d641',
}''';
}
| flutter/dev/conductor/core/test/repository_test.dart/0 | {
"file_path": "flutter/dev/conductor/core/test/repository_test.dart",
"repo_id": "flutter",
"token_count": 6057
} | 550 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/framework/ios.dart';
import 'package:flutter_devicelab/framework/task_result.dart';
import 'package:flutter_devicelab/framework/utils.dart';
import 'package:path/path.dart' as path;
/// Tests that iOS and macOS .xcframeworks can be built.
Future<void> main() async {
await task(() async {
section('Create module project');
final Directory tempDir = Directory.systemTemp.createTempSync('flutter_module_test.');
try {
await inDirectory(tempDir, () async {
section('Test iOS module template');
final Directory moduleProjectDir =
Directory(path.join(tempDir.path, 'hello_module'));
await flutter(
'create',
options: <String>[
'--org',
'io.flutter.devicelab',
'--template',
'module',
'hello_module',
],
);
await _addPlugin(moduleProjectDir);
await _testBuildIosFramework(moduleProjectDir, isModule: true);
section('Test app template');
final Directory projectDir =
Directory(path.join(tempDir.path, 'hello_project'));
await flutter(
'create',
options: <String>['--org', 'io.flutter.devicelab', 'hello_project'],
);
await _addPlugin(projectDir);
await _testBuildIosFramework(projectDir);
await _testBuildMacOSFramework(projectDir);
});
return TaskResult.success(null);
} on TaskResult catch (taskResult) {
return taskResult;
} catch (e) {
return TaskResult.failure(e.toString());
} finally {
rmTree(tempDir);
}
});
}
Future<void> _addPlugin(Directory projectDir) async {
section('Add plugins');
final File pubspec = File(path.join(projectDir.path, 'pubspec.yaml'));
String content = pubspec.readAsStringSync();
content = content.replaceFirst(
'\ndependencies:\n',
'\ndependencies:\n package_info: 2.0.2\n connectivity: 3.0.6\n',
);
pubspec.writeAsStringSync(content, flush: true);
await inDirectory(projectDir, () async {
await flutter(
'packages',
options: <String>['get'],
);
});
}
Future<void> _testBuildIosFramework(Directory projectDir, { bool isModule = false}) async {
// This builds all build modes' frameworks by default
section('Build iOS app');
const String outputDirectoryName = 'flutter-frameworks';
await inDirectory(projectDir, () async {
final StringBuffer outputError = StringBuffer();
await evalFlutter(
'build',
options: <String>[
'ios-framework',
'--verbose',
'--output=$outputDirectoryName',
'--obfuscate',
'--split-debug-info=symbols',
],
stderr: outputError,
);
if (!outputError.toString().contains('Bitcode support has been deprecated.')) {
throw TaskResult.failure('Missing bitcode deprecation warning');
}
});
final String outputPath = path.join(projectDir.path, outputDirectoryName);
checkFileExists(path.join(
outputPath,
'Debug',
'Flutter.xcframework',
'ios-arm64',
'Flutter.framework',
'Flutter',
));
final String debugAppFrameworkPath = path.join(
outputPath,
'Debug',
'App.xcframework',
'ios-arm64',
'App.framework',
'App',
);
checkFileExists(debugAppFrameworkPath);
checkFileExists(path.join(
outputPath,
'Debug',
'App.xcframework',
'ios-arm64',
'App.framework',
'Info.plist',
));
section('Check debug build has Dart snapshot as asset');
checkFileExists(path.join(
outputPath,
'Debug',
'App.xcframework',
'ios-arm64_x86_64-simulator',
'App.framework',
'flutter_assets',
'vm_snapshot_data',
));
section('Check obfuscation symbols');
checkFileExists(path.join(
projectDir.path,
'symbols',
'app.ios-arm64.symbols',
));
section('Check debug build has no Dart AOT');
final String aotSymbols = await _dylibSymbols(debugAppFrameworkPath);
if (aotSymbols.contains('architecture') ||
aotSymbols.contains('_kDartVmSnapshot')) {
throw TaskResult.failure('Debug App.framework contains AOT');
}
section('Check profile, release builds has Dart AOT dylib');
for (final String mode in <String>['Profile', 'Release']) {
final String appFrameworkPath = path.join(
outputPath,
mode,
'App.xcframework',
'ios-arm64',
'App.framework',
'App',
);
await _checkDylib(appFrameworkPath);
final String aotSymbols = await _dylibSymbols(appFrameworkPath);
if (!aotSymbols.contains('_kDartVmSnapshot')) {
throw TaskResult.failure('$mode App.framework missing Dart AOT');
}
checkFileNotExists(path.join(
outputPath,
mode,
'App.xcframework',
'ios-arm64',
'App.framework',
'flutter_assets',
'vm_snapshot_data',
));
final String appFrameworkDsymPath = path.join(
outputPath,
mode,
'App.xcframework',
'ios-arm64',
'dSYMs',
'App.framework.dSYM'
);
checkDirectoryExists(appFrameworkDsymPath);
await _checkDsym(path.join(
appFrameworkDsymPath,
'Contents',
'Resources',
'DWARF',
'App',
));
checkFileExists(path.join(
outputPath,
mode,
'App.xcframework',
'ios-arm64_x86_64-simulator',
'App.framework',
'App',
));
checkFileExists(path.join(
outputPath,
mode,
'App.xcframework',
'ios-arm64_x86_64-simulator',
'App.framework',
'Info.plist',
));
}
section("Check all modes' engine dylib");
for (final String mode in <String>['Debug', 'Profile', 'Release']) {
checkFileExists(path.join(
outputPath,
mode,
'Flutter.xcframework',
'ios-arm64',
'Flutter.framework',
'Flutter',
));
checkFileExists(path.join(
outputPath,
mode,
'Flutter.xcframework',
'ios-arm64_x86_64-simulator',
'Flutter.framework',
'Flutter',
));
checkFileExists(path.join(
outputPath,
mode,
'Flutter.xcframework',
'ios-arm64_x86_64-simulator',
'Flutter.framework',
'Headers',
'Flutter.h',
));
}
section('Check all modes have plugins');
for (final String mode in <String>['Debug', 'Profile', 'Release']) {
final String pluginFrameworkPath = path.join(
outputPath,
mode,
'connectivity.xcframework',
'ios-arm64',
'connectivity.framework',
'connectivity',
);
await _checkDylib(pluginFrameworkPath);
if (!await _linksOnFlutter(pluginFrameworkPath)) {
throw TaskResult.failure('$pluginFrameworkPath does not link on Flutter');
}
final String transitiveDependencyFrameworkPath = path.join(
outputPath,
mode,
'Reachability.xcframework',
'ios-arm64',
'Reachability.framework',
'Reachability',
);
if (!exists(File(transitiveDependencyFrameworkPath))) {
throw TaskResult.failure('Expected debug Flutter engine artifact binary to exist');
}
if (await _linksOnFlutter(transitiveDependencyFrameworkPath)) {
throw TaskResult.failure(
'Transitive dependency $transitiveDependencyFrameworkPath unexpectedly links on Flutter');
}
checkFileExists(path.join(
outputPath,
mode,
'connectivity.xcframework',
'ios-arm64',
'connectivity.framework',
'Headers',
'FLTConnectivityPlugin.h',
));
if (mode != 'Debug') {
checkDirectoryExists(path.join(
outputPath,
mode,
'connectivity.xcframework',
'ios-arm64',
'dSYMs',
'connectivity.framework.dSYM',
));
}
final String simulatorFrameworkPath = path.join(
outputPath,
mode,
'connectivity.xcframework',
'ios-arm64_x86_64-simulator',
'connectivity.framework',
'connectivity',
);
final String simulatorFrameworkHeaderPath = path.join(
outputPath,
mode,
'connectivity.xcframework',
'ios-arm64_x86_64-simulator',
'connectivity.framework',
'Headers',
'FLTConnectivityPlugin.h',
);
checkFileExists(simulatorFrameworkPath);
checkFileExists(simulatorFrameworkHeaderPath);
}
section('Check all modes have generated plugin registrant');
for (final String mode in <String>['Debug', 'Profile', 'Release']) {
if (!isModule) {
continue;
}
final String registrantFrameworkPath = path.join(
outputPath,
mode,
'FlutterPluginRegistrant.xcframework',
'ios-arm64',
'FlutterPluginRegistrant.framework',
'FlutterPluginRegistrant',
);
await _checkStatic(registrantFrameworkPath);
checkFileExists(path.join(
outputPath,
mode,
'FlutterPluginRegistrant.xcframework',
'ios-arm64',
'FlutterPluginRegistrant.framework',
'Headers',
'GeneratedPluginRegistrant.h',
));
final String simulatorHeaderPath = path.join(
outputPath,
mode,
'FlutterPluginRegistrant.xcframework',
'ios-arm64_x86_64-simulator',
'FlutterPluginRegistrant.framework',
'Headers',
'GeneratedPluginRegistrant.h',
);
checkFileExists(simulatorHeaderPath);
}
// This builds all build modes' frameworks by default
section('Build podspec and static plugins');
const String cocoapodsOutputDirectoryName = 'flutter-frameworks-cocoapods';
await inDirectory(projectDir, () async {
await flutter(
'build',
options: <String>[
'ios-framework',
'--cocoapods',
'--force', // Allow podspec creation on master.
'--output=$cocoapodsOutputDirectoryName',
'--static',
],
);
});
final String cocoapodsOutputPath = path.join(projectDir.path, cocoapodsOutputDirectoryName);
for (final String mode in <String>['Debug', 'Profile', 'Release']) {
checkFileExists(path.join(
cocoapodsOutputPath,
mode,
'Flutter.podspec',
));
await _checkDylib(path.join(
cocoapodsOutputPath,
mode,
'App.xcframework',
'ios-arm64',
'App.framework',
'App',
));
if (mode != 'Debug') {
final String appFrameworkDsymPath = path.join(
cocoapodsOutputPath,
mode,
'App.xcframework',
'ios-arm64',
'dSYMs',
'App.framework.dSYM'
);
checkDirectoryExists(appFrameworkDsymPath);
await _checkDsym(path.join(
appFrameworkDsymPath,
'Contents',
'Resources',
'DWARF',
'App',
));
}
if (Directory(path.join(
cocoapodsOutputPath,
mode,
'FlutterPluginRegistrant.xcframework',
)).existsSync() !=
isModule) {
throw TaskResult.failure(
'Unexpected FlutterPluginRegistrant.xcframework.');
}
await _checkStatic(path.join(
cocoapodsOutputPath,
mode,
'package_info.xcframework',
'ios-arm64',
'package_info.framework',
'package_info',
));
await _checkStatic(path.join(
cocoapodsOutputPath,
mode,
'connectivity.xcframework',
'ios-arm64',
'connectivity.framework',
'connectivity',
));
checkDirectoryExists(path.join(
cocoapodsOutputPath,
mode,
'Reachability.xcframework',
));
}
if (File(path.join(
outputPath,
'GeneratedPluginRegistrant.h',
)).existsSync() ==
isModule) {
throw TaskResult.failure('Unexpected GeneratedPluginRegistrant.h.');
}
if (File(path.join(
outputPath,
'GeneratedPluginRegistrant.m',
)).existsSync() ==
isModule) {
throw TaskResult.failure('Unexpected GeneratedPluginRegistrant.m.');
}
section('Build frameworks without plugins');
await _testBuildFrameworksWithoutPlugins(projectDir, platform: 'ios');
section('check --static cannot be used with the --no-plugins flag');
await _testStaticAndNoPlugins(projectDir);
}
Future<void> _testBuildMacOSFramework(Directory projectDir) async {
// This builds all build modes' frameworks by default
section('Build macOS frameworks');
const String outputDirectoryName = 'flutter-frameworks';
await inDirectory(projectDir, () async {
await flutter(
'build',
options: <String>[
'macos-framework',
'--verbose',
'--output=$outputDirectoryName',
'--obfuscate',
'--split-debug-info=symbols',
],
);
});
final String outputPath = path.join(projectDir.path, outputDirectoryName);
final String flutterFramework = path.join(
outputPath,
'Debug',
'FlutterMacOS.xcframework',
'macos-arm64_x86_64',
'FlutterMacOS.framework',
);
checkDirectoryExists(flutterFramework);
final String debugAppFrameworkPath = path.join(
outputPath,
'Debug',
'App.xcframework',
'macos-arm64_x86_64',
'App.framework',
'App',
);
checkSymlinkExists(debugAppFrameworkPath);
checkFileExists(path.join(
outputPath,
'Debug',
'App.xcframework',
'macos-arm64_x86_64',
'App.framework',
'Resources',
'Info.plist',
));
section('Check debug build has Dart snapshot as asset');
checkFileExists(path.join(
outputPath,
'Debug',
'App.xcframework',
'macos-arm64_x86_64',
'App.framework',
'Resources',
'flutter_assets',
'vm_snapshot_data',
));
section('Check obfuscation symbols');
checkFileExists(path.join(
projectDir.path,
'symbols',
'app.darwin-arm64.symbols',
));
checkFileExists(path.join(
projectDir.path,
'symbols',
'app.darwin-x86_64.symbols',
));
section('Check debug build has no Dart AOT');
final String aotSymbols = await _dylibSymbols(debugAppFrameworkPath);
if (aotSymbols.contains('architecture') ||
aotSymbols.contains('_kDartVmSnapshot')) {
throw TaskResult.failure('Debug App.framework contains AOT');
}
section('Check profile, release builds has Dart AOT dylib');
for (final String mode in <String>['Profile', 'Release']) {
final String appFrameworkPath = path.join(
outputPath,
mode,
'App.xcframework',
'macos-arm64_x86_64',
'App.framework',
'App',
);
await _checkDylib(appFrameworkPath);
final String aotSymbols = await _dylibSymbols(appFrameworkPath);
if (!aotSymbols.contains('_kDartVmSnapshot')) {
throw TaskResult.failure('$mode App.framework missing Dart AOT');
}
checkFileNotExists(path.join(
outputPath,
mode,
'App.xcframework',
'macos-arm64_x86_64',
'App.framework',
'Resources',
'flutter_assets',
'vm_snapshot_data',
));
checkFileExists(path.join(
outputPath,
mode,
'App.xcframework',
'macos-arm64_x86_64',
'App.framework',
'Resources',
'Info.plist',
));
final String appFrameworkDsymPath = path.join(
outputPath,
mode,
'App.xcframework',
'macos-arm64_x86_64',
'dSYMs',
'App.framework.dSYM'
);
checkDirectoryExists(appFrameworkDsymPath);
await _checkDsym(path.join(
appFrameworkDsymPath,
'Contents',
'Resources',
'DWARF',
'App',
));
}
section("Check all modes' engine dylib");
for (final String mode in <String>['Debug', 'Profile', 'Release']) {
final String engineBinary = path.join(
outputPath,
mode,
'FlutterMacOS.xcframework',
'macos-arm64_x86_64',
'FlutterMacOS.framework',
'FlutterMacOS',
);
checkSymlinkExists(engineBinary);
checkFileExists(path.join(
outputPath,
mode,
'FlutterMacOS.xcframework',
'macos-arm64_x86_64',
'FlutterMacOS.framework',
'Headers',
'FlutterMacOS.h',
));
}
section('Check all modes have plugins');
for (final String mode in <String>['Debug', 'Profile', 'Release']) {
final String pluginFrameworkPath = path.join(
outputPath,
mode,
'connectivity_macos.xcframework',
'macos-arm64_x86_64',
'connectivity_macos.framework',
'connectivity_macos',
);
await _checkDylib(pluginFrameworkPath);
if (!await _linksOnFlutterMacOS(pluginFrameworkPath)) {
throw TaskResult.failure('$pluginFrameworkPath does not link on Flutter');
}
final String transitiveDependencyFrameworkPath = path.join(
outputPath,
mode,
'Reachability.xcframework',
'macos-arm64_x86_64',
'Reachability.framework',
'Reachability',
);
if (await _linksOnFlutterMacOS(transitiveDependencyFrameworkPath)) {
throw TaskResult.failure('Transitive dependency $transitiveDependencyFrameworkPath unexpectedly links on Flutter');
}
checkFileExists(path.join(
outputPath,
mode,
'connectivity_macos.xcframework',
'macos-arm64_x86_64',
'connectivity_macos.framework',
'Headers',
'connectivity_macos-Swift.h',
));
checkDirectoryExists(path.join(
outputPath,
mode,
'connectivity_macos.xcframework',
'macos-arm64_x86_64',
'connectivity_macos.framework',
'Modules',
'connectivity_macos.swiftmodule',
));
if (mode != 'Debug') {
checkDirectoryExists(path.join(
outputPath,
mode,
'connectivity_macos.xcframework',
'macos-arm64_x86_64',
'dSYMs',
'connectivity_macos.framework.dSYM',
));
}
checkSymlinkExists(path.join(
outputPath,
mode,
'connectivity_macos.xcframework',
'macos-arm64_x86_64',
'connectivity_macos.framework',
'connectivity_macos',
));
}
// This builds all build modes' frameworks by default
section('Build podspec and static plugins');
const String cocoapodsOutputDirectoryName = 'flutter-frameworks-cocoapods';
await inDirectory(projectDir, () async {
await flutter(
'build',
options: <String>[
'macos-framework',
'--cocoapods',
'--force', // Allow podspec creation on master.
'--output=$cocoapodsOutputDirectoryName',
'--static',
],
);
});
final String cocoapodsOutputPath = path.join(projectDir.path, cocoapodsOutputDirectoryName);
for (final String mode in <String>['Debug', 'Profile', 'Release']) {
checkFileExists(path.join(
cocoapodsOutputPath,
mode,
'FlutterMacOS.podspec',
));
await _checkDylib(path.join(
cocoapodsOutputPath,
mode,
'App.xcframework',
'macos-arm64_x86_64',
'App.framework',
'App',
));
if (mode != 'Debug') {
final String appFrameworkDsymPath = path.join(
cocoapodsOutputPath,
mode,
'App.xcframework',
'macos-arm64_x86_64',
'dSYMs',
'App.framework.dSYM'
);
checkDirectoryExists(appFrameworkDsymPath);
await _checkDsym(path.join(
appFrameworkDsymPath,
'Contents',
'Resources',
'DWARF',
'App',
));
}
await _checkStatic(path.join(
cocoapodsOutputPath,
mode,
'package_info.xcframework',
'macos-arm64_x86_64',
'package_info.framework',
'package_info',
));
await _checkStatic(path.join(
cocoapodsOutputPath,
mode,
'connectivity_macos.xcframework',
'macos-arm64_x86_64',
'connectivity_macos.framework',
'connectivity_macos',
));
checkDirectoryExists(path.join(
cocoapodsOutputPath,
mode,
'Reachability.xcframework',
));
}
checkFileExists(path.join(
outputPath,
'GeneratedPluginRegistrant.swift',
));
section('Validate embed FlutterMacOS.framework with CocoaPods');
final File podspec = File(path.join(
cocoapodsOutputPath,
'Debug',
'FlutterMacOS.podspec',
));
podspec.writeAsStringSync(
podspec.readAsStringSync().replaceFirst('null.null.0', '0.0.0'),
);
final Directory macosDirectory = Directory(path.join(projectDir.path, 'macos'));
final File podfile = File(path.join(macosDirectory.path, 'Podfile'));
final String currentPodfile = podfile.readAsStringSync();
// Temporarily test Add-to-App Cocoapods podspec for framework
podfile.writeAsStringSync('''
target 'Runner' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
pod 'FlutterMacOS', :podspec => '${podspec.path}'
end
''');
await inDirectory(macosDirectory, () async {
await eval('pod', <String>['install']);
});
// Change podfile back to original
podfile.writeAsStringSync(currentPodfile);
await inDirectory(macosDirectory, () async {
await eval('pod', <String>['install']);
});
section('Build frameworks without plugins');
await _testBuildFrameworksWithoutPlugins(projectDir, platform: 'macos');
}
Future<void> _testBuildFrameworksWithoutPlugins(Directory projectDir, { required String platform}) async {
const String noPluginsOutputDir = 'flutter-frameworks-no-plugins';
await inDirectory(projectDir, () async {
await flutter(
'build',
options: <String>[
'$platform-framework',
'--cocoapods',
'--force', // Allow podspec creation on master.
'--output=$noPluginsOutputDir',
'--no-plugins',
],
);
});
final String noPluginsOutputPath = path.join(projectDir.path, noPluginsOutputDir);
for (final String mode in <String>['Debug', 'Profile', 'Release']) {
checkFileExists(path.join(
noPluginsOutputPath,
mode,
'Flutter${platform == 'macos' ? 'MacOS' : ''}.podspec',
));
checkDirectoryExists(path.join(
noPluginsOutputPath,
mode,
'App.xcframework',
));
checkDirectoryNotExists(path.join(
noPluginsOutputPath,
mode,
'package_info.xcframework',
));
checkDirectoryNotExists(path.join(
noPluginsOutputPath,
mode,
'connectivity.xcframework',
));
checkDirectoryNotExists(path.join(
noPluginsOutputPath,
mode,
'Reachability.xcframework',
));
}
}
Future<void> _testStaticAndNoPlugins(Directory projectDir) async {
const String noPluginsOutputDir = 'flutter-frameworks-no-plugins-static';
final ProcessResult result = await inDirectory(projectDir, () async {
return executeFlutter(
'build',
options: <String>[
'ios-framework',
'--cocoapods',
'--force', // Allow podspec creation on master.
'--output=$noPluginsOutputDir',
'--no-plugins',
'--static'
],
canFail: true
);
});
if (result.exitCode == 0) {
throw TaskResult.failure('Build framework command did not exit with error as expected');
}
final String output = '${result.stdout}\n${result.stderr}';
if (!output.contains('--static cannot be used with the --no-plugins flag')) {
throw TaskResult.failure(output);
}
}
Future<void> _checkDylib(String pathToLibrary) async {
final String binaryFileType = await fileType(pathToLibrary);
if (!binaryFileType.contains('dynamically linked')) {
throw TaskResult.failure('$pathToLibrary is not a dylib, found: $binaryFileType');
}
}
Future<void> _checkDsym(String pathToSymbolFile) async {
final String binaryFileType = await fileType(pathToSymbolFile);
if (!binaryFileType.contains('dSYM companion file')) {
throw TaskResult.failure('$pathToSymbolFile is not a dSYM, found: $binaryFileType');
}
}
Future<void> _checkStatic(String pathToLibrary) async {
final String binaryFileType = await fileType(pathToLibrary);
if (!binaryFileType.contains('current ar archive random library')) {
throw TaskResult.failure('$pathToLibrary is not a static library, found: $binaryFileType');
}
}
Future<String> _dylibSymbols(String pathToDylib) {
return eval('nm', <String>[
'-g',
pathToDylib,
'-arch',
'arm64',
]);
}
Future<bool> _linksOnFlutter(String pathToBinary) async {
final String loadCommands = await eval('otool', <String>[
'-l',
'-arch',
'arm64',
pathToBinary,
]);
return loadCommands.contains('Flutter.framework');
}
Future<bool> _linksOnFlutterMacOS(String pathToBinary) async {
final String loadCommands = await eval('otool', <String>[
'-l',
'-arch',
'arm64',
pathToBinary,
]);
return loadCommands.contains('FlutterMacOS.framework');
}
| flutter/dev/devicelab/bin/tasks/build_ios_framework_module_test.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/build_ios_framework_module_test.dart",
"repo_id": "flutter",
"token_count": 10340
} | 551 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_devicelab/framework/devices.dart';
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/framework/utils.dart';
import 'package:flutter_devicelab/tasks/perf_tests.dart';
const String kPackageName = 'com.example.macrobenchmarks';
class FastScrollLargeImagesMemoryTest extends MemoryTest {
FastScrollLargeImagesMemoryTest()
: super(
'${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
'test_memory/large_images.dart', kPackageName,
);
@override
AndroidDevice? get device => super.device as AndroidDevice?;
@override
int get iterationCount => 5;
@override
Future<void> useMemory() async {
await launchApp();
await recordStart();
await device!.shellExec('input', <String>['swipe', '0 1500 0 0 50']);
await Future<void>.delayed(const Duration(milliseconds: 15000));
await recordEnd();
}
}
Future<void> main() async {
deviceOperatingSystem = DeviceOperatingSystem.android;
await task(FastScrollLargeImagesMemoryTest().run);
}
| flutter/dev/devicelab/bin/tasks/fast_scroll_large_images__memory.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/fast_scroll_large_images__memory.dart",
"repo_id": "flutter",
"token_count": 408
} | 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 '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 path;
void main() {
task(() async {
deviceOperatingSystem = DeviceOperatingSystem.ios;
final Device device = await devices.workingDevice;
await device.unlock();
final Directory appDir = dir(path.join(flutterDirectory.path, 'dev/integration_tests/ui'));
section('TEST WHETHER `flutter drive --route` WORKS on IOS');
await inDirectory(appDir, () async {
return flutter(
'drive',
options: <String>[
'--verbose',
'-d',
device.deviceId,
'--route',
'/smuggle-it',
'lib/route.dart',
],
);
});
return TaskResult.success(null);
});
}
| flutter/dev/devicelab/bin/tasks/route_test_ios.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/route_test_ios.dart",
"repo_id": "flutter",
"token_count": 435
} | 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_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/framework/task_result.dart';
/// Smoke test of a task that fails by returning an unsuccessful response.
Future<void> main() async {
await task(() async {
return TaskResult.failure('Failed');
});
}
| flutter/dev/devicelab/bin/tasks/smoke_test_failure.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/smoke_test_failure.dart",
"repo_id": "flutter",
"token_count": 136
} | 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:file/file.dart';
import 'package:file/local.dart';
import 'package:meta/meta.dart';
import 'package:platform/platform.dart';
/// The current host machine running the tests.
HostAgent get hostAgent => HostAgent(platform: const LocalPlatform(), fileSystem: const LocalFileSystem());
/// Host machine running the tests.
class HostAgent {
HostAgent({required Platform platform, required FileSystem fileSystem})
: _platform = platform,
_fileSystem = fileSystem;
final Platform _platform;
final FileSystem _fileSystem;
/// Creates a directory to dump file artifacts.
Directory? get dumpDirectory {
if (_dumpDirectory == null) {
// Set in LUCI recipe.
final String? directoryPath = _platform.environment['FLUTTER_LOGS_DIR'];
if (directoryPath != null) {
_dumpDirectory = _fileSystem.directory(directoryPath)..createSync(recursive: true);
print('Found FLUTTER_LOGS_DIR dump directory ${_dumpDirectory?.path}');
}
}
return _dumpDirectory;
}
static Directory? _dumpDirectory;
@visibleForTesting
void resetDumpDirectory() {
_dumpDirectory = null;
}
}
| flutter/dev/devicelab/lib/framework/host_agent.dart/0 | {
"file_path": "flutter/dev/devicelab/lib/framework/host_agent.dart",
"repo_id": "flutter",
"token_count": 407
} | 555 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io' show Directory, File, Process, ProcessSignal;
import '../framework/devices.dart';
import '../framework/framework.dart';
import '../framework/task_result.dart';
import '../framework/utils.dart';
const String _messagePrefix = 'entrypoint:';
const String _entrypointName = 'entrypoint';
const String _dartCode = '''
import 'package:flutter/widgets.dart';
@pragma('vm:entry-point')
void main() {
print('$_messagePrefix main');
runApp(const ColoredBox(color: Color(0xffcc0000)));
}
@pragma('vm:entry-point')
void $_entrypointName() {
print('$_messagePrefix $_entrypointName');
runApp(const ColoredBox(color: Color(0xff00cc00)));
}
''';
const String _kotlinCode = '''
package com.example.entrypoint_dart_registrant
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
override fun getDartEntrypointFunctionName(): String {
return "$_entrypointName"
}
}
''';
Future<TaskResult> _runWithTempDir(Directory tempDir) async {
const String testDirName = 'entrypoint_dart_registrant';
final String testPath = '${tempDir.path}/$testDirName';
await inDirectory(tempDir, () async {
await flutter('create', options: <String>[
'--platforms',
'android',
testDirName,
]);
});
final String mainPath = '${tempDir.path}/$testDirName/lib/main.dart';
print(mainPath);
File(mainPath).writeAsStringSync(_dartCode);
final String activityPath =
'${tempDir.path}/$testDirName/android/app/src/main/kotlin/com/example/entrypoint_dart_registrant/MainActivity.kt';
File(activityPath).writeAsStringSync(_kotlinCode);
final Device device = await devices.workingDevice;
await device.unlock();
final String entrypoint = await inDirectory(testPath, () async {
// The problem only manifested when the dart plugin registrant was used
// (which path_provider has).
await flutter('pub', options: <String>['add', 'path_provider:2.0.9']);
// The problem only manifested on release builds, so we test release.
final Process process =
await startFlutter('run', options: <String>['--release']);
final Completer<String> completer = Completer<String>();
final StreamSubscription<String> stdoutSub = process.stdout
.transform<String>(const Utf8Decoder())
.transform<String>(const LineSplitter())
.listen((String line) async {
print(line);
if (line.contains(_messagePrefix)) {
completer.complete(line);
}
});
final String entrypoint = await completer.future;
await stdoutSub.cancel();
process.stdin.write('q');
await process.stdin.flush();
process.kill(ProcessSignal.sigint);
return entrypoint;
});
if (entrypoint.contains('$_messagePrefix $_entrypointName')) {
return TaskResult.success(null);
} else {
return TaskResult.failure('expected entrypoint:"$_entrypointName" but found:"$entrypoint"');
}
}
/// Asserts that the custom entrypoint works in the presence of the dart plugin
/// registrant.
TaskFunction entrypointDartRegistrant() {
return () async {
final Directory tempDir =
Directory.systemTemp.createTempSync('entrypoint_dart_registrant.');
try {
return await _runWithTempDir(tempDir);
} finally {
rmTree(tempDir);
}
};
}
| flutter/dev/devicelab/lib/tasks/entrypoint_dart_registrant.dart/0 | {
"file_path": "flutter/dev/devicelab/lib/tasks/entrypoint_dart_registrant.dart",
"repo_id": "flutter",
"token_count": 1203
} | 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:collection/collection.dart' show ListEquality, MapEquality;
import 'package:flutter_devicelab/framework/devices.dart';
import 'package:meta/meta.dart';
import 'common.dart';
void main() {
group('device', () {
late Device device;
setUp(() {
FakeDevice.resetLog();
device = FakeDevice(deviceId: 'fakeDeviceId');
});
tearDown(() {
});
group('cpu check', () {
test('arm64', () async {
FakeDevice.pretendArm64();
final AndroidDevice androidDevice = device as AndroidDevice;
expect(await androidDevice.isArm64(), isTrue);
expectLog(<CommandArgs>[
cmd(command: 'getprop', arguments: <String>['ro.bootimage.build.fingerprint', ';', 'getprop', 'ro.build.version.release', ';', 'getprop', 'ro.build.version.sdk']),
cmd(command: 'getprop', arguments: <String>['ro.product.cpu.abi']),
]);
});
});
group('isAwake/isAsleep', () {
test('reads Awake', () async {
FakeDevice.pretendAwake();
expect(await device.isAwake(), isTrue);
expect(await device.isAsleep(), isFalse);
});
test('reads Awake - samsung devices', () async {
FakeDevice.pretendAwakeSamsung();
expect(await device.isAwake(), isTrue);
expect(await device.isAsleep(), isFalse);
});
test('reads Asleep', () async {
FakeDevice.pretendAsleep();
expect(await device.isAwake(), isFalse);
expect(await device.isAsleep(), isTrue);
});
});
group('togglePower', () {
test('sends power event', () async {
await device.togglePower();
expectLog(<CommandArgs>[
cmd(command: 'getprop', arguments: <String>['ro.bootimage.build.fingerprint', ';', 'getprop', 'ro.build.version.release', ';', 'getprop', 'ro.build.version.sdk']),
cmd(command: 'input', arguments: <String>['keyevent', '26']),
]);
});
});
group('wakeUp', () {
test('when awake', () async {
FakeDevice.pretendAwake();
await device.wakeUp();
expectLog(<CommandArgs>[
cmd(command: 'getprop', arguments: <String>['ro.bootimage.build.fingerprint', ';', 'getprop', 'ro.build.version.release', ';', 'getprop', 'ro.build.version.sdk']),
cmd(command: 'dumpsys', arguments: <String>['power']),
]);
});
test('when asleep', () async {
FakeDevice.pretendAsleep();
await device.wakeUp();
expectLog(<CommandArgs>[
cmd(command: 'getprop', arguments: <String>['ro.bootimage.build.fingerprint', ';', 'getprop', 'ro.build.version.release', ';', 'getprop', 'ro.build.version.sdk']),
cmd(command: 'dumpsys', arguments: <String>['power']),
cmd(command: 'input', arguments: <String>['keyevent', '26']),
]);
});
});
group('sendToSleep', () {
test('when asleep', () async {
FakeDevice.pretendAsleep();
await device.sendToSleep();
expectLog(<CommandArgs>[
cmd(command: 'getprop', arguments: <String>['ro.bootimage.build.fingerprint', ';', 'getprop', 'ro.build.version.release', ';', 'getprop', 'ro.build.version.sdk']),
cmd(command: 'dumpsys', arguments: <String>['power']),
]);
});
test('when awake', () async {
FakeDevice.pretendAwake();
await device.sendToSleep();
expectLog(<CommandArgs>[
cmd(command: 'getprop', arguments: <String>['ro.bootimage.build.fingerprint', ';', 'getprop', 'ro.build.version.release', ';', 'getprop', 'ro.build.version.sdk']),
cmd(command: 'dumpsys', arguments: <String>['power']),
cmd(command: 'input', arguments: <String>['keyevent', '26']),
]);
});
});
group('unlock', () {
test('sends unlock event', () async {
FakeDevice.pretendAwake();
await device.unlock();
expectLog(<CommandArgs>[
cmd(command: 'getprop', arguments: <String>['ro.bootimage.build.fingerprint', ';', 'getprop', 'ro.build.version.release', ';', 'getprop', 'ro.build.version.sdk']),
cmd(command: 'dumpsys', arguments: <String>['power']),
cmd(command: 'input', arguments: <String>['keyevent', '82']),
]);
});
});
group('adb', () {
test('tap', () async {
await device.tap(100, 200);
expectLog(<CommandArgs>[
cmd(command: 'getprop', arguments: <String>['ro.bootimage.build.fingerprint', ';', 'getprop', 'ro.build.version.release', ';', 'getprop', 'ro.build.version.sdk']),
cmd(command: 'input', arguments: <String>['tap', '100', '200']),
]);
});
});
});
}
void expectLog(List<CommandArgs> log) {
expect(FakeDevice.commandLog, log);
}
CommandArgs cmd({
required String command,
List<String>? arguments,
Map<String, String>? environment,
}) {
return CommandArgs(
command: command,
arguments: arguments,
environment: environment,
);
}
@immutable
class CommandArgs {
const CommandArgs({ required this.command, this.arguments, this.environment });
final String command;
final List<String>? arguments;
final Map<String, String>? environment;
@override
String toString() => 'CommandArgs(command: $command, arguments: $arguments, environment: $environment)';
@override
bool operator==(Object other) {
if (other.runtimeType != CommandArgs) {
return false;
}
return other is CommandArgs
&& other.command == command
&& const ListEquality<String>().equals(other.arguments, arguments)
&& const MapEquality<String, String>().equals(other.environment, environment);
}
@override
int get hashCode {
return Object.hash(
command,
Object.hashAll(arguments ?? const <String>[]),
Object.hashAllUnordered(environment?.keys ?? const <String>[]),
Object.hashAllUnordered(environment?.values ?? const <String>[]),
);
}
}
class FakeDevice extends AndroidDevice {
FakeDevice({required super.deviceId});
static String output = '';
static List<CommandArgs> commandLog = <CommandArgs>[];
static void resetLog() {
commandLog.clear();
}
static void pretendAwake() {
output = '''
mWakefulness=Awake
''';
}
static void pretendAwakeSamsung() {
output = '''
getWakefulnessLocked()=Awake
''';
}
static void pretendAsleep() {
output = '''
mWakefulness=Asleep
''';
}
static void pretendArm64() {
output = '''
arm64
''';
}
@override
Future<String> shellEval(String command, List<String> arguments, { Map<String, String>? environment, bool silent = false }) async {
commandLog.add(CommandArgs(
command: command,
arguments: arguments,
environment: environment,
));
return output;
}
@override
Future<void> shellExec(String command, List<String> arguments, { Map<String, String>? environment, bool silent = false }) async {
commandLog.add(CommandArgs(
command: command,
arguments: arguments,
environment: environment,
));
}
}
| flutter/dev/devicelab/test/adb_test.dart/0 | {
"file_path": "flutter/dev/devicelab/test/adb_test.dart",
"repo_id": "flutter",
"token_count": 2864
} | 557 |
# Welcome to the Flutter API reference documentation!
Flutter is Google's SDK for crafting beautiful, fast user experiences for
mobile, web, and desktop from a single codebase. Flutter works with existing
code, is used by developers and organizations around the world, and is free
and open source.
This API reference covers all libraries that are exported by the Flutter
SDK.
## More Documentation
This site hosts Flutter's API documentation. Other documentation can be found at
the following locations:
* [flutter.dev](https://flutter.dev) (main Flutter site)
* [Stable channel API Docs](https://api.flutter.dev)
* [Main channel API Docs](https://main-api.flutter.dev)
* Engine Embedder API documentation:
* [Android Embedder](../javadoc/index.html)
* [iOS Embedder](../ios-embedder/index.html)
* [macOS Embedder](../macos-embedder/index.html)
* [Linux Embedder](../linux-embedder/index.html)
* [Windows Embedder](../windows-embedder/index.html)
* [Web Embedder](dart-ui_web/dart-ui_web-library.html)
* [Installation](https://flutter.dev/docs/get-started/install)
* [Codelabs](https://flutter.dev/docs/codelabs)
* [Contributing to Flutter](https://github.com/flutter/flutter/blob/main/CONTRIBUTING.md)
## Offline Documentation
In addition to the online sites above, Flutter's documentation can be downloaded
as an HTML documentation ZIP file for use when offline or when you have a poor
internet connection.
**Warning: the offline documentation files are quite large, approximately 700 MB
to 900 MB.**
Offline HTML documentation ZIP bundles:
* [Stable channel](https://api.flutter.dev/offline/flutter.docs.zip)
* [Main channel](https://main-api.flutter.dev/offline/flutter.docs.zip)
Or, you can add Flutter to the open-source [Zeal](https://zealdocs.org/) app
using the following XML configurations. Follow the instructions in the
application for adding a feed.
* Stable channel Zeal XML configuration URL:
<https://api.flutter.dev/offline/flutter.xml>
* Main channel Zeal XML configuration URL:
<https://main-api.flutter.dev/offline/flutter.xml>
## Importing a Library
### Framework Libraries
Libraries in the "Libraries" section below (or in the left navigation) are part
of the core Flutter framework and are imported using
`'package:flutter/<library>.dart'`, like so:
```dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
```
### Dart Libraries
Libraries in the "Dart" section exist in the `dart:` namespace and are imported
using `'dart:<library>'`, like so:
```dart
import 'dart:async';
import 'dart:ui';
```
Except for `'dart:core'`, you must import a Dart library before you can use it.
### Supporting Libraries
Libraries in other sections are supporting libraries that ship with Flutter.
They are organized by package and are imported using
`'package:<package>/<library>.dart'`, like so:
```dart
import 'package:flutter_test/flutter_test.dart';
import 'package:file/local.dart';
```
## Packages on pub.dev
Flutter has a rich ecosystem of packages that have been contributed by the
Flutter team and the broader open source community to a central repository.
Among the thousands of packages, you'll find support for Firebase, Google
Fonts, hardware services like Bluetooth and camera, new widgets and
animations, and integration with other popular web services. You can browse
those packages at [pub.dev](https://pub.dev).
| flutter/dev/docs/README.md/0 | {
"file_path": "flutter/dev/docs/README.md",
"repo_id": "flutter",
"token_count": 995
} | 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.
/// The name of the route containing the test suite.
const String popupControlsRoute = 'popups';
/// The string supplied to the [ValueKey] for the popup menu button.
const String popupButtonKeyValue = 'PopupControls#PopupButton1';
/// The string supplied to the [ValueKey] for the popup menu.
const String popupKeyValue = 'PopupControls#Popup1';
/// The string supplied to the [ValueKey] for the dropdown button.
const String dropdownButtonKeyValue = 'PopupControls#DropdownButton1';
/// The string supplied to the [ValueKey] for the dropdown button menu.
const String dropdownKeyValue = 'PopupControls#Dropdown1';
/// The string supplied to the [ValueKey] for the alert button.
const String alertButtonKeyValue = 'PopupControls#AlertButton1';
/// The string supplied to the [ValueKey] for the alert dialog.
const String alertKeyValue = 'PopupControls#Alert1';
const List<String> popupItems = <String>['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'];
| flutter/dev/integration_tests/android_semantics_testing/lib/src/tests/popup_constants.dart/0 | {
"file_path": "flutter/dev/integration_tests/android_semantics_testing/lib/src/tests/popup_constants.dart",
"repo_id": "flutter",
"token_count": 314
} | 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.
package io.flutter.integration.android_verified_input;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.plugin.common.StandardMessageCodec;
import io.flutter.plugin.platform.PlatformView;
import io.flutter.plugin.platform.PlatformViewFactory;
import java.util.Map;
public class VerifiedInputViewFactory extends PlatformViewFactory {
VerifiedInputViewFactory() {
super(StandardMessageCodec.INSTANCE);
}
@NonNull
@Override
public PlatformView create(@NonNull Context context, int id, @Nullable Object args) {
final Map<String, Object> creationParams = (Map<String, Object>) args;
return new VerifiedInputView(context, creationParams);
}
}
| flutter/dev/integration_tests/android_verified_input/android/app/src/main/java/io/flutter/integration/android_verified_input/VerifiedInputViewFactory.java/0 | {
"file_path": "flutter/dev/integration_tests/android_verified_input/android/app/src/main/java/io/flutter/integration/android_verified_input/VerifiedInputViewFactory.java",
"repo_id": "flutter",
"token_count": 260
} | 560 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';
Future<void> main() async {
late FlutterDriver driver;
setUpAll(() async {
driver = await FlutterDriver.connect();
});
tearDownAll(() {
driver.close();
});
test('verified input', () async {
// Wait for the PlatformView to show up.
await driver.waitFor(find.byValueKey('PlatformView'));
final DriverOffset offset = await driver.getCenter(find.byValueKey('PlatformView'));
// This future will complete when the input event is verified or fails
// to be verified.
final Future<String> inputEventWasVerified = driver.requestData('input_was_verified');
// Keep issuing taps until we get the requested data. The actual setup
// of the platform view is asynchronous so we might have to tap more than
// once to get a response.
bool stop = false;
inputEventWasVerified.whenComplete(() => stop = true);
while (!stop) {
// We must use the Android input tool to get verified input events.
final ProcessResult result =
await Process.run('adb', <String>['shell', 'input', 'tap', '${offset.dx}', '${offset.dy}']);
expect(result.exitCode, equals(0));
}
// Input
expect(await inputEventWasVerified, equals('true'));
}, timeout: Timeout.none);
}
| flutter/dev/integration_tests/android_verified_input/test_driver/main_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/android_verified_input/test_driver/main_test.dart",
"repo_id": "flutter",
"token_count": 493
} | 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 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_driver/driver_extension.dart';
void main() {
enableFlutterDriverExtension();
runMainApp();
}
void runMainApp() {
runApp(const Center(child: Flavor()));
}
class Flavor extends StatefulWidget {
const Flavor({super.key});
@override
State<Flavor> createState() => _FlavorState();
}
class _FlavorState extends State<Flavor> {
String? _flavor;
@override
void initState() {
super.initState();
const MethodChannel('flavor').invokeMethod<String>('getFlavor').then((String? flavor) {
setState(() {
_flavor = flavor;
});
});
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: _flavor == null
? const Text('Awaiting flavor...')
: Text(_flavor!, key: const ValueKey<String>('flavor')),
);
}
}
| flutter/dev/integration_tests/flavors/lib/main.dart/0 | {
"file_path": "flutter/dev/integration_tests/flavors/lib/main.dart",
"repo_id": "flutter",
"token_count": 393
} | 562 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| flutter/dev/integration_tests/flavors/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "flutter/dev/integration_tests/flavors/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "flutter",
"token_count": 32
} | 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.
package io.flutter.demo.gallery;
import android.os.ConditionVariable;
import androidx.annotation.NonNull;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
/** Instrumentation for testing using Android Espresso framework. */
public class FlutterGalleryInstrumentation implements MethodCallHandler {
private final ConditionVariable testFinished = new ConditionVariable();
private volatile boolean testSuccessful;
FlutterGalleryInstrumentation(@NonNull BinaryMessenger messenger) {
new MethodChannel(messenger, "io.flutter.demo.gallery/TestLifecycleListener")
.setMethodCallHandler(this);
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
testSuccessful = call.method.equals("success");
testFinished.open();
result.success(null);
}
public boolean isTestSuccessful() {
return testSuccessful;
}
public void waitForTestToFinish() throws Exception {
testFinished.block();
}
}
| flutter/dev/integration_tests/flutter_gallery/android/app/src/main/java/io/flutter/demo/gallery/FlutterGalleryInstrumentation.java/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/android/app/src/main/java/io/flutter/demo/gallery/FlutterGalleryInstrumentation.java",
"repo_id": "flutter",
"token_count": 386
} | 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';
import '../gallery/demo.dart';
class ImagesDemo extends StatelessWidget {
const ImagesDemo({super.key});
static const String routeName = '/images';
@override
Widget build(BuildContext context) {
return TabbedComponentDemoScaffold(
title: 'Animated images',
demos: <ComponentDemoTabData>[
ComponentDemoTabData(
tabName: 'WEBP',
description: '',
exampleCodeTag: 'animated_image',
demoWidget: Semantics(
label: 'Example of animated WEBP',
child: Image.asset(
'animated_images/animated_flutter_stickers.webp',
package: 'flutter_gallery_assets',
),
),
),
ComponentDemoTabData(
tabName: 'GIF',
description: '',
exampleCodeTag: 'animated_image',
demoWidget: Semantics(
label: 'Example of animated GIF',
child: Image.asset(
'animated_images/animated_flutter_lgtm.gif',
package: 'flutter_gallery_assets',
),
),
),
],
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/images_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/images_demo.dart",
"repo_id": "flutter",
"token_count": 595
} | 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';
import '../../gallery/demo.dart';
enum GridDemoTileStyle {
imageOnly,
oneLine,
twoLine
}
typedef BannerTapCallback = void Function(Photo photo);
const double _kMinFlingVelocity = 800.0;
const String _kGalleryAssetsPackage = 'flutter_gallery_assets';
class Photo {
Photo({
this.assetName,
this.assetPackage,
this.title,
this.caption,
this.isFavorite = false,
});
final String? assetName;
final String? assetPackage;
final String? title;
final String? caption;
bool isFavorite;
String? get tag => assetName; // Assuming that all asset names are unique.
bool get isValid => assetName != null && title != null && caption != null;
}
class GridPhotoViewer extends StatefulWidget {
const GridPhotoViewer({ super.key, this.photo });
final Photo? photo;
@override
State<GridPhotoViewer> createState() => _GridPhotoViewerState();
}
class _GridTitleText extends StatelessWidget {
const _GridTitleText(this.text);
final String? text;
@override
Widget build(BuildContext context) {
return FittedBox(
fit: BoxFit.scaleDown,
alignment: Alignment.centerLeft,
child: Text(text!),
);
}
}
class _GridPhotoViewerState extends State<GridPhotoViewer> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<Offset> _flingAnimation;
Offset _offset = Offset.zero;
double _scale = 1.0;
late Offset _normalizedOffset;
late double _previousScale;
@override
void initState() {
super.initState();
_controller = AnimationController(vsync: this)
..addListener(_handleFlingAnimation);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
// The maximum offset value is 0,0. If the size of this renderer's box is w,h
// then the minimum offset value is w - _scale * w, h - _scale * h.
Offset _clampOffset(Offset offset) {
final Size size = context.size!;
final Offset minOffset = Offset(size.width, size.height) * (1.0 - _scale);
return Offset(
offset.dx.clamp(minOffset.dx, 0.0),
offset.dy.clamp(minOffset.dy, 0.0),
);
}
void _handleFlingAnimation() {
setState(() {
_offset = _flingAnimation.value;
});
}
void _handleOnScaleStart(ScaleStartDetails details) {
setState(() {
_previousScale = _scale;
_normalizedOffset = (details.focalPoint - _offset) / _scale;
// The fling animation stops if an input gesture starts.
_controller.stop();
});
}
void _handleOnScaleUpdate(ScaleUpdateDetails details) {
setState(() {
_scale = (_previousScale * details.scale).clamp(1.0, 4.0);
// Ensure that image location under the focal point stays in the same place despite scaling.
_offset = _clampOffset(details.focalPoint - _normalizedOffset * _scale);
});
}
void _handleOnScaleEnd(ScaleEndDetails details) {
final double magnitude = details.velocity.pixelsPerSecond.distance;
if (magnitude < _kMinFlingVelocity) {
return;
}
final Offset direction = details.velocity.pixelsPerSecond / magnitude;
final double distance = (Offset.zero & context.size!).shortestSide;
_flingAnimation = _controller.drive(Tween<Offset>(
begin: _offset,
end: _clampOffset(_offset + direction * distance),
));
_controller
..value = 0.0
..fling(velocity: magnitude / 1000.0);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onScaleStart: _handleOnScaleStart,
onScaleUpdate: _handleOnScaleUpdate,
onScaleEnd: _handleOnScaleEnd,
child: ClipRect(
child: Transform(
transform: Matrix4.identity()
..translate(_offset.dx, _offset.dy)
..scale(_scale),
child: Image.asset(
widget.photo!.assetName!,
package: widget.photo!.assetPackage,
fit: BoxFit.cover,
),
),
),
);
}
}
class GridDemoPhotoItem extends StatelessWidget {
GridDemoPhotoItem({
super.key,
required this.photo,
required this.tileStyle,
required this.onBannerTap,
}) : assert(photo.isValid);
final Photo photo;
final GridDemoTileStyle tileStyle;
final BannerTapCallback onBannerTap; // User taps on the photo's header or footer.
void showPhoto(BuildContext context) {
Navigator.push(context, MaterialPageRoute<void>(
builder: (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(photo.title!),
),
body: SizedBox.expand(
child: Hero(
tag: photo.tag!,
child: GridPhotoViewer(photo: photo),
),
),
);
}
));
}
@override
Widget build(BuildContext context) {
final Widget image = Semantics(
label: '${photo.title} - ${photo.caption}',
child: GestureDetector(
onTap: () { showPhoto(context); },
child: Hero(
key: Key(photo.assetName!),
tag: photo.tag!,
child: Image.asset(
photo.assetName!,
package: photo.assetPackage,
fit: BoxFit.cover,
),
),
),
);
final IconData icon = photo.isFavorite ? Icons.star : Icons.star_border;
switch (tileStyle) {
case GridDemoTileStyle.imageOnly:
return image;
case GridDemoTileStyle.oneLine:
return GridTile(
header: GestureDetector(
onTap: () { onBannerTap(photo); },
child: GridTileBar(
title: _GridTitleText(photo.title),
backgroundColor: Colors.black45,
leading: Icon(
icon,
color: Colors.white,
),
),
),
child: image,
);
case GridDemoTileStyle.twoLine:
return GridTile(
footer: GestureDetector(
onTap: () { onBannerTap(photo); },
child: GridTileBar(
backgroundColor: Colors.black45,
title: _GridTitleText(photo.title),
subtitle: _GridTitleText(photo.caption),
trailing: Icon(
icon,
color: Colors.white,
),
),
),
child: image,
);
}
}
}
class GridListDemo extends StatefulWidget {
const GridListDemo({ super.key });
static const String routeName = '/material/grid-list';
@override
GridListDemoState createState() => GridListDemoState();
}
class GridListDemoState extends State<GridListDemo> {
GridDemoTileStyle _tileStyle = GridDemoTileStyle.twoLine;
List<Photo> photos = <Photo>[
Photo(
assetName: 'places/india_chennai_flower_market.png',
assetPackage: _kGalleryAssetsPackage,
title: 'Chennai',
caption: 'Flower Market',
),
Photo(
assetName: 'places/india_tanjore_bronze_works.png',
assetPackage: _kGalleryAssetsPackage,
title: 'Tanjore',
caption: 'Bronze Works',
),
Photo(
assetName: 'places/india_tanjore_market_merchant.png',
assetPackage: _kGalleryAssetsPackage,
title: 'Tanjore',
caption: 'Market',
),
Photo(
assetName: 'places/india_tanjore_thanjavur_temple.png',
assetPackage: _kGalleryAssetsPackage,
title: 'Tanjore',
caption: 'Thanjavur Temple',
),
Photo(
assetName: 'places/india_tanjore_thanjavur_temple_carvings.png',
assetPackage: _kGalleryAssetsPackage,
title: 'Tanjore',
caption: 'Thanjavur Temple',
),
Photo(
assetName: 'places/india_pondicherry_salt_farm.png',
assetPackage: _kGalleryAssetsPackage,
title: 'Pondicherry',
caption: 'Salt Farm',
),
Photo(
assetName: 'places/india_chennai_highway.png',
assetPackage: _kGalleryAssetsPackage,
title: 'Chennai',
caption: 'Scooters',
),
Photo(
assetName: 'places/india_chettinad_silk_maker.png',
assetPackage: _kGalleryAssetsPackage,
title: 'Chettinad',
caption: 'Silk Maker',
),
Photo(
assetName: 'places/india_chettinad_produce.png',
assetPackage: _kGalleryAssetsPackage,
title: 'Chettinad',
caption: 'Lunch Prep',
),
Photo(
assetName: 'places/india_tanjore_market_technology.png',
assetPackage: _kGalleryAssetsPackage,
title: 'Tanjore',
caption: 'Market',
),
Photo(
assetName: 'places/india_pondicherry_beach.png',
assetPackage: _kGalleryAssetsPackage,
title: 'Pondicherry',
caption: 'Beach',
),
Photo(
assetName: 'places/india_pondicherry_fisherman.png',
assetPackage: _kGalleryAssetsPackage,
title: 'Pondicherry',
caption: 'Fisherman',
),
];
void changeTileStyle(GridDemoTileStyle value) {
setState(() {
_tileStyle = value;
});
}
@override
Widget build(BuildContext context) {
final Orientation orientation = MediaQuery.of(context).orientation;
return Scaffold(
appBar: AppBar(
title: const Text('Grid list'),
actions: <Widget>[
MaterialDemoDocumentationButton(GridListDemo.routeName),
PopupMenuButton<GridDemoTileStyle>(
onSelected: changeTileStyle,
itemBuilder: (BuildContext context) => <PopupMenuItem<GridDemoTileStyle>>[
const PopupMenuItem<GridDemoTileStyle>(
value: GridDemoTileStyle.imageOnly,
child: Text('Image only'),
),
const PopupMenuItem<GridDemoTileStyle>(
value: GridDemoTileStyle.oneLine,
child: Text('One line'),
),
const PopupMenuItem<GridDemoTileStyle>(
value: GridDemoTileStyle.twoLine,
child: Text('Two line'),
),
],
),
],
),
body: Column(
children: <Widget>[
Expanded(
child: SafeArea(
top: false,
bottom: false,
child: GridView.count(
crossAxisCount: (orientation == Orientation.portrait) ? 2 : 3,
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
padding: const EdgeInsets.all(4.0),
childAspectRatio: (orientation == Orientation.portrait) ? 1.0 : 1.3,
children: photos.map<Widget>((Photo photo) {
return GridDemoPhotoItem(
photo: photo,
tileStyle: _tileStyle,
onBannerTap: (Photo photo) {
setState(() {
photo.isFavorite = !photo.isFavorite;
});
},
);
}).toList(),
),
),
),
],
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/material/grid_list_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/grid_list_demo.dart",
"repo_id": "flutter",
"token_count": 4930
} | 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 '../../gallery/demo.dart';
const String _text1 =
'Snackbars provide lightweight feedback about an operation by '
'showing a brief message at the bottom of the screen. Snackbars '
'can contain an action.';
const String _text2 =
'Snackbars should contain a single line of text directly related '
'to the operation performed. They cannot contain icons.';
const String _text3 =
'By default snackbars automatically disappear after a few seconds ';
class SnackBarDemo extends StatefulWidget {
const SnackBarDemo({ super.key });
static const String routeName = '/material/snack-bar';
@override
State<SnackBarDemo> createState() => _SnackBarDemoState();
}
class _SnackBarDemoState extends State<SnackBarDemo> {
int _snackBarIndex = 1;
Widget buildBody(BuildContext context) {
return SafeArea(
top: false,
bottom: false,
child: ListView(
padding: const EdgeInsets.all(24.0),
children: <Widget>[
const Text(_text1),
const Text(_text2),
Center(
child: ElevatedButton(
child: const Text('SHOW A SNACKBAR'),
onPressed: () {
final int thisSnackBarIndex = _snackBarIndex++;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('This is snackbar #$thisSnackBarIndex.'),
action: SnackBarAction(
label: 'ACTION',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("You pressed snackbar $thisSnackBarIndex's action."),
));
},
),
));
},
),
),
const Text(_text3),
]
.map<Widget>((Widget child) {
return Container(
margin: const EdgeInsets.symmetric(vertical: 12.0),
child: child,
);
})
.toList(),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Snackbar'),
actions: <Widget>[MaterialDemoDocumentationButton(SnackBarDemo.routeName)],
),
body: Builder(
// Create an inner BuildContext so that the snackBar onPressed methods
// can refer to the Scaffold with Scaffold.of().
builder: buildBody
),
floatingActionButton: FloatingActionButton(
tooltip: 'Create',
child: const Icon(Icons.add),
onPressed: () {
print('Floating Action Button was pressed');
},
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/material/snack_bar_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/snack_bar_demo.dart",
"repo_id": "flutter",
"token_count": 1273
} | 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/material.dart';
import 'package:intl/intl.dart';
import 'package:scoped_model/scoped_model.dart';
import 'colors.dart';
import 'expanding_bottom_sheet.dart';
import 'model/app_state_model.dart';
import 'model/product.dart';
const double _leftColumnWidth = 60.0;
class ShoppingCartPage extends StatefulWidget {
const ShoppingCartPage({super.key});
@override
State<ShoppingCartPage> createState() => _ShoppingCartPageState();
}
class _ShoppingCartPageState extends State<ShoppingCartPage> {
List<Widget> _createShoppingCartRows(AppStateModel model) {
return model.productsInCart.keys
.map((int id) => ShoppingCartRow(
product: model.getProductById(id),
quantity: model.productsInCart[id],
onPressed: () {
model.removeItemFromCart(id);
},
),
)
.toList();
}
@override
Widget build(BuildContext context) {
final ThemeData localTheme = Theme.of(context);
return Scaffold(
backgroundColor: kShrinePink50,
body: SafeArea(
child: ScopedModelDescendant<AppStateModel>(
builder: (BuildContext context, Widget? child, AppStateModel model) {
return Stack(
children: <Widget>[
ListView(
children: <Widget>[
Row(
children: <Widget>[
SizedBox(
width: _leftColumnWidth,
child: IconButton(
icon: const Icon(Icons.keyboard_arrow_down),
onPressed: () => ExpandingBottomSheet.of(context)!.close(),
),
),
Text(
'CART',
style: localTheme.textTheme.titleMedium!.copyWith(fontWeight: FontWeight.w600),
),
const SizedBox(width: 16.0),
Text('${model.totalCartQuantity} ITEMS'),
],
),
const SizedBox(height: 16.0),
Column(
children: _createShoppingCartRows(model),
),
ShoppingCartSummary(model: model),
const SizedBox(height: 100.0),
],
),
Positioned(
bottom: 16.0,
left: 16.0,
right: 16.0,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: kShrinePink100,
shape: const BeveledRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(7.0)),
),
),
child: const Padding(
padding: EdgeInsets.symmetric(vertical: 12.0),
child: Text('CLEAR CART'),
),
onPressed: () {
model.clearCart();
ExpandingBottomSheet.of(context)!.close();
},
),
),
],
);
},
),
),
);
}
}
class ShoppingCartSummary extends StatelessWidget {
const ShoppingCartSummary({super.key, this.model});
final AppStateModel? model;
@override
Widget build(BuildContext context) {
final TextStyle smallAmountStyle = Theme.of(context).textTheme.bodyMedium!.copyWith(color: kShrineBrown600);
final TextStyle? largeAmountStyle = Theme.of(context).textTheme.headlineMedium;
final NumberFormat formatter = NumberFormat.simpleCurrency(
decimalDigits: 2,
locale: Localizations.localeOf(context).toString(),
);
return Row(
children: <Widget>[
const SizedBox(width: _leftColumnWidth),
Expanded(
child: Padding(
padding: const EdgeInsets.only(right: 16.0),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
const Expanded(
child: Text('TOTAL'),
),
Text(
formatter.format(model!.totalCost),
style: largeAmountStyle,
),
],
),
const SizedBox(height: 16.0),
Row(
children: <Widget>[
const Expanded(
child: Text('Subtotal:'),
),
Text(
formatter.format(model!.subtotalCost),
style: smallAmountStyle,
),
],
),
const SizedBox(height: 4.0),
Row(
children: <Widget>[
const Expanded(
child: Text('Shipping:'),
),
Text(
formatter.format(model!.shippingCost),
style: smallAmountStyle,
),
],
),
const SizedBox(height: 4.0),
Row(
children: <Widget>[
const Expanded(
child: Text('Tax:'),
),
Text(
formatter.format(model!.tax),
style: smallAmountStyle,
),
],
),
],
),
),
),
],
);
}
}
class ShoppingCartRow extends StatelessWidget {
const ShoppingCartRow({
super.key,
required this.product,
required this.quantity,
this.onPressed,
});
final Product product;
final int? quantity;
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) {
final NumberFormat formatter = NumberFormat.simpleCurrency(
decimalDigits: 0,
locale: Localizations.localeOf(context).toString(),
);
final ThemeData localTheme = Theme.of(context);
return Padding(
padding: const EdgeInsets.only(bottom: 16.0),
child: Row(
key: ValueKey<int>(product.id),
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
width: _leftColumnWidth,
child: IconButton(
icon: const Icon(Icons.remove_circle_outline),
onPressed: onPressed,
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.only(right: 16.0),
child: Column(
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Image.asset(
product.assetName,
package: product.assetPackage,
fit: BoxFit.cover,
width: 75.0,
height: 75.0,
),
const SizedBox(width: 16.0),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: Text('Quantity: $quantity'),
),
Text('x ${formatter.format(product.price)}'),
],
),
Text(
product.name,
style: localTheme.textTheme.titleMedium!.copyWith(fontWeight: FontWeight.w600),
),
],
),
),
],
),
const SizedBox(height: 16.0),
const Divider(
color: kShrineBrown900,
height: 10.0,
),
],
),
),
),
],
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/shopping_cart.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/shopping_cart.dart",
"repo_id": "flutter",
"token_count": 5068
} | 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 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart' show defaultTargetPlatform;
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart' show timeDilation;
import 'package:scoped_model/scoped_model.dart';
import 'package:url_launcher/url_launcher.dart';
import '../demo/shrine/model/app_state_model.dart';
import 'demos.dart';
import 'home.dart';
import 'options.dart';
import 'scales.dart';
import 'themes.dart';
import 'updater.dart';
class GalleryApp extends StatefulWidget {
const GalleryApp({
super.key,
this.updateUrlFetcher,
this.enablePerformanceOverlay = true,
this.enableRasterCacheImagesCheckerboard = true,
this.enableOffscreenLayersCheckerboard = true,
this.onSendFeedback,
this.testMode = false,
});
final UpdateUrlFetcher? updateUrlFetcher;
final bool enablePerformanceOverlay;
final bool enableRasterCacheImagesCheckerboard;
final bool enableOffscreenLayersCheckerboard;
final VoidCallback? onSendFeedback;
final bool testMode;
@override
State<GalleryApp> createState() => _GalleryAppState();
}
class _GalleryAppState extends State<GalleryApp> {
GalleryOptions? _options;
Timer? _timeDilationTimer;
late final AppStateModel model = AppStateModel()..loadProducts();
Map<String, WidgetBuilder> _buildRoutes() {
// For a different example of how to set up an application routing table
// using named routes, consider the example in the Navigator class documentation:
// https://api.flutter.dev/flutter/widgets/Navigator-class.html
return <String, WidgetBuilder>{
for (final GalleryDemo demo in kAllGalleryDemos) demo.routeName: demo.buildRoute,
};
}
@override
void initState() {
super.initState();
_options = GalleryOptions(
themeMode: ThemeMode.system,
textScaleFactor: kAllGalleryTextScaleValues[0],
visualDensity: kAllGalleryVisualDensityValues[0],
timeDilation: timeDilation,
platform: defaultTargetPlatform,
);
}
@override
void reassemble() {
_options = _options!.copyWith(platform: defaultTargetPlatform);
super.reassemble();
}
@override
void dispose() {
_timeDilationTimer?.cancel();
_timeDilationTimer = null;
super.dispose();
}
void _handleOptionsChanged(GalleryOptions newOptions) {
setState(() {
if (_options!.timeDilation != newOptions.timeDilation) {
_timeDilationTimer?.cancel();
_timeDilationTimer = null;
if (newOptions.timeDilation > 1.0) {
// We delay the time dilation change long enough that the user can see
// that UI has started reacting and then we slam on the brakes so that
// they see that the time is in fact now dilated.
_timeDilationTimer = Timer(const Duration(milliseconds: 150), () {
timeDilation = newOptions.timeDilation;
});
} else {
timeDilation = newOptions.timeDilation;
}
}
_options = newOptions;
});
}
Widget _applyTextScaleFactor(Widget child) {
return Builder(
builder: (BuildContext context) {
final double? textScaleFactor = _options!.textScaleFactor!.scale;
return MediaQuery.withClampedTextScaling(
minScaleFactor: textScaleFactor ?? 0.0,
maxScaleFactor: textScaleFactor ?? double.infinity,
child: child,
);
},
);
}
@override
Widget build(BuildContext context) {
Widget home = GalleryHome(
testMode: widget.testMode,
optionsPage: GalleryOptionsPage(
options: _options,
onOptionsChanged: _handleOptionsChanged,
onSendFeedback: widget.onSendFeedback ?? () {
launchUrl(Uri.parse('https://github.com/flutter/flutter/issues/new/choose'), mode: LaunchMode.externalApplication);
},
),
);
if (widget.updateUrlFetcher != null) {
home = Updater(
updateUrlFetcher: widget.updateUrlFetcher!,
child: home,
);
}
return ScopedModel<AppStateModel>(
model: model,
child: MaterialApp(
// The automatically applied scrollbars on desktop can cause a crash for
// demos where many scrollables are all attached to the same
// PrimaryScrollController. The gallery needs to be migrated before
// enabling this. https://github.com/flutter/gallery/issues/523
scrollBehavior: const MaterialScrollBehavior().copyWith(scrollbars: false),
theme: kLightGalleryTheme.copyWith(platform: _options!.platform, visualDensity: _options!.visualDensity!.visualDensity),
darkTheme: kDarkGalleryTheme.copyWith(platform: _options!.platform, visualDensity: _options!.visualDensity!.visualDensity),
themeMode: _options!.themeMode,
title: 'Flutter Gallery',
color: Colors.grey,
showPerformanceOverlay: _options!.showPerformanceOverlay,
checkerboardOffscreenLayers: _options!.showOffscreenLayersCheckerboard,
checkerboardRasterCacheImages: _options!.showRasterCacheImagesCheckerboard,
routes: _buildRoutes(),
builder: (BuildContext context, Widget? child) {
return Directionality(
textDirection: _options!.textDirection,
child: _applyTextScaleFactor(
// Specifically use a blank Cupertino theme here and do not transfer
// over the Material primary color etc except the brightness to
// showcase standard iOS looks.
Builder(builder: (BuildContext context) {
return CupertinoTheme(
data: CupertinoThemeData(
brightness: Theme.of(context).brightness,
),
child: child!,
);
}),
),
);
},
home: home,
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/gallery/app.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/gallery/app.dart",
"repo_id": "flutter",
"token_count": 2292
} | 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 'dart:async';
import 'package:flutter/rendering.dart';
import 'package:flutter_goldens/flutter_goldens.dart' as flutter_goldens show testExecutable;
import 'package:flutter_test/flutter_test.dart';
Future<void> testExecutable(FutureOr<void> Function() testMain) {
// Enable extra checks since this package exercises a lot of the framework.
debugCheckIntrinsicSizes = true;
// Make tap() et al fail if the given finder specifies a widget that would not
// receive the event.
WidgetController.hitTestWarningShouldBeFatal = true;
// Enable golden file testing using Skia Gold.
return flutter_goldens.testExecutable(testMain);
}
| flutter/dev/integration_tests/flutter_gallery/test/flutter_test_config.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/test/flutter_test_config.dart",
"repo_id": "flutter",
"token_count": 238
} | 570 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.integration.platformviews;
import android.content.Context;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;
import io.flutter.plugin.platform.PlatformViewFactory;
public class SimpleViewFactory extends PlatformViewFactory {
final DartExecutor executor;
public SimpleViewFactory(DartExecutor executor) {
super(null);
this.executor = executor;
}
@Override
public PlatformView create(Context context, int id, Object params) {
MethodChannel methodChannel = new MethodChannel(executor, "simple_view/" + id);
return new SimplePlatformView(context, methodChannel);
}
}
| flutter/dev/integration_tests/hybrid_android_views/android/app/src/main/java/io/flutter/integration/androidviews/SimpleViewFactory.java/0 | {
"file_path": "flutter/dev/integration_tests/hybrid_android_views/android/app/src/main/java/io/flutter/integration/androidviews/SimpleViewFactory.java",
"repo_id": "flutter",
"token_count": 280
} | 571 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'android_platform_view.dart';
import 'future_data_handler.dart';
import 'page.dart';
class NestedViewEventPage extends PageWidget {
const NestedViewEventPage({Key? key})
: super('Nested View Event Tests', const ValueKey<String>('NestedViewEventTile'), key: key);
@override
Widget build(BuildContext context) => const NestedViewEventBody();
}
class NestedViewEventBody extends StatefulWidget {
const NestedViewEventBody({super.key});
@override
State<NestedViewEventBody> createState() => NestedViewEventBodyState();
}
enum _LastTestStatus {
pending,
success,
error
}
class NestedViewEventBodyState extends State<NestedViewEventBody> {
MethodChannel? viewChannel;
_LastTestStatus _lastTestStatus = _LastTestStatus.pending;
String? lastError;
int? id;
int nestedViewClickCount = 0;
bool showPlatformView = true;
bool useHybridComposition = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Nested view event'),
),
body: Column(
children: <Widget>[
SizedBox(
height: 300,
child: Stack(
alignment: Alignment.topCenter,
children: <Widget>[
if (showPlatformView)
AndroidPlatformView(
key: const ValueKey<String>('PlatformView'),
viewType: 'simple_view',
onPlatformViewCreated: onPlatformViewCreated,
useHybridComposition: useHybridComposition,
),
// The overlapping widget stabilizes the view tree by ensuring
// that there is widget content on top of the platform view.
// Without this widget, we rely on the UI elements down below
// to "incidentally" draw on top of the PlatformView which
// is not a reliable behavior as we eliminate non-visible
// rendering operations throughout the framework and engine.
const Positioned(
top: 50,
child: Text('overlapping widget',
style: TextStyle(color: Colors.yellow),
),
),
],
),
),
if (_lastTestStatus != _LastTestStatus.pending) _statusWidget(),
if (viewChannel != null) ... <Widget>[
Row(
children: <Widget>[
Expanded(
child: ElevatedButton(
key: const ValueKey<String>('ShowAlertDialog'),
onPressed: onShowAlertDialogPressed,
child: const Text('SHOW ALERT DIALOG'),
),
),
Expanded(
child: ElevatedButton(
key: const ValueKey<String>('TogglePlatformView'),
onPressed: onTogglePlatformView,
child: const Text('TOGGLE PLATFORM VIEW'),
),
),
],
),
Row(
children: <Widget>[
Expanded(
child: ElevatedButton(
key: const ValueKey<String>('ToggleHybridComposition'),
child: const Text('TOGGLE HC'),
onPressed: () {
setState(() {
useHybridComposition = !useHybridComposition;
});
},
),
),
Expanded(
child: ElevatedButton(
key: const ValueKey<String>('AddChildView'),
onPressed: onChildViewPressed,
child: const Text('ADD CHILD VIEW'),
),
),
Expanded(
child: ElevatedButton(
key: const ValueKey<String>('TapChildView'),
onPressed: onTapChildViewPressed,
child: const Text('TAP CHILD VIEW'),
),
),
],
),
if (nestedViewClickCount > 0)
Text(
'Click count: $nestedViewClickCount',
key: const ValueKey<String>('NestedViewClickCount'),
),
],
],
),
);
}
Widget _statusWidget() {
assert(_lastTestStatus != _LastTestStatus.pending);
final String message = _lastTestStatus == _LastTestStatus.success ? 'Success' : lastError!;
return ColoredBox(
color: _lastTestStatus == _LastTestStatus.success ? Colors.green : Colors.red,
child: Text(
message,
key: const ValueKey<String>('Status'),
style: TextStyle(
color: _lastTestStatus == _LastTestStatus.error ? Colors.yellow : null,
),
),
);
}
Future<void> onShowAlertDialogPressed() async {
if (_lastTestStatus != _LastTestStatus.pending) {
setState(() {
_lastTestStatus = _LastTestStatus.pending;
});
}
try {
await viewChannel!.invokeMethod<void>('showAndHideAlertDialog');
setState(() {
_lastTestStatus = _LastTestStatus.success;
});
} catch (e) {
setState(() {
_lastTestStatus = _LastTestStatus.error;
lastError = '$e';
});
}
}
Future<void> onTogglePlatformView() async {
setState(() {
showPlatformView = !showPlatformView;
});
}
Future<void> onChildViewPressed() async {
try {
await viewChannel!.invokeMethod<void>('addChildViewAndWaitForClick');
setState(() {
nestedViewClickCount++;
});
} catch (e) {
setState(() {
_lastTestStatus = _LastTestStatus.error;
lastError = '$e';
});
}
}
Future<void> onTapChildViewPressed() async {
await Future<void>.delayed(const Duration(seconds: 1));
// Dispatch a tap event on the child view inside the platform view.
//
// Android mutates `MotionEvent` instances, so in this case *do not* dispatch
// new instances as it won't cover the `MotionEventTracker` class in the embedding
// which tracks events.
//
// See the issue this prevents: https://github.com/flutter/flutter/issues/61169
await Process.run('input', const <String>['tap', '250', '550']);
}
void onPlatformViewCreated(int id) {
this.id = id;
setState(() {
viewChannel = MethodChannel('simple_view/$id');
});
driverDataHandler.registerHandler('hierarchy')
.complete(() async => (await channel.invokeMethod<String>('getViewHierarchy'))!);
}
}
| flutter/dev/integration_tests/hybrid_android_views/lib/nested_view_event_page.dart/0 | {
"file_path": "flutter/dev/integration_tests/hybrid_android_views/lib/nested_view_event_page.dart",
"repo_id": "flutter",
"token_count": 3236
} | 572 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Flutter/Flutter.h>
#import "AppDelegate.h"
#import "HybridViewController.h"
@interface HybridViewController ()
@end
static NSString *_kChannel = @"increment";
static NSString *_kPing = @"ping";
@implementation HybridViewController {
FlutterBasicMessageChannel *_messageChannel;
}
- (FlutterEngine *)engine {
return [(AppDelegate *)[[UIApplication sharedApplication] delegate] engine];
}
- (FlutterBasicMessageChannel *)reloadMessageChannel {
return [(AppDelegate *)[[UIApplication sharedApplication] delegate]
reloadMessageChannel];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"Hybrid Flutter/Native";
UIStackView *stackView = [[UIStackView alloc] initWithFrame:self.view.frame];
stackView.axis = UILayoutConstraintAxisVertical;
stackView.distribution = UIStackViewDistributionFillEqually;
stackView.layoutMargins = UIEdgeInsetsMake(0, 0, 50, 0);
stackView.layoutMarginsRelativeArrangement = YES;
[self.view addSubview:stackView];
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]
initWithTitle:@"Back"
style:UIBarButtonItemStylePlain
target:nil
action:nil];
NativeViewController *nativeViewController =
[[NativeViewController alloc] initWithDelegate:self];
[self addChildViewController:nativeViewController];
[stackView addArrangedSubview:nativeViewController.view];
[nativeViewController didMoveToParentViewController:self];
_flutterViewController =
[[FlutterViewController alloc] initWithEngine:[self engine]
nibName:nil
bundle:nil];
[[self reloadMessageChannel] sendMessage:@"hybrid"];
_messageChannel = [[FlutterBasicMessageChannel alloc]
initWithName:_kChannel
binaryMessenger:_flutterViewController.binaryMessenger
codec:[FlutterStringCodec sharedInstance]];
[self addChildViewController:_flutterViewController];
[stackView addArrangedSubview:_flutterViewController.view];
[_flutterViewController didMoveToParentViewController:self];
__weak NativeViewController *weakNativeViewController = nativeViewController;
[_messageChannel setMessageHandler:^(id message, FlutterReply reply) {
[weakNativeViewController didReceiveIncrement];
reply(@"");
}];
}
- (void)didTapIncrementButton {
[_messageChannel sendMessage:_kPing];
}
@end
| flutter/dev/integration_tests/ios_host_app/Host/HybridViewController.m/0 | {
"file_path": "flutter/dev/integration_tests/ios_host_app/Host/HybridViewController.m",
"repo_id": "flutter",
"token_count": 1056
} | 573 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.3.0'
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
tasks.register("clean", Delete) {
delete rootProject.buildDir
}
| flutter/dev/integration_tests/module_host_with_custom_build_v2_embedding/build.gradle/0 | {
"file_path": "flutter/dev/integration_tests/module_host_with_custom_build_v2_embedding/build.gradle",
"repo_id": "flutter",
"token_count": 184
} | 574 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
export 'package:gallery/demos/cupertino/cupertino_activity_indicator_demo.dart';
export 'package:gallery/demos/cupertino/cupertino_alert_demo.dart';
export 'package:gallery/demos/cupertino/cupertino_button_demo.dart';
export 'package:gallery/demos/cupertino/cupertino_context_menu_demo.dart';
export 'package:gallery/demos/cupertino/cupertino_navigation_bar_demo.dart';
export 'package:gallery/demos/cupertino/cupertino_picker_demo.dart';
export 'package:gallery/demos/cupertino/cupertino_scrollbar_demo.dart';
export 'package:gallery/demos/cupertino/cupertino_search_text_field_demo.dart';
export 'package:gallery/demos/cupertino/cupertino_segmented_control_demo.dart';
export 'package:gallery/demos/cupertino/cupertino_slider_demo.dart';
export 'package:gallery/demos/cupertino/cupertino_switch_demo.dart';
export 'package:gallery/demos/cupertino/cupertino_tab_bar_demo.dart';
export 'package:gallery/demos/cupertino/cupertino_text_field_demo.dart';
| flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_demos.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_demos.dart",
"repo_id": "flutter",
"token_count": 403
} | 575 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import '../../gallery_localizations.dart';
import 'material_demo_types.dart';
class ButtonDemo extends StatelessWidget {
const ButtonDemo({super.key, required this.type});
final ButtonDemoType type;
String _title(BuildContext context) {
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
switch (type) {
case ButtonDemoType.text:
return localizations.demoTextButtonTitle;
case ButtonDemoType.elevated:
return localizations.demoElevatedButtonTitle;
case ButtonDemoType.outlined:
return localizations.demoOutlinedButtonTitle;
case ButtonDemoType.toggle:
return localizations.demoToggleButtonTitle;
case ButtonDemoType.floating:
return localizations.demoFloatingButtonTitle;
}
}
@override
Widget build(BuildContext context) {
Widget? buttons;
switch (type) {
case ButtonDemoType.text:
buttons = _TextButtonDemo();
case ButtonDemoType.elevated:
buttons = _ElevatedButtonDemo();
case ButtonDemoType.outlined:
buttons = _OutlinedButtonDemo();
case ButtonDemoType.toggle:
buttons = _ToggleButtonsDemo();
case ButtonDemoType.floating:
buttons = _FloatingActionButtonDemo();
}
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(_title(context)),
),
body: buttons,
);
}
}
// BEGIN buttonDemoText
class _TextButtonDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextButton(
onPressed: () {},
child: Text(localizations.buttonText),
),
const SizedBox(width: 12),
TextButton.icon(
icon: const Icon(Icons.add, size: 18),
label: Text(localizations.buttonText),
onPressed: () {},
),
],
),
const SizedBox(height: 12),
// Disabled buttons
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextButton(
onPressed: null,
child: Text(localizations.buttonText),
),
const SizedBox(width: 12),
TextButton.icon(
icon: const Icon(Icons.add, size: 18),
label: Text(localizations.buttonText),
onPressed: null,
),
],
),
],
);
}
}
// END
// BEGIN buttonDemoElevated
class _ElevatedButtonDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () {},
child: Text(localizations.buttonText),
),
const SizedBox(width: 12),
ElevatedButton.icon(
icon: const Icon(Icons.add, size: 18),
label: Text(localizations.buttonText),
onPressed: () {},
),
],
),
const SizedBox(height: 12),
// Disabled buttons
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: null,
child: Text(localizations.buttonText),
),
const SizedBox(width: 12),
ElevatedButton.icon(
icon: const Icon(Icons.add, size: 18),
label: Text(localizations.buttonText),
onPressed: null,
),
],
),
],
);
}
}
// END
// BEGIN buttonDemoOutlined
class _OutlinedButtonDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
OutlinedButton(
onPressed: () {},
child: Text(localizations.buttonText),
),
const SizedBox(width: 12),
OutlinedButton.icon(
icon: const Icon(Icons.add, size: 18),
label: Text(localizations.buttonText),
onPressed: () {},
),
],
),
const SizedBox(height: 12),
// Disabled buttons
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
OutlinedButton(
onPressed: null,
child: Text(localizations.buttonText),
),
const SizedBox(width: 12),
OutlinedButton.icon(
icon: const Icon(Icons.add, size: 18),
label: Text(localizations.buttonText),
onPressed: null,
),
],
),
],
);
}
}
// END
// BEGIN buttonDemoToggle
class _ToggleButtonsDemo extends StatefulWidget {
@override
_ToggleButtonsDemoState createState() => _ToggleButtonsDemoState();
}
class _ToggleButtonsDemoState extends State<_ToggleButtonsDemo>
with RestorationMixin {
final List<RestorableBool> isSelected = <RestorableBool>[
RestorableBool(false),
RestorableBool(true),
RestorableBool(false),
];
@override
String get restorationId => 'toggle_button_demo';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(isSelected[0], 'first_item');
registerForRestoration(isSelected[1], 'second_item');
registerForRestoration(isSelected[2], 'third_item');
}
@override
void dispose() {
for (final RestorableBool restorableBool in isSelected) {
restorableBool.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ToggleButtons(
onPressed: (int index) {
setState(() {
isSelected[index].value = !isSelected[index].value;
});
},
isSelected: isSelected.map((RestorableBool element) => element.value).toList(),
children: const <Widget>[
Icon(Icons.format_bold),
Icon(Icons.format_italic),
Icon(Icons.format_underline),
],
),
const SizedBox(height: 12),
// Disabled toggle buttons
ToggleButtons(
isSelected: isSelected.map((RestorableBool element) => element.value).toList(),
children: const <Widget>[
Icon(Icons.format_bold),
Icon(Icons.format_italic),
Icon(Icons.format_underline),
],
),
],
),
);
}
}
// END
// BEGIN buttonDemoFloating
class _FloatingActionButtonDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
return Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FloatingActionButton(
onPressed: () {},
tooltip: localizations.buttonTextCreate,
child: const Icon(Icons.add),
),
const SizedBox(width: 12),
FloatingActionButton.extended(
icon: const Icon(Icons.add),
label: Text(localizations.buttonTextCreate),
onPressed: () {},
),
],
),
);
}
}
// END
| flutter/dev/integration_tests/new_gallery/lib/demos/material/button_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/material/button_demo.dart",
"repo_id": "flutter",
"token_count": 3866
} | 576 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../../gallery_localizations.dart';
import 'material_demo_types.dart';
class SlidersDemo extends StatelessWidget {
const SlidersDemo({super.key, required this.type});
final SlidersDemoType type;
String _title(BuildContext context) {
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
switch (type) {
case SlidersDemoType.sliders:
return localizations.demoSlidersTitle;
case SlidersDemoType.rangeSliders:
return localizations.demoRangeSlidersTitle;
case SlidersDemoType.customSliders:
return localizations.demoCustomSlidersTitle;
}
}
@override
Widget build(BuildContext context) {
Widget sliders;
switch (type) {
case SlidersDemoType.sliders:
sliders = _Sliders();
case SlidersDemoType.rangeSliders:
sliders = _RangeSliders();
case SlidersDemoType.customSliders:
sliders = _CustomSliders();
}
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(_title(context)),
),
body: sliders,
);
}
}
// BEGIN slidersDemo
class _Sliders extends StatefulWidget {
@override
_SlidersState createState() => _SlidersState();
}
class _SlidersState extends State<_Sliders> with RestorationMixin {
final RestorableDouble _continuousValue = RestorableDouble(25);
final RestorableDouble _discreteValue = RestorableDouble(20);
@override
String get restorationId => 'slider_demo';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_continuousValue, 'continuous_value');
registerForRestoration(_discreteValue, 'discrete_value');
}
@override
void dispose() {
_continuousValue.dispose();
_discreteValue.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 40),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Semantics(
label: localizations.demoSlidersEditableNumericalValue,
child: SizedBox(
width: 64,
height: 48,
child: TextField(
textAlign: TextAlign.center,
onSubmitted: (String value) {
final double? newValue = double.tryParse(value);
if (newValue != null &&
newValue != _continuousValue.value) {
setState(() {
_continuousValue.value =
newValue.clamp(0, 100) as double;
});
}
},
keyboardType: TextInputType.number,
controller: TextEditingController(
text: _continuousValue.value.toStringAsFixed(0),
),
),
),
),
Slider(
value: _continuousValue.value,
max: 100,
onChanged: (double value) {
setState(() {
_continuousValue.value = value;
});
},
),
// Disabled slider
Slider(
value: _continuousValue.value,
max: 100,
onChanged: null,
),
Text(localizations
.demoSlidersContinuousWithEditableNumericalValue),
],
),
const SizedBox(height: 80),
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Slider(
value: _discreteValue.value,
max: 200,
divisions: 5,
label: _discreteValue.value.round().toString(),
onChanged: (double value) {
setState(() {
_discreteValue.value = value;
});
},
),
// Disabled slider
Slider(
value: _discreteValue.value,
max: 200,
divisions: 5,
label: _discreteValue.value.round().toString(),
onChanged: null,
),
Text(localizations.demoSlidersDiscrete),
],
),
],
),
);
}
}
// END
// BEGIN rangeSlidersDemo
class _RangeSliders extends StatefulWidget {
@override
_RangeSlidersState createState() => _RangeSlidersState();
}
class _RangeSlidersState extends State<_RangeSliders> with RestorationMixin {
final RestorableDouble _continuousStartValue = RestorableDouble(25);
final RestorableDouble _continuousEndValue = RestorableDouble(75);
final RestorableDouble _discreteStartValue = RestorableDouble(40);
final RestorableDouble _discreteEndValue = RestorableDouble(120);
@override
String get restorationId => 'range_sliders_demo';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_continuousStartValue, 'continuous_start_value');
registerForRestoration(_continuousEndValue, 'continuous_end_value');
registerForRestoration(_discreteStartValue, 'discrete_start_value');
registerForRestoration(_discreteEndValue, 'discrete_end_value');
}
@override
void dispose() {
_continuousStartValue.dispose();
_continuousEndValue.dispose();
_discreteStartValue.dispose();
_discreteEndValue.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final RangeValues continuousValues = RangeValues(
_continuousStartValue.value,
_continuousEndValue.value,
);
final RangeValues discreteValues = RangeValues(
_discreteStartValue.value,
_discreteEndValue.value,
);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 40),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
RangeSlider(
values: continuousValues,
max: 100,
onChanged: (RangeValues values) {
setState(() {
_continuousStartValue.value = values.start;
_continuousEndValue.value = values.end;
});
},
),
// Disabled range slider
RangeSlider(
values: continuousValues,
max: 100,
onChanged: null,
),
Text(GalleryLocalizations.of(context)!.demoSlidersContinuous),
],
),
const SizedBox(height: 80),
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
RangeSlider(
values: discreteValues,
max: 200,
divisions: 5,
labels: RangeLabels(
discreteValues.start.round().toString(),
discreteValues.end.round().toString(),
),
onChanged: (RangeValues values) {
setState(() {
_discreteStartValue.value = values.start;
_discreteEndValue.value = values.end;
});
},
),
// Disabled range slider
RangeSlider(
values: discreteValues,
max: 200,
divisions: 5,
labels: RangeLabels(
discreteValues.start.round().toString(),
discreteValues.end.round().toString(),
),
onChanged: null,
),
Text(GalleryLocalizations.of(context)!.demoSlidersDiscrete),
],
),
],
),
);
}
}
// END
// BEGIN customSlidersDemo
Path _downTriangle(double size, Offset thumbCenter, {bool invert = false}) {
final Path thumbPath = Path();
final double height = math.sqrt(3) / 2;
final double centerHeight = size * height / 3;
final double halfSize = size / 2;
final int sign = invert ? -1 : 1;
thumbPath.moveTo(
thumbCenter.dx - halfSize, thumbCenter.dy + sign * centerHeight);
thumbPath.lineTo(thumbCenter.dx, thumbCenter.dy - 2 * sign * centerHeight);
thumbPath.lineTo(
thumbCenter.dx + halfSize, thumbCenter.dy + sign * centerHeight);
thumbPath.close();
return thumbPath;
}
Path _rightTriangle(double size, Offset thumbCenter, {bool invert = false}) {
final Path thumbPath = Path();
final double halfSize = size / 2;
final int sign = invert ? -1 : 1;
thumbPath.moveTo(thumbCenter.dx + halfSize * sign, thumbCenter.dy);
thumbPath.lineTo(thumbCenter.dx - halfSize * sign, thumbCenter.dy - size);
thumbPath.lineTo(thumbCenter.dx - halfSize * sign, thumbCenter.dy + size);
thumbPath.close();
return thumbPath;
}
Path _upTriangle(double size, Offset thumbCenter) =>
_downTriangle(size, thumbCenter, invert: true);
Path _leftTriangle(double size, Offset thumbCenter) =>
_rightTriangle(size, thumbCenter, invert: true);
class _CustomRangeThumbShape extends RangeSliderThumbShape {
const _CustomRangeThumbShape();
static const double _thumbSize = 4;
static const double _disabledThumbSize = 3;
@override
Size getPreferredSize(bool isEnabled, bool isDiscrete) {
return isEnabled
? const Size.fromRadius(_thumbSize)
: const Size.fromRadius(_disabledThumbSize);
}
static final Animatable<double> sizeTween = Tween<double>(
begin: _disabledThumbSize,
end: _thumbSize,
);
@override
void paint(
PaintingContext context,
Offset center, {
required Animation<double> activationAnimation,
required Animation<double> enableAnimation,
bool isDiscrete = false,
bool isEnabled = false,
bool? isOnTop,
TextDirection? textDirection,
required SliderThemeData sliderTheme,
Thumb? thumb,
bool? isPressed,
}) {
final Canvas canvas = context.canvas;
final ColorTween colorTween = ColorTween(
begin: sliderTheme.disabledThumbColor,
end: sliderTheme.thumbColor,
);
final double size = _thumbSize * sizeTween.evaluate(enableAnimation);
Path thumbPath;
switch (textDirection!) {
case TextDirection.rtl:
switch (thumb!) {
case Thumb.start:
thumbPath = _rightTriangle(size, center);
case Thumb.end:
thumbPath = _leftTriangle(size, center);
}
case TextDirection.ltr:
switch (thumb!) {
case Thumb.start:
thumbPath = _leftTriangle(size, center);
case Thumb.end:
thumbPath = _rightTriangle(size, center);
}
}
canvas.drawPath(
thumbPath,
Paint()..color = colorTween.evaluate(enableAnimation)!,
);
}
}
class _CustomThumbShape extends SliderComponentShape {
const _CustomThumbShape();
static const double _thumbSize = 4;
static const double _disabledThumbSize = 3;
@override
Size getPreferredSize(bool isEnabled, bool isDiscrete) {
return isEnabled
? const Size.fromRadius(_thumbSize)
: const Size.fromRadius(_disabledThumbSize);
}
static final Animatable<double> sizeTween = Tween<double>(
begin: _disabledThumbSize,
end: _thumbSize,
);
@override
void paint(
PaintingContext context,
Offset thumbCenter, {
Animation<double>? activationAnimation,
required Animation<double> enableAnimation,
bool? isDiscrete,
TextPainter? labelPainter,
RenderBox? parentBox,
required SliderThemeData sliderTheme,
TextDirection? textDirection,
double? value,
double? textScaleFactor,
Size? sizeWithOverflow,
}) {
final Canvas canvas = context.canvas;
final ColorTween colorTween = ColorTween(
begin: sliderTheme.disabledThumbColor,
end: sliderTheme.thumbColor,
);
final double size = _thumbSize * sizeTween.evaluate(enableAnimation);
final Path thumbPath = _downTriangle(size, thumbCenter);
canvas.drawPath(
thumbPath,
Paint()..color = colorTween.evaluate(enableAnimation)!,
);
}
}
class _CustomValueIndicatorShape extends SliderComponentShape {
const _CustomValueIndicatorShape();
static const double _indicatorSize = 4;
static const double _disabledIndicatorSize = 3;
static const double _slideUpHeight = 40;
@override
Size getPreferredSize(bool isEnabled, bool isDiscrete) {
return Size.fromRadius(isEnabled ? _indicatorSize : _disabledIndicatorSize);
}
static final Animatable<double> sizeTween = Tween<double>(
begin: _disabledIndicatorSize,
end: _indicatorSize,
);
@override
void paint(
PaintingContext context,
Offset thumbCenter, {
required Animation<double> activationAnimation,
required Animation<double> enableAnimation,
bool? isDiscrete,
required TextPainter labelPainter,
RenderBox? parentBox,
required SliderThemeData sliderTheme,
TextDirection? textDirection,
double? value,
double? textScaleFactor,
Size? sizeWithOverflow,
}) {
final Canvas canvas = context.canvas;
final ColorTween enableColor = ColorTween(
begin: sliderTheme.disabledThumbColor,
end: sliderTheme.valueIndicatorColor,
);
final Tween<double> slideUpTween = Tween<double>(
begin: 0,
end: _slideUpHeight,
);
final double size = _indicatorSize * sizeTween.evaluate(enableAnimation);
final Offset slideUpOffset =
Offset(0, -slideUpTween.evaluate(activationAnimation));
final Path thumbPath = _upTriangle(size, thumbCenter + slideUpOffset);
final Color paintColor = enableColor
.evaluate(enableAnimation)!
.withAlpha((255 * activationAnimation.value).round());
canvas.drawPath(
thumbPath,
Paint()..color = paintColor,
);
canvas.drawLine(
thumbCenter,
thumbCenter + slideUpOffset,
Paint()
..color = paintColor
..style = PaintingStyle.stroke
..strokeWidth = 2);
labelPainter.paint(
canvas,
thumbCenter +
slideUpOffset +
Offset(-labelPainter.width / 2, -labelPainter.height - 4),
);
}
}
class _CustomSliders extends StatefulWidget {
@override
_CustomSlidersState createState() => _CustomSlidersState();
}
class _CustomSlidersState extends State<_CustomSliders> with RestorationMixin {
final RestorableDouble _continuousStartCustomValue = RestorableDouble(40);
final RestorableDouble _continuousEndCustomValue = RestorableDouble(160);
final RestorableDouble _discreteCustomValue = RestorableDouble(25);
@override
String get restorationId => 'custom_sliders_demo';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(
_continuousStartCustomValue, 'continuous_start_custom_value');
registerForRestoration(
_continuousEndCustomValue, 'continuous_end_custom_value');
registerForRestoration(_discreteCustomValue, 'discrete_custom_value');
}
@override
void dispose() {
_continuousStartCustomValue.dispose();
_continuousEndCustomValue.dispose();
_discreteCustomValue.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final RangeValues customRangeValue = RangeValues(
_continuousStartCustomValue.value,
_continuousEndCustomValue.value,
);
final ThemeData theme = Theme.of(context);
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 40),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SliderTheme(
data: theme.sliderTheme.copyWith(
trackHeight: 2,
activeTrackColor: Colors.deepPurple,
inactiveTrackColor:
theme.colorScheme.onSurface.withOpacity(0.5),
activeTickMarkColor:
theme.colorScheme.onSurface.withOpacity(0.7),
inactiveTickMarkColor:
theme.colorScheme.surface.withOpacity(0.7),
overlayColor: theme.colorScheme.onSurface.withOpacity(0.12),
thumbColor: Colors.deepPurple,
valueIndicatorColor: Colors.deepPurpleAccent,
thumbShape: const _CustomThumbShape(),
valueIndicatorShape: const _CustomValueIndicatorShape(),
valueIndicatorTextStyle: theme.textTheme.bodyLarge!
.copyWith(color: theme.colorScheme.onSurface),
),
child: Slider(
value: _discreteCustomValue.value,
max: 200,
divisions: 5,
semanticFormatterCallback: (double value) =>
value.round().toString(),
label: '${_discreteCustomValue.value.round()}',
onChanged: (double value) {
setState(() {
_discreteCustomValue.value = value;
});
},
),
),
Text(localizations.demoSlidersDiscreteSliderWithCustomTheme),
],
),
const SizedBox(height: 80),
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SliderTheme(
data: const SliderThemeData(
trackHeight: 2,
activeTrackColor: Colors.deepPurple,
inactiveTrackColor: Colors.black26,
activeTickMarkColor: Colors.white70,
inactiveTickMarkColor: Colors.black,
overlayColor: Colors.black12,
thumbColor: Colors.deepPurple,
rangeThumbShape: _CustomRangeThumbShape(),
showValueIndicator: ShowValueIndicator.never,
),
child: RangeSlider(
values: customRangeValue,
max: 200,
onChanged: (RangeValues values) {
setState(() {
_continuousStartCustomValue.value = values.start;
_continuousEndCustomValue.value = values.end;
});
},
),
),
Text(localizations
.demoSlidersContinuousRangeSliderWithCustomTheme),
],
),
],
),
);
}
}
// END
| flutter/dev/integration_tests/new_gallery/lib/demos/material/sliders_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/material/sliders_demo.dart",
"repo_id": "flutter",
"token_count": 8708
} | 577 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:dual_screen/dual_screen.dart';
import 'package:flutter/material.dart';
import '../../gallery_localizations.dart';
// BEGIN twoPaneDemo
enum TwoPaneDemoType {
foldable,
tablet,
smallScreen,
}
class TwoPaneDemo extends StatefulWidget {
const TwoPaneDemo({
super.key,
required this.restorationId,
required this.type,
});
final String restorationId;
final TwoPaneDemoType type;
@override
TwoPaneDemoState createState() => TwoPaneDemoState();
}
class TwoPaneDemoState extends State<TwoPaneDemo> with RestorationMixin {
final RestorableInt _currentIndex = RestorableInt(-1);
@override
String get restorationId => widget.restorationId;
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_currentIndex, 'two_pane_selected_item');
}
@override
void dispose() {
_currentIndex.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
TwoPanePriority panePriority = TwoPanePriority.both;
if (widget.type == TwoPaneDemoType.smallScreen) {
panePriority = _currentIndex.value == -1
? TwoPanePriority.start
: TwoPanePriority.end;
}
return SimulateScreen(
type: widget.type,
child: TwoPane(
paneProportion: 0.3,
panePriority: panePriority,
startPane: ListPane(
selectedIndex: _currentIndex.value,
onSelect: (int index) {
setState(() {
_currentIndex.value = index;
});
},
),
endPane: DetailsPane(
selectedIndex: _currentIndex.value,
onClose: widget.type == TwoPaneDemoType.smallScreen
? () {
setState(() {
_currentIndex.value = -1;
});
}
: null,
),
),
);
}
}
class ListPane extends StatelessWidget {
const ListPane({
super.key,
required this.onSelect,
required this.selectedIndex,
});
final ValueChanged<int> onSelect;
final int selectedIndex;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(GalleryLocalizations.of(context)!.demoTwoPaneList),
),
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(
onTap: () {
onSelect(index);
},
selected: selectedIndex == index,
leading: ExcludeSemantics(
child: CircleAvatar(child: Text('$index')),
),
title: Text(
GalleryLocalizations.of(context)!.demoTwoPaneItem(index),
),
),
],
),
),
);
}
}
class DetailsPane extends StatelessWidget {
const DetailsPane({
super.key,
required this.selectedIndex,
this.onClose,
});
final VoidCallback? onClose;
final int selectedIndex;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
leading: onClose == null
? null
: IconButton(icon: const Icon(Icons.close), onPressed: onClose),
title: Text(
GalleryLocalizations.of(context)!.demoTwoPaneDetails,
),
),
body: ColoredBox(
color: const Color(0xfffafafa),
child: Center(
child: Text(
selectedIndex == -1
? GalleryLocalizations.of(context)!.demoTwoPaneSelectItem
: GalleryLocalizations.of(context)!
.demoTwoPaneItemDetails(selectedIndex),
),
),
),
);
}
}
class SimulateScreen extends StatelessWidget {
const SimulateScreen({
super.key,
required this.type,
required this.child,
});
final TwoPaneDemoType type;
final TwoPane child;
// An approximation of a real foldable
static const double foldableAspectRatio = 20 / 18;
// 16x9 candy bar phone
static const double singleScreenAspectRatio = 9 / 16;
// Taller desktop / tablet
static const double tabletAspectRatio = 4 / 3;
// How wide should the hinge be, as a proportion of total width
static const double hingeProportion = 1 / 35;
@override
Widget build(BuildContext context) {
return Center(
child: Container(
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(16),
),
padding: const EdgeInsets.all(14),
child: AspectRatio(
aspectRatio: type == TwoPaneDemoType.foldable
? foldableAspectRatio
: type == TwoPaneDemoType.tablet
? tabletAspectRatio
: singleScreenAspectRatio,
child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
final Size size = Size(constraints.maxWidth, constraints.maxHeight);
final Size hingeSize = Size(size.width * hingeProportion, size.height);
// Position the hinge in the middle of the display
final Rect hingeBounds = Rect.fromLTWH(
(size.width - hingeSize.width) / 2,
0,
hingeSize.width,
hingeSize.height,
);
return MediaQuery(
data: MediaQueryData(
size: size,
displayFeatures: <DisplayFeature>[
if (type == TwoPaneDemoType.foldable)
DisplayFeature(
bounds: hingeBounds,
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.postureFlat,
),
],
),
child: child,
);
}),
),
),
);
}
}
// END
| flutter/dev/integration_tests/new_gallery/lib/demos/reference/two_pane_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/reference/two_pane_demo.dart",
"repo_id": "flutter",
"token_count": 2887
} | 578 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import '../constants.dart';
import '../data/gallery_options.dart';
import '../gallery_localizations.dart';
import '../layout/adaptive.dart';
import 'home.dart';
import 'settings.dart';
import 'settings_icon/icon.dart' as settings_icon;
const double _settingsButtonWidth = 64;
const double _settingsButtonHeightDesktop = 56;
const double _settingsButtonHeightMobile = 40;
class Backdrop extends StatefulWidget {
const Backdrop({
super.key,
required this.isDesktop,
this.settingsPage,
this.homePage,
});
final bool isDesktop;
final Widget? settingsPage;
final Widget? homePage;
@override
State<Backdrop> createState() => _BackdropState();
}
class _BackdropState extends State<Backdrop> with TickerProviderStateMixin {
late AnimationController _settingsPanelController;
late AnimationController _iconController;
late FocusNode _settingsPageFocusNode;
late ValueNotifier<bool> _isSettingsOpenNotifier;
late Widget _settingsPage;
late Widget _homePage;
@override
void initState() {
super.initState();
_settingsPanelController = AnimationController(
vsync: this,
duration: widget.isDesktop
? settingsPanelMobileAnimationDuration
: settingsPanelDesktopAnimationDuration);
_iconController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 500),
);
_settingsPageFocusNode = FocusNode();
_isSettingsOpenNotifier = ValueNotifier<bool>(false);
_settingsPage = widget.settingsPage ??
SettingsPage(
animationController: _settingsPanelController,
);
_homePage = widget.homePage ?? const HomePage();
}
@override
void dispose() {
_settingsPanelController.dispose();
_iconController.dispose();
_settingsPageFocusNode.dispose();
_isSettingsOpenNotifier.dispose();
super.dispose();
}
void _toggleSettings() {
// Animate the settings panel to open or close.
if (_isSettingsOpenNotifier.value) {
_settingsPanelController.reverse();
_iconController.reverse();
} else {
_settingsPanelController.forward();
_iconController.forward();
}
_isSettingsOpenNotifier.value = !_isSettingsOpenNotifier.value;
}
Animation<RelativeRect> _slideDownSettingsPageAnimation(
BoxConstraints constraints) {
return RelativeRectTween(
begin: RelativeRect.fromLTRB(0, -constraints.maxHeight, 0, 0),
end: RelativeRect.fill,
).animate(
CurvedAnimation(
parent: _settingsPanelController,
curve: const Interval(
0.0,
0.4,
curve: Curves.ease,
),
),
);
}
Animation<RelativeRect> _slideDownHomePageAnimation(
BoxConstraints constraints) {
return RelativeRectTween(
begin: RelativeRect.fill,
end: RelativeRect.fromLTRB(
0,
constraints.biggest.height - galleryHeaderHeight,
0,
-galleryHeaderHeight,
),
).animate(
CurvedAnimation(
parent: _settingsPanelController,
curve: const Interval(
0.0,
0.4,
curve: Curves.ease,
),
),
);
}
Widget _buildStack(BuildContext context, BoxConstraints constraints) {
final bool isDesktop = isDisplayDesktop(context);
final Widget settingsPage = ValueListenableBuilder<bool>(
valueListenable: _isSettingsOpenNotifier,
builder: (BuildContext context, bool isSettingsOpen, Widget? child) {
return ExcludeSemantics(
excluding: !isSettingsOpen,
child: isSettingsOpen
? KeyboardListener(
includeSemantics: false,
focusNode: _settingsPageFocusNode,
onKeyEvent: (KeyEvent event) {
if (event.logicalKey == LogicalKeyboardKey.escape) {
_toggleSettings();
}
},
child: FocusScope(child: _settingsPage),
)
: ExcludeFocus(child: _settingsPage),
);
},
);
final Widget homePage = ValueListenableBuilder<bool>(
valueListenable: _isSettingsOpenNotifier,
builder: (BuildContext context, bool isSettingsOpen, Widget? child) {
return ExcludeSemantics(
excluding: isSettingsOpen,
child: FocusTraversalGroup(child: _homePage),
);
},
);
return AnnotatedRegion<SystemUiOverlayStyle>(
value: GalleryOptions.of(context).resolvedSystemUiOverlayStyle(),
child: Stack(
children: <Widget>[
if (!isDesktop) ...<Widget>[
// Slides the settings page up and down from the top of the
// screen.
PositionedTransition(
rect: _slideDownSettingsPageAnimation(constraints),
child: settingsPage,
),
// Slides the home page up and down below the bottom of the
// screen.
PositionedTransition(
rect: _slideDownHomePageAnimation(constraints),
child: homePage,
),
],
if (isDesktop) ...<Widget>[
Semantics(sortKey: const OrdinalSortKey(2), child: homePage),
ValueListenableBuilder<bool>(
valueListenable: _isSettingsOpenNotifier,
builder: (BuildContext context, bool isSettingsOpen, Widget? child) {
if (isSettingsOpen) {
return ExcludeSemantics(
child: Listener(
onPointerDown: (_) => _toggleSettings(),
child: const ModalBarrier(dismissible: false),
),
);
} else {
return Container();
}
},
),
Semantics(
sortKey: const OrdinalSortKey(3),
child: ScaleTransition(
alignment: Directionality.of(context) == TextDirection.ltr
? Alignment.topRight
: Alignment.topLeft,
scale: CurvedAnimation(
parent: _settingsPanelController,
curve: Curves.fastOutSlowIn,
),
child: Align(
alignment: AlignmentDirectional.topEnd,
child: Material(
elevation: 7,
clipBehavior: Clip.antiAlias,
borderRadius: BorderRadius.circular(40),
color: Theme.of(context).colorScheme.secondaryContainer,
child: Container(
constraints: const BoxConstraints(
maxHeight: 560,
maxWidth: desktopSettingsWidth,
minWidth: desktopSettingsWidth,
),
child: settingsPage,
),
),
),
),
),
],
_SettingsIcon(
animationController: _iconController,
toggleSettings: _toggleSettings,
isSettingsOpenNotifier: _isSettingsOpenNotifier,
),
],
),
);
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: _buildStack,
);
}
}
class _SettingsIcon extends AnimatedWidget {
const _SettingsIcon({
required this.animationController,
required this.toggleSettings,
required this.isSettingsOpenNotifier,
}) : super(listenable: animationController);
final AnimationController animationController;
final VoidCallback toggleSettings;
final ValueNotifier<bool> isSettingsOpenNotifier;
String _settingsSemanticLabel(bool isOpen, BuildContext context) {
return isOpen
? GalleryLocalizations.of(context)!.settingsButtonCloseLabel
: GalleryLocalizations.of(context)!.settingsButtonLabel;
}
@override
Widget build(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
final double safeAreaTopPadding = MediaQuery.of(context).padding.top;
return Align(
alignment: AlignmentDirectional.topEnd,
child: Semantics(
sortKey: const OrdinalSortKey(1),
button: true,
enabled: true,
label: _settingsSemanticLabel(isSettingsOpenNotifier.value, context),
child: SizedBox(
width: _settingsButtonWidth,
height: isDesktop
? _settingsButtonHeightDesktop
: _settingsButtonHeightMobile + safeAreaTopPadding,
child: Material(
borderRadius: const BorderRadiusDirectional.only(
bottomStart: Radius.circular(10),
),
color:
isSettingsOpenNotifier.value & !animationController.isAnimating
? Colors.transparent
: Theme.of(context).colorScheme.secondaryContainer,
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () {
toggleSettings();
SemanticsService.announce(
_settingsSemanticLabel(isSettingsOpenNotifier.value, context),
GalleryOptions.of(context).resolvedTextDirection()!,
);
},
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 3, end: 18),
child: settings_icon.SettingsIcon(animationController.value),
),
),
),
),
),
);
}
}
| flutter/dev/integration_tests/new_gallery/lib/pages/backdrop.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/pages/backdrop.dart",
"repo_id": "flutter",
"token_count": 4381
} | 579 |
// 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 FlyForm extends BackLayerItem {
const FlyForm({super.key}) : super(index: 0);
@override
State<FlyForm> createState() => _FlyFormState();
}
class _FlyFormState extends State<FlyForm> with RestorationMixin {
final RestorableTextEditingController travelerController = RestorableTextEditingController();
final RestorableTextEditingController countryDestinationController = RestorableTextEditingController();
final RestorableTextEditingController destinationController = RestorableTextEditingController();
final RestorableTextEditingController dateController = RestorableTextEditingController();
@override
String get restorationId => 'fly_form';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(travelerController, 'diner_controller');
registerForRestoration(countryDestinationController, 'date_controller');
registerForRestoration(destinationController, 'time_controller');
registerForRestoration(dateController, 'location_controller');
}
@override
void dispose() {
travelerController.dispose();
countryDestinationController.dispose();
destinationController.dispose();
dateController.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.place,
title: localizations.craneFormOrigin,
textController: countryDestinationController.value,
),
HeaderFormField(
index: 2,
iconData: Icons.airplanemode_active,
title: localizations.craneFormDestination,
textController: destinationController.value,
),
HeaderFormField(
index: 3,
iconData: Icons.date_range,
title: localizations.craneFormDates,
textController: dateController.value,
),
],
);
}
}
| flutter/dev/integration_tests/new_gallery/lib/studies/crane/fly_form.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/crane/fly_form.dart",
"repo_id": "flutter",
"token_count": 868
} | 580 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
/// Most color assignments in Rally are not like the typical color
/// assignments that are common in other apps. Instead of primarily mapping to
/// component type and part, they are assigned round robin based on layout.
class RallyColors {
static const List<Color> accountColors = <Color>[
Color(0xFF005D57),
Color(0xFF04B97F),
Color(0xFF37EFBA),
Color(0xFF007D51),
];
static const List<Color> billColors = <Color>[
Color(0xFFFFDC78),
Color(0xFFFF6951),
Color(0xFFFFD7D0),
Color(0xFFFFAC12),
];
static const List<Color> budgetColors = <Color>[
Color(0xFFB2F2FF),
Color(0xFFB15DFF),
Color(0xFF72DEFF),
Color(0xFF0082FB),
];
static const Color gray = Color(0xFFD8D8D8);
static const Color gray60 = Color(0x99D8D8D8);
static const Color gray25 = Color(0x40D8D8D8);
static const Color white60 = Color(0x99FFFFFF);
static const Color primaryBackground = Color(0xFF33333D);
static const Color inputBackground = Color(0xFF26282F);
static const Color cardBackground = Color(0x03FEFEFE);
static const Color buttonColor = Color(0xFF09AF79);
static const Color focusColor = Color(0xCCFFFFFF);
static const Color dividerColor = Color(0xAA282828);
/// Convenience method to get a single account color with position i.
static Color accountColor(int i) {
return cycledColor(accountColors, i);
}
/// Convenience method to get a single bill color with position i.
static Color billColor(int i) {
return cycledColor(billColors, i);
}
/// Convenience method to get a single budget color with position i.
static Color budgetColor(int i) {
return cycledColor(budgetColors, i);
}
/// Gets a color from a list that is considered to be infinitely repeating.
static Color cycledColor(List<Color> colors, int i) {
return colors[i % colors.length];
}
}
| flutter/dev/integration_tests/new_gallery/lib/studies/rally/colors.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/rally/colors.dart",
"repo_id": "flutter",
"token_count": 682
} | 581 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'package:scoped_model/scoped_model.dart';
import '../../data/gallery_options.dart';
import '../../layout/adaptive.dart';
import 'expanding_bottom_sheet.dart';
import 'model/app_state_model.dart';
import 'supplemental/asymmetric_view.dart';
const String _ordinalSortKeyName = 'home';
class ProductPage extends StatelessWidget {
const ProductPage({super.key});
@override
Widget build(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
return ScopedModelDescendant<AppStateModel>(
builder: (BuildContext context, Widget? child, AppStateModel model) {
return isDesktop
? DesktopAsymmetricView(products: model.getProducts())
: MobileAsymmetricView(products: model.getProducts());
});
}
}
class HomePage extends StatelessWidget {
const HomePage({
this.expandingBottomSheet,
this.scrim,
this.backdrop,
super.key,
});
final ExpandingBottomSheet? expandingBottomSheet;
final Widget? scrim;
final Widget? backdrop;
@override
Widget build(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
// Use sort keys to make sure the cart button is always on the top.
// This way, a11y users do not have to scroll through the entire list to
// find the cart, and can easily get to the cart from anywhere on the page.
return ApplyTextOptions(
child: Stack(
children: <Widget>[
Semantics(
container: true,
sortKey: const OrdinalSortKey(1, name: _ordinalSortKeyName),
child: backdrop,
),
ExcludeSemantics(child: scrim),
Align(
alignment: isDesktop
? AlignmentDirectional.topEnd
: AlignmentDirectional.bottomEnd,
child: Semantics(
container: true,
sortKey: const OrdinalSortKey(0, name: _ordinalSortKeyName),
child: expandingBottomSheet,
),
),
],
),
);
}
}
| flutter/dev/integration_tests/new_gallery/lib/studies/shrine/home.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/shrine/home.dart",
"repo_id": "flutter",
"token_count": 872
} | 582 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../layout/letter_spacing.dart';
import 'colors.dart';
import 'supplemental/cut_corners_border.dart';
const double defaultLetterSpacing = 0.03;
const double mediumLetterSpacing = 0.04;
const double largeLetterSpacing = 1.0;
final ThemeData shrineTheme = _buildShrineTheme();
IconThemeData _customIconTheme(IconThemeData original) {
return original.copyWith(color: shrineBrown900);
}
ThemeData _buildShrineTheme() {
final ThemeData base = ThemeData.light();
return base.copyWith(
appBarTheme: const AppBarTheme(
systemOverlayStyle: SystemUiOverlayStyle.dark,
elevation: 0,
),
scaffoldBackgroundColor: shrineBackgroundWhite,
cardColor: shrineBackgroundWhite,
primaryIconTheme: _customIconTheme(base.iconTheme),
inputDecorationTheme: const InputDecorationTheme(
border: CutCornersBorder(
borderSide: BorderSide(color: shrineBrown900, width: 0.5),
),
contentPadding: EdgeInsets.symmetric(vertical: 20, horizontal: 16),
),
textTheme: _buildShrineTextTheme(base.textTheme),
textSelectionTheme: const TextSelectionThemeData(
selectionColor: shrinePink100,
),
primaryTextTheme: _buildShrineTextTheme(base.primaryTextTheme),
iconTheme: _customIconTheme(base.iconTheme),
colorScheme: _shrineColorScheme.copyWith(
error: shrineErrorRed,
primary: shrinePink100,
),
);
}
TextTheme _buildShrineTextTheme(TextTheme base) {
return GoogleFonts.rubikTextTheme(base
.copyWith(
headlineSmall: base.headlineSmall!.copyWith(
fontWeight: FontWeight.w500,
letterSpacing: letterSpacingOrNone(defaultLetterSpacing),
),
titleLarge: base.titleLarge!.copyWith(
fontSize: 18,
letterSpacing: letterSpacingOrNone(defaultLetterSpacing),
),
bodySmall: base.bodySmall!.copyWith(
fontWeight: FontWeight.w400,
fontSize: 14,
letterSpacing: letterSpacingOrNone(defaultLetterSpacing),
),
bodyLarge: base.bodyLarge!.copyWith(
fontWeight: FontWeight.w500,
fontSize: 16,
letterSpacing: letterSpacingOrNone(defaultLetterSpacing),
),
bodyMedium: base.bodyMedium!.copyWith(
letterSpacing: letterSpacingOrNone(defaultLetterSpacing),
),
titleMedium: base.titleMedium!.copyWith(
letterSpacing: letterSpacingOrNone(defaultLetterSpacing),
),
headlineMedium: base.headlineMedium!.copyWith(
letterSpacing: letterSpacingOrNone(defaultLetterSpacing),
),
labelLarge: base.labelLarge!.copyWith(
fontWeight: FontWeight.w500,
fontSize: 14,
letterSpacing: letterSpacingOrNone(defaultLetterSpacing),
),
)
.apply(
displayColor: shrineBrown900,
bodyColor: shrineBrown900,
));
}
const ColorScheme _shrineColorScheme = ColorScheme(
primary: shrinePink100,
primaryContainer: shrineBrown900,
secondary: shrinePink50,
secondaryContainer: shrineBrown900,
surface: shrineSurfaceWhite,
background: shrineBackgroundWhite,
error: shrineErrorRed,
onPrimary: shrineBrown900,
onSecondary: shrineBrown900,
onSurface: shrineBrown900,
onBackground: shrineBrown900,
onError: shrineSurfaceWhite,
brightness: Brightness.light,
);
| flutter/dev/integration_tests/new_gallery/lib/studies/shrine/theme.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/shrine/theme.dart",
"repo_id": "flutter",
"token_count": 1359
} | 583 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Spellcheck Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Spellcheck Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: EditableText(
controller: TextEditingController(),
backgroundCursorColor: Colors.grey,
focusNode: FocusNode(),
style: const TextStyle(),
cursorColor: Colors.red,
spellCheckConfiguration:
const SpellCheckConfiguration(
misspelledTextStyle: TextField.materialMisspelledTextStyle,
)
)
),
);
}
}
| flutter/dev/integration_tests/spell_check/lib/main.dart/0 | {
"file_path": "flutter/dev/integration_tests/spell_check/lib/main.dart",
"repo_id": "flutter",
"token_count": 534
} | 584 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart' as widgets show Container, Size, runApp;
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:integration_ui/resize.dart' as app;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('end-to-end test', () {
testWidgets('Use button to resize window',
timeout: const Timeout(Duration(seconds: 5)),
(WidgetTester tester) async {
const app.ResizeApp resizeApp = app.ResizeApp();
widgets.runApp(resizeApp);
await tester.pumpAndSettle();
final Finder fab = find.byKey(app.ResizeApp.extendedFab);
expect(fab, findsOneWidget);
final Finder root = find.byWidget(resizeApp);
final widgets.Size sizeBefore = tester.getSize(root);
await tester.tap(fab);
await tester.pumpAndSettle();
final widgets.Size sizeAfter = tester.getSize(root);
expect(sizeAfter.width, equals(sizeBefore.width + app.ResizeApp.resizeBy));
expect(sizeAfter.height, equals(sizeBefore.height + app.ResizeApp.resizeBy));
final Finder widthLabel = find.byKey(app.ResizeApp.widthLabel);
expect(widthLabel, findsOneWidget);
expect(find.text('width: ${sizeAfter.width}'), findsOneWidget);
final Finder heightLabel = find.byKey(app.ResizeApp.heightLabel);
expect(heightLabel, findsOneWidget);
expect(find.text('height: ${sizeAfter.height}'), findsOneWidget);
});
});
testWidgets('resize window after calling runApp twice, the second with no content',
timeout: const Timeout(Duration(seconds: 5)),
(WidgetTester tester) async {
const app.ResizeApp root = app.ResizeApp();
widgets.runApp(root);
widgets.runApp(widgets.Container());
await tester.pumpAndSettle();
const widgets.Size expectedSize = widgets.Size(100, 100);
await app.ResizeApp.resize(expectedSize);
});
}
| flutter/dev/integration_tests/ui/integration_test/resize_integration_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/ui/integration_test/resize_integration_test.dart",
"repo_id": "flutter",
"token_count": 741
} | 585 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:developer';
import 'package:flutter/widgets.dart';
void main() {
final Set<Widget> widgets = <Widget>{};
widgets.add(const Text('same'));
widgets.add(const Text('same'));
// If track-widget-creation is enabled, the set will have 2 members.
// Otherwise is will only have one.
registerExtension('ext.devicelab.test', (String method, Map<String, Object> params) async {
return ServiceExtensionResponse.result('{"result":${widgets.length}}');
});
}
| flutter/dev/integration_tests/ui/lib/track_widget_creation.dart/0 | {
"file_path": "flutter/dev/integration_tests/ui/lib/track_widget_creation.dart",
"repo_id": "flutter",
"token_count": 194
} | 586 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import Cocoa
import FlutterMacOS
extension NSWindow {
var titlebarHeight: CGFloat {
frame.height - contentRect(forFrameRect: frame).height
}
}
class MainFlutterWindow: NSWindow {
override func awakeFromNib() {
let flutterViewController = FlutterViewController()
let windowFrame = self.frame
self.contentViewController = flutterViewController
self.setFrame(windowFrame, display: true)
RegisterMethodChannel(registry: flutterViewController)
RegisterGeneratedPlugins(registry: flutterViewController)
super.awakeFromNib()
}
func RegisterMethodChannel(registry: FlutterPluginRegistry) {
let registrar = registry.registrar(forPlugin: "resize")
let channel = FlutterMethodChannel(name: "samples.flutter.dev/resize",
binaryMessenger: registrar.messenger)
channel.setMethodCallHandler({ (call, result) in
if call.method == "resize" {
if let args = call.arguments as? Dictionary<String, Any>,
let width = args["width"] as? Double,
var height = args["height"] as? Double {
height += self.titlebarHeight
let currentFrame: NSRect = self.frame
let nextFrame: NSRect = NSMakeRect(
currentFrame.minX - (width - currentFrame.width) / 2,
currentFrame.minY - (height - currentFrame.height) / 2,
width,
height
)
self.setFrame(nextFrame, display: true, animate: false)
result(true)
} else {
result(FlutterError.init(code: "bad args", message: nil, details: nil))
}
}
})
}
}
| flutter/dev/integration_tests/ui/macos/Runner/MainFlutterWindow.swift/0 | {
"file_path": "flutter/dev/integration_tests/ui/macos/Runner/MainFlutterWindow.swift",
"repo_id": "flutter",
"token_count": 697
} | 587 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:html';
import 'package:flutter_test/flutter_test.dart';
/// Whether the current browser is Firefox.
bool get isFirefox => window.navigator.userAgent.toLowerCase().contains('firefox');
/// Finds elements in the DOM tree rendered by the Flutter Web engine.
///
/// If the browser supports shadow DOM, looks in the shadow root under the
/// `<flt-glass-pane>` element. Otherwise, looks under `<flt-glass-pane>`
/// without penetrating the shadow DOM. In the latter case, if the application
/// creates platform views, this will also find platform view elements.
List<Node> findElements(String selector) {
final Element? flutterView = document.querySelector('flutter-view');
if (flutterView == null) {
fail(
'Failed to locate <flutter-view>. Possible reasons:\n'
' - The application failed to start'
' - `findElements` was called before the application started'
);
}
return flutterView.querySelectorAll(selector);
}
| flutter/dev/integration_tests/web_e2e_tests/lib/common.dart/0 | {
"file_path": "flutter/dev/integration_tests/web_e2e_tests/lib/common.dart",
"repo_id": "flutter",
"token_count": 331
} | 588 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:html' as html;
import 'dart:ui_web' as ui_web;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:web_e2e_tests/platform_messages_main.dart' as app;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('platform message for Clipboard.setData reply with future',
(WidgetTester tester) async {
app.main();
await tester.pumpAndSettle();
// TODO(nurhan): https://github.com/flutter/flutter/issues/51885
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, null);
// Focus on a TextFormField.
final Finder finder = find.byKey(const Key('input'));
expect(finder, findsOneWidget);
await tester.tap(find.byKey(const Key('input')));
// Focus in input, otherwise clipboard will fail with
// 'document is not focused' platform exception.
html.document.querySelector('input')?.focus();
await Clipboard.setData(const ClipboardData(text: 'sample text'));
}, skip: true); // https://github.com/flutter/flutter/issues/54296
testWidgets('Should create and dispose view embedder',
(WidgetTester tester) async {
int viewInstanceCount = 0;
platformViewsRegistry.getNextPlatformViewId();
ui_web.platformViewRegistry.registerViewFactory('MyView', (int viewId) {
viewInstanceCount += 1;
return html.DivElement();
});
app.main();
await tester.pumpAndSettle();
final Map<String, dynamic> createArgs = <String, dynamic>{
'id': 567,
'viewType': 'MyView',
};
await SystemChannels.platform_views.invokeMethod<void>('create', createArgs);
await SystemChannels.platform_views.invokeMethod<void>('dispose', 567);
expect(viewInstanceCount, 1);
});
}
| flutter/dev/integration_tests/web_e2e_tests/test_driver/platform_messages_integration.dart/0 | {
"file_path": "flutter/dev/integration_tests/web_e2e_tests/test_driver/platform_messages_integration.dart",
"repo_id": "flutter",
"token_count": 706
} | 589 |
#include "Generated.xcconfig"
| flutter/dev/manual_tests/ios/Flutter/Release.xcconfig/0 | {
"file_path": "flutter/dev/manual_tests/ios/Flutter/Release.xcconfig",
"repo_id": "flutter",
"token_count": 12
} | 590 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
class CardModel {
CardModel(this.value, this.size, this.color);
int value;
Size size;
Color color;
String get label => 'Card $value';
Key get key => ObjectKey(this);
}
class PageViewApp extends StatefulWidget {
const PageViewApp({super.key});
@override
PageViewAppState createState() => PageViewAppState();
}
class PageViewAppState extends State<PageViewApp> {
@override
void initState() {
super.initState();
const List<Size> cardSizes = <Size>[
Size(100.0, 300.0),
Size(300.0, 100.0),
Size(200.0, 400.0),
Size(400.0, 400.0),
Size(300.0, 400.0),
];
cardModels = List<CardModel>.generate(cardSizes.length, (int i) {
final Color? color = Color.lerp(Colors.red.shade300, Colors.blue.shade900, i / cardSizes.length);
return CardModel(i, cardSizes[i], color!);
});
}
static const TextStyle cardLabelStyle =
TextStyle(color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.bold);
List<CardModel> cardModels = <CardModel>[];
Size pageSize = const Size(200.0, 200.0);
Axis scrollDirection = Axis.horizontal;
bool itemsWrap = false;
Widget buildCard(CardModel cardModel) {
final Widget card = Card(
color: cardModel.color,
child: Container(
width: cardModel.size.width,
height: cardModel.size.height,
padding: const EdgeInsets.all(8.0),
child: Center(child: Text(cardModel.label, style: cardLabelStyle)),
),
);
final BoxConstraints constraints = (scrollDirection == Axis.vertical)
? BoxConstraints.tightFor(height: pageSize.height)
: BoxConstraints.tightFor(width: pageSize.width);
return Container(
key: cardModel.key,
constraints: constraints,
child: Center(child: card),
);
}
void switchScrollDirection() {
setState(() {
scrollDirection = (scrollDirection == Axis.vertical)
? Axis.horizontal
: Axis.vertical;
});
}
void toggleItemsWrap() {
setState(() {
itemsWrap = !itemsWrap;
});
}
Widget _buildDrawer() {
return Drawer(
child: ListView(
children: <Widget>[
const DrawerHeader(child: Center(child: Text('Options'))),
ListTile(
leading: const Icon(Icons.more_horiz),
selected: scrollDirection == Axis.horizontal,
trailing: const Text('Horizontal Layout'),
onTap: switchScrollDirection,
),
ListTile(
leading: const Icon(Icons.more_vert),
selected: scrollDirection == Axis.vertical,
trailing: const Text('Vertical Layout'),
onTap: switchScrollDirection,
),
ListTile(
onTap: toggleItemsWrap,
title: const Text('Scrolling wraps around'),
// TODO(abarth): Actually make this checkbox change this value.
trailing: Checkbox(value: itemsWrap, onChanged: null),
),
],
),
);
}
AppBar _buildAppBar() {
return AppBar(
title: const Text('PageView'),
actions: <Widget>[
Text(scrollDirection == Axis.horizontal ? 'horizontal' : 'vertical'),
],
);
}
Widget _buildBody(BuildContext context) {
return PageView(
// TODO(abarth): itemsWrap: itemsWrap,
scrollDirection: scrollDirection,
children: cardModels.map<Widget>(buildCard).toList(),
);
}
@override
Widget build(BuildContext context) {
return IconTheme(
data: const IconThemeData(color: Colors.white),
child: Scaffold(
appBar: _buildAppBar(),
drawer: _buildDrawer(),
body: _buildBody(context),
),
);
}
}
void main() {
runApp(
const MaterialApp(
title: 'PageView',
home: PageViewApp(),
),
);
}
| flutter/dev/manual_tests/lib/page_view.dart/0 | {
"file_path": "flutter/dev/manual_tests/lib/page_view.dart",
"repo_id": "flutter",
"token_count": 1643
} | 591 |
name: missing_dependency_tests
environment:
sdk: '>=3.2.0-0 <4.0.0'
dependencies:
flutter:
sdk: flutter
| flutter/dev/missing_dependency_tests/pubspec.yaml/0 | {
"file_path": "flutter/dev/missing_dependency_tests/pubspec.yaml",
"repo_id": "flutter",
"token_count": 54
} | 592 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ## Usage
//
// Run this program from the root of the git repository.
//
// ```
// dart dev/tools/gen_defaults/bin/gen_defaults.dart [-v]
// ```
import 'dart:convert';
import 'dart:io';
import 'package:args/args.dart';
import 'package:gen_defaults/action_chip_template.dart';
import 'package:gen_defaults/app_bar_template.dart';
import 'package:gen_defaults/badge_template.dart';
import 'package:gen_defaults/banner_template.dart';
import 'package:gen_defaults/bottom_app_bar_template.dart';
import 'package:gen_defaults/bottom_sheet_template.dart';
import 'package:gen_defaults/button_template.dart';
import 'package:gen_defaults/card_template.dart';
import 'package:gen_defaults/checkbox_template.dart';
import 'package:gen_defaults/chip_template.dart';
import 'package:gen_defaults/color_scheme_template.dart';
import 'package:gen_defaults/date_picker_template.dart';
import 'package:gen_defaults/dialog_template.dart';
import 'package:gen_defaults/divider_template.dart';
import 'package:gen_defaults/drawer_template.dart';
import 'package:gen_defaults/expansion_tile_template.dart';
import 'package:gen_defaults/fab_template.dart';
import 'package:gen_defaults/filter_chip_template.dart';
import 'package:gen_defaults/icon_button_template.dart';
import 'package:gen_defaults/input_chip_template.dart';
import 'package:gen_defaults/input_decorator_template.dart';
import 'package:gen_defaults/list_tile_template.dart';
import 'package:gen_defaults/menu_template.dart';
import 'package:gen_defaults/motion_template.dart';
import 'package:gen_defaults/navigation_bar_template.dart';
import 'package:gen_defaults/navigation_drawer_template.dart';
import 'package:gen_defaults/navigation_rail_template.dart';
import 'package:gen_defaults/popup_menu_template.dart';
import 'package:gen_defaults/progress_indicator_template.dart';
import 'package:gen_defaults/radio_template.dart';
import 'package:gen_defaults/search_bar_template.dart';
import 'package:gen_defaults/search_view_template.dart';
import 'package:gen_defaults/segmented_button_template.dart';
import 'package:gen_defaults/slider_template.dart';
import 'package:gen_defaults/snackbar_template.dart';
import 'package:gen_defaults/surface_tint.dart';
import 'package:gen_defaults/switch_template.dart';
import 'package:gen_defaults/tabs_template.dart';
import 'package:gen_defaults/text_field_template.dart';
import 'package:gen_defaults/time_picker_template.dart';
import 'package:gen_defaults/token_logger.dart';
import 'package:gen_defaults/typography_template.dart';
Map<String, dynamic> _readTokenFile(File file) {
return jsonDecode(file.readAsStringSync()) as Map<String, dynamic>;
}
const String materialLib = 'packages/flutter/lib/src/material';
const String dataDir = 'dev/tools/gen_defaults/data';
Future<void> main(List<String> args) async {
// Parse arguments
final ArgParser parser = ArgParser();
parser.addFlag(
'verbose',
abbr: 'v',
help: 'Enable verbose output',
negatable: false,
);
final ArgResults argResults = parser.parse(args);
final bool verbose = argResults['verbose'] as bool;
// Map of version number to list of data files that use that version.
final Map<String, List<String>> versionMap = <String, List<String>>{};
// Map of all tokens to their values.
final Map<String, dynamic> tokens = <String, dynamic>{};
// Initialize.
for (final FileSystemEntity tokenFile in Directory(dataDir).listSync()) {
final Map<String, dynamic> tokenFileTokens = _readTokenFile(tokenFile as File);
final String version = tokenFileTokens['version'] as String;
tokenFileTokens.remove('version');
versionMap[version] ??= <String>[];
versionMap[version]!.add(tokenFile.uri.pathSegments.last);
tokens.addAll(tokenFileTokens);
}
tokenLogger.init(allTokens: tokens, versionMap: versionMap);
// Handle light/dark color tokens separately because they share identical token names.
final Map<String, dynamic> colorLightTokens = _readTokenFile(File('$dataDir/color_light.json'));
final Map<String, dynamic> colorDarkTokens = _readTokenFile(File('$dataDir/color_dark.json'));
// Generate tokens files.
ChipTemplate('Chip', '$materialLib/chip.dart', tokens).updateFile();
ActionChipTemplate('ActionChip', '$materialLib/action_chip.dart', tokens).updateFile();
AppBarTemplate('AppBar', '$materialLib/app_bar.dart', tokens).updateFile();
BottomAppBarTemplate('BottomAppBar', '$materialLib/bottom_app_bar.dart', tokens).updateFile();
BadgeTemplate('Badge', '$materialLib/badge.dart', tokens).updateFile();
BannerTemplate('Banner', '$materialLib/banner.dart', tokens).updateFile();
BottomAppBarTemplate('BottomAppBar', '$materialLib/bottom_app_bar.dart', tokens).updateFile();
BottomSheetTemplate('BottomSheet', '$materialLib/bottom_sheet.dart', tokens).updateFile();
ButtonTemplate('md.comp.elevated-button', 'ElevatedButton', '$materialLib/elevated_button.dart', tokens).updateFile();
ButtonTemplate('md.comp.filled-button', 'FilledButton', '$materialLib/filled_button.dart', tokens).updateFile();
ButtonTemplate('md.comp.filled-tonal-button', 'FilledTonalButton', '$materialLib/filled_button.dart', tokens).updateFile();
ButtonTemplate('md.comp.outlined-button', 'OutlinedButton', '$materialLib/outlined_button.dart', tokens).updateFile();
ButtonTemplate('md.comp.text-button', 'TextButton', '$materialLib/text_button.dart', tokens).updateFile();
CardTemplate('md.comp.elevated-card', 'Card', '$materialLib/card.dart', tokens).updateFile();
CardTemplate('md.comp.filled-card', 'FilledCard', '$materialLib/card.dart', tokens).updateFile();
CardTemplate('md.comp.outlined-card', 'OutlinedCard', '$materialLib/card.dart', tokens).updateFile();
CheckboxTemplate('Checkbox', '$materialLib/checkbox.dart', tokens).updateFile();
ColorSchemeTemplate(colorLightTokens, colorDarkTokens, 'ColorScheme', '$materialLib/theme_data.dart', tokens).updateFile();
DatePickerTemplate('DatePicker', '$materialLib/date_picker_theme.dart', tokens).updateFile();
DialogFullscreenTemplate('DialogFullscreen', '$materialLib/dialog.dart', tokens).updateFile();
DialogTemplate('Dialog', '$materialLib/dialog.dart', tokens).updateFile();
DividerTemplate('Divider', '$materialLib/divider.dart', tokens).updateFile();
DrawerTemplate('Drawer', '$materialLib/drawer.dart', tokens).updateFile();
ExpansionTileTemplate('ExpansionTile', '$materialLib/expansion_tile.dart', tokens).updateFile();
FABTemplate('FAB', '$materialLib/floating_action_button.dart', tokens).updateFile();
FilterChipTemplate('ChoiceChip', '$materialLib/choice_chip.dart', tokens).updateFile();
FilterChipTemplate('FilterChip', '$materialLib/filter_chip.dart', tokens).updateFile();
IconButtonTemplate('md.comp.icon-button', 'IconButton', '$materialLib/icon_button.dart', tokens).updateFile();
IconButtonTemplate('md.comp.filled-icon-button', 'FilledIconButton', '$materialLib/icon_button.dart', tokens).updateFile();
IconButtonTemplate('md.comp.filled-tonal-icon-button', 'FilledTonalIconButton', '$materialLib/icon_button.dart', tokens).updateFile();
IconButtonTemplate('md.comp.outlined-icon-button', 'OutlinedIconButton', '$materialLib/icon_button.dart', tokens).updateFile();
InputChipTemplate('InputChip', '$materialLib/input_chip.dart', tokens).updateFile();
ListTileTemplate('LisTile', '$materialLib/list_tile.dart', tokens).updateFile();
InputDecoratorTemplate('InputDecorator', '$materialLib/input_decorator.dart', tokens).updateFile();
MenuTemplate('Menu', '$materialLib/menu_anchor.dart', tokens).updateFile();
MotionTemplate('Motion', '$materialLib/motion.dart', tokens, tokenLogger).updateFile();
NavigationBarTemplate('NavigationBar', '$materialLib/navigation_bar.dart', tokens).updateFile();
NavigationDrawerTemplate('NavigationDrawer', '$materialLib/navigation_drawer.dart', tokens).updateFile();
NavigationRailTemplate('NavigationRail', '$materialLib/navigation_rail.dart', tokens).updateFile();
PopupMenuTemplate('PopupMenu', '$materialLib/popup_menu.dart', tokens).updateFile();
ProgressIndicatorTemplate('ProgressIndicator', '$materialLib/progress_indicator.dart', tokens).updateFile();
RadioTemplate('Radio<T>', '$materialLib/radio.dart', tokens).updateFile();
SearchBarTemplate('SearchBar', '$materialLib/search_anchor.dart', tokens).updateFile();
SearchViewTemplate('SearchView', '$materialLib/search_anchor.dart', tokens).updateFile();
SegmentedButtonTemplate('md.comp.outlined-segmented-button', 'SegmentedButton', '$materialLib/segmented_button.dart', tokens).updateFile();
SnackbarTemplate('md.comp.snackbar', 'Snackbar', '$materialLib/snack_bar.dart', tokens).updateFile();
SliderTemplate('md.comp.slider', 'Slider', '$materialLib/slider.dart', tokens).updateFile();
SurfaceTintTemplate('SurfaceTint', '$materialLib/elevation_overlay.dart', tokens).updateFile();
SwitchTemplate('Switch', '$materialLib/switch.dart', tokens).updateFile();
TimePickerTemplate('TimePicker', '$materialLib/time_picker.dart', tokens).updateFile();
TextFieldTemplate('TextField', '$materialLib/text_field.dart', tokens).updateFile();
TabsTemplate('Tabs', '$materialLib/tabs.dart', tokens).updateFile();
TypographyTemplate('Typography', '$materialLib/typography.dart', tokens).updateFile();
tokenLogger.printVersionUsage(verbose: verbose);
tokenLogger.printTokensUsage(verbose: verbose);
if (!verbose) {
print('\nTo see detailed version and token usage, run with --verbose (-v).');
}
tokenLogger.dumpToFile('dev/tools/gen_defaults/generated/used_tokens.csv');
}
| flutter/dev/tools/gen_defaults/bin/gen_defaults.dart/0 | {
"file_path": "flutter/dev/tools/gen_defaults/bin/gen_defaults.dart",
"repo_id": "flutter",
"token_count": 3103
} | 593 |
{
"version": "v0_206",
"md.comp.filter-chip.container.height": 32.0,
"md.comp.filter-chip.container.shape": "md.sys.shape.corner.small",
"md.comp.filter-chip.disabled.label-text.color": "onSurface",
"md.comp.filter-chip.disabled.label-text.opacity": 0.38,
"md.comp.filter-chip.dragged.container.elevation": "md.sys.elevation.level4",
"md.comp.filter-chip.elevated.container.elevation": "md.sys.elevation.level1",
"md.comp.filter-chip.elevated.container.shadow-color": "shadow",
"md.comp.filter-chip.elevated.disabled.container.color": "onSurface",
"md.comp.filter-chip.elevated.disabled.container.elevation": "md.sys.elevation.level0",
"md.comp.filter-chip.elevated.disabled.container.opacity": 0.12,
"md.comp.filter-chip.elevated.focus.container.elevation": "md.sys.elevation.level1",
"md.comp.filter-chip.elevated.hover.container.elevation": "md.sys.elevation.level2",
"md.comp.filter-chip.elevated.pressed.container.elevation": "md.sys.elevation.level1",
"md.comp.filter-chip.elevated.selected.container.color": "secondaryContainer",
"md.comp.filter-chip.elevated.unselected.container.color": "surfaceContainerLow",
"md.comp.filter-chip.flat.container.elevation": "md.sys.elevation.level0",
"md.comp.filter-chip.flat.disabled.selected.container.color": "onSurface",
"md.comp.filter-chip.flat.disabled.selected.container.opacity": 0.12,
"md.comp.filter-chip.flat.disabled.unselected.outline.color": "onSurface",
"md.comp.filter-chip.flat.disabled.unselected.outline.opacity": 0.12,
"md.comp.filter-chip.flat.selected.container.color": "secondaryContainer",
"md.comp.filter-chip.flat.selected.focus.container.elevation": "md.sys.elevation.level0",
"md.comp.filter-chip.flat.selected.hover.container.elevation": "md.sys.elevation.level1",
"md.comp.filter-chip.flat.selected.outline.width": 0.0,
"md.comp.filter-chip.flat.selected.pressed.container.elevation": "md.sys.elevation.level0",
"md.comp.filter-chip.flat.unselected.focus.container.elevation": "md.sys.elevation.level0",
"md.comp.filter-chip.flat.unselected.focus.outline.color": "onSurfaceVariant",
"md.comp.filter-chip.flat.unselected.hover.container.elevation": "md.sys.elevation.level0",
"md.comp.filter-chip.flat.unselected.outline.color": "outline",
"md.comp.filter-chip.flat.unselected.outline.width": 1.0,
"md.comp.filter-chip.flat.unselected.pressed.container.elevation": "md.sys.elevation.level0",
"md.comp.filter-chip.focus.indicator.color": "secondary",
"md.comp.filter-chip.focus.indicator.outline.offset": "md.sys.state.focus-indicator.outer-offset",
"md.comp.filter-chip.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness",
"md.comp.filter-chip.label-text.text-style": "labelLarge",
"md.comp.filter-chip.selected.dragged.label-text.color": "onSecondaryContainer",
"md.comp.filter-chip.selected.dragged.state-layer.color": "onSecondaryContainer",
"md.comp.filter-chip.selected.dragged.state-layer.opacity": "md.sys.state.dragged.state-layer-opacity",
"md.comp.filter-chip.selected.focus.label-text.color": "onSecondaryContainer",
"md.comp.filter-chip.selected.focus.state-layer.color": "onSecondaryContainer",
"md.comp.filter-chip.selected.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.filter-chip.selected.hover.label-text.color": "onSecondaryContainer",
"md.comp.filter-chip.selected.hover.state-layer.color": "onSecondaryContainer",
"md.comp.filter-chip.selected.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.filter-chip.selected.label-text.color": "onSecondaryContainer",
"md.comp.filter-chip.selected.pressed.label-text.color": "onSecondaryContainer",
"md.comp.filter-chip.selected.pressed.state-layer.color": "onSurfaceVariant",
"md.comp.filter-chip.selected.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.filter-chip.unselected.dragged.label-text.color": "onSurfaceVariant",
"md.comp.filter-chip.unselected.dragged.state-layer.color": "onSurfaceVariant",
"md.comp.filter-chip.unselected.dragged.state-layer.opacity": "md.sys.state.dragged.state-layer-opacity",
"md.comp.filter-chip.unselected.focus.label-text.color": "onSurfaceVariant",
"md.comp.filter-chip.unselected.focus.state-layer.color": "onSurfaceVariant",
"md.comp.filter-chip.unselected.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.filter-chip.unselected.hover.label-text.color": "onSurfaceVariant",
"md.comp.filter-chip.unselected.hover.state-layer.color": "onSurfaceVariant",
"md.comp.filter-chip.unselected.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.filter-chip.unselected.label-text.color": "onSurfaceVariant",
"md.comp.filter-chip.unselected.pressed.label-text.color": "onSurfaceVariant",
"md.comp.filter-chip.unselected.pressed.state-layer.color": "onSecondaryContainer",
"md.comp.filter-chip.unselected.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.filter-chip.with-icon.icon.size": 18.0,
"md.comp.filter-chip.with-leading-icon.disabled.leading-icon.color": "onSurface",
"md.comp.filter-chip.with-leading-icon.disabled.leading-icon.opacity": 0.38,
"md.comp.filter-chip.with-leading-icon.selected.dragged.leading-icon.color": "onSecondaryContainer",
"md.comp.filter-chip.with-leading-icon.selected.focus.leading-icon.color": "onSecondaryContainer",
"md.comp.filter-chip.with-leading-icon.selected.hover.leading-icon.color": "onSecondaryContainer",
"md.comp.filter-chip.with-leading-icon.selected.leading-icon.color": "onSecondaryContainer",
"md.comp.filter-chip.with-leading-icon.selected.pressed.leading-icon.color": "onSecondaryContainer",
"md.comp.filter-chip.with-leading-icon.unselected.dragged.leading-icon.color": "primary",
"md.comp.filter-chip.with-leading-icon.unselected.focus.leading-icon.color": "primary",
"md.comp.filter-chip.with-leading-icon.unselected.hover.leading-icon.color": "primary",
"md.comp.filter-chip.with-leading-icon.unselected.leading-icon.color": "primary",
"md.comp.filter-chip.with-leading-icon.unselected.pressed.leading-icon.color": "primary",
"md.comp.filter-chip.with-trailing-icon.disabled.trailing-icon.color": "onSurface",
"md.comp.filter-chip.with-trailing-icon.disabled.trailing-icon.opacity": 0.38,
"md.comp.filter-chip.with-trailing-icon.selected.dragged.trailing-icon.color": "onSecondaryContainer",
"md.comp.filter-chip.with-trailing-icon.selected.focus.trailing-icon.color": "onSecondaryContainer",
"md.comp.filter-chip.with-trailing-icon.selected.hover.trailing-icon.color": "onSecondaryContainer",
"md.comp.filter-chip.with-trailing-icon.selected.pressed.trailing-icon.color": "onSecondaryContainer",
"md.comp.filter-chip.with-trailing-icon.selected.trailing-icon.color": "onSecondaryContainer",
"md.comp.filter-chip.with-trailing-icon.unselected.dragged.trailing-icon.color": "onSurfaceVariant",
"md.comp.filter-chip.with-trailing-icon.unselected.focus.trailing-icon.color": "onSurfaceVariant",
"md.comp.filter-chip.with-trailing-icon.unselected.hover.trailing-icon.color": "onSurfaceVariant",
"md.comp.filter-chip.with-trailing-icon.unselected.pressed.trailing-icon.color": "onSurfaceVariant",
"md.comp.filter-chip.with-trailing-icon.unselected.trailing-icon.color": "onSurfaceVariant"
}
| flutter/dev/tools/gen_defaults/data/chip_filter.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/chip_filter.json",
"repo_id": "flutter",
"token_count": 2677
} | 594 |
{
"version": "v0_206",
"md.comp.icon-button.disabled.icon.color": "onSurface",
"md.comp.icon-button.disabled.icon.opacity": 0.38,
"md.comp.icon-button.focus.indicator.color": "secondary",
"md.comp.icon-button.focus.indicator.outline.offset": "md.sys.state.focus-indicator.outer-offset",
"md.comp.icon-button.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness",
"md.comp.icon-button.icon.size": 24.0,
"md.comp.icon-button.selected.focus.icon.color": "primary",
"md.comp.icon-button.selected.focus.state-layer.color": "primary",
"md.comp.icon-button.selected.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.icon-button.selected.hover.icon.color": "primary",
"md.comp.icon-button.selected.hover.state-layer.color": "primary",
"md.comp.icon-button.selected.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.icon-button.selected.icon.color": "primary",
"md.comp.icon-button.selected.pressed.icon.color": "primary",
"md.comp.icon-button.selected.pressed.state-layer.color": "primary",
"md.comp.icon-button.selected.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.icon-button.state-layer.height": 40.0,
"md.comp.icon-button.state-layer.shape": "md.sys.shape.corner.full",
"md.comp.icon-button.state-layer.width": 40.0,
"md.comp.icon-button.unselected.focus.icon.color": "onSurfaceVariant",
"md.comp.icon-button.unselected.focus.state-layer.color": "onSurfaceVariant",
"md.comp.icon-button.unselected.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.icon-button.unselected.hover.icon.color": "onSurfaceVariant",
"md.comp.icon-button.unselected.hover.state-layer.color": "onSurfaceVariant",
"md.comp.icon-button.unselected.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.icon-button.unselected.icon.color": "onSurfaceVariant",
"md.comp.icon-button.unselected.pressed.icon.color": "onSurfaceVariant",
"md.comp.icon-button.unselected.pressed.state-layer.color": "onSurfaceVariant",
"md.comp.icon-button.unselected.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity"
}
| flutter/dev/tools/gen_defaults/data/icon_button.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/icon_button.json",
"repo_id": "flutter",
"token_count": 825
} | 595 |
{
"version": "v0_206",
"md.comp.search-bar.avatar.shape": "md.sys.shape.corner.full",
"md.comp.search-bar.avatar.size": 30.0,
"md.comp.search-bar.container.color": "surfaceContainerHigh",
"md.comp.search-bar.container.elevation": "md.sys.elevation.level3",
"md.comp.search-bar.container.height": 56.0,
"md.comp.search-bar.container.shape": "md.sys.shape.corner.full",
"md.comp.search-bar.focus.indicator.color": "secondary",
"md.comp.search-bar.focus.indicator.outline.offset": "md.sys.state.focus-indicator.outer-offset",
"md.comp.search-bar.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness",
"md.comp.search-bar.hover.state-layer.color": "onSurface",
"md.comp.search-bar.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.search-bar.hover.supporting-text.color": "onSurfaceVariant",
"md.comp.search-bar.input-text.color": "onSurface",
"md.comp.search-bar.input-text.text-style": "bodyLarge",
"md.comp.search-bar.leading-icon.color": "onSurface",
"md.comp.search-bar.pressed.state-layer.color": "onSurface",
"md.comp.search-bar.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.search-bar.pressed.supporting-text.color": "onSurfaceVariant",
"md.comp.search-bar.supporting-text.color": "onSurfaceVariant",
"md.comp.search-bar.supporting-text.text-style": "bodyLarge",
"md.comp.search-bar.trailing-icon.color": "onSurfaceVariant"
}
| flutter/dev/tools/gen_defaults/data/search_bar.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/search_bar.json",
"repo_id": "flutter",
"token_count": 567
} | 596 |
{
"version": "v0_206",
"md.ref.typeface.brand": "Roboto",
"md.ref.typeface.plain": "Roboto",
"md.ref.typeface.weight-bold": 700,
"md.ref.typeface.weight-medium": 500,
"md.ref.typeface.weight-regular": 400
}
| flutter/dev/tools/gen_defaults/data/typeface.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/typeface.json",
"repo_id": "flutter",
"token_count": 94
} | 597 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'template.dart';
class DrawerTemplate extends TokenTemplate {
const DrawerTemplate(super.blockName, super.fileName, super.tokens);
@override
String generate() => '''
class _${blockName}DefaultsM3 extends DrawerThemeData {
_${blockName}DefaultsM3(this.context)
: super(elevation: ${elevation("md.comp.navigation-drawer.modal.container")});
final BuildContext context;
late final TextDirection direction = Directionality.of(context);
@override
Color? get backgroundColor => ${componentColor("md.comp.navigation-drawer.modal.container")};
@override
Color? get surfaceTintColor => ${colorOrTransparent("md.comp.navigation-drawer.container.surface-tint-layer.color")};
@override
Color? get shadowColor => ${colorOrTransparent("md.comp.navigation-drawer.container.shadow-color")};
// There isn't currently a token for this value, but it is shown in the spec,
// so hard coding here for now.
@override
ShapeBorder? get shape => RoundedRectangleBorder(
borderRadius: const BorderRadiusDirectional.horizontal(
end: Radius.circular(16.0),
).resolve(direction),
);
// There isn't currently a token for this value, but it is shown in the spec,
// so hard coding here for now.
@override
ShapeBorder? get endShape => RoundedRectangleBorder(
borderRadius: const BorderRadiusDirectional.horizontal(
start: Radius.circular(16.0),
).resolve(direction),
);
}
''';
}
| flutter/dev/tools/gen_defaults/lib/drawer_template.dart/0 | {
"file_path": "flutter/dev/tools/gen_defaults/lib/drawer_template.dart",
"repo_id": "flutter",
"token_count": 504
} | 598 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'template.dart';
class SearchBarTemplate extends TokenTemplate {
const SearchBarTemplate(super.blockName, super.fileName, super.tokens, {
super.colorSchemePrefix = '_colors.',
super.textThemePrefix = '_textTheme.'
});
String _surfaceTint() {
final String? color = colorOrTransparent('md.comp.search-bar.container.surface-tint-layer.color');
final String surfaceTintColor = 'MaterialStatePropertyAll<Color>($color);';
if (color == 'Colors.transparent') {
return 'const $surfaceTintColor';
}
return surfaceTintColor;
}
@override
String generate() => '''
class _SearchBarDefaultsM3 extends SearchBarThemeData {
_SearchBarDefaultsM3(this.context);
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
late final TextTheme _textTheme = Theme.of(context).textTheme;
@override
MaterialStateProperty<Color?>? get backgroundColor =>
MaterialStatePropertyAll<Color>(${componentColor("md.comp.search-bar.container")});
@override
MaterialStateProperty<double>? get elevation =>
const MaterialStatePropertyAll<double>(${elevation("md.comp.search-bar.container")});
@override
MaterialStateProperty<Color>? get shadowColor =>
MaterialStatePropertyAll<Color>(_colors.shadow);
@override
MaterialStateProperty<Color>? get surfaceTintColor =>
${_surfaceTint()}
@override
MaterialStateProperty<Color?>? get overlayColor =>
MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return ${componentColor("md.comp.search-bar.pressed.state-layer")};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor("md.comp.search-bar.hover.state-layer")};
}
if (states.contains(MaterialState.focused)) {
return ${colorOrTransparent("md.comp.search-bar.focused.state-layer")};
}
return Colors.transparent;
});
// No default side
@override
MaterialStateProperty<OutlinedBorder>? get shape =>
const MaterialStatePropertyAll<OutlinedBorder>(${shape('md.comp.search-bar.container', '')});
@override
MaterialStateProperty<EdgeInsetsGeometry>? get padding =>
const MaterialStatePropertyAll<EdgeInsetsGeometry>(EdgeInsets.symmetric(horizontal: 8.0));
@override
MaterialStateProperty<TextStyle?> get textStyle =>
MaterialStatePropertyAll<TextStyle?>(${textStyleWithColor('md.comp.search-bar.input-text')});
@override
MaterialStateProperty<TextStyle?> get hintStyle =>
MaterialStatePropertyAll<TextStyle?>(${textStyleWithColor('md.comp.search-bar.supporting-text')});
@override
BoxConstraints get constraints =>
const BoxConstraints(minWidth: 360.0, maxWidth: 800.0, minHeight: ${getToken('md.comp.search-bar.container.height')});
@override
TextCapitalization get textCapitalization => TextCapitalization.none;
}
''';
}
| flutter/dev/tools/gen_defaults/lib/search_bar_template.dart/0 | {
"file_path": "flutter/dev/tools/gen_defaults/lib/search_bar_template.dart",
"repo_id": "flutter",
"token_count": 1002
} | 599 |
## Keycode Generator
This directory contains a keycode generator that can generate Dart code for
the `LogicalKeyboardKey` and `PhysicalKeyboardKey` classes.
It generates multiple files across Flutter. For framework, it generates
* [`keyboard_key.g.dart`](../../../packages/flutter/lib/src/services/keyboard_key.g.dart), which contains the definition and list of logical keys and physical keys; and
* [`keyboard_maps.g.dart`](../../../packages/flutter/lib/src/services/keyboard_maps.g.dart), which contains platform-specific immutable maps used for the `RawKeyboard` API.
For engine, it generates one key mapping file for each platform, as well as some
files for testing purposes.
It draws information from various source bases, including online
repositories, and manual mapping in the `data` subdirectory. It incorporates
this information into a giant list of physical keys
([`physical_key_data.g.json`](data/physical_key_data.g.json)),
and another for logical keys
([`logical_key_data.g.json`](data/logical_key_data.g.json)).
The two files are checked in, and can be used as the data source next time so that
output files can be generated without the Internet.
## Running the tool
The tool can be run based on the existing database. To do this, run:
```bash
/PATH/TO/ROOT/bin/gen_keycodes
```
The tool can also be run by rebuilding the database by drawing online information
anew before generating the files. To do this, run:
```bash
/PATH/TO/ROOT/bin/gen_keycodes --collect
```
This will generate `physical_key_data.g.json` and `logical_key_data.g.json`. These
files should be checked in.
By default this tool assumes that the gclient directory for flutter/engine
and the root for the flutter/flutter are placed at the same folder. If not,
use `--engine-root=/ENGINE/GCLIENT/ROOT` to specify the engine root.
Other options can be found using `--help`.
## Key ID Scheme
To provide keys with unique ID codes, Flutter uses a scheme to assign keycodes
which keeps us out of the business of minting new codes ourselves. This applies
both logical keys and physical keys.
The codes are meant to be opaque to the user, and should never be unpacked for
meaning, since the coding scheme could change at any time and the meaning is
likely to be retrievable more reliably and correctly from the API.
However, if you are porting Flutter to a new platform, you should follow the
following guidelines for specifying key codes.
The key code is a 52-bit integer (due to the limitation of JavaScript). The
entire namespace is divided into 32-bit *planes*. The upper 20 bits of the ID
represent the plane ID, while the lower 32 bits represent values in the plane.
For example, plane 0x1 refers to the range 0x1 0000 0000 - 0x1 FFFF FFFF. Each
plane manages how the values within the range are assigned.
The planes are planned as follows:
- **Plane 0x00**: The Unicode plane. For logical keys, this plane contains keys
that generate Unicode characters when pressed (this includes dead keys, but
not e.g. function keys or shift keys). The value is defined as the Unicode
code point corresponding to the character, lower case and without modifier
keys if possible. Examples are Key A (0x61), Digit 1 (0x31), Colon (0x3A),
and Key Ù (0xD9). (The "Colon" key represents a keyboard key that prints the
":" character without modifiers, which can be found on the French layout. On
the US layout, the key that prints ":" is the Semicolon key.) For physical
keys, this plane contains keys from USB HID usages.
- **Plane 0x01**: The unprintable plane. This plane contains logical keys that
are defined by the [Chromium key
list](https://chromium.googlesource.com/codesearch/chromium/src/+/refs/heads/master/ui/events/keycodes/dom/dom_key_data.inc)
and do not generate Unicode characters. The value is defined as the macro
value defined by the Chromium key list. Examples are CapsLock (0x105),
ArrowUp (0x304), F1 (0x801), Hiragata (0x716), and TVPower (0xD4B).
Some keys that exist in the Chromium key list are not present in Flutter in this plane, most notably
modifiers keys (such as Shift). See the Flutter plane below for more
information.
- **Plane 0x02**: The Flutter plane. This plane contains keys that are
defined by Flutter. Modifier keys are placed in this plane, because Flutter
distinguishes between sided modifier keys (for example "ShiftLeft" and
"ShiftRight"), while the web doesn't (only has "Shift"). Other examples are
numpad keys and gamepad keys.
- **Plane 0x03-0x0F**: Reserved.
- **Plane 0x10-0x1F**: Platform planes managed by Flutter. Each platform plane
corresponds to a Flutter embedding officially supported by Flutter. The
platforms are listed as follows:
| Code | Platform |
| ---- | -------- |
| 0x11 | Android |
| 0x12 | Fuchsia |
| 0x13 | iOS |
| 0x14 | macOS |
| 0x15 | Gtk |
| 0x16 | Windows |
| 0x17 | Web |
| 0x18 | GLFW |
Platform planes store keys that are private to the Flutter embedding of this
platform. This most likely means that these keys have not been officially
recognized by Flutter.
The value scheme within a platform plane is decided by the platform,
typically using the other fields from the platform's native key event.
In time, keys that originally belong to a platform plane might be added to
Flutter, especially if a key is found shared by multiple platforms. The values
of that key will be changed to a new value within the Flutter plane, and all
platforms managed by Flutter will start to send the new value, making it a
breaking change. Therefore, when handling an unrecognized key on a platform
managed by Flutter, it is recommended to file a new issue to add this value
to `keyboard_key.g.dart` instead of using the platform-plane value. However,
for a custom platform (see below), since the platform author has full control
over key mapping, such change will not cause breakage and it is recommended
to use the platform-plane value to avoid adding platform-exclusive values
to the framework.
- **Plane 0x20-0x2F**: Custom platform planes. Similar to Flutter's platform
planes, but for private use by custom platforms.
| flutter/dev/tools/gen_keycodes/README.md/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/README.md",
"repo_id": "flutter",
"token_count": 1717
} | 600 |
{
"Backspace": ["Backspace"],
"Tab": ["Tab"],
"Enter": ["Enter"],
"Escape": ["Escape"],
"CapsLock": ["CapsLock"],
"NumLock": ["NumLock"],
"ArrowDown": ["ArrowDown"],
"ArrowLeft": ["ArrowLeft"],
"ArrowRight": ["ArrowRight"],
"ArrowUp": ["ArrowUp"],
"End": ["End"],
"Home": ["Home"],
"PageDown": ["PageDown"],
"PageUp": ["PageUp"],
"Insert": ["Insert"],
"Delete": ["Delete"],
"ContextMenu": ["ContextMenu"],
"F1": ["F1"],
"F2": ["F2"],
"F3": ["F3"],
"F4": ["F4"],
"F5": ["F5"],
"F6": ["F6"],
"F7": ["F7"],
"F8": ["F8"],
"F9": ["F9"],
"F10": ["F10"],
"F11": ["F11"],
"F12": ["F12"],
"F13": ["F13"],
"F14": ["F14"],
"F15": ["F15"],
"F16": ["F16"],
"F17": ["F17"],
"F18": ["F18"],
"F19": ["F19"],
"F20": ["F20"],
"NumpadEnter": ["NumpadEnter"],
"NumpadMultiply": ["NumpadMultiply"],
"NumpadAdd": ["NumpadAdd"],
"NumpadComma": ["NumpadComma"],
"NumpadSubtract": ["NumpadSubtract"],
"NumpadDecimal": ["NumpadDecimal"],
"NumpadDivide": ["NumpadDivide"],
"Numpad0": ["Numpad0"],
"Numpad1": ["Numpad1"],
"Numpad2": ["Numpad2"],
"Numpad3": ["Numpad3"],
"Numpad4": ["Numpad4"],
"Numpad5": ["Numpad5"],
"Numpad6": ["Numpad6"],
"Numpad7": ["Numpad7"],
"Numpad8": ["Numpad8"],
"Numpad9": ["Numpad9"],
"NumpadEqual": ["NumpadEqual"],
"AltLeft": ["AltLeft"],
"ControlLeft": ["ControlLeft"],
"MetaLeft": ["MetaLeft"],
"ShiftLeft": ["ShiftLeft"],
"AltRight": ["AltRight"],
"ControlRight": ["ControlRight"],
"MetaRight": ["MetaRight"],
"ShiftRight": ["ShiftRight"],
"Lang1": ["Lang1"],
"Lang2": ["Lang2"],
"Lang3": ["Lang3"],
"Lang4": ["Lang4"],
"Lang5": ["Lang5"],
"IntlYen": ["IntlYen"],
"IntlRo": ["IntlRo"],
"AudioVolumeUp": ["AudioVolumeUp"],
"AudioVolumeDown": ["AudioVolumeDown"],
"AudioVolumeMute": ["AudioVolumeMute"]
}
| flutter/dev/tools/gen_keycodes/data/ios_logical_to_physical.json/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/data/ios_logical_to_physical.json",
"repo_id": "flutter",
"token_count": 845
} | 601 |
// 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.
#include "flutter/shell/platform/windows/keyboard_key_embedder_handler.h"
#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/windows_flutter_key_map_cc.tmpl
// instead.
//
// See flutter/flutter:dev/tools/gen_keycodes/README.md for more information.
namespace flutter {
std::map<uint64_t, uint64_t> KeyboardKeyEmbedderHandler::windowsToPhysicalMap_ =
{
@@@WINDOWS_SCAN_CODE_MAP@@@
};
std::map<uint64_t, uint64_t> KeyboardKeyEmbedderHandler::windowsToLogicalMap_ =
{
@@@WINDOWS_KEY_CODE_MAP@@@
};
std::map<uint64_t, uint64_t> KeyboardKeyEmbedderHandler::scanCodeToLogicalMap_ =
{
@@@WINDOWS_SCAN_CODE_TO_LOGICAL_MAP@@@
};
@@@MASK_CONSTANTS@@@
} // namespace flutter
| flutter/dev/tools/gen_keycodes/data/windows_flutter_key_map_cc.tmpl/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/data/windows_flutter_key_map_cc.tmpl",
"repo_id": "flutter",
"token_count": 386
} | 602 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:io';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
import 'constants.dart';
/// The location of the Flutter root directory, based on the known location of
/// this script.
final Directory flutterRoot = Directory(path.dirname(Platform.script.toFilePath())).parent.parent.parent.parent;
String get dataRoot => testDataRoot ?? _dataRoot;
String _dataRoot = path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data');
/// Allows overriding of the [dataRoot] for testing purposes.
@visibleForTesting
String? testDataRoot;
/// Converts `FOO_BAR` to `FooBar`.
String shoutingToUpperCamel(String shouting) {
final RegExp initialLetter = RegExp(r'(?:_|^)([^_])([^_]*)');
final String snake = shouting.toLowerCase();
final String result = snake.replaceAllMapped(initialLetter, (Match match) {
return match.group(1)!.toUpperCase() + match.group(2)!.toLowerCase();
});
return result;
}
/// Converts 'FooBar' to 'fooBar'.
///
/// 'TVFoo' should be convert to 'tvFoo'.
/// 'KeyX' should be convert to 'keyX'.
String upperCamelToLowerCamel(String upperCamel) {
final RegExp initialGroup = RegExp(r'^([A-Z]([A-Z]*|[^A-Z]*))([A-Z]([^A-Z]|$)|$)');
return upperCamel.replaceFirstMapped(initialGroup, (Match match) {
return match.group(1)!.toLowerCase() + (match.group(3) ?? '');
});
}
/// Converts 'fooBar' to 'FooBar'.
String lowerCamelToUpperCamel(String lowerCamel) {
return lowerCamel.substring(0, 1).toUpperCase() + lowerCamel.substring(1);
}
/// A list of Dart reserved words.
///
/// Since these are Dart reserved words, we can't use them as-is for enum names.
const List<String> kDartReservedWords = <String>[
'abstract',
'as',
'assert',
'async',
'await',
'break',
'case',
'catch',
'class',
'const',
'continue',
'covariant',
'default',
'deferred',
'do',
'dynamic',
'else',
'enum',
'export',
'extends',
'external',
'factory',
'false',
'final',
'finally',
'for',
'Function',
'get',
'hide',
'if',
'implements',
'import',
'in',
'interface',
'is',
'library',
'mixin',
'new',
'null',
'on',
'operator',
'part',
'rethrow',
'return',
'set',
'show',
'static',
'super',
'switch',
'sync',
'this',
'throw',
'true',
'try',
'typedef',
'var',
'void',
'while',
'with',
'yield',
];
/// Converts an integer into a hex string with the given number of digits.
String toHex(int? value, {int digits = 8}) {
if (value == null) {
return 'null';
}
return '0x${value.toRadixString(16).padLeft(digits, '0')}';
}
/// Parses an integer from a hex string.
int getHex(String input) {
return int.parse(input, radix: 16);
}
/// Given an [input] string, wraps the text at 80 characters and prepends each
/// line with the [prefix] string. Use for generated comments.
String wrapString(String input, {required String prefix}) {
final int wrapWidth = 80 - prefix.length;
final StringBuffer result = StringBuffer();
final List<String> words = input.split(RegExp(r'\s+'));
String currentLine = words.removeAt(0);
for (final String word in words) {
if ((currentLine.length + word.length) < wrapWidth) {
currentLine += ' $word';
} else {
result.writeln('$prefix$currentLine');
currentLine = word;
}
}
if (currentLine.isNotEmpty) {
result.writeln('$prefix$currentLine');
}
return result.toString();
}
/// Run `fn` with each corresponding element from list1 and list2.
///
/// If `list1` has a different length from `list2`, the execution is aborted
/// after printing an error.
///
/// An null list is considered a list with length 0.
void zipStrict<T1, T2>(Iterable<T1> list1, Iterable<T2> list2, void Function(T1, T2) fn) {
assert(list1.length == list2.length);
final Iterator<T1> it1 = list1.iterator;
final Iterator<T2> it2 = list2.iterator;
while (it1.moveNext()) {
it2.moveNext();
fn(it1.current, it2.current);
}
}
/// Read a Map<String, String> out of its string representation in JSON.
Map<String, String> parseMapOfString(String jsonString) {
return (json.decode(jsonString) as Map<String, dynamic>).cast<String, String>();
}
/// Read a Map<String, List<String>> out of its string representation in JSON.
Map<String, List<String>> parseMapOfListOfString(String jsonString) {
final Map<String, List<dynamic>> dynamicMap = (json.decode(jsonString) as Map<String, dynamic>).cast<String, List<dynamic>>();
return dynamicMap.map<String, List<String>>((String key, List<dynamic> value) {
return MapEntry<String, List<String>>(key, value.cast<String>());
});
}
Map<String, List<String?>> parseMapOfListOfNullableString(String jsonString) {
final Map<String, List<dynamic>> dynamicMap = (json.decode(jsonString) as Map<String, dynamic>).cast<String, List<dynamic>>();
return dynamicMap.map<String, List<String?>>((String key, List<dynamic> value) {
return MapEntry<String, List<String?>>(key, value.cast<String?>());
});
}
Map<String, bool> parseMapOfBool(String jsonString) {
return (json.decode(jsonString) as Map<String, dynamic>).cast<String, bool>();
}
/// Reverse the map of { fromValue -> list of toValue } to { toValue -> fromValue } and return.
Map<String, String> reverseMapOfListOfString(Map<String, List<String>> inMap, void Function(String fromValue, String newToValue) onDuplicate) {
final Map<String, String> result = <String, String>{};
inMap.forEach((String fromValue, List<String> toValues) {
for (final String toValue in toValues) {
if (result.containsKey(toValue)) {
onDuplicate(fromValue, toValue);
continue;
}
result[toValue] = fromValue;
}
});
return result;
}
/// Remove entries whose value `isEmpty` or is null, and return the map.
///
/// Will modify the input map.
Map<String, dynamic> removeEmptyValues(Map<String, dynamic> map) {
return map..removeWhere((String key, dynamic value) {
if (value == null) {
return true;
}
if (value is Map<String, dynamic>) {
final Map<String, dynamic> regularizedMap = removeEmptyValues(value);
return regularizedMap.isEmpty;
}
if (value is Iterable<dynamic>) {
return value.isEmpty;
}
return false;
});
}
void addNameValue(List<String> names, List<int> values, String name, int value) {
final int foundIndex = values.indexOf(value);
if (foundIndex == -1) {
names.add(name);
values.add(value);
} else {
if (!RegExp(r'(^|, )abc1($|, )').hasMatch(name)) {
names[foundIndex] = '${names[foundIndex]}, $name';
}
}
}
enum DeduplicateBehavior {
// Warn the duplicate entry.
kWarn,
// Skip the latter duplicate entry.
kSkip,
// Keep all duplicate entries.
kKeep,
}
/// The information for a line used by [OutputLines].
class OutputLine<T extends Comparable<Object>> {
OutputLine(this.key, String value)
: values = <String>[value];
final T key;
final List<String> values;
}
/// A utility class to build join a number of lines in a sorted order.
///
/// Use [add] to add a line and associate it with an index. Use [sortedJoin] to
/// get the joined string of these lines joined sorting them in the order of the
/// index.
class OutputLines<T extends Comparable<Object>> {
OutputLines(this.mapName, {this.behavior = DeduplicateBehavior.kWarn});
/// What to do if there are entries with the same key.
final DeduplicateBehavior behavior;
/// The name for this map.
///
/// Used in warning messages.
final String mapName;
final Map<T, OutputLine<T>> lines = <T, OutputLine<T>>{};
void add(T key, String line) {
final OutputLine<T>? existing = lines[key];
if (existing != null) {
switch (behavior) {
case DeduplicateBehavior.kWarn:
print('Warn: Request to add $key to map "$mapName" as:\n $line\n but it already exists as:\n ${existing.values[0]}');
return;
case DeduplicateBehavior.kSkip:
return;
case DeduplicateBehavior.kKeep:
existing.values.add(line);
return;
}
}
lines[key] = OutputLine<T>(key, line);
}
String join() {
return lines.values.map((OutputLine<T> line) => line.values.join('\n')).join('\n');
}
String sortedJoin() {
return (lines.values.toList()
..sort((OutputLine<T> a, OutputLine<T> b) => a.key.compareTo(b.key)))
.map((OutputLine<T> line) => line.values.join('\n'))
.join('\n');
}
}
int toPlane(int value, int plane) {
return (value & kValueMask.value) + (plane & kPlaneMask.value);
}
int getPlane(int value) {
return value & kPlaneMask.value;
}
| flutter/dev/tools/gen_keycodes/lib/utils.dart/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/lib/utils.dart",
"repo_id": "flutter",
"token_count": 3180
} | 603 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:args/args.dart';
import 'package:path/path.dart' as path;
/// If no `copies` param is passed in, we scale the generated app up to 60k lines.
const int kTargetLineCount = 60 * 1024;
/// Make `n` copies of flutter_gallery.
void main(List<String> args) {
// If we're run from the `tools` dir, set the cwd to the repo root.
if (path.basename(Directory.current.path) == 'tools') {
Directory.current = Directory.current.parent.parent;
}
final ArgParser argParser = ArgParser();
argParser.addOption('out');
argParser.addOption('copies');
argParser.addFlag('delete', negatable: false);
argParser.addFlag('help', abbr: 'h', negatable: false);
final ArgResults results = argParser.parse(args);
if (results['help'] as bool) {
print('Generate n copies of flutter_gallery.\n');
print('usage: dart mega_gallery.dart <options>');
print(argParser.usage);
exit(0);
}
final Directory source = Directory(_normalize('dev/integration_tests/flutter_gallery'));
final Directory out = Directory(_normalize(results['out'] as String));
if (results['delete'] as bool) {
if (out.existsSync()) {
print('Deleting ${out.path}');
out.deleteSync(recursive: true);
}
exit(0);
}
if (!results.wasParsed('out')) {
print('The --out parameter is required.');
print(argParser.usage);
exit(1);
}
int copies;
if (!results.wasParsed('copies')) {
final SourceStats stats = getStatsFor(_dir(source, 'lib'));
copies = (kTargetLineCount / stats.lines).round();
} else {
copies = int.parse(results['copies'] as String);
}
print('Making $copies copies of flutter_gallery.');
print('');
print('Stats:');
print(' packages/flutter : ${getStatsFor(Directory("packages/flutter"))}');
print(' dev/integration_tests/flutter_gallery : ${getStatsFor(Directory("dev/integration_tests/flutter_gallery"))}');
final Directory lib = _dir(out, 'lib');
if (lib.existsSync()) {
lib.deleteSync(recursive: true);
}
// Copy everything that's not a symlink, dot directory, or build/.
_copy(source, out);
// Make n - 1 copies.
for (int i = 1; i < copies; i++) {
_copyGallery(out, i);
}
// Create a new entry-point.
_createEntry(_file(out, 'lib/main.dart'), copies);
// Update the pubspec.
String pubspec = _file(out, 'pubspec.yaml').readAsStringSync();
pubspec = pubspec.replaceAll('../../packages/flutter', '../../../packages/flutter');
_file(out, 'pubspec.yaml').writeAsStringSync(pubspec);
// Replace the (flutter_gallery specific) analysis_options.yaml file with a default one.
_file(out, 'analysis_options.yaml').writeAsStringSync(
'''
analyzer:
errors:
# See analysis_options.yaml in the flutter root for context.
deprecated_member_use: ignore
deprecated_member_use_from_same_package: ignore
'''
);
_file(out, '.dartignore').writeAsStringSync('');
// Count source lines and number of files; tell how to run it.
print(' ${path.relative(results["out"] as String)} : ${getStatsFor(out)}');
}
// TODO(devoncarew): Create an entry-point that builds a UI with all `n` copies.
void _createEntry(File mainFile, int copies) {
final StringBuffer imports = StringBuffer();
for (int i = 1; i < copies; i++) {
imports.writeln('// ignore: unused_import');
imports.writeln("import 'gallery_$i/main.dart' as main_$i;");
}
final String contents = '''
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'gallery/app.dart';
${imports.toString().trim()}
void main() {
runApp(const GalleryApp());
}
''';
mainFile.writeAsStringSync(contents);
}
void _copyGallery(Directory galleryDir, int index) {
final Directory lib = _dir(galleryDir, 'lib');
final Directory dest = _dir(lib, 'gallery_$index');
dest.createSync();
// Copy demo/, gallery/, and main.dart.
_copy(_dir(lib, 'demo'), _dir(dest, 'demo'));
_copy(_dir(lib, 'gallery'), _dir(dest, 'gallery'));
_file(dest, 'main.dart').writeAsBytesSync(_file(lib, 'main.dart').readAsBytesSync());
}
void _copy(Directory source, Directory target) {
if (!target.existsSync()) {
target.createSync(recursive: true);
}
for (final FileSystemEntity entity in source.listSync(followLinks: false)) {
final String name = path.basename(entity.path);
if (entity is Directory) {
if (name == 'build' || name.startsWith('.')) {
continue;
}
_copy(entity, Directory(path.join(target.path, name)));
} else if (entity is File) {
if (name == '.packages' || name == 'pubspec.lock') {
continue;
}
final File dest = File(path.join(target.path, name));
dest.writeAsBytesSync(entity.readAsBytesSync());
}
}
}
Directory _dir(Directory parent, String name) => Directory(path.join(parent.path, name));
File _file(Directory parent, String name) => File(path.join(parent.path, name));
String _normalize(String filePath) => path.normalize(path.absolute(filePath));
class SourceStats {
int files = 0;
int lines = 0;
@override
String toString() => '${_comma(files).padLeft(3)} files, ${_comma(lines).padLeft(6)} lines';
}
SourceStats getStatsFor(Directory dir, [SourceStats? stats]) {
stats ??= SourceStats();
for (final FileSystemEntity entity in dir.listSync(followLinks: false)) {
final String name = path.basename(entity.path);
if (entity is File && name.endsWith('.dart')) {
stats.files += 1;
stats.lines += _lineCount(entity);
} else if (entity is Directory && !name.startsWith('.')) {
getStatsFor(entity, stats);
}
}
return stats;
}
int _lineCount(File file) {
return file.readAsLinesSync().where((String line) {
line = line.trim();
if (line.isEmpty || line.startsWith('//')) {
return false;
}
return true;
}).length;
}
String _comma(int count) {
final String str = count.toString();
if (str.length > 3) {
return '${str.substring(0, str.length - 3)},${str.substring(str.length - 3)}';
}
return str;
}
| flutter/dev/tools/mega_gallery.dart/0 | {
"file_path": "flutter/dev/tools/mega_gallery.dart",
"repo_id": "flutter",
"token_count": 2217
} | 604 |
<svg id="svg_build_00" xmlns="http://www.w3.org/2000/svg" width="48px" height="48px" >
<g if="group_1">
<path id="path_1" d="M 0,19.0 L 48.0, 19.0 L 48.0, 29.0 L 0, 29.0 Z " fill="#000000" />
<path id="path_2" d="M 0,34.0 L 48.0, 34.0 L 48.0, 44.0 L 0, 44.0 Z " fill="#000000" />
</g>
</svg>
| flutter/dev/tools/vitool/test_assets/bars_group.svg/0 | {
"file_path": "flutter/dev/tools/vitool/test_assets/bars_group.svg",
"repo_id": "flutter",
"token_count": 159
} | 605 |
// 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 base [CupertinoListSection] and [CupertinoListTile].
void main() => runApp(const CupertinoListSectionBaseApp());
class CupertinoListSectionBaseApp extends StatelessWidget {
const CupertinoListSectionBaseApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
home: ListSectionBaseExample(),
);
}
}
class ListSectionBaseExample extends StatelessWidget {
const ListSectionBaseExample({super.key});
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
child: CupertinoListSection(
header: const Text('My Reminders'),
children: <CupertinoListTile>[
CupertinoListTile(
title: const Text('Open pull request'),
leading: Container(
width: double.infinity,
height: double.infinity,
color: CupertinoColors.activeGreen,
),
trailing: const CupertinoListTileChevron(),
onTap: () => Navigator.of(context).push(
CupertinoPageRoute<void>(
builder: (BuildContext context) {
return const _SecondPage(text: 'Open pull request');
},
),
),
),
CupertinoListTile(
title: const Text('Push to master'),
leading: Container(
width: double.infinity,
height: double.infinity,
color: CupertinoColors.systemRed,
),
additionalInfo: const Text('Not available'),
),
CupertinoListTile(
title: const Text('View last commit'),
leading: Container(
width: double.infinity,
height: double.infinity,
color: CupertinoColors.activeOrange,
),
additionalInfo: const Text('12 days ago'),
trailing: const CupertinoListTileChevron(),
onTap: () => Navigator.of(context).push(
CupertinoPageRoute<void>(
builder: (BuildContext context) {
return const _SecondPage(text: 'Last commit');
},
),
),
),
],
),
);
}
}
class _SecondPage extends StatelessWidget {
const _SecondPage({required this.text});
final String text;
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
child: Center(
child: Text(text),
),
);
}
}
| flutter/examples/api/lib/cupertino/list_section/list_section_base.0.dart/0 | {
"file_path": "flutter/examples/api/lib/cupertino/list_section/list_section_base.0.dart",
"repo_id": "flutter",
"token_count": 1223
} | 606 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
/// Flutter code sample for [CupertinoSlidingSegmentedControl].
enum Sky { midnight, viridian, cerulean }
Map<Sky, Color> skyColors = <Sky, Color>{
Sky.midnight: const Color(0xff191970),
Sky.viridian: const Color(0xff40826d),
Sky.cerulean: const Color(0xff007ba7),
};
void main() => runApp(const SegmentedControlApp());
class SegmentedControlApp extends StatelessWidget {
const SegmentedControlApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
theme: CupertinoThemeData(brightness: Brightness.light),
home: SegmentedControlExample(),
);
}
}
class SegmentedControlExample extends StatefulWidget {
const SegmentedControlExample({super.key});
@override
State<SegmentedControlExample> createState() => _SegmentedControlExampleState();
}
class _SegmentedControlExampleState extends State<SegmentedControlExample> {
Sky _selectedSegment = Sky.midnight;
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
backgroundColor: skyColors[_selectedSegment],
navigationBar: CupertinoNavigationBar(
// This Cupertino segmented control has the enum "Sky" as the type.
middle: CupertinoSlidingSegmentedControl<Sky>(
backgroundColor: CupertinoColors.systemGrey2,
thumbColor: skyColors[_selectedSegment]!,
// This represents the currently selected segmented control.
groupValue: _selectedSegment,
// Callback that sets the selected segmented control.
onValueChanged: (Sky? value) {
if (value != null) {
setState(() {
_selectedSegment = value;
});
}
},
children: const <Sky, Widget>{
Sky.midnight: Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Text(
'Midnight',
style: TextStyle(color: CupertinoColors.white),
),
),
Sky.viridian: Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Text(
'Viridian',
style: TextStyle(color: CupertinoColors.white),
),
),
Sky.cerulean: Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Text(
'Cerulean',
style: TextStyle(color: CupertinoColors.white),
),
),
},
),
),
child: Center(
child: Text(
'Selected Segment: ${_selectedSegment.name}',
style: const TextStyle(color: CupertinoColors.white),
),
),
);
}
}
| flutter/examples/api/lib/cupertino/segmented_control/cupertino_sliding_segmented_control.0.dart/0 | {
"file_path": "flutter/examples/api/lib/cupertino/segmented_control/cupertino_sliding_segmented_control.0.dart",
"repo_id": "flutter",
"token_count": 1277
} | 607 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [AppBar].
final List<int> _items = List<int>.generate(51, (int index) => index);
void main() => runApp(const AppBarApp());
class AppBarApp extends StatelessWidget {
const AppBarApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
colorSchemeSeed: const Color(0xff6750a4),
useMaterial3: true,
),
home: const AppBarExample(),
);
}
}
class AppBarExample extends StatefulWidget {
const AppBarExample({super.key});
@override
State<AppBarExample> createState() => _AppBarExampleState();
}
class _AppBarExampleState extends State<AppBarExample> {
bool shadowColor = false;
double? scrolledUnderElevation;
@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 Scaffold(
appBar: AppBar(
title: const Text('AppBar Demo'),
scrolledUnderElevation: scrolledUnderElevation,
shadowColor: shadowColor ? Theme.of(context).colorScheme.shadow : null,
),
body: GridView.builder(
itemCount: _items.length,
padding: const EdgeInsets.all(8.0),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
childAspectRatio: 2.0,
mainAxisSpacing: 10.0,
crossAxisSpacing: 10.0,
),
itemBuilder: (BuildContext context, int index) {
if (index == 0) {
return Center(
child: Text(
'Scroll to see the Appbar in effect.',
style: Theme.of(context).textTheme.labelLarge,
textAlign: TextAlign.center,
),
);
}
return Container(
alignment: Alignment.center,
// tileColor: _items[index].isOdd ? oddItemColor : evenItemColor,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: _items[index].isOdd ? oddItemColor : evenItemColor,
),
child: Text('Item $index'),
);
},
),
bottomNavigationBar: BottomAppBar(
child: Padding(
padding: const EdgeInsets.all(8),
child: OverflowBar(
overflowAlignment: OverflowBarAlignment.center,
alignment: MainAxisAlignment.center,
overflowSpacing: 5.0,
children: <Widget>[
ElevatedButton.icon(
onPressed: () {
setState(() {
shadowColor = !shadowColor;
});
},
icon: Icon(
shadowColor ? Icons.visibility_off : Icons.visibility,
),
label: const Text('shadow color'),
),
const SizedBox(width: 5),
ElevatedButton(
onPressed: () {
if (scrolledUnderElevation == null) {
setState(() {
// Default elevation is 3.0, increment by 1.0.
scrolledUnderElevation = 4.0;
});
} else {
setState(() {
scrolledUnderElevation = scrolledUnderElevation! + 1.0;
});
}
},
child: Text(
'scrolledUnderElevation: ${scrolledUnderElevation ?? 'default'}',
),
),
],
),
),
),
);
}
}
| flutter/examples/api/lib/material/app_bar/app_bar.1.dart/0 | {
"file_path": "flutter/examples/api/lib/material/app_bar/app_bar.1.dart",
"repo_id": "flutter",
"token_count": 1933
} | 608 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [BottomNavigationBar].
void main() => runApp(const BottomNavigationBarExampleApp());
class BottomNavigationBarExampleApp extends StatelessWidget {
const BottomNavigationBarExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: BottomNavigationBarExample(),
);
}
}
class BottomNavigationBarExample extends StatefulWidget {
const BottomNavigationBarExample({super.key});
@override
State<BottomNavigationBarExample> createState() => _BottomNavigationBarExampleState();
}
class _BottomNavigationBarExampleState extends State<BottomNavigationBarExample> {
int _selectedIndex = 0;
static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: Home',
style: optionStyle,
),
Text(
'Index 1: Business',
style: optionStyle,
),
Text(
'Index 2: School',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}
| flutter/examples/api/lib/material/bottom_navigation_bar/bottom_navigation_bar.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/bottom_navigation_bar/bottom_navigation_bar.0.dart",
"repo_id": "flutter",
"token_count": 839
} | 609 |
// 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 [ChipAttributes.avatarBoxConstraints].
void main() => runApp(const AvatarBoxConstraintsApp());
class AvatarBoxConstraintsApp extends StatelessWidget {
const AvatarBoxConstraintsApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: AvatarBoxConstraintsExample(),
),
),
);
}
}
class AvatarBoxConstraintsExample extends StatelessWidget {
const AvatarBoxConstraintsExample({super.key});
@override
Widget build(BuildContext context) {
return const Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RawChip(
avatarBoxConstraints: BoxConstraints.tightForFinite(),
avatar: Icon(Icons.star),
label: SizedBox(
width: 150,
child: Text(
'One line text.',
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
),
),
SizedBox(height: 10),
RawChip(
avatarBoxConstraints: BoxConstraints.tightForFinite(),
avatar: Icon(Icons.star),
label: SizedBox(
width: 150,
child: Text(
'This text will wrap into two lines.',
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
),
),
SizedBox(height: 10),
RawChip(
avatarBoxConstraints: BoxConstraints.tightForFinite(),
avatar: Icon(Icons.star),
label: SizedBox(
width: 150,
child: Text(
'This is a very long text that will wrap into three lines.',
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
),
),
],
);
}
}
| flutter/examples/api/lib/material/chip/chip_attributes.avatar_box_constraints.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/chip/chip_attributes.avatar_box_constraints.0.dart",
"repo_id": "flutter",
"token_count": 961
} | 610 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/// Flutter code sample for [AlertDialog].
void main() => runApp(const AdaptiveAlertDialogApp());
class AdaptiveAlertDialogApp extends StatelessWidget {
const AdaptiveAlertDialogApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
// Try this: set the platform to TargetPlatform.android and see the difference
theme: ThemeData(platform: TargetPlatform.iOS, useMaterial3: true),
home: Scaffold(
appBar: AppBar(title: const Text('AlertDialog Sample')),
body: const Center(
child: AdaptiveDialogExample(),
),
),
);
}
}
class AdaptiveDialogExample extends StatelessWidget {
const AdaptiveDialogExample({super.key});
Widget adaptiveAction({
required BuildContext context,
required VoidCallback onPressed,
required Widget child
}) {
final ThemeData theme = Theme.of(context);
switch (theme.platform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
return TextButton(onPressed: onPressed, child: child);
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return CupertinoDialogAction(onPressed: onPressed, child: child);
}
}
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () => showAdaptiveDialog<String>(
context: context,
builder: (BuildContext context) => AlertDialog.adaptive(
title: const Text('AlertDialog Title'),
content: const Text('AlertDialog description'),
actions: <Widget>[
adaptiveAction(
context: context,
onPressed: () => Navigator.pop(context, 'Cancel'),
child: const Text('Cancel'),
),
adaptiveAction(
context: context,
onPressed: () => Navigator.pop(context, 'OK'),
child: const Text('OK'),
),
],
),
),
child: const Text('Show Dialog'),
);
}
}
| flutter/examples/api/lib/material/dialog/adaptive_alert_dialog.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/dialog/adaptive_alert_dialog.0.dart",
"repo_id": "flutter",
"token_count": 887
} | 611 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.