text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2014 The Flutter 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:test/test.dart' hide isInstanceOf; import 'common.dart'; import 'constants.dart'; /// Matches an [AndroidSemanticsNode]. /// /// Any properties which aren't supplied are ignored during the comparison, /// with the exception of `isHeading`. The heading property is not available /// on all versions of Android. If it is not available on the tested version, /// it will be match whatever it is compared against. /// /// This matcher is intended to compare the accessibility values generated by /// the Android accessibility bridge, and not the semantics object created by /// the Flutter framework. Matcher hasAndroidSemantics({ String? text, String? contentDescription, String? className, int? id, Rect? rect, Size? size, List<AndroidSemanticsAction>? actions, List<AndroidSemanticsAction>? ignoredActions, List<AndroidSemanticsNode>? children, bool? isChecked, bool? isCheckable, bool? isEditable, bool? isEnabled, bool? isFocusable, bool? isFocused, bool? isHeading, bool? isPassword, bool? isLongClickable, }) { return _AndroidSemanticsMatcher( text: text, contentDescription: contentDescription, className: className, rect: rect, size: size, id: id, actions: actions, ignoredActions: ignoredActions, isChecked: isChecked, isCheckable: isCheckable, isEditable: isEditable, isEnabled: isEnabled, isFocusable: isFocusable, isFocused: isFocused, isHeading: isHeading, isPassword: isPassword, isLongClickable: isLongClickable, ); } class _AndroidSemanticsMatcher extends Matcher { _AndroidSemanticsMatcher({ this.text, this.contentDescription, this.className, this.id, this.actions, this.ignoredActions, this.rect, this.size, this.isChecked, this.isCheckable, this.isEnabled, this.isEditable, this.isFocusable, this.isFocused, this.isHeading, this.isPassword, this.isLongClickable, }) : assert(ignoredActions == null || actions != null, 'actions must not be null if ignoredActions is not null'), assert(ignoredActions == null || !actions!.any(ignoredActions.contains)); final String? text; final String? className; final String? contentDescription; final int? id; final List<AndroidSemanticsAction>? actions; final List<AndroidSemanticsAction>? ignoredActions; final Rect? rect; final Size? size; final bool? isChecked; final bool? isCheckable; final bool? isEditable; final bool? isEnabled; final bool? isFocusable; final bool? isFocused; final bool? isHeading; final bool? isPassword; final bool? isLongClickable; @override Description describe(Description description) { description.add('AndroidSemanticsNode'); if (text != null) { description.add(' with text: $text'); } if (contentDescription != null) { description.add( 'with contentDescription $contentDescription'); } if (className != null) { description.add(' with className: $className'); } if (id != null) { description.add(' with id: $id'); } if (actions != null) { description.add(' with actions: $actions'); } if (ignoredActions != null) { description.add(' with ignoredActions: $ignoredActions'); } if (rect != null) { description.add(' with rect: $rect'); } if (size != null) { description.add(' with size: $size'); } if (isChecked != null) { description.add(' with flag isChecked: $isChecked'); } if (isEditable != null) { description.add(' with flag isEditable: $isEditable'); } if (isEnabled != null) { description.add(' with flag isEnabled: $isEnabled'); } if (isFocusable != null) { description.add(' with flag isFocusable: $isFocusable'); } if (isFocused != null) { description.add(' with flag isFocused: $isFocused'); } if (isHeading != null) { description.add(' with flag isHeading: $isHeading'); } if (isPassword != null) { description.add(' with flag isPassword: $isPassword'); } if (isLongClickable != null) { description.add(' with flag isLongClickable: $isLongClickable'); } return description; } @override bool matches(covariant AndroidSemanticsNode item, Map<dynamic, dynamic> matchState) { if (text != null && text != item.text) { return _failWithMessage('Expected text: $text', matchState); } if (contentDescription != null && contentDescription != item.contentDescription) { return _failWithMessage('Expected contentDescription: $contentDescription', matchState); } if (className != null && className != item.className) { return _failWithMessage('Expected className: $className', matchState); } if (id != null && id != item.id) { return _failWithMessage('Expected id: $id', matchState); } if (rect != null && rect != item.getRect()) { return _failWithMessage('Expected rect: $rect', matchState); } if (size != null && size != item.getSize()) { return _failWithMessage('Expected size: $size', matchState); } if (actions != null) { final List<AndroidSemanticsAction> itemActions = item.getActions(); if (ignoredActions != null) { itemActions.removeWhere(ignoredActions!.contains); } if (!unorderedEquals(actions!).matches(itemActions, matchState)) { final List<String> actionsString = actions!.map<String>((AndroidSemanticsAction action) => action.toString()).toList()..sort(); final List<String> itemActionsString = itemActions.map<String>((AndroidSemanticsAction action) => action.toString()).toList()..sort(); final Set<String> unexpectedInString = itemActionsString.toSet().difference(actionsString.toSet()); final Set<String> missingInString = actionsString.toSet().difference(itemActionsString.toSet()); if (missingInString.isEmpty && unexpectedInString.isEmpty) { return true; } return _failWithMessage('Expected actions: $actionsString\nActual actions: $itemActionsString\nUnexpected: $unexpectedInString\nMissing: $missingInString', matchState); } } if (isChecked != null && isChecked != item.isChecked) { return _failWithMessage('Expected isChecked: $isChecked', matchState); } if (isCheckable != null && isCheckable != item.isCheckable) { return _failWithMessage('Expected isCheckable: $isCheckable', matchState); } if (isEditable != null && isEditable != item.isEditable) { return _failWithMessage('Expected isEditable: $isEditable', matchState); } if (isEnabled != null && isEnabled != item.isEnabled) { return _failWithMessage('Expected isEnabled: $isEnabled', matchState); } if (isFocusable != null && isFocusable != item.isFocusable) { return _failWithMessage('Expected isFocusable: $isFocusable', matchState); } if (isFocused != null && isFocused != item.isFocused) { return _failWithMessage('Expected isFocused: $isFocused', matchState); } // Heading is not available in all Android versions, so match anything if it is not set by the platform if (isHeading != null && isHeading != item.isHeading && item.isHeading != null) { return _failWithMessage('Expected isHeading: $isHeading', matchState); } if (isPassword != null && isPassword != item.isPassword) { return _failWithMessage('Expected isPassword: $isPassword', matchState); } if (isLongClickable != null && isLongClickable != item.isLongClickable) { return _failWithMessage('Expected longClickable: $isLongClickable', matchState); } return true; } @override Description describeMismatch(dynamic item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) { final String? failure = matchState['failure'] as String?; return mismatchDescription.add(failure ?? 'hasAndroidSemantics matcher does not complete successfully'); } bool _failWithMessage(String value, Map<dynamic, dynamic> matchState) { matchState['failure'] = value; return false; } }
flutter/dev/integration_tests/android_semantics_testing/lib/src/matcher.dart/0
{ "file_path": "flutter/dev/integration_tests/android_semantics_testing/lib/src/matcher.dart", "repo_id": "flutter", "token_count": 2884 }
512
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Cocoa import FlutterMacOS let DATE: UInt8 = 128 let PAIR: UInt8 = 129 class Pair { let first: Any? let second: Any? init(first: Any?, second: Any?) { self.first = first self.second = second } } class ExtendedWriter: FlutterStandardWriter { override func writeValue(_ value: Any) { if let date = value as? Date { self.writeByte(DATE) let time = date.timeIntervalSince1970 var ms = Int64(time * 1000.0) self.writeBytes(&ms, length: UInt(MemoryLayout<Int64>.size)) } else if let pair = value as? Pair { self.writeByte(PAIR) self.writeValue(pair.first!) self.writeValue(pair.second!) } else { super.writeValue(value) } } } class ExtendedReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { if type == DATE { var ms: Int64 = 0 self.readBytes(&ms, length: UInt(MemoryLayout<Int64>.size)) let time: Double = Double(ms) / 1000.0 return NSDate(timeIntervalSince1970: time) } else if type == PAIR { return Pair(first: self.readValue(), second: self.readValue()) } else { return super.readValue(ofType: type) } } } class ExtendedReaderWriter: FlutterStandardReaderWriter { override func reader(with data: Data) -> FlutterStandardReader { return ExtendedReader(data: data) } override func writer(with data: NSMutableData) -> FlutterStandardWriter { return ExtendedWriter(data: data) } } class MainFlutterWindow: NSWindow { override func awakeFromNib() { let flutterViewController = FlutterViewController() let windowFrame = self.frame self.contentViewController = flutterViewController self.setFrame(windowFrame, display: true) RegisterGeneratedPlugins(registry: flutterViewController) let registrar = flutterViewController.registrar(forPlugin: "channel-integration-test") setupMessagingHandshakeOnChannel( FlutterBasicMessageChannel( name: "binary-msg", binaryMessenger: registrar.messenger, codec: FlutterBinaryCodec.sharedInstance())) setupMessagingHandshakeOnChannel( FlutterBasicMessageChannel( name: "string-msg", binaryMessenger: registrar.messenger, codec: FlutterStringCodec.sharedInstance())) setupMessagingHandshakeOnChannel( FlutterBasicMessageChannel( name: "json-msg", binaryMessenger: registrar.messenger, codec: FlutterJSONMessageCodec.sharedInstance())) setupMessagingHandshakeOnChannel( FlutterBasicMessageChannel( name: "std-msg", binaryMessenger: registrar.messenger, codec: FlutterStandardMessageCodec(readerWriter: ExtendedReaderWriter()))) setupMethodHandshakeOnChannel( FlutterMethodChannel( name: "json-method", binaryMessenger: registrar.messenger, codec: FlutterJSONMethodCodec.sharedInstance())) setupMethodHandshakeOnChannel( FlutterMethodChannel( name: "std-method", binaryMessenger: registrar.messenger, codec: FlutterStandardMethodCodec(readerWriter: ExtendedReaderWriter()))) FlutterBasicMessageChannel( name: "std-echo", binaryMessenger: registrar.messenger, codec: FlutterStandardMessageCodec.sharedInstance() ).setMessageHandler { message, reply in reply(message) } super.awakeFromNib() } func setupMessagingHandshakeOnChannel(_ channel: FlutterBasicMessageChannel) { channel.setMessageHandler { message, reply in channel.sendMessage(message) { messageReply in channel.sendMessage(messageReply) reply(message) } } } func setupMethodHandshakeOnChannel(_ channel: FlutterMethodChannel) { channel.setMethodCallHandler { call, result in if call.method == "success" { channel.invokeMethod(call.method, arguments: call.arguments) { value in channel.invokeMethod(call.method, arguments: value) result(call.arguments) } } else if call.method == "error" { channel.invokeMethod(call.method, arguments: call.arguments) { value in let error = value as! FlutterError channel.invokeMethod(call.method, arguments: error.details) result(error) } } else { channel.invokeMethod(call.method, arguments: call.arguments) { value in channel.invokeMethod(call.method, arguments: nil) result(FlutterMethodNotImplemented) } } } } }
flutter/dev/integration_tests/channels/macos/Runner/MainFlutterWindow.swift/0
{ "file_path": "flutter/dev/integration_tests/channels/macos/Runner/MainFlutterWindow.swift", "repo_id": "flutter", "token_count": 1717 }
513
# This is a Gradle generated file for dependency locking. # Manual edits can break the build and are not advised. # This file is expected to be part of source control. androidx.databinding:databinding-common:7.2.0=classpath androidx.databinding:databinding-compiler-common:7.2.0=classpath com.android.databinding:baseLibrary:7.2.0=classpath com.android.tools.analytics-library:crash:30.2.0=classpath com.android.tools.analytics-library:protos:30.2.0=classpath com.android.tools.analytics-library:shared:30.2.0=classpath com.android.tools.analytics-library:tracker:30.2.0=classpath com.android.tools.build.jetifier:jetifier-core:1.0.0-beta09=classpath com.android.tools.build.jetifier:jetifier-processor:1.0.0-beta09=classpath com.android.tools.build:aapt2-proto:7.2.0-7984345=classpath com.android.tools.build:aaptcompiler:7.2.0=classpath com.android.tools.build:apksig:7.2.0=classpath com.android.tools.build:apkzlib:7.2.0=classpath com.android.tools.build:builder-model:7.2.0=classpath com.android.tools.build:builder-test-api:7.2.0=classpath com.android.tools.build:builder:7.2.0=classpath com.android.tools.build:bundletool:1.8.2=classpath com.android.tools.build:gradle-api:7.2.0=classpath com.android.tools.build:gradle:7.2.0=classpath com.android.tools.build:manifest-merger:30.2.0=classpath com.android.tools.build:transform-api:2.0.0-deprecated-use-gradle-api=classpath com.android.tools.ddms:ddmlib:30.2.0=classpath com.android.tools.layoutlib:layoutlib-api:30.2.0=classpath com.android.tools.lint:lint-model:30.2.0=classpath com.android.tools.lint:lint-typedef-remover:30.2.0=classpath com.android.tools.utp:android-device-provider-ddmlib-proto:30.2.0=classpath com.android.tools.utp:android-device-provider-gradle-proto:30.2.0=classpath com.android.tools.utp:android-test-plugin-host-additional-test-output-proto:30.2.0=classpath com.android.tools.utp:android-test-plugin-host-coverage-proto:30.2.0=classpath com.android.tools.utp:android-test-plugin-host-retention-proto:30.2.0=classpath com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:30.2.0=classpath com.android.tools:annotations:30.2.0=classpath com.android.tools:common:30.2.0=classpath com.android.tools:dvlib:30.2.0=classpath com.android.tools:repository:30.2.0=classpath com.android.tools:sdk-common:30.2.0=classpath com.android.tools:sdklib:30.2.0=classpath com.android:signflinger:7.2.0=classpath com.android:zipflinger:7.2.0=classpath com.fasterxml.jackson.core:jackson-annotations:2.11.1=classpath com.fasterxml.jackson.core:jackson-core:2.11.1=classpath com.fasterxml.jackson.core:jackson-databind:2.11.1=classpath com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.11.1=classpath com.fasterxml.jackson.module:jackson-module-jaxb-annotations:2.11.1=classpath com.fasterxml.jackson.module:jackson-module-kotlin:2.11.1=classpath com.fasterxml.woodstox:woodstox-core:6.2.1=classpath com.github.gundy:semver4j:0.16.4=classpath com.google.android:annotations:4.1.1.4=classpath com.google.api.grpc:proto-google-common-protos:1.12.0=classpath com.google.auto.value:auto-value-annotations:1.6.2=classpath com.google.code.findbugs:jsr305:3.0.2=classpath com.google.code.gson:gson:2.8.6=classpath com.google.crypto.tink:tink:1.3.0-rc2=classpath com.google.dagger:dagger:2.28.3=classpath com.google.errorprone:error_prone_annotations:2.3.4=classpath com.google.flatbuffers:flatbuffers-java:1.12.0=classpath com.google.guava:failureaccess:1.0.1=classpath com.google.guava:guava:30.1-jre=classpath com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=classpath com.google.j2objc:j2objc-annotations:1.3=classpath com.google.jimfs:jimfs:1.1=classpath com.google.protobuf:protobuf-java-util:3.10.0=classpath com.google.protobuf:protobuf-java:3.10.0=classpath com.google.testing.platform:core-proto:0.0.8-alpha07=classpath com.googlecode.json-simple:json-simple:1.1=classpath com.googlecode.juniversalchardet:juniversalchardet:1.0.3=classpath com.squareup:javapoet:1.10.0=classpath com.squareup:javawriter:2.5.0=classpath com.sun.activation:javax.activation:1.2.0=classpath com.sun.istack:istack-commons-runtime:3.0.8=classpath com.sun.xml.fastinfoset:FastInfoset:1.2.16=classpath commons-codec:commons-codec:1.11=classpath commons-io:commons-io:2.4=classpath commons-logging:commons-logging:1.2=classpath de.undercouch:gradle-download-task:4.0.2=classpath io.grpc:grpc-api:1.21.1=classpath io.grpc:grpc-context:1.21.1=classpath io.grpc:grpc-core:1.21.1=classpath io.grpc:grpc-netty:1.21.1=classpath io.grpc:grpc-protobuf-lite:1.21.1=classpath io.grpc:grpc-protobuf:1.21.1=classpath io.grpc:grpc-stub:1.21.1=classpath io.netty:netty-buffer:4.1.34.Final=classpath io.netty:netty-codec-http2:4.1.34.Final=classpath io.netty:netty-codec-http:4.1.34.Final=classpath io.netty:netty-codec-socks:4.1.34.Final=classpath io.netty:netty-codec:4.1.34.Final=classpath io.netty:netty-common:4.1.34.Final=classpath io.netty:netty-handler-proxy:4.1.34.Final=classpath io.netty:netty-handler:4.1.34.Final=classpath io.netty:netty-resolver:4.1.34.Final=classpath io.netty:netty-transport:4.1.34.Final=classpath io.opencensus:opencensus-api:0.21.0=classpath io.opencensus:opencensus-contrib-grpc-metrics:0.21.0=classpath it.unimi.dsi:fastutil:8.4.0=classpath jakarta.activation:jakarta.activation-api:1.2.1=classpath jakarta.xml.bind:jakarta.xml.bind-api:2.3.2=classpath javax.inject:javax.inject:1=classpath net.java.dev.jna:jna-platform:5.6.0=classpath net.java.dev.jna:jna:5.6.0=classpath net.sf.jopt-simple:jopt-simple:4.9=classpath net.sf.kxml:kxml2:2.3.0=classpath org.antlr:antlr4-runtime:4.5.2-1=classpath org.apache.commons:commons-compress:1.20=classpath org.apache.httpcomponents:httpclient:4.5.9=classpath org.apache.httpcomponents:httpcore:4.4.11=classpath org.apache.httpcomponents:httpmime:4.5.6=classpath org.bitbucket.b_c:jose4j:0.7.0=classpath org.bouncycastle:bcpkix-jdk15on:1.56=classpath org.bouncycastle:bcprov-jdk15on:1.56=classpath org.checkerframework:checker-qual:3.5.0=classpath org.codehaus.mojo:animal-sniffer-annotations:1.17=classpath org.codehaus.woodstox:stax2-api:4.2.1=classpath org.glassfish.jaxb:jaxb-runtime:2.3.2=classpath org.glassfish.jaxb:txw2:2.3.2=classpath org.jdom:jdom2:2.0.6=classpath org.jetbrains.dokka:dokka-core:1.4.32=classpath org.jetbrains.intellij.deps:trove4j:1.0.20181211=classpath org.jetbrains.kotlin:kotlin-android-extensions:1.4.32=classpath org.jetbrains.kotlin:kotlin-annotation-processing-gradle:1.4.32=classpath org.jetbrains.kotlin:kotlin-build-common:1.4.32=classpath org.jetbrains.kotlin:kotlin-compiler-embeddable:1.4.32=classpath org.jetbrains.kotlin:kotlin-compiler-runner:1.4.32=classpath org.jetbrains.kotlin:kotlin-daemon-client:1.4.32=classpath org.jetbrains.kotlin:kotlin-daemon-embeddable:1.4.32=classpath org.jetbrains.kotlin:kotlin-gradle-plugin-api:1.4.32=classpath org.jetbrains.kotlin:kotlin-gradle-plugin-model:1.4.32=classpath org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.32=classpath org.jetbrains.kotlin:kotlin-reflect:1.5.31=classpath org.jetbrains.kotlin:kotlin-script-runtime:1.4.32=classpath org.jetbrains.kotlin:kotlin-scripting-common:1.4.32=classpath org.jetbrains.kotlin:kotlin-scripting-compiler-embeddable:1.4.32=classpath org.jetbrains.kotlin:kotlin-scripting-compiler-impl-embeddable:1.4.32=classpath org.jetbrains.kotlin:kotlin-scripting-jvm:1.4.32=classpath org.jetbrains.kotlin:kotlin-stdlib-common:1.5.31=classpath org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.5.31=classpath org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.5.31=classpath org.jetbrains.kotlin:kotlin-stdlib:1.5.31=classpath org.jetbrains.kotlin:kotlin-util-io:1.4.32=classpath org.jetbrains.kotlin:kotlin-util-klib:1.4.32=classpath org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.4.1=classpath org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.1=classpath org.jetbrains:annotations:13.0=classpath org.jetbrains:markdown-jvm:0.2.1=classpath org.jetbrains:markdown:0.2.1=classpath org.json:json:20180813=classpath org.jsoup:jsoup:1.13.1=classpath org.jvnet.staxex:stax-ex:1.8.1=classpath org.ow2.asm:asm-analysis:9.1=classpath org.ow2.asm:asm-commons:9.1=classpath org.ow2.asm:asm-tree:9.1=classpath org.ow2.asm:asm-util:9.1=classpath org.ow2.asm:asm:9.1=classpath org.slf4j:slf4j-api:1.7.30=classpath org.tensorflow:tensorflow-lite-metadata:0.1.0-rc2=classpath xerces:xercesImpl:2.12.0=classpath xml-apis:xml-apis:1.4.01=classpath empty=
flutter/dev/integration_tests/deferred_components_test/android/buildscript-gradle.lockfile/0
{ "file_path": "flutter/dev/integration_tests/deferred_components_test/android/buildscript-gradle.lockfile", "repo_id": "flutter", "token_count": 3740 }
514
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. plugins { id "com.android.application" id "dev.flutter.flutter-gradle-plugin" } def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withInputStream { stream -> localProperties.load(stream) } } android { compileSdk flutter.compileSdkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { applicationId "io.flutter.externalui" minSdkVersion flutter.minSdkVersion targetSdkVersion flutter.targetSdkVersion versionCode 1 versionName "1.0" } buildTypes { release { signingConfig signingConfigs.debug } } } flutter { source '../..' }
flutter/dev/integration_tests/external_textures/android/app/build.gradle/0
{ "file_path": "flutter/dev/integration_tests/external_textures/android/app/build.gradle", "repo_id": "flutter", "token_count": 386 }
515
# Flutter gallery An older copy of the Flutter gallery demo application used for integration testing. For the current Flutter Gallery app sample, see this repo: https://github.com/flutter/gallery ## Icon Android launcher icons were generated using Android Asset Studio: https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html#foreground.type=image&foreground.space.trim=1&foreground.space.pad=0.1&foreColor=607d8b%2C0&crop=0&backgroundShape=square&backColor=fafafa%2C100&effects=none
flutter/dev/integration_tests/flutter_gallery/README.md/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/README.md", "repo_id": "flutter", "token_count": 150 }
516
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Raw data for the animation demo. import 'package:flutter/material.dart'; const Color _mariner = Color(0xFF3B5F8F); const Color _mediumPurple = Color(0xFF8266D4); const Color _tomato = Color(0xFFF95B57); const Color _mySin = Color(0xFFF3A646); const String _kGalleryAssetsPackage = 'flutter_gallery_assets'; class SectionDetail { const SectionDetail({ this.title, this.subtitle, this.imageAsset, this.imageAssetPackage, }); final String? title; final String? subtitle; final String? imageAsset; final String? imageAssetPackage; } @immutable class Section { const Section({ this.title, this.backgroundAsset, this.backgroundAssetPackage, this.leftColor, this.rightColor, this.details, }); final String? title; final String? backgroundAsset; final String? backgroundAssetPackage; final Color? leftColor; final Color? rightColor; final List<SectionDetail>? details; @override bool operator==(Object other) { return other is Section && other.title == title; } @override int get hashCode => title.hashCode; } // TODO(hansmuller): replace the SectionDetail images and text. Get rid of // the const vars like _eyeglassesDetail and insert a variety of titles and // image SectionDetails in the allSections list. const SectionDetail _eyeglassesDetail = SectionDetail( imageAsset: 'products/sunnies.png', imageAssetPackage: _kGalleryAssetsPackage, title: 'Flutter enables interactive animation', subtitle: '3K views - 5 days', ); const SectionDetail _eyeglassesImageDetail = SectionDetail( imageAsset: 'products/sunnies.png', imageAssetPackage: _kGalleryAssetsPackage, ); const SectionDetail _seatingDetail = SectionDetail( imageAsset: 'products/table.png', imageAssetPackage: _kGalleryAssetsPackage, title: 'Flutter enables interactive animation', subtitle: '3K views - 5 days', ); const SectionDetail _seatingImageDetail = SectionDetail( imageAsset: 'products/table.png', imageAssetPackage: _kGalleryAssetsPackage, ); const SectionDetail _decorationDetail = SectionDetail( imageAsset: 'products/earrings.png', imageAssetPackage: _kGalleryAssetsPackage, title: 'Flutter enables interactive animation', subtitle: '3K views - 5 days', ); const SectionDetail _decorationImageDetail = SectionDetail( imageAsset: 'products/earrings.png', imageAssetPackage: _kGalleryAssetsPackage, ); const SectionDetail _protectionDetail = SectionDetail( imageAsset: 'products/hat.png', imageAssetPackage: _kGalleryAssetsPackage, title: 'Flutter enables interactive animation', subtitle: '3K views - 5 days', ); const SectionDetail _protectionImageDetail = SectionDetail( imageAsset: 'products/hat.png', imageAssetPackage: _kGalleryAssetsPackage, ); final List<Section> allSections = <Section>[ const Section( title: 'SUNGLASSES', leftColor: _mediumPurple, rightColor: _mariner, backgroundAsset: 'products/sunnies.png', backgroundAssetPackage: _kGalleryAssetsPackage, details: <SectionDetail>[ _eyeglassesDetail, _eyeglassesImageDetail, _eyeglassesDetail, _eyeglassesDetail, _eyeglassesDetail, _eyeglassesDetail, ], ), const Section( title: 'FURNITURE', leftColor: _tomato, rightColor: _mediumPurple, backgroundAsset: 'products/table.png', backgroundAssetPackage: _kGalleryAssetsPackage, details: <SectionDetail>[ _seatingDetail, _seatingImageDetail, _seatingDetail, _seatingDetail, _seatingDetail, _seatingDetail, ], ), const Section( title: 'JEWELRY', leftColor: _mySin, rightColor: _tomato, backgroundAsset: 'products/earrings.png', backgroundAssetPackage: _kGalleryAssetsPackage, details: <SectionDetail>[ _decorationDetail, _decorationImageDetail, _decorationDetail, _decorationDetail, _decorationDetail, _decorationDetail, ], ), const Section( title: 'HEADWEAR', leftColor: Colors.white, rightColor: _tomato, backgroundAsset: 'products/hat.png', backgroundAssetPackage: _kGalleryAssetsPackage, details: <SectionDetail>[ _protectionDetail, _protectionImageDetail, _protectionDetail, _protectionDetail, _protectionDetail, _protectionDetail, ], ), ];
flutter/dev/integration_tests/flutter_gallery/lib/demo/animation/sections.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/animation/sections.dart", "repo_id": "flutter", "token_count": 1589 }
517
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; import '../../gallery/demo.dart'; class CupertinoSliderDemo extends StatefulWidget { const CupertinoSliderDemo({super.key}); static const String routeName = '/cupertino/slider'; @override State<CupertinoSliderDemo> createState() => _CupertinoSliderDemoState(); } class _CupertinoSliderDemoState extends State<CupertinoSliderDemo> { double _value = 25.0; double _discreteValue = 20.0; @override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( middle: const Text('Sliders'), // We're specifying a back label here because the previous page is a // Material page. CupertinoPageRoutes could auto-populate these back // labels. previousPageTitle: 'Cupertino', trailing: CupertinoDemoDocumentationButton(CupertinoSliderDemo.routeName), ), child: DefaultTextStyle( style: CupertinoTheme.of(context).textTheme.textStyle, child: SafeArea( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Column( mainAxisSize: MainAxisSize.min, children: <Widget> [ CupertinoSlider( value: _value, max: 100.0, onChanged: (double value) { setState(() { _value = value; }); }, ), Text('Cupertino Continuous: ${_value.toStringAsFixed(1)}'), ], ), Column( mainAxisSize: MainAxisSize.min, children: <Widget> [ CupertinoSlider( value: _discreteValue, max: 100.0, divisions: 5, onChanged: (double value) { setState(() { _discreteValue = value; }); }, ), Text('Cupertino Discrete: $_discreteValue'), ], ), ], ), ), ), ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_slider_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_slider_demo.dart", "repo_id": "flutter", "token_count": 1361 }
518
// Copyright 2014 The Flutter 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 '../../gallery/demo.dart'; const String _kAsset0 = 'people/square/trevor.png'; const String _kAsset1 = 'people/square/stella.png'; const String _kAsset2 = 'people/square/sandra.png'; const String _kGalleryAssetsPackage = 'flutter_gallery_assets'; class DrawerDemo extends StatefulWidget { const DrawerDemo({super.key}); static const String routeName = '/material/drawer'; @override State<DrawerDemo> createState() => _DrawerDemoState(); } class _DrawerDemoState extends State<DrawerDemo> with TickerProviderStateMixin { final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>(); static const List<String> _drawerContents = <String>[ 'A', 'B', 'C', 'D', 'E', ]; static final Animatable<Offset> _drawerDetailsTween = Tween<Offset>( begin: const Offset(0.0, -1.0), end: Offset.zero, ).chain(CurveTween( curve: Curves.fastOutSlowIn, )); late AnimationController _controller; late Animation<double> _drawerContentsOpacity; late Animation<Offset> _drawerDetailsPosition; bool _showDrawerContents = true; @override void initState() { super.initState(); _controller = AnimationController( vsync: this, duration: const Duration(milliseconds: 200), ); _drawerContentsOpacity = CurvedAnimation( parent: ReverseAnimation(_controller), curve: Curves.fastOutSlowIn, ); _drawerDetailsPosition = _controller.drive(_drawerDetailsTween); } @override void dispose() { _controller.dispose(); super.dispose(); } IconData? _backIcon() { switch (Theme.of(context).platform) { case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: return Icons.arrow_back; case TargetPlatform.iOS: case TargetPlatform.macOS: return Icons.arrow_back_ios; } } void _showNotImplementedMessage() { Navigator.pop(context); // Dismiss the drawer. ScaffoldMessenger.of(context).showSnackBar(const SnackBar( content: Text("The drawer's items don't do anything"), )); } @override Widget build(BuildContext context) { return Scaffold( drawerDragStartBehavior: DragStartBehavior.down, key: _scaffoldKey, appBar: AppBar( leading: IconButton( icon: Icon(_backIcon()), alignment: Alignment.centerLeft, tooltip: 'Back', onPressed: () { Navigator.pop(context); }, ), title: const Text('Navigation drawer'), actions: <Widget>[MaterialDemoDocumentationButton(DrawerDemo.routeName)], ), drawer: Drawer( child: Column( children: <Widget>[ UserAccountsDrawerHeader( accountName: const Text('Trevor Widget'), accountEmail: const Text('[email protected]'), currentAccountPicture: const CircleAvatar( backgroundImage: AssetImage( _kAsset0, package: _kGalleryAssetsPackage, ), ), otherAccountsPictures: <Widget>[ GestureDetector( dragStartBehavior: DragStartBehavior.down, onTap: () { _onOtherAccountsTap(context); }, child: Semantics( label: 'Switch to Account B', child: const CircleAvatar( backgroundImage: AssetImage( _kAsset1, package: _kGalleryAssetsPackage, ), ), ), ), GestureDetector( dragStartBehavior: DragStartBehavior.down, onTap: () { _onOtherAccountsTap(context); }, child: Semantics( label: 'Switch to Account C', child: const CircleAvatar( backgroundImage: AssetImage( _kAsset2, package: _kGalleryAssetsPackage, ), ), ), ), ], margin: EdgeInsets.zero, onDetailsPressed: () { _showDrawerContents = !_showDrawerContents; if (_showDrawerContents) { _controller.reverse(); } else { _controller.forward(); } }, ), MediaQuery.removePadding( context: context, // DrawerHeader consumes top MediaQuery padding. removeTop: true, child: Expanded( child: ListView( dragStartBehavior: DragStartBehavior.down, padding: const EdgeInsets.only(top: 8.0), children: <Widget>[ Stack( children: <Widget>[ // The initial contents of the drawer. FadeTransition( opacity: _drawerContentsOpacity, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: _drawerContents.map<Widget>((String id) { return ListTile( leading: CircleAvatar(child: Text(id)), title: Text('Drawer item $id'), onTap: _showNotImplementedMessage, ); }).toList(), ), ), // The drawer's "details" view. SlideTransition( position: _drawerDetailsPosition, child: FadeTransition( opacity: ReverseAnimation(_drawerContentsOpacity), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ ListTile( leading: const Icon(Icons.add), title: const Text('Add account'), onTap: _showNotImplementedMessage, ), ListTile( leading: const Icon(Icons.settings), title: const Text('Manage accounts'), onTap: _showNotImplementedMessage, ), ], ), ), ), ], ), ], ), ), ), ], ), ), body: Center( child: InkWell( onTap: () { _scaffoldKey.currentState!.openDrawer(); }, child: Semantics( button: true, label: 'Open drawer', excludeSemantics: true, child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Container( width: 100.0, height: 100.0, decoration: const BoxDecoration( shape: BoxShape.circle, image: DecorationImage( image: AssetImage( _kAsset0, package: _kGalleryAssetsPackage, ), ), ), ), Padding( padding: const EdgeInsets.only(top: 8.0), child: Text('Tap here to open the drawer', style: Theme.of(context).textTheme.titleMedium, ), ), ], ), ), ), ), ); } void _onOtherAccountsTap(BuildContext context) { showDialog<void>( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('Account switching not implemented.'), actions: <Widget>[ TextButton( child: const Text('OK'), onPressed: () { Navigator.pop(context); }, ), ], ); }, ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/material/drawer_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/drawer_demo.dart", "repo_id": "flutter", "token_count": 5022 }
519
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import '../../gallery/demo.dart'; enum _ReorderableListType { /// A list tile that contains a [CircleAvatar]. horizontalAvatar, /// A list tile that contains a [CircleAvatar]. verticalAvatar, /// A list tile that contains three lines of text and a checkbox. threeLine, } class ReorderableListDemo extends StatefulWidget { const ReorderableListDemo({ super.key }); static const String routeName = '/material/reorderable-list'; @override State<ReorderableListDemo> createState() => _ListDemoState(); } class _ListItem { _ListItem(this.value, this.checkState); final String value; bool? checkState; } class _ListDemoState extends State<ReorderableListDemo> { static final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); PersistentBottomSheetController? _bottomSheet; _ReorderableListType? _itemType = _ReorderableListType.threeLine; bool? _reverse = false; bool _reverseSort = false; final List<_ListItem> _items = <String>[ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', ].map<_ListItem>((String item) => _ListItem(item, false)).toList(); void changeItemType(_ReorderableListType? type) { setState(() { _itemType = type; }); // Rebuild the bottom sheet to reflect the selected list view. _bottomSheet?.setState!(() { // Trigger a rebuild. }); // Close the bottom sheet to give the user a clear view of the list. _bottomSheet?.close(); } void changeReverse(bool? newValue) { setState(() { _reverse = newValue; }); // Rebuild the bottom sheet to reflect the selected list view. _bottomSheet?.setState!(() { // Trigger a rebuild. }); // Close the bottom sheet to give the user a clear view of the list. _bottomSheet?.close(); } void _showConfigurationSheet() { setState(() { _bottomSheet = scaffoldKey.currentState!.showBottomSheet((BuildContext bottomSheetContext) { return DecoratedBox( decoration: const BoxDecoration( border: Border(top: BorderSide(color: Colors.black26)), ), child: ListView( shrinkWrap: true, primary: false, children: <Widget>[ CheckboxListTile( dense: true, title: const Text('Reverse'), value: _reverse, onChanged: changeReverse, ), RadioListTile<_ReorderableListType>( dense: true, title: const Text('Horizontal Avatars'), value: _ReorderableListType.horizontalAvatar, groupValue: _itemType, onChanged: changeItemType, ), RadioListTile<_ReorderableListType>( dense: true, title: const Text('Vertical Avatars'), value: _ReorderableListType.verticalAvatar, groupValue: _itemType, onChanged: changeItemType, ), RadioListTile<_ReorderableListType>( dense: true, title: const Text('Three-line'), value: _ReorderableListType.threeLine, groupValue: _itemType, onChanged: changeItemType, ), ], ), ); }); // Garbage collect the bottom sheet when it closes. _bottomSheet?.closed.whenComplete(() { if (mounted) { setState(() { _bottomSheet = null; }); } }); }); } Widget buildListTile(_ListItem item) { const Widget secondary = Text( 'Even more additional list item information appears on line three.', ); late Widget listTile; switch (_itemType) { case _ReorderableListType.threeLine: listTile = CheckboxListTile( key: Key(item.value), isThreeLine: true, value: item.checkState ?? false, onChanged: (bool? newValue) { setState(() { item.checkState = newValue; }); }, title: Text('This item represents ${item.value}.'), subtitle: secondary, secondary: const Icon(Icons.drag_handle), ); case _ReorderableListType.horizontalAvatar: case _ReorderableListType.verticalAvatar: listTile = SizedBox( key: Key(item.value), height: 100.0, width: 100.0, child: CircleAvatar( backgroundColor: Colors.green, child: Text(item.value), ), ); case null: listTile = Container( key: Key(item.value), ); } return listTile; } void _onReorder(int oldIndex, int newIndex) { setState(() { if (newIndex > oldIndex) { newIndex -= 1; } final _ListItem item = _items.removeAt(oldIndex); _items.insert(newIndex, item); }); } @override Widget build(BuildContext context) { return Scaffold( key: scaffoldKey, appBar: AppBar( title: const Text('Reorderable list'), actions: <Widget>[ MaterialDemoDocumentationButton(ReorderableListDemo.routeName), IconButton( icon: const Icon(Icons.sort_by_alpha), tooltip: 'Sort', onPressed: () { setState(() { _reverseSort = !_reverseSort; _items.sort((_ListItem a, _ListItem b) => _reverseSort ? b.value.compareTo(a.value) : a.value.compareTo(b.value)); }); }, ), IconButton( icon: Icon( Theme.of(context).platform == TargetPlatform.iOS ? Icons.more_horiz : Icons.more_vert, ), tooltip: 'Show menu', onPressed: _bottomSheet == null ? _showConfigurationSheet : null, ), ], ), body: Scrollbar( child: ReorderableListView( primary: true, header: _itemType != _ReorderableListType.threeLine ? Padding( padding: const EdgeInsets.all(8.0), child: Text('Header of the list', style: Theme.of(context).textTheme.headlineSmall)) : null, onReorder: _onReorder, reverse: _reverse!, scrollDirection: _itemType == _ReorderableListType.horizontalAvatar ? Axis.horizontal : Axis.vertical, padding: const EdgeInsets.symmetric(vertical: 8.0), children: _items.map<Widget>(buildListTile).toList(), ), ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/material/reorderable_list_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/reorderable_list_demo.dart", "repo_id": "flutter", "token_count": 3147 }
520
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:scoped_model/scoped_model.dart'; import 'backdrop.dart'; import 'expanding_bottom_sheet.dart'; import 'model/app_state_model.dart'; import 'model/product.dart'; import 'supplemental/asymmetric_view.dart'; class ProductPage extends StatelessWidget { const ProductPage({super.key, this.category = Category.all}); final Category category; @override Widget build(BuildContext context) { return ScopedModelDescendant<AppStateModel>( builder: (BuildContext context, Widget? child, AppStateModel model) { return AsymmetricView(products: model.getProducts()); }); } } class HomePage extends StatelessWidget { const HomePage({ this.expandingBottomSheet, this.backdrop, super.key, }); final ExpandingBottomSheet? expandingBottomSheet; final Backdrop? backdrop; @override Widget build(BuildContext context) { return Stack( children: <Widget>[ if (backdrop != null) backdrop!, Align(alignment: Alignment.bottomRight, child: expandingBottomSheet), ], ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/home.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/home.dart", "repo_id": "flutter", "token_count": 433 }
521
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math'; import 'package:flutter/material.dart'; import 'package:vector_math/vector_math.dart' show Vector2; // Provides calculations for an object moving with inertia and friction using // the equation of motion from physics. // https://en.wikipedia.org/wiki/Equations_of_motion#Constant_translational_acceleration_in_a_straight_line @immutable class InertialMotion { const InertialMotion(this._initialVelocity, this._initialPosition); static const double _kFrictionalAcceleration = 0.01; // How quickly to stop final Velocity _initialVelocity; final Offset _initialPosition; // The position when the motion stops. Offset get finalPosition { return _getPositionAt(Duration(milliseconds: duration.toInt())); } // The total time that the animation takes start to stop in milliseconds. double get duration { return (_initialVelocity.pixelsPerSecond.dx / 1000 / _acceleration.x).abs(); } // The acceleration opposing the initial velocity in x and y components. Vector2 get _acceleration { final double velocityTotal = _initialVelocity.pixelsPerSecond.dx.abs() + _initialVelocity.pixelsPerSecond.dy.abs(); final double vRatioX = _initialVelocity.pixelsPerSecond.dx / velocityTotal; final double vRatioY = _initialVelocity.pixelsPerSecond.dy / velocityTotal; return Vector2( _kFrictionalAcceleration * vRatioX, _kFrictionalAcceleration * vRatioY, ); } // The position at a given time. Offset _getPositionAt(Duration time) { final double xf = _getPosition( r0: _initialPosition.dx, v0: _initialVelocity.pixelsPerSecond.dx / 1000, t: time.inMilliseconds, a: _acceleration.x, ); final double yf = _getPosition( r0: _initialPosition.dy, v0: _initialVelocity.pixelsPerSecond.dy / 1000, t: time.inMilliseconds, a: _acceleration.y, ); return Offset(xf, yf); } // Solve the equation of motion to find the position at a given point in time // in one dimension. double _getPosition({required double r0, required double v0, required int t, required double a}) { // Stop movement when it would otherwise reverse direction. final double stopTime = (v0 / a).abs(); if (t > stopTime) { t = stopTime.toInt(); } return r0 + v0 * t + 0.5 * a * pow(t, 2); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/transformations/transformations_demo_inertial_motion.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/transformations/transformations_demo_inertial_motion.dart", "repo_id": "flutter", "token_count": 842 }
522
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; final ThemeData kLightGalleryTheme = _buildLightTheme(); final ThemeData kDarkGalleryTheme = _buildDarkTheme(); TextTheme _buildTextTheme(TextTheme base) { return base.copyWith( titleLarge: base.titleLarge!.copyWith( fontFamily: 'GoogleSans', ), ); } ThemeData _buildDarkTheme() { const Color primaryColor = Color(0xFF0175c2); const Color secondaryColor = Color(0xFF13B9FD); final ColorScheme colorScheme = const ColorScheme.dark().copyWith( primary: primaryColor, secondary: secondaryColor, onPrimary: Colors.white, error: const Color(0xFFB00020), surface: const Color(0xFF202124), ); final ThemeData base = ThemeData( useMaterial3: false, brightness: Brightness.dark, colorScheme: colorScheme, primaryColor: primaryColor, primaryColorDark: const Color(0xFF0050a0), primaryColorLight: secondaryColor, indicatorColor: Colors.white, canvasColor: const Color(0xFF202124), scaffoldBackgroundColor: const Color(0xFF202124), ); return base.copyWith( textTheme: _buildTextTheme(base.textTheme), primaryTextTheme: _buildTextTheme(base.primaryTextTheme), ); } ThemeData _buildLightTheme() { const Color primaryColor = Color(0xFF0175c2); const Color secondaryColor = Color(0xFF13B9FD); final ColorScheme colorScheme = const ColorScheme.light().copyWith( primary: primaryColor, secondary: secondaryColor, error: const Color(0xFFB00020), ); final ThemeData base = ThemeData( useMaterial3: false, brightness: Brightness.light, colorScheme: colorScheme, primaryColor: primaryColor, indicatorColor: Colors.white, splashColor: Colors.white24, splashFactory: InkRipple.splashFactory, canvasColor: Colors.white, scaffoldBackgroundColor: Colors.white, ); return base.copyWith( textTheme: _buildTextTheme(base.textTheme), primaryTextTheme: _buildTextTheme(base.primaryTextTheme), ); }
flutter/dev/integration_tests/flutter_gallery/lib/gallery/themes.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/gallery/themes.dart", "repo_id": "flutter", "token_count": 720 }
523
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
flutter/dev/integration_tests/flutter_gallery/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/macos/Runner/Configs/Release.xcconfig", "repo_id": "flutter", "token_count": 32 }
524
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_gallery/demo/material/menu_demo.dart'; import 'package:flutter_gallery/gallery/themes.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Menu icon satisfies accessibility contrast ratio guidelines, light mode', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( theme: kLightGalleryTheme, home: const MenuDemo(), )); await expectLater(tester, meetsGuideline(textContrastGuideline)); await expectLater(tester, meetsGuideline(CustomMinimumContrastGuideline(finder: find.byWidgetPredicate((Widget widget) => widget is Icon)))); }); testWidgets('Menu icon satisfies accessibility contrast ratio guidelines, dark mode', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( theme: kDarkGalleryTheme, home: const MenuDemo(), )); await expectLater(tester, meetsGuideline(textContrastGuideline)); await expectLater(tester, meetsGuideline(CustomMinimumContrastGuideline(finder: find.byWidgetPredicate((Widget widget) => widget is Icon)))); }); testWidgets('The selected menu item update test', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( theme: kDarkGalleryTheme, home: const MenuDemo(), )); // Popup the menu. await tester.tap(find.text('An item with a simple menu')); await tester.pumpAndSettle(); // Select one item. await tester.tap(find.text('Menu item value three')); await tester.pumpAndSettle(); // The subtitle updated with the selected item. expect(find.text('Menu item value three'), findsOneWidget); }); }
flutter/dev/integration_tests/flutter_gallery/test/demo/material/menu_demo_test.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/test/demo/material/menu_demo_test.dart", "repo_id": "flutter", "token_count": 597 }
525
# Deprecated settings.gradle This project is meant to test that apps using the deprecated `android/settings.gradle` (_PluginEach_ used until Flutter v1.22.0) can still be built. This project can be removed once apps have been migrated to this new file. Issue: https://github.com/flutter/flutter/issues/54566
flutter/dev/integration_tests/gradle_deprecated_settings/README.md/0
{ "file_path": "flutter/dev/integration_tests/gradle_deprecated_settings/README.md", "repo_id": "flutter", "token_count": 86 }
526
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; MethodChannel channel = const MethodChannel('android_views_integration'); class AndroidPlatformView extends StatelessWidget { /// Creates a platform view for Android, which is rendered as a /// native view. /// `viewType` identifies the type of Android view to create. const AndroidPlatformView({ super.key, this.onPlatformViewCreated, this.useHybridComposition = false, required this.viewType, }); /// The unique identifier for the view type to be embedded by this widget. /// /// A PlatformViewFactory for this type must have been registered. final String viewType; /// Callback to invoke after the platform view has been created. /// /// May be null. final PlatformViewCreatedCallback? onPlatformViewCreated; // Use hybrid composition. final bool useHybridComposition; @override Widget build(BuildContext context) { return PlatformViewLink( viewType: viewType, surfaceFactory: (BuildContext context, PlatformViewController controller) { return AndroidViewSurface( controller: controller as AndroidViewController, gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, hitTestBehavior: PlatformViewHitTestBehavior.opaque, ); }, onCreatePlatformView: (PlatformViewCreationParams params) { print('useHybridComposition=$useHybridComposition'); late AndroidViewController controller; if (useHybridComposition) { controller = PlatformViewsService.initExpensiveAndroidView( id: params.id, viewType: params.viewType, layoutDirection: TextDirection.ltr, ); } else { controller = PlatformViewsService.initSurfaceAndroidView( id: params.id, viewType: params.viewType, layoutDirection: TextDirection.ltr, ); } if (onPlatformViewCreated != null) { controller.addOnPlatformViewCreatedListener(onPlatformViewCreated!); } return controller ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated) ..create(); }, ); } }
flutter/dev/integration_tests/hybrid_android_views/lib/android_platform_view.dart/0
{ "file_path": "flutter/dev/integration_tests/hybrid_android_views/lib/android_platform_view.dart", "repo_id": "flutter", "token_count": 897 }
527
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() { // Disconnects semantics listener for testing purposes. // If the test passes, LifeCycleSpy will rewire the semantics listener back. SwitchableSemanticsBinding.ensureInitialized(); assert(!SwitchableSemanticsBinding.instance.semanticsEnabled); runApp(const LifeCycleSpy()); } /// A Test widget that spies on app life cycle changes. /// /// It will collect the AppLifecycleState sequence during its lifetime, and it /// will rewire semantics harness if the sequence it receives matches the /// expected list. /// /// Rewiring semantics is a signal to native IOS test that the test has passed. class LifeCycleSpy extends StatefulWidget { const LifeCycleSpy({super.key}); @override State<LifeCycleSpy> createState() => _LifeCycleSpyState(); } class _LifeCycleSpyState extends State<LifeCycleSpy> with WidgetsBindingObserver { final List<AppLifecycleState> _expectedLifeCycleSequence = <AppLifecycleState>[ AppLifecycleState.detached, AppLifecycleState.inactive, AppLifecycleState.resumed, ]; List<AppLifecycleState?>? _actualLifeCycleSequence; @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); _actualLifeCycleSequence = <AppLifecycleState?>[ ServicesBinding.instance.lifecycleState, ]; } @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { setState(() { _actualLifeCycleSequence = List<AppLifecycleState>.from(_actualLifeCycleSequence!); _actualLifeCycleSequence?.add(state); }); } @override Widget build(BuildContext context) { if (const ListEquality<AppLifecycleState?>().equals(_actualLifeCycleSequence, _expectedLifeCycleSequence)) { // Rewires the semantics harness if test passes. SwitchableSemanticsBinding.instance.semanticsEnabled = true; } return const MaterialApp( title: 'Flutter View', home: Text('test'), ); } } class SwitchableSemanticsBinding extends WidgetsFlutterBinding { static SwitchableSemanticsBinding get instance => BindingBase.checkInstance(_instance); static SwitchableSemanticsBinding? _instance; static SwitchableSemanticsBinding ensureInitialized() { if (_instance == null) { SwitchableSemanticsBinding(); } return SwitchableSemanticsBinding.instance; } VoidCallback? _originalSemanticsListener; @override void initInstances() { super.initInstances(); _instance = this; _updateHandler(); } @override bool get semanticsEnabled => _semanticsEnabled.value; final ValueNotifier<bool> _semanticsEnabled = ValueNotifier<bool>(false); set semanticsEnabled(bool value) { _semanticsEnabled.value = value; _updateHandler(); } void _updateHandler() { if (_semanticsEnabled.value) { platformDispatcher.onSemanticsEnabledChanged = _originalSemanticsListener; _originalSemanticsListener = null; } else { _originalSemanticsListener = platformDispatcher.onSemanticsEnabledChanged; platformDispatcher.onSemanticsEnabledChanged = null; } } @override void addSemanticsEnabledListener(VoidCallback listener) { _semanticsEnabled.addListener(listener); } @override void removeSemanticsEnabledListener(VoidCallback listener) { _semanticsEnabled.removeListener(listener); } }
flutter/dev/integration_tests/ios_add2app_life_cycle/flutterapp/lib/main.dart/0
{ "file_path": "flutter/dev/integration_tests/ios_add2app_life_cycle/flutterapp/lib/main.dart", "repo_id": "flutter", "token_count": 1206 }
528
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "MainViewController.h" #import "AppDelegate.h" #import "FullScreenViewController.h" @interface MainViewController () @property(nonatomic, strong) UIStackView* stackView; @end @implementation MainViewController - (void)viewDidLoad { [super viewDidLoad]; [self.view setFrame:self.view.window.bounds]; self.title = @"Flutter iOS Demos"; self.view.backgroundColor = UIColor.whiteColor; self.stackView = [[UIStackView alloc] initWithFrame:self.view.frame]; self.stackView.axis = UILayoutConstraintAxisVertical; self.stackView.distribution = UIStackViewDistributionEqualSpacing; self.stackView.alignment = UIStackViewAlignmentCenter; self.stackView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; self.stackView.layoutMargins = UIEdgeInsetsMake(0, 0, 50, 0); self.stackView.layoutMarginsRelativeArrangement = YES; [self.view addSubview:_stackView]; [self addButton:@"Full Screen (Cold)" action:@selector(showFullScreenCold)]; } - (void)showFullScreenCold { FlutterEngine *engine = [(AppDelegate *)[[UIApplication sharedApplication] delegate] engine]; FullScreenViewController *flutterViewController = [[FullScreenViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [self.navigationController pushViewController:flutterViewController animated:NO]; // Animating this is janky because of // transitions with header on the native side. // It's especially bad with a cold engine. } - (void)addButton:(NSString *)title action:(SEL)action { UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; [button setTitle:title forState:UIControlStateNormal]; [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside]; [self.stackView addArrangedSubview:button]; } @end
flutter/dev/integration_tests/ios_add2app_life_cycle/ios_add2app/MainViewController.m/0
{ "file_path": "flutter/dev/integration_tests/ios_add2app_life_cycle/ios_add2app/MainViewController.m", "repo_id": "flutter", "token_count": 814 }
529
<?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>CFBundleDisplayName</key> <string>Flutter Extension Test</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string> <key>CFBundleShortVersionString</key> <string>$(MARKETING_VERSION)</string> <key>CFBundleVersion</key> <string>1</string> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> </array> <key>WKWatchKitApp</key> <true/> </dict> </plist>
flutter/dev/integration_tests/ios_app_with_extensions/ios/watch/Info.plist/0
{ "file_path": "flutter/dev/integration_tests/ios_app_with_extensions/ios/watch/Info.plist", "repo_id": "flutter", "token_count": 426 }
530
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface DualFlutterViewController : UIViewController @property (readonly, strong, nonatomic) FlutterViewController* topFlutterViewController; @property (readonly, strong, nonatomic) FlutterViewController* bottomFlutterViewController; @end NS_ASSUME_NONNULL_END
flutter/dev/integration_tests/ios_host_app/Host/DualFlutterViewController.h/0
{ "file_path": "flutter/dev/integration_tests/ios_host_app/Host/DualFlutterViewController.h", "repo_id": "flutter", "token_count": 144 }
531
#include "Generated.xcconfig"
flutter/dev/integration_tests/ios_platform_view_tests/ios/Flutter/Release.xcconfig/0
{ "file_path": "flutter/dev/integration_tests/ios_platform_view_tests/ios/Flutter/Release.xcconfig", "repo_id": "flutter", "token_count": 12 }
532
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import '../../gallery_localizations.dart'; // BEGIN appbarDemo class AppBarDemo extends StatelessWidget { const AppBarDemo({super.key}); @override Widget build(BuildContext context) { final GalleryLocalizations localization = GalleryLocalizations.of(context)!; return Scaffold( appBar: AppBar( leading: IconButton( tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip, icon: const Icon(Icons.menu), onPressed: () {}, ), title: Text( localization.demoAppBarTitle, ), actions: <Widget>[ IconButton( tooltip: localization.starterAppTooltipFavorite, icon: const Icon( Icons.favorite, ), onPressed: () {}, ), IconButton( tooltip: localization.starterAppTooltipSearch, icon: const Icon( Icons.search, ), onPressed: () {}, ), PopupMenuButton<Text>( itemBuilder: (BuildContext context) { return <PopupMenuEntry<Text>>[ PopupMenuItem<Text>( child: Text( localization.demoNavigationRailFirst, ), ), PopupMenuItem<Text>( child: Text( localization.demoNavigationRailSecond, ), ), PopupMenuItem<Text>( child: Text( localization.demoNavigationRailThird, ), ), ]; }, ) ], ), body: Center( child: Text( localization.cupertinoTabBarHomeTab, ), ), ); } } // END
flutter/dev/integration_tests/new_gallery/lib/demos/material/app_bar_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/material/app_bar_demo.dart", "repo_id": "flutter", "token_count": 1042 }
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:animations/animations.dart'; import 'package:flutter/material.dart'; import '../../gallery_localizations.dart'; // BEGIN sharedZAxisTransitionDemo class SharedZAxisTransitionDemo extends StatelessWidget { const SharedZAxisTransitionDemo({super.key}); @override Widget build(BuildContext context) { return Navigator( onGenerateRoute: (RouteSettings settings) { return _createHomeRoute(); }, ); } Route<void> _createHomeRoute() { return PageRouteBuilder<void>( pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, title: Column( children: <Widget>[ Text(localizations.demoSharedZAxisTitle), Text( '(${localizations.demoSharedZAxisDemoInstructions})', style: Theme.of(context) .textTheme .titleSmall! .copyWith(color: Colors.white), ), ], ), actions: <Widget>[ IconButton( icon: const Icon(Icons.settings), onPressed: () { Navigator.of(context).push<void>(_createSettingsRoute()); }, ), ], ), body: const _RecipePage(), ); }, transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { return SharedAxisTransition( fillColor: Colors.transparent, transitionType: SharedAxisTransitionType.scaled, animation: animation, secondaryAnimation: secondaryAnimation, child: child, ); }, ); } Route<void> _createSettingsRoute() { return PageRouteBuilder<void>( pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) => const _SettingsPage(), transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { return SharedAxisTransition( fillColor: Colors.transparent, transitionType: SharedAxisTransitionType.scaled, animation: animation, secondaryAnimation: secondaryAnimation, child: child, ); }, ); } } class _SettingsPage extends StatelessWidget { const _SettingsPage(); @override Widget build(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; final List<_SettingsInfo> settingsList = <_SettingsInfo>[ _SettingsInfo( Icons.person, localizations.demoSharedZAxisProfileSettingLabel, ), _SettingsInfo( Icons.notifications, localizations.demoSharedZAxisNotificationSettingLabel, ), _SettingsInfo( Icons.security, localizations.demoSharedZAxisPrivacySettingLabel, ), _SettingsInfo( Icons.help, localizations.demoSharedZAxisHelpSettingLabel, ), ]; return Scaffold( appBar: AppBar( title: Text( localizations.demoSharedZAxisSettingsPageTitle, ), ), body: ListView( children: <Widget>[ for (final _SettingsInfo setting in settingsList) _SettingsTile(setting), ], ), ); } } class _SettingsTile extends StatelessWidget { const _SettingsTile(this.settingData); final _SettingsInfo settingData; @override Widget build(BuildContext context) { return Column( children: <Widget>[ ListTile( leading: Icon(settingData.settingIcon), title: Text(settingData.settingsLabel), ), const Divider(thickness: 2), ], ); } } class _SettingsInfo { const _SettingsInfo(this.settingIcon, this.settingsLabel); final IconData settingIcon; final String settingsLabel; } class _RecipePage extends StatelessWidget { const _RecipePage(); @override Widget build(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; final List<_RecipeInfo> savedRecipes = <_RecipeInfo>[ _RecipeInfo( localizations.demoSharedZAxisBurgerRecipeTitle, localizations.demoSharedZAxisBurgerRecipeDescription, 'crane/destinations/eat_2.jpg', ), _RecipeInfo( localizations.demoSharedZAxisSandwichRecipeTitle, localizations.demoSharedZAxisSandwichRecipeDescription, 'crane/destinations/eat_3.jpg', ), _RecipeInfo( localizations.demoSharedZAxisDessertRecipeTitle, localizations.demoSharedZAxisDessertRecipeDescription, 'crane/destinations/eat_4.jpg', ), _RecipeInfo( localizations.demoSharedZAxisShrimpPlateRecipeTitle, localizations.demoSharedZAxisShrimpPlateRecipeDescription, 'crane/destinations/eat_6.jpg', ), _RecipeInfo( localizations.demoSharedZAxisCrabPlateRecipeTitle, localizations.demoSharedZAxisCrabPlateRecipeDescription, 'crane/destinations/eat_8.jpg', ), _RecipeInfo( localizations.demoSharedZAxisBeefSandwichRecipeTitle, localizations.demoSharedZAxisBeefSandwichRecipeDescription, 'crane/destinations/eat_10.jpg', ), ]; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ const SizedBox(height: 8), Padding( padding: const EdgeInsetsDirectional.only(start: 8.0), child: Text(localizations.demoSharedZAxisSavedRecipesListTitle), ), const SizedBox(height: 4), Expanded( child: ListView( padding: const EdgeInsets.all(8), children: <Widget>[ for (final _RecipeInfo recipe in savedRecipes) _RecipeTile(recipe, savedRecipes.indexOf(recipe)) ], ), ), ], ); } } class _RecipeInfo { const _RecipeInfo(this.recipeName, this.recipeDescription, this.recipeImage); final String recipeName; final String recipeDescription; final String recipeImage; } class _RecipeTile extends StatelessWidget { const _RecipeTile(this._recipe, this._index); final _RecipeInfo _recipe; final int _index; @override Widget build(BuildContext context) { return Row( children: <Widget>[ SizedBox( height: 70, width: 100, child: ClipRRect( borderRadius: const BorderRadius.all(Radius.circular(4)), child: Image.asset( _recipe.recipeImage, package: 'flutter_gallery_assets', fit: BoxFit.fill, ), ), ), const SizedBox(width: 24), Expanded( child: Column( children: <Widget>[ ListTile( title: Text(_recipe.recipeName), subtitle: Text(_recipe.recipeDescription), trailing: Text('0${_index + 1}'), ), const Divider(thickness: 2), ], ), ), ], ); } } // END sharedZAxisTransitionDemo
flutter/dev/integration_tests/new_gallery/lib/demos/reference/motion_demo_shared_z_axis_transition.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/reference/motion_demo_shared_z_axis_transition.dart", "repo_id": "flutter", "token_count": 3339 }
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/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:intl/intl.dart'; import '../../data/gallery_options.dart'; import '../../gallery_localizations.dart'; import '../../layout/image_placeholder.dart'; import '../../layout/text_scale.dart'; class ArticleData { ArticleData({ required this.imageUrl, required this.imageAspectRatio, required this.category, required this.title, this.snippet, }); final String imageUrl; final double imageAspectRatio; final String category; final String title; final String? snippet; } class HorizontalArticlePreview extends StatelessWidget { const HorizontalArticlePreview({ super.key, required this.data, this.minutes, }); final ArticleData data; final int? minutes; @override Widget build(BuildContext context) { final TextTheme textTheme = Theme.of(context).textTheme; return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SelectableText( data.category, style: textTheme.titleMedium, ), const SizedBox(height: 12), SelectableText( data.title, style: textTheme.headlineSmall!.copyWith(fontSize: 16), ), ], ), ), if (minutes != null) ...<Widget>[ SelectableText( GalleryLocalizations.of(context)!.craneMinutes(minutes!), style: textTheme.bodyLarge, ), const SizedBox(width: 8), ], FadeInImagePlaceholder( image: AssetImage(data.imageUrl, package: 'flutter_gallery_assets'), placeholder: Container( color: Colors.black.withOpacity(0.1), width: 64 / (1 / data.imageAspectRatio), height: 64, ), fit: BoxFit.cover, excludeFromSemantics: true, ), ], ); } } class VerticalArticlePreview extends StatelessWidget { const VerticalArticlePreview({ super.key, required this.data, this.width, this.headlineTextStyle, this.showSnippet = false, }); final ArticleData data; final double? width; final TextStyle? headlineTextStyle; final bool showSnippet; @override Widget build(BuildContext context) { final TextTheme textTheme = Theme.of(context).textTheme; return SizedBox( width: width ?? double.infinity, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SizedBox( width: double.infinity, child: FadeInImagePlaceholder( image: AssetImage( data.imageUrl, package: 'flutter_gallery_assets', ), placeholder: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { return Container( color: Colors.black.withOpacity(0.1), width: constraints.maxWidth, height: constraints.maxWidth / data.imageAspectRatio, ); }), fit: BoxFit.fitWidth, width: double.infinity, excludeFromSemantics: true, ), ), const SizedBox(height: 12), SelectableText( data.category, style: textTheme.titleMedium, ), const SizedBox(height: 12), SelectableText( data.title, style: headlineTextStyle ?? textTheme.headlineSmall, ), if (showSnippet) ...<Widget>[ const SizedBox(height: 4), SelectableText( data.snippet!, style: textTheme.bodyMedium, ), ], ], ), ); } } List<Widget> buildArticlePreviewItems(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; final Widget articleDivider = Container( margin: const EdgeInsets.symmetric(vertical: 16), color: Colors.black.withOpacity(0.07), height: 1, ); final Widget sectionDivider = Container( margin: const EdgeInsets.symmetric(vertical: 16), color: Colors.black.withOpacity(0.2), height: 1, ); final TextTheme textTheme = Theme.of(context).textTheme; return <Widget>[ VerticalArticlePreview( data: ArticleData( imageUrl: 'fortnightly/fortnightly_healthcare.jpg', imageAspectRatio: 391 / 248, category: localizations.fortnightlyMenuWorld.toUpperCase(), title: localizations.fortnightlyHeadlineHealthcare, ), headlineTextStyle: textTheme.headlineSmall!.copyWith(fontSize: 20), ), articleDivider, HorizontalArticlePreview( data: ArticleData( imageUrl: 'fortnightly/fortnightly_war.png', imageAspectRatio: 1, category: localizations.fortnightlyMenuPolitics.toUpperCase(), title: localizations.fortnightlyHeadlineWar, ), ), articleDivider, HorizontalArticlePreview( data: ArticleData( imageUrl: 'fortnightly/fortnightly_gas.png', imageAspectRatio: 1, category: localizations.fortnightlyMenuTech.toUpperCase(), title: localizations.fortnightlyHeadlineGasoline, ), ), sectionDivider, SelectableText( localizations.fortnightlyLatestUpdates, style: textTheme.titleLarge, ), articleDivider, HorizontalArticlePreview( data: ArticleData( imageUrl: 'fortnightly/fortnightly_army.png', imageAspectRatio: 1, category: localizations.fortnightlyMenuPolitics.toUpperCase(), title: localizations.fortnightlyHeadlineArmy, ), minutes: 2, ), articleDivider, HorizontalArticlePreview( data: ArticleData( imageUrl: 'fortnightly/fortnightly_stocks.png', imageAspectRatio: 77 / 64, category: localizations.fortnightlyMenuWorld.toUpperCase(), title: localizations.fortnightlyHeadlineStocks, ), minutes: 5, ), articleDivider, HorizontalArticlePreview( data: ArticleData( imageUrl: 'fortnightly/fortnightly_fabrics.png', imageAspectRatio: 76 / 64, category: localizations.fortnightlyMenuTech.toUpperCase(), title: localizations.fortnightlyHeadlineFabrics, ), minutes: 4, ), articleDivider, ]; } class HashtagBar extends StatelessWidget { const HashtagBar({super.key}); @override Widget build(BuildContext context) { final Container verticalDivider = Container( margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), color: Colors.black.withOpacity(0.1), width: 1, ); final TextTheme textTheme = Theme.of(context).textTheme; final double height = 32 * reducedTextScale(context); final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return SizedBox( height: height, child: ListView( restorationId: 'hashtag_bar_list_view', scrollDirection: Axis.horizontal, children: <Widget>[ const SizedBox(width: 16), Center( child: SelectableText( '#${localizations.fortnightlyTrendingTechDesign}', style: textTheme.titleSmall, ), ), verticalDivider, Center( child: SelectableText( '#${localizations.fortnightlyTrendingReform}', style: textTheme.titleSmall, ), ), verticalDivider, Center( child: SelectableText( '#${localizations.fortnightlyTrendingHealthcareRevolution}', style: textTheme.titleSmall, ), ), verticalDivider, Center( child: SelectableText( '#${localizations.fortnightlyTrendingGreenArmy}', style: textTheme.titleSmall, ), ), verticalDivider, Center( child: SelectableText( '#${localizations.fortnightlyTrendingStocks}', style: textTheme.titleSmall, ), ), verticalDivider, ], ), ); } } class NavigationMenu extends StatelessWidget { const NavigationMenu({super.key, this.isCloseable = false}); final bool isCloseable; @override Widget build(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return ListView( children: <Widget>[ if (isCloseable) Row( children: <Widget>[ IconButton( icon: const Icon(Icons.close), tooltip: MaterialLocalizations.of(context).closeButtonTooltip, onPressed: () => Navigator.pop(context), ), Image.asset( 'fortnightly/fortnightly_title.png', package: 'flutter_gallery_assets', excludeFromSemantics: true, ), ], ), const SizedBox(height: 32), MenuItem( localizations.fortnightlyMenuFrontPage, header: true, ), MenuItem(localizations.fortnightlyMenuWorld), MenuItem(localizations.fortnightlyMenuUS), MenuItem(localizations.fortnightlyMenuPolitics), MenuItem(localizations.fortnightlyMenuBusiness), MenuItem(localizations.fortnightlyMenuTech), MenuItem(localizations.fortnightlyMenuScience), MenuItem(localizations.fortnightlyMenuSports), MenuItem(localizations.fortnightlyMenuTravel), MenuItem(localizations.fortnightlyMenuCulture), ], ); } } class MenuItem extends StatelessWidget { const MenuItem(this.title, {super.key, this.header = false}); final String title; final bool header; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 8), child: Row( children: <Widget>[ Container( width: 32, alignment: Alignment.centerLeft, child: header ? null : const Icon(Icons.arrow_drop_down), ), Expanded( child: SelectableText( title, style: Theme.of(context).textTheme.titleMedium!.copyWith( fontWeight: header ? FontWeight.w700 : FontWeight.w600, fontSize: 16, ), ), ), ], ), ); } } class StockItem extends StatelessWidget { const StockItem({ super.key, required this.ticker, required this.price, required this.percent, }); final String ticker; final String price; final double percent; @override Widget build(BuildContext context) { final TextTheme textTheme = Theme.of(context).textTheme; final NumberFormat percentFormat = NumberFormat.decimalPercentPattern( locale: GalleryOptions.of(context).locale.toString(), decimalDigits: 2, ); return Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SelectableText(ticker, style: textTheme.titleMedium), const SizedBox(height: 2), Row( children: <Widget>[ Expanded( child: SelectableText( price, style: textTheme.titleSmall!.copyWith( color: textTheme.titleSmall!.color!.withOpacity(0.75), ), ), ), SelectableText( percent > 0 ? '+' : '-', style: textTheme.titleSmall!.copyWith( fontSize: 12, color: percent > 0 ? const Color(0xff20CF63) : const Color(0xff661FFF), ), ), const SizedBox(width: 4), SelectableText( percentFormat.format(percent.abs() / 100), style: textTheme.bodySmall!.copyWith( fontSize: 12, color: textTheme.titleSmall!.color!.withOpacity(0.75), ), ), ], ) ], ); } } List<Widget> buildStockItems(BuildContext context) { final Widget articleDivider = Container( margin: const EdgeInsets.symmetric(vertical: 16), color: Colors.black.withOpacity(0.07), height: 1, ); const double imageAspectRatio = 165 / 55; return <Widget>[ SizedBox( width: double.infinity, child: FadeInImagePlaceholder( image: const AssetImage( 'fortnightly/fortnightly_chart.png', package: 'flutter_gallery_assets', ), placeholder: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { return Container( color: Colors.black.withOpacity(0.1), width: constraints.maxWidth, height: constraints.maxWidth / imageAspectRatio, ); }), width: double.infinity, fit: BoxFit.contain, excludeFromSemantics: true, ), ), articleDivider, const StockItem( ticker: 'DIJA', price: '7,031.21', percent: -0.48, ), articleDivider, const StockItem( ticker: 'SP', price: '1,967.84', percent: -0.23, ), articleDivider, const StockItem( ticker: 'Nasdaq', price: '6,211.46', percent: 0.52, ), articleDivider, const StockItem( ticker: 'Nikkei', price: '5,891', percent: 1.16, ), articleDivider, const StockItem( ticker: 'DJ Total', price: '89.02', percent: 0.80, ), articleDivider, ]; } class VideoPreview extends StatelessWidget { const VideoPreview({ super.key, required this.data, required this.time, }); final ArticleData data; final String time; @override Widget build(BuildContext context) { final TextTheme textTheme = Theme.of(context).textTheme; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SizedBox( width: double.infinity, child: FadeInImagePlaceholder( image: AssetImage( data.imageUrl, package: 'flutter_gallery_assets', ), placeholder: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { return Container( color: Colors.black.withOpacity(0.1), width: constraints.maxWidth, height: constraints.maxWidth / data.imageAspectRatio, ); }), fit: BoxFit.contain, width: double.infinity, excludeFromSemantics: true, ), ), const SizedBox(height: 4), Row( children: <Widget>[ Expanded( child: SelectableText( data.category, style: textTheme.titleMedium, ), ), SelectableText(time, style: textTheme.bodyLarge) ], ), const SizedBox(height: 4), SelectableText(data.title, style: textTheme.headlineSmall!.copyWith(fontSize: 16)), ], ); } } List<Widget> buildVideoPreviewItems(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return <Widget>[ VideoPreview( data: ArticleData( imageUrl: 'fortnightly/fortnightly_feminists.jpg', imageAspectRatio: 148 / 88, category: localizations.fortnightlyMenuPolitics.toUpperCase(), title: localizations.fortnightlyHeadlineFeminists, ), time: '2:31', ), const SizedBox(height: 32), VideoPreview( data: ArticleData( imageUrl: 'fortnightly/fortnightly_bees.jpg', imageAspectRatio: 148 / 88, category: localizations.fortnightlyMenuUS.toUpperCase(), title: localizations.fortnightlyHeadlineBees, ), time: '1:37', ), ]; } ThemeData buildTheme(BuildContext context) { final TextTheme lightTextTheme = ThemeData.light().textTheme; return ThemeData( scaffoldBackgroundColor: Colors.white, appBarTheme: AppBarTheme( color: Colors.white, elevation: 0, iconTheme: IconTheme.of(context).copyWith(color: Colors.black), ), highlightColor: Colors.transparent, textTheme: TextTheme( // preview snippet bodyMedium: GoogleFonts.merriweather( fontWeight: FontWeight.w300, fontSize: 16, textStyle: lightTextTheme.bodyMedium, ), // time in latest updates bodyLarge: GoogleFonts.libreFranklin( fontWeight: FontWeight.w500, fontSize: 11, color: Colors.black.withOpacity(0.5), textStyle: lightTextTheme.bodyLarge, ), // preview headlines headlineSmall: GoogleFonts.libreFranklin( fontWeight: FontWeight.w500, fontSize: 16, textStyle: lightTextTheme.headlineSmall, ), // (caption 2), preview category, stock ticker titleMedium: GoogleFonts.robotoCondensed( fontWeight: FontWeight.w700, fontSize: 16, ), titleSmall: GoogleFonts.libreFranklin( fontWeight: FontWeight.w400, fontSize: 14, textStyle: lightTextTheme.titleSmall, ), // section titles: Top Highlights, Last Updated... titleLarge: GoogleFonts.merriweather( fontWeight: FontWeight.w700, fontStyle: FontStyle.italic, fontSize: 14, textStyle: lightTextTheme.titleLarge, ), ), ); }
flutter/dev/integration_tests/new_gallery/lib/studies/fortnightly/shared.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/fortnightly/shared.dart", "repo_id": "flutter", "token_count": 8219 }
535
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import '../../../layout/adaptive.dart'; import '../colors.dart'; import '../data.dart'; import '../routes.dart' as rally_route; class SettingsView extends StatefulWidget { const SettingsView({super.key}); @override State<SettingsView> createState() => _SettingsViewState(); } class _SettingsViewState extends State<SettingsView> { @override Widget build(BuildContext context) { return FocusTraversalGroup( child: Container( padding: EdgeInsets.only(top: isDisplayDesktop(context) ? 24 : 0), child: ListView( restorationId: 'settings_list_view', shrinkWrap: true, children: <Widget>[ for (final String title in DummyDataService.getSettingsTitles(context)) ...<Widget>[ _SettingsItem(title), const Divider( color: RallyColors.dividerColor, height: 1, ) ] ], ), ), ); } } class _SettingsItem extends StatelessWidget { const _SettingsItem(this.title); final String title; @override Widget build(BuildContext context) { return TextButton( style: TextButton.styleFrom( foregroundColor: Colors.white, padding: EdgeInsets.zero, ), onPressed: () { Navigator.of(context).restorablePushNamed(rally_route.loginRoute); }, child: Container( alignment: AlignmentDirectional.centerStart, padding: const EdgeInsets.symmetric(vertical: 24, horizontal: 28), child: Text(title), ), ); } }
flutter/dev/integration_tests/new_gallery/lib/studies/rally/tabs/settings.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/rally/tabs/settings.dart", "repo_id": "flutter", "token_count": 730 }
536
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:scoped_model/scoped_model.dart'; import '../../data/gallery_options.dart'; import '../../gallery_localizations.dart'; import '../../layout/adaptive.dart'; import 'backdrop.dart'; import 'category_menu_page.dart'; import 'expanding_bottom_sheet.dart'; import 'home.dart'; import 'login.dart'; import 'model/app_state_model.dart'; import 'model/product.dart'; import 'page_status.dart'; import 'routes.dart' as routes; import 'scrim.dart'; import 'supplemental/layout_cache.dart'; import 'theme.dart'; class ShrineApp extends StatefulWidget { const ShrineApp({super.key}); static const String loginRoute = routes.loginRoute; static const String homeRoute = routes.homeRoute; @override State<ShrineApp> createState() => _ShrineAppState(); } class _ShrineAppState extends State<ShrineApp> with TickerProviderStateMixin, RestorationMixin { // Controller to coordinate both the opening/closing of backdrop and sliding // of expanding bottom sheet late AnimationController _controller; // Animation Controller for expanding/collapsing the cart menu. late AnimationController _expandingController; final _RestorableAppStateModel _model = _RestorableAppStateModel(); final RestorableDouble _expandingTabIndex = RestorableDouble(0); final RestorableDouble _tabIndex = RestorableDouble(1); final Map<String, List<List<int>>> _layouts = <String, List<List<int>>>{}; @override String get restorationId => 'shrine_app_state'; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_model, 'app_state_model'); registerForRestoration(_tabIndex, 'tab_index'); registerForRestoration( _expandingTabIndex, 'expanding_tab_index', ); _controller.value = _tabIndex.value; _expandingController.value = _expandingTabIndex.value; } @override void initState() { super.initState(); _controller = AnimationController( vsync: this, duration: const Duration(milliseconds: 450), value: 1, ); // Save state restoration animation values only when the cart page // fully opens or closes. _controller.addStatusListener((AnimationStatus status) { if (status == AnimationStatus.completed || status == AnimationStatus.dismissed) { _tabIndex.value = _controller.value; } }); _expandingController = AnimationController( duration: const Duration(milliseconds: 500), vsync: this, ); // Save state restoration animation values only when the menu page // fully opens or closes. _expandingController.addStatusListener((AnimationStatus status) { if (status == AnimationStatus.completed || status == AnimationStatus.dismissed) { _expandingTabIndex.value = _expandingController.value; } }); } @override void dispose() { _controller.dispose(); _expandingController.dispose(); _tabIndex.dispose(); _expandingTabIndex.dispose(); super.dispose(); } Widget mobileBackdrop() { return Backdrop( frontLayer: const ProductPage(), backLayer: CategoryMenuPage(onCategoryTap: () => _controller.forward()), frontTitle: const Text('SHRINE'), backTitle: Text(GalleryLocalizations.of(context)!.shrineMenuCaption), controller: _controller, ); } Widget desktopBackdrop() { return const DesktopBackdrop( frontLayer: ProductPage(), backLayer: CategoryMenuPage(), ); } // Closes the bottom sheet if it is open. Future<bool> _onWillPop() async { final AnimationStatus status = _expandingController.status; if (status == AnimationStatus.completed || status == AnimationStatus.forward) { await _expandingController.reverse(); return false; } return true; } @override Widget build(BuildContext context) { final Widget home = LayoutCache( layouts: _layouts, child: PageStatus( menuController: _controller, cartController: _expandingController, child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) => HomePage( backdrop: isDisplayDesktop(context) ? desktopBackdrop() : mobileBackdrop(), scrim: Scrim(controller: _expandingController), expandingBottomSheet: ExpandingBottomSheet( hideController: _controller, expandingController: _expandingController, ), ), ), ), ); return ScopedModel<AppStateModel>( model: _model.value, // ignore: deprecated_member_use child: WillPopScope( onWillPop: _onWillPop, child: MaterialApp( // By default on desktop, scrollbars are applied by the // ScrollBehavior. This overrides that. All vertical scrollables in // the gallery need to be audited before enabling this feature, // see https://github.com/flutter/gallery/issues/541 scrollBehavior: const MaterialScrollBehavior().copyWith(scrollbars: false), restorationScopeId: 'shrineApp', title: 'Shrine', debugShowCheckedModeBanner: false, initialRoute: ShrineApp.loginRoute, routes: <String, WidgetBuilder>{ ShrineApp.loginRoute: (BuildContext context) => const LoginPage(), ShrineApp.homeRoute: (BuildContext context) => home, }, theme: shrineTheme.copyWith( platform: GalleryOptions.of(context).platform, ), // L10n settings. localizationsDelegates: GalleryLocalizations.localizationsDelegates, supportedLocales: GalleryLocalizations.supportedLocales, locale: GalleryOptions.of(context).locale, ), ), ); } } class _RestorableAppStateModel extends RestorableListenable<AppStateModel> { @override AppStateModel createDefaultValue() => AppStateModel()..loadProducts(); @override AppStateModel fromPrimitives(Object? data) { final AppStateModel appState = AppStateModel()..loadProducts(); final Map<String, dynamic> appData = Map<String, dynamic>.from(data! as Map<dynamic, dynamic>); // Reset selected category. final int categoryIndex = appData['category_index'] as int; appState.setCategory(categories[categoryIndex]); // Reset cart items. final Map<dynamic, dynamic> cartItems = appData['cart_data'] as Map<dynamic, dynamic>; cartItems.forEach((dynamic id, dynamic quantity) { appState.addMultipleProductsToCart(id as int, quantity as int); }); return appState; } @override Object toPrimitives() { return <String, dynamic>{ 'cart_data': value.productsInCart, 'category_index': categories.indexOf(value.selectedCategory), }; } }
flutter/dev/integration_tests/new_gallery/lib/studies/shrine/app.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/shrine/app.dart", "repo_id": "flutter", "token_count": 2518 }
537
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' show lerpDouble; import 'package:flutter/material.dart'; class CutCornersBorder extends OutlineInputBorder { const CutCornersBorder({ super.borderSide, super.borderRadius = const BorderRadius.all(Radius.circular(2)), this.cut = 7, super.gapPadding = 2, }); @override CutCornersBorder copyWith({ BorderSide? borderSide, BorderRadius? borderRadius, double? gapPadding, double? cut, }) { return CutCornersBorder( borderSide: borderSide ?? this.borderSide, borderRadius: borderRadius ?? this.borderRadius, gapPadding: gapPadding ?? this.gapPadding, cut: cut ?? this.cut, ); } final double cut; @override ShapeBorder? lerpFrom(ShapeBorder? a, double t) { if (a is CutCornersBorder) { final CutCornersBorder outline = a; return CutCornersBorder( borderRadius: BorderRadius.lerp(outline.borderRadius, borderRadius, t)!, borderSide: BorderSide.lerp(outline.borderSide, borderSide, t), cut: cut, gapPadding: outline.gapPadding, ); } return super.lerpFrom(a, t); } @override ShapeBorder? lerpTo(ShapeBorder? b, double t) { if (b is CutCornersBorder) { final CutCornersBorder outline = b; return CutCornersBorder( borderRadius: BorderRadius.lerp(borderRadius, outline.borderRadius, t)!, borderSide: BorderSide.lerp(borderSide, outline.borderSide, t), cut: cut, gapPadding: outline.gapPadding, ); } return super.lerpTo(b, t); } Path _notchedCornerPath(Rect center, [double start = 0, double extent = 0]) { final Path path = Path(); if (start > 0 || extent > 0) { path.relativeMoveTo(extent + start, center.top); _notchedSidesAndBottom(center, path); path ..lineTo(center.left + cut, center.top) ..lineTo(start, center.top); } else { path.moveTo(center.left + cut, center.top); _notchedSidesAndBottom(center, path); path.lineTo(center.left + cut, center.top); } return path; } Path _notchedSidesAndBottom(Rect center, Path path) { return path ..lineTo(center.right - cut, center.top) ..lineTo(center.right, center.top + cut) ..lineTo(center.right, center.top + center.height - cut) ..lineTo(center.right - cut, center.top + center.height) ..lineTo(center.left + cut, center.top + center.height) ..lineTo(center.left, center.top + center.height - cut) ..lineTo(center.left, center.top + cut); } @override void paint( Canvas canvas, Rect rect, { double? gapStart, double gapExtent = 0, double gapPercentage = 0, TextDirection? textDirection, }) { assert(gapPercentage >= 0 && gapPercentage <= 1); final Paint paint = borderSide.toPaint(); final RRect outer = borderRadius.toRRect(rect); if (gapStart == null || gapExtent <= 0 || gapPercentage == 0) { canvas.drawPath(_notchedCornerPath(outer.middleRect), paint); } else { final double? extent = lerpDouble(0.0, gapExtent + gapPadding * 2, gapPercentage); switch (textDirection!) { case TextDirection.rtl: { final Path path = _notchedCornerPath( outer.middleRect, gapStart + gapPadding - extent!, extent); canvas.drawPath(path, paint); break; } case TextDirection.ltr: { final Path path = _notchedCornerPath( outer.middleRect, gapStart - gapPadding, extent!); canvas.drawPath(path, paint); break; } } } } }
flutter/dev/integration_tests/new_gallery/lib/studies/shrine/supplemental/cut_corners_border.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/shrine/supplemental/cut_corners_border.dart", "repo_id": "flutter", "token_count": 1573 }
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. // Replace Windows line endings with Unix line endings String standardizeLineEndings(String str) => str.replaceAll('\r\n', '\n');
flutter/dev/integration_tests/new_gallery/test/utils.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/test/utils.dart", "repo_id": "flutter", "token_count": 78 }
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_driver/driver_extension.dart'; void main() { enableFlutterDriverExtension(); runApp(MaterialApp( home: Material( child: Builder( builder: (BuildContext context) { return TextButton( child: const Text( 'flutter drive lib/xxx.dart', textDirection: TextDirection.ltr, ), onPressed: () { Navigator.push<Object?>( context, MaterialPageRoute<Object?>( builder: (BuildContext context) { return const Material( child: Center( child: Text( 'navigated here', textDirection: TextDirection.ltr, ), ), ); }, ), ); }, ); }, ), ), )); }
flutter/dev/integration_tests/ui/lib/main.dart/0
{ "file_path": "flutter/dev/integration_tests/ui/lib/main.dart", "repo_id": "flutter", "token_count": 647 }
540
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
flutter/dev/integration_tests/ui/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "flutter/dev/integration_tests/ui/macos/Runner/Configs/Debug.xcconfig", "repo_id": "flutter", "token_count": 32 }
541
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_driver/flutter_driver.dart'; import 'package:integration_ui/keys.dart' as keys; import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; void main() { group('end-to-end test', () { late FlutterDriver driver; setUpAll(() async { driver = await FlutterDriver.connect(); }); tearDownAll(() async { await driver.close(); }); test('Ensure keyboard dismissal resizes the view to original size', () async { await driver.setTextEntryEmulation(enabled: false); final SerializableFinder heightText = find.byValueKey(keys.kHeightText); await driver.waitFor(heightText); // Measure the initial height. final String startHeight = await driver.getText(heightText); // Focus the text field to show the keyboard. final SerializableFinder defaultTextField = find.byValueKey(keys.kDefaultTextField); await driver.waitFor(defaultTextField); await driver.tap(defaultTextField); bool heightTextDidShrink = false; for (int i = 0; i < 6; ++i) { await Future<void>.delayed(const Duration(seconds: 1)); // Measure the height with keyboard displayed. final String heightWithKeyboardShown = await driver.getText(heightText); if (double.parse(heightWithKeyboardShown) < double.parse(startHeight)) { heightTextDidShrink = true; break; } } expect(heightTextDidShrink, isTrue); // Unfocus the text field to dismiss the keyboard. final SerializableFinder unfocusButton = find.byValueKey(keys.kUnfocusButton); await driver.waitFor(unfocusButton); await driver.tap(unfocusButton); bool heightTextDidExpand = false; for (int i = 0; i < 3; ++i) { await Future<void>.delayed(const Duration(seconds: 1)); // Measure the final height. final String endHeight = await driver.getText(heightText); if (endHeight == startHeight) { heightTextDidExpand = true; break; } } expect(heightTextDidExpand, isTrue); }, timeout: Timeout.none); }); }
flutter/dev/integration_tests/ui/test_driver/keyboard_resize_test.dart/0
{ "file_path": "flutter/dev/integration_tests/ui/test_driver/keyboard_resize_test.dart", "repo_id": "flutter", "token_count": 839 }
542
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:html' as html; Future<void> main() async { final StringBuffer output = StringBuffer(); const String combined = String.fromEnvironment('test.valueA') + String.fromEnvironment('test.valueB'); if (combined == 'Example,AValue') { output.write('--- TEST SUCCEEDED ---'); print('--- TEST SUCCEEDED ---'); } else { output.write('--- TEST FAILED ---'); print('--- TEST FAILED ---'); } html.HttpRequest.request( '/test-result', method: 'POST', sendData: '$output', ); }
flutter/dev/integration_tests/web/lib/web_define_loading.dart/0
{ "file_path": "flutter/dev/integration_tests/web/lib/web_define_loading.dart", "repo_id": "flutter", "token_count": 227 }
543
{ "name": "web_integration_test", "short_name": "web_integration_test", "start_url": ".", "display": "standalone", "background_color": "#0175C2", "theme_color": "#0175C2", "description": "A new Flutter project.", "orientation": "portrait-primary", "prefer_related_applications": false, "icons": [] }
flutter/dev/integration_tests/web/web/manifest.json/0
{ "file_path": "flutter/dev/integration_tests/web/web/manifest.json", "repo_id": "flutter", "token_count": 140 }
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/material.dart'; void main() { runApp(const MaterialApp( title: 'Hover Demo', home: HoverDemo(), )); } class HoverDemo extends StatefulWidget { const HoverDemo({super.key}); @override State<HoverDemo> createState() => _HoverDemoState(); } class _HoverDemoState extends State<HoverDemo> { @override Widget build(BuildContext context) { final TextTheme textTheme = Theme.of(context).textTheme; final ButtonStyle overrideFocusColor = ButtonStyle( overlayColor: MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) { return states.contains(MaterialState.focused) ? Colors.deepOrangeAccent : Colors.transparent; }) ); return DefaultTextStyle( style: textTheme.headlineMedium!, child: Scaffold( appBar: AppBar( title: const Text('Hover Demo'), ), floatingActionButton: FloatingActionButton( child: const Text('+'), onPressed: () {}, ), body: Center( child: Builder(builder: (BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Row( children: <Widget>[ ElevatedButton( onPressed: () => print('Button pressed.'), style: overrideFocusColor, child: const Text('Button'), ), TextButton( onPressed: () => print('Button pressed.'), style: overrideFocusColor, child: const Text('Button'), ), IconButton( onPressed: () => print('Button pressed'), icon: const Icon(Icons.access_alarm), focusColor: Colors.deepOrangeAccent, ), ], ), const Padding( padding: EdgeInsets.all(8.0), child: TextField( decoration: InputDecoration(labelText: 'Enter Text', filled: true), ), ), const Padding( padding: EdgeInsets.all(8.0), child: TextField( decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Enter Text', filled: false, ), ), ), ], ); }), ), ), ); } }
flutter/dev/manual_tests/lib/hover.dart/0
{ "file_path": "flutter/dev/manual_tests/lib/hover.dart", "repo_id": "flutter", "token_count": 1461 }
545
#include "ephemeral/Flutter-Generated.xcconfig"
flutter/dev/manual_tests/macos/Flutter/Flutter-Release.xcconfig/0
{ "file_path": "flutter/dev/manual_tests/macos/Flutter/Flutter-Release.xcconfig", "repo_id": "flutter", "token_count": 19 }
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:convert'; import 'dart:io'; import 'dart:math' as math; import 'package:archive/archive_io.dart'; import 'package:args/args.dart'; import 'package:file/file.dart'; import 'package:file/local.dart'; import 'package:http/http.dart' as http; import 'package:intl/intl.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as path; import 'package:platform/platform.dart'; import 'package:process/process.dart'; import 'package:pub_semver/pub_semver.dart'; import 'dartdoc_checker.dart'; const String kDummyPackageName = 'Flutter'; const String kPlatformIntegrationPackageName = 'platform_integration'; class PlatformDocsSection { const PlatformDocsSection({ required this.zipName, required this.sectionName, required this.checkFile, required this.subdir, }); final String zipName; final String sectionName; final String checkFile; final String subdir; } const Map<String, PlatformDocsSection> kPlatformDocs = <String, PlatformDocsSection>{ 'android': PlatformDocsSection( zipName: 'android-javadoc.zip', sectionName: 'Android', checkFile: 'io/flutter/view/FlutterView.html', subdir: 'javadoc', ), 'ios': PlatformDocsSection( zipName: 'ios-docs.zip', sectionName: 'iOS', checkFile: 'interface_flutter_view.html', subdir: 'ios-embedder', ), 'macos': PlatformDocsSection( zipName: 'macos-docs.zip', sectionName: 'macOS', checkFile: 'interface_flutter_view.html', subdir: 'macos-embedder', ), 'linux': PlatformDocsSection( zipName: 'linux-docs.zip', sectionName: 'Linux', checkFile: 'struct___fl_view.html', subdir: 'linux-embedder', ), 'windows': PlatformDocsSection( zipName: 'windows-docs.zip', sectionName: 'Windows', checkFile: 'classflutter_1_1_flutter_view.html', subdir: 'windows-embedder', ), 'impeller': PlatformDocsSection( zipName: 'impeller-docs.zip', sectionName: 'Impeller', checkFile: 'classimpeller_1_1_canvas.html', subdir: 'impeller', ), }; /// This script will generate documentation for the packages in `packages/` and /// write the documentation to the output directory specified on the command /// line. /// /// This script also updates the index.html file so that it can be placed at the /// root of api.flutter.dev. The files are kept inside of /// api.flutter.dev/flutter, so we need to manipulate paths a bit. See /// https://github.com/flutter/flutter/issues/3900 for more info. /// /// This will only work on UNIX systems, not Windows. It requires that 'git', /// 'zip', and 'tar' be in the PATH. It requires that 'flutter' has been run /// previously. It uses the version of Dart downloaded by the 'flutter' tool in /// this repository and will fail if that is absent. Future<void> main(List<String> arguments) async { const FileSystem filesystem = LocalFileSystem(); const ProcessManager processManager = LocalProcessManager(); const Platform platform = LocalPlatform(); // The place to find customization files and configuration files for docs // generation. final Directory docsRoot = FlutterInformation.instance.getFlutterRoot().childDirectory('dev').childDirectory('docs').absolute; final ArgParser argParser = _createArgsParser( publishDefault: docsRoot.childDirectory('doc').path, ); final ArgResults args = argParser.parse(arguments); if (args['help'] as bool) { print('Usage:'); print(argParser.usage); exit(0); } final Directory publishRoot = filesystem.directory(args['output-dir']! as String).absolute; final Directory packageRoot = publishRoot.parent; if (!filesystem.directory(packageRoot).existsSync()) { filesystem.directory(packageRoot).createSync(recursive: true); } if (!filesystem.directory(publishRoot).existsSync()) { filesystem.directory(publishRoot).createSync(recursive: true); } final Configurator configurator = Configurator( publishRoot: publishRoot, packageRoot: packageRoot, docsRoot: docsRoot, filesystem: filesystem, processManager: processManager, platform: platform, ); configurator.generateConfiguration(); final PlatformDocGenerator platformGenerator = PlatformDocGenerator(outputDir: publishRoot, filesystem: filesystem); await platformGenerator.generatePlatformDocs(); final DartdocGenerator dartdocGenerator = DartdocGenerator( publishRoot: publishRoot, packageRoot: packageRoot, docsRoot: docsRoot, filesystem: filesystem, processManager: processManager, useJson: args['json'] as bool? ?? true, validateLinks: args['validate-links']! as bool, verbose: args['verbose'] as bool? ?? false, ); await dartdocGenerator.generateDartdoc(); await configurator.generateOfflineAssetsIfNeeded(); } ArgParser _createArgsParser({required String publishDefault}) { final ArgParser parser = ArgParser(); parser.addFlag('help', abbr: 'h', negatable: false, help: 'Show command help.'); parser.addFlag('verbose', defaultsTo: true, help: 'Whether to report all error messages (on) or attempt to ' 'filter out some known false positives (off). Shut this off ' 'locally if you want to address Flutter-specific issues.'); parser.addFlag('json', help: 'Display json-formatted output from dartdoc and skip stdout/stderr prefixing.'); parser.addFlag('validate-links', help: 'Display warnings for broken links generated by dartdoc (slow)'); parser.addOption('output-dir', defaultsTo: publishDefault, help: 'Sets the output directory for the documentation.'); return parser; } /// A class used to configure the staging area for building the docs in. /// /// The [generateConfiguration] function generates a dummy package with a /// pubspec. It copies any assets and customization files from the framework /// repo. It creates a metadata file for searches. /// /// Once the docs have been generated, [generateOfflineAssetsIfNeeded] will /// create offline assets like Dash/Zeal docsets and an offline ZIP file of the /// site if the build is a CI build that is not a presubmit build. class Configurator { Configurator({ required this.docsRoot, required this.publishRoot, required this.packageRoot, required this.filesystem, required this.processManager, required this.platform, }); /// The root of the directory in the Flutter repo where configuration data is /// stored. final Directory docsRoot; /// The root of the output area for the dartdoc docs. /// /// Typically this is a "doc" subdirectory under the [packageRoot]. final Directory publishRoot; /// The root of the staging area for creating docs. final Directory packageRoot; /// The [FileSystem] object used to create [File] and [Directory] objects. final FileSystem filesystem; /// The [ProcessManager] object used to invoke external processes. /// /// Can be replaced by tests to have a fake process manager. final ProcessManager processManager; /// The [Platform] to use for this run. /// /// Can be replaced by tests to test behavior on different platforms. final Platform platform; void generateConfiguration() { final Version version = FlutterInformation.instance.getFlutterVersion(); _createDummyPubspec(); _createDummyLibrary(); _createPageFooter(packageRoot, version); _copyCustomizations(); _createSearchMetadata( docsRoot.childDirectory('lib').childFile('opensearch.xml'), publishRoot.childFile('opensearch.xml')); } Future<void> generateOfflineAssetsIfNeeded() async { // Only create the offline docs if we're running in a non-presubmit build: // it takes too long otherwise. if (platform.environment.containsKey('LUCI_CI') && (platform.environment['LUCI_PR'] ?? '').isEmpty) { _createOfflineZipFile(); await _createDocset(); _moveOfflineIntoPlace(); _createRobotsTxt(); } } /// Returns import or on-disk paths for all libraries in the Flutter SDK. Iterable<String> _libraryRefs() sync* { for (final Directory dir in findPackages(filesystem)) { final String dirName = dir.basename; for (final FileSystemEntity file in dir.childDirectory('lib').listSync()) { if (file is File && file.path.endsWith('.dart')) { yield '$dirName/${file.basename}'; } } } // Add a fake package for platform integration APIs. yield '$kPlatformIntegrationPackageName/android.dart'; yield '$kPlatformIntegrationPackageName/ios.dart'; yield '$kPlatformIntegrationPackageName/macos.dart'; yield '$kPlatformIntegrationPackageName/linux.dart'; yield '$kPlatformIntegrationPackageName/windows.dart'; } void _createDummyPubspec() { // Create the pubspec.yaml file. final List<String> pubspec = <String>[ 'name: $kDummyPackageName', 'homepage: https://flutter.dev', 'version: 0.0.0', 'environment:', " sdk: '>=3.2.0-0 <4.0.0'", 'dependencies:', for (final String package in findPackageNames(filesystem)) ' $package:\n sdk: flutter', ' $kPlatformIntegrationPackageName: 0.0.1', 'dependency_overrides:', ' $kPlatformIntegrationPackageName:', ' path: ${docsRoot.childDirectory(kPlatformIntegrationPackageName).path}', ]; packageRoot.childFile('pubspec.yaml').writeAsStringSync(pubspec.join('\n')); } void _createDummyLibrary() { final Directory libDir = packageRoot.childDirectory('lib'); libDir.createSync(); final StringBuffer contents = StringBuffer('library temp_doc;\n\n'); for (final String libraryRef in _libraryRefs()) { contents.writeln("import 'package:$libraryRef';"); } packageRoot.childDirectory('lib') ..createSync(recursive: true) ..childFile('temp_doc.dart').writeAsStringSync(contents.toString()); } void _createPageFooter(Directory footerPath, Version version) { final String timestamp = DateFormat('yyyy-MM-dd HH:mm').format(DateTime.now()); String channel = FlutterInformation.instance.getBranchName(); // Backward compatibility: Still support running on "master", but pretend it is "main". if (channel == 'master') { channel = 'main'; } final String gitRevision = FlutterInformation.instance.getFlutterRevision(); final String channelOut = channel.isEmpty ? '' : '• $channel'; footerPath.childFile('footer.html').writeAsStringSync('<script src="footer.js"></script>'); publishRoot.childDirectory('flutter').childFile('footer.js') ..createSync(recursive: true) ..writeAsStringSync(''' (function() { var span = document.querySelector('footer>span'); if (span) { span.innerText = 'Flutter $version • $timestamp • $gitRevision $channelOut'; } var sourceLink = document.querySelector('a.source-link'); if (sourceLink) { sourceLink.href = sourceLink.href.replace('/main/', '/$gitRevision/'); } })(); '''); } void _copyCustomizations() { final List<String> files = <String>[ 'README.md', 'analysis_options.yaml', 'dartdoc_options.yaml', ]; for (final String file in files) { final File source = docsRoot.childFile(file); final File destination = packageRoot.childFile(file); // Have to canonicalize because otherwise things like /foo/bar/baz and // /foo/../foo/bar/baz won't compare as identical. if (path.canonicalize(source.absolute.path) != path.canonicalize(destination.absolute.path)) { source.copySync(destination.path); print('Copied ${path.canonicalize(source.absolute.path)} to ${path.canonicalize(destination.absolute.path)}'); } } final Directory assetsDir = filesystem.directory(publishRoot.childDirectory('assets')); final Directory assetSource = docsRoot.childDirectory('assets'); if (path.canonicalize(assetSource.absolute.path) == path.canonicalize(assetsDir.absolute.path)) { // Don't try and copy the directory over itself. return; } if (assetsDir.existsSync()) { assetsDir.deleteSync(recursive: true); } copyDirectorySync( docsRoot.childDirectory('assets'), assetsDir, onFileCopied: (File src, File dest) { print('Copied ${path.canonicalize(src.absolute.path)} to ${path.canonicalize(dest.absolute.path)}'); }, filesystem: filesystem, ); } /// Generates an OpenSearch XML description that can be used to add a custom /// search for Flutter API docs to the browser. Unfortunately, it has to know /// the URL to which site to search, so we customize it here based upon the /// branch name. void _createSearchMetadata(File templatePath, File metadataPath) { final String template = templatePath.readAsStringSync(); final String branch = FlutterInformation.instance.getBranchName(); final String metadata = template.replaceAll( '{SITE_URL}', branch == 'stable' ? 'https://api.flutter.dev/' : 'https://main-api.flutter.dev/', ); metadataPath.parent.create(recursive: true); metadataPath.writeAsStringSync(metadata); } Future<void> _createDocset() async { // Must have dashing installed: go get -u github.com/technosophos/dashing // Dashing produces a LOT of log output (~30MB), so we collect it, and just // show the end of it if there was a problem. print('${DateTime.now().toUtc()}: Building Flutter docset.'); // If dashing gets stuck, Cirrus will time out the build after an hour, and we // never get to see the logs. Thus, we run it in the background and tail the // logs only if it fails. final ProcessWrapper result = ProcessWrapper( await processManager.start( <String>[ 'dashing', 'build', '--source', publishRoot.path, '--config', docsRoot.childFile('dashing.json').path, ], workingDirectory: packageRoot.path, ), ); final List<int> buffer = <int>[]; result.stdout.listen(buffer.addAll); result.stderr.listen(buffer.addAll); // If the dashing process exited with an error, print the last 200 lines of stderr and exit. final int exitCode = await result.done; if (exitCode != 0) { print('Dashing docset generation failed with code $exitCode'); final List<String> output = systemEncoding.decode(buffer).split('\n'); print(output.sublist(math.max(output.length - 200, 0)).join('\n')); exit(exitCode); } buffer.clear(); // Copy the favicon file to the output directory. final File faviconFile = publishRoot.childDirectory('flutter').childDirectory('static-assets').childFile('favicon.png'); final File iconFile = packageRoot.childDirectory('flutter.docset').childFile('icon.png'); faviconFile ..createSync(recursive: true) ..copySync(iconFile.path); // Post-process the dashing output. final File infoPlist = packageRoot.childDirectory('flutter.docset').childDirectory('Contents').childFile('Info.plist'); String contents = infoPlist.readAsStringSync(); // Since I didn't want to add the XML package as a dependency just for this, // I just used a regular expression to make this simple change. final RegExp findRe = RegExp(r'(\s*<key>DocSetPlatformFamily</key>\s*<string>)[^<]+(</string>)', multiLine: true); contents = contents.replaceAllMapped(findRe, (Match match) { return '${match.group(1)}dartlang${match.group(2)}'; }); infoPlist.writeAsStringSync(contents); final Directory offlineDir = publishRoot.childDirectory('offline'); if (!offlineDir.existsSync()) { offlineDir.createSync(recursive: true); } tarDirectory(packageRoot, offlineDir.childFile('flutter.docset.tar.gz'), processManager: processManager); // Write the Dash/Zeal XML feed file. final bool isStable = platform.environment['LUCI_BRANCH'] == 'stable'; offlineDir.childFile('flutter.xml').writeAsStringSync('<entry>\n' ' <version>${FlutterInformation.instance.getFlutterVersion()}</version>\n' ' <url>https://${isStable ? '' : 'main-'}api.flutter.dev/offline/flutter.docset.tar.gz</url>\n' '</entry>\n'); } // Creates the offline ZIP file containing all of the website HTML files. void _createOfflineZipFile() { print('${DateTime.now().toLocal()}: Creating offline docs archive.'); zipDirectory(publishRoot, packageRoot.childFile('flutter.docs.zip'), processManager: processManager); } // Moves the generated offline archives into the publish directory so that // they can be included in the output ZIP file. void _moveOfflineIntoPlace() { print('${DateTime.now().toUtc()}: Moving offline docs into place.'); final Directory offlineDir = publishRoot.childDirectory('offline')..createSync(recursive: true); packageRoot.childFile('flutter.docs.zip').renameSync(offlineDir.childFile('flutter.docs.zip').path); } // Creates a robots.txt file that disallows indexing unless the branch is the // stable branch. void _createRobotsTxt() { final File robotsTxt = publishRoot.childFile('robots.txt'); if (FlutterInformation.instance.getBranchName() == 'stable') { robotsTxt.writeAsStringSync('# All robots welcome!'); } else { robotsTxt.writeAsStringSync('User-agent: *\nDisallow: /'); } } } /// Runs Dartdoc inside of the given pre-prepared staging area, prepared by /// [Configurator.generateConfiguration]. /// /// Performs a sanity check of the output once the generation is complete. class DartdocGenerator { DartdocGenerator({ required this.docsRoot, required this.publishRoot, required this.packageRoot, required this.filesystem, required this.processManager, this.useJson = true, this.validateLinks = true, this.verbose = false, }); /// The root of the directory in the Flutter repo where configuration data is /// stored. final Directory docsRoot; /// The root of the output area for the dartdoc docs. /// /// Typically this is a "doc" subdirectory under the [packageRoot]. final Directory publishRoot; /// The root of the staging area for creating docs. final Directory packageRoot; /// The [FileSystem] object used to create [File] and [Directory] objects. final FileSystem filesystem; /// The [ProcessManager] object used to invoke external processes. /// /// Can be replaced by tests to have a fake process manager. final ProcessManager processManager; /// Whether or not dartdoc should output an index.json file of the /// documentation. final bool useJson; // Whether or not to have dartdoc validate its own links. final bool validateLinks; /// Whether or not to filter overly verbose log output from dartdoc. final bool verbose; Future<void> generateDartdoc() async { final Directory flutterRoot = FlutterInformation.instance.getFlutterRoot(); final Map<String, String> pubEnvironment = <String, String>{ 'FLUTTER_ROOT': flutterRoot.absolute.path, }; // If there's a .pub-cache dir in the Flutter root, use that. final File pubCache = flutterRoot.childFile('.pub-cache'); if (pubCache.existsSync()) { pubEnvironment['PUB_CACHE'] = pubCache.path; } // Run pub. ProcessWrapper process = ProcessWrapper(await runPubProcess( arguments: <String>['get'], workingDirectory: packageRoot, environment: pubEnvironment, filesystem: filesystem, processManager: processManager, )); printStream(process.stdout, prefix: 'pub:stdout: '); printStream(process.stderr, prefix: 'pub:stderr: '); final int code = await process.done; if (code != 0) { exit(code); } final Version version = FlutterInformation.instance.getFlutterVersion(); // Verify which version of snippets and dartdoc we're using. final ProcessResult snippetsResult = processManager.runSync( <String>[ FlutterInformation.instance.getFlutterBinaryPath().path, 'pub', 'global', 'list', ], workingDirectory: packageRoot.path, environment: pubEnvironment, stdoutEncoding: utf8, ); print(''); final Iterable<RegExpMatch> versionMatches = RegExp(r'^(?<name>snippets|dartdoc) (?<version>[^\s]+)', multiLine: true) .allMatches(snippetsResult.stdout as String); for (final RegExpMatch match in versionMatches) { print('${match.namedGroup('name')} version: ${match.namedGroup('version')}'); } print('flutter version: $version\n'); // Dartdoc warnings and errors in these packages are considered fatal. // All packages owned by flutter should be in the list. final List<String> flutterPackages = <String>[ kDummyPackageName, kPlatformIntegrationPackageName, ...findPackageNames(filesystem), // TODO(goderbauer): Figure out how to only include `dart:ui` of // `sky_engine` below, https://github.com/dart-lang/dartdoc/issues/2278. // 'sky_engine', ]; // Generate the documentation. We don't need to exclude flutter_tools in // this list because it's not in the recursive dependencies of the package // defined at packageRoot final List<String> dartdocArgs = <String>[ 'global', 'run', '--enable-asserts', 'dartdoc', '--output', publishRoot.childDirectory('flutter').path, '--allow-tools', if (useJson) '--json', if (validateLinks) '--validate-links' else '--no-validate-links', '--link-to-source-excludes', flutterRoot.childDirectory('bin').childDirectory('cache').path, '--link-to-source-root', flutterRoot.path, '--link-to-source-uri-template', 'https://github.com/flutter/flutter/blob/main/%f%#L%l%', '--inject-html', '--use-base-href', '--header', docsRoot.childFile('styles.html').path, '--header', docsRoot.childFile('analytics-header.html').path, '--header', docsRoot.childFile('survey.html').path, '--header', docsRoot.childFile('snippets.html').path, '--header', docsRoot.childFile('opensearch.html').path, '--footer', docsRoot.childFile('analytics-footer.html').path, '--footer-text', packageRoot.childFile('footer.html').path, '--allow-warnings-in-packages', flutterPackages.join(','), '--exclude-packages', <String>[ 'analyzer', 'args', 'barback', 'csslib', 'flutter_goldens', 'flutter_goldens_client', 'front_end', 'fuchsia_remote_debug_protocol', 'glob', 'html', 'http_multi_server', 'io', 'isolate', 'js', 'kernel', 'logging', 'mime', 'mockito', 'node_preamble', 'plugin', 'shelf', 'shelf_packages_handler', 'shelf_static', 'shelf_web_socket', 'utf', 'watcher', 'yaml', ].join(','), '--exclude', <String>[ 'dart:io/network_policy.dart', // dart-lang/dartdoc#2437 'package:Flutter/temp_doc.dart', 'package:http/browser_client.dart', 'package:intl/intl_browser.dart', 'package:matcher/mirror_matchers.dart', 'package:quiver/io.dart', 'package:quiver/mirrors.dart', 'package:vm_service_client/vm_service_client.dart', 'package:web_socket_channel/html.dart', ].join(','), '--favicon', docsRoot.childFile('favicon.ico').absolute.path, '--package-order', 'flutter,Dart,$kPlatformIntegrationPackageName,flutter_test,flutter_driver', '--auto-include-dependencies', ]; String quote(String arg) => arg.contains(' ') ? "'$arg'" : arg; print('Executing: (cd "${packageRoot.path}" ; ' '${FlutterInformation.instance.getDartBinaryPath().path} ' '${dartdocArgs.map<String>(quote).join(' ')})'); process = ProcessWrapper(await runPubProcess( arguments: dartdocArgs, workingDirectory: packageRoot, environment: pubEnvironment, processManager: processManager, )); printStream( process.stdout, prefix: useJson ? '' : 'dartdoc:stdout: ', filter: <Pattern>[ if (!verbose) RegExp(r'^Generating docs for library '), // Unnecessary verbosity ], ); printStream( process.stderr, prefix: useJson ? '' : 'dartdoc:stderr: ', filter: <Pattern>[ if (!verbose) RegExp( // Remove warnings from packages outside our control r'^ warning: .+: \(.+[\\/]\.pub-cache[\\/]hosted[\\/]pub.dartlang.org[\\/].+\)', ), ], ); final int exitCode = await process.done; if (exitCode != 0) { exit(exitCode); } _sanityCheckDocs(); checkForUnresolvedDirectives(publishRoot.childDirectory('flutter')); _createIndexAndCleanup(); print('Documentation written to ${publishRoot.path}'); } void _sanityCheckExample(String fileString, String regExpString) { final File file = filesystem.file(fileString); if (file.existsSync()) { final RegExp regExp = RegExp(regExpString, dotAll: true); final String contents = file.readAsStringSync(); if (!regExp.hasMatch(contents)) { throw Exception("Missing example code matching '$regExpString' in ${file.path}."); } } else { throw Exception( "Missing example code sanity test file ${file.path}. Either it didn't get published, or you might have to update the test to look at a different file."); } } /// A subset of all generated doc files for [_sanityCheckDocs]. @visibleForTesting List<File> get canaries { final Directory flutterDirectory = publishRoot.childDirectory('flutter'); final Directory widgetsDirectory = flutterDirectory.childDirectory('widgets'); return <File>[ publishRoot.childDirectory('assets').childFile('overrides.css'), flutterDirectory.childDirectory('dart-io').childFile('File-class.html'), flutterDirectory.childDirectory('dart-ui').childFile('Canvas-class.html'), flutterDirectory.childDirectory('dart-ui').childDirectory('Canvas').childFile('drawRect.html'), flutterDirectory .childDirectory('flutter_driver') .childDirectory('FlutterDriver') .childFile('FlutterDriver.connectedTo.html'), flutterDirectory.childDirectory('flutter_test').childDirectory('WidgetTester').childFile('pumpWidget.html'), flutterDirectory.childDirectory('material').childFile('Material-class.html'), flutterDirectory.childDirectory('material').childFile('Tooltip-class.html'), widgetsDirectory.childFile('Widget-class.html'), widgetsDirectory.childFile('Listener-class.html'), ]; } /// Runs a sanity check by running a test. void _sanityCheckDocs([Platform platform = const LocalPlatform()]) { for (final File canary in canaries) { if (!canary.existsSync()) { throw Exception('Missing "${canary.path}", which probably means the documentation failed to build correctly.'); } } // Make sure at least one example of each kind includes source code. final Directory widgetsDirectory = publishRoot .childDirectory('flutter') .childDirectory('widgets'); // Check a "sample" example, any one will do. _sanityCheckExample( widgetsDirectory.childFile('showGeneralDialog.html').path, r'\s*<pre\s+id="longSnippet1".*<code\s+class="language-dart">\s*import &#39;package:flutter&#47;material.dart&#39;;', ); // Check a "snippet" example, any one will do. _sanityCheckExample( widgetsDirectory.childDirectory('ModalRoute').childFile('barrierColor.html').path, r'\s*<pre.*id="sample-code">.*Color\s+get\s+barrierColor.*</pre>', ); // Check a "dartpad" example, any one will do, and check for the correct URL // arguments. // Just use "main" for any branch other than "stable", just like it is done // in the snippet generator at https://github.com/flutter/assets-for-api-docs/blob/cc56972b8f03552fc5f9f9f1ef309efc6c93d7bc/packages/snippets/lib/src/snippet_generator.dart#L104. final String? luciBranch = platform.environment['LUCI_BRANCH']?.trim(); final String expectedChannel = luciBranch == 'stable' ? 'stable' : 'main'; final List<String> argumentRegExps = <String>[ r'split=\d+', r'run=true', r'sample_id=widgets\.Listener\.\d+', 'channel=$expectedChannel', ]; for (final String argumentRegExp in argumentRegExps) { _sanityCheckExample( widgetsDirectory.childFile('Listener-class.html').path, r'\s*<iframe\s+class="snippet-dartpad"\s+src="' r'https:\/\/dartpad.dev\/embed-flutter.html\?.*?\b' '$argumentRegExp' r'\b.*">\s*<\/iframe>', ); } } /// Creates a custom index.html because we try to maintain old /// paths. Cleanup unused index.html files no longer needed. void _createIndexAndCleanup() { print('\nCreating a custom index.html in ${publishRoot.childFile('index.html').path}'); _copyIndexToRootOfDocs(); _addHtmlBaseToIndex(); _changePackageToSdkInTitlebar(); _putRedirectInOldIndexLocation(); _writeSnippetsIndexFile(); print('\nDocs ready to go!'); } void _copyIndexToRootOfDocs() { publishRoot.childDirectory('flutter').childFile('index.html').copySync(publishRoot.childFile('index.html').path); } void _changePackageToSdkInTitlebar() { final File indexFile = publishRoot.childFile('index.html'); String indexContents = indexFile.readAsStringSync(); indexContents = indexContents.replaceFirst( '<li><a href="https://flutter.dev">Flutter package</a></li>', '<li><a href="https://flutter.dev">Flutter SDK</a></li>', ); indexFile.writeAsStringSync(indexContents); } void _addHtmlBaseToIndex() { final File indexFile = publishRoot.childFile('index.html'); String indexContents = indexFile.readAsStringSync(); indexContents = indexContents.replaceFirst( '</title>\n', '</title>\n <base href="./flutter/">\n', ); for (final String platform in kPlatformDocs.keys) { final String sectionName = kPlatformDocs[platform]!.sectionName; final String subdir = kPlatformDocs[platform]!.subdir; indexContents = indexContents.replaceAll( 'href="$sectionName/$sectionName-library.html"', 'href="../$subdir/index.html"', ); } indexFile.writeAsStringSync(indexContents); } void _putRedirectInOldIndexLocation() { const String metaTag = '<meta http-equiv="refresh" content="0;URL=../index.html">'; publishRoot.childDirectory('flutter').childFile('index.html').writeAsStringSync(metaTag); } void _writeSnippetsIndexFile() { final Directory snippetsDir = publishRoot.childDirectory('snippets'); if (snippetsDir.existsSync()) { const JsonEncoder jsonEncoder = JsonEncoder.withIndent(' '); final Iterable<File> files = snippetsDir.listSync().whereType<File>().where((File file) => path.extension(file.path) == '.json'); // Combine all the metadata into a single JSON array. final Iterable<String> fileContents = files.map((File file) => file.readAsStringSync()); final List<dynamic> metadataObjects = fileContents.map<dynamic>(json.decode).toList(); final String jsonArray = jsonEncoder.convert(metadataObjects); snippetsDir.childFile('index.json').writeAsStringSync(jsonArray); } } } /// Downloads and unpacks the platform specific documentation generated by the /// engine build. /// /// Unpacks and massages the data so that it can be properly included in the /// output archive. class PlatformDocGenerator { PlatformDocGenerator({required this.outputDir, required this.filesystem}); final FileSystem filesystem; final Directory outputDir; final String engineRevision = FlutterInformation.instance.getEngineRevision(); final String engineRealm = FlutterInformation.instance.getEngineRealm(); /// This downloads an archive of platform docs for the engine from the artifact /// store and extracts them to the location used for Dartdoc. Future<void> generatePlatformDocs() async { final String realm = engineRealm.isNotEmpty ? '$engineRealm/' : ''; for (final String platform in kPlatformDocs.keys) { final String zipFile = kPlatformDocs[platform]!.zipName; final String url = 'https://storage.googleapis.com/${realm}flutter_infra_release/flutter/$engineRevision/$zipFile'; await _extractDocs(url, platform, kPlatformDocs[platform]!, outputDir); } } /// Fetches the zip archive at the specified url. /// /// Returns null if the archive fails to download after [maxTries] attempts. Future<Archive?> _fetchArchive(String url, int maxTries) async { List<int>? responseBytes; for (int i = 0; i < maxTries; i++) { final http.Response response = await http.get(Uri.parse(url)); if (response.statusCode == 200) { responseBytes = response.bodyBytes; break; } stderr.writeln('Failed attempt ${i + 1} to fetch $url.'); // On failure print a short snipped from the body in case it's helpful. final int bodyLength = math.min(1024, response.body.length); stderr.writeln('Response status code ${response.statusCode}. Body: ${response.body.substring(0, bodyLength)}'); sleep(const Duration(seconds: 1)); } return responseBytes == null ? null : ZipDecoder().decodeBytes(responseBytes); } Future<void> _extractDocs(String url, String name, PlatformDocsSection platform, Directory outputDir) async { const int maxTries = 5; final Archive? archive = await _fetchArchive(url, maxTries); if (archive == null) { stderr.writeln('Failed to fetch zip archive from: $url after $maxTries attempts. Giving up.'); exit(1); } final Directory output = outputDir.childDirectory(platform.subdir); print('Extracting ${platform.zipName} to ${output.path}'); output.createSync(recursive: true); for (final ArchiveFile af in archive) { if (!af.name.endsWith('/')) { final File file = filesystem.file('${output.path}/${af.name}'); file.createSync(recursive: true); file.writeAsBytesSync(af.content as List<int>); } } final File testFile = output.childFile(platform.checkFile); if (!testFile.existsSync()) { print('Expected file ${testFile.path} not found'); exit(1); } print('${platform.sectionName} ready to go!'); } } /// Recursively copies `srcDir` to `destDir`, invoking [onFileCopied], if /// specified, for each source/destination file pair. /// /// Creates `destDir` if needed. void copyDirectorySync(Directory srcDir, Directory destDir, {void Function(File srcFile, File destFile)? onFileCopied, required FileSystem filesystem}) { if (!srcDir.existsSync()) { throw Exception('Source directory "${srcDir.path}" does not exist, nothing to copy'); } if (!destDir.existsSync()) { destDir.createSync(recursive: true); } for (final FileSystemEntity entity in srcDir.listSync()) { final String newPath = path.join(destDir.path, path.basename(entity.path)); if (entity is File) { final File newFile = filesystem.file(newPath); entity.copySync(newPath); onFileCopied?.call(entity, newFile); } else if (entity is Directory) { copyDirectorySync(entity, filesystem.directory(newPath), filesystem: filesystem); } else { throw Exception('${entity.path} is neither File nor Directory'); } } } void printStream(Stream<List<int>> stream, {String prefix = '', List<Pattern> filter = const <Pattern>[]}) { stream.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).listen((String line) { if (!filter.any((Pattern pattern) => line.contains(pattern))) { print('$prefix$line'.trim()); } }); } void zipDirectory(Directory src, File output, {required ProcessManager processManager}) { // We would use the archive package to do this in one line, but it // is a lot slower, and doesn't do compression nearly as well. final ProcessResult zipProcess = processManager.runSync( <String>[ 'zip', '-r', '-9', '-q', output.path, '.', ], workingDirectory: src.path, ); if (zipProcess.exitCode != 0) { print('Creating offline ZIP archive ${output.path} failed:'); print(zipProcess.stderr); exit(1); } } void tarDirectory(Directory src, File output, {required ProcessManager processManager}) { // We would use the archive package to do this in one line, but it // is a lot slower, and doesn't do compression nearly as well. final ProcessResult tarProcess = processManager.runSync( <String>[ 'tar', 'cf', output.path, '--use-compress-program', 'gzip --best', 'flutter.docset', ], workingDirectory: src.path, ); if (tarProcess.exitCode != 0) { print('Creating a tarball ${output.path} failed:'); print(tarProcess.stderr); exit(1); } } Future<Process> runPubProcess({ required List<String> arguments, Directory? workingDirectory, Map<String, String>? environment, @visibleForTesting ProcessManager processManager = const LocalProcessManager(), @visibleForTesting FileSystem filesystem = const LocalFileSystem(), }) { return processManager.start( <Object>[FlutterInformation.instance.getFlutterBinaryPath().path, 'pub', ...arguments], workingDirectory: (workingDirectory ?? filesystem.currentDirectory).path, environment: environment, ); } List<String> findPackageNames(FileSystem filesystem) { return findPackages(filesystem).map<String>((FileSystemEntity file) => path.basename(file.path)).toList(); } /// Finds all packages in the Flutter SDK List<Directory> findPackages(FileSystem filesystem) { return FlutterInformation.instance .getFlutterRoot() .childDirectory('packages') .listSync() .where((FileSystemEntity entity) { if (entity is! Directory) { return false; } final File pubspec = entity.childFile('pubspec.yaml'); if (!pubspec.existsSync()) { print("Unexpected package '${entity.path}' found in packages directory"); return false; } // Would be nice to use a real YAML parser here, but we don't want to // depend on a whole package for it, and this is sufficient. return !pubspec.readAsStringSync().contains('nodoc: true'); }) .cast<Directory>() .toList(); } /// An exception class used to indicate problems when collecting information. class FlutterInformationException implements Exception { FlutterInformationException(this.message); final String message; @override String toString() { return '$runtimeType: $message'; } } /// A singleton used to consolidate the way in which information about the /// Flutter repo and environment is collected. /// /// Collects the information once, and caches it for any later access. /// /// The singleton instance can be overridden by tests by setting [instance]. class FlutterInformation { FlutterInformation({ this.platform = const LocalPlatform(), this.processManager = const LocalProcessManager(), this.filesystem = const LocalFileSystem(), }); final Platform platform; final ProcessManager processManager; final FileSystem filesystem; static FlutterInformation? _instance; static FlutterInformation get instance => _instance ??= FlutterInformation(); @visibleForTesting static set instance(FlutterInformation? value) => _instance = value; /// The path to the Dart binary in the Flutter repo. /// /// This is probably a shell script. File getDartBinaryPath() { return getFlutterRoot().childDirectory('bin').childFile('dart'); } /// The path to the Dart binary in the Flutter repo. /// /// This is probably a shell script. File getFlutterBinaryPath() { return getFlutterRoot().childDirectory('bin').childFile('flutter'); } /// The path to the Flutter repo root directory. /// /// If the environment variable `FLUTTER_ROOT` is set, will use that instead /// of looking for it. /// /// Otherwise, uses the output of `flutter --version --machine` to find the /// Flutter root. Directory getFlutterRoot() { if (platform.environment['FLUTTER_ROOT'] != null) { return filesystem.directory(platform.environment['FLUTTER_ROOT']); } return getFlutterInformation()['flutterRoot']! as Directory; } /// Gets the semver version of the Flutter framework in the repo. Version getFlutterVersion() => getFlutterInformation()['frameworkVersion']! as Version; /// Gets the git hash of the engine used by the Flutter framework in the repo. String getEngineRevision() => getFlutterInformation()['engineRevision']! as String; /// Gets the value stored in bin/internal/engine.realm used by the Flutter /// framework repo. String getEngineRealm() => getFlutterInformation()['engineRealm']! as String; /// Gets the git hash of the Flutter framework in the repo. String getFlutterRevision() => getFlutterInformation()['flutterGitRevision']! as String; /// Gets the name of the current branch in the Flutter framework in the repo. String getBranchName() => getFlutterInformation()['branchName']! as String; Map<String, Object>? _cachedFlutterInformation; /// Gets a Map of various kinds of information about the Flutter repo. Map<String, Object> getFlutterInformation() { if (_cachedFlutterInformation != null) { return _cachedFlutterInformation!; } String flutterVersionJson; if (platform.environment['FLUTTER_VERSION'] != null) { flutterVersionJson = platform.environment['FLUTTER_VERSION']!; } else { // Determine which flutter command to run, which will determine which // flutter root is eventually used. If the FLUTTER_ROOT is set, then use // that flutter command, otherwise use the first one in the PATH. String flutterCommand; if (platform.environment['FLUTTER_ROOT'] != null) { flutterCommand = filesystem .directory(platform.environment['FLUTTER_ROOT']) .childDirectory('bin') .childFile('flutter') .absolute .path; } else { flutterCommand = 'flutter'; } ProcessResult result; try { result = processManager.runSync( <String>[flutterCommand, '--version', '--machine'], stdoutEncoding: utf8, ); } on ProcessException catch (e) { throw FlutterInformationException( 'Unable to determine Flutter information. Either set FLUTTER_ROOT, or place the ' 'flutter command in your PATH.\n$e'); } if (result.exitCode != 0) { throw FlutterInformationException( 'Unable to determine Flutter information, because of abnormal exit of flutter command.'); } // Strip out any non-JSON that might be printed along with the command // output. flutterVersionJson = (result.stdout as String) .replaceAll('Waiting for another flutter command to release the startup lock...', ''); } final Map<String, dynamic> flutterVersion = json.decode(flutterVersionJson) as Map<String, dynamic>; if (flutterVersion['flutterRoot'] == null || flutterVersion['frameworkVersion'] == null || flutterVersion['dartSdkVersion'] == null) { throw FlutterInformationException( 'Flutter command output has unexpected format, unable to determine flutter root location.'); } final Map<String, Object> info = <String, Object>{}; final Directory flutterRoot = filesystem.directory(flutterVersion['flutterRoot']! as String); info['flutterRoot'] = flutterRoot; info['frameworkVersion'] = Version.parse(flutterVersion['frameworkVersion'] as String); info['engineRevision'] = flutterVersion['engineRevision'] as String; final File engineRealm = flutterRoot.childDirectory('bin').childDirectory('internal').childFile('engine.realm'); info['engineRealm'] = engineRealm.existsSync() ? engineRealm.readAsStringSync().trim() : ''; final RegExpMatch? dartVersionRegex = RegExp(r'(?<base>[\d.]+)(?:\s+\(build (?<detail>[-.\w]+)\))?') .firstMatch(flutterVersion['dartSdkVersion'] as String); if (dartVersionRegex == null) { throw FlutterInformationException( 'Flutter command output has unexpected format, unable to parse dart SDK version ${flutterVersion['dartSdkVersion']}.'); } info['dartSdkVersion'] = Version.parse(dartVersionRegex.namedGroup('detail') ?? dartVersionRegex.namedGroup('base')!); info['branchName'] = _getBranchName(); info['flutterGitRevision'] = _getFlutterGitRevision(); _cachedFlutterInformation = info; return info; } // Get the name of the release branch. // // On LUCI builds, the git HEAD is detached, so first check for the env // variable "LUCI_BRANCH"; if it is not set, fall back to calling git. String _getBranchName() { final String? luciBranch = platform.environment['LUCI_BRANCH']; if (luciBranch != null && luciBranch.trim().isNotEmpty) { return luciBranch.trim(); } final ProcessResult gitResult = processManager.runSync(<String>['git', 'status', '-b', '--porcelain']); if (gitResult.exitCode != 0) { throw 'git status exit with non-zero exit code: ${gitResult.exitCode}'; } final RegExp gitBranchRegexp = RegExp(r'^## (.*)'); final RegExpMatch? gitBranchMatch = gitBranchRegexp.firstMatch((gitResult.stdout as String).trim().split('\n').first); return gitBranchMatch == null ? '' : gitBranchMatch.group(1)!.split('...').first; } // Get the git revision for the repo. String _getFlutterGitRevision() { const int kGitRevisionLength = 10; final ProcessResult gitResult = processManager.runSync(<String>['git', 'rev-parse', 'HEAD']); if (gitResult.exitCode != 0) { throw 'git rev-parse exit with non-zero exit code: ${gitResult.exitCode}'; } final String gitRevision = (gitResult.stdout as String).trim(); return gitRevision.length > kGitRevisionLength ? gitRevision.substring(0, kGitRevisionLength) : gitRevision; } }
flutter/dev/tools/create_api_docs.dart/0
{ "file_path": "flutter/dev/tools/create_api_docs.dart", "repo_id": "flutter", "token_count": 16237 }
547
{ "version": "v0_206", "md.comp.filled-card.container.color": "surfaceContainerHighest", "md.comp.filled-card.container.elevation": "md.sys.elevation.level0", "md.comp.filled-card.container.shadow-color": "shadow", "md.comp.filled-card.container.shape": "md.sys.shape.corner.medium", "md.comp.filled-card.disabled.container.color": "surfaceVariant", "md.comp.filled-card.disabled.container.elevation": "md.sys.elevation.level0", "md.comp.filled-card.disabled.container.opacity": 0.38, "md.comp.filled-card.dragged.container.elevation": "md.sys.elevation.level3", "md.comp.filled-card.dragged.state-layer.color": "onSurface", "md.comp.filled-card.dragged.state-layer.opacity": "md.sys.state.dragged.state-layer-opacity", "md.comp.filled-card.focus.container.elevation": "md.sys.elevation.level0", "md.comp.filled-card.focus.indicator.color": "secondary", "md.comp.filled-card.focus.indicator.outline.offset": "md.sys.state.focus-indicator.outer-offset", "md.comp.filled-card.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness", "md.comp.filled-card.focus.state-layer.color": "onSurface", "md.comp.filled-card.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.filled-card.hover.container.elevation": "md.sys.elevation.level1", "md.comp.filled-card.hover.state-layer.color": "onSurface", "md.comp.filled-card.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity", "md.comp.filled-card.icon.color": "primary", "md.comp.filled-card.icon.size": 24.0, "md.comp.filled-card.pressed.container.elevation": "md.sys.elevation.level0", "md.comp.filled-card.pressed.state-layer.color": "onSurface", "md.comp.filled-card.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity" }
flutter/dev/tools/gen_defaults/data/card_filled.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/card_filled.json", "repo_id": "flutter", "token_count": 686 }
548
{ "version": "v0_206", "md.sys.elevation.level0": 0.0, "md.sys.elevation.level1": 1.0, "md.sys.elevation.level2": 3.0, "md.sys.elevation.level3": 6.0, "md.sys.elevation.level4": 8.0, "md.sys.elevation.level5": 12.0 }
flutter/dev/tools/gen_defaults/data/elevation.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/elevation.json", "repo_id": "flutter", "token_count": 122 }
549
{ "version": "v0_206", "md.comp.secondary-navigation-tab.active-indicator.color": "primary", "md.comp.secondary-navigation-tab.active-indicator.height": 2.0, "md.comp.secondary-navigation-tab.active.label-text.color": "onSurface", "md.comp.secondary-navigation-tab.container.color": "surface", "md.comp.secondary-navigation-tab.container.elevation": "md.sys.elevation.level0", "md.comp.secondary-navigation-tab.container.height": 48.0, "md.comp.secondary-navigation-tab.container.shadow-color": "shadow", "md.comp.secondary-navigation-tab.container.shape": "md.sys.shape.corner.none", "md.comp.secondary-navigation-tab.focus.indicator.color": "secondary", "md.comp.secondary-navigation-tab.focus.indicator.outline.offset": "md.sys.state.focus-indicator.inner-offset", "md.comp.secondary-navigation-tab.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness", "md.comp.secondary-navigation-tab.focus.label-text.color": "onSurface", "md.comp.secondary-navigation-tab.focus.state-layer.color": "onSurface", "md.comp.secondary-navigation-tab.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.secondary-navigation-tab.hover.label-text.color": "onSurface", "md.comp.secondary-navigation-tab.hover.state-layer.color": "onSurface", "md.comp.secondary-navigation-tab.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity", "md.comp.secondary-navigation-tab.inactive.label-text.color": "onSurfaceVariant", "md.comp.secondary-navigation-tab.label-text.text-style": "titleSmall", "md.comp.secondary-navigation-tab.pressed.label-text.color": "onSurface", "md.comp.secondary-navigation-tab.pressed.state-layer.color": "onSurface", "md.comp.secondary-navigation-tab.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity", "md.comp.secondary-navigation-tab.with-icon.active.icon.color": "onSurface", "md.comp.secondary-navigation-tab.with-icon.focus.icon.color": "onSurface", "md.comp.secondary-navigation-tab.with-icon.hover.icon.color": "onSurface", "md.comp.secondary-navigation-tab.with-icon.icon.size": 24.0, "md.comp.secondary-navigation-tab.with-icon.inactive.icon.color": "onSurfaceVariant", "md.comp.secondary-navigation-tab.with-icon.pressed.icon.color": "onSurface" }
flutter/dev/tools/gen_defaults/data/navigation_tab_secondary.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/navigation_tab_secondary.json", "repo_id": "flutter", "token_count": 831 }
550
{ "version": "v0_206", "md.sys.typescale.body-large.font": "md.ref.typeface.plain", "md.sys.typescale.body-large.line-height": 24.0, "md.sys.typescale.body-large.size": 16.0, "md.sys.typescale.body-large.tracking": 0.5, "md.sys.typescale.body-large.weight": "md.ref.typeface.weight-regular", "md.sys.typescale.body-medium.font": "md.ref.typeface.plain", "md.sys.typescale.body-medium.line-height": 20.0, "md.sys.typescale.body-medium.size": 14.0, "md.sys.typescale.body-medium.tracking": 0.25, "md.sys.typescale.body-medium.weight": "md.ref.typeface.weight-regular", "md.sys.typescale.body-small.font": "md.ref.typeface.plain", "md.sys.typescale.body-small.line-height": 16.0, "md.sys.typescale.body-small.size": 12.0, "md.sys.typescale.body-small.tracking": 0.4, "md.sys.typescale.body-small.weight": "md.ref.typeface.weight-regular", "md.sys.typescale.display-large.font": "md.ref.typeface.brand", "md.sys.typescale.display-large.line-height": 64.0, "md.sys.typescale.display-large.size": 57.0, "md.sys.typescale.display-large.tracking": -0.25, "md.sys.typescale.display-large.weight": "md.ref.typeface.weight-regular", "md.sys.typescale.display-medium.font": "md.ref.typeface.brand", "md.sys.typescale.display-medium.line-height": 52.0, "md.sys.typescale.display-medium.size": 45.0, "md.sys.typescale.display-medium.tracking": 0.0, "md.sys.typescale.display-medium.weight": "md.ref.typeface.weight-regular", "md.sys.typescale.display-small.font": "md.ref.typeface.brand", "md.sys.typescale.display-small.line-height": 44.0, "md.sys.typescale.display-small.size": 36.0, "md.sys.typescale.display-small.tracking": 0.0, "md.sys.typescale.display-small.weight": "md.ref.typeface.weight-regular", "md.sys.typescale.headline-large.font": "md.ref.typeface.brand", "md.sys.typescale.headline-large.line-height": 40.0, "md.sys.typescale.headline-large.size": 32.0, "md.sys.typescale.headline-large.tracking": 0.0, "md.sys.typescale.headline-large.weight": "md.ref.typeface.weight-regular", "md.sys.typescale.headline-medium.font": "md.ref.typeface.brand", "md.sys.typescale.headline-medium.line-height": 36.0, "md.sys.typescale.headline-medium.size": 28.0, "md.sys.typescale.headline-medium.tracking": 0.0, "md.sys.typescale.headline-medium.weight": "md.ref.typeface.weight-regular", "md.sys.typescale.headline-small.font": "md.ref.typeface.brand", "md.sys.typescale.headline-small.line-height": 32.0, "md.sys.typescale.headline-small.size": 24.0, "md.sys.typescale.headline-small.tracking": 0.0, "md.sys.typescale.headline-small.weight": "md.ref.typeface.weight-regular", "md.sys.typescale.label-large.font": "md.ref.typeface.plain", "md.sys.typescale.label-large.line-height": 20.0, "md.sys.typescale.label-large.size": 14.0, "md.sys.typescale.label-large.tracking": 0.1, "md.sys.typescale.label-large.weight": "md.ref.typeface.weight-medium", "md.sys.typescale.label-large.weight.prominent": "md.ref.typeface.weight-bold", "md.sys.typescale.label-medium.font": "md.ref.typeface.plain", "md.sys.typescale.label-medium.line-height": 16.0, "md.sys.typescale.label-medium.size": 12.0, "md.sys.typescale.label-medium.tracking": 0.5, "md.sys.typescale.label-medium.weight": "md.ref.typeface.weight-medium", "md.sys.typescale.label-medium.weight.prominent": "md.ref.typeface.weight-bold", "md.sys.typescale.label-small.font": "md.ref.typeface.plain", "md.sys.typescale.label-small.line-height": 16.0, "md.sys.typescale.label-small.size": 11.0, "md.sys.typescale.label-small.tracking": 0.5, "md.sys.typescale.label-small.weight": "md.ref.typeface.weight-medium", "md.sys.typescale.title-large.font": "md.ref.typeface.brand", "md.sys.typescale.title-large.line-height": 28.0, "md.sys.typescale.title-large.size": 22.0, "md.sys.typescale.title-large.tracking": 0.0, "md.sys.typescale.title-large.weight": "md.ref.typeface.weight-regular", "md.sys.typescale.title-medium.font": "md.ref.typeface.plain", "md.sys.typescale.title-medium.line-height": 24.0, "md.sys.typescale.title-medium.size": 16.0, "md.sys.typescale.title-medium.tracking": 0.15, "md.sys.typescale.title-medium.weight": "md.ref.typeface.weight-medium", "md.sys.typescale.title-small.font": "md.ref.typeface.plain", "md.sys.typescale.title-small.line-height": 20.0, "md.sys.typescale.title-small.size": 14.0, "md.sys.typescale.title-small.tracking": 0.1, "md.sys.typescale.title-small.weight": "md.ref.typeface.weight-medium" }
flutter/dev/tools/gen_defaults/data/text_style.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/text_style.json", "repo_id": "flutter", "token_count": 1910 }
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 'template.dart'; class ChipTemplate extends TokenTemplate { const ChipTemplate(super.blockName, super.fileName, super.tokens, { super.colorSchemePrefix = '_colors.', super.textThemePrefix = '_textTheme.' }); static const String tokenGroup = 'md.comp.filter-chip'; static const String variant = '.flat'; @override String generate() => ''' class _${blockName}DefaultsM3 extends ChipThemeData { _${blockName}DefaultsM3(this.context, this.isEnabled) : super( elevation: ${elevation("$tokenGroup$variant.container")}, shape: ${shape("$tokenGroup.container")}, showCheckmark: true, ); final BuildContext context; final bool isEnabled; late final ColorScheme _colors = Theme.of(context).colorScheme; late final TextTheme _textTheme = Theme.of(context).textTheme; @override TextStyle? get labelStyle => ${textStyle("$tokenGroup.label-text")}?.copyWith( color: isEnabled ? ${color("$tokenGroup.unselected.label-text.color")} : ${color("$tokenGroup.disabled.label-text.color")}, ); @override MaterialStateProperty<Color?>? get color => null; // Subclasses override this getter @override Color? get shadowColor => ${colorOrTransparent("$tokenGroup.container.shadow-color")}; @override Color? get surfaceTintColor => ${colorOrTransparent("$tokenGroup.container.surface-tint-layer.color")}; @override Color? get checkmarkColor => null; @override Color? get deleteIconColor => isEnabled ? ${color("$tokenGroup.with-trailing-icon.unselected.trailing-icon.color")} : ${color("$tokenGroup.with-trailing-icon.disabled.trailing-icon.color")}; @override BorderSide? get side => isEnabled ? ${border('$tokenGroup$variant.unselected.outline')} : ${border('$tokenGroup$variant.disabled.unselected.outline')}; @override IconThemeData? get iconTheme => IconThemeData( color: isEnabled ? ${color("$tokenGroup.with-leading-icon.unselected.leading-icon.color")} : ${color("$tokenGroup.with-leading-icon.disabled.leading-icon.color")}, size: ${getToken("$tokenGroup.with-icon.icon.size")}, ); @override EdgeInsetsGeometry? get padding => const EdgeInsets.all(8.0); /// The label padding of the chip scales with the font size specified in the /// [labelStyle], and the system font size settings that scale font sizes /// globally. /// /// The chip at effective font size 14.0 starts with 8px on each side and as /// the font size scales up to closer to 28.0, the label padding is linearly /// interpolated from 8px to 4px. Once the label has a font size of 2 or /// higher, label padding remains 4px. @override EdgeInsetsGeometry? get labelPadding { final double fontSize = labelStyle?.fontSize ?? 14.0; final double fontSizeRatio = MediaQuery.textScalerOf(context).scale(fontSize) / 14.0; return EdgeInsets.lerp( const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 4.0), clampDouble(fontSizeRatio - 1.0, 0.0, 1.0), )!; } } '''; }
flutter/dev/tools/gen_defaults/lib/chip_template.dart/0
{ "file_path": "flutter/dev/tools/gen_defaults/lib/chip_template.dart", "repo_id": "flutter", "token_count": 1078 }
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 'template.dart'; class NavigationDrawerTemplate extends TokenTemplate { const NavigationDrawerTemplate(super.blockName, super.fileName, super.tokens, { super.colorSchemePrefix = '_colors.', super.textThemePrefix = '_textTheme.' }); @override String generate() => ''' class _${blockName}DefaultsM3 extends NavigationDrawerThemeData { _${blockName}DefaultsM3(this.context) : super( elevation: ${elevation("md.comp.navigation-drawer.modal.container")}, tileHeight: ${getToken("md.comp.navigation-drawer.active-indicator.height")}, indicatorShape: ${shape("md.comp.navigation-drawer.active-indicator")}, indicatorSize: const Size(${getToken("md.comp.navigation-drawer.active-indicator.width")}, ${getToken("md.comp.navigation-drawer.active-indicator.height")}), ); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; late final TextTheme _textTheme = Theme.of(context).textTheme; @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")}; @override Color? get indicatorColor => ${componentColor("md.comp.navigation-drawer.active-indicator")}; @override MaterialStateProperty<IconThemeData?>? get iconTheme { return MaterialStateProperty.resolveWith((Set<MaterialState> states) { return IconThemeData( size: ${getToken("md.comp.navigation-drawer.icon.size")}, color: states.contains(MaterialState.disabled) ? _colors.onSurfaceVariant.withOpacity(0.38) : states.contains(MaterialState.selected) ? ${componentColor("md.comp.navigation-drawer.active.icon")} : ${componentColor("md.comp.navigation-drawer.inactive.icon")}, ); }); } @override MaterialStateProperty<TextStyle?>? get labelTextStyle { return MaterialStateProperty.resolveWith((Set<MaterialState> states) { final TextStyle style = ${textStyle("md.comp.navigation-drawer.label-text")}!; return style.apply( color: states.contains(MaterialState.disabled) ? _colors.onSurfaceVariant.withOpacity(0.38) : states.contains(MaterialState.selected) ? ${componentColor("md.comp.navigation-drawer.active.label-text")} : ${componentColor("md.comp.navigation-drawer.inactive.label-text")}, ); }); } } '''; }
flutter/dev/tools/gen_defaults/lib/navigation_drawer_template.dart/0
{ "file_path": "flutter/dev/tools/gen_defaults/lib/navigation_drawer_template.dart", "repo_id": "flutter", "token_count": 1007 }
553
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:collection'; import 'dart:io'; final TokenLogger tokenLogger = TokenLogger(); /// Class to keep track of used tokens and versions. class TokenLogger { TokenLogger(); void init({ required Map<String, dynamic> allTokens, required Map<String, List<String>> versionMap }){ _allTokens = allTokens; _versionMap = versionMap; } /// Map of all tokens to their values. late Map<String, dynamic> _allTokens; // Map of versions to their token files. late Map<String, List<String>> _versionMap; // Sorted set of used tokens. final SplayTreeSet<String> _usedTokens = SplayTreeSet<String>(); // Set of tokens that were referenced on some templates, but do not exist. final Set<String> _unavailableTokens = <String>{}; void clear() { _allTokens.clear(); _versionMap.clear(); _usedTokens.clear(); _unavailableTokens.clear(); } /// Logs a token. void log(String token) { if (!_allTokens.containsKey(token)) { _unavailableTokens.add(token); return; } _usedTokens.add(token); } /// Prints version usage to the console. void printVersionUsage({required bool verbose}) { final String versionsString = 'Versions used: ${_versionMap.keys.join(', ')}'; print(versionsString); if (verbose) { for (final String version in _versionMap.keys) { print(' $version:'); final List<String> files = List<String>.from(_versionMap[version]!); files.sort(); for (final String file in files) { print(' $file'); } } print(''); } } /// Prints tokens usage to the console. void printTokensUsage({required bool verbose}) { final Set<String> allTokensSet = _allTokens.keys.toSet(); if (verbose) { for (final String token in SplayTreeSet<String>.from(allTokensSet).toList()) { if (_usedTokens.contains(token)) { print('✅ $token'); } else { print('❌ $token'); } } print(''); } print('Tokens used: ${_usedTokens.length}/${_allTokens.length}'); if (_unavailableTokens.isNotEmpty) { print(''); print('\x1B[31m' 'Some referenced tokens do not exist: ${_unavailableTokens.length}' '\x1B[0m'); for (final String token in _unavailableTokens) { print(' $token'); } } } /// Dumps version and tokens usage to a file. void dumpToFile(String path) { final File file = File(path); file.createSync(recursive: true); final String versionsString = 'Versions used, ${_versionMap.keys.join(', ')}'; file.writeAsStringSync('$versionsString\n${_usedTokens.join(',\n')}\n'); } }
flutter/dev/tools/gen_defaults/lib/token_logger.dart/0
{ "file_path": "flutter/dev/tools/gen_defaults/lib/token_logger.dart", "repo_id": "flutter", "token_count": 1046 }
554
{ "LOCK": ["CapsLock", "CapsLock"], "MOD2": ["NumLock", "NumLock"] }
flutter/dev/tools/gen_keycodes/data/gtk_lock_bit_mapping.json/0
{ "file_path": "flutter/dev/tools/gen_keycodes/data/gtk_lock_bit_mapping.json", "repo_id": "flutter", "token_count": 33 }
555
// These are supplemental code data to be added to those that Chromium // defines. // ============================================================ // Game controller buttons // ============================================================ // Since the web doesn't have game controller buttons defined in the // same way, these map USB HID codes for game controller buttons to // Android/Linux button names. // // The HID codes here are not real USB HID codes, because the USB HID standard // doesn't define game controller buttons in this way. It defines only two // button "collections" (fire/jump and trigger), with the button number for // each collection sent as extra data. Since we're just using USB HID as a // convenient namespace, and not using these HID codes for interfacing with a // USB protocol, we can define new ones to enumerate the buttons. These don't // collide with any currently defined HID codes. // // USB HID evdev XKB Win Mac DOMKey Code DOM_CODE(0x05ff01, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton1", BUTTON_1), DOM_CODE(0x05ff02, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton2", BUTTON_2), DOM_CODE(0x05ff03, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton3", BUTTON_3), DOM_CODE(0x05ff04, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton4", BUTTON_4), DOM_CODE(0x05ff05, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton5", BUTTON_5), DOM_CODE(0x05ff06, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton6", BUTTON_6), DOM_CODE(0x05ff07, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton7", BUTTON_7), DOM_CODE(0x05ff08, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton8", BUTTON_8), DOM_CODE(0x05ff09, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton9", BUTTON_9), DOM_CODE(0x05ff0a, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton10", BUTTON_10), DOM_CODE(0x05ff0b, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton11", BUTTON_11), DOM_CODE(0x05ff0c, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton12", BUTTON_12), DOM_CODE(0x05ff0d, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton13", BUTTON_13), DOM_CODE(0x05ff0e, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton14", BUTTON_14), DOM_CODE(0x05ff0f, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton15", BUTTON_15), DOM_CODE(0x05ff10, 0x0000, 0x0000, 0x0000, 0xffff, "GameButton16", BUTTON_16), DOM_CODE(0x05ff11, 0x0000, 0x0000, 0x0000, 0xffff, "GameButtonA", BUTTON_A), DOM_CODE(0x05ff12, 0x0000, 0x0000, 0x0000, 0xffff, "GameButtonB", BUTTON_B), DOM_CODE(0x05ff13, 0x0000, 0x0000, 0x0000, 0xffff, "GameButtonC", BUTTON_C), DOM_CODE(0x05ff14, 0x0000, 0x0000, 0x0000, 0xffff, "GameButtonLeft1", BUTTON_L1), DOM_CODE(0x05ff15, 0x0000, 0x0000, 0x0000, 0xffff, "GameButtonLeft2", BUTTON_L2), DOM_CODE(0x05ff16, 0x0000, 0x0000, 0x0000, 0xffff, "GameButtonMode", BUTTON_MODE), DOM_CODE(0x05ff17, 0x0000, 0x0000, 0x0000, 0xffff, "GameButtonRight1", BUTTON_R1), DOM_CODE(0x05ff18, 0x0000, 0x0000, 0x0000, 0xffff, "GameButtonRight2", BUTTON_R2), DOM_CODE(0x05ff19, 0x0000, 0x0000, 0x0000, 0xffff, "GameButtonSelect", BUTTON_SELECT), DOM_CODE(0x05ff1a, 0x0000, 0x0000, 0x0000, 0xffff, "GameButtonStart", BUTTON_START), DOM_CODE(0x05ff1b, 0x0000, 0x0000, 0x0000, 0xffff, "GameButtonThumbLeft", BUTTON_THUMBL), DOM_CODE(0x05ff1c, 0x0000, 0x0000, 0x0000, 0xffff, "GameButtonThumbRight", BUTTON_THUMBR), DOM_CODE(0x05ff1d, 0x0000, 0x0000, 0x0000, 0xffff, "GameButtonX", BUTTON_X), DOM_CODE(0x05ff1e, 0x0000, 0x0000, 0x0000, 0xffff, "GameButtonY", BUTTON_Y), DOM_CODE(0x05ff1f, 0x0000, 0x0000, 0x0000, 0xffff, "GameButtonZ", BUTTON_Z), // Sometimes the Escape key produces "Esc" instead of "Escape". This includes // older IE and Firefox browsers, and the current Cobalt browser. // See: https://github.com/flutter/flutter/issues/106062 DOM_CODE(0x070029, 0x0000, 0x0000, 0x0000, 0xffff, "Esc", ESCAPE), // ============================================================ // Fn key for Mac // ============================================================ // The Mac defines a key code for the Fn key on Mac keyboards, but it's not // defined on other platforms. Chromium does define an "Fn" row, but doesn't // give it a Mac keycode. This overrides their definition. // USB HID evdev XKB Win Mac DOMKey Code DOM_CODE(0x000012, 0x0000, 0x0000, 0x0000, 0x003f, "Fn", FN),
flutter/dev/tools/gen_keycodes/data/supplemental_hid_codes.inc/0
{ "file_path": "flutter/dev/tools/gen_keycodes/data/supplemental_hid_codes.inc", "repo_id": "flutter", "token_count": 1750 }
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 'dart:convert'; import 'dart:io'; import 'package:path/path.dart' as path; import 'constants.dart'; import 'physical_key_data.dart'; import 'utils.dart'; bool _isControlCharacter(int codeUnit) { return (codeUnit <= 0x1f && codeUnit >= 0x00) || (codeUnit >= 0x7f && codeUnit <= 0x9f); } /// A pair of strings that represents left and right modifiers. class _ModifierPair { const _ModifierPair(this.left, this.right); final String left; final String right; } // Return map[key1][key2] as a non-nullable List<T>, where both map[key1] or // map[key1][key2] might be null. List<T> _getGrandchildList<T>(Map<String, dynamic> map, String key1, String key2) { final dynamic value = (map[key1] as Map<String, dynamic>?)?[key2]; final List<dynamic>? dynamicNullableList = value as List<dynamic>?; final List<dynamic> dynamicList = dynamicNullableList ?? <dynamic>[]; return dynamicList.cast<T>(); } /// The data structure used to manage keyboard key entries. /// /// The main constructor parses the given input data into the data structure. /// /// The data structure can be also loaded and saved to JSON, with the /// [LogicalKeyData.fromJson] constructor and [toJson] method, respectively. class LogicalKeyData { factory LogicalKeyData( String chromiumKeys, String gtkKeyCodeHeader, String gtkNameMap, String windowsKeyCodeHeader, String windowsNameMap, String androidKeyCodeHeader, String androidNameMap, String macosLogicalToPhysical, String iosLogicalToPhysical, String glfwHeaderFile, String glfwNameMap, PhysicalKeyData physicalKeyData, ) { final Map<String, LogicalKeyEntry> data = _readKeyEntries(chromiumKeys); _readWindowsKeyCodes(data, windowsKeyCodeHeader, parseMapOfListOfString(windowsNameMap)); _readGtkKeyCodes(data, gtkKeyCodeHeader, parseMapOfListOfString(gtkNameMap)); _readAndroidKeyCodes(data, androidKeyCodeHeader, parseMapOfListOfString(androidNameMap)); _readMacOsKeyCodes(data, physicalKeyData, parseMapOfListOfString(macosLogicalToPhysical)); _readIosKeyCodes(data, physicalKeyData, parseMapOfListOfString(iosLogicalToPhysical)); _readFuchsiaKeyCodes(data, physicalKeyData); _readGlfwKeyCodes(data, glfwHeaderFile, parseMapOfListOfString(glfwNameMap)); // Sort entries by value final List<MapEntry<String, LogicalKeyEntry>> sortedEntries = data.entries.toList()..sort( (MapEntry<String, LogicalKeyEntry> a, MapEntry<String, LogicalKeyEntry> b) => LogicalKeyEntry.compareByValue(a.value, b.value), ); data ..clear() ..addEntries(sortedEntries); return LogicalKeyData._(data); } /// Parses the given JSON data and populates the data structure from it. factory LogicalKeyData.fromJson(Map<String, dynamic> contentMap) { final Map<String, LogicalKeyEntry> data = <String, LogicalKeyEntry>{}; data.addEntries(contentMap.values.map((dynamic value) { final LogicalKeyEntry entry = LogicalKeyEntry.fromJsonMapEntry(value as Map<String, dynamic>); return MapEntry<String, LogicalKeyEntry>(entry.name, entry); })); return LogicalKeyData._(data); } /// Parses the input data given in from the various data source files, /// populating the data structure. /// /// None of the parameters may be null. LogicalKeyData._(this._data); /// Converts the data structure into a JSON structure that can be parsed by /// [LogicalKeyData.fromJson]. Map<String, dynamic> toJson() { final Map<String, dynamic> outputMap = <String, dynamic>{}; for (final LogicalKeyEntry entry in _data.values) { outputMap[entry.name] = entry.toJson(); } return outputMap; } /// Find an entry from name. /// /// Asserts if the name is not found. LogicalKeyEntry entryByName(String name) { assert(_data.containsKey(name), 'Unable to find logical entry by name $name.'); return _data[name]!; } /// All entries. Iterable<LogicalKeyEntry> get entries => _data.values; // Keys mapped from their names. final Map<String, LogicalKeyEntry> _data; /// Parses entries from Chromium's key mapping header file. /// /// Lines in this file look like either of these (without the ///): /// Key Enum Unicode code point /// DOM_KEY_UNI("Backspace", BACKSPACE, 0x0008), /// Key Enum Value /// DOM_KEY_MAP("Accel", ACCEL, 0x0101), /// /// Flutter's supplemental_key_data.inc also has some new formats. /// The following format uses a character as the 3rd argument. /// Key Enum Character /// DOM_KEY_UNI("KeyB", KEY_B, 'b'), /// /// The following format should be mapped to the Flutter plane. /// Key Enum Character /// FLUTTER_KEY_MAP("Lang4", LANG4, 0x00013), static Map<String, LogicalKeyEntry> _readKeyEntries(String input) { final Map<int, LogicalKeyEntry> dataByValue = <int, LogicalKeyEntry>{}; final RegExp domKeyRegExp = RegExp( r'(?<source>DOM|FLUTTER)_KEY_(?<kind>UNI|MAP)\s*\(\s*' r'"(?<name>[^\s]+?)",\s*' r'(?<enum>[^\s]+?),\s*' r"(?:0[xX](?<unicode>[a-fA-F0-9]+)|'(?<char>.)')\s*" r'\)', // Multiline is necessary because some definitions spread across // multiple lines. multiLine: true, ); final RegExp commentRegExp = RegExp(r'//.*$', multiLine: true); input = input.replaceAll(commentRegExp, ''); for (final RegExpMatch match in domKeyRegExp.allMatches(input)) { final String source = match.namedGroup('source')!; final String webName = match.namedGroup('name')!; // ".AltGraphLatch" is consumed internally and not expressed to the Web. if (webName.startsWith('.')) { continue; } final String name = LogicalKeyEntry.computeName(webName.replaceAll(RegExp('[^A-Za-z0-9]'), '')); final int value = match.namedGroup('unicode') != null ? getHex(match.namedGroup('unicode')!) : match.namedGroup('char')!.codeUnitAt(0); final String? keyLabel = (match.namedGroup('kind')! == 'UNI' && !_isControlCharacter(value)) ? String.fromCharCode(value) : null; // Skip modifier keys from DOM. They will be added with supplemental data. if (_chromeModifiers.containsKey(name) && source == 'DOM') { continue; } final bool isPrintable = keyLabel != null; final int entryValue = toPlane(value, _sourceToPlane(source, isPrintable)); final LogicalKeyEntry entry = dataByValue.putIfAbsent(entryValue, () => LogicalKeyEntry.fromName( value: entryValue, name: name, keyLabel: keyLabel, ), ); if (source == 'DOM' && !isPrintable) { entry.webNames.add(webName); } } return Map<String, LogicalKeyEntry>.fromEntries( dataByValue.values.map((LogicalKeyEntry entry) => MapEntry<String, LogicalKeyEntry>(entry.name, entry), ), ); } static void _readMacOsKeyCodes( Map<String, LogicalKeyEntry> data, PhysicalKeyData physicalKeyData, Map<String, List<String>> logicalToPhysical, ) { final Map<String, String> physicalToLogical = reverseMapOfListOfString(logicalToPhysical, (String logicalKeyName, String physicalKeyName) { print('Duplicate logical key name $logicalKeyName for macOS'); }); physicalToLogical.forEach((String physicalKeyName, String logicalKeyName) { final PhysicalKeyEntry physicalEntry = physicalKeyData.entryByName(physicalKeyName); assert(physicalEntry.macOSScanCode != null, 'Physical entry $physicalKeyName does not have a macOSScanCode.'); final LogicalKeyEntry? logicalEntry = data[logicalKeyName]; assert(logicalEntry != null, 'Unable to find logical entry by name $logicalKeyName.'); logicalEntry!.macOSKeyCodeNames.add(physicalEntry.name); logicalEntry.macOSKeyCodeValues.add(physicalEntry.macOSScanCode!); }); } static void _readIosKeyCodes( Map<String, LogicalKeyEntry> data, PhysicalKeyData physicalKeyData, Map<String, List<String>> logicalToPhysical, ) { final Map<String, String> physicalToLogical = reverseMapOfListOfString(logicalToPhysical, (String logicalKeyName, String physicalKeyName) { print('Duplicate logical key name $logicalKeyName for iOS'); }); physicalToLogical.forEach((String physicalKeyName, String logicalKeyName) { final PhysicalKeyEntry physicalEntry = physicalKeyData.entryByName(physicalKeyName); assert(physicalEntry.iOSScanCode != null, 'Physical entry $physicalKeyName does not have an iosScanCode.'); final LogicalKeyEntry? logicalEntry = data[logicalKeyName]; assert(logicalEntry != null, 'Unable to find logical entry by name $logicalKeyName.'); logicalEntry!.iOSKeyCodeNames.add(physicalEntry.name); logicalEntry.iOSKeyCodeValues.add(physicalEntry.iOSScanCode!); }); } /// Parses entries from GTK's gdkkeysyms.h key code data file. /// /// Lines in this file look like this (without the ///): /// /** Space key. */ /// #define GDK_KEY_space 0x020 static void _readGtkKeyCodes(Map<String, LogicalKeyEntry> data, String headerFile, Map<String, List<String>> nameToGtkName) { final RegExp definedCodes = RegExp( r'#define ' r'GDK_KEY_(?<name>[a-zA-Z0-9_]+)\s*' r'0x(?<value>[0-9a-f]+),?', ); final Map<String, String> gtkNameToFlutterName = reverseMapOfListOfString(nameToGtkName, (String flutterName, String gtkName) { print('Duplicate GTK logical name $gtkName'); }); for (final RegExpMatch match in definedCodes.allMatches(headerFile)) { final String gtkName = match.namedGroup('name')!; final String? name = gtkNameToFlutterName[gtkName]; final int value = int.parse(match.namedGroup('value')!, radix: 16); if (name == null) { // print('Unmapped GTK logical entry $gtkName'); continue; } final LogicalKeyEntry? entry = data[name]; if (entry == null) { print('Invalid logical entry by name $name (from GTK $gtkName)'); continue; } entry ..gtkNames.add(gtkName) ..gtkValues.add(value); } } static void _readWindowsKeyCodes(Map<String, LogicalKeyEntry> data, String headerFile, Map<String, List<String>> nameMap) { // The mapping from the Flutter name (e.g. "enter") to the Windows name (e.g. // "RETURN"). final Map<String, String> nameToFlutterName = reverseMapOfListOfString(nameMap, (String flutterName, String windowsName) { print('Duplicate Windows logical name $windowsName'); }); final RegExp definedCodes = RegExp( r'define ' r'VK_(?<name>[A-Z0-9_]+)\s*' r'(?<value>[A-Z0-9_x]+),?', ); for (final RegExpMatch match in definedCodes.allMatches(headerFile)) { final String windowsName = match.namedGroup('name')!; final String? name = nameToFlutterName[windowsName]; final int value = int.tryParse(match.namedGroup('value')!)!; if (name == null) { print('Unmapped Windows logical entry $windowsName'); continue; } final LogicalKeyEntry? entry = data[name]; if (entry == null) { print('Invalid logical entry by name $name (from Windows $windowsName)'); continue; } addNameValue( entry.windowsNames, entry.windowsValues, windowsName, value, ); } } /// Parses entries from Android's keycodes.h key code data file. /// /// Lines in this file look like this (without the ///): /// /** Left Control modifier key. */ /// AKEYCODE_CTRL_LEFT = 113, static void _readAndroidKeyCodes(Map<String, LogicalKeyEntry> data, String headerFile, Map<String, List<String>> nameMap) { final Map<String, String> nameToFlutterName = reverseMapOfListOfString(nameMap, (String flutterName, String androidName) { print('Duplicate Android logical name $androidName'); }); final RegExp enumBlock = RegExp(r'enum\s*\{(.*)\};', multiLine: true); // Eliminate everything outside of the enum block. headerFile = headerFile.replaceAllMapped(enumBlock, (Match match) => match.group(1)!); final RegExp enumEntry = RegExp( r'AKEYCODE_(?<name>[A-Z0-9_]+)\s*' r'=\s*' r'(?<value>[0-9]+),?', ); for (final RegExpMatch match in enumEntry.allMatches(headerFile)) { final String androidName = match.namedGroup('name')!; final String? name = nameToFlutterName[androidName]; final int value = int.tryParse(match.namedGroup('value')!)!; if (name == null) { print('Unmapped Android logical entry $androidName'); continue; } final LogicalKeyEntry? entry = data[name]; if (entry == null) { print('Invalid logical entry by name $name (from Android $androidName)'); continue; } entry ..androidNames.add(androidName) ..androidValues.add(value); } } static void _readFuchsiaKeyCodes(Map<String, LogicalKeyEntry> data, PhysicalKeyData physicalData) { for (final LogicalKeyEntry entry in data.values) { final int? value = (() { if (entry.value == 0) { return 0; } final String? keyLabel = printable[entry.constantName]; if (keyLabel != null && !entry.constantName.startsWith('numpad')) { return toPlane(keyLabel.codeUnitAt(0), kUnicodePlane.value); } else { final PhysicalKeyEntry? physicalEntry = physicalData.tryEntryByName(entry.name); if (physicalEntry != null) { return toPlane(physicalEntry.usbHidCode, kFuchsiaPlane.value); } } })(); if (value != null) { entry.fuchsiaValues.add(value); } } } /// Parses entries from GLFW's keycodes.h key code data file. /// /// Lines in this file look like this (without the ///): /// /** Space key. */ /// #define GLFW_KEY_SPACE 32, /// #define GLFW_KEY_LAST GLFW_KEY_MENU static void _readGlfwKeyCodes(Map<String, LogicalKeyEntry> data, String headerFile, Map<String, List<String>> nameMap) { final Map<String, String> nameToFlutterName = reverseMapOfListOfString(nameMap, (String flutterName, String glfwName) { print('Duplicate GLFW logical name $glfwName'); }); // Only get the KEY definitions, ignore the rest (mouse, joystick, etc). final RegExp definedCodes = RegExp( r'define\s+' r'GLFW_KEY_(?<name>[A-Z0-9_]+)\s+' r'(?<value>[A-Z0-9_]+),?', ); final Map<String, dynamic> replaced = <String, dynamic>{}; for (final RegExpMatch match in definedCodes.allMatches(headerFile)) { final String name = match.namedGroup('name')!; final String value = match.namedGroup('value')!; replaced[name] = int.tryParse(value) ?? value.replaceAll('GLFW_KEY_', ''); } final Map<String, int> glfwNameToKeyCode = <String, int>{}; replaced.forEach((String key, dynamic value) { // Some definition values point to other definitions (e.g #define GLFW_KEY_LAST GLFW_KEY_MENU). if (value is String) { glfwNameToKeyCode[key] = replaced[value] as int; } else { glfwNameToKeyCode[key] = value as int; } }); glfwNameToKeyCode.forEach((String glfwName, int value) { final String? name = nameToFlutterName[glfwName]; if (name == null) { return; } final LogicalKeyEntry? entry = data[nameToFlutterName[glfwName]]; if (entry == null) { print('Invalid logical entry by name $name (from GLFW $glfwName)'); return; } addNameValue( entry.glfwNames, entry.glfwValues, glfwName, value, ); }); } // Map Web key to the pair of key names static final Map<String, _ModifierPair> _chromeModifiers = () { final String rawJson = File(path.join(dataRoot, 'chromium_modifiers.json',)).readAsStringSync(); return (json.decode(rawJson) as Map<String, dynamic>).map((String key, dynamic value) { final List<dynamic> pair = value as List<dynamic>; return MapEntry<String, _ModifierPair>(key, _ModifierPair(pair[0] as String, pair[1] as String)); }); }(); /// Returns the static map of printable representations. static final Map<String, String> printable = (() { final String printableKeys = File(path.join(dataRoot, 'printable.json',)).readAsStringSync(); return (json.decode(printableKeys) as Map<String, dynamic>) .cast<String, String>(); })(); /// Returns the static map of synonym representations. /// /// These include synonyms for keys which don't have printable /// representations, and appear in more than one place on the keyboard (e.g. /// SHIFT, ALT, etc.). static final Map<String, List<String>> synonyms = (() { final String synonymKeys = File(path.join(dataRoot, 'synonyms.json',)).readAsStringSync(); final Map<String, dynamic> dynamicSynonym = json.decode(synonymKeys) as Map<String, dynamic>; return dynamicSynonym.map((String name, dynamic values) { // The keygen and algorithm of macOS relies on synonyms being pairs. // See siblingKeyMap in macos_code_gen.dart. final List<String> names = (values as List<dynamic>).whereType<String>().toList(); assert(names.length == 2); return MapEntry<String, List<String>>(name, names); }); })(); static int _sourceToPlane(String source, bool isPrintable) { if (isPrintable) { return kUnicodePlane.value; } switch (source) { case 'DOM': return kUnprintablePlane.value; case 'FLUTTER': return kFlutterPlane.value; default: assert(false, 'Unrecognized logical key source $source'); return kFlutterPlane.value; } } } /// A single entry in the key data structure. /// /// Can be read from JSON with the [LogicalKeyEntry.fromJsonMapEntry] constructor, or /// written with the [toJson] method. class LogicalKeyEntry { /// Creates a single key entry from available data. LogicalKeyEntry({ required this.value, required this.name, this.keyLabel, }) : webNames = <String>[], macOSKeyCodeNames = <String>[], macOSKeyCodeValues = <int>[], iOSKeyCodeNames = <String>[], iOSKeyCodeValues = <int>[], gtkNames = <String>[], gtkValues = <int>[], windowsNames = <String>[], windowsValues = <int>[], androidNames = <String>[], androidValues = <int>[], fuchsiaValues = <int>[], glfwNames = <String>[], glfwValues = <int>[]; LogicalKeyEntry.fromName({ required int value, required String name, String? keyLabel, }) : this( value: value, name: name, keyLabel: keyLabel, ); /// Populates the key from a JSON map. LogicalKeyEntry.fromJsonMapEntry(Map<String, dynamic> map) : value = map['value'] as int, name = map['name'] as String, webNames = _getGrandchildList<String>(map, 'names', 'web'), macOSKeyCodeNames = _getGrandchildList<String>(map, 'names', 'macos'), macOSKeyCodeValues = _getGrandchildList<int>(map, 'values', 'macos'), iOSKeyCodeNames = _getGrandchildList<String>(map, 'names', 'ios'), iOSKeyCodeValues = _getGrandchildList<int>(map, 'values', 'ios'), gtkNames = _getGrandchildList<String>(map, 'names', 'gtk'), gtkValues = _getGrandchildList<int>(map, 'values', 'gtk'), windowsNames = _getGrandchildList<String>(map, 'names', 'windows'), windowsValues = _getGrandchildList<int>(map, 'values', 'windows'), androidNames = _getGrandchildList<String>(map, 'names', 'android'), androidValues = _getGrandchildList<int>(map, 'values', 'android'), fuchsiaValues = _getGrandchildList<int>(map, 'values', 'fuchsia'), glfwNames = _getGrandchildList<String>(map, 'names', 'glfw'), glfwValues = _getGrandchildList<int>(map, 'values', 'glfw'), keyLabel = map['keyLabel'] as String?; final int value; final String name; /// The name of the key suitable for placing in comments. String get commentName => computeCommentName(name); String get constantName => computeConstantName(commentName); /// The name of the key, mostly derived from the DomKey name in Chromium, /// but where there was no DomKey representation, derived from the Chromium /// symbol name. final List<String> webNames; /// The names of the key codes that corresponds to this logical key on macOS, /// created from the corresponding physical keys. final List<String> macOSKeyCodeNames; /// The key codes that corresponds to this logical key on macOS, created from /// the physical key list substituted with the key mapping. final List<int> macOSKeyCodeValues; /// The names of the key codes that corresponds to this logical key on iOS, /// created from the corresponding physical keys. final List<String> iOSKeyCodeNames; /// The key codes that corresponds to this logical key on iOS, created from the /// physical key list substituted with the key mapping. final List<int> iOSKeyCodeValues; /// The list of names that GTK gives to this key (symbol names minus the /// prefix). final List<String> gtkNames; /// The list of GTK key codes matching this key, created by looking up the /// Linux name in the GTK data, and substituting the GTK key code /// value. final List<int> gtkValues; /// The list of names that Windows gives to this key (symbol names minus the /// prefix). final List<String> windowsNames; /// The list of Windows key codes matching this key, created by looking up the /// Windows name in the Chromium data, and substituting the Windows key code /// value. final List<int> windowsValues; /// The list of names that Android gives to this key (symbol names minus the /// prefix). final List<String> androidNames; /// The list of Android key codes matching this key, created by looking up the /// Android name in the Chromium data, and substituting the Android key code /// value. final List<int> androidValues; final List<int> fuchsiaValues; /// The list of names that GLFW gives to this key (symbol names minus the /// prefix). final List<String> glfwNames; /// The list of GLFW key codes matching this key, created by looking up the /// GLFW name in the Chromium data, and substituting the GLFW key code /// value. final List<int> glfwValues; /// A string indicating the letter on the keycap of a letter key. /// /// This is only used to generate the key label mapping in keyboard_maps.g.dart. /// [LogicalKeyboardKey.keyLabel] uses a different definition and is generated /// differently. final String? keyLabel; /// Creates a JSON map from the key data. Map<String, dynamic> toJson() { return removeEmptyValues(<String, dynamic>{ 'name': name, 'value': value, 'keyLabel': keyLabel, 'names': <String, dynamic>{ 'web': webNames, 'macos': macOSKeyCodeNames, 'ios': iOSKeyCodeNames, 'gtk': gtkNames, 'windows': windowsNames, 'android': androidNames, 'glfw': glfwNames, }, 'values': <String, List<int>>{ 'macos': macOSKeyCodeValues, 'ios': iOSKeyCodeValues, 'gtk': gtkValues, 'windows': windowsValues, 'android': androidValues, 'fuchsia': fuchsiaValues, 'glfw': glfwValues, }, }); } @override String toString() { return "'$name': (value: ${toHex(value)}) "; } /// Gets the named used for the key constant in the definitions in /// keyboard_key.g.dart. /// /// If set by the constructor, returns the name set, but otherwise constructs /// the name from the various different names available, making sure that the /// name isn't a Dart reserved word (if it is, then it adds the word "Key" to /// the end of the name). static String computeName(String rawName) { final String result = rawName.replaceAll('PinP', 'PInP'); if (kDartReservedWords.contains(result)) { return '${result}Key'; } return result; } /// Takes the [name] and converts it from lower camel case to capitalized /// separate words (e.g. "wakeUp" converts to "Wake Up"). static String computeCommentName(String name) { final String replaced = name.replaceAllMapped( RegExp(r'(Digit|Numpad|Lang|Button|Left|Right)([0-9]+)'), (Match match) => '${match.group(1)} ${match.group(2)}', ); return replaced // 'fooBar' => 'foo Bar', 'fooBAR' => 'foo BAR' .replaceAllMapped(RegExp(r'([^A-Z])([A-Z])'), (Match match) => '${match.group(1)} ${match.group(2)}') // 'ABCDoo' => 'ABC Doo' .replaceAllMapped(RegExp(r'([A-Z])([A-Z])([a-z])'), (Match match) => '${match.group(1)} ${match.group(2)}${match.group(3)}') // 'AB1' => 'AB 1', 'F1' => 'F1' .replaceAllMapped(RegExp(r'([A-Z]{2,})([0-9])'), (Match match) => '${match.group(1)} ${match.group(2)}') // 'Foo1' => 'Foo 1' .replaceAllMapped(RegExp(r'([a-z])([0-9])'), (Match match) => '${match.group(1)} ${match.group(2)}') .trim(); } static String computeConstantName(String commentName) { // Convert the first word in the comment name. final String lowerCamelSpace = commentName.replaceFirstMapped(RegExp(r'^[^ ]+'), (Match match) => match[0]!.toLowerCase(), ); final String result = lowerCamelSpace.replaceAll(' ', ''); if (kDartReservedWords.contains(result)) { return '${result}Key'; } return result; } static int compareByValue(LogicalKeyEntry a, LogicalKeyEntry b) => a.value.compareTo(b.value); }
flutter/dev/tools/gen_keycodes/lib/logical_key_data.dart/0
{ "file_path": "flutter/dev/tools/gen_keycodes/lib/logical_key_data.dart", "repo_id": "flutter", "token_count": 9665 }
557
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'localizations_utils.dart'; String generateMaterialHeader(String regenerateInstructions) { return ''' // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file has been automatically generated. Please do not edit it manually. // To regenerate the file, use: // $regenerateInstructions import 'dart:collection'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart' as intl; import '../material_localizations.dart'; // The classes defined here encode all of the translations found in the // `flutter_localizations/lib/src/l10n/*.arb` files. // // These classes are constructed by the [getMaterialTranslation] method at the // bottom of this file, and used by the [_MaterialLocalizationsDelegate.load] // method defined in `flutter_localizations/lib/src/material_localizations.dart`.'''; } /// Returns the source of the constructor for a GlobalMaterialLocalizations /// subclass. String generateMaterialConstructor(LocaleInfo locale) { final String localeName = locale.originalString; return ''' /// Create an instance of the translation bundle for ${describeLocale(localeName)}. /// /// For details on the meaning of the arguments, see [GlobalMaterialLocalizations]. const MaterialLocalization${locale.camelCase()}({ super.localeName = '$localeName', required super.fullYearFormat, required super.compactDateFormat, required super.shortDateFormat, required super.mediumDateFormat, required super.longDateFormat, required super.yearMonthFormat, required super.shortMonthDayFormat, required super.decimalFormat, required super.twoDigitZeroPaddedFormat, });'''; } const String materialFactoryName = 'getMaterialTranslation'; const String materialFactoryDeclaration = ''' GlobalMaterialLocalizations? getMaterialTranslation( Locale locale, intl.DateFormat fullYearFormat, intl.DateFormat compactDateFormat, intl.DateFormat shortDateFormat, intl.DateFormat mediumDateFormat, intl.DateFormat longDateFormat, intl.DateFormat yearMonthFormat, intl.DateFormat shortMonthDayFormat, intl.NumberFormat decimalFormat, intl.NumberFormat twoDigitZeroPaddedFormat, ) {'''; const String materialFactoryArguments = 'fullYearFormat: fullYearFormat, compactDateFormat: compactDateFormat, shortDateFormat: shortDateFormat, mediumDateFormat: mediumDateFormat, longDateFormat: longDateFormat, yearMonthFormat: yearMonthFormat, shortMonthDayFormat: shortMonthDayFormat, decimalFormat: decimalFormat, twoDigitZeroPaddedFormat: twoDigitZeroPaddedFormat'; const String materialSupportedLanguagesConstant = 'kMaterialSupportedLanguages'; const String materialSupportedLanguagesDocMacro = 'flutter.localizations.material.languages';
flutter/dev/tools/localization/gen_material_localizations.dart/0
{ "file_path": "flutter/dev/tools/localization/gen_material_localizations.dart", "repo_id": "flutter", "token_count": 825 }
558
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as path; import 'package:vitool/vitool.dart'; void main() { test('parsePixels', () { expect(parsePixels('23px'), 23); expect(parsePixels('9px'), 9); expect(() { parsePixels('9pt'); }, throwsArgumentError); }); test('parsePoints', () { expect(parsePoints('1.0, 2.0'), const <Point<double>>[Point<double>(1.0, 2.0)], ); expect(parsePoints('12.0, 34.0 5.0, 6.6'), const <Point<double>>[ Point<double>(12.0, 34.0), Point<double>(5.0, 6.6), ], ); expect(parsePoints('12.0 34.0 5.0 6.6'), const <Point<double>>[ Point<double>(12.0, 34.0), Point<double>(5.0, 6.6), ], ); }); group('parseSvg', () { test('empty SVGs', () { interpretSvg(testAsset('empty_svg_1_48x48.svg')); interpretSvg(testAsset('empty_svg_2_100x50.svg')); }); test('illegal SVGs', () { expect( () { interpretSvg(testAsset('illegal_svg_multiple_roots.svg')); }, throwsA(anything), ); }); test('SVG size', () { expect( interpretSvg(testAsset('empty_svg_1_48x48.svg')).size, const Point<double>(48.0, 48.0), ); expect( interpretSvg(testAsset('empty_svg_2_100x50.svg')).size, const Point<double>(100.0, 50.0), ); }); test('horizontal bar', () { final FrameData frameData = interpretSvg(testAsset('horizontal_bar.svg')); expect(frameData.paths, <SvgPath>[ const SvgPath('path_1', <SvgPathCommand>[ SvgPathCommand('M', <Point<double>>[Point<double>(0.0, 19.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(48.0, 19.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(48.0, 29.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(0.0, 29.0)]), SvgPathCommand('Z', <Point<double>>[]), ]), ]); }); test('leading space path command', () { interpretSvg(testAsset('leading_space_path_command.svg')); }); test('SVG illegal path', () { expect( () { interpretSvg(testAsset('illegal_path.svg')); }, throwsA(anything), ); }); test('SVG group', () { final FrameData frameData = interpretSvg(testAsset('bars_group.svg')); expect(frameData.paths, const <SvgPath>[ SvgPath('path_1', <SvgPathCommand>[ SvgPathCommand('M', <Point<double>>[Point<double>(0.0, 19.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(48.0, 19.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(48.0, 29.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(0.0, 29.0)]), SvgPathCommand('Z', <Point<double>>[]), ]), SvgPath('path_2', <SvgPathCommand>[ SvgPathCommand('M', <Point<double>>[Point<double>(0.0, 34.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(48.0, 34.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(48.0, 44.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(0.0, 44.0)]), SvgPathCommand('Z', <Point<double>>[]), ]), ]); }); test('SVG group translate', () { final FrameData frameData = interpretSvg(testAsset('bar_group_translate.svg')); expect(frameData.paths, const <SvgPath>[ SvgPath('path_1', <SvgPathCommand>[ SvgPathCommand('M', <Point<double>>[Point<double>(0.0, 34.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(48.0, 34.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(48.0, 44.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(0.0, 44.0)]), SvgPathCommand('Z', <Point<double>>[]), ]), ]); }); test('SVG group scale', () { final FrameData frameData = interpretSvg(testAsset('bar_group_scale.svg')); expect(frameData.paths, const <SvgPath>[ SvgPath( 'path_1', <SvgPathCommand>[ SvgPathCommand('M', <Point<double>>[Point<double>(0.0, 9.5)]), SvgPathCommand('L', <Point<double>>[Point<double>(24.0, 9.5)]), SvgPathCommand('L', <Point<double>>[Point<double>(24.0, 14.5)]), SvgPathCommand('L', <Point<double>>[Point<double>(0.0, 14.5)]), SvgPathCommand('Z', <Point<double>>[]), ]), ]); }); test('SVG group rotate scale', () { final FrameData frameData = interpretSvg(testAsset('bar_group_rotate_scale.svg')); expect(frameData.paths, const <PathMatcher>[ PathMatcher( SvgPath( 'path_1', <SvgPathCommand>[ SvgPathCommand('L', <Point<double>>[Point<double>(29.0, 0.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(29.0, 48.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(19.0, 48.0)]), SvgPathCommand('M', <Point<double>>[Point<double>(19.0, 0.0)]), SvgPathCommand('Z', <Point<double>>[]), ]), margin: precisionErrorTolerance, ), ]); }); test('SVG illegal transform', () { expect( () { interpretSvg(testAsset('illegal_transform.svg')); }, throwsA(anything), ); }); test('SVG group opacity', () { final FrameData frameData = interpretSvg(testAsset('bar_group_opacity.svg')); expect(frameData.paths, const <SvgPath>[ SvgPath( 'path_1', <SvgPathCommand>[ SvgPathCommand('M', <Point<double>>[Point<double>(0.0, 19.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(48.0, 19.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(48.0, 29.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(0.0, 29.0)]), SvgPathCommand('Z', <Point<double>>[]), ], opacity: 0.5, ), ]); }); test('horizontal bar relative', () { // This asset uses the relative 'l' command instead of 'L'. final FrameData frameData = interpretSvg(testAsset('horizontal_bar_relative.svg')); expect(frameData.paths, const <SvgPath>[ SvgPath( 'path_1', <SvgPathCommand>[ SvgPathCommand('M', <Point<double>>[Point<double>(0.0, 19.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(48.0, 19.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(48.0, 29.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(0.0, 29.0)]), SvgPathCommand('Z', <Point<double>>[]), ]), ]); }); test('close in middle of path', () { // This asset uses the relative 'l' command instead of 'L'. final FrameData frameData = interpretSvg(testAsset('close_path_in_middle.svg')); expect(frameData.paths, const <SvgPath>[ SvgPath( 'path_1', <SvgPathCommand>[ SvgPathCommand('M', <Point<double>>[Point<double>(50.0, 50.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(60.0, 50.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(60.0, 60.0)]), SvgPathCommand('Z', <Point<double>>[]), SvgPathCommand('L', <Point<double>>[Point<double>(50.0, 40.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(40.0, 40.0)]), SvgPathCommand('Z', <Point<double>>[]), ]), ]); }); }); group('create PathAnimation', () { test('single path', () { const List<FrameData> frameData = <FrameData>[ FrameData( Point<double>(10.0, 10.0), <SvgPath>[ SvgPath( 'path_1', <SvgPathCommand>[ SvgPathCommand('M', <Point<double>>[Point<double>(0.0, 0.0)]), SvgPathCommand('L', <Point<double>>[Point<double>(10.0, 10.0)]), ], ), ], ), ]; expect(PathAnimation.fromFrameData(frameData, 0), const PathAnimationMatcher(PathAnimation( <PathCommandAnimation>[ PathCommandAnimation('M', <List<Point<double>>>[ <Point<double>>[Point<double>(0.0, 0.0)], ]), PathCommandAnimation('L', <List<Point<double>>>[ <Point<double>>[Point<double>(10.0, 10.0)], ]), ], opacities: <double>[1.0], )), ); }); test('multiple paths', () { const List<FrameData> frameData = <FrameData>[ FrameData( Point<double>(10.0, 10.0), <SvgPath>[ SvgPath( 'path_1', <SvgPathCommand>[ SvgPathCommand('M', <Point<double>>[Point<double>(0.0, 0.0)]), ], ), SvgPath( 'path_2', <SvgPathCommand>[ SvgPathCommand('M', <Point<double>>[Point<double>(5.0, 6.0)]), ], ), ], ), ]; expect(PathAnimation.fromFrameData(frameData, 0), const PathAnimationMatcher(PathAnimation( <PathCommandAnimation>[ PathCommandAnimation('M', <List<Point<double>>>[ <Point<double>>[Point<double>(0.0, 0.0)], ]), ], opacities: <double>[1.0], )), ); expect(PathAnimation.fromFrameData(frameData, 1), const PathAnimationMatcher(PathAnimation( <PathCommandAnimation>[ PathCommandAnimation('M', <List<Point<double>>>[ <Point<double>>[Point<double>(5.0, 6.0)], ]), ], opacities: <double>[1.0], )), ); }); test('multiple frames', () { const List<FrameData> frameData = <FrameData>[ FrameData( Point<double>(10.0, 10.0), <SvgPath>[ SvgPath( 'path_1', <SvgPathCommand>[ SvgPathCommand('M', <Point<double>>[Point<double>(0.0, 0.0)]), ], opacity: 0.5, ), ], ), FrameData( Point<double>(10.0, 10.0), <SvgPath>[ SvgPath( 'path_1', <SvgPathCommand>[ SvgPathCommand('M', <Point<double>>[Point<double>(10.0, 10.0)]), ], ), ], ), ]; expect(PathAnimation.fromFrameData(frameData, 0), const PathAnimationMatcher(PathAnimation( <PathCommandAnimation>[ PathCommandAnimation('M', <List<Point<double>>>[ <Point<double>>[ Point<double>(0.0, 0.0), Point<double>(10.0, 10.0), ], ]), ], opacities: <double>[0.5, 1.0], )), ); }); }); group('create Animation', () { test('multiple paths', () { const List<FrameData> frameData = <FrameData>[ FrameData( Point<double>(10.0, 10.0), <SvgPath>[ SvgPath( 'path_1', <SvgPathCommand>[ SvgPathCommand('M', <Point<double>>[Point<double>(0.0, 0.0)]), ], ), SvgPath( 'path_1', <SvgPathCommand>[ SvgPathCommand('M', <Point<double>>[Point<double>(5.0, 6.0)]), ], ), ], ), ]; final Animation animation = Animation.fromFrameData(frameData); expect(animation.paths[0], const PathAnimationMatcher(PathAnimation( <PathCommandAnimation>[ PathCommandAnimation('M', <List<Point<double>>>[ <Point<double>>[Point<double>(0.0, 0.0)], ]), ], opacities: <double>[1.0], )), ); expect(animation.paths[1], const PathAnimationMatcher(PathAnimation( <PathCommandAnimation>[ PathCommandAnimation('M', <List<Point<double>>>[ <Point<double>>[Point<double>(5.0, 6.0)], ]), ], opacities: <double>[1.0], )), ); expect(animation.size, const Point<double>(10.0, 10.0)); }); }); group('toDart', () { test('_PathMoveTo', () { const PathCommandAnimation command = PathCommandAnimation( 'M', <List<Point<double>>>[ <Point<double>>[ Point<double>(1.0, 2.0), Point<double>(3.0, 4.0), ], ], ); expect(command.toDart(), ' const _PathMoveTo(\n' ' const <Offset>[\n' ' const Offset(1.0, 2.0),\n' ' const Offset(3.0, 4.0),\n' ' ],\n' ' ),\n', ); }); test('_PathLineTo', () { const PathCommandAnimation command = PathCommandAnimation( 'L', <List<Point<double>>>[ <Point<double>>[ Point<double>(1.0, 2.0), Point<double>(3.0, 4.0), ], ], ); expect(command.toDart(), ' const _PathLineTo(\n' ' const <Offset>[\n' ' const Offset(1.0, 2.0),\n' ' const Offset(3.0, 4.0),\n' ' ],\n' ' ),\n', ); }); test('_PathCubicTo', () { const PathCommandAnimation command = PathCommandAnimation( 'C', <List<Point<double>>>[ <Point<double>>[ Point<double>(16.0, 24.0), Point<double>(16.0, 10.0), ], <Point<double>>[ Point<double>(16.0, 25.0), Point<double>(16.0, 11.0), ], <Point<double>>[ Point<double>(40.0, 40.0), Point<double>(40.0, 40.0), ], ], ); expect(command.toDart(), ' const _PathCubicTo(\n' ' const <Offset>[\n' ' const Offset(16.0, 24.0),\n' ' const Offset(16.0, 10.0),\n' ' ],\n' ' const <Offset>[\n' ' const Offset(16.0, 25.0),\n' ' const Offset(16.0, 11.0),\n' ' ],\n' ' const <Offset>[\n' ' const Offset(40.0, 40.0),\n' ' const Offset(40.0, 40.0),\n' ' ],\n' ' ),\n', ); }); test('_PathClose', () { const PathCommandAnimation command = PathCommandAnimation( 'Z', <List<Point<double>>>[], ); expect(command.toDart(), ' const _PathClose(\n' ' ),\n', ); }); test('Unsupported path command', () { const PathCommandAnimation command = PathCommandAnimation( 'h', <List<Point<double>>>[], ); expect( () { command.toDart(); }, throwsA(anything), ); }); test('_PathFrames', () { const PathAnimation pathAnimation = PathAnimation( <PathCommandAnimation>[ PathCommandAnimation('M', <List<Point<double>>>[ <Point<double>>[ Point<double>(0.0, 0.0), Point<double>(10.0, 10.0), ], ]), PathCommandAnimation('L', <List<Point<double>>>[ <Point<double>>[ Point<double>(48.0, 10.0), Point<double>(0.0, 0.0), ], ]), ], opacities: <double>[0.5, 1.0], ); expect(pathAnimation.toDart(), ' const _PathFrames(\n' ' opacities: const <double>[\n' ' 0.5,\n' ' 1.0,\n' ' ],\n' ' commands: const <_PathCommand>[\n' ' const _PathMoveTo(\n' ' const <Offset>[\n' ' const Offset(0.0, 0.0),\n' ' const Offset(10.0, 10.0),\n' ' ],\n' ' ),\n' ' const _PathLineTo(\n' ' const <Offset>[\n' ' const Offset(48.0, 10.0),\n' ' const Offset(0.0, 0.0),\n' ' ],\n' ' ),\n' ' ],\n' ' ),\n', ); }); test('Animation', () { const Animation animation = Animation( Point<double>(48.0, 48.0), <PathAnimation>[ PathAnimation( <PathCommandAnimation>[ PathCommandAnimation('M', <List<Point<double>>>[ <Point<double>>[ Point<double>(0.0, 0.0), Point<double>(10.0, 10.0), ], ]), PathCommandAnimation('L', <List<Point<double>>>[ <Point<double>>[ Point<double>(48.0, 10.0), Point<double>(0.0, 0.0), ], ]), ], opacities: <double>[0.5, 1.0], ), PathAnimation( <PathCommandAnimation>[ PathCommandAnimation('M', <List<Point<double>>>[ <Point<double>>[ Point<double>(0.0, 0.0), Point<double>(10.0, 10.0), ], ]), ], opacities: <double>[0.5, 1.0], ), ]); expect(animation.toDart('_AnimatedIconData', r'_$data1'), 'const _AnimatedIconData _\$data1 = const _AnimatedIconData(\n' ' const Size(48.0, 48.0),\n' ' const <_PathFrames>[\n' ' const _PathFrames(\n' ' opacities: const <double>[\n' ' 0.5,\n' ' 1.0,\n' ' ],\n' ' commands: const <_PathCommand>[\n' ' const _PathMoveTo(\n' ' const <Offset>[\n' ' const Offset(0.0, 0.0),\n' ' const Offset(10.0, 10.0),\n' ' ],\n' ' ),\n' ' const _PathLineTo(\n' ' const <Offset>[\n' ' const Offset(48.0, 10.0),\n' ' const Offset(0.0, 0.0),\n' ' ],\n' ' ),\n' ' ],\n' ' ),\n' ' const _PathFrames(\n' ' opacities: const <double>[\n' ' 0.5,\n' ' 1.0,\n' ' ],\n' ' commands: const <_PathCommand>[\n' ' const _PathMoveTo(\n' ' const <Offset>[\n' ' const Offset(0.0, 0.0),\n' ' const Offset(10.0, 10.0),\n' ' ],\n' ' ),\n' ' ],\n' ' ),\n' ' ],\n' ');', ); }); }); } // Matches all path commands' points within an error margin. class PathMatcher extends Matcher { const PathMatcher(this.actual, {this.margin = 0.0}); final SvgPath actual; final double margin; @override Description describe(Description description) => description.add('$actual (±$margin)'); @override bool matches(dynamic item, Map<dynamic, dynamic> matchState) { if (item == null) { return item == actual; } if (item.runtimeType != actual.runtimeType) { return false; } final SvgPath other = item as SvgPath; if (other.id != actual.id || other.opacity != actual.opacity) { return false; } if (other.commands.length != actual.commands.length) { return false; } for (int i = 0; i < other.commands.length; i += 1) { if (!commandsMatch(actual.commands[i], other.commands[i])) { return false; } } return true; } bool commandsMatch(SvgPathCommand actual, SvgPathCommand other) { if (other.points.length != actual.points.length) { return false; } for (int i = 0; i < other.points.length; i += 1) { if ((other.points[i].x - actual.points[i].x).abs() > margin) { return false; } if ((other.points[i].y - actual.points[i].y).abs() > margin) { return false; } } return true; } } class PathAnimationMatcher extends Matcher { const PathAnimationMatcher(this.expected); final PathAnimation expected; @override Description describe(Description description) => description.add('$expected'); @override bool matches(dynamic item, Map<dynamic, dynamic> matchState) { if (item == null) { return item == expected; } if (item.runtimeType != expected.runtimeType) { return false; } final PathAnimation other = item as PathAnimation; if (!const ListEquality<double>().equals(other.opacities, expected.opacities)) { return false; } if (other.commands.length != expected.commands.length) { return false; } for (int i = 0; i < other.commands.length; i += 1) { if (!commandsMatch(expected.commands[i], other.commands[i])) { return false; } } return true; } bool commandsMatch(PathCommandAnimation expected, PathCommandAnimation other) { if (other.points.length != expected.points.length) { return false; } for (int i = 0; i < other.points.length; i += 1) { if (!const ListEquality<Point<double>>().equals(other.points[i], expected.points[i])) { return false; } } return true; } } String testAsset(String name) { return path.join('test_assets', name); }
flutter/dev/tools/vitool/test/vitool_test.dart/0
{ "file_path": "flutter/dev/tools/vitool/test/vitool_test.dart", "repo_id": "flutter", "token_count": 11946 }
559
# API Example Code This directory contains the API sample code that is referenced from the API documentation in the framework. The examples can be run individually by just specifying the path to the example on the command line (or in the run configuration of an IDE). For example (no pun intended!), to run the first example from the `Curve2D` class in Chrome, you would run it like so from the [api](.) directory: ``` % flutter run -d chrome lib/animation/curves/curve2_d.0.dart ``` All of these same examples are available on the API docs site. For instance, the example above is available on [this page]( https://api.flutter.dev/flutter/animation/Curve2D-class.html#animation.Curve2D.1). Most of the samples are available as interactive examples in [Dartpad](https://dartpad.dev), but some (the ones marked with `{@tool sample}` in the framework source code), just don't make sense on the web, and so are available as standalone examples that can be run here. For instance, setting the system overlay style doesn't make sense on the web (it only changes the notification area background color on Android), so you can run the example for that on an Android device like so: ``` % flutter run -d MyAndroidDevice lib/services/system_chrome/system_chrome.set_system_u_i_overlay_style.1.dart ``` ## Naming > `lib/library/file/class_name.n.dart` > > `lib/library/file/class_name.member_name.n.dart` The naming scheme for the files is similar to the hierarchy under [packages/flutter/lib/src](../../packages/flutter/lib/src), except that the files are represented as directories (without the `.dart` suffix), and each sample in the file is a separate file in that directory. So, for the example above, where the examples are from the [packages/flutter/lib/src/animation/curves.dart](../../packages/flutter/lib/src/animation/curves.dart) file, the `Curve2D` class, the first sample (hence the index "0") for that symbol resides in the file named [lib/animation/curves/curve2_d.0.dart](lib/animation/curves/curve2_d.0.dart). Symbol names are converted from "CamelCase" to "snake_case". Dots are left between symbol names, so the first example for symbol `InputDecoration.prefixIconConstraints` would be converted to `input_decoration.prefix_icon_constraints.0.dart`. If the same example is linked to from multiple symbols, the source will be in the canonical location for one of the symbols, and the link in the API docs block for the other symbols will point to the first symbol's example location. ## Authoring > For more detailed information about authoring examples, see > [the snippets package](https://pub.dev/packages/snippets). When authoring examples, first place a block in the Dartdoc documentation for the symbol you would like to attach it to. Here's what it might look like if you wanted to add a new example to the `Curve2D` class: ```dart /// {@tool dartpad} /// Write a description of the example here. This description will appear in the /// API web documentation to introduce the example. /// /// ** See code in examples/api/lib/animation/curves/curve2_d.0.dart ** /// {@end-tool} ``` The "See code in" line needs to be formatted exactly as above, with no wrapping or newlines, one space after the "`**`" at the beginning, and one space before the "`**`" at the end, and the words "See code in" at the beginning of the line. This is what the snippets tool use when finding the example source code that you are creating. Use `{@tool dartpad}` for Dartpad examples, and use `{@tool sample}` for examples that shouldn't be run/shown in Dartpad. Once that comment block is inserted in the source code, create a new file at the appropriate path under [`examples/api`](.). See the [sample_templates](./lib/sample_templates/) directory for examples of different types of samples with some best practices applied. The filename should match the location of the source file it is linked from, and is named for the symbol it is attached to, in lower_snake_case, with an index relating to their order within the doc comment. So, for the `Curve2D` example above, since it's in the `animation` library, in a file called `curves.dart`, and it's the first example, it should have the name `examples/api/lib/animation/curves/curve2_d.0.dart`. You should also add tests for your sample code under [`examples/api/test`](./test), that matches their location under [lib](./lib), ending in `_test.dart`. See the section on [writing tests](#writing-tests) for more information on what kinds of tests to write. The entire example should be in a single file, so that Dartpad can load it. Only packages that can be loaded by Dartpad may be imported. If you use one that hasn't been used in an example before, you may have to add it to the [pubspec.yaml](pubspec.yaml) in the api directory. ## Snippets There is another type of example that can also be authored, using `{@tool snippet}`. Snippet examples are just written inline in the source, like so: ```dart /// {@tool dartpad} /// Write a description of the example here. This description will appear in the /// API web documentation to introduce the example. /// /// ```dart /// // Sample code goes here, e.g.: /// const Widget emptyBox = SizedBox(); /// ``` /// {@end-tool} ``` The source for these snippets isn't stored under the [`examples/api`](.) directory, or available in Dartpad in the API docs, since they're not intended to be runnable, they just show some incomplete snippet of example code. It must compile (in the context of the sample analyzer), but doesn't need to do anything. See [the snippets documentation]( https://pub.dev/packages/snippets#snippet-tool) for more information about the context that the analyzer uses. ## Writing Tests Examples are required to have tests. There is already a "smoke test" that simply builds and runs all the API examples, just to make sure that they start up without crashing. Functionality tests are required the examples, and generally just do what is normally done for writing tests. The one thing that makes it more challenging to do for examples is that they can't really be written for testability in any obvious way, since that would complicate the examples and make them harder to explain. As an example, in regular framework code, you might include a parameter for a `Platform` object that can be overridden by a test to supply a dummy platform, but in the example. This would be unnecessarily complex for the example. In all other ways, these are just normal tests. You don't need to re-test the functionality of the widget being used in the example, but you should test the functionality and integrity of the example itself. Tests go into a directory under [test](./test) that matches their location under [lib](./lib). They are named the same as the example they are testing, with `_test.dart` at the end, like other tests. For instance, a `LayoutBuilder` example that resides in [`lib/widgets/layout_builder/layout_builder.0.dart`]( ./lib/widgets/layout_builder/layout_builder.0.dart) would have its tests in a file named [`test/widgets/layout_builder/layout_builder.0_test.dart`]( ./test/widgets/layout_builder/layout_builder.0_test.dart)
flutter/examples/api/README.md/0
{ "file_path": "flutter/examples/api/README.md", "repo_id": "flutter", "token_count": 1993 }
560
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; /// Flutter code sample for [CupertinoDatePicker]. void main() => runApp(const DatePickerApp()); class DatePickerApp extends StatelessWidget { const DatePickerApp({super.key}); @override Widget build(BuildContext context) { return const CupertinoApp( theme: CupertinoThemeData(brightness: Brightness.light), home: DatePickerExample(), ); } } class DatePickerExample extends StatefulWidget { const DatePickerExample({super.key}); @override State<DatePickerExample> createState() => _DatePickerExampleState(); } class _DatePickerExampleState extends State<DatePickerExample> { DateTime date = DateTime(2016, 10, 26); DateTime time = DateTime(2016, 5, 10, 22, 35); DateTime dateTime = DateTime(2016, 8, 3, 17, 45); // This function displays a CupertinoModalPopup with a reasonable fixed height // which hosts CupertinoDatePicker. void _showDialog(Widget child) { showCupertinoModalPopup<void>( context: context, builder: (BuildContext context) => Container( height: 216, padding: const EdgeInsets.only(top: 6.0), // The Bottom margin is provided to align the popup above the system // navigation bar. margin: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom, ), // Provide a background color for the popup. color: CupertinoColors.systemBackground.resolveFrom(context), // Use a SafeArea widget to avoid system overlaps. child: SafeArea( top: false, child: child, ), ), ); } @override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar( middle: Text('CupertinoDatePicker Sample'), ), child: DefaultTextStyle( style: TextStyle( color: CupertinoColors.label.resolveFrom(context), fontSize: 22.0, ), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ _DatePickerItem( children: <Widget>[ const Text('Date'), CupertinoButton( // Display a CupertinoDatePicker in date picker mode. onPressed: () => _showDialog( CupertinoDatePicker( initialDateTime: date, mode: CupertinoDatePickerMode.date, use24hFormat: true, // This shows day of week alongside day of month showDayOfWeek: true, // This is called when the user changes the date. onDateTimeChanged: (DateTime newDate) { setState(() => date = newDate); }, ), ), // In this example, the date is formatted manually. You can // use the intl package to format the value based on the // user's locale settings. child: Text( '${date.month}-${date.day}-${date.year}', style: const TextStyle( fontSize: 22.0, ), ), ), ], ), _DatePickerItem( children: <Widget>[ const Text('Time'), CupertinoButton( // Display a CupertinoDatePicker in time picker mode. onPressed: () => _showDialog( CupertinoDatePicker( initialDateTime: time, mode: CupertinoDatePickerMode.time, use24hFormat: true, // This is called when the user changes the time. onDateTimeChanged: (DateTime newTime) { setState(() => time = newTime); }, ), ), // In this example, the time value is formatted manually. // You can use the intl package to format the value based on // the user's locale settings. child: Text( '${time.hour}:${time.minute}', style: const TextStyle( fontSize: 22.0, ), ), ), ], ), _DatePickerItem( children: <Widget>[ const Text('DateTime'), CupertinoButton( // Display a CupertinoDatePicker in dateTime picker mode. onPressed: () => _showDialog( CupertinoDatePicker( initialDateTime: dateTime, use24hFormat: true, // This is called when the user changes the dateTime. onDateTimeChanged: (DateTime newDateTime) { setState(() => dateTime = newDateTime); }, ), ), // In this example, the time value is formatted manually. You // can use the intl package to format the value based on the // user's locale settings. child: Text( '${dateTime.month}-${dateTime.day}-${dateTime.year} ${dateTime.hour}:${dateTime.minute}', style: const TextStyle( fontSize: 22.0, ), ), ), ], ), ], ), ), ), ); } } // This class simply decorates a row of widgets. class _DatePickerItem extends StatelessWidget { const _DatePickerItem({required this.children}); final List<Widget> children; @override Widget build(BuildContext context) { return DecoratedBox( decoration: const BoxDecoration( border: Border( top: BorderSide( color: CupertinoColors.inactiveGray, width: 0.0, ), bottom: BorderSide( color: CupertinoColors.inactiveGray, width: 0.0, ), ), ), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: children, ), ), ); } }
flutter/examples/api/lib/cupertino/date_picker/cupertino_date_picker.0.dart/0
{ "file_path": "flutter/examples/api/lib/cupertino/date_picker/cupertino_date_picker.0.dart", "repo_id": "flutter", "token_count": 3610 }
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. // Flutter code sample [ActionChip]. import 'package:flutter/material.dart'; void main() => runApp(const ChipApp()); class ChipApp extends StatelessWidget { const ChipApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(colorSchemeSeed: const Color(0xff6750a4), useMaterial3: true), home: const ActionChipExample(), ); } } class ActionChipExample extends StatefulWidget { const ActionChipExample({super.key}); @override State<ActionChipExample> createState() => _ActionChipExampleState(); } class _ActionChipExampleState extends State<ActionChipExample> { bool favorite = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('ActionChip Sample'), ), body: Center( child: ActionChip( avatar: Icon(favorite ? Icons.favorite : Icons.favorite_border), label: const Text('Save to favorites'), onPressed: () { setState(() { favorite = !favorite; }); }, ), ), ); } }
flutter/examples/api/lib/material/action_chip/action_chip.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/action_chip/action_chip.0.dart", "repo_id": "flutter", "token_count": 482 }
562
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/material.dart'; /// Flutter code sample for [Autocomplete] that demonstrates fetching the /// options asynchronously and debouncing the network calls, including handling /// network errors. void main() => runApp(const AutocompleteExampleApp()); const Duration fakeAPIDuration = Duration(seconds: 1); const Duration debounceDuration = Duration(milliseconds: 500); class AutocompleteExampleApp extends StatelessWidget { const AutocompleteExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Autocomplete - async, debouncing, and network errors'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Type below to autocomplete the following possible results: ${_FakeAPI._kOptions}.'), const SizedBox(height: 32.0), const _AsyncAutocomplete(), ], ), ), ), ); } } class _AsyncAutocomplete extends StatefulWidget { const _AsyncAutocomplete(); @override State<_AsyncAutocomplete > createState() => _AsyncAutocompleteState(); } class _AsyncAutocompleteState extends State<_AsyncAutocomplete > { // The query currently being searched for. If null, there is no pending // request. String? _currentQuery; // The most recent options received from the API. late Iterable<String> _lastOptions = <String>[]; late final _Debounceable<Iterable<String>?, String> _debouncedSearch; // Whether to consider the fake network to be offline. bool _networkEnabled = true; // A network error was received on the most recent query. bool _networkError = false; // Calls the "remote" API to search with the given query. Returns null when // the call has been made obsolete. Future<Iterable<String>?> _search(String query) async { _currentQuery = query; late final Iterable<String> options; try { options = await _FakeAPI.search(_currentQuery!, _networkEnabled); } catch (error) { if (error is _NetworkException) { setState(() { _networkError = true; }); return <String>[]; } rethrow; } // If another search happened after this one, throw away these options. if (_currentQuery != query) { return null; } _currentQuery = null; return options; } @override void initState() { super.initState(); _debouncedSearch = _debounce<Iterable<String>?, String>(_search); } @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( _networkEnabled ? 'Network is on, toggle to induce network errors.' : 'Network is off, toggle to allow requests to go through.', ), Switch( value: _networkEnabled, onChanged: (bool? value) { setState(() { _networkEnabled = !_networkEnabled; }); }, ), const SizedBox( height: 32.0, ), Autocomplete<String>( fieldViewBuilder: (BuildContext context, TextEditingController controller, FocusNode focusNode, VoidCallback onFieldSubmitted) { return TextFormField( decoration: InputDecoration( errorText: _networkError ? 'Network error, please try again.' : null, ), controller: controller, focusNode: focusNode, onFieldSubmitted: (String value) { onFieldSubmitted(); }, ); }, optionsBuilder: (TextEditingValue textEditingValue) async { setState(() { _networkError = false; }); final Iterable<String>? options = await _debouncedSearch(textEditingValue.text); if (options == null) { return _lastOptions; } _lastOptions = options; return options; }, onSelected: (String selection) { debugPrint('You just selected $selection'); }, ), ], ); } } // Mimics a remote API. class _FakeAPI { static const List<String> _kOptions = <String>[ 'aardvark', 'bobcat', 'chameleon', ]; // Searches the options, but injects a fake "network" delay. static Future<Iterable<String>> search(String query, bool networkEnabled) async { await Future<void>.delayed(fakeAPIDuration); // Fake 1 second delay. if (!networkEnabled) { throw const _NetworkException(); } if (query == '') { return const Iterable<String>.empty(); } return _kOptions.where((String option) { return option.contains(query.toLowerCase()); }); } } typedef _Debounceable<S, T> = Future<S?> Function(T parameter); /// Returns a new function that is a debounced version of the given function. /// /// This means that the original function will be called only after no calls /// have been made for the given Duration. _Debounceable<S, T> _debounce<S, T>(_Debounceable<S?, T> function) { _DebounceTimer? debounceTimer; return (T parameter) async { if (debounceTimer != null && !debounceTimer!.isCompleted) { debounceTimer!.cancel(); } debounceTimer = _DebounceTimer(); try { await debounceTimer!.future; } catch (error) { if (error is _CancelException) { return null; } rethrow; } return function(parameter); }; } // A wrapper around Timer used for debouncing. class _DebounceTimer { _DebounceTimer( ) { _timer = Timer(debounceDuration, _onComplete); } late final Timer _timer; final Completer<void> _completer = Completer<void>(); void _onComplete() { _completer.complete(); } Future<void> get future => _completer.future; bool get isCompleted => _completer.isCompleted; void cancel() { _timer.cancel(); _completer.completeError(const _CancelException()); } } // An exception indicating that the timer was canceled. class _CancelException implements Exception { const _CancelException(); } // An exception indicating that a network request has failed. class _NetworkException implements Exception { const _NetworkException(); }
flutter/examples/api/lib/material/autocomplete/autocomplete.4.dart/0
{ "file_path": "flutter/examples/api/lib/material/autocomplete/autocomplete.4.dart", "repo_id": "flutter", "token_count": 2527 }
563
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for M3 [Checkbox] with error state. void main() => runApp(const CheckboxExampleApp()); class CheckboxExampleApp extends StatelessWidget { const CheckboxExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(useMaterial3: true, colorSchemeSeed: const Color(0xff6750a4)), title: 'Checkbox Sample', home: Scaffold( appBar: AppBar(title: const Text('Checkbox Sample')), body: const Center( child: CheckboxExample(), ), ), ); } } class CheckboxExample extends StatefulWidget { const CheckboxExample({super.key}); @override State<CheckboxExample> createState() => _CheckboxExampleState(); } class _CheckboxExampleState extends State<CheckboxExample> { bool? isChecked = true; @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Checkbox( tristate: true, value: isChecked, onChanged: (bool? value) { setState(() { isChecked = value; }); }, ), Checkbox( isError: true, tristate: true, value: isChecked, onChanged: (bool? value) { setState(() { isChecked = value; }); }, ), Checkbox( isError: true, tristate: true, value: isChecked, onChanged: null, ), ], ); } }
flutter/examples/api/lib/material/checkbox/checkbox.1.dart/0
{ "file_path": "flutter/examples/api/lib/material/checkbox/checkbox.1.dart", "repo_id": "flutter", "token_count": 778 }
564
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [DataTable]. void main() => runApp(const DataTableExampleApp()); class DataTableExampleApp extends StatelessWidget { const DataTableExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('DataTable Sample')), body: const DataTableExample(), ), ); } } class DataTableExample extends StatelessWidget { const DataTableExample({super.key}); @override Widget build(BuildContext context) { return DataTable( columns: const <DataColumn>[ DataColumn( label: Expanded( child: Text( 'Name', style: TextStyle(fontStyle: FontStyle.italic), ), ), ), DataColumn( label: Expanded( child: Text( 'Age', style: TextStyle(fontStyle: FontStyle.italic), ), ), ), DataColumn( label: Expanded( child: Text( 'Role', style: TextStyle(fontStyle: FontStyle.italic), ), ), ), ], rows: const <DataRow>[ DataRow( cells: <DataCell>[ DataCell(Text('Sarah')), DataCell(Text('19')), DataCell(Text('Student')), ], ), DataRow( cells: <DataCell>[ DataCell(Text('Janine')), DataCell(Text('43')), DataCell(Text('Professor')), ], ), DataRow( cells: <DataCell>[ DataCell(Text('William')), DataCell(Text('27')), DataCell(Text('Associate Professor')), ], ), ], ); } }
flutter/examples/api/lib/material/data_table/data_table.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/data_table/data_table.0.dart", "repo_id": "flutter", "token_count": 978 }
565
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [Drawer]. void main() => runApp(const DrawerApp()); class DrawerApp extends StatelessWidget { const DrawerApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: const DrawerExample(), ); } } class DrawerExample extends StatefulWidget { const DrawerExample({super.key}); @override State<DrawerExample> createState() => _DrawerExampleState(); } class _DrawerExampleState extends State<DrawerExample> { String selectedPage = ''; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Drawer Example'), ), drawer: Drawer( child: ListView( padding: EdgeInsets.zero, children: <Widget>[ const DrawerHeader( decoration: BoxDecoration( color: Colors.blue, ), child: Text( 'Drawer Header', style: TextStyle( color: Colors.white, fontSize: 24, ), ), ), ListTile( leading: const Icon(Icons.message), title: const Text('Messages'), onTap: () { setState(() { selectedPage = 'Messages'; }); }, ), ListTile( leading: const Icon(Icons.account_circle), title: const Text('Profile'), onTap: () { setState(() { selectedPage = 'Profile'; }); }, ), ListTile( leading: const Icon(Icons.settings), title: const Text('Settings'), onTap: () { setState(() { selectedPage = 'Settings'; }); }, ), ], ), ), body: Center( child: Text('Page: $selectedPage'), ), ); } }
flutter/examples/api/lib/material/drawer/drawer.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/drawer/drawer.0.dart", "repo_id": "flutter", "token_count": 1165 }
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'; /// Flutter code sample for [FloatingActionButton]. void main() { runApp(const FloatingActionButtonExampleApp()); } class FloatingActionButtonExampleApp extends StatelessWidget { const FloatingActionButtonExampleApp({ super.key }); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: const FloatingActionButtonExample(), ); } } class FloatingActionButtonExample extends StatefulWidget { const FloatingActionButtonExample({ super.key }); @override State<FloatingActionButtonExample> createState() => _FloatingActionButtonExampleState(); } class _FloatingActionButtonExampleState extends State<FloatingActionButtonExample> { // The FAB's foregroundColor, backgroundColor, and shape static const List<(Color?, Color? background, ShapeBorder?)> customizations = <(Color?, Color?, ShapeBorder?)>[ (null, null, null), // The FAB uses its default for null parameters. (null, Colors.green, null), (Colors.white, Colors.green, null), (Colors.white, Colors.green, CircleBorder()), ]; int index = 0; // Selects the customization. @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('FloatingActionButton Sample'), ), body: const Center(child: Text('Press the button below!')), floatingActionButton: FloatingActionButton( onPressed: () { setState(() { index = (index + 1) % customizations.length; }); }, foregroundColor: customizations[index].$1, backgroundColor: customizations[index].$2, shape: customizations[index].$3, child: const Icon(Icons.navigation), ), ); } }
flutter/examples/api/lib/material/floating_action_button/floating_action_button.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/floating_action_button/floating_action_button.0.dart", "repo_id": "flutter", "token_count": 648 }
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'; /// Flutter code sample for [ListTile]. void main() => runApp(const ListTileApp()); class ListTileApp extends StatelessWidget { const ListTileApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: const ListTileExample(), ); } } class ListTileExample extends StatefulWidget { const ListTileExample({super.key}); @override State<ListTileExample> createState() => _ListTileExampleState(); } class _ListTileExampleState extends State<ListTileExample> { bool _selected = false; bool _enabled = true; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('ListTile Sample')), body: Center( child: ListTile( enabled: _enabled, selected: _selected, onTap: () { setState(() { // This is called when the user toggles the switch. _selected = !_selected; }); }, // This sets text color and icon color to red when list tile is disabled and // green when list tile is selected, otherwise sets it to black. iconColor: MaterialStateColor.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return Colors.red; } if (states.contains(MaterialState.selected)) { return Colors.green; } return Colors.black; }), // This sets text color and icon color to red when list tile is disabled and // green when list tile is selected, otherwise sets it to black. textColor: MaterialStateColor.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return Colors.red; } if (states.contains(MaterialState.selected)) { return Colors.green; } return Colors.black; }), leading: const Icon(Icons.person), title: const Text('Headline'), subtitle: Text('Enabled: $_enabled, Selected: $_selected'), trailing: Switch( onChanged: (bool? value) { // This is called when the user toggles the switch. setState(() { _enabled = value!; }); }, value: _enabled, ), ), ), ); } }
flutter/examples/api/lib/material/list_tile/list_tile.3.dart/0
{ "file_path": "flutter/examples/api/lib/material/list_tile/list_tile.3.dart", "repo_id": "flutter", "token_count": 1139 }
568
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [NavigationBar] with nested [Navigator] destinations. void main() { runApp(const MaterialApp(home: Home())); } class Home extends StatefulWidget { const Home({super.key}); @override State<Home> createState() => _HomeState(); } class _HomeState extends State<Home> with TickerProviderStateMixin<Home> { static const List<Destination> allDestinations = <Destination>[ Destination(0, 'Teal', Icons.home, Colors.teal), Destination(1, 'Cyan', Icons.business, Colors.cyan), Destination(2, 'Orange', Icons.school, Colors.orange), Destination(3, 'Blue', Icons.flight, Colors.blue), ]; late final List<GlobalKey<NavigatorState>> navigatorKeys; late final List<GlobalKey> destinationKeys; late final List<AnimationController> destinationFaders; late final List<Widget> destinationViews; int selectedIndex = 0; AnimationController buildFaderController() { final AnimationController controller = AnimationController( vsync: this, duration: const Duration(milliseconds: 300), ); controller.addStatusListener( (AnimationStatus status) { if (status == AnimationStatus.dismissed) { setState(() {}); // Rebuild unselected destinations offstage. } }, ); return controller; } @override void initState() { super.initState(); navigatorKeys = List<GlobalKey<NavigatorState>>.generate( allDestinations.length, (int index) => GlobalKey(), ).toList(); destinationFaders = List<AnimationController>.generate( allDestinations.length, (int index) => buildFaderController(), ).toList(); destinationFaders[selectedIndex].value = 1.0; final CurveTween tween = CurveTween(curve: Curves.fastOutSlowIn); destinationViews = allDestinations.map<Widget>( (Destination destination) { return FadeTransition( opacity: destinationFaders[destination.index].drive(tween), child: DestinationView( destination: destination, navigatorKey: navigatorKeys[destination.index], ), ); }, ).toList(); } @override void dispose() { for (final AnimationController controller in destinationFaders) { controller.dispose(); } super.dispose(); } @override Widget build(BuildContext context) { return NavigatorPopHandler( onPop: () { final NavigatorState navigator = navigatorKeys[selectedIndex].currentState!; navigator.pop(); }, child: Scaffold( body: SafeArea( top: false, child: Stack( fit: StackFit.expand, children: allDestinations.map( (Destination destination) { final int index = destination.index; final Widget view = destinationViews[index]; if (index == selectedIndex) { destinationFaders[index].forward(); return Offstage(offstage: false, child: view); } else { destinationFaders[index].reverse(); if (destinationFaders[index].isAnimating) { return IgnorePointer(child: view); } return Offstage(child: view); } }, ).toList(), ), ), bottomNavigationBar: NavigationBar( selectedIndex: selectedIndex, onDestinationSelected: (int index) { setState(() { selectedIndex = index; }); }, destinations: allDestinations.map<NavigationDestination>( (Destination destination) { return NavigationDestination( icon: Icon(destination.icon, color: destination.color), label: destination.title, ); }, ).toList(), ), ), ); } } class Destination { const Destination(this.index, this.title, this.icon, this.color); final int index; final String title; final IconData icon; final MaterialColor color; } class RootPage extends StatelessWidget { const RootPage({super.key, required this.destination}); final Destination destination; Widget _buildDialog(BuildContext context) { return AlertDialog( title: Text('${destination.title} AlertDialog'), actions: <Widget>[ TextButton( onPressed: () { Navigator.pop(context); }, child: const Text('OK'), ), ], ); } @override Widget build(BuildContext context) { final TextStyle headlineSmall = Theme.of(context).textTheme.headlineSmall!; final ButtonStyle buttonStyle = ElevatedButton.styleFrom( backgroundColor: destination.color, foregroundColor: Colors.white, visualDensity: VisualDensity.comfortable, padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16), textStyle: headlineSmall, ); return Scaffold( appBar: AppBar( title: Text('${destination.title} RootPage - /'), backgroundColor: destination.color, foregroundColor: Colors.white, ), backgroundColor: destination.color[50], body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ ElevatedButton( style: buttonStyle, onPressed: () { Navigator.pushNamed(context, '/list'); }, child: const Text('Push /list'), ), const SizedBox(height: 16), ElevatedButton( style: buttonStyle, onPressed: () { showDialog<void>( context: context, useRootNavigator: false, builder: _buildDialog, ); }, child: const Text('Local Dialog'), ), const SizedBox(height: 16), ElevatedButton( style: buttonStyle, onPressed: () { showDialog<void>( context: context, useRootNavigator: true, // ignore: avoid_redundant_argument_values builder: _buildDialog, ); }, child: const Text('Root Dialog'), ), const SizedBox(height: 16), Builder( builder: (BuildContext context) { return ElevatedButton( style: buttonStyle, onPressed: () { showBottomSheet( context: context, builder: (BuildContext context) { return Container( padding: const EdgeInsets.all(16), width: double.infinity, child: Text( '${destination.title} BottomSheet\n' 'Tap the back button to dismiss', style: headlineSmall, softWrap: true, textAlign: TextAlign.center, ), ); }, ); }, child: const Text('Local BottomSheet'), ); }, ), ], ), ), ); } } class ListPage extends StatelessWidget { const ListPage({super.key, required this.destination}); final Destination destination; @override Widget build(BuildContext context) { const int itemCount = 50; final ColorScheme colorScheme = Theme.of(context).colorScheme; final ButtonStyle buttonStyle = OutlinedButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), side: BorderSide( color: colorScheme.onSurface.withOpacity(0.12), ), ), foregroundColor: destination.color, fixedSize: const Size.fromHeight(64), textStyle: Theme.of(context).textTheme.headlineSmall, ); return Scaffold( appBar: AppBar( title: Text('${destination.title} ListPage - /list'), backgroundColor: destination.color, foregroundColor: Colors.white, ), backgroundColor: destination.color[50], body: SizedBox.expand( child: ListView.builder( itemCount: itemCount, itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8), child: OutlinedButton( style: buttonStyle.copyWith( backgroundColor: MaterialStatePropertyAll<Color>( Color.lerp( destination.color[100], Colors.white, index / itemCount )!, ), ), onPressed: () { Navigator.pushNamed(context, '/text'); }, child: Text('Push /text [$index]'), ), ); }, ), ), ); } } class TextPage extends StatefulWidget { const TextPage({super.key, required this.destination}); final Destination destination; @override State<TextPage> createState() => _TextPageState(); } class _TextPageState extends State<TextPage> { late final TextEditingController textController; @override void initState() { super.initState(); textController = TextEditingController(text: 'Sample Text'); } @override void dispose() { textController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); return Scaffold( appBar: AppBar( title: Text('${widget.destination.title} TextPage - /list/text'), backgroundColor: widget.destination.color, foregroundColor: Colors.white, ), backgroundColor: widget.destination.color[50], body: Container( padding: const EdgeInsets.all(32.0), alignment: Alignment.center, child: TextField( controller: textController, style: theme.primaryTextTheme.headlineMedium?.copyWith( color: widget.destination.color, ), decoration: InputDecoration( focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: widget.destination.color, width: 3.0, ), ), ), ), ), ); } } class DestinationView extends StatefulWidget { const DestinationView({ super.key, required this.destination, required this.navigatorKey, }); final Destination destination; final Key navigatorKey; @override State<DestinationView> createState() => _DestinationViewState(); } class _DestinationViewState extends State<DestinationView> { @override Widget build(BuildContext context) { return Navigator( key: widget.navigatorKey, onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<void>( settings: settings, builder: (BuildContext context) { switch (settings.name) { case '/': return RootPage(destination: widget.destination); case '/list': return ListPage(destination: widget.destination); case '/text': return TextPage(destination: widget.destination); } assert(false); return const SizedBox(); }, ); }, ); } }
flutter/examples/api/lib/material/navigation_bar/navigation_bar.2.dart/0
{ "file_path": "flutter/examples/api/lib/material/navigation_bar/navigation_bar.2.dart", "repo_id": "flutter", "token_count": 5496 }
569
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [Scrollbar]. void main() => runApp(const ScrollbarExampleApp()); class ScrollbarExampleApp extends StatelessWidget { const ScrollbarExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Scrollbar Sample')), body: const ScrollbarExample(), ), ); } } class ScrollbarExample extends StatelessWidget { const ScrollbarExample({super.key}); @override Widget build(BuildContext context) { return Scrollbar( child: GridView.builder( primary: true, itemCount: 120, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3), itemBuilder: (BuildContext context, int index) { return Center( child: Text('item $index'), ); }, ), ); } }
flutter/examples/api/lib/material/scrollbar/scrollbar.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/scrollbar/scrollbar.0.dart", "repo_id": "flutter", "token_count": 404 }
570
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [Slider]. void main() => runApp(const SliderApp()); class SliderApp extends StatelessWidget { const SliderApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: SliderExample(), ); } } class SliderExample extends StatefulWidget { const SliderExample({super.key}); @override State<SliderExample> createState() => _SliderExampleState(); } class _SliderExampleState extends State<SliderExample> { double _currentSliderPrimaryValue = 0.2; double _currentSliderSecondaryValue = 0.5; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Slider')), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Slider( value: _currentSliderPrimaryValue, secondaryTrackValue: _currentSliderSecondaryValue, label: _currentSliderPrimaryValue.round().toString(), onChanged: (double value) { setState(() { _currentSliderPrimaryValue = value; }); }, ), Slider( value: _currentSliderSecondaryValue, label: _currentSliderSecondaryValue.round().toString(), onChanged: (double value) { setState(() { _currentSliderSecondaryValue = value; }); }, ), ], ), ); } }
flutter/examples/api/lib/material/slider/slider.2.dart/0
{ "file_path": "flutter/examples/api/lib/material/slider/slider.2.dart", "repo_id": "flutter", "token_count": 712 }
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 'package:flutter/material.dart'; /// Flutter code sample for [TabController]. void main() => runApp(const TabControllerExampleApp()); class TabControllerExampleApp extends StatelessWidget { const TabControllerExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: TabControllerExample(), ); } } const List<Tab> tabs = <Tab>[ Tab(text: 'Zeroth'), Tab(text: 'First'), Tab(text: 'Second'), ]; class TabControllerExample extends StatelessWidget { const TabControllerExample({super.key}); @override Widget build(BuildContext context) { return DefaultTabController( length: tabs.length, // The Builder widget is used to have a different BuildContext to access // closest DefaultTabController. child: Builder(builder: (BuildContext context) { final TabController tabController = DefaultTabController.of(context); tabController.addListener(() { if (!tabController.indexIsChanging) { // Your code goes here. // To get index of current tab use tabController.index } }); return Scaffold( appBar: AppBar( bottom: const TabBar( tabs: tabs, ), ), body: TabBarView( children: tabs.map((Tab tab) { return Center( child: Text( '${tab.text!} Tab', style: Theme.of(context).textTheme.headlineSmall, ), ); }).toList(), ), ); }), ); } }
flutter/examples/api/lib/material/tab_controller/tab_controller.1.dart/0
{ "file_path": "flutter/examples/api/lib/material/tab_controller/tab_controller.1.dart", "repo_id": "flutter", "token_count": 736 }
572
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [Tooltip]. void main() => runApp(const TooltipExampleApp()); class TooltipExampleApp extends StatelessWidget { const TooltipExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(tooltipTheme: const TooltipThemeData(preferBelow: false)), home: Scaffold( appBar: AppBar(title: const Text('Tooltip Sample')), body: const Center( child: TooltipSample(), ), ), ); } } class TooltipSample extends StatelessWidget { const TooltipSample({super.key}); @override Widget build(BuildContext context) { return Tooltip( message: 'I am a Tooltip', decoration: BoxDecoration( borderRadius: BorderRadius.circular(25), gradient: const LinearGradient(colors: <Color>[Colors.amber, Colors.red]), ), height: 50, padding: const EdgeInsets.all(8.0), preferBelow: true, textStyle: const TextStyle( fontSize: 24, ), showDuration: const Duration(seconds: 2), waitDuration: const Duration(seconds: 1), child: const Text('Tap this text and hold down to show a tooltip.'), ); } }
flutter/examples/api/lib/material/tooltip/tooltip.1.dart/0
{ "file_path": "flutter/examples/api/lib/material/tooltip/tooltip.1.dart", "repo_id": "flutter", "token_count": 517 }
573
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/material.dart'; /// Flutter code sample for [StreamBuilder]. void main() => runApp(const StreamBuilderExampleApp()); class StreamBuilderExampleApp extends StatelessWidget { const StreamBuilderExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: StreamBuilderExample(), ); } } class StreamBuilderExample extends StatefulWidget { const StreamBuilderExample({super.key}); @override State<StreamBuilderExample> createState() => _StreamBuilderExampleState(); } class _StreamBuilderExampleState extends State<StreamBuilderExample> { final Stream<int> _bids = (() { late final StreamController<int> controller; controller = StreamController<int>( onListen: () async { await Future<void>.delayed(const Duration(seconds: 1)); controller.add(1); await Future<void>.delayed(const Duration(seconds: 1)); await controller.close(); }, ); return controller.stream; })(); @override Widget build(BuildContext context) { return DefaultTextStyle( style: Theme.of(context).textTheme.displayMedium!, textAlign: TextAlign.center, child: Container( alignment: FractionalOffset.center, color: Colors.white, child: StreamBuilder<int>( stream: _bids, builder: (BuildContext context, AsyncSnapshot<int> snapshot) { List<Widget> children; if (snapshot.hasError) { children = <Widget>[ const Icon( Icons.error_outline, color: Colors.red, size: 60, ), Padding( padding: const EdgeInsets.only(top: 16), child: Text('Error: ${snapshot.error}'), ), Padding( padding: const EdgeInsets.only(top: 8), child: Text('Stack trace: ${snapshot.stackTrace}'), ), ]; } else { switch (snapshot.connectionState) { case ConnectionState.none: children = const <Widget>[ Icon( Icons.info, color: Colors.blue, size: 60, ), Padding( padding: EdgeInsets.only(top: 16), child: Text('Select a lot'), ), ]; case ConnectionState.waiting: children = const <Widget>[ SizedBox( width: 60, height: 60, child: CircularProgressIndicator(), ), Padding( padding: EdgeInsets.only(top: 16), child: Text('Awaiting bids...'), ), ]; case ConnectionState.active: children = <Widget>[ const Icon( Icons.check_circle_outline, color: Colors.green, size: 60, ), Padding( padding: const EdgeInsets.only(top: 16), child: Text('\$${snapshot.data}'), ), ]; case ConnectionState.done: children = <Widget>[ const Icon( Icons.info, color: Colors.blue, size: 60, ), Padding( padding: const EdgeInsets.only(top: 16), child: Text('\$${snapshot.data} (closed)'), ), ]; } } return Column( mainAxisAlignment: MainAxisAlignment.center, children: children, ); }, ), ), ); } }
flutter/examples/api/lib/widgets/async/stream_builder.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/async/stream_builder.0.dart", "repo_id": "flutter", "token_count": 2306 }
574
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [Flow]. void main() => runApp(const FlowApp()); class FlowApp extends StatelessWidget { const FlowApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Flow Example'), ), body: const FlowMenu(), ), ); } } class FlowMenu extends StatefulWidget { const FlowMenu({super.key}); @override State<FlowMenu> createState() => _FlowMenuState(); } class _FlowMenuState extends State<FlowMenu> with SingleTickerProviderStateMixin { late AnimationController menuAnimation; IconData lastTapped = Icons.notifications; final List<IconData> menuItems = <IconData>[ Icons.home, Icons.new_releases, Icons.notifications, Icons.settings, Icons.menu, ]; void _updateMenu(IconData icon) { if (icon != Icons.menu) { setState(() => lastTapped = icon); } } @override void initState() { super.initState(); menuAnimation = AnimationController( duration: const Duration(milliseconds: 250), vsync: this, ); } Widget flowMenuItem(IconData icon) { final double buttonDiameter = MediaQuery.of(context).size.width / menuItems.length; return Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: RawMaterialButton( fillColor: lastTapped == icon ? Colors.amber[700] : Colors.blue, splashColor: Colors.amber[100], shape: const CircleBorder(), constraints: BoxConstraints.tight(Size(buttonDiameter, buttonDiameter)), onPressed: () { _updateMenu(icon); menuAnimation.status == AnimationStatus.completed ? menuAnimation.reverse() : menuAnimation.forward(); }, child: Icon( icon, color: Colors.white, size: 45.0, ), ), ); } @override Widget build(BuildContext context) { return Flow( delegate: FlowMenuDelegate(menuAnimation: menuAnimation), children: menuItems.map<Widget>((IconData icon) => flowMenuItem(icon)).toList(), ); } } class FlowMenuDelegate extends FlowDelegate { FlowMenuDelegate({required this.menuAnimation}) : super(repaint: menuAnimation); final Animation<double> menuAnimation; @override bool shouldRepaint(FlowMenuDelegate oldDelegate) { return menuAnimation != oldDelegate.menuAnimation; } @override void paintChildren(FlowPaintingContext context) { double dx = 0.0; for (int i = 0; i < context.childCount; ++i) { dx = context.getChildSize(i)!.width * i; context.paintChild( i, transform: Matrix4.translationValues( dx * menuAnimation.value, 0, 0, ), ); } } }
flutter/examples/api/lib/widgets/basic/flow.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/basic/flow.0.dart", "repo_id": "flutter", "token_count": 1141 }
575
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [EditableText.onChanged]. void main() => runApp(const OnChangedExampleApp()); class OnChangedExampleApp extends StatelessWidget { const OnChangedExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: OnChangedExample(), ); } } class OnChangedExample extends StatefulWidget { const OnChangedExample({super.key}); @override State<OnChangedExample> createState() => _OnChangedExampleState(); } class _OnChangedExampleState extends State<OnChangedExample> { final TextEditingController _controller = TextEditingController(); @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text('What number comes next in the sequence?'), const Text('1, 1, 2, 3, 5, 8...?'), TextField( controller: _controller, onChanged: (String value) async { if (value != '13') { return; } await showDialog<void>( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('That is correct!'), content: const Text('13 is the right answer.'), actions: <Widget>[ TextButton( onPressed: () { Navigator.pop(context); }, child: const Text('OK'), ), ], ); }, ); }, ), ], ), ); } }
flutter/examples/api/lib/widgets/editable_text/editable_text.on_changed.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/editable_text/editable_text.on_changed.0.dart", "repo_id": "flutter", "token_count": 955 }
576
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [GestureDetector]. void main() => runApp(const GestureDetectorExampleApp()); class GestureDetectorExampleApp extends StatelessWidget { const GestureDetectorExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: GestureDetectorExample(), ); } } class GestureDetectorExample extends StatefulWidget { const GestureDetectorExample({super.key}); @override State<GestureDetectorExample> createState() => _GestureDetectorExampleState(); } class _GestureDetectorExampleState extends State<GestureDetectorExample> { bool _lightIsOn = false; @override Widget build(BuildContext context) { return Scaffold( body: Container( alignment: FractionalOffset.center, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: Icon( Icons.lightbulb_outline, color: _lightIsOn ? Colors.yellow.shade600 : Colors.black, size: 60, ), ), GestureDetector( onTap: () { setState(() { // Toggle light when tapped. _lightIsOn = !_lightIsOn; }); }, child: Container( color: Colors.yellow.shade600, padding: const EdgeInsets.all(8), // Change button text when light changes state. child: Text(_lightIsOn ? 'TURN LIGHT OFF' : 'TURN LIGHT ON'), ), ), ], ), ), ); } }
flutter/examples/api/lib/widgets/gesture_detector/gesture_detector.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/gesture_detector/gesture_detector.0.dart", "repo_id": "flutter", "token_count": 867 }
577
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [InheritedModel]. enum LogoAspect { backgroundColor, large } void main() => runApp(const InheritedModelApp()); class InheritedModelApp extends StatelessWidget { const InheritedModelApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: InheritedModelExample(), ); } } class LogoModel extends InheritedModel<LogoAspect> { const LogoModel({ super.key, this.backgroundColor, this.large, required super.child, }); final Color? backgroundColor; final bool? large; static Color? backgroundColorOf(BuildContext context) { return InheritedModel.inheritFrom<LogoModel>(context, aspect: LogoAspect.backgroundColor)?.backgroundColor; } static bool sizeOf(BuildContext context) { return InheritedModel.inheritFrom<LogoModel>(context, aspect: LogoAspect.large)?.large ?? false; } @override bool updateShouldNotify(LogoModel oldWidget) { return backgroundColor != oldWidget.backgroundColor || large != oldWidget.large; } @override bool updateShouldNotifyDependent(LogoModel oldWidget, Set<LogoAspect> dependencies) { if (backgroundColor != oldWidget.backgroundColor && dependencies.contains(LogoAspect.backgroundColor)) { return true; } if (large != oldWidget.large && dependencies.contains(LogoAspect.large)) { return true; } return false; } } class InheritedModelExample extends StatefulWidget { const InheritedModelExample({super.key}); @override State<InheritedModelExample> createState() => _InheritedModelExampleState(); } class _InheritedModelExampleState extends State<InheritedModelExample> { bool large = false; Color color = Colors.blue; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('InheritedModel Sample')), body: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Center( child: LogoModel( backgroundColor: color, large: large, child: const BackgroundWidget( child: LogoWidget(), ), ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ ElevatedButton( onPressed: () { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Rebuilt Background'), duration: Duration(milliseconds: 500), ), ); setState(() { if (color == Colors.blue) { color = Colors.red; } else { color = Colors.blue; } }); }, child: const Text('Update background'), ), ElevatedButton( onPressed: () { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Rebuilt LogoWidget'), duration: Duration(milliseconds: 500), ), ); setState(() { large = !large; }); }, child: const Text('Resize Logo'), ), ], ) ], ), ); } } class BackgroundWidget extends StatelessWidget { const BackgroundWidget({super.key, required this.child}); final Widget child; @override Widget build(BuildContext context) { final Color color = LogoModel.backgroundColorOf(context)!; return AnimatedContainer( padding: const EdgeInsets.all(12.0), color: color, duration: const Duration(seconds: 2), curve: Curves.fastOutSlowIn, child: child, ); } } class LogoWidget extends StatelessWidget { const LogoWidget({super.key}); @override Widget build(BuildContext context) { final bool largeLogo = LogoModel.sizeOf(context); return AnimatedContainer( padding: const EdgeInsets.all(20.0), duration: const Duration(seconds: 2), curve: Curves.fastLinearToSlowEaseIn, alignment: Alignment.center, child: FlutterLogo(size: largeLogo ? 200.0 : 100.0), ); } }
flutter/examples/api/lib/widgets/inherited_model/inherited_model.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/inherited_model/inherited_model.0.dart", "repo_id": "flutter", "token_count": 2020 }
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'; /// Flutter code sample for a [PageView] using the `findChildIndexCallback` argument. void main() => runApp(const PageViewExampleApp()); class PageViewExampleApp extends StatelessWidget { const PageViewExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(home: PageViewExample()); } } class PageViewExample extends StatefulWidget { const PageViewExample({super.key}); @override State<PageViewExample> createState() => _PageViewExampleState(); } class _PageViewExampleState extends State<PageViewExample> { List<String> items = <String>['1', '2', '3', '4', '5']; void _reverse() { setState(() { items = items.reversed.toList(); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('PageView Sample')), body: SafeArea( child: PageView.custom( childrenDelegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return KeepAliveItem( data: items[index], key: ValueKey<String>(items[index]), ); }, childCount: items.length, findChildIndexCallback: (Key key) { final ValueKey<String> valueKey = key as ValueKey<String>; final String data = valueKey.value; final int index = items.indexOf(data); if (index >= 0) { return index; } return null; }, ), ), ), bottomNavigationBar: BottomAppBar( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextButton( onPressed: () => _reverse(), child: const Text('Reverse items'), ), ], ), ), ); } } class KeepAliveItem extends StatefulWidget { const KeepAliveItem({super.key, required this.data}); final String data; @override State<KeepAliveItem> createState() => _KeepAliveItemState(); } class _KeepAliveItemState extends State<KeepAliveItem> with AutomaticKeepAliveClientMixin { @override bool get wantKeepAlive => true; @override Widget build(BuildContext context) { super.build(context); return Text(widget.data); } }
flutter/examples/api/lib/widgets/page_view/page_view.1.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/page_view/page_view.1.dart", "repo_id": "flutter", "token_count": 1055 }
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'; /// Flutter code sample for [RawScrollbar]. void main() => runApp(const RawScrollbarExampleApp()); class RawScrollbarExampleApp extends StatelessWidget { const RawScrollbarExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('RawScrollbar Sample')), body: const Center( child: RawScrollbarExample(), ), ), ); } } class RawScrollbarExample extends StatefulWidget { const RawScrollbarExample({super.key}); @override State<RawScrollbarExample> createState() => _RawScrollbarExampleState(); } class _RawScrollbarExampleState extends State<RawScrollbarExample> { final ScrollController _firstController = ScrollController(); @override Widget build(BuildContext context) { return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { return Row( children: <Widget>[ SizedBox( width: constraints.maxWidth / 2, // When using the PrimaryScrollController and a Scrollbar // together, only one ScrollPosition can be attached to the // PrimaryScrollController at a time. Providing a // unique scroll controller to this scroll view prevents it // from attaching to the PrimaryScrollController. child: Scrollbar( thumbVisibility: true, controller: _firstController, child: ListView.builder( controller: _firstController, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.all(8.0), child: Text('Scrollable 1 : Index $index'), ); }), )), SizedBox( width: constraints.maxWidth / 2, // This vertical scroll view has primary set to true, so it is // using the PrimaryScrollController. On mobile platforms, the // PrimaryScrollController automatically attaches to vertical // ScrollViews, unlike on Desktop platforms, where the primary // parameter is required. child: Scrollbar( thumbVisibility: true, child: ListView.builder( primary: true, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Container( height: 50, color: index.isEven ? Colors.amberAccent : Colors.blueAccent, child: Padding( padding: const EdgeInsets.all(8.0), child: Text('Scrollable 2 : Index $index'), )); }), )), ], ); }); } }
flutter/examples/api/lib/widgets/scrollbar/raw_scrollbar.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/scrollbar/raw_scrollbar.0.dart", "repo_id": "flutter", "token_count": 1464 }
580
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; void main() => runApp(const SliverConstrainedCrossAxisExampleApp()); class SliverConstrainedCrossAxisExampleApp extends StatelessWidget { const SliverConstrainedCrossAxisExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('SliverConstrainedCrossAxis Sample')), body: const SliverConstrainedCrossAxisExample(), ), ); } } class SliverConstrainedCrossAxisExample extends StatelessWidget { const SliverConstrainedCrossAxisExample({super.key}); @override Widget build(BuildContext context) { return CustomScrollView( slivers: <Widget>[ SliverConstrainedCrossAxis( maxExtent: 200, sliver: SliverList.builder( itemBuilder: (BuildContext context, int index) { return Container( color: index.isEven ? Colors.amber[300] : Colors.blue[300], height: 100.0, child: Center( child: Text( 'Item $index', style: const TextStyle(fontSize: 24), ), ), ); }, itemCount: 10, ), ), ], ); } }
flutter/examples/api/lib/widgets/sliver/sliver_constrained_cross_axis.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/sliver/sliver_constrained_cross_axis.0.dart", "repo_id": "flutter", "token_count": 654 }
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'; /// Flutter code sample for [DecoratedBoxTransition]. void main() => runApp(const DecoratedBoxTransitionExampleApp()); class DecoratedBoxTransitionExampleApp extends StatelessWidget { const DecoratedBoxTransitionExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: DecoratedBoxTransitionExample(), ); } } class DecoratedBoxTransitionExample extends StatefulWidget { const DecoratedBoxTransitionExample({super.key}); @override State<DecoratedBoxTransitionExample> createState() => _DecoratedBoxTransitionExampleState(); } /// [AnimationController]s can be created with `vsync: this` because of /// [TickerProviderStateMixin]. class _DecoratedBoxTransitionExampleState extends State<DecoratedBoxTransitionExample> with TickerProviderStateMixin { final DecorationTween decorationTween = DecorationTween( begin: BoxDecoration( color: const Color(0xFFFFFFFF), border: Border.all(style: BorderStyle.none), borderRadius: BorderRadius.circular(60.0), boxShadow: const <BoxShadow>[ BoxShadow( color: Color(0x66666666), blurRadius: 10.0, spreadRadius: 3.0, offset: Offset(0, 6.0), ), ], ), end: BoxDecoration( color: const Color(0xFFFFFFFF), border: Border.all( style: BorderStyle.none, ), borderRadius: BorderRadius.zero, // No shadow. ), ); late final AnimationController _controller = AnimationController( vsync: this, duration: const Duration(seconds: 3), )..repeat(reverse: true); @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return ColoredBox( color: Colors.white, child: Center( child: DecoratedBoxTransition( decoration: decorationTween.animate(_controller), child: Container( width: 200, height: 200, padding: const EdgeInsets.all(10), child: const FlutterLogo(), ), ), ), ); } }
flutter/examples/api/lib/widgets/transitions/decorated_box_transition.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/transitions/decorated_box_transition.0.dart", "repo_id": "flutter", "token_count": 880 }
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'; /// Flutter code sample for [UndoHistoryController]. void main() { runApp(const UndoHistoryControllerExampleApp()); } class UndoHistoryControllerExampleApp extends StatelessWidget { const UndoHistoryControllerExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { final TextEditingController _controller = TextEditingController(); final FocusNode _focusNode = FocusNode(); final UndoHistoryController _undoController = UndoHistoryController(); TextStyle? get enabledStyle => Theme.of(context).textTheme.bodyMedium; TextStyle? get disabledStyle => Theme.of(context).textTheme.bodyMedium?.copyWith(color: Colors.grey); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextField( maxLines: 4, controller: _controller, focusNode: _focusNode, undoController: _undoController, ), ValueListenableBuilder<UndoHistoryValue>( valueListenable: _undoController, builder: (BuildContext context, UndoHistoryValue value, Widget? child) { return Row( children: <Widget>[ TextButton( child: Text('Undo', style: value.canUndo ? enabledStyle : disabledStyle), onPressed: () { _undoController.undo(); }, ), TextButton( child: Text('Redo', style: value.canRedo ? enabledStyle : disabledStyle), onPressed: () { _undoController.redo(); }, ), ], ); }, ), ], ), ), ); } }
flutter/examples/api/lib/widgets/undo_history/undo_history_controller.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/undo_history/undo_history_controller.0.dart", "repo_id": "flutter", "token_count": 1074 }
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/cupertino.dart'; import 'package:flutter_api_samples/cupertino/switch/cupertino_switch.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Toggling cupertino switch updates icon', (WidgetTester tester) async { await tester.pumpWidget( const example.CupertinoSwitchApp(), ); final Finder switchFinder = find.byType(CupertinoSwitch); CupertinoSwitch cupertinoSwitch = tester.widget<CupertinoSwitch>(switchFinder); expect(cupertinoSwitch.value, true); await tester.tap(switchFinder); await tester.pumpAndSettle(); cupertinoSwitch = tester.widget<CupertinoSwitch>(switchFinder); expect(cupertinoSwitch.value, false); }); }
flutter/examples/api/test/cupertino/switch/cupertino_switch.0_test.dart/0
{ "file_path": "flutter/examples/api/test/cupertino/switch/cupertino_switch.0_test.dart", "repo_id": "flutter", "token_count": 305 }
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/material.dart'; import 'package:flutter_api_samples/material/app_bar/app_bar.2.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Appbar and actions', (WidgetTester tester) async { await tester.pumpWidget( const example.AppBarApp(), ); expect(find.byType(AppBar), findsOneWidget); expect(find.widgetWithText(TextButton, 'Action 1'), findsOneWidget); expect(find.widgetWithText(TextButton, 'Action 2'), findsOneWidget); }); }
flutter/examples/api/test/material/app_bar/app_bar.2_test.dart/0
{ "file_path": "flutter/examples/api/test/material/app_bar/app_bar.2_test.dart", "repo_id": "flutter", "token_count": 230 }
585
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_api_samples/material/card/card.1.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Card has clip applied', (WidgetTester tester) async { await tester.pumpWidget(const example.CardExampleApp()); final Card card = tester.firstWidget(find.byType(Card)); expect(card.clipBehavior, Clip.hardEdge); }); }
flutter/examples/api/test/material/card/card.1_test.dart/0
{ "file_path": "flutter/examples/api/test/material/card/card.1_test.dart", "repo_id": "flutter", "token_count": 189 }
586
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_api_samples/material/context_menu/selectable_region_toolbar_builder.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('showing and hiding the custom context menu on SelectionArea', (WidgetTester tester) async { await tester.pumpWidget( const example.SelectableRegionToolbarBuilderExampleApp(), ); expect(BrowserContextMenu.enabled, !kIsWeb); // Allow the selection overlay geometry to be created. await tester.pumpAndSettle(); expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); // Right clicking the Text in the SelectionArea shows the custom context // menu. final TestGesture primaryMouseButtonGesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); final TestGesture gesture = await tester.startGesture( tester.getCenter(find.text(example.text)), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); expect(find.text('Print'), findsOneWidget); // Tap to dismiss. await primaryMouseButtonGesture.down(tester.getCenter(find.byType(Scaffold))); await tester.pump(); await primaryMouseButtonGesture.up(); await tester.pumpAndSettle(); expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); }); }
flutter/examples/api/test/material/context_menu/selectable_region_toolbar_builder.0_test.dart/0
{ "file_path": "flutter/examples/api/test/material/context_menu/selectable_region_toolbar_builder.0_test.dart", "repo_id": "flutter", "token_count": 607 }
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 'package:flutter/material.dart'; import 'package:flutter_api_samples/material/divider/vertical_divider.1.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Vertical Divider', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( body: example.VerticalDividerExampleApp(), ), ), ); expect(find.byType(VerticalDivider), findsOneWidget); // Divider is positioned vertically. Offset card = tester.getTopRight(find.byType(Card).first); expect(card.dx, tester.getTopLeft(find.byType(VerticalDivider)).dx); card = tester.getTopLeft(find.byType(Card).last); expect(card.dx, tester.getTopRight(find.byType(VerticalDivider)).dx); }); }
flutter/examples/api/test/material/divider/vertical_divider.1_test.dart/0
{ "file_path": "flutter/examples/api/test/material/divider/vertical_divider.1_test.dart", "repo_id": "flutter", "token_count": 350 }
588
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_api_samples/material/floating_action_button/floating_action_button.2.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('FloatingActionButton variants', (WidgetTester tester) async { await tester.pumpWidget( const example.FloatingActionButtonExampleApp(), ); FloatingActionButton getFAB(Finder finder) { return tester.widget<FloatingActionButton>(finder); } final ColorScheme colorScheme = ThemeData(useMaterial3: true).colorScheme; // Test the FAB with surface color mapping. FloatingActionButton fab = getFAB(find.byType(FloatingActionButton).at(0)); expect(fab.foregroundColor, colorScheme.primary); expect(fab.backgroundColor, colorScheme.surface); // Test the FAB with secondary color mapping. fab = getFAB(find.byType(FloatingActionButton).at(1)); expect(fab.foregroundColor, colorScheme.onSecondaryContainer); expect(fab.backgroundColor, colorScheme.secondaryContainer); // Test the FAB with tertiary color mapping. fab = getFAB(find.byType(FloatingActionButton).at(2)); expect(fab.foregroundColor, colorScheme.onTertiaryContainer); expect(fab.backgroundColor, colorScheme.tertiaryContainer); }); }
flutter/examples/api/test/material/floating_action_button/floating_action_button.2_test.dart/0
{ "file_path": "flutter/examples/api/test/material/floating_action_button/floating_action_button.2_test.dart", "repo_id": "flutter", "token_count": 480 }
589
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_api_samples/material/list_tile/list_tile.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('ListTile with Hero does not throw', (WidgetTester tester) async { const int totalTiles = 3; await tester.pumpWidget( const example.ListTileApp(), ); expect(find.byType(ListTile), findsNWidgets(totalTiles)); const String heroTransitionText = 'Tap here for Hero transition'; const String goBackText = 'Tap here to go back'; expect(find.text(heroTransitionText), findsOneWidget); expect(find.text(goBackText), findsNothing); // Tap on the ListTile widget to trigger the Hero transition. await tester.tap(find.text(heroTransitionText)); await tester.pumpAndSettle(); // The Hero transition is triggered and tap to go back text is displayed. expect(find.text(heroTransitionText), findsNothing); expect(find.text(goBackText), findsOneWidget); expect(tester.takeException(), null); }); }
flutter/examples/api/test/material/list_tile/list_tile.0_test.dart/0
{ "file_path": "flutter/examples/api/test/material/list_tile/list_tile.0_test.dart", "repo_id": "flutter", "token_count": 394 }
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'; import 'package:flutter_api_samples/material/radio_list_tile/custom_labeled_radio.1.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Tapping LabeledRadio toggles the radio', (WidgetTester tester) async { await tester.pumpWidget( const example.LabeledRadioApp(), ); // First Radio is initially unchecked. Radio<bool> radio = tester.widget(find.byType(Radio<bool>).first); expect(radio.value, true); expect(radio.groupValue, false); // Last Radio is initially checked. radio = tester.widget(find.byType(Radio<bool>).last); expect(radio.value, false); expect(radio.groupValue, false); // Tap the first labeled radio to toggle the Radio widget. await tester.tap(find.byType(example.LabeledRadio).first); await tester.pumpAndSettle(); // First Radio is now checked. radio = tester.widget(find.byType(Radio<bool>).first); expect(radio.value, true); expect(radio.groupValue, true); // Last Radio is now unchecked. radio = tester.widget(find.byType(Radio<bool>).last); expect(radio.value, false); expect(radio.groupValue, true); }); }
flutter/examples/api/test/material/radio_list_tile/custom_labeled_radio.1_test.dart/0
{ "file_path": "flutter/examples/api/test/material/radio_list_tile/custom_labeled_radio.1_test.dart", "repo_id": "flutter", "token_count": 470 }
591
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_api_samples/material/search_anchor/search_bar.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Can open search view', (WidgetTester tester) async { await tester.pumpWidget( const example.SearchBarApp(), ); final Finder searchBarFinder = find.byType(SearchBar); final SearchBar searchBar = tester.widget<SearchBar>(searchBarFinder); expect(find.byIcon(Icons.search), findsOneWidget); expect(searchBar.trailing, isNotEmpty); expect(searchBar.trailing?.length, equals(1)); final Finder trailingButtonFinder = find.widgetWithIcon(IconButton, Icons.wb_sunny_outlined); expect(trailingButtonFinder, findsOneWidget); await tester.tap(trailingButtonFinder); await tester.pumpAndSettle(); expect(find.widgetWithIcon(IconButton, Icons.brightness_2_outlined), findsOneWidget); await tester.tap(searchBarFinder); await tester.pumpAndSettle(); expect(find.text('item 0'), findsOneWidget); expect(find.text('item 1'), findsOneWidget); expect(find.text('item 2'), findsOneWidget); expect(find.text('item 3'), findsOneWidget); expect(find.text('item 4'), findsOneWidget); }); }
flutter/examples/api/test/material/search_anchor/search_bar.0_test.dart/0
{ "file_path": "flutter/examples/api/test/material/search_anchor/search_bar.0_test.dart", "repo_id": "flutter", "token_count": 485 }
592
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_api_samples/material/switch_list_tile/switch_list_tile.1.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Switch aligns appropriately', (WidgetTester tester) async { await tester.pumpWidget( const example.SwitchListTileApp(), ); expect(find.byType(SwitchListTile), findsNWidgets(3)); Offset tileTopLeft = tester.getTopLeft(find.byType(SwitchListTile).at(0)); Offset switchTopLeft = tester.getTopLeft(find.byType(Switch).at(0)); // The switch is centered vertically with the text. expect(switchTopLeft - tileTopLeft, const Offset(716.0, 16.0)); tileTopLeft = tester.getTopLeft(find.byType(SwitchListTile).at(1)); switchTopLeft = tester.getTopLeft(find.byType(Switch).at(1)); // The switch is centered vertically with the text. expect(switchTopLeft - tileTopLeft, const Offset(716.0, 30.0)); tileTopLeft = tester.getTopLeft(find.byType(SwitchListTile).at(2)); switchTopLeft = tester.getTopLeft(find.byType(Switch).at(2)); // The switch is aligned to the top vertically with the text. expect(switchTopLeft - tileTopLeft, const Offset(716.0, 8.0)); }); testWidgets('Switches can be checked', (WidgetTester tester) async { await tester.pumpWidget( const example.SwitchListTileApp(), ); expect(find.byType(SwitchListTile), findsNWidgets(3)); // All switches are on. expect(tester.widget<Switch>(find.byType(Switch).at(0)).value, isTrue); expect(tester.widget<Switch>(find.byType(Switch).at(1)).value, isTrue); expect(tester.widget<Switch>(find.byType(Switch).at(2)).value, isTrue); // Tap the first switch. await tester.tap(find.byType(Switch).at(0)); await tester.pumpAndSettle(); // The first switch is off. expect(tester.widget<Switch>(find.byType(Switch).at(0)).value, isFalse); expect(tester.widget<Switch>(find.byType(Switch).at(1)).value, isTrue); expect(tester.widget<Switch>(find.byType(Switch).at(2)).value, isTrue); // Tap the second switch. await tester.tap(find.byType(Switch).at(1)); await tester.pumpAndSettle(); // The first and second switches are off. expect(tester.widget<Switch>(find.byType(Switch).at(0)).value, isFalse); expect(tester.widget<Switch>(find.byType(Switch).at(1)).value, isFalse); expect(tester.widget<Switch>(find.byType(Switch).at(2)).value, isTrue); // Tap the third switch. await tester.tap(find.byType(Switch).at(2)); await tester.pumpAndSettle(); // All switches are off. expect(tester.widget<Switch>(find.byType(Switch).at(0)).value, isFalse); expect(tester.widget<Switch>(find.byType(Switch).at(1)).value, isFalse); expect(tester.widget<Switch>(find.byType(Switch).at(2)).value, isFalse); }); }
flutter/examples/api/test/material/switch_list_tile/switch_list_tile.1_test.dart/0
{ "file_path": "flutter/examples/api/test/material/switch_list_tile/switch_list_tile.1_test.dart", "repo_id": "flutter", "token_count": 1090 }
593
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_api_samples/painting/borders/border_side.stroke_align.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Finds the expected BorderedBox', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: example.StrokeAlignExample(), ), ); expect(find.byType(example.StrokeAlignExample), findsOneWidget); expect(find.byType(example.BorderedBox), findsNWidgets(10)); }); }
flutter/examples/api/test/painting/border_side.stroke_align.0_test.dart/0
{ "file_path": "flutter/examples/api/test/painting/border_side.stroke_align.0_test.dart", "repo_id": "flutter", "token_count": 248 }
594
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_api_samples/services/text_input/text_input_control.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Enter text using the VKB', (WidgetTester tester) async { await tester.pumpWidget(const example.TextInputControlExampleApp()); await tester.pumpAndSettle(); await tester.tap(find.descendant( of: find.byType(example.MyVirtualKeyboard), matching: find.widgetWithText(ElevatedButton, 'A'), )); await tester.pumpAndSettle(); expect(find.widgetWithText(TextField, 'A'), findsOneWidget); await tester.tap(find.descendant( of: find.byType(example.MyVirtualKeyboard), matching: find.widgetWithText(ElevatedButton, 'B'), )); await tester.pumpAndSettle(); expect(find.widgetWithText(TextField, 'AB'), findsOneWidget); await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pumpAndSettle(); await tester.tap(find.descendant( of: find.byType(example.MyVirtualKeyboard), matching: find.widgetWithText(ElevatedButton, 'C'), )); await tester.pumpAndSettle(); expect(find.widgetWithText(TextField, 'ACB'), findsOneWidget); }); }
flutter/examples/api/test/services/text_input/text_input_control.0_test.dart/0
{ "file_path": "flutter/examples/api/test/services/text_input/text_input_control.0_test.dart", "repo_id": "flutter", "token_count": 522 }
595
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_api_samples/widgets/app_lifecycle_listener/app_lifecycle_listener.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('AppLifecycleListener example', (WidgetTester tester) async { await tester.pumpWidget( const example.AppLifecycleListenerExample(), ); expect(find.textContaining('Current State:'), findsOneWidget); expect(find.textContaining('State History:'), findsOneWidget); }); }
flutter/examples/api/test/widgets/app_lifecycle_listener/app_lifecycle_listener.0_test.dart/0
{ "file_path": "flutter/examples/api/test/widgets/app_lifecycle_listener/app_lifecycle_listener.0_test.dart", "repo_id": "flutter", "token_count": 207 }
596
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_api_samples/widgets/basic/listener.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Listener detects press & release, and cursor location', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp(home: example.ListenerExample()), ); expect(find.text('0 presses\n0 releases'), findsOneWidget); expect(find.text('The cursor is here: (0.00, 0.00)'), findsOneWidget); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.down(tester.getCenter(find.byType(ColoredBox))); await tester.pump(); expect(find.text('1 presses\n0 releases'), findsOneWidget); expect(find.text('The cursor is here: (400.00, 300.00)'), findsOneWidget); await gesture.up(); await tester.pump(); expect(find.text('1 presses\n1 releases'), findsOneWidget); expect(find.text('The cursor is here: (400.00, 300.00)'), findsOneWidget); }); }
flutter/examples/api/test/widgets/basic/listener.0_test.dart/0
{ "file_path": "flutter/examples/api/test/widgets/basic/listener.0_test.dart", "repo_id": "flutter", "token_count": 434 }
597
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_api_samples/widgets/heroes/hero.1.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Hero flight animation with default rect tween', (WidgetTester tester) async { await tester.pumpWidget( const example.HeroApp(), ); expect(find.text('Hero Sample'), findsOneWidget); await tester.tap(find.byType(ElevatedButton)); await tester.pump(); Size heroSize = tester.getSize(find.byType(Container).first); expect(heroSize, const Size(50.0, 50.0)); // Jump 25% into the transition (total length = 300ms) await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).first); expect(heroSize.width.roundToDouble(), 170.0); expect(heroSize.height.roundToDouble(), 73.0); // Jump to 50% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).first); expect(heroSize.width.roundToDouble(), 371.0); expect(heroSize.height.roundToDouble(), 273.0); // Jump to 75% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).first); expect(heroSize.width.roundToDouble(), 398.0); expect(heroSize.height.roundToDouble(), 376.0); // Jump to 100% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).first); expect(heroSize, const Size(400.0, 400.0)); expect(find.byIcon(Icons.arrow_back), findsOneWidget); await tester.tap(find.byIcon(Icons.arrow_back)); await tester.pump(); // Jump 25% into the transition (total length = 300ms) await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).first); expect(heroSize.width.roundToDouble(), 398.0); expect(heroSize.height.roundToDouble(), 376.0); // Jump to 50% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).first); expect(heroSize.width.roundToDouble(), 371.0); expect(heroSize.height.roundToDouble(), 273.0); // Jump to 75% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).first); expect(heroSize.width.roundToDouble(), 170.0); expect(heroSize.height.roundToDouble(), 73.0); // Jump to 100% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).first); expect(heroSize, const Size(50.0, 50.0)); }); testWidgets('Hero flight animation with custom rect tween', (WidgetTester tester) async { await tester.pumpWidget( const example.HeroApp(), ); expect(find.text('Hero Sample'), findsOneWidget); await tester.tap(find.byType(ElevatedButton)); await tester.pump(); Size heroSize = tester.getSize(find.byType(Container).last); expect(heroSize, const Size(50.0, 50.0)); // Jump 25% into the transition (total length = 300ms) await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).last); expect(heroSize.width.roundToDouble(), 133.0); expect(heroSize.height.roundToDouble(), 133.0); // Jump to 50% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).last); expect(heroSize.width.roundToDouble(), 321.0); expect(heroSize.height.roundToDouble(), 321.0); // Jump to 75% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).first); expect(heroSize.width.roundToDouble(), 398.0); expect(heroSize.height.roundToDouble(), 376.0); // Jump to 100% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).last); expect(heroSize, const Size(400.0, 400.0)); expect(find.byIcon(Icons.arrow_back), findsOneWidget); await tester.tap(find.byIcon(Icons.arrow_back)); await tester.pump(); // Jump 25% into the transition (total length = 300ms) await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).last); expect(heroSize.width.roundToDouble(), 386.0); expect(heroSize.height.roundToDouble(), 386.0); // Jump to 50% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).last); expect(heroSize.width.roundToDouble(), 321.0); expect(heroSize.height.roundToDouble(), 321.0); // Jump to 75% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).last); expect(heroSize.width.roundToDouble(), 133.0); expect(heroSize.height.roundToDouble(), 133.0); // Jump to 100% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container).last); expect(heroSize, const Size(50.0, 50.0)); }); }
flutter/examples/api/test/widgets/heroes/hero.1_test.dart/0
{ "file_path": "flutter/examples/api/test/widgets/heroes/hero.1_test.dart", "repo_id": "flutter", "token_count": 2048 }
598
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_api_samples/widgets/routes/show_general_dialog.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Open and dismiss general dialog', (WidgetTester tester) async { const String dialogText = 'Alert!'; await tester.pumpWidget( const example.GeneralDialogApp(), ); expect(find.text(dialogText), findsNothing); // Tap on the button to show the dialog. await tester.tap(find.byType(OutlinedButton)); await tester.pumpAndSettle(); expect(find.text(dialogText), findsOneWidget); // Try to dismiss the dialog with a tap on the scrim. await tester.tapAt(const Offset(10.0, 10.0)); await tester.pumpAndSettle(); expect(find.text(dialogText), findsNothing); }); }
flutter/examples/api/test/widgets/routes/show_general_dialog.0_test.dart/0
{ "file_path": "flutter/examples/api/test/widgets/routes/show_general_dialog.0_test.dart", "repo_id": "flutter", "token_count": 337 }
599
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_api_samples/widgets/text_magnifier/text_magnifier.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; List<TextSelectionPoint> _globalize( Iterable<TextSelectionPoint> points, RenderBox box) { return points.map<TextSelectionPoint>((TextSelectionPoint point) { return TextSelectionPoint( box.localToGlobal(point.point), point.direction, ); }).toList(); } RenderEditable _findRenderEditable<T extends State<StatefulWidget>>(WidgetTester tester) { return (tester.state(find.byType(TextField)) as TextSelectionGestureDetectorBuilderDelegate) .editableTextKey .currentState! .renderEditable; } Offset _textOffsetToPosition<T extends State<StatefulWidget>>(WidgetTester tester, int offset) { final RenderEditable renderEditable = _findRenderEditable(tester); final List<TextSelectionPoint> endpoints = renderEditable .getEndpointsForSelection( TextSelection.collapsed(offset: offset), ) .map<TextSelectionPoint>((TextSelectionPoint point) => TextSelectionPoint( renderEditable.localToGlobal(point.point), point.direction, )) .toList(); return endpoints[0].point + const Offset(0.0, -2.0); } void main() { const Duration durationBetweenActions = Duration(milliseconds: 20); const String defaultText = 'I am a magnifier, fear me!'; Future<void> showMagnifier(WidgetTester tester, int textOffset) async { assert(textOffset >= 0); final Offset tapOffset = _textOffsetToPosition(tester, textOffset); // Double tap 'Magnifier' word to show the selection handles. final TestGesture testGesture = await tester.startGesture(tapOffset); await tester.pump(durationBetweenActions); await testGesture.up(); await tester.pump(durationBetweenActions); await testGesture.down(tapOffset); await tester.pump(durationBetweenActions); await testGesture.up(); await tester.pumpAndSettle(); final TextEditingController controller = tester .firstWidget<TextField>(find.byType(TextField)) .controller!; final TextSelection selection = controller.selection; final RenderEditable renderEditable = _findRenderEditable(tester); final List<TextSelectionPoint> endpoints = _globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); final Offset handlePos = endpoints.last.point + const Offset(10.0, 10.0); final TestGesture gesture = await tester.startGesture(handlePos); await gesture.moveTo( _textOffsetToPosition( tester, defaultText.length - 2, ), ); await tester.pump(); } testWidgets('should show custom magnifier on drag', (WidgetTester tester) async { await tester.pumpWidget(const example.TextMagnifierExampleApp(text: defaultText)); await showMagnifier(tester, defaultText.indexOf('e')); expect(find.byType(example.CustomMagnifier), findsOneWidget); await expectLater( find.byType(example.TextMagnifierExampleApp), matchesGoldenFile('text_magnifier.0_test.png'), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android }), skip: true, // This image is flaky. https://github.com/flutter/flutter/issues/144350 ); testWidgets('should show custom magnifier in RTL', (WidgetTester tester) async { const String text = 'أثارت زر'; const String textToTapOn = 'ت'; await tester.pumpWidget(const example.TextMagnifierExampleApp(textDirection: TextDirection.rtl, text: text)); await showMagnifier(tester, text.indexOf(textToTapOn)); expect(find.byType(example.CustomMagnifier), findsOneWidget); }); }
flutter/examples/api/test/widgets/text_magnifier/text_magnifier.0_test.dart/0
{ "file_path": "flutter/examples/api/test/widgets/text_magnifier/text_magnifier.0_test.dart", "repo_id": "flutter", "token_count": 1402 }
600
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Foundation/Foundation.h> #import "NativeViewController.h" @interface NativeViewController () @property int counter; @property (weak, nonatomic) IBOutlet UILabel* incrementLabel; @end @implementation NativeViewController - (void)viewDidLoad { [super viewDidLoad]; self.counter = 0; } - (IBAction)handleIncrement:(id)sender { [self.delegate didTapIncrementButton]; } - (void)didReceiveIncrement { self.counter++; NSString* text = [NSString stringWithFormat:@"Flutter button tapped %d %@.", self.counter, (self.counter == 1)? @"time" : @"times"]; self.incrementLabel.text = text; } @end
flutter/examples/flutter_view/ios/Runner/NativeViewController.m/0
{ "file_path": "flutter/examples/flutter_view/ios/Runner/NativeViewController.m", "repo_id": "flutter", "token_count": 343 }
601
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
flutter/examples/flutter_view/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "flutter/examples/flutter_view/macos/Runner/Configs/Release.xcconfig", "repo_id": "flutter", "token_count": 32 }
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. // This example shows how to draw some bi-directional text using the raw // interface to the engine. import 'dart:typed_data'; import 'dart:ui' as ui; // The FlutterView into which this example will draw; set in the main method. late final ui.FlutterView view; // A paragraph represents a rectangular region that contains some text. late ui.Paragraph paragraph; ui.Picture paint(ui.Rect paintBounds) { final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder, paintBounds); final double devicePixelRatio = view.devicePixelRatio; final ui.Size logicalSize = view.physicalSize / devicePixelRatio; canvas.translate(logicalSize.width / 2.0, logicalSize.height / 2.0); canvas.drawRect( const ui.Rect.fromLTRB(-100.0, -100.0, 100.0, 100.0), ui.Paint()..color = const ui.Color.fromARGB(255, 0, 255, 0), ); // The paint method of Paragraph draws the contents of the paragraph onto the // given canvas. canvas.drawParagraph(paragraph, ui.Offset(-paragraph.width / 2.0, (paragraph.width / 2.0) - 125.0)); return recorder.endRecording(); } ui.Scene composite(ui.Picture picture, ui.Rect paintBounds) { final double devicePixelRatio = view.devicePixelRatio; final Float64List deviceTransform = Float64List(16) ..[0] = devicePixelRatio ..[5] = devicePixelRatio ..[10] = 1.0 ..[15] = 1.0; final ui.SceneBuilder sceneBuilder = ui.SceneBuilder() ..pushTransform(deviceTransform) ..addPicture(ui.Offset.zero, picture) ..pop(); return sceneBuilder.build(); } void beginFrame(Duration timeStamp) { final ui.Rect paintBounds = ui.Offset.zero & (view.physicalSize / view.devicePixelRatio); final ui.Picture picture = paint(paintBounds); final ui.Scene scene = composite(picture, paintBounds); view.render(scene); } void main() { // TODO(goderbauer): Create a window if embedder doesn't provide an implicit view to draw into. assert(ui.PlatformDispatcher.instance.implicitView != null); view = ui.PlatformDispatcher.instance.implicitView!; // To create a paragraph of text, we use ParagraphBuilder. final ui.ParagraphBuilder builder = ui.ParagraphBuilder( // The text below has a primary direction of left-to-right. // The embedded text has other directions. // If this was TextDirection.rtl, the "Hello, world" text would end up on // the other side of the right-to-left text. ui.ParagraphStyle(textDirection: ui.TextDirection.ltr), ) // We first push a style that turns the text blue. ..pushStyle(ui.TextStyle(color: const ui.Color(0xFF0000FF))) ..addText('Hello, ') // The next run of text will be bold. ..pushStyle(ui.TextStyle(fontWeight: ui.FontWeight.bold)) ..addText('world. ') // The pop() command signals the end of the bold styling. ..pop() // We add text to the paragraph in logical order. The paragraph object // understands bi-directional text and will compute the visual ordering // during layout. ..addText('هذا هو قليلا طويلة من النص الذي يجب التفاف .') // The second pop() removes the blue color. ..pop() // We can add more text with the default styling. ..addText(' و أكثر قليلا لجعله أطول. ') ..addText('สวัสดี'); // When we're done adding styles and text, we build the Paragraph object, at // which time we can apply styling that affects the entire paragraph, such as // left, right, or center alignment. Once built, the contents of the paragraph // cannot be altered, but sizing and positioning information can be updated. paragraph = builder.build() // Next, we supply a width that the text is permitted to occupy and we ask // the paragraph to the visual position of each its glyphs as well as its // overall size, subject to its sizing constraints. ..layout(const ui.ParagraphConstraints(width: 180.0)); // Finally, we register our beginFrame callback and kick off the first frame. ui.PlatformDispatcher.instance ..onBeginFrame = beginFrame ..scheduleFrame(); }
flutter/examples/layers/raw/text.dart/0
{ "file_path": "flutter/examples/layers/raw/text.dart", "repo_id": "flutter", "token_count": 1394 }
603
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import '../rendering/src/sector_layout.dart'; import '../widgets/sectors.dart'; void main() { test('SectorConstraints', () { expect(const SectorConstraints().isTight, isFalse); }); testWidgets('Sector Sixes', (WidgetTester tester) async { await tester.pumpWidget(const SectorApp()); }); }
flutter/examples/layers/test/sector_test.dart/0
{ "file_path": "flutter/examples/layers/test/sector_test.dart", "repo_id": "flutter", "token_count": 172 }
604
// Copyright 2014 The Flutter 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.example.platformchannel; import android.content.BroadcastReceiver; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Bundle; import androidx.annotation.NonNull; import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.plugin.common.EventChannel; import io.flutter.plugin.common.EventChannel.EventSink; import io.flutter.plugin.common.EventChannel.StreamHandler; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; import io.flutter.plugin.common.MethodCall; import io.flutter.plugins.GeneratedPluginRegistrant; public class MainActivity extends FlutterActivity { private static final String BATTERY_CHANNEL = "samples.flutter.io/battery"; private static final String CHARGING_CHANNEL = "samples.flutter.io/charging"; @Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { new EventChannel(flutterEngine.getDartExecutor(), CHARGING_CHANNEL).setStreamHandler( new StreamHandler() { private BroadcastReceiver chargingStateChangeReceiver; @Override public void onListen(Object arguments, EventSink events) { chargingStateChangeReceiver = createChargingStateChangeReceiver(events); registerReceiver( chargingStateChangeReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); } @Override public void onCancel(Object arguments) { unregisterReceiver(chargingStateChangeReceiver); chargingStateChangeReceiver = null; } } ); new MethodChannel(flutterEngine.getDartExecutor(), BATTERY_CHANNEL).setMethodCallHandler( new MethodCallHandler() { @Override public void onMethodCall(MethodCall call, Result result) { if (call.method.equals("getBatteryLevel")) { int batteryLevel = getBatteryLevel(); if (batteryLevel != -1) { result.success(batteryLevel); } else { result.error("UNAVAILABLE", "Battery level not available.", null); } } else { result.notImplemented(); } } } ); } private BroadcastReceiver createChargingStateChangeReceiver(final EventSink events) { return new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1); if (status == BatteryManager.BATTERY_STATUS_UNKNOWN) { events.error("UNAVAILABLE", "Charging status unavailable", null); } else { boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; events.success(isCharging ? "charging" : "discharging"); } } }; } private int getBatteryLevel() { if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE); return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY); } else { Intent intent = new ContextWrapper(getApplicationContext()). registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); return (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); } } }
flutter/examples/platform_channel/android/app/src/main/java/com/example/platformchannel/MainActivity.java/0
{ "file_path": "flutter/examples/platform_channel/android/app/src/main/java/com/example/platformchannel/MainActivity.java", "repo_id": "flutter", "token_count": 1450 }
605
#include "ephemeral/Flutter-Generated.xcconfig"
flutter/examples/platform_channel/macos/Flutter/Flutter-Release.xcconfig/0
{ "file_path": "flutter/examples/platform_channel/macos/Flutter/Flutter-Release.xcconfig", "repo_id": "flutter", "token_count": 19 }
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 Foundation import IOKit.ps enum PowerState { case ac case battery case unknown } /// A convenience wrapper for an IOKit power source. final class PowerSource { let info = IOPSCopyPowerSourcesInfo().takeRetainedValue() let sources: Array<CFTypeRef> init() { sources = IOPSCopyPowerSourcesList(info).takeRetainedValue() as Array } func hasBattery() -> Bool { return !sources.isEmpty } /// Returns the current power source capacity. Apple-defined power sources will return this value /// as a percentage. func getCurrentCapacity() -> Int? { if let source = sources.first { let description = IOPSGetPowerSourceDescription(info, source).takeUnretainedValue() as! [String: AnyObject] if let level = description[kIOPSCurrentCapacityKey] as? Int { return level } } return nil } /// Returns whether the device is drawing battery power or connected to an external power source. func getPowerState() -> PowerState { if let source = sources.first { let description = IOPSGetPowerSourceDescription(info, source).takeUnretainedValue() as! [String: AnyObject] if let state = description[kIOPSPowerSourceStateKey] as? String { switch state { case kIOPSACPowerValue: return .ac case kIOPSBatteryPowerValue: return .battery default: return .unknown } } } return .unknown } } protocol PowerSourceStateChangeDelegate: AnyObject { func didChangePowerSourceState() } /// A listener for system power source state change events. Notifies the delegate on each event. final class PowerSourceStateChangeHandler { private var runLoopSource: CFRunLoopSource? weak var delegate: PowerSourceStateChangeDelegate? init() { let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) self.runLoopSource = IOPSNotificationCreateRunLoopSource( { (context: UnsafeMutableRawPointer?) in let unownedSelf = Unmanaged<PowerSourceStateChangeHandler>.fromOpaque( UnsafeRawPointer(context!) ).takeUnretainedValue() unownedSelf.delegate?.didChangePowerSourceState() }, context ).takeRetainedValue() CFRunLoopAddSource(CFRunLoopGetCurrent(), self.runLoopSource, .defaultMode) } deinit { CFRunLoopRemoveSource(CFRunLoopGetCurrent(), self.runLoopSource, .defaultMode) } }
flutter/examples/platform_channel/macos/Runner/PowerSource.swift/0
{ "file_path": "flutter/examples/platform_channel/macos/Runner/PowerSource.swift", "repo_id": "flutter", "token_count": 881 }
607
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
flutter/examples/platform_view/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "flutter/examples/platform_view/macos/Runner/Configs/Debug.xcconfig", "repo_id": "flutter", "token_count": 32 }
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. #include "my_application.h" #include <flutter_linux/flutter_linux.h> #include "my_texture.h" #ifdef GDK_WINDOWING_X11 #include <gdk/gdkx.h> #endif #include "flutter/generated_plugin_registrant.h" struct _MyApplication { GtkApplication parent_instance; // Channel to receive texture requests from Flutter. FlMethodChannel* texture_channel; // Texture we've created. MyTexture* texture; FlView* view; }; G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) // Handle request to create the texture. static FlMethodResponse* handle_create(MyApplication* self, FlMethodCall* method_call) { if (self->texture != nullptr) { return FL_METHOD_RESPONSE(fl_method_error_response_new( "Error", "texture already created", nullptr)); } FlValue* args = fl_method_call_get_args(method_call); if (fl_value_get_type(args) != FL_VALUE_TYPE_LIST || fl_value_get_length(args) != 2) { return FL_METHOD_RESPONSE(fl_method_error_response_new( "Invalid args", "Invalid create args", nullptr)); } FlValue* width_value = fl_value_get_list_value(args, 0); FlValue* height_value = fl_value_get_list_value(args, 1); if (fl_value_get_type(width_value) != FL_VALUE_TYPE_INT || fl_value_get_type(height_value) != FL_VALUE_TYPE_INT) { return FL_METHOD_RESPONSE(fl_method_error_response_new( "Invalid args", "Invalid create args", nullptr)); } FlEngine* engine = fl_view_get_engine(self->view); FlTextureRegistrar* texture_registrar = fl_engine_get_texture_registrar(engine); self->texture = my_texture_new(fl_value_get_int(width_value), fl_value_get_int(height_value), 0x05, 0x53, 0xb1); if (!fl_texture_registrar_register_texture(texture_registrar, FL_TEXTURE(self->texture))) { return FL_METHOD_RESPONSE(fl_method_error_response_new( "Error", "Failed to register texture", nullptr)); } // Return the texture ID to Flutter so it can use this texture. g_autoptr(FlValue) id = fl_value_new_int(fl_texture_get_id(FL_TEXTURE(self->texture))); return FL_METHOD_RESPONSE(fl_method_success_response_new(id)); } // Handle request to set the texture color. static FlMethodResponse* handle_set_color(MyApplication* self, FlMethodCall* method_call) { FlValue* args = fl_method_call_get_args(method_call); if (fl_value_get_type(args) != FL_VALUE_TYPE_LIST || fl_value_get_length(args) != 3) { return FL_METHOD_RESPONSE(fl_method_error_response_new( "Invalid args", "Invalid setColor args", nullptr)); } FlValue* r_value = fl_value_get_list_value(args, 0); FlValue* g_value = fl_value_get_list_value(args, 1); FlValue* b_value = fl_value_get_list_value(args, 2); if (fl_value_get_type(r_value) != FL_VALUE_TYPE_INT || fl_value_get_type(g_value) != FL_VALUE_TYPE_INT || fl_value_get_type(b_value) != FL_VALUE_TYPE_INT) { return FL_METHOD_RESPONSE(fl_method_error_response_new( "Invalid args", "Invalid setColor args", nullptr)); } FlEngine* engine = fl_view_get_engine(self->view); FlTextureRegistrar* texture_registrar = fl_engine_get_texture_registrar(engine); // Redraw in requested color. my_texture_set_color(self->texture, fl_value_get_int(r_value), fl_value_get_int(g_value), fl_value_get_int(b_value)); // Notify Flutter the texture has changed. fl_texture_registrar_mark_texture_frame_available(texture_registrar, FL_TEXTURE(self->texture)); return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); } // Handle texture requests from Flutter. static void texture_channel_method_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { MyApplication* self = MY_APPLICATION(user_data); const char* name = fl_method_call_get_name(method_call); if (g_str_equal(name, "create")) { g_autoptr(FlMethodResponse) response = handle_create(self, method_call); fl_method_call_respond(method_call, response, NULL); } else if (g_str_equal(name, "setColor")) { g_autoptr(FlMethodResponse) response = handle_set_color(self, method_call); fl_method_call_respond(method_call, response, NULL); } else { fl_method_call_respond_not_implemented(method_call, NULL); } } // Implements GObject::dispose. static void my_application_dispose(GObject* object) { MyApplication* self = MY_APPLICATION(object); g_clear_object(&self->texture_channel); g_clear_object(&self->texture); G_OBJECT_CLASS(my_application_parent_class)->dispose(object); } // Implements GApplication::activate. static void my_application_activate(GApplication* application) { MyApplication* self = MY_APPLICATION(application); GtkWindow* window = GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); gtk_window_set_default_size(window, 1280, 720); gtk_widget_show(GTK_WIDGET(window)); g_autoptr(FlDartProject) project = fl_dart_project_new(); self->view = fl_view_new(project); gtk_widget_show(GTK_WIDGET(self->view)); gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(self->view)); // Create channel to handle texture requests from Flutter. FlEngine* engine = fl_view_get_engine(self->view); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); self->texture_channel = fl_method_channel_new( fl_engine_get_binary_messenger(engine), "samples.flutter.io/texture", FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler( self->texture_channel, texture_channel_method_cb, self, nullptr); fl_register_plugins(FL_PLUGIN_REGISTRY(self->view)); gtk_widget_grab_focus(GTK_WIDGET(self->view)); } static void my_application_class_init(MyApplicationClass* klass) { G_OBJECT_CLASS(klass)->dispose = my_application_dispose; G_APPLICATION_CLASS(klass)->activate = my_application_activate; } static void my_application_init(MyApplication* self) {} MyApplication* my_application_new() { return MY_APPLICATION(g_object_new(my_application_get_type(), "application-id", APPLICATION_ID, "flags", G_APPLICATION_NON_UNIQUE, nullptr)); }
flutter/examples/texture/linux/my_application.cc/0
{ "file_path": "flutter/examples/texture/linux/my_application.cc", "repo_id": "flutter", "token_count": 2636 }
609
## Directory contents The `.yaml` files in these directories are used to define the [`dart fix` framework](https://dart.dev/tools/dart-fix) refactorings used by the Flutter framework. The number of fix rules defined in a file should not exceed 50 for better maintainability. Searching for `title:` in a given `.yaml` file will account for the number of fixes. Splitting out fix rules should be done by class. When adding a new `.yaml` file, make a copy of `fix_template.yaml`. If the new file is not for generic library fixes (`fix_material.yaml`), ensure it is enclosed in an appropriate library directory (`fix_data/fix_material`), and named after the class. Fix files outside of generic libraries should represent individual classes (`fix_data/fix_material/fix_app_bar.yaml`). See the flutter/packages/flutter/test_fixes directory for the tests that validate these fix rules. To run these tests locally, execute this command in the flutter/packages/flutter/test_fixes directory. ```sh dart fix --compare-to-golden ``` For more documentation about Data Driven Fixes, see https://dart.dev/go/data-driven-fixes#test-folder. To learn more about how fixes are authored in package:flutter, see https://github.com/flutter/flutter/wiki/Data-driven-Fixes ## When making structural changes to this directory The tests in this directory are also invoked from external repositories. Specifically, the CI system for the dart-lang/sdk repo runs these tests in order to ensure that changes to the dart fix file format do not break Flutter. See [tools/bots/flutter/analyze_flutter_flutter.sh](https://github.com/dart-lang/sdk/blob/main/tools/bots/flutter/analyze_flutter_flutter.sh) for where the tests are invoked. When possible, please coordinate changes to this directory that might affect the `analyze_flutter_flutter.sh` script.
flutter/packages/flutter/lib/fix_data/README.md/0
{ "file_path": "flutter/packages/flutter/lib/fix_data/README.md", "repo_id": "flutter", "token_count": 524 }
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. # For details regarding the *Flutter Fix* feature, see # https://flutter.dev/docs/development/tools/flutter-fix # Please add new fixes to the top of the file, separated by one blank line # from other fixes. In a comment, include a link to the PR where the change # requiring the fix was made. # Every fix must be tested. See the flutter/packages/flutter/test_fixes/README.md # file for instructions on testing these data driven fixes. # For documentation about this file format, see # https://dart.dev/go/data-driven-fixes. # * Fixes in this file are for BuildContext from the Widgets library. * # For fixes to # * Actions: fix_actions.yaml # * Element: fix_element.yaml # * ListWheelScrollView: fix_list_wheel_scroll_view.yaml # * Widgets (general): fix_widgets.yaml version: 1 transforms: # Change made in https://github.com/flutter/flutter/pull/44189. - title: "Rename to 'dependOnInheritedElement'" date: 2019-11-22 element: uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ] inClass: 'BuildContext' method: 'inheritFromElement' changes: - kind: 'rename' newName: 'dependOnInheritedElement' # Change made in https://github.com/flutter/flutter/pull/44189. - title: "Migrate to 'dependOnInheritedWidgetOfExactType'" date: 2019-11-22 element: uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ] inClass: 'BuildContext' method: 'inheritFromWidgetOfExactType' changes: - kind: 'rename' newName: 'dependOnInheritedWidgetOfExactType' - kind: 'removeParameter' index: 0 - kind: 'addTypeParameter' index: 0 name: 'T' argumentValue: expression: '{% type %}' variables: type: kind: fragment value: 'arguments[0]' # Change made in https://github.com/flutter/flutter/pull/44189. - title: "Migrate to 'getElementForInheritedWidgetOfExactType'" date: 2019-11-22 element: uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ] inClass: 'BuildContext' method: 'ancestorInheritedElementForWidgetOfExactType' changes: - kind: 'rename' newName: 'getElementForInheritedWidgetOfExactType' - kind: 'removeParameter' index: 0 - kind: 'addTypeParameter' index: 0 name: 'T' argumentValue: expression: '{% type %}' variables: type: kind: fragment value: 'arguments[0]' # Change made in https://github.com/flutter/flutter/pull/44189. - title: "Migrate to 'findAncestorWidgetOfExactType'" date: 2019-11-22 element: uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ] inClass: 'BuildContext' method: 'ancestorWidgetOfExactType' changes: - kind: 'rename' newName: 'findAncestorWidgetOfExactType' - kind: 'removeParameter' index: 0 - kind: 'addTypeParameter' index: 0 name: 'T' argumentValue: expression: '{% type %}' variables: type: kind: fragment value: 'arguments[0]' # Change made in https://github.com/flutter/flutter/pull/44189. - title: "Migrate to 'findAncestorStateOfType'" date: 2019-11-22 element: uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ] inClass: 'BuildContext' method: 'ancestorStateOfType' changes: - kind: 'rename' newName: 'findAncestorStateOfType' - kind: 'removeParameter' index: 0 - kind: 'addTypeParameter' index: 0 name: 'T' argumentValue: expression: '{% type %}' variables: type: kind: fragment value: 'arguments[0].typeArguments[0]' # Change made in https://github.com/flutter/flutter/pull/44189. - title: "Migrate to 'rootAncestorStateOfType'" date: 2019-11-22 element: uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ] inClass: 'BuildContext' method: 'rootAncestorStateOfType' changes: - kind: 'rename' newName: 'findRootAncestorStateOfType' - kind: 'removeParameter' index: 0 - kind: 'addTypeParameter' index: 0 name: 'T' argumentValue: expression: '{% type %}' variables: type: kind: fragment value: 'arguments[0].typeArguments[0]' # Change made in https://github.com/flutter/flutter/pull/44189. - title: "Migrate to 'ancestorRenderObjectOfType'" date: 2019-11-22 element: uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ] inClass: 'BuildContext' method: 'ancestorRenderObjectOfType' changes: - kind: 'rename' newName: 'findAncestorRenderObjectOfType' - kind: 'removeParameter' index: 0 - kind: 'addTypeParameter' index: 0 name: 'T' argumentValue: expression: '{% type %}' variables: type: kind: fragment value: 'arguments[0].typeArguments[0]' # Before adding a new fix: read instructions at the top of this file.
flutter/packages/flutter/lib/fix_data/fix_widgets/fix_build_context.yaml/0
{ "file_path": "flutter/packages/flutter/lib/fix_data/fix_widgets/fix_build_context.yaml", "repo_id": "flutter", "token_count": 2410 }
611