text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
name: macrobenchmarks
description: Performance benchmarks using flutter drive.
environment:
sdk: '>=3.2.0-0 <4.0.0'
dependencies:
flutter:
sdk: flutter
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
# To change the version of the gallery assets, edit
# //packages/flutter_tools/lib/src/commands/update_packages.dart
# and run
# flutter update-packages --force-upgrade
flutter_gallery_assets: 1.0.2
web: 0.5.1
async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
characters: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
clock: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
fake_async: 1.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
file: 7.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
leak_tracker: 10.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
leak_tracker_flutter_testing: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
leak_tracker_testing: 3.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
material_color_utilities: 0.8.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
meta: 1.12.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
path: 1.9.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
stack_trace: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
stream_channel: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
sync_http: 0.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
test_api: 0.7.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
vm_service: 14.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
webdriver: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
dev_dependencies:
test: 1.25.2
integration_test:
sdk: flutter
_fe_analyzer_shared: 67.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
analyzer: 6.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
args: 2.4.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
convert: 3.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
coverage: 1.7.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
crypto: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
frontend_server_client: 3.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
glob: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
http_multi_server: 3.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
http_parser: 4.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
io: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
js: 0.7.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
logging: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
mime: 1.0.5 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
node_preamble: 2.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
package_config: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
pool: 1.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
pub_semver: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf_packages_handler: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf_static: 1.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf_web_socket: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_map_stack_trace: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_maps: 0.10.12 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
test_core: 0.6.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
typed_data: 1.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
watcher: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
web_socket_channel: 2.4.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
webkit_inspection_protocol: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
yaml: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
flutter:
uses-material-design: true
assets:
- packages/flutter_gallery_assets/animated_images/animated_flutter_lgtm.gif
- packages/flutter_gallery_assets/food/butternut_squash_soup.png
- packages/flutter_gallery_assets/food/cherry_pie.png
- assets/999x1000.png
- assets/Icon-192.png
# The following assets are required for running Flutter Gallery benchmarks.
- packages/flutter_gallery_assets/assets/icons/settings/settings_light.flr
- packages/flutter_gallery_assets/assets/icons/settings/settings_dark.flr
- packages/flutter_gallery_assets/assets/studies/shrine_card_dark.png
- packages/flutter_gallery_assets/assets/studies/starter_card.png
- packages/flutter_gallery_assets/assets/studies/starter_card_dark.png
- packages/flutter_gallery_assets/assets/studies/fortnightly_card_dark.png
- packages/flutter_gallery_assets/assets/studies/rally_card_dark.png
- packages/flutter_gallery_assets/assets/studies/fortnightly_card.png
- packages/flutter_gallery_assets/assets/studies/crane_card.png
- packages/flutter_gallery_assets/assets/studies/shrine_card.png
- packages/flutter_gallery_assets/assets/studies/crane_card_dark.png
- packages/flutter_gallery_assets/assets/studies/rally_card.png
- packages/flutter_gallery_assets/assets/logo/flutter_logo.png
- packages/flutter_gallery_assets/assets/logo/flutter_logo_color.png
- packages/flutter_gallery_assets/assets/icons/cupertino/cupertino.png
- packages/flutter_gallery_assets/assets/icons/material/material.png
- packages/flutter_gallery_assets/assets/icons/reference/reference.png
- packages/flutter_gallery_assets/assets/demos/bottom_navigation_background.png
- packages/flutter_gallery_assets/fonts/GalleryIcons.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Merriweather-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Eczar-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Montserrat-Medium.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Rubik-Bold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Merriweather-Light.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/RobotoCondensed-Bold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Raleway-Medium.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Raleway-SemiBold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/LibreFranklin-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/RobotoMono-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/LibreFranklin-ExtraBold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/LibreFranklin-Bold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Oswald-SemiBold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Oswald-Medium.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/LibreFranklin-SemiBold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Raleway-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Montserrat-Bold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Merriweather-BoldItalic.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Raleway-Light.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Rubik-Medium.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Montserrat-SemiBold.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/RobotoCondensed-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/LibreFranklin-Medium.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Montserrat-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Rubik-Regular.ttf
- packages/flutter_gallery_assets/fonts/google_fonts/Eczar-SemiBold.ttf
- packages/flutter_gallery_assets/crane/destinations/eat_1.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_2.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_3.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_4.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_5.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_6.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_7.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_8.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_9.jpg
- packages/flutter_gallery_assets/crane/destinations/eat_10.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_0.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_1.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_2.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_3.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_4.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_5.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_6.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_7.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_8.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_9.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_10.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_11.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_12.jpg
- packages/flutter_gallery_assets/crane/destinations/fly_13.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_0.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_1.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_2.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_3.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_4.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_5.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_6.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_7.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_8.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_9.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_10.jpg
- packages/flutter_gallery_assets/crane/destinations/sleep_11.jpg
- packages/flutter_gallery_assets/crane/logo/logo.png
- packages/flutter_gallery_assets/fortnightly/fortnightly_army.png
- packages/flutter_gallery_assets/fortnightly/fortnightly_bees.jpg
- packages/flutter_gallery_assets/fortnightly/fortnightly_chart.png
- packages/flutter_gallery_assets/fortnightly/fortnightly_fabrics.png
- packages/flutter_gallery_assets/fortnightly/fortnightly_feminists.jpg
- packages/flutter_gallery_assets/fortnightly/fortnightly_gas.png
- packages/flutter_gallery_assets/fortnightly/fortnightly_healthcare.jpg
- packages/flutter_gallery_assets/fortnightly/fortnightly_stocks.png
- packages/flutter_gallery_assets/fortnightly/fortnightly_title.png
- packages/flutter_gallery_assets/fortnightly/fortnightly_war.png
- packages/flutter_gallery_assets/places/india_chennai_flower_market.png
- packages/flutter_gallery_assets/places/india_thanjavur_market.png
- packages/flutter_gallery_assets/places/india_tanjore_bronze_works.png
- packages/flutter_gallery_assets/places/india_tanjore_market_merchant.png
- packages/flutter_gallery_assets/places/india_tanjore_thanjavur_temple.png
- packages/flutter_gallery_assets/places/india_pondicherry_salt_farm.png
- packages/flutter_gallery_assets/places/india_chennai_highway.png
- packages/flutter_gallery_assets/places/india_chettinad_silk_maker.png
- packages/flutter_gallery_assets/places/india_tanjore_thanjavur_temple_carvings.png
- packages/flutter_gallery_assets/places/india_chettinad_produce.png
- packages/flutter_gallery_assets/places/india_tanjore_market_technology.png
- packages/flutter_gallery_assets/places/india_pondicherry_beach.png
- packages/flutter_gallery_assets/places/india_pondicherry_fisherman.png
- packages/flutter_gallery_assets/splash_effects/splash_effect_1.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_2.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_3.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_4.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_5.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_6.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_7.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_8.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_9.gif
- packages/flutter_gallery_assets/splash_effects/splash_effect_10.gif
# The following font is required for running Flutter Gallery benchmarks.
fonts:
- family: GalleryIcons
fonts:
- asset: packages/flutter_gallery_assets/fonts/GalleryIcons.ttf
# PUBSPEC CHECKSUM: 56bd
| flutter/dev/benchmarks/macrobenchmarks/pubspec.yaml/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/pubspec.yaml",
"repo_id": "flutter",
"token_count": 5500
} | 512 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:macrobenchmarks/common.dart';
import 'package:macrobenchmarks/main.dart';
Future<void> endOfAnimation() async {
do {
await SchedulerBinding.instance.endOfFrame;
} while (SchedulerBinding.instance.hasScheduledFrame);
}
Future<void> main() async {
runApp(const MacrobenchmarksApp(initialRoute: kHeavyGridViewRouteName));
await endOfAnimation();
await Future<void>.delayed(const Duration(milliseconds: 50));
debugPrint('==== MEMORY BENCHMARK ==== READY ====');
}
| flutter/dev/benchmarks/macrobenchmarks/test_memory/heavy_gridview.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/test_memory/heavy_gridview.dart",
"repo_id": "flutter",
"token_count": 249
} | 513 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart' show collectAllElementsFrom;
import '../common.dart';
const int _kNumIters = 10000;
Future<void> main() async {
assert(false, "Don't run benchmarks in debug mode! Use 'flutter run --release'.");
runApp(MaterialApp(
home: Scaffold(
body: GridView.count(
crossAxisCount: 5,
children: List<Widget>.generate(25, (int index) {
return Center(
child: Scaffold(
appBar: AppBar(
title: Text('App $index'),
actions: const <Widget>[
Icon(Icons.help),
Icon(Icons.add),
Icon(Icons.ac_unit),
],
),
body: const Column(
children: <Widget>[
Text('Item 1'),
Text('Item 2'),
Text('Item 3'),
Text('Item 4'),
],
),
),
);
}),
),
),
));
// Lists may not be scrolled into frame in landscape.
SystemChrome.setPreferredOrientations(<DeviceOrientation>[
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
// Wait for frame rendering to stabilize.
for (int i = 0; i < 5; i++) {
await SchedulerBinding.instance.endOfFrame;
}
final Stopwatch watch = Stopwatch();
print('flutter_test allElements benchmark... (${WidgetsBinding.instance.rootElement})');
// Make sure we get enough elements to process for consistent benchmark runs
int elementCount = collectAllElementsFrom(WidgetsBinding.instance.rootElement!, skipOffstage: false).length;
while (elementCount < 2458) {
await Future<void>.delayed(Duration.zero);
elementCount = collectAllElementsFrom(WidgetsBinding.instance.rootElement!, skipOffstage: false).length;
}
print('element count: $elementCount');
watch.start();
for (int i = 0; i < _kNumIters; i += 1) {
final List<Element> allElements = collectAllElementsFrom(
WidgetsBinding.instance.rootElement!,
skipOffstage: false,
).toList();
allElements.clear();
}
watch.stop();
final BenchmarkResultPrinter printer = BenchmarkResultPrinter();
printer.addResult(
description: 'All elements iterate',
value: watch.elapsedMicroseconds / _kNumIters,
unit: 'µs per iteration',
name: 'all_elements_iteration',
);
printer.printToStdout();
}
| flutter/dev/benchmarks/microbenchmarks/lib/foundation/all_elements_bench.dart/0 | {
"file_path": "flutter/dev/benchmarks/microbenchmarks/lib/foundation/all_elements_bench.dart",
"repo_id": "flutter",
"token_count": 1116
} | 514 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../common.dart';
const int _kNumIterations = 1000;
const int _kNumWarmUp = 100;
void main() {
assert(false, "Don't run benchmarks in debug mode! Use 'flutter run --release'.");
// Warm up lap
for (int i = 0; i < _kNumWarmUp; i += 1) {
sumIterable(generateIterableSyncStar());
sumIterable(generateIterableList());
sumIterable(Iterable<int>.generate(100, generate));
}
final Stopwatch watch = Stopwatch();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
sumIterable(generateIterableSyncStar());
}
final int traverseIterableSyncStar = watch.elapsedMicroseconds;
watch
..reset()
..start();
for (int i = 0; i < _kNumIterations; i += 1) {
sumIterable(generateIterableList());
}
final int traverseIterableList = watch.elapsedMicroseconds;
watch
..reset()
..start();
for (int i = 0; i < _kNumIterations; i += 1) {
sumIterable(Iterable<int>.generate(100, generate));
}
final int traverseIterableGenerated = watch.elapsedMicroseconds;
watch
..reset()
..start();
final BenchmarkResultPrinter printer = BenchmarkResultPrinter();
const double scale = 1000.0 / _kNumIterations;
printer.addResult(
description: 'traverseIterableSyncStar',
value: traverseIterableSyncStar * scale,
unit: 'ns per iteration',
name: 'traverseIterableSyncStar_iteration',
);
printer.addResult(
description: 'traverseIterableList',
value: traverseIterableList * scale,
unit: 'ns per iteration',
name: 'traverseIterableList_iteration',
);
printer.addResult(
description: 'traverseIterableGenerated',
value: traverseIterableGenerated * scale,
unit: 'ns per iteration',
name: 'traverseIterableGenerated_iteration',
);
printer.printToStdout();
}
int generate(int index) => index;
// Generate an Iterable using a sync* method.
Iterable<int> generateIterableSyncStar() sync* {
for (int i = 0; i < 100; i++) {
yield i;
}
}
// Generate an Iterable using a List.
Iterable<int> generateIterableList() {
final List<int> items = <int>[];
for (int i = 0; i < 100; i++) {
items.add(i);
}
return items;
}
int sumIterable(Iterable<int> values) {
int result = 0;
for (final int value in values) {
result += value;
}
return result;
}
| flutter/dev/benchmarks/microbenchmarks/lib/language/sync_star_bench.dart/0 | {
"file_path": "flutter/dev/benchmarks/microbenchmarks/lib/language/sync_star_bench.dart",
"repo_id": "flutter",
"token_count": 858
} | 515 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dev.flutter.multipleflutters
import android.os.Bundle
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import io.flutter.FlutterInjector
import io.flutter.embedding.android.FlutterFragment
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor
class MainActivity : FragmentActivity() {
private val numberOfFlutters = 20
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val root = LinearLayout(this)
root.layoutParams =
LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT,
)
root.orientation = LinearLayout.VERTICAL
root.weightSum = numberOfFlutters.toFloat()
val fragmentManager: FragmentManager = supportFragmentManager
setContentView(root)
val app = applicationContext as App
val dartEntrypoint =
DartExecutor.DartEntrypoint(
FlutterInjector.instance().flutterLoader().findAppBundlePath(),
"main",
)
val engines =
generateSequence(0) { it + 1 }
.take(numberOfFlutters)
.map { app.engines.createAndRunEngine(this, dartEntrypoint) }
.toList()
for (i in 0 until numberOfFlutters) {
val flutterContainer = FrameLayout(this)
root.addView(flutterContainer)
flutterContainer.id = 12345 + i
flutterContainer.layoutParams =
LinearLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT,
1.0f,
)
val engine = engines[i]
FlutterEngineCache.getInstance().put(i.toString(), engine)
val flutterFragment =
FlutterFragment.withCachedEngine(i.toString()).build<FlutterFragment>()
fragmentManager
.beginTransaction()
.add(
12345 + i,
flutterFragment,
)
.commit()
}
}
override fun onDestroy() {
for (i in 0 until numberOfFlutters) {
FlutterEngineCache.getInstance().remove(i.toString())
}
super.onDestroy()
}
}
| flutter/dev/benchmarks/multiple_flutters/android/app/src/main/java/dev/flutter/multipleflutters/MainActivity.kt/0 | {
"file_path": "flutter/dev/benchmarks/multiple_flutters/android/app/src/main/java/dev/flutter/multipleflutters/MainActivity.kt",
"repo_id": "flutter",
"token_count": 1230
} | 516 |
# platform_channels_benchmarks
The harness for running performance benchmark tests for Platform Channels.
If you want to run these benchmarks outside of devicelab you need to first run:
`flutter create --platforms="ios,android" --no-overwrite .`
| flutter/dev/benchmarks/platform_channels_benchmarks/README.md/0 | {
"file_path": "flutter/dev/benchmarks/platform_channels_benchmarks/README.md",
"repo_id": "flutter",
"token_count": 64
} | 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. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<application android:label="Stocks" android:icon="@mipmap/ic_launcher">
<activity android:name="io.flutter.embedding.android.FlutterActivity"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
| flutter/dev/benchmarks/test_apps/stocks/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "flutter/dev/benchmarks/test_apps/stocks/android/app/src/main/AndroidManifest.xml",
"repo_id": "flutter",
"token_count": 565
} | 518 |
{
"title": "Stocks",
"@title": {
"description": "Title for the Stocks application"
},
"market": "MARKET",
"@market": {
"description": "Label for the Market tab"
},
"portfolio": "PORTFOLIO",
"@portfolio": {
"description": "Label for the Portfolio tab"
}
}
| flutter/dev/benchmarks/test_apps/stocks/lib/i18n/stocks_en.arb/0 | {
"file_path": "flutter/dev/benchmarks/test_apps/stocks/lib/i18n/stocks_en.arb",
"repo_id": "flutter",
"token_count": 107
} | 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:analyzer/dart/analysis/results.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:path/path.dart' as path;
import '../utils.dart';
import 'analyze.dart';
// The comment pattern representing the "flutter_ignore" inline directive that
// indicates the line should be exempt from the stopwatch check.
final Pattern _ignoreStopwatch = RegExp(r'// flutter_ignore: .*stopwatch .*\(see analyze\.dart\)');
/// Use of Stopwatches can introduce test flakes as the logical time of a
/// stopwatch can fall out of sync with the mocked time of FakeAsync in testing.
/// The Clock object provides a safe stopwatch instead, which is paired with
/// FakeAsync as part of the test binding.
final AnalyzeRule noStopwatches = _NoStopwatches();
class _NoStopwatches implements AnalyzeRule {
final Map<ResolvedUnitResult, List<AstNode>> _errors = <ResolvedUnitResult, List<AstNode>>{};
@override
void applyTo(ResolvedUnitResult unit) {
final _StopwatchVisitor visitor = _StopwatchVisitor(unit);
unit.unit.visitChildren(visitor);
final List<AstNode> violationsInUnit = visitor.stopwatchAccessNodes;
if (violationsInUnit.isNotEmpty) {
_errors.putIfAbsent(unit, () => <AstNode>[]).addAll(violationsInUnit);
}
}
@override
void reportViolations(String workingDirectory) {
if (_errors.isEmpty) {
return;
}
String locationInFile(ResolvedUnitResult unit, AstNode node) {
return '${path.relative(path.relative(unit.path, from: workingDirectory))}:${unit.lineInfo.getLocation(node.offset).lineNumber}';
}
foundError(<String>[
for (final MapEntry<ResolvedUnitResult, List<AstNode>> entry in _errors.entries)
for (final AstNode node in entry.value)
'${locationInFile(entry.key, node)}: ${node.parent}',
'\n${bold}Stopwatches introduce flakes by falling out of sync with the FakeAsync used in testing.$reset',
'A Stopwatch that stays in sync with FakeAsync is available through the Gesture or Test bindings, through samplingClock.'
]);
}
@override
String toString() => 'No "Stopwatch"';
}
// This visitor finds invocation sites of Stopwatch (and subclasses) constructors
// and references to "external" functions that return a Stopwatch (and subclasses),
// including constructors, and put them in the stopwatchAccessNodes list.
class _StopwatchVisitor extends RecursiveAstVisitor<void> {
_StopwatchVisitor(this.compilationUnit);
final ResolvedUnitResult compilationUnit;
final List<AstNode> stopwatchAccessNodes = <AstNode>[];
final Map<ClassElement, bool> _isStopwatchClassElementCache = <ClassElement, bool>{};
bool _checkIfImplementsStopwatchRecursively(ClassElement classElement) {
if (classElement.library.isDartCore) {
return classElement.name == 'Stopwatch';
}
return classElement.allSupertypes.any((InterfaceType interface) {
final InterfaceElement interfaceElement = interface.element;
return interfaceElement is ClassElement && _implementsStopwatch(interfaceElement);
});
}
// The cached version, call this method instead of _checkIfImplementsStopwatchRecursively.
bool _implementsStopwatch(ClassElement classElement) {
return classElement.library.isDartCore
? classElement.name == 'Stopwatch'
:_isStopwatchClassElementCache.putIfAbsent(classElement, () => _checkIfImplementsStopwatchRecursively(classElement));
}
bool _isInternal(LibraryElement libraryElement) {
return path.isWithin(
compilationUnit.session.analysisContext.contextRoot.root.path,
libraryElement.source.fullName,
);
}
bool _hasTrailingFlutterIgnore(AstNode node) {
return compilationUnit.content
.substring(node.offset + node.length, compilationUnit.lineInfo.getOffsetOfLineAfter(node.offset + node.length))
.contains(_ignoreStopwatch);
}
// We don't care about directives or comments, skip them.
@override
void visitImportDirective(ImportDirective node) { }
@override
void visitExportDirective(ExportDirective node) { }
@override
void visitComment(Comment node) { }
@override
void visitConstructorName(ConstructorName node) {
final Element? element = node.staticElement;
if (element is! ConstructorElement) {
assert(false, '$element of $node is not a ConstructorElement.');
return;
}
final bool isAllowed = switch (element.returnType) {
InterfaceType(element: final ClassElement classElement) => !_implementsStopwatch(classElement),
InterfaceType(element: InterfaceElement()) => true,
};
if (isAllowed || _hasTrailingFlutterIgnore(node)) {
return;
}
stopwatchAccessNodes.add(node);
}
@override
void visitSimpleIdentifier(SimpleIdentifier node) {
final bool isAllowed = switch (node.staticElement) {
ExecutableElement(
returnType: DartType(element: final ClassElement classElement),
library: final LibraryElement libraryElement
) => _isInternal(libraryElement) || !_implementsStopwatch(classElement),
Element() || null => true,
};
if (isAllowed || _hasTrailingFlutterIgnore(node)) {
return;
}
stopwatchAccessNodes.add(node);
}
}
| flutter/dev/bots/custom_rules/no_stop_watches.dart/0 | {
"file_path": "flutter/dev/bots/custom_rules/no_stop_watches.dart",
"repo_id": "flutter",
"token_count": 1765
} | 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.
// This file is used by ../analyze_snippet_code_test.dart, which depends on the
// precise contents (including especially the comments) of this file.
// Examples can assume:
// int x = ''; // error (invalid_assignment)
/// ```dart
/// print(x);
/// ```
String? bar;
/// error: empty dart block
/// ```dart
/// ```
String? foo;
| flutter/dev/bots/test/analyze-snippet-code-test-input/short_but_still_broken.dart/0 | {
"file_path": "flutter/dev/bots/test/analyze-snippet-code-test-input/short_but_still_broken.dart",
"repo_id": "flutter",
"token_count": 151
} | 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.
// ignore_for_file: type=lint
bool isThereMeaningOfLife = true;
void main() {
if (isThereMeaningOfLife) {}
if(isThereMeaningOfLife) {}
//^
switch (isThereMeaningOfLife) {
case false:
case true:
}
switch(isThereMeaningOfLife) {
// ^
case false:
case true:
}
for (int index = 0; index < 10; index++) {}
for(int index = 0; index < 10; index++) {}
// ^
while (isThereMeaningOfLife) {}
while(isThereMeaningOfLife) {}
// ^
try {
} catch (e) {}
try {
} catch(e) {}
// ^
}
| flutter/dev/bots/test/analyze-test-input/root/packages/foo/spaces_after_flow.dart/0 | {
"file_path": "flutter/dev/bots/test/analyze-test-input/root/packages/foo/spaces_after_flow.dart",
"repo_id": "flutter",
"token_count": 265
} | 522 |
# Flutter Conductor
Command-line tool for managing a release of the Flutter SDK. Also see
https://github.com/flutter/flutter/wiki/Release-process for more information on
the release process.
## Requirements
Some basic requirements to conduct a release are:
- a Linux or macOS computer set up for Flutter development. The conductor does
not support Windows.
- git
- Mirrors on GitHub of the Flutter
[framework](https://github.com/flutter/flutter) and
[engine](https://github.com/flutter/engine) repositories.
For the best experience, it is recommended to use ssh protocol for connecting to
GitHub remote repositories (i.e. for `--framework-mirror` and `--engine-mirror`
specify the remote with the format `[email protected]:username/reponame`). If your
local ssh key is password-protected, it is recommended to use ssh-agent to
unlock your ssh key for the session; if you do not, each time the conductor
attempts to interact with a remote, the user will be prompted to enter their ssh
key password.
## Usage
The main entrypoint for the conductor is [bin/conductor](bin/conductor). For
brevity, the rest of this document will assume that this entrypoint is on the
shell path.
All available commands can be seen via:
`conductor help`
Releases are initialized with the `start` sub-command, like:
```
conductor start \
--candidate-branch=flutter-2.2-candidate.10 \
--release-channel=beta \
--github-username=kingOfDevelopers \
--engine-cherrypicks=72114dafe28c8700f1d5d629c6ae9d34172ba395 \
--framework-cherrypicks=a3e66b396746f6581b2b7efd1b0d0f0074215128,d8d853436206e86f416236b930e97779b143a100 \
--dart-revision=4511eb2a779a612d9d6b2012123575013e0aef12 \
```
The conductor will, based on the release channel and the presence/lack of
previous tags, determine which part of the release version should be
incremented. In the cases where this is not correct, the version can be
overridden with `--version-override=3.0.0`.
For more details on these command line arguments, see `conductor help start`.
This command will write to disk a state file that will persist until the release
is completed. If you already have a persistent state file, this command will
fail with an error message. To see the current status of the release (at any
time), issue the command:
`conductor status`
To delete a persistent state file (either because the release was successfully
completed or abandoned), use the command:
`conductor clean`
Once initializing the release, the conductor tool will issue instructions for
manual steps that must be executed by the user. At any time these instructions
can be seen via `conductor status`. Once these manual steps have been completed,
you can proceed to the next step by using the command:
`conductor next`
## Steps
Once the user has finished manual steps for each step, they proceed to the next
step with the command:
`conductor next`
### Apply Engine Cherrypicks
The tool will attempt to auto-apply all engine cherrypicks. However, any
cherrypicks that result in a merge conflict will be reverted and it is left to
the user to manually cherry-pick them (with the command `git cherry-pick
$REVISION`) and resolve the merge conflict in their checkout.
Once a PR is opened, the user must validate CI builds. If there are regressions
(or if the `licenses_check` fails, then
`//engine/ci/licenses_golden/licenses_third_party` must be updated to match the
output of the failing test), then the user must fix these tests in their local
checkout and push their changes again.
### Apply Framework Cherrypicks
The tool will attempt to auto-apply all framework cherrypicks. However, any
cherrypicks that result in a merge conflict will be reverted and it is left to
the user to manually cherry-pick them (with the command `git cherry-pick
$REVISION`) and resolve the merge conflict in their checkout.
### Publish Version
This step will add a version git tag to the final Framework commit and push it
to the upstream repository. The presence of a tag affects what the flutter CLI
tool reports the current version is.
### Publish Channel
This step will push the Framework candidate branch to the upstream release
branch (e.g. the `stable` branch). Once this push happens upstream, the release
has officially been published, and the code will be available to existing
Flutter users via `flutter upgrade`.
### Verify Release
For the final step, the user must manually verify that packaging builds have
finished successfully. The SDK compressed archives will not be available from
the website until the packaging build has finished. The conductor will produce
links to the dashboards for monitoring CI builds.
| flutter/dev/conductor/README.md/0 | {
"file_path": "flutter/dev/conductor/README.md",
"repo_id": "flutter",
"token_count": 1236
} | 523 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:io' as io;
import 'package:process/process.dart';
import 'git.dart';
import 'globals.dart';
import 'repository.dart';
import 'stdio.dart';
/// A service for rolling the SDK's pub packages to latest and open a PR upstream.
class PackageAutoroller {
PackageAutoroller({
required this.githubClient,
required this.token,
required this.framework,
required this.orgName,
required this.processManager,
required this.githubUsername,
Stdio? stdio,
}) {
this.stdio = stdio ?? VerboseStdio.local();
if (token.trim().isEmpty) {
throw Exception('empty token!');
}
if (githubClient.trim().isEmpty) {
throw Exception('Must provide path to GitHub client!');
}
if (orgName.trim().isEmpty) {
throw Exception('Must provide an orgName!');
}
}
late final Stdio stdio;
final FrameworkRepository framework;
final ProcessManager processManager;
/// Path to GitHub CLI client.
final String githubClient;
final String githubUsername;
/// GitHub API access token.
final String token;
static const String hostname = 'github.com';
String get prBody {
return '''
This PR was generated by the automated
[Pub packages autoroller](https://github.com/flutter/flutter/blob/main/dev/conductor/core/bin/packages_autoroller.dart).''';
}
/// Name of the feature branch to be opened on against the mirror repo.
///
/// We never re-use a previous branch, so the branch name ends in an index
/// number, which gets incremented for each roll.
late final Future<String> featureBranchName = (() async {
final List<String> remoteBranches = await framework.listRemoteBranches(framework.mirrorRemote!.name);
int x = 1;
String name(int index) => 'packages-autoroller-branch-$index';
while (remoteBranches.contains(name(x))) {
x += 1;
}
return name(x);
})();
void log(String message) {
stdio.printStatus(_redactToken(message));
}
/// Name of the GitHub organization to push the feature branch to.
final String orgName;
Future<void> roll() async {
try {
await authLogin();
final bool openPrAlready = await hasOpenPrs();
if (openPrAlready) {
// Don't open multiple roll PRs.
return;
}
final bool didUpdate = await updatePackages();
if (!didUpdate) {
log('Packages are already at latest.');
return;
}
await pushBranch();
await createPr(repository: await framework.checkoutDirectory);
await authLogout();
} on Exception catch (exception) {
final String message = _redactToken(exception.toString());
throw Exception('${exception.runtimeType}: $message');
}
}
// Ensure we don't leak the GitHub token in exception messages
String _redactToken(String message) => message.replaceAll(token, '[GitHub TOKEN]');
/// Attempt to update all pub packages.
///
/// Will return whether or not any changes were made.
Future<bool> updatePackages({
bool verbose = true,
}) async {
final String author = '$githubUsername <[email protected]>';
await framework.newBranch(await featureBranchName);
final io.Process flutterProcess = await framework.streamFlutter(<String>[
if (verbose) '--verbose',
'update-packages',
'--force-upgrade',
]);
final int exitCode = await flutterProcess.exitCode;
if (exitCode != 0) {
throw ConductorException('Failed to update packages with exit code $exitCode');
}
// If the git checkout is clean, then pub packages are already at latest that cleanly resolve.
if (await framework.gitCheckoutClean()) {
return false;
}
await framework.commit(
'roll packages',
addFirst: true,
author: author,
);
return true;
}
Future<void> pushBranch() async {
final String projectName = framework.mirrorRemote!.url.split(r'/').last;
// Encode the token into the remote URL for authentication to work
final String remote = 'https://$token@$hostname/$orgName/$projectName';
await framework.pushRef(
fromRef: await featureBranchName,
toRef: await featureBranchName,
remote: remote,
);
}
Future<void> authLogout() {
return cli(
<String>['auth', 'logout', '--hostname', hostname],
allowFailure: true,
);
}
Future<void> authLogin() {
return cli(
<String>[
'auth',
'login',
'--hostname',
hostname,
'--git-protocol',
'https',
'--with-token',
],
stdin: '$token\n',
);
}
static const String _prTitle = 'Roll pub packages';
/// Create a pull request on GitHub.
///
/// Depends on the gh cli tool.
Future<void> createPr({
required io.Directory repository,
String body = 'This PR was generated by `flutter update-packages --force-upgrade`.',
String base = FrameworkRepository.defaultBranch,
bool draft = false,
}) async {
const List<String> labels = <String>['tool', 'autosubmit'];
// We will wrap title and body in double quotes before delegating to gh
// binary
await cli(
<String>[
'pr',
'create',
'--title',
_prTitle,
'--body',
body.trim(),
'--head',
'$orgName:${await featureBranchName}',
'--base',
base,
for (final String label in labels) ...<String>['--label', label],
if (draft)
'--draft',
],
workingDirectory: repository.path,
);
}
Future<void> help([List<String>? args]) {
return cli(<String>[
'help',
...?args,
]);
}
/// Run a sub-process with the GitHub CLI client.
///
/// Will return STDOUT of the sub-process.
Future<String> cli(
List<String> args, {
bool allowFailure = false,
String? stdin,
String? workingDirectory,
}) async {
log('Executing "$githubClient ${args.join(' ')}" in $workingDirectory');
final io.Process process = await processManager.start(
<String>[githubClient, ...args],
workingDirectory: workingDirectory,
environment: <String, String>{},
);
final List<String> stderrStrings = <String>[];
final List<String> stdoutStrings = <String>[];
final Future<void> stdoutFuture = process.stdout
.transform(utf8.decoder)
.forEach(stdoutStrings.add);
final Future<void> stderrFuture = process.stderr
.transform(utf8.decoder)
.forEach(stderrStrings.add);
if (stdin != null) {
process.stdin.write(stdin);
await process.stdin.flush();
await process.stdin.close();
}
final int exitCode = await process.exitCode;
await Future.wait(<Future<Object?>>[
stdoutFuture,
stderrFuture,
]);
final String stderr = stderrStrings.join();
final String stdout = stdoutStrings.join();
if (!allowFailure && exitCode != 0) {
throw GitException(
'$stderr\n$stdout',
args,
);
}
log(stdout);
return stdout;
}
Future<bool> hasOpenPrs() async {
// gh pr list --author christopherfujino --repo flutter/flutter --state open --json number
final String openPrString = await cli(<String>[
'pr',
'list',
'--author',
githubUsername,
'--repo',
'flutter/flutter',
'--state',
'open',
'--search',
_prTitle,
// Return structured JSON with the PR numbers of open PRs
'--json',
'number',
]);
// This will be an array of objects, one for each open PR.
final List<Object?> openPrs = json.decode(openPrString) as List<Object?>;
// We are only interested in pub rolls, not devicelab flaky PRs
if (openPrs.isNotEmpty) {
log('$githubUsername already has open tool PRs:\n$openPrs');
return true;
}
return false;
}
}
| flutter/dev/conductor/core/lib/src/packages_autoroller.dart/0 | {
"file_path": "flutter/dev/conductor/core/lib/src/packages_autoroller.dart",
"repo_id": "flutter",
"token_count": 3030
} | 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:args/command_runner.dart';
import 'package:conductor_core/src/candidates.dart';
import 'package:conductor_core/src/repository.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.dart';
import './common.dart';
void main() {
group('candidates command', () {
const String flutterRoot = '/flutter';
const String flutterBinPath = '$flutterRoot/bin/flutter';
const String checkoutsParentDirectory = '$flutterRoot/dev/tools/';
const String remoteName = 'origin';
late MemoryFileSystem fileSystem;
late FakePlatform platform;
late TestStdio stdio;
late FakeProcessManager processManager;
final String operatingSystem = const LocalPlatform().operatingSystem;
setUp(() {
stdio = TestStdio();
fileSystem = MemoryFileSystem.test();
});
CommandRunner<void> createRunner({
required Checkouts checkouts,
}) {
final CandidatesCommand command = CandidatesCommand(
checkouts: checkouts,
flutterRoot: fileSystem.directory(flutterRoot),
);
return CommandRunner<void>('clean-test', '')..addCommand(command);
}
test('prints only branches from targeted remote', () async {
const String currentVersion = '1.2.3';
const String branch = 'flutter-1.3-candidate.0';
processManager = FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['git', 'fetch', remoteName],
),
const FakeCommand(
command: <String>[flutterBinPath, 'help'],
),
const FakeCommand(
command: <String>[flutterBinPath, '--version', '--machine'],
stdout: '{"frameworkVersion": "$currentVersion"}',
),
FakeCommand(
command: const <String>[
'git',
'branch',
'--no-color',
'--remotes',
'--list',
'$remoteName/*',
],
stdout: <String>[
'other-remote/flutter-5.0-candidate.0',
'$remoteName/$branch',
].join('\n'),
),
]);
final String pathSeparator = operatingSystem == 'windows' ? r'\' : '/';
platform = FakePlatform(
environment: <String, String>{
'HOME': <String>['path', 'to', 'home'].join(pathSeparator),
},
pathSeparator: pathSeparator,
);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(checkoutsParentDirectory),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final CommandRunner<void> runner = createRunner(checkouts: checkouts);
await runner.run(<String>['candidates', '--$kRemote', remoteName]);
expect(stdio.stdout.contains('currentVersion = $currentVersion'), true);
expect(stdio.stdout.contains(branch), true);
expect(stdio.stdout.contains('flutter-5.0-candidate.0'), false);
});
test('does not print branches older or equal to current version', () async {
const String currentVersion = '2.3.0-13.0.pre.48';
const String newBranch = 'flutter-2.4-candidate.0';
const String oldBranch = 'flutter-1.0-candidate.0';
const String currentBranch = 'flutter-2.3-candidate.13';
processManager = FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['git', 'fetch', remoteName],
),
const FakeCommand(
command: <String>[flutterBinPath, 'help'],
),
const FakeCommand(
command: <String>[flutterBinPath, '--version', '--machine'],
stdout: '{"frameworkVersion": "$currentVersion"}',
),
FakeCommand(
command: const <String>[
'git',
'branch',
'--no-color',
'--remotes',
'--list',
'$remoteName/*',
],
stdout: <String>[
'$remoteName/$oldBranch',
'$remoteName/$currentBranch',
'$remoteName/$newBranch',
].join('\n'),
),
]);
final String pathSeparator = operatingSystem == 'windows' ? r'\' : '/';
platform = FakePlatform(
environment: <String, String>{
'HOME': <String>['path', 'to', 'home'].join(pathSeparator),
},
pathSeparator: pathSeparator,
);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(checkoutsParentDirectory),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final CommandRunner<void> runner = createRunner(checkouts: checkouts);
await runner.run(<String>['candidates', '--$kRemote', remoteName]);
expect(stdio.stdout.contains('currentVersion = $currentVersion'), true);
expect(stdio.stdout.contains(newBranch), true);
expect(stdio.stdout.contains(oldBranch), false);
expect(stdio.stdout.contains(currentBranch), false);
});
}, onPlatform: <String, dynamic>{
'windows': const Skip('Flutter Conductor only supported on macos/linux'),
});
}
| flutter/dev/conductor/core/test/candidates_test.dart/0 | {
"file_path": "flutter/dev/conductor/core/test/candidates_test.dart",
"repo_id": "flutter",
"token_count": 2226
} | 525 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:io';
import 'package:flutter_devicelab/framework/apk_utils.dart';
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/framework/task_result.dart';
import 'package:flutter_devicelab/framework/utils.dart';
import 'package:path/path.dart' as path;
final String gradlew = Platform.isWindows ? 'gradlew.bat' : 'gradlew';
final String gradlewExecutable = Platform.isWindows ? '.\\$gradlew' : './$gradlew';
/// Tests that we respect storage proxy URLs in gradle dependencies.
Future<void> main() async {
await task(() async {
section('Find Java');
final String? javaHome = await findJavaHome();
if (javaHome == null) {
return TaskResult.failure('Could not find Java');
}
print('\nUsing JAVA_HOME=$javaHome');
section('Create project');
await runProjectTest((FlutterProject flutterProject) async {
await inDirectory(path.join(flutterProject.rootPath, 'android'), () async {
section('Insert gradle testing script');
final File build = File(path.join(
flutterProject.rootPath, 'android', 'app', 'build.gradle',
));
build.writeAsStringSync(
'''
task printEngineMavenUrl() {
doLast {
println project.repositories.find { it.name == 'maven' }.url
}
}
''',
mode: FileMode.append,
flush: true,
);
section('Checking default maven URL');
String gradleOutput = await eval(
gradlewExecutable,
<String>['printEngineMavenUrl', '-q'],
);
const LineSplitter splitter = LineSplitter();
List<String> outputLines = splitter.convert(gradleOutput);
String mavenUrl = outputLines.last;
print('Returned maven url: $mavenUrl');
String realm = File(
path.join(flutterDirectory.path, 'bin', 'internal', 'engine.realm'),
).readAsStringSync().trim();
if (realm.isNotEmpty) {
realm = '$realm/';
}
if (mavenUrl != 'https://storage.googleapis.com/${realm}download.flutter.io') {
throw TaskResult.failure(
'Expected Android engine maven dependency URL to '
'resolve to https://storage.googleapis.com/${realm}download.flutter.io. Got '
'$mavenUrl instead',
);
}
section('Checking overridden maven URL');
gradleOutput = await eval(
gradlewExecutable,
<String>['printEngineMavenUrl','-q'],
environment: <String, String>{
'FLUTTER_STORAGE_BASE_URL': 'https://my.special.proxy',
},
);
outputLines = splitter.convert(gradleOutput);
mavenUrl = outputLines.last;
if (mavenUrl != 'https://my.special.proxy/${realm}download.flutter.io') {
throw TaskResult.failure(
'Expected overridden Android engine maven '
'dependency URL to resolve to proxy location '
'https://my.special.proxy/${realm}download.flutter.io. Got '
'$mavenUrl instead',
);
}
});
});
return TaskResult.success(null);
});
}
| flutter/dev/devicelab/bin/tasks/engine_dependency_proxy_test.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/engine_dependency_proxy_test.dart",
"repo_id": "flutter",
"token_count": 1395
} | 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 'dart:io';
import 'package:flutter_devicelab/framework/apk_utils.dart';
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/framework/task_result.dart';
import 'package:flutter_devicelab/framework/utils.dart';
import 'package:path/path.dart' as path;
Future<void> main() async {
await task(() async {
try {
await runPluginProjectTest((FlutterPluginProject pluginProject) async {
section('APK content for task assembleDebug without explicit target platform');
await inDirectory(pluginProject.exampleAndroidPath, () {
return flutter(
'build',
options: <String>[
'apk',
'--debug',
'--verbose',
],
);
});
Iterable<String> apkFiles = await getFilesInApk(pluginProject.debugApkPath);
checkCollectionContains<String>(<String>[
...flutterAssets,
...debugAssets,
...baseApkFiles,
'lib/armeabi-v7a/libflutter.so',
'lib/arm64-v8a/libflutter.so',
// Debug mode intentionally includes `x86` and `x86_64`.
'lib/x86/libflutter.so',
'lib/x86_64/libflutter.so',
], apkFiles);
checkCollectionDoesNotContain<String>(<String>[
'lib/arm64-v8a/libapp.so',
'lib/armeabi-v7a/libapp.so',
'lib/x86/libapp.so',
'lib/x86_64/libapp.so',
], apkFiles);
section('APK content for task assembleRelease without explicit target platform');
await inDirectory(pluginProject.exampleAndroidPath, () {
return flutter(
'build',
options: <String>[
'apk',
'--release',
'--verbose',
],
);
});
apkFiles = await getFilesInApk(pluginProject.releaseApkPath);
checkCollectionContains<String>(<String>[
...flutterAssets,
...baseApkFiles,
'lib/armeabi-v7a/libflutter.so',
'lib/armeabi-v7a/libapp.so',
'lib/arm64-v8a/libflutter.so',
'lib/arm64-v8a/libapp.so',
'lib/x86_64/libflutter.so',
'lib/x86_64/libapp.so',
], apkFiles);
checkCollectionDoesNotContain<String>(debugAssets, apkFiles);
section('APK content for task assembleRelease with target platform = android-arm, android-arm64');
await inDirectory(pluginProject.exampleAndroidPath, () {
return flutter(
'build',
options: <String>[
'apk',
'--release',
'--verbose',
'--target-platform=android-arm,android-arm64',
],
);
});
apkFiles = await getFilesInApk(pluginProject.releaseApkPath);
checkCollectionContains<String>(<String>[
...flutterAssets,
...baseApkFiles,
'lib/armeabi-v7a/libflutter.so',
'lib/armeabi-v7a/libapp.so',
'lib/arm64-v8a/libflutter.so',
'lib/arm64-v8a/libapp.so',
], apkFiles);
checkCollectionDoesNotContain<String>(debugAssets, apkFiles);
section('APK content for task assembleRelease with '
'target platform = android-arm, android-arm64 and split per ABI');
await inDirectory(pluginProject.exampleAndroidPath, () {
return flutter(
'build',
options: <String>[
'apk',
'--release',
'--verbose',
'--split-per-abi',
'--target-platform=android-arm,android-arm64',
],
);
});
final Iterable<String> armApkFiles = await getFilesInApk(pluginProject.releaseArmApkPath);
checkCollectionContains<String>(<String>[
...flutterAssets,
...baseApkFiles,
'lib/armeabi-v7a/libflutter.so',
'lib/armeabi-v7a/libapp.so',
], armApkFiles);
checkCollectionDoesNotContain<String>(debugAssets, armApkFiles);
final Iterable<String> arm64ApkFiles = await getFilesInApk(pluginProject.releaseArm64ApkPath);
checkCollectionContains<String>(<String>[
...flutterAssets,
...baseApkFiles,
'lib/arm64-v8a/libflutter.so',
'lib/arm64-v8a/libapp.so',
], arm64ApkFiles);
checkCollectionDoesNotContain<String>(debugAssets, arm64ApkFiles);
});
await runProjectTest((FlutterProject project) async {
section('gradlew assembleRelease');
await inDirectory(project.rootPath, () {
return flutter(
'build',
options: <String>[
'apk',
'--release',
'--verbose',
],
);
});
// When the platform-target isn't specified, we generate the snapshots
// for arm and arm64.
final List<String> targetPlatforms = <String>[
'arm64-v8a',
'armeabi-v7a',
];
for (final String targetPlatform in targetPlatforms) {
final String androidArmSnapshotPath = path.join(
project.rootPath,
'build',
'app',
'intermediates',
'flutter',
'release',
targetPlatform,
);
final String sharedLibrary = path.join(androidArmSnapshotPath, 'app.so');
if (!File(sharedLibrary).existsSync()) {
throw TaskResult.failure("Shared library doesn't exist");
}
}
});
return TaskResult.success(null);
} on TaskResult catch (taskResult) {
return taskResult;
} catch (e) {
return TaskResult.failure(e.toString());
}
});
}
| flutter/dev/devicelab/bin/tasks/gradle_plugin_fat_apk_test.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/gradle_plugin_fat_apk_test.dart",
"repo_id": "flutter",
"token_count": 2870
} | 527 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:flutter_devicelab/framework/apk_utils.dart';
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/framework/task_result.dart';
import 'package:flutter_devicelab/framework/utils.dart';
import 'package:path/path.dart' as path;
final String gradlew = Platform.isWindows ? 'gradlew.bat' : 'gradlew';
final String gradlewExecutable = Platform.isWindows ? '.\\$gradlew' : './$gradlew';
/// Tests that the Android app containing a Flutter module can be built when
/// it has custom build types and flavors.
Future<void> main() async {
await task(() async {
section('Find Java');
final String? javaHome = await findJavaHome();
if (javaHome == null) {
return TaskResult.failure('Could not find Java');
}
print('\nUsing JAVA_HOME=$javaHome');
section('Create Flutter module project');
await flutter(
'precache',
options: <String>['--android', '--no-ios'],
);
final Directory tempDir = Directory.systemTemp.createTempSync('flutter_module_test.');
final Directory projectDir = Directory(path.join(tempDir.path, 'hello'));
try {
await inDirectory(tempDir, () async {
await flutter(
'create',
options: <String>['--org', 'io.flutter.devicelab', '--template=module', 'hello'],
);
});
section('Run flutter pub get');
await inDirectory(projectDir, () async {
await flutter(
'pub',
options: <String>['get'],
);
});
section('Add to existing Android app');
final Directory hostAppDir = Directory(path.join(tempDir.path, 'hello_host_app_with_custom_build'));
mkdir(hostAppDir);
recursiveCopy(
Directory(
path.join(
flutterDirectory.path,
'dev',
'integration_tests',
'module_host_with_custom_build_v2_embedding',
),
),
hostAppDir,
);
copy(
File(path.join(projectDir.path, '.android', gradlew)),
hostAppDir,
);
copy(
File(path.join(projectDir.path, '.android', 'gradle', 'wrapper', 'gradle-wrapper.jar')),
Directory(path.join(hostAppDir.path, 'gradle', 'wrapper')),
);
Future<void> clean() async {
section('Clean');
await inDirectory(hostAppDir, () async {
await exec(gradlewExecutable,
<String>['clean'],
environment: <String, String>{
'JAVA_HOME': javaHome,
},
);
});
}
if (!Platform.isWindows) {
section('Make $gradlewExecutable executable');
await inDirectory(hostAppDir, () async {
await exec('chmod', <String>['+x', gradlewExecutable]);
});
}
section('Build debug APKs');
section('Run app:assembleDemoDebug');
await inDirectory(hostAppDir, () async {
await exec(gradlewExecutable,
<String>['app:assembleDemoDebug'],
environment: <String, String>{
'JAVA_HOME': javaHome,
},
);
});
final String demoDebugApk = path.join(
hostAppDir.path,
'app',
'build',
'outputs',
'apk',
'demo',
'debug',
'app-demo-debug.apk',
);
if (!exists(File(demoDebugApk))) {
return TaskResult.failure('Failed to build app-demo-debug.apk');
}
section('Verify snapshots in app-demo-debug.apk');
checkCollectionContains<String>(<String>[
...flutterAssets,
...debugAssets,
], await getFilesInApk(demoDebugApk));
await clean();
// Change the order of the task and ensure that flutter_assets are in the APK.
// https://github.com/flutter/flutter/pull/41333
section('Run app:assembleDemoDebug - Merge assets before processing manifest');
await inDirectory(hostAppDir, () async {
await exec(gradlewExecutable,
<String>[
// Normally, `app:processDemoDebugManifest` runs before `app:mergeDemoDebugAssets`.
// In this case, we run `app:mergeDemoDebugAssets` first.
'app:mergeDemoDebugAssets',
'app:processDemoDebugManifest',
'app:assembleDemoDebug',
],
environment: <String, String>{
'JAVA_HOME': javaHome,
},
);
});
final String demoDebugApk2 = path.join(
hostAppDir.path,
'app',
'build',
'outputs',
'apk',
'demo',
'debug',
'app-demo-debug.apk',
);
if (!exists(File(demoDebugApk2))) {
return TaskResult.failure('Failed to build app-demo-debug.apk');
}
section('Verify snapshots in app-demo-debug.apk');
checkCollectionContains<String>(<String>[
...flutterAssets,
...debugAssets,
], await getFilesInApk(demoDebugApk2));
await clean();
section('Run app:assembleDemoStaging');
await inDirectory(hostAppDir, () async {
await exec(gradlewExecutable,
<String>['app:assembleDemoStaging'],
environment: <String, String>{
'JAVA_HOME': javaHome,
},
);
});
final String demoStagingApk = path.join(
hostAppDir.path,
'app',
'build',
'outputs',
'apk',
'demo',
'staging',
'app-demo-staging.apk',
);
if (!exists(File(demoStagingApk))) {
return TaskResult.failure('Failed to build app-demo-staging.apk');
}
section('Verify snapshots in app-demo-staging.apk');
checkCollectionContains<String>(<String>[
...flutterAssets,
...debugAssets,
], await getFilesInApk(demoStagingApk));
await clean();
section('Build release APKs');
section('Run app:assembleDemoRelease');
await inDirectory(hostAppDir, () async {
await exec(gradlewExecutable,
<String>['app:assembleDemoRelease'],
environment: <String, String>{
'JAVA_HOME': javaHome,
},
);
});
final String demoReleaseApk = path.join(
hostAppDir.path,
'app',
'build',
'outputs',
'apk',
'demo',
'release',
'app-demo-release-unsigned.apk',
);
if (!exists(File(demoReleaseApk))) {
return TaskResult.failure('Failed to build app-demo-release-unsigned.apk');
}
section('Verify AOT ELF in app-demo-release-unsigned.apk');
checkCollectionContains<String>(<String>[
...flutterAssets,
'lib/arm64-v8a/libflutter.so',
'lib/arm64-v8a/libapp.so',
'lib/armeabi-v7a/libflutter.so',
'lib/armeabi-v7a/libapp.so',
], await getFilesInApk(demoReleaseApk));
await clean();
section('Run app:assembleDemoProd');
await inDirectory(hostAppDir, () async {
await exec(gradlewExecutable,
<String>['app:assembleDemoProd'],
environment: <String, String>{
'JAVA_HOME': javaHome,
},
);
});
final String demoProdApk = path.join(
hostAppDir.path,
'app',
'build',
'outputs',
'apk',
'demo',
'prod',
'app-demo-prod-unsigned.apk',
);
if (!exists(File(demoProdApk))) {
return TaskResult.failure('Failed to build app-demo-prod-unsigned.apk');
}
section('Verify AOT ELF in app-demo-prod-unsigned.apk');
checkCollectionContains<String>(<String>[
...flutterAssets,
'lib/arm64-v8a/libapp.so',
'lib/arm64-v8a/libflutter.so',
'lib/armeabi-v7a/libapp.so',
'lib/armeabi-v7a/libflutter.so',
], await getFilesInApk(demoProdApk));
return TaskResult.success(null);
} on TaskResult catch (taskResult) {
return taskResult;
} catch (e) {
return TaskResult.failure(e.toString());
} finally {
rmTree(tempDir);
}
});
}
| flutter/dev/devicelab/bin/tasks/module_host_with_custom_build_test.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/module_host_with_custom_build_test.dart",
"repo_id": "flutter",
"token_count": 3838
} | 528 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/tasks/plugin_tests.dart';
Future<void> main() async {
await task(combine(<TaskFunction>[
PluginTest('ios', <String>['-i', 'objc', '--platforms=ios']).call,
PluginTest('ios', <String>['-i', 'swift', '--platforms=ios']).call,
// Test that app builds with Flutter as a transitive dependency.
PluginTest('ios', <String>['-i', 'objc', '--platforms=ios'], cocoapodsTransitiveFlutterDependency: true).call,
// Test that Dart-only plugins are supported.
PluginTest('ios', <String>['--platforms=ios'], dartOnlyPlugin: true).call,
// Test that shared darwin directories are supported.
PluginTest('ios', <String>['--platforms=ios,macos'], sharedDarwinSource: true).call,
// Test that FFI plugins are supported.
PluginTest('ios', <String>['--platforms=ios'], template: 'plugin_ffi').call,
]));
}
| flutter/dev/devicelab/bin/tasks/plugin_test_ios.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/plugin_test_ios.dart",
"repo_id": "flutter",
"token_count": 367
} | 529 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter_devicelab/framework/devices.dart';
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/framework/task_result.dart';
import 'package:flutter_devicelab/framework/utils.dart';
import 'package:path/path.dart' as path;
import 'package:vm_service/vm_service.dart';
import 'package:vm_service/vm_service_io.dart';
void main() {
task(() async {
int? vmServicePort;
final Device device = await devices.workingDevice;
await device.unlock();
final Directory appDir = dir(path.join(flutterDirectory.path, 'dev/integration_tests/ui'));
await inDirectory(appDir, () async {
final Completer<void> ready = Completer<void>();
late bool ok;
print('run: starting...');
final Process run = await startFlutter(
'run',
options: <String>['--verbose', '--no-fast-start', '--no-publish-port', '--disable-service-auth-codes', '-d', device.deviceId, 'lib/main.dart'],
);
run.stdout
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen((String line) {
print('run:stdout: $line');
if (vmServicePort == null) {
vmServicePort = parseServicePort(line);
if (vmServicePort != null) {
print('service protocol connection available at port $vmServicePort');
print('run: ready!');
ready.complete();
ok = true;
}
}
});
run.stderr
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen((String line) {
stderr.writeln('run:stderr: $line');
});
unawaited(run.exitCode.then<void>((int exitCode) { ok = false; }));
await Future.any<dynamic>(<Future<dynamic>>[ ready.future, run.exitCode ]);
if (!ok) {
throw 'Failed to run test app.';
}
final VmService client = await vmServiceConnectUri('ws://localhost:$vmServicePort/ws');
final VM vm = await client.getVM();
final IsolateRef isolate = vm.isolates!.first;
final StreamController<Event> frameEventsController = StreamController<Event>();
final StreamController<Event> navigationEventsController = StreamController<Event>();
try {
await client.streamListen(EventKind.kExtension);
} catch (err) {
// Do nothing on errors.
}
client.onExtensionEvent.listen((Event event) {
if (event.extensionKind == 'Flutter.Frame') {
frameEventsController.add(event);
} else if (event.extensionKind == 'Flutter.Navigation') {
navigationEventsController.add(event);
}
});
final Stream<Event> frameEvents = frameEventsController.stream;
final Stream<Event> navigationEvents = navigationEventsController.stream;
print('reassembling app...');
final Future<Event> frameFuture = frameEvents.first;
await client.callServiceExtension('ext.flutter.reassemble', isolateId: isolate.id);
// ensure we get an event
final Event event = await frameFuture;
print('${event.kind}: ${event.data}');
// validate the fields
// {number: 8, startTime: 0, elapsed: 1437, build: 600, raster: 800}
print(event.extensionData!.data);
expect(event.extensionData!.data['number'] is int);
expect((event.extensionData!.data['number'] as int) >= 0);
expect(event.extensionData!.data['startTime'] is int);
expect((event.extensionData!.data['startTime'] as int) >= 0);
expect(event.extensionData!.data['elapsed'] is int);
expect((event.extensionData!.data['elapsed'] as int) >= 0);
expect(event.extensionData!.data['build'] is int);
expect((event.extensionData!.data['build'] as int) >= 0);
expect(event.extensionData!.data['raster'] is int);
expect((event.extensionData!.data['raster'] as int) >= 0);
final Future<Event> navigationFuture = navigationEvents.first;
// This tap triggers a navigation event.
unawaited(device.tap(100, 200));
final Event navigationEvent = await navigationFuture;
// validate the fields
expect(navigationEvent.extensionData!.data['route'] is Map<dynamic, dynamic>);
final Map<dynamic, dynamic> route = navigationEvent.extensionData!.data['route'] as Map<dynamic, dynamic>;
expect(route['description'] is String);
expect(route['settings'] is Map<dynamic, dynamic>);
final Map<dynamic, dynamic> settings = route['settings'] as Map<dynamic, dynamic>;
expect(settings.containsKey('name'));
run.stdin.write('q');
final int result = await run.exitCode;
if (result != 0) {
throw 'Received unexpected exit code $result from run process.';
}
});
return TaskResult.success(null);
});
}
void expect(bool value) {
if (!value) {
throw 'failed assertion in service extensions test';
}
}
| flutter/dev/devicelab/bin/tasks/service_extensions_test.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/service_extensions_test.dart",
"repo_id": "flutter",
"token_count": 1957
} | 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 'dart:math' as math;
import 'task_result.dart';
const String kBenchmarkTypeKeyName = 'benchmark_type';
const String kBenchmarkVersionKeyName = 'version';
const String kLocalEngineKeyName = 'local_engine';
const String kLocalEngineHostKeyName = 'local_engine_host';
const String kTaskNameKeyName = 'task_name';
const String kRunStartKeyName = 'run_start';
const String kRunEndKeyName = 'run_end';
const String kAResultsKeyName = 'default_results';
const String kBResultsKeyName = 'local_engine_results';
const String kBenchmarkResultsType = 'A/B summaries';
const String kBenchmarkABVersion = '1.0';
enum FieldJustification { LEFT, RIGHT, CENTER }
/// Collects data from an A/B test and produces a summary for human evaluation.
///
/// See [printSummary] for more.
class ABTest {
ABTest({required this.localEngine, required this.localEngineHost, required this.taskName})
: runStart = DateTime.now(),
_aResults = <String, List<double>>{},
_bResults = <String, List<double>>{};
ABTest.fromJsonMap(Map<String, dynamic> jsonResults)
: localEngine = jsonResults[kLocalEngineKeyName] as String,
localEngineHost = jsonResults[kLocalEngineHostKeyName] as String,
taskName = jsonResults[kTaskNameKeyName] as String,
runStart = DateTime.parse(jsonResults[kRunStartKeyName] as String),
_runEnd = DateTime.parse(jsonResults[kRunEndKeyName] as String),
_aResults = _convertFrom(jsonResults[kAResultsKeyName] as Map<String, dynamic>),
_bResults = _convertFrom(jsonResults[kBResultsKeyName] as Map<String, dynamic>);
final String localEngine;
final String localEngineHost;
final String taskName;
final DateTime runStart;
DateTime? _runEnd;
DateTime? get runEnd => _runEnd;
final Map<String, List<double>> _aResults;
final Map<String, List<double>> _bResults;
static Map<String, List<double>> _convertFrom(dynamic results) {
final Map<String, dynamic> resultMap = results as Map<String, dynamic>;
return <String, List<double>> {
for (final String key in resultMap.keys)
key: (resultMap[key] as List<dynamic>).cast<double>(),
};
}
/// Adds the result of a single A run of the benchmark.
///
/// The result may contain multiple score keys.
///
/// [result] is expected to be a serialization of [TaskResult].
void addAResult(TaskResult result) {
if (_runEnd != null) {
throw StateError('Cannot add results to ABTest after it is finalized');
}
_addResult(result, _aResults);
}
/// Adds the result of a single B run of the benchmark.
///
/// The result may contain multiple score keys.
///
/// [result] is expected to be a serialization of [TaskResult].
void addBResult(TaskResult result) {
if (_runEnd != null) {
throw StateError('Cannot add results to ABTest after it is finalized');
}
_addResult(result, _bResults);
}
void finalize() {
_runEnd = DateTime.now();
}
Map<String, dynamic> get jsonMap => <String, dynamic>{
kBenchmarkTypeKeyName: kBenchmarkResultsType,
kBenchmarkVersionKeyName: kBenchmarkABVersion,
kLocalEngineKeyName: localEngine,
kLocalEngineHostKeyName: localEngineHost,
kTaskNameKeyName: taskName,
kRunStartKeyName: runStart.toIso8601String(),
kRunEndKeyName: runEnd!.toIso8601String(),
kAResultsKeyName: _aResults,
kBResultsKeyName: _bResults,
};
static void updateColumnLengths(List<int> lengths, List<String?> results) {
for (int column = 0; column < lengths.length; column++) {
if (results[column] != null) {
lengths[column] = math.max(lengths[column], results[column]?.length ?? 0);
}
}
}
static void formatResult(StringBuffer buffer,
List<int> lengths,
List<FieldJustification> aligns,
List<String?> values) {
for (int column = 0; column < lengths.length; column++) {
final int len = lengths[column];
String? value = values[column];
if (value == null) {
value = ''.padRight(len);
} else {
switch (aligns[column]) {
case FieldJustification.LEFT:
value = value.padRight(len);
case FieldJustification.RIGHT:
value = value.padLeft(len);
case FieldJustification.CENTER:
value = value.padLeft((len + value.length) ~/2);
value = value.padRight(len);
}
}
if (column > 0) {
value = value.padLeft(len+1);
}
buffer.write(value);
}
buffer.writeln();
}
/// Returns the summary as a tab-separated spreadsheet.
///
/// This value can be copied straight to a Google Spreadsheet for further analysis.
String asciiSummary() {
final Map<String, _ScoreSummary> summariesA = _summarize(_aResults);
final Map<String, _ScoreSummary> summariesB = _summarize(_bResults);
final List<List<String?>> tableRows = <List<String?>>[
for (final String scoreKey in <String>{...summariesA.keys, ...summariesB.keys})
<String?>[
scoreKey,
summariesA[scoreKey]?.averageString, summariesA[scoreKey]?.noiseString,
summariesB[scoreKey]?.averageString, summariesB[scoreKey]?.noiseString,
summariesA[scoreKey]?.improvementOver(summariesB[scoreKey]),
],
];
final List<String> titles = <String>[
'Score',
'Average A', '(noise)',
'Average B', '(noise)',
'Speed-up',
];
final List<FieldJustification> alignments = <FieldJustification>[
FieldJustification.LEFT,
FieldJustification.RIGHT, FieldJustification.LEFT,
FieldJustification.RIGHT, FieldJustification.LEFT,
FieldJustification.CENTER,
];
final List<int> lengths = List<int>.filled(6, 0);
updateColumnLengths(lengths, titles);
for (final List<String?> row in tableRows) {
updateColumnLengths(lengths, row);
}
final StringBuffer buffer = StringBuffer();
formatResult(buffer, lengths,
<FieldJustification>[
FieldJustification.CENTER,
...alignments.skip(1),
], titles);
for (final List<String?> row in tableRows) {
formatResult(buffer, lengths, alignments, row);
}
return buffer.toString();
}
/// Returns unprocessed data collected by the A/B test formatted as
/// a tab-separated spreadsheet.
String rawResults() {
final StringBuffer buffer = StringBuffer();
for (final String scoreKey in _allScoreKeys) {
buffer.writeln('$scoreKey:');
buffer.write(' A:\t');
if (_aResults.containsKey(scoreKey)) {
for (final double score in _aResults[scoreKey]!) {
buffer.write('${score.toStringAsFixed(2)}\t');
}
} else {
buffer.write('N/A');
}
buffer.writeln();
buffer.write(' B:\t');
if (_bResults.containsKey(scoreKey)) {
for (final double score in _bResults[scoreKey]!) {
buffer.write('${score.toStringAsFixed(2)}\t');
}
} else {
buffer.write('N/A');
}
buffer.writeln();
}
return buffer.toString();
}
Set<String> get _allScoreKeys {
return <String>{
..._aResults.keys,
..._bResults.keys,
};
}
/// Returns the summary as a tab-separated spreadsheet.
///
/// This value can be copied straight to a Google Spreadsheet for further analysis.
String printSummary() {
final Map<String, _ScoreSummary> summariesA = _summarize(_aResults);
final Map<String, _ScoreSummary> summariesB = _summarize(_bResults);
final StringBuffer buffer = StringBuffer(
'Score\tAverage A (noise)\tAverage B (noise)\tSpeed-up\n',
);
for (final String scoreKey in _allScoreKeys) {
final _ScoreSummary? summaryA = summariesA[scoreKey];
final _ScoreSummary? summaryB = summariesB[scoreKey];
buffer.write('$scoreKey\t');
if (summaryA != null) {
buffer.write('${summaryA.averageString} ${summaryA.noiseString}\t');
} else {
buffer.write('\t');
}
if (summaryB != null) {
buffer.write('${summaryB.averageString} ${summaryB.noiseString}\t');
} else {
buffer.write('\t');
}
if (summaryA != null && summaryB != null) {
buffer.write('${summaryA.improvementOver(summaryB)}\t');
}
buffer.writeln();
}
return buffer.toString();
}
}
class _ScoreSummary {
_ScoreSummary({
required this.average,
required this.noise,
});
/// Average (arithmetic mean) of a series of values collected by a benchmark.
final double average;
/// The noise (standard deviation divided by [average]) in the collected
/// values.
final double noise;
String get averageString => average.toStringAsFixed(2);
String get noiseString => '(${_ratioToPercent(noise)})';
String improvementOver(_ScoreSummary? other) {
return other == null ? '' : '${(average / other.average).toStringAsFixed(2)}x';
}
}
void _addResult(TaskResult result, Map<String, List<double>> results) {
for (final String scoreKey in result.benchmarkScoreKeys ?? <String>[]) {
final double score = (result.data![scoreKey] as num).toDouble();
results.putIfAbsent(scoreKey, () => <double>[]).add(score);
}
}
Map<String, _ScoreSummary> _summarize(Map<String, List<double>> results) {
return results.map<String, _ScoreSummary>((String scoreKey, List<double> values) {
final double average = _computeAverage(values);
return MapEntry<String, _ScoreSummary>(scoreKey, _ScoreSummary(
average: average,
// If the average is zero, the benchmark got the perfect score with no noise.
noise: average > 0
? _computeStandardDeviationForPopulation(values) / average
: 0.0,
));
});
}
/// Computes the arithmetic mean (or average) of given [values].
double _computeAverage(Iterable<double> values) {
final double sum = values.reduce((double a, double b) => a + b);
return sum / values.length;
}
/// Computes population standard deviation.
///
/// Unlike sample standard deviation, which divides by N - 1, this divides by N.
///
/// See also:
///
/// * https://en.wikipedia.org/wiki/Standard_deviation
double _computeStandardDeviationForPopulation(Iterable<double> population) {
final double mean = _computeAverage(population);
final double sumOfSquaredDeltas = population.fold<double>(
0.0,
(double previous, num value) => previous += math.pow(value - mean, 2),
);
return math.sqrt(sumOfSquaredDeltas / population.length);
}
String _ratioToPercent(double value) {
return '${(value * 100).toStringAsFixed(2)}%';
}
| flutter/dev/devicelab/lib/framework/ab.dart/0 | {
"file_path": "flutter/dev/devicelab/lib/framework/ab.dart",
"repo_id": "flutter",
"token_count": 4041
} | 531 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as path;
import '../framework/framework.dart';
import '../framework/task_result.dart';
import '../framework/utils.dart';
const List<String> kSentinelStr = <String>[
'==== sentinel #1 ====',
'==== sentinel #2 ====',
'==== sentinel #3 ====',
];
/// Tests that Choreographer#doFrame finishes during application startup.
/// This test fails if the application hangs during this period.
/// https://ui.perfetto.dev/#!/?s=da6628c3a92456ae8fa3f345d0186e781da77e90fc8a64d073e9fee11d1e65
/// Regression test for https://github.com/flutter/flutter/issues/98973
TaskFunction androidChoreographerDoFrameTest({
Map<String, String>? environment,
}) {
final Directory tempDir = Directory.systemTemp
.createTempSync('flutter_devicelab_android_surface_recreation.');
return () async {
try {
section('Create app');
await inDirectory(tempDir, () async {
await flutter(
'create',
options: <String>[
'--platforms',
'android',
'app',
],
environment: environment,
);
});
final File mainDart = File(path.join(
tempDir.absolute.path,
'app',
'lib',
'main.dart',
));
if (!mainDart.existsSync()) {
return TaskResult.failure('${mainDart.path} does not exist');
}
section('Patch lib/main.dart');
await mainDart.writeAsString('''
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
print('${kSentinelStr[0]}');
await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
print('${kSentinelStr[1]}');
// If the Android UI thread is blocked, then this Future won't resolve.
await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
print('${kSentinelStr[2]}');
runApp(
Container(
decoration: BoxDecoration(
color: const Color(0xff7c94b6),
),
),
);
}
''', flush: true);
Future<TaskResult> runTestFor(String mode) async {
int nextCompleterIdx = 0;
final Map<String, Completer<void>> sentinelCompleters = <String, Completer<void>>{};
for (final String sentinel in kSentinelStr) {
sentinelCompleters[sentinel] = Completer<void>();
}
section('Flutter run (mode: $mode)');
late Process run;
await inDirectory(path.join(tempDir.path, 'app'), () async {
run = await startFlutter(
'run',
options: <String>['--$mode', '--verbose'],
);
});
int currSentinelIdx = 0;
final StreamSubscription<void> stdout = run.stdout
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen((String line) {
if (currSentinelIdx < sentinelCompleters.keys.length &&
line.contains(sentinelCompleters.keys.elementAt(currSentinelIdx))) {
sentinelCompleters.values.elementAt(currSentinelIdx).complete();
currSentinelIdx++;
print('stdout(MATCHED): $line');
} else {
print('stdout: $line');
}
});
final StreamSubscription<void> stderr = run.stderr
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen((String line) {
print('stderr: $line');
});
final Completer<void> exitCompleter = Completer<void>();
unawaited(run.exitCode.then((int exitCode) {
exitCompleter.complete();
}));
section('Wait for sentinels (mode: $mode)');
for (final Completer<void> completer in sentinelCompleters.values) {
if (nextCompleterIdx == 0) {
// Don't time out because we don't know how long it would take to get the first log.
await Future.any<dynamic>(
<Future<dynamic>>[
completer.future,
exitCompleter.future,
],
);
} else {
try {
// Time out since this should not take 1s after the first log was received.
await Future.any<dynamic>(
<Future<dynamic>>[
completer.future.timeout(const Duration(seconds: 1)),
exitCompleter.future,
],
);
} on TimeoutException {
break;
}
}
if (exitCompleter.isCompleted) {
// The process exited.
break;
}
nextCompleterIdx++;
}
section('Quit app (mode: $mode)');
run.stdin.write('q');
await exitCompleter.future;
section('Stop listening to stdout and stderr (mode: $mode)');
await stdout.cancel();
await stderr.cancel();
run.kill();
if (nextCompleterIdx == sentinelCompleters.values.length) {
return TaskResult.success(null);
}
final String nextSentinel = sentinelCompleters.keys.elementAt(nextCompleterIdx);
return TaskResult.failure('Expected sentinel `$nextSentinel` in mode $mode');
}
final TaskResult debugResult = await runTestFor('debug');
if (debugResult.failed) {
return debugResult;
}
final TaskResult profileResult = await runTestFor('profile');
if (profileResult.failed) {
return profileResult;
}
final TaskResult releaseResult = await runTestFor('release');
if (releaseResult.failed) {
return releaseResult;
}
return TaskResult.success(null);
} finally {
rmTree(tempDir);
}
};
}
| flutter/dev/devicelab/lib/tasks/android_choreographer_do_frame_test.dart/0 | {
"file_path": "flutter/dev/devicelab/lib/tasks/android_choreographer_do_frame_test.dart",
"repo_id": "flutter",
"token_count": 2665
} | 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 'dart:ffi';
import 'dart:io';
import 'package:path/path.dart' as path;
import '../framework/framework.dart';
import '../framework/ios.dart';
import '../framework/task_result.dart';
import '../framework/utils.dart';
/// Combines several TaskFunctions with trivial success value into one.
TaskFunction combine(List<TaskFunction> tasks) {
return () async {
for (final TaskFunction task in tasks) {
final TaskResult result = await task();
if (result.failed) {
return result;
}
}
return TaskResult.success(null);
};
}
/// Defines task that creates new Flutter project, adds a local and remote
/// plugin, and then builds the specified [buildTarget].
class PluginTest {
PluginTest(
this.buildTarget,
this.options, {
this.pluginCreateEnvironment,
this.appCreateEnvironment,
this.dartOnlyPlugin = false,
this.sharedDarwinSource = false,
this.template = 'plugin',
this.cocoapodsTransitiveFlutterDependency = false,
});
final String buildTarget;
final List<String> options;
final Map<String, String>? pluginCreateEnvironment;
final Map<String, String>? appCreateEnvironment;
final bool dartOnlyPlugin;
final bool sharedDarwinSource;
final String template;
final bool cocoapodsTransitiveFlutterDependency;
Future<TaskResult> call() async {
final Directory tempDir =
Directory.systemTemp.createTempSync('flutter_devicelab_plugin_test.');
// FFI plugins do not have support for `flutter test`.
// `flutter test` does not do a native build.
// Supporting `flutter test` would require invoking a native build.
final bool runFlutterTest = template != 'plugin_ffi';
try {
section('Create plugin');
final _FlutterProject plugin = await _FlutterProject.create(
tempDir, options, buildTarget,
name: 'plugintest', template: template, environment: pluginCreateEnvironment);
if (dartOnlyPlugin) {
await plugin.convertDefaultPluginToDartPlugin();
}
if (sharedDarwinSource) {
await plugin.convertDefaultPluginToSharedDarwinPlugin();
}
section('Test plugin');
if (runFlutterTest) {
await plugin.runFlutterTest();
if (!dartOnlyPlugin) {
await plugin.example.runNativeTests(buildTarget);
}
}
section('Create Flutter app');
final _FlutterProject app = await _FlutterProject.create(tempDir, options, buildTarget,
name: 'plugintestapp', template: 'app', environment: appCreateEnvironment);
try {
section('Add plugins');
await app.addPlugin('plugintest',
pluginPath: path.join('..', 'plugintest'));
await app.addPlugin('path_provider');
section('Build app');
await app.build(buildTarget, validateNativeBuildProject: !dartOnlyPlugin);
if (cocoapodsTransitiveFlutterDependency) {
section('Test app with Flutter as a transitive CocoaPods dependency');
await app.addCocoapodsTransitiveFlutterDependency();
await app.build(buildTarget, validateNativeBuildProject: !dartOnlyPlugin);
}
if (runFlutterTest) {
section('Test app');
await app.runFlutterTest();
}
// Validate local engine handling. Currently only implemented for macOS.
if (!dartOnlyPlugin) {
section('Validate local engine configuration');
final String fakeEngineSourcePath = path.join(tempDir.path, 'engine');
await _testLocalEngineConfiguration(app, fakeEngineSourcePath);
}
} finally {
await plugin.delete();
await app.delete();
}
return TaskResult.success(null);
} catch (e) {
return TaskResult.failure(e.toString());
} finally {
rmTree(tempDir);
}
}
Future<void> _testLocalEngineConfiguration(_FlutterProject app, String fakeEngineSourcePath) async {
// The tool requires that a directory that looks like an engine build
// actually exists when passing --local-engine, so create a fake skeleton.
final Directory buildDir = Directory(path.join(fakeEngineSourcePath, 'out', 'foo'));
buildDir.createSync(recursive: true);
// Currently this test is only implemented for macOS; it can be extended to
// others as needed.
if (buildTarget == 'macos') {
// When using a local engine, podhelper.rb will search for a "macos-"
// directory within the FlutterMacOS.xcframework, so create a dummy one.
Directory(
path.join(buildDir.path, 'FlutterMacOS.xcframework/macos-arm64_x86_64'),
).createSync(recursive: true);
// Clean before regenerating the config to ensure that the pod steps run.
await inDirectory(Directory(app.rootPath), () async {
await evalFlutter('clean');
});
await app.build(buildTarget, configOnly: true, localEngine: buildDir);
}
}
}
class _FlutterProject {
_FlutterProject(this.parent, this.name);
final Directory parent;
final String name;
String get rootPath => path.join(parent.path, name);
File get pubspecFile => File(path.join(rootPath, 'pubspec.yaml'));
_FlutterProject get example {
return _FlutterProject(Directory(path.join(rootPath)), 'example');
}
Future<void> addPlugin(String plugin, {String? pluginPath}) async {
final File pubspec = pubspecFile;
String content = await pubspec.readAsString();
final String dependency =
pluginPath != null ? '$plugin:\n path: $pluginPath' : '$plugin:';
content = content.replaceFirst(
'\ndependencies:\n',
'\ndependencies:\n $dependency\n',
);
await pubspec.writeAsString(content, flush: true);
}
/// Converts a plugin created from the standard template to a Dart-only
/// plugin.
Future<void> convertDefaultPluginToDartPlugin() async {
final String dartPluginClass = 'DartClassFor$name';
// Convert the metadata.
final File pubspec = pubspecFile;
String content = await pubspec.readAsString();
content = content.replaceAll(
RegExp(r' pluginClass: .*?\n'),
' dartPluginClass: $dartPluginClass\n',
);
await pubspec.writeAsString(content, flush: true);
// Add the Dart registration hook that the build will generate a call to.
final File dartCode = File(path.join(rootPath, 'lib', '$name.dart'));
content = await dartCode.readAsString();
content = '''
$content
class $dartPluginClass {
static void registerWith() {}
}
''';
await dartCode.writeAsString(content, flush: true);
// Remove any native plugin code.
const List<String> platforms = <String>[
'android',
'ios',
'linux',
'macos',
'windows',
];
for (final String platform in platforms) {
final Directory platformDir = Directory(path.join(rootPath, platform));
if (platformDir.existsSync()) {
await platformDir.delete(recursive: true);
}
}
}
/// Converts an iOS/macOS plugin created from the standard template to a shared
/// darwin directory plugin.
Future<void> convertDefaultPluginToSharedDarwinPlugin() async {
// Convert the metadata.
final File pubspec = pubspecFile;
String pubspecContent = await pubspec.readAsString();
const String originalIOSKey = '\n ios:\n';
const String originalMacOSKey = '\n macos:\n';
if (!pubspecContent.contains(originalIOSKey) || !pubspecContent.contains(originalMacOSKey)) {
print(pubspecContent);
throw TaskResult.failure('Missing expected darwin platform plugin keys');
}
pubspecContent = pubspecContent.replaceAll(
originalIOSKey,
'$originalIOSKey sharedDarwinSource: true\n'
);
pubspecContent = pubspecContent.replaceAll(
originalMacOSKey,
'$originalMacOSKey sharedDarwinSource: true\n'
);
await pubspec.writeAsString(pubspecContent, flush: true);
// Copy ios to darwin, and delete macos.
final Directory iosDir = Directory(path.join(rootPath, 'ios'));
final Directory darwinDir = Directory(path.join(rootPath, 'darwin'));
recursiveCopy(iosDir, darwinDir);
await iosDir.delete(recursive: true);
await Directory(path.join(rootPath, 'macos')).delete(recursive: true);
final File podspec = File(path.join(darwinDir.path, '$name.podspec'));
String podspecContent = await podspec.readAsString();
if (!podspecContent.contains('s.platform =')) {
print(podspecContent);
throw TaskResult.failure('Missing expected podspec platform');
}
// Remove "s.platform = :ios" to work on all platforms, including macOS.
podspecContent = podspecContent.replaceFirst(RegExp(r'.*s\.platform.*'), '');
podspecContent = podspecContent.replaceFirst("s.dependency 'Flutter'", "s.ios.dependency 'Flutter'\ns.osx.dependency 'FlutterMacOS'");
await podspec.writeAsString(podspecContent, flush: true);
// Make PlugintestPlugin.swift compile on iOS and macOS with target conditionals.
final String pluginClass = '${name[0].toUpperCase()}${name.substring(1)}Plugin';
print('pluginClass: $pluginClass');
final File pluginRegister = File(path.join(darwinDir.path, 'Classes', '$pluginClass.swift'));
final String pluginRegisterContent = '''
#if os(macOS)
import FlutterMacOS
#elseif os(iOS)
import Flutter
#endif
public class $pluginClass: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
#if os(macOS)
let channel = FlutterMethodChannel(name: "$name", binaryMessenger: registrar.messenger)
#elseif os(iOS)
let channel = FlutterMethodChannel(name: "$name", binaryMessenger: registrar.messenger())
#endif
let instance = $pluginClass()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
#if os(macOS)
result("macOS " + ProcessInfo.processInfo.operatingSystemVersionString)
#elseif os(iOS)
result("iOS " + UIDevice.current.systemVersion)
#endif
}
}
''';
await pluginRegister.writeAsString(pluginRegisterContent, flush: true);
}
Future<void> runFlutterTest() async {
await inDirectory(Directory(rootPath), () async {
await flutter('test');
});
}
Future<void> runNativeTests(String buildTarget) async {
// Native unit tests rely on building the app first to generate necessary
// build files.
await build(buildTarget, validateNativeBuildProject: false);
switch (buildTarget) {
case 'apk':
if (await exec(
path.join('.', 'gradlew'),
<String>['testDebugUnitTest'],
workingDirectory: path.join(rootPath, 'android'),
canFail: true,
) != 0) {
throw TaskResult.failure('Platform unit tests failed');
}
case 'ios':
String? simulatorDeviceId;
try {
await testWithNewIOSSimulator('TestNativeUnitTests', (String deviceId) async {
simulatorDeviceId = deviceId;
if (!await runXcodeTests(
platformDirectory: path.join(rootPath, 'ios'),
destination: 'id=$deviceId',
configuration: 'Debug',
testName: 'native_plugin_unit_tests_ios',
skipCodesign: true,
)) {
throw TaskResult.failure('Platform unit tests failed');
}
});
} finally {
await removeIOSSimulator(simulatorDeviceId);
}
case 'linux':
if (await exec(
path.join(rootPath, 'build', 'linux', 'x64', 'release', 'plugins', 'plugintest', 'plugintest_test'),
<String>[],
canFail: true,
) != 0) {
throw TaskResult.failure('Platform unit tests failed');
}
case 'macos':
if (!await runXcodeTests(
platformDirectory: path.join(rootPath, 'macos'),
destination: 'platform=macOS',
configuration: 'Debug',
testName: 'native_plugin_unit_tests_macos',
skipCodesign: true,
)) {
throw TaskResult.failure('Platform unit tests failed');
}
case 'windows':
final String arch = Abi.current() == Abi.windowsX64 ? 'x64': 'arm64';
if (await exec(
path.join(rootPath, 'build', 'windows', arch, 'plugins', 'plugintest', 'Release', 'plugintest_test.exe'),
<String>[],
canFail: true,
) != 0) {
throw TaskResult.failure('Platform unit tests failed');
}
}
}
static Future<_FlutterProject> create(
Directory directory,
List<String> options,
String target,
{
required String name,
required String template,
Map<String, String>? environment,
}) async {
await inDirectory(directory, () async {
await flutter(
'create',
options: <String>[
'--template=$template',
'--org',
'io.flutter.devicelab',
...options,
name,
],
environment: environment,
);
});
final _FlutterProject project = _FlutterProject(directory, name);
if (template == 'plugin' && (target == 'ios' || target == 'macos')) {
project._reduceDarwinPluginMinimumVersion(name, target);
}
return project;
}
/// Creates a Pod that uses a Flutter plugin as a dependency and therefore
/// Flutter as a transitive dependency.
Future<void> addCocoapodsTransitiveFlutterDependency() async {
final String iosDirectoryPath = path.join(rootPath, 'ios');
final File nativePod = File(path.join(
iosDirectoryPath,
'NativePod',
'NativePod.podspec',
));
nativePod.createSync(recursive: true);
nativePod.writeAsStringSync('''
Pod::Spec.new do |s|
s.name = 'NativePod'
s.version = '1.0.0'
s.summary = 'A pod to test Flutter as a transitive dependency.'
s.homepage = 'https://flutter.dev'
s.license = { :type => 'BSD' }
s.author = { 'Flutter Dev Team' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = "Classes", "Classes/**/*.{h,m}"
s.dependency 'plugintest'
end
''');
final File nativePodClass = File(path.join(
iosDirectoryPath,
'NativePod',
'Classes',
'NativePodTest.m',
));
nativePodClass.createSync(recursive: true);
nativePodClass.writeAsStringSync('''
#import <Flutter/Flutter.h>
@interface NativePodTest : NSObject
@end
@implementation NativePodTest
@end
''');
final File podfileFile = File(path.join(iosDirectoryPath, 'Podfile'));
final List<String> podfileContents = podfileFile.readAsLinesSync();
final int index = podfileContents.indexWhere((String line) => line.contains('flutter_install_all_ios_pods'));
podfileContents.insert(index, "pod 'NativePod', :path => 'NativePod'");
podfileFile.writeAsStringSync(podfileContents.join('\n'));
}
// Make the platform version artificially low to test that the "deployment
// version too low" warning is never emitted.
void _reduceDarwinPluginMinimumVersion(String plugin, String target) {
final File podspec = File(path.join(rootPath, target, '$plugin.podspec'));
if (!podspec.existsSync()) {
throw TaskResult.failure('podspec file missing at ${podspec.path}');
}
final String versionString = target == 'ios'
? "s.platform = :ios, '12.0'"
: "s.platform = :osx, '10.11'";
String podspecContent = podspec.readAsStringSync();
if (!podspecContent.contains(versionString)) {
throw TaskResult.failure('Update this test to match plugin minimum $target deployment version');
}
// Add transitive dependency on AppAuth 1.6 targeting iOS 8 and macOS 10.9, which no longer builds in Xcode
// to test the version is forced higher and builds.
const String iosContent = '''
s.platform = :ios, '10.0'
s.dependency 'AppAuth', '1.6.0'
''';
const String macosContent = '''
s.platform = :osx, '10.8'
s.dependency 'AppAuth', '1.6.0'
''';
podspecContent = podspecContent.replaceFirst(versionString, target == 'ios' ? iosContent : macosContent);
podspec.writeAsStringSync(podspecContent, flush: true);
}
Future<void> build(
String target, {
bool validateNativeBuildProject = true,
bool configOnly = false,
Directory? localEngine,
}) async {
await inDirectory(Directory(rootPath), () async {
final String buildOutput = await evalFlutter('build', options: <String>[
target,
'-v',
if (target == 'ios')
'--no-codesign',
if (configOnly)
'--config-only',
if (localEngine != null)
// The engine directory is of the form <fake-source-path>/out/<fakename>,
// which has to be broken up into the component flags.
...<String>[
'--local-engine-src-path=${localEngine.parent.parent.path}',
'--local-engine=${path.basename(localEngine.path)}',
'--local-engine-host=${path.basename(localEngine.path)}',
]
]);
if (target == 'ios' || target == 'macos') {
// This warning is confusing and shouldn't be emitted. Plugins often support lower versions than the
// Flutter app, but as long as they support the minimum it will work.
// warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0,
// but the range of supported deployment target versions is 9.0 to 14.0.99.
//
// (or "The macOS deployment target 'MACOSX_DEPLOYMENT_TARGET'"...)
if (buildOutput.contains('is set to 10.0, but the range of supported deployment target versions') ||
buildOutput.contains('is set to 10.8, but the range of supported deployment target versions')) {
throw TaskResult.failure('Minimum plugin version warning present');
}
if (validateNativeBuildProject) {
final File podsProject = File(path.join(rootPath, target, 'Pods', 'Pods.xcodeproj', 'project.pbxproj'));
if (!podsProject.existsSync()) {
throw TaskResult.failure('Xcode Pods project file missing at ${podsProject.path}');
}
final String podsProjectContent = podsProject.readAsStringSync();
if (target == 'ios') {
// Plugins with versions lower than the app version should not have IPHONEOS_DEPLOYMENT_TARGET set.
// The plugintest plugin target should not have IPHONEOS_DEPLOYMENT_TARGET set since it has been lowered
// in _reduceDarwinPluginMinimumVersion to 10, which is below the target version of 11.
if (podsProjectContent.contains('IPHONEOS_DEPLOYMENT_TARGET = 10')) {
throw TaskResult.failure('Plugin build setting IPHONEOS_DEPLOYMENT_TARGET not removed');
}
// Transitive dependency AppAuth targeting too-low 8.0 was not fixed.
if (podsProjectContent.contains('IPHONEOS_DEPLOYMENT_TARGET = 8')) {
throw TaskResult.failure('Transitive dependency build setting IPHONEOS_DEPLOYMENT_TARGET=8 not removed');
}
if (!podsProjectContent.contains(r'"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = "$(inherited) i386";')) {
throw TaskResult.failure(r'EXCLUDED_ARCHS is not "$(inherited) i386"');
}
} else if (target == 'macos') {
// Same for macOS deployment target, but 10.8.
// The plugintest target should not have MACOSX_DEPLOYMENT_TARGET set.
if (podsProjectContent.contains('MACOSX_DEPLOYMENT_TARGET = 10.8')) {
throw TaskResult.failure('Plugin build setting MACOSX_DEPLOYMENT_TARGET not removed');
}
// Transitive dependency AppAuth targeting too-low 10.9 was not fixed.
if (podsProjectContent.contains('MACOSX_DEPLOYMENT_TARGET = 10.9')) {
throw TaskResult.failure('Transitive dependency build setting MACOSX_DEPLOYMENT_TARGET=10.9 not removed');
}
}
if (localEngine != null) {
final RegExp localEngineSearchPath = RegExp('FRAMEWORK_SEARCH_PATHS\\s*=[^;]*${localEngine.path}');
if (!localEngineSearchPath.hasMatch(podsProjectContent)) {
throw TaskResult.failure('FRAMEWORK_SEARCH_PATHS does not contain the --local-engine path');
}
}
}
}
});
}
Future<void> delete() async {
if (Platform.isWindows) {
// A running Gradle daemon might prevent us from deleting the project
// folder on Windows.
final String wrapperPath =
path.absolute(path.join(rootPath, 'android', 'gradlew.bat'));
if (File(wrapperPath).existsSync()) {
await exec(wrapperPath, <String>['--stop'], canFail: true);
}
// TODO(ianh): Investigating if flakiness is timing dependent.
await Future<void>.delayed(const Duration(seconds: 10));
}
rmTree(parent);
}
}
| flutter/dev/devicelab/lib/tasks/plugin_tests.dart/0 | {
"file_path": "flutter/dev/devicelab/lib/tasks/plugin_tests.dart",
"repo_id": "flutter",
"token_count": 8081
} | 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 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter_devicelab/framework/running_processes.dart';
import 'package:process/process.dart';
import 'common.dart';
void main() {
test('Parse PowerShell result', () {
const String powershellOutput = r'''
ProcessId CreationDate CommandLine
--------- ------------ -----------
6552 3/7/2019 5:00:27 PM "C:\tools\dart-sdk\bin\dart.exe" .\bin\agent.dart ci
6553 3/7/2019 10:00:27 PM "C:\tools\dart-sdk1\bin\dart.exe" .\bin\agent.dart ci
6554 3/7/2019 11:00:27 AM "C:\tools\dart-sdk2\bin\dart.exe" .\bin\agent.dart ci
''';
final List<RunningProcessInfo> results =
processPowershellOutput(powershellOutput).toList();
expect(results.length, 3);
expect(
results,
equals(<RunningProcessInfo>[
RunningProcessInfo(
6552,
r'"C:\tools\dart-sdk\bin\dart.exe" .\bin\agent.dart ci',
DateTime(2019, 7, 3, 17, 0, 27),
),
RunningProcessInfo(
6553,
r'"C:\tools\dart-sdk1\bin\dart.exe" .\bin\agent.dart ci',
DateTime(2019, 7, 3, 22, 0, 27),
),
RunningProcessInfo(
6554,
r'"C:\tools\dart-sdk2\bin\dart.exe" .\bin\agent.dart ci',
DateTime(2019, 7, 3, 11, 0, 27),
),
]));
});
test('Parse Posix output', () {
const String psOutput = r'''
STARTED PID COMMAND
Sat Mar 9 20:12:47 2019 1 /sbin/launchd
Sat Mar 9 20:13:00 2019 49 /usr/sbin/syslogd
''';
final List<RunningProcessInfo> results =
processPsOutput(psOutput, null).toList();
expect(results.length, 2);
expect(
results,
equals(<RunningProcessInfo>[
RunningProcessInfo(
1,
'/sbin/launchd',
DateTime(2019, 3, 9, 20, 12, 47),
),
RunningProcessInfo(
49,
'/usr/sbin/syslogd',
DateTime(2019, 3, 9, 20, 13),
),
]));
});
test('RunningProcessInfo.terminate', () {
final RunningProcessInfo process = RunningProcessInfo(123, 'test', DateTime(456));
final FakeProcessManager fakeProcessManager = FakeProcessManager();
process.terminate(processManager: fakeProcessManager);
if (Platform.isWindows) {
expect(fakeProcessManager.log, <String>['run([taskkill.exe, /pid, 123, /f], null, null, null, null, null, null)']);
} else {
expect(fakeProcessManager.log, <String>['killPid(123, SIGKILL)']);
}
});
}
class FakeProcessManager implements ProcessManager {
final List<String> log = <String>[];
@override
bool canRun(Object? a, { String? workingDirectory }) {
log.add('canRun($a, $workingDirectory)');
return true;
}
@override
bool killPid(int a, [ProcessSignal? b]) {
log.add('killPid($a, $b)');
return true;
}
@override
Future<ProcessResult> run(List<Object> a, {
Map<String, String>? environment,
bool? includeParentEnvironment,
bool? runInShell,
Encoding? stderrEncoding,
Encoding? stdoutEncoding,
String? workingDirectory,
}) async {
log.add('run($a, $environment, $includeParentEnvironment, $runInShell, $stderrEncoding, $stdoutEncoding, $workingDirectory)');
return ProcessResult(1, 0, 'stdout', 'stderr');
}
@override
ProcessResult runSync(List<Object> a, {
Map<String, String>? environment,
bool? includeParentEnvironment,
bool? runInShell,
Encoding? stderrEncoding,
Encoding? stdoutEncoding,
String? workingDirectory,
}) {
log.add('runSync($a, $environment, $includeParentEnvironment, $runInShell, $stderrEncoding, $stdoutEncoding, $workingDirectory)');
return ProcessResult(1, 0, 'stdout', 'stderr');
}
@override
Future<Process> start(
List<Object> a, {
Map<String, String>? environment,
bool? includeParentEnvironment,
ProcessStartMode? mode,
bool? runInShell,
String? workingDirectory,
}) {
log.add('start($a, $environment, $includeParentEnvironment, $mode, $runInShell, $workingDirectory)');
return Completer<Process>().future;
}
}
| flutter/dev/devicelab/test/running_processes_test.dart/0 | {
"file_path": "flutter/dev/devicelab/test/running_processes_test.dart",
"repo_id": "flutter",
"token_count": 1857
} | 534 |
# Forbidden from release tests
This program compiles the Dart portions of a Flutter application to the
AOT format used for release builds, and verifies that debugging related types
are not retained. By default, it uses the `//examples/hello_world` application
in this repository.
This harness is invoked from `dev/bots/test.dart`. By default it uses the
`examples/hello_world.dart` as if it were being compiled for Android arm64
release. New forbidden types may be added by adding more `--forbidden-type`
options in the `runForbiddenFromReleaseTests` method in `dev/bots/test.dart`
| flutter/dev/forbidden_from_release_tests/README.md/0 | {
"file_path": "flutter/dev/forbidden_from_release_tests/README.md",
"repo_id": "flutter",
"token_count": 152
} | 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.
/// Class name constants which correspond to the class names used by the
/// Android accessibility bridge.
class AndroidClassName {
/// The class name used for checkboxes.
static const String checkBox = 'android.widget.CheckBox';
/// The default className if none is provided by flutter.
static const String view = 'android.view.View';
/// The class name used for radio buttons.
static const String radio = 'android.widget.RadioButton';
/// The class name used for editable text fields.
static const String editText = 'android.widget.EditText';
/// The class name used for read only text fields.
static const String textView = 'android.widget.TextView';
/// The class name used for toggle switches.
static const String toggleSwitch = 'android.widget.Switch';
/// The default className for buttons.
static const String button = 'android.widget.Button';
}
/// Action constants which correspond to `AccessibilityAction` in Android.
enum AndroidSemanticsAction {
/// Matches `AccessibilityAction.ACTION_FOCUS`.
focus(_kFocusIndex),
/// Matches `AccessibilityAction.ACTION_CLEAR_FOCUS`.
clearFocus(_kClearFocusIndex),
/// Matches `AccessibilityAction.ACTION_SELECT`.
select(_kSelectIndex),
/// Matches `AccessibilityAction.ACTION_CLEAR_SELECTION`.
clearSelection(_kClearSelectionIndex),
/// Matches `AccessibilityAction.ACTION_CLICK`.
click(_kClickIndex),
/// Matches `AccessibilityAction.ACTION_LONG_CLICK`.
longClick(_kLongClickIndex),
/// Matches `AccessibilityAction.ACTION_ACCESSIBILITY_FOCUS`.
accessibilityFocus(_kAccessibilityFocusIndex),
/// Matches `AccessibilityAction.ACTION_CLEAR_ACCESSIBILITY_FOCUS`.
clearAccessibilityFocus(_kClearAccessibilityFocusIndex),
/// Matches `AccessibilityAction.ACTION_NEXT_AT_MOVEMENT_GRANULARITY`.
nextAtMovementGranularity(_kNextAtMovementGranularityIndex),
/// Matches `AccessibilityAction.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY`.
previousAtMovementGranularity(_kPreviousAtMovementGranularityIndex),
/// Matches `AccessibilityAction.ACTION_NEXT_HTML_ELEMENT`.
nextHtmlElement(_kNextHtmlElementIndex),
/// Matches `AccessibilityAction.ACTION_PREVIOUS_HTML_ELEMENT`.
previousHtmlElement(_kPreviousHtmlElementIndex),
/// Matches `AccessibilityAction.ACTION_SCROLL_FORWARD`.
scrollForward(_kScrollForwardIndex),
/// Matches `AccessibilityAction.ACTION_SCROLL_BACKWARD`.
scrollBackward(_kScrollBackwardIndex),
/// Matches `AccessibilityAction.ACTION_CUT`.
cut(_kCutIndex),
/// Matches `AccessibilityAction.ACTION_COPY`.
copy(_kCopyIndex),
/// Matches `AccessibilityAction.ACTION_PASTE`.
paste(_kPasteIndex),
/// Matches `AccessibilityAction.ACTION_SET_SELECTION`.
setSelection(_kSetSelectionIndex),
/// Matches `AccessibilityAction.ACTION_EXPAND`.
expand(_kExpandIndex),
/// Matches `AccessibilityAction.ACTION_COLLAPSE`.
collapse(_kCollapseIndex),
/// Matches `AccessibilityAction.SET_TEXT`.
setText(_kSetText);
const AndroidSemanticsAction(this.id);
/// The Android id of the action.
final int id;
// These indices need to be in sync with android_semantics_testing/android/app/src/main/java/com/yourcompany/platforminteraction/MainActivity.java
static const int _kFocusIndex = 1 << 0;
static const int _kClearFocusIndex = 1 << 1;
static const int _kSelectIndex = 1 << 2;
static const int _kClearSelectionIndex = 1 << 3;
static const int _kClickIndex = 1 << 4;
static const int _kLongClickIndex = 1 << 5;
static const int _kAccessibilityFocusIndex = 1 << 6;
static const int _kClearAccessibilityFocusIndex = 1 << 7;
static const int _kNextAtMovementGranularityIndex = 1 << 8;
static const int _kPreviousAtMovementGranularityIndex = 1 << 9;
static const int _kNextHtmlElementIndex = 1 << 10;
static const int _kPreviousHtmlElementIndex = 1 << 11;
static const int _kScrollForwardIndex = 1 << 12;
static const int _kScrollBackwardIndex = 1 << 13;
static const int _kCutIndex = 1 << 14;
static const int _kCopyIndex = 1 << 15;
static const int _kPasteIndex = 1 << 16;
static const int _kSetSelectionIndex = 1 << 17;
static const int _kExpandIndex = 1 << 18;
static const int _kCollapseIndex = 1 << 19;
static const int _kSetText = 1 << 21;
static const Map<int, AndroidSemanticsAction> _kActionById = <int, AndroidSemanticsAction>{
_kFocusIndex: focus,
_kClearFocusIndex: clearFocus,
_kSelectIndex: select,
_kClearSelectionIndex: clearSelection,
_kClickIndex: click,
_kLongClickIndex: longClick,
_kAccessibilityFocusIndex: accessibilityFocus,
_kClearAccessibilityFocusIndex: clearAccessibilityFocus,
_kNextAtMovementGranularityIndex: nextAtMovementGranularity,
_kPreviousAtMovementGranularityIndex: previousAtMovementGranularity,
_kNextHtmlElementIndex: nextHtmlElement,
_kPreviousHtmlElementIndex: previousHtmlElement,
_kScrollForwardIndex: scrollForward,
_kScrollBackwardIndex: scrollBackward,
_kCutIndex: cut,
_kCopyIndex: copy,
_kPasteIndex: paste,
_kSetSelectionIndex: setSelection,
_kExpandIndex: expand,
_kCollapseIndex: collapse,
_kSetText: setText,
};
/// Creates a new [AndroidSemanticsAction] from an integer `value`.
///
/// Returns `null` if the id is not a known Android accessibility action.
static AndroidSemanticsAction? deserialize(int value) {
return _kActionById[value];
}
}
| flutter/dev/integration_tests/android_semantics_testing/lib/src/constants.dart/0 | {
"file_path": "flutter/dev/integration_tests/android_semantics_testing/lib/src/constants.dart",
"repo_id": "flutter",
"token_count": 1706
} | 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.
// This file is auto generated.
// To update all the build.gradle files in the Flutter repo,
// See dev/tools/bin/generate_gradle_lockfiles.dart.
buildscript {
ext.kotlin_version = '1.7.10'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.3.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
configurations.classpath {
resolutionStrategy.activateDependencyLocking()
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
project.getTasks().withType(JavaCompile){
options.compilerArgs << "-Xlint:all" << "-Werror"
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
project.evaluationDependsOn(':app')
dependencyLocking {
ignoredDependencies.add('io.flutter:*')
lockFile = file("${rootProject.projectDir}/project-${project.name}.lockfile")
if (!project.hasProperty('local-engine-repo')) {
lockAllConfigurations()
}
}
}
tasks.register("clean", Delete) {
delete rootProject.buildDir
}
| flutter/dev/integration_tests/deferred_components_test/android/build.gradle/0 | {
"file_path": "flutter/dev/integration_tests/deferred_components_test/android/build.gradle",
"repo_id": "flutter",
"token_count": 530
} | 537 |
# external_textures
Tests external texture rendering between a native[^1] platform and Flutter.
Part of Flutter's API for [plugins](https://flutter.dev/docs/development/packages-and-plugins/developing-packages#plugin) includes passing _external textures_, or textures
created outside of Flutter, to Flutter, typically using the [`Texture`][texture]
widget. This is useful for plugins that render video, or for plugins that
interact with the camera.
For example:
- [`packages/camera`][camera]
- [`packages/video_player`][video_player]
[texture]: https://api.flutter.dev/flutter/widgets/Texture-class.html
[camera]: https://github.com/flutter/packages/tree/8255fbed74465425a1ec06a1804225e705e29f52/packages/camera
[video_player]: https://github.com/flutter/packages/tree/8255fbed74465425a1ec06a1804225e705e29f52/packages/video_player
Because external textures are created outside of Flutter, there is often subtle
translation that needs to happen between the native platform and Flutter, which
is hard to observe. These integration tests are designed to help catch these
subtle translation issues.
## How it works
- Each `lib/*_main.dart` file is a Flutter app instrumenting a test case.
- There is a corresponding `test_driver/*_test.dart` that runs assertions.
To run the test cases locally, use `flutter drive`[^2]:
```shell
flutter drive lib/frame_rate_main.dart --driver test_driver/frame_rate_test.dart
```
> [!TIP]
> On CI, the test cases are run within our [device lab](../../devicelab/README.md).
>
> See [`devicelab/lib/tasks/integration_tests.dart`](../../devicelab/lib/tasks/integration_tests.dart)
> and search for `createExternalUiFrameRateIntegrationTest`.
>
> The actual tests are run by task runners:
>
> - [Android](../../devicelab/bin/tasks/external_textures_integration_test.dart)
> - [iOS](../../devicelab/bin/tasks/external_textures_integration_test_ios.dart)
[^1]: Only iOS and Android.
[^2]: Unfortunately documentation is quite limited. See [#142021](https://github.com/flutter/flutter/issues/142021).
| flutter/dev/integration_tests/external_textures/README.md/0 | {
"file_path": "flutter/dev/integration_tests/external_textures/README.md",
"repo_id": "flutter",
"token_count": 644
} | 538 |
// This xcconfig used for both the paid and free flavor, but the plugins are not different between
// them. Pick one.
#include? "Pods/Target Support Files/Pods-Free App/Pods-Free App.release free.xcconfig"
#include "Generated.xcconfig"
| flutter/dev/integration_tests/flavors/ios/Flutter/Release.xcconfig/0 | {
"file_path": "flutter/dev/integration_tests/flavors/ios/Flutter/Release.xcconfig",
"repo_id": "flutter",
"token_count": 74
} | 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.
// Based on https://material.uplabs.com/posts/google-newsstand-navigation-pattern
// See also: https://material-motion.github.io/material-motion/documentation/
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'sections.dart';
import 'widgets.dart';
const Color _kAppBackgroundColor = Color(0xFF353662);
const Duration _kScrollDuration = Duration(milliseconds: 400);
const Curve _kScrollCurve = Curves.fastOutSlowIn;
// This app's contents start out at _kHeadingMaxHeight and they function like
// an appbar. Initially the appbar occupies most of the screen and its section
// headings are laid out in a column. By the time its height has been
// reduced to _kAppBarMidHeight, its layout is horizontal, only one section
// heading is visible, and the section's list of details is visible below the
// heading. The appbar's height can be reduced to no more than _kAppBarMinHeight.
const double _kAppBarMinHeight = 90.0;
const double _kAppBarMidHeight = 256.0;
// The AppBar's max height depends on the screen, see _AnimationDemoHomeState._buildBody()
// Initially occupies the same space as the status bar and gets smaller as
// the primary scrollable scrolls upwards.
// TODO(hansmuller): it would be worth adding something like this to the framework.
class _RenderStatusBarPaddingSliver extends RenderSliver {
_RenderStatusBarPaddingSliver({
required double maxHeight,
required double scrollFactor,
}) : assert(maxHeight >= 0.0),
assert(scrollFactor >= 1.0),
_maxHeight = maxHeight,
_scrollFactor = scrollFactor;
// The height of the status bar
double get maxHeight => _maxHeight;
double _maxHeight;
set maxHeight(double value) {
assert(maxHeight >= 0.0);
if (_maxHeight == value) {
return;
}
_maxHeight = value;
markNeedsLayout();
}
// That rate at which this renderer's height shrinks when the scroll
// offset changes.
double get scrollFactor => _scrollFactor;
double _scrollFactor;
set scrollFactor(double value) {
assert(scrollFactor >= 1.0);
if (_scrollFactor == value) {
return;
}
_scrollFactor = value;
markNeedsLayout();
}
@override
void performLayout() {
final double height = (maxHeight - constraints.scrollOffset / scrollFactor).clamp(0.0, maxHeight);
geometry = SliverGeometry(
paintExtent: math.min(height, constraints.remainingPaintExtent),
scrollExtent: maxHeight,
maxPaintExtent: maxHeight,
);
}
}
class _StatusBarPaddingSliver extends SingleChildRenderObjectWidget {
const _StatusBarPaddingSliver({
required this.maxHeight,
this.scrollFactor = 5.0,
}) : assert(maxHeight >= 0.0),
assert(scrollFactor >= 1.0);
final double maxHeight;
final double scrollFactor;
@override
_RenderStatusBarPaddingSliver createRenderObject(BuildContext context) {
return _RenderStatusBarPaddingSliver(
maxHeight: maxHeight,
scrollFactor: scrollFactor,
);
}
@override
void updateRenderObject(BuildContext context, _RenderStatusBarPaddingSliver renderObject) {
renderObject
..maxHeight = maxHeight
..scrollFactor = scrollFactor;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder description) {
super.debugFillProperties(description);
description.add(DoubleProperty('maxHeight', maxHeight));
description.add(DoubleProperty('scrollFactor', scrollFactor));
}
}
class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
_SliverAppBarDelegate({
required this.minHeight,
required this.maxHeight,
required this.child,
});
final double minHeight;
final double maxHeight;
final Widget child;
@override
double get minExtent => minHeight;
@override
double get maxExtent => math.max(maxHeight, minHeight);
@override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
return SizedBox.expand(child: child);
}
@override
bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
return maxHeight != oldDelegate.maxHeight
|| minHeight != oldDelegate.minHeight
|| child != oldDelegate.child;
}
@override
String toString() => '_SliverAppBarDelegate';
}
// Arrange the section titles, indicators, and cards. The cards are only included when
// the layout is transitioning between vertical and horizontal. Once the layout is
// horizontal the cards are laid out by a PageView.
//
// The layout of the section cards, titles, and indicators is defined by the
// two 0.0-1.0 "t" parameters, both of which are based on the layout's height:
// - tColumnToRow
// 0.0 when height is maxHeight and the layout is a column
// 1.0 when the height is midHeight and the layout is a row
// - tCollapsed
// 0.0 when height is midHeight and the layout is a row
// 1.0 when height is minHeight and the layout is a (still) row
//
// minHeight < midHeight < maxHeight
//
// The general approach here is to compute the column layout and row size
// and position of each element and then interpolate between them using
// tColumnToRow. Once tColumnToRow reaches 1.0, the layout changes are
// defined by tCollapsed. As tCollapsed increases the titles spread out
// until only one title is visible and the indicators cluster together
// until they're all visible.
class _AllSectionsLayout extends MultiChildLayoutDelegate {
_AllSectionsLayout({
this.translation,
this.tColumnToRow,
this.tCollapsed,
this.cardCount,
this.selectedIndex,
});
final Alignment? translation;
final double? tColumnToRow;
final double? tCollapsed;
final int? cardCount;
final double? selectedIndex;
Rect? _interpolateRect(Rect begin, Rect end) {
return Rect.lerp(begin, end, tColumnToRow!);
}
Offset? _interpolatePoint(Offset begin, Offset end) {
return Offset.lerp(begin, end, tColumnToRow!);
}
@override
void performLayout(Size size) {
final double columnCardX = size.width / 5.0;
final double columnCardWidth = size.width - columnCardX;
final double columnCardHeight = size.height / cardCount!;
final double rowCardWidth = size.width;
final Offset offset = translation!.alongSize(size);
double columnCardY = 0.0;
double rowCardX = -(selectedIndex! * rowCardWidth);
// When tCollapsed > 0 the titles spread apart
final double columnTitleX = size.width / 10.0;
final double rowTitleWidth = size.width * ((1 + tCollapsed!) / 2.25);
double rowTitleX = (size.width - rowTitleWidth) / 2.0 - selectedIndex! * rowTitleWidth;
// When tCollapsed > 0, the indicators move closer together
//final double rowIndicatorWidth = 48.0 + (1.0 - tCollapsed) * (rowTitleWidth - 48.0);
const double paddedSectionIndicatorWidth = kSectionIndicatorWidth + 8.0;
final double rowIndicatorWidth = paddedSectionIndicatorWidth +
(1.0 - tCollapsed!) * (rowTitleWidth - paddedSectionIndicatorWidth);
double rowIndicatorX = (size.width - rowIndicatorWidth) / 2.0 - selectedIndex! * rowIndicatorWidth;
// Compute the size and origin of each card, title, and indicator for the maxHeight
// "column" layout, and the midHeight "row" layout. The actual layout is just the
// interpolated value between the column and row layouts for t.
for (int index = 0; index < cardCount!; index++) {
// Layout the card for index.
final Rect columnCardRect = Rect.fromLTWH(columnCardX, columnCardY, columnCardWidth, columnCardHeight);
final Rect rowCardRect = Rect.fromLTWH(rowCardX, 0.0, rowCardWidth, size.height);
final Rect cardRect = _interpolateRect(columnCardRect, rowCardRect)!.shift(offset);
final String cardId = 'card$index';
if (hasChild(cardId)) {
layoutChild(cardId, BoxConstraints.tight(cardRect.size));
positionChild(cardId, cardRect.topLeft);
}
// Layout the title for index.
final Size titleSize = layoutChild('title$index', BoxConstraints.loose(cardRect.size));
final double columnTitleY = columnCardRect.centerLeft.dy - titleSize.height / 2.0;
final double rowTitleY = rowCardRect.centerLeft.dy - titleSize.height / 2.0;
final double centeredRowTitleX = rowTitleX + (rowTitleWidth - titleSize.width) / 2.0;
final Offset columnTitleOrigin = Offset(columnTitleX, columnTitleY);
final Offset rowTitleOrigin = Offset(centeredRowTitleX, rowTitleY);
final Offset titleOrigin = _interpolatePoint(columnTitleOrigin, rowTitleOrigin)!;
positionChild('title$index', titleOrigin + offset);
// Layout the selection indicator for index.
final Size indicatorSize = layoutChild('indicator$index', BoxConstraints.loose(cardRect.size));
final double columnIndicatorX = cardRect.centerRight.dx - indicatorSize.width - 16.0;
final double columnIndicatorY = cardRect.bottomRight.dy - indicatorSize.height - 16.0;
final Offset columnIndicatorOrigin = Offset(columnIndicatorX, columnIndicatorY);
final Rect titleRect = Rect.fromPoints(titleOrigin, titleSize.bottomRight(titleOrigin));
final double centeredRowIndicatorX = rowIndicatorX + (rowIndicatorWidth - indicatorSize.width) / 2.0;
final double rowIndicatorY = titleRect.bottomCenter.dy + 16.0;
final Offset rowIndicatorOrigin = Offset(centeredRowIndicatorX, rowIndicatorY);
final Offset indicatorOrigin = _interpolatePoint(columnIndicatorOrigin, rowIndicatorOrigin)!;
positionChild('indicator$index', indicatorOrigin + offset);
columnCardY += columnCardHeight;
rowCardX += rowCardWidth;
rowTitleX += rowTitleWidth;
rowIndicatorX += rowIndicatorWidth;
}
}
@override
bool shouldRelayout(_AllSectionsLayout oldDelegate) {
return tColumnToRow != oldDelegate.tColumnToRow
|| cardCount != oldDelegate.cardCount
|| selectedIndex != oldDelegate.selectedIndex;
}
}
class _AllSectionsView extends AnimatedWidget {
_AllSectionsView({
required this.sectionIndex,
required this.sections,
required this.selectedIndex,
this.minHeight,
this.midHeight,
this.maxHeight,
this.sectionCards = const <Widget>[],
}) : assert(sectionCards.length == sections.length),
assert(sectionIndex >= 0 && sectionIndex < sections.length),
assert(selectedIndex.value! >= 0.0 && selectedIndex.value! < sections.length.toDouble()),
super(listenable: selectedIndex);
final int sectionIndex;
final List<Section> sections;
final ValueNotifier<double?> selectedIndex;
final double? minHeight;
final double? midHeight;
final double? maxHeight;
final List<Widget> sectionCards;
double _selectedIndexDelta(int index) {
return (index.toDouble() - selectedIndex.value!).abs().clamp(0.0, 1.0);
}
Widget _build(BuildContext context, BoxConstraints constraints) {
final Size size = constraints.biggest;
// The layout's progress from a column to a row. Its value is
// 0.0 when size.height equals the maxHeight, 1.0 when the size.height
// equals the midHeight.
final double tColumnToRow =
1.0 - ((size.height - midHeight!) /
(maxHeight! - midHeight!)).clamp(0.0, 1.0);
// The layout's progress from the midHeight row layout to
// a minHeight row layout. Its value is 0.0 when size.height equals
// midHeight and 1.0 when size.height equals minHeight.
final double tCollapsed =
1.0 - ((size.height - minHeight!) /
(midHeight! - minHeight!)).clamp(0.0, 1.0);
double indicatorOpacity(int index) {
return 1.0 - _selectedIndexDelta(index) * 0.5;
}
double titleOpacity(int index) {
return 1.0 - _selectedIndexDelta(index) * tColumnToRow * 0.5;
}
double titleScale(int index) {
return 1.0 - _selectedIndexDelta(index) * tColumnToRow * 0.15;
}
final List<Widget> children = List<Widget>.from(sectionCards);
for (int index = 0; index < sections.length; index++) {
final Section section = sections[index];
children.add(LayoutId(
id: 'title$index',
child: SectionTitle(
section: section,
scale: titleScale(index),
opacity: titleOpacity(index),
),
));
}
for (int index = 0; index < sections.length; index++) {
children.add(LayoutId(
id: 'indicator$index',
child: SectionIndicator(
opacity: indicatorOpacity(index),
),
));
}
return CustomMultiChildLayout(
delegate: _AllSectionsLayout(
translation: Alignment((selectedIndex.value! - sectionIndex) * 2.0 - 1.0, -1.0),
tColumnToRow: tColumnToRow,
tCollapsed: tCollapsed,
cardCount: sections.length,
selectedIndex: selectedIndex.value,
),
children: children,
);
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: _build);
}
}
// Support snapping scrolls to the midScrollOffset: the point at which the
// app bar's height is _kAppBarMidHeight and only one section heading is
// visible.
class _SnappingScrollPhysics extends ClampingScrollPhysics {
const _SnappingScrollPhysics({
super.parent,
required this.midScrollOffset,
});
final double midScrollOffset;
@override
_SnappingScrollPhysics applyTo(ScrollPhysics? ancestor) {
return _SnappingScrollPhysics(parent: buildParent(ancestor), midScrollOffset: midScrollOffset);
}
Simulation _toMidScrollOffsetSimulation(double offset, double dragVelocity, ScrollMetrics metrics) {
final double velocity = math.max(dragVelocity, minFlingVelocity);
return ScrollSpringSimulation(spring, offset, midScrollOffset, velocity, tolerance: toleranceFor(metrics));
}
Simulation _toZeroScrollOffsetSimulation(double offset, double dragVelocity, ScrollMetrics metrics) {
final double velocity = math.max(dragVelocity, minFlingVelocity);
return ScrollSpringSimulation(spring, offset, 0.0, velocity, tolerance: toleranceFor(metrics));
}
@override
Simulation? createBallisticSimulation(ScrollMetrics position, double dragVelocity) {
final Simulation? simulation = super.createBallisticSimulation(position, dragVelocity);
final double offset = position.pixels;
if (simulation != null) {
// The drag ended with sufficient velocity to trigger creating a simulation.
// If the simulation is headed up towards midScrollOffset but will not reach it,
// then snap it there. Similarly if the simulation is headed down past
// midScrollOffset but will not reach zero, then snap it to zero.
final double simulationEnd = simulation.x(double.infinity);
if (simulationEnd >= midScrollOffset) {
return simulation;
}
if (dragVelocity > 0.0) {
return _toMidScrollOffsetSimulation(offset, dragVelocity, position);
}
if (dragVelocity < 0.0) {
return _toZeroScrollOffsetSimulation(offset, dragVelocity, position);
}
} else {
// The user ended the drag with little or no velocity. If they
// didn't leave the offset above midScrollOffset, then
// snap to midScrollOffset if they're more than halfway there,
// otherwise snap to zero.
final double snapThreshold = midScrollOffset / 2.0;
if (offset >= snapThreshold && offset < midScrollOffset) {
return _toMidScrollOffsetSimulation(offset, dragVelocity, position);
}
if (offset > 0.0 && offset < snapThreshold) {
return _toZeroScrollOffsetSimulation(offset, dragVelocity, position);
}
}
return simulation;
}
}
class AnimationDemoHome extends StatefulWidget {
const AnimationDemoHome({ super.key });
static const String routeName = '/animation';
@override
State<AnimationDemoHome> createState() => _AnimationDemoHomeState();
}
class _AnimationDemoHomeState extends State<AnimationDemoHome> {
final ScrollController _scrollController = ScrollController();
final PageController _headingPageController = PageController();
final PageController _detailsPageController = PageController();
ScrollPhysics _headingScrollPhysics = const NeverScrollableScrollPhysics();
ValueNotifier<double?> selectedIndex = ValueNotifier<double?>(0.0);
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: _kAppBackgroundColor,
body: Builder(
// Insert an element so that _buildBody can find the PrimaryScrollController.
builder: _buildBody,
),
);
}
void _handleBackButton(double midScrollOffset) {
if (_scrollController.offset >= midScrollOffset) {
_scrollController.animateTo(0.0, curve: _kScrollCurve, duration: _kScrollDuration);
} else {
Navigator.maybePop(context);
}
}
// Only enable paging for the heading when the user has scrolled to midScrollOffset.
// Paging is enabled/disabled by setting the heading's PageView scroll physics.
bool _handleScrollNotification(ScrollNotification notification, double midScrollOffset) {
if (notification.depth == 0 && notification is ScrollUpdateNotification) {
final ScrollPhysics physics = _scrollController.position.pixels >= midScrollOffset
? const PageScrollPhysics()
: const NeverScrollableScrollPhysics();
if (physics != _headingScrollPhysics) {
setState(() {
_headingScrollPhysics = physics;
});
}
}
return false;
}
void _maybeScroll(double midScrollOffset, int pageIndex, double xOffset) {
if (_scrollController.offset < midScrollOffset) {
// Scroll the overall list to the point where only one section card shows.
// At the same time scroll the PageViews to the page at pageIndex.
_headingPageController.animateToPage(pageIndex, curve: _kScrollCurve, duration: _kScrollDuration);
_scrollController.animateTo(midScrollOffset, curve: _kScrollCurve, duration: _kScrollDuration);
} else {
// One one section card is showing: scroll one page forward or back.
final double centerX = _headingPageController.position.viewportDimension / 2.0;
final int newPageIndex = xOffset > centerX ? pageIndex + 1 : pageIndex - 1;
_headingPageController.animateToPage(newPageIndex, curve: _kScrollCurve, duration: _kScrollDuration);
}
}
bool _handlePageNotification(ScrollNotification notification, PageController leader, PageController follower) {
if (notification.depth == 0 && notification is ScrollUpdateNotification) {
selectedIndex.value = leader.page;
if (follower.page != leader.page) {
follower.position.jumpToWithoutSettling(leader.position.pixels);
}
}
return false;
}
Iterable<Widget> _detailItemsFor(Section section) {
final Iterable<Widget> detailItems = section.details!.map<Widget>((SectionDetail detail) {
return SectionDetailView(detail: detail);
});
return ListTile.divideTiles(context: context, tiles: detailItems);
}
List<Widget> _allHeadingItems(double maxHeight, double midScrollOffset) {
final List<Widget> sectionCards = <Widget>[];
for (int index = 0; index < allSections.length; index++) {
sectionCards.add(LayoutId(
id: 'card$index',
child: GestureDetector(
behavior: HitTestBehavior.opaque,
child: SectionCard(section: allSections[index]),
onTapUp: (TapUpDetails details) {
final double xOffset = details.globalPosition.dx;
setState(() {
_maybeScroll(midScrollOffset, index, xOffset);
});
},
),
));
}
final List<Widget> headings = <Widget>[];
for (int index = 0; index < allSections.length; index++) {
headings.add(ColoredBox(
color: _kAppBackgroundColor,
child: ClipRect(
child: _AllSectionsView(
sectionIndex: index,
sections: allSections,
selectedIndex: selectedIndex,
minHeight: _kAppBarMinHeight,
midHeight: _kAppBarMidHeight,
maxHeight: maxHeight,
sectionCards: sectionCards,
),
),
)
);
}
return headings;
}
Widget _buildBody(BuildContext context) {
final MediaQueryData mediaQueryData = MediaQuery.of(context);
final double statusBarHeight = mediaQueryData.padding.top;
final double screenHeight = mediaQueryData.size.height;
final double appBarMaxHeight = screenHeight - statusBarHeight;
// The scroll offset that reveals the appBarMidHeight appbar.
final double appBarMidScrollOffset = statusBarHeight + appBarMaxHeight - _kAppBarMidHeight;
return SizedBox.expand(
child: Stack(
children: <Widget>[
NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification notification) {
return _handleScrollNotification(notification, appBarMidScrollOffset);
},
child: CustomScrollView(
controller: _scrollController,
physics: _SnappingScrollPhysics(midScrollOffset: appBarMidScrollOffset),
slivers: <Widget>[
// Start out below the status bar, gradually move to the top of the screen.
_StatusBarPaddingSliver(
maxHeight: statusBarHeight,
scrollFactor: 7.0,
),
// Section Headings
SliverPersistentHeader(
pinned: true,
delegate: _SliverAppBarDelegate(
minHeight: _kAppBarMinHeight,
maxHeight: appBarMaxHeight,
child: NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification notification) {
return _handlePageNotification(notification, _headingPageController, _detailsPageController);
},
child: PageView(
physics: _headingScrollPhysics,
controller: _headingPageController,
children: _allHeadingItems(appBarMaxHeight, appBarMidScrollOffset),
),
),
),
),
// Details
SliverToBoxAdapter(
child: SizedBox(
height: 610.0,
child: NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification notification) {
return _handlePageNotification(notification, _detailsPageController, _headingPageController);
},
child: PageView(
controller: _detailsPageController,
children: allSections.map<Widget>((Section section) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: _detailItemsFor(section).toList(),
);
}).toList(),
),
),
),
),
],
),
),
Positioned(
top: statusBarHeight,
left: 0.0,
child: IconTheme(
data: const IconThemeData(color: Colors.white),
child: SafeArea(
top: false,
bottom: false,
child: IconButton(
icon: const BackButtonIcon(),
tooltip: 'Back',
onPressed: () {
_handleBackButton(appBarMidScrollOffset);
},
),
),
),
),
],
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/animation/home.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/animation/home.dart",
"repo_id": "flutter",
"token_count": 8784
} | 540 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
const Color _kKeyUmbraOpacity = Color(0x33000000); // alpha = 0.2
const Color _kKeyPenumbraOpacity = Color(0x24000000); // alpha = 0.14
const Color _kAmbientShadowOpacity = Color(0x1F000000); // alpha = 0.12
class CupertinoSegmentedControlDemo extends StatefulWidget {
const CupertinoSegmentedControlDemo({super.key});
static const String routeName = 'cupertino/segmented_control';
@override
State<CupertinoSegmentedControlDemo> createState() => _CupertinoSegmentedControlDemoState();
}
class _CupertinoSegmentedControlDemoState extends State<CupertinoSegmentedControlDemo> {
final Map<int, Widget> children = const <int, Widget>{
0: Text('Small'),
1: Text('Medium'),
2: Text('Large'),
};
final Map<int, Widget> icons = const <int, Widget>{
0: Center(
child: FlutterLogo(
size: 100.0,
),
),
1: Center(
child: FlutterLogo(
size: 200.0,
),
),
2: Center(
child: FlutterLogo(
size: 300.0,
),
),
};
int? currentSegment = 0;
void onValueChanged(int? newValue) {
setState(() {
currentSegment = newValue;
});
}
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: const Text('Segmented Control'),
// 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(CupertinoSegmentedControlDemo.routeName),
),
child: DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.textStyle.copyWith(fontSize: 13),
child: SafeArea(
child: Column(
children: <Widget>[
const Padding(padding: EdgeInsets.all(16.0)),
SizedBox(
width: 500.0,
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: onValueChanged,
groupValue: currentSegment,
),
),
SizedBox(
width: 500,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: CupertinoSlidingSegmentedControl<int>(
children: children,
onValueChanged: onValueChanged,
groupValue: currentSegment,
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 32.0,
horizontal: 16.0,
),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated,
child: Builder(
builder: (BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(
vertical: 64.0,
horizontal: 16.0,
),
decoration: BoxDecoration(
color: CupertinoTheme.of(context).scaffoldBackgroundColor,
borderRadius: BorderRadius.circular(3.0),
boxShadow: const <BoxShadow>[
BoxShadow(
offset: Offset(0.0, 3.0),
blurRadius: 5.0,
spreadRadius: -1.0,
color: _kKeyUmbraOpacity,
),
BoxShadow(
offset: Offset(0.0, 6.0),
blurRadius: 10.0,
color: _kKeyPenumbraOpacity,
),
BoxShadow(
offset: Offset(0.0, 1.0),
blurRadius: 18.0,
color: _kAmbientShadowOpacity,
),
],
),
child: icons[currentSegment!],
);
},
),
),
),
),
],
),
),
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_segmented_control_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_segmented_control_demo.dart",
"repo_id": "flutter",
"token_count": 2705
} | 541 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
import 'full_screen_dialog_demo.dart';
enum DialogDemoAction {
cancel,
discard,
disagree,
agree,
}
const String _alertWithoutTitleText = 'Discard draft?';
const String _alertWithTitleText =
'Let Google help apps determine location. This means sending anonymous location '
'data to Google, even when no apps are running.';
class DialogDemoItem extends StatelessWidget {
const DialogDemoItem({ super.key, this.icon, this.color, this.text, this.onPressed });
final IconData? icon;
final Color? color;
final String? text;
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) {
return SimpleDialogOption(
onPressed: onPressed,
child: Row(
children: <Widget>[
Icon(icon, size: 36.0, color: color),
Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Text(text!),
),
],
),
);
}
}
class DialogDemo extends StatefulWidget {
const DialogDemo({super.key});
static const String routeName = '/material/dialog';
@override
DialogDemoState createState() => DialogDemoState();
}
class DialogDemoState extends State<DialogDemo> {
TimeOfDay? _selectedTime;
@override
void initState() {
super.initState();
final DateTime now = DateTime.now();
_selectedTime = TimeOfDay(hour: now.hour, minute: now.minute);
}
void showDemoDialog<T>({ required BuildContext context, Widget? child }) {
showDialog<T>(
context: context,
builder: (BuildContext context) => child!,
)
.then((T? value) { // The value passed to Navigator.pop() or null.
if (value != null) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('You selected: $value'),
));
}
});
}
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final TextStyle dialogTextStyle = theme.textTheme.titleMedium!.copyWith(color: theme.textTheme.bodySmall!.color);
return Scaffold(
appBar: AppBar(
title: const Text('Dialogs'),
actions: <Widget>[MaterialDemoDocumentationButton(DialogDemo.routeName)],
),
body: ListView(
padding: const EdgeInsets.symmetric(vertical: 24.0, horizontal: 72.0),
children: <Widget>[
ElevatedButton(
child: const Text('ALERT'),
onPressed: () {
showDemoDialog<DialogDemoAction>(
context: context,
child: AlertDialog(
content: Text(
_alertWithoutTitleText,
style: dialogTextStyle,
),
actions: <Widget>[
TextButton(
child: const Text('CANCEL'),
onPressed: () { Navigator.pop(context, DialogDemoAction.cancel); },
),
TextButton(
child: const Text('DISCARD'),
onPressed: () { Navigator.pop(context, DialogDemoAction.discard); },
),
],
),
);
},
),
ElevatedButton(
child: const Text('ALERT WITH TITLE'),
onPressed: () {
showDemoDialog<DialogDemoAction>(
context: context,
child: AlertDialog(
title: const Text("Use Google's location service?"),
content: Text(
_alertWithTitleText,
style: dialogTextStyle,
),
actions: <Widget>[
TextButton(
child: const Text('DISAGREE'),
onPressed: () { Navigator.pop(context, DialogDemoAction.disagree); },
),
TextButton(
child: const Text('AGREE'),
onPressed: () { Navigator.pop(context, DialogDemoAction.agree); },
),
],
),
);
},
),
ElevatedButton(
child: const Text('SIMPLE'),
onPressed: () {
showDemoDialog<String>(
context: context,
child: SimpleDialog(
title: const Text('Set backup account'),
children: <Widget>[
DialogDemoItem(
icon: Icons.account_circle,
color: theme.primaryColor,
text: '[email protected]',
onPressed: () { Navigator.pop(context, '[email protected]'); },
),
DialogDemoItem(
icon: Icons.account_circle,
color: theme.primaryColor,
text: '[email protected]',
onPressed: () { Navigator.pop(context, '[email protected]'); },
),
DialogDemoItem(
icon: Icons.add_circle,
text: 'add account',
color: theme.disabledColor,
),
],
),
);
},
),
ElevatedButton(
child: const Text('CONFIRMATION'),
onPressed: () {
showTimePicker(
context: context,
initialTime: _selectedTime!,
)
.then((TimeOfDay? value) {
if (value != null && value != _selectedTime) {
_selectedTime = value;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('You selected: ${value.format(context)}'),
));
}
});
},
),
ElevatedButton(
child: const Text('FULLSCREEN'),
onPressed: () {
Navigator.push(context, MaterialPageRoute<DismissDialogAction>(
builder: (BuildContext context) => const FullScreenDialogDemo(),
fullscreenDialog: true,
));
},
),
]
// Add a little space between the buttons
.map<Widget>((Widget button) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: button,
);
})
.toList(),
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/material/dialog_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/dialog_demo.dart",
"repo_id": "flutter",
"token_count": 3489
} | 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 'package:flutter/material.dart';
import '../../gallery/demo.dart';
class ProgressIndicatorDemo extends StatefulWidget {
const ProgressIndicatorDemo({super.key});
static const String routeName = '/material/progress-indicator';
@override
State<ProgressIndicatorDemo> createState() => _ProgressIndicatorDemoState();
}
class _ProgressIndicatorDemoState extends State<ProgressIndicatorDemo> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 1500),
vsync: this,
animationBehavior: AnimationBehavior.preserve,
)..forward();
_animation = CurvedAnimation(
parent: _controller,
curve: const Interval(0.0, 0.9, curve: Curves.fastOutSlowIn),
reverseCurve: Curves.fastOutSlowIn,
)..addStatusListener((AnimationStatus status) {
if (status == AnimationStatus.dismissed) {
_controller.forward();
} else if (status == AnimationStatus.completed) {
_controller.reverse();
}
});
}
@override
void dispose() {
_controller.stop();
super.dispose();
}
void _handleTap() {
setState(() {
// valueAnimation.isAnimating is part of our build state
if (_controller.isAnimating) {
_controller.stop();
} else {
switch (_controller.status) {
case AnimationStatus.dismissed:
case AnimationStatus.forward:
_controller.forward();
case AnimationStatus.reverse:
case AnimationStatus.completed:
_controller.reverse();
}
}
});
}
Widget _buildIndicators(BuildContext context, Widget? child) {
final List<Widget> indicators = <Widget>[
const SizedBox(
width: 200.0,
child: LinearProgressIndicator(),
),
const LinearProgressIndicator(),
const LinearProgressIndicator(),
LinearProgressIndicator(value: _animation.value),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
const CircularProgressIndicator(),
SizedBox(
width: 20.0,
height: 20.0,
child: CircularProgressIndicator(value: _animation.value),
),
SizedBox(
width: 100.0,
height: 20.0,
child: Text('${(_animation.value * 100.0).toStringAsFixed(1)}%',
textAlign: TextAlign.right,
),
),
],
),
];
return Column(
children: indicators
.map<Widget>((Widget c) => Container(
margin: const EdgeInsets.symmetric(vertical: 15.0, horizontal: 20.0),
child: c,
))
.toList(),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Progress indicators'),
actions: <Widget>[MaterialDemoDocumentationButton(ProgressIndicatorDemo.routeName)],
),
body: Center(
child: SingleChildScrollView(
child: DefaultTextStyle(
style: Theme.of(context).textTheme.titleLarge!,
child: GestureDetector(
onTap: _handleTap,
behavior: HitTestBehavior.opaque,
child: SafeArea(
top: false,
bottom: false,
child: Container(
padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
child: AnimatedBuilder(
animation: _animation,
builder: _buildIndicators,
),
),
),
),
),
),
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/material/progress_indicator_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/progress_indicator_demo.dart",
"repo_id": "flutter",
"token_count": 1749
} | 543 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'colors.dart';
import 'model/app_state_model.dart';
import 'model/product.dart';
import 'shopping_cart.dart';
// These curves define the emphasized easing curve.
const Cubic _kAccelerateCurve = Cubic(0.548, 0.0, 0.757, 0.464);
const Cubic _kDecelerateCurve = Cubic(0.23, 0.94, 0.41, 1.0);
// The time at which the accelerate and decelerate curves switch off
const double _kPeakVelocityTime = 0.248210;
// Percent (as a decimal) of animation that should be completed at _peakVelocityTime
const double _kPeakVelocityProgress = 0.379146;
const double _kCartHeight = 56.0;
// Radius of the shape on the top left of the sheet.
const double _kCornerRadius = 24.0;
// Width for just the cart icon and no thumbnails.
const double _kWidthForCartIcon = 64.0;
class ExpandingBottomSheet extends StatefulWidget {
const ExpandingBottomSheet({super.key, required this.hideController});
final AnimationController hideController;
@override
ExpandingBottomSheetState createState() => ExpandingBottomSheetState();
static ExpandingBottomSheetState? of(BuildContext context, {bool isNullOk = false}) {
final ExpandingBottomSheetState? result = context.findAncestorStateOfType<ExpandingBottomSheetState>();
if (isNullOk || result != null) {
return result;
}
throw FlutterError(
'ExpandingBottomSheet.of() called with a context that does not contain a ExpandingBottomSheet.\n');
}
}
// Emphasized Easing is a motion curve that has an organic, exciting feeling.
// It's very fast to begin with and then very slow to finish. Unlike standard
// curves, like [Curves.fastOutSlowIn], it can't be expressed in a cubic bezier
// curve formula. It's quintic, not cubic. But it _can_ be expressed as one
// curve followed by another, which we do here.
Animation<T> _getEmphasizedEasingAnimation<T>({
required T begin,
required T peak,
required T end,
required bool isForward,
required Animation<double> parent,
}) {
Curve firstCurve;
Curve secondCurve;
double firstWeight;
double secondWeight;
if (isForward) {
firstCurve = _kAccelerateCurve;
secondCurve = _kDecelerateCurve;
firstWeight = _kPeakVelocityTime;
secondWeight = 1.0 - _kPeakVelocityTime;
} else {
firstCurve = _kDecelerateCurve.flipped;
secondCurve = _kAccelerateCurve.flipped;
firstWeight = 1.0 - _kPeakVelocityTime;
secondWeight = _kPeakVelocityTime;
}
return TweenSequence<T>(
<TweenSequenceItem<T>>[
TweenSequenceItem<T>(
weight: firstWeight,
tween: Tween<T>(
begin: begin,
end: peak,
).chain(CurveTween(curve: firstCurve)),
),
TweenSequenceItem<T>(
weight: secondWeight,
tween: Tween<T>(
begin: peak,
end: end,
).chain(CurveTween(curve: secondCurve)),
),
],
).animate(parent);
}
// Calculates the value where two double Animations should be joined. Used by
// callers of _getEmphasisedEasing<double>().
double _getPeakPoint({required double begin, required double end}) {
return begin + (end - begin) * _kPeakVelocityProgress;
}
class ExpandingBottomSheetState extends State<ExpandingBottomSheet> with TickerProviderStateMixin {
final GlobalKey _expandingBottomSheetKey = GlobalKey(debugLabel: 'Expanding bottom sheet');
// The width of the Material, calculated by _widthFor() & based on the number
// of products in the cart. 64.0 is the width when there are 0 products
// (_kWidthForZeroProducts)
double _width = _kWidthForCartIcon;
// Controller for the opening and closing of the ExpandingBottomSheet
late AnimationController _controller;
// Animations for the opening and closing of the ExpandingBottomSheet
late Animation<double> _widthAnimation;
late Animation<double> _heightAnimation;
late Animation<double> _thumbnailOpacityAnimation;
late Animation<double> _cartOpacityAnimation;
late Animation<double> _shapeAnimation;
late Animation<Offset> _slideAnimation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 500),
vsync: this,
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Animation<double> _getWidthAnimation(double screenWidth) {
if (_controller.status == AnimationStatus.forward) {
// Opening animation
return Tween<double>(begin: _width, end: screenWidth).animate(
CurvedAnimation(
parent: _controller.view,
curve: const Interval(0.0, 0.3, curve: Curves.fastOutSlowIn),
),
);
} else {
// Closing animation
return _getEmphasizedEasingAnimation(
begin: _width,
peak: _getPeakPoint(begin: _width, end: screenWidth),
end: screenWidth,
isForward: false,
parent: CurvedAnimation(parent: _controller.view, curve: const Interval(0.0, 0.87)),
);
}
}
Animation<double> _getHeightAnimation(double screenHeight) {
if (_controller.status == AnimationStatus.forward) {
// Opening animation
return _getEmphasizedEasingAnimation(
begin: _kCartHeight,
peak: _kCartHeight + (screenHeight - _kCartHeight) * _kPeakVelocityProgress,
end: screenHeight,
isForward: true,
parent: _controller.view,
);
} else {
// Closing animation
return Tween<double>(
begin: _kCartHeight,
end: screenHeight,
).animate(
CurvedAnimation(
parent: _controller.view,
curve: const Interval(0.434, 1.0), // not used
// only the reverseCurve will be used
reverseCurve: Interval(0.434, 1.0, curve: Curves.fastOutSlowIn.flipped),
),
);
}
}
// Animation of the cut corner. It's cut when closed and not cut when open.
Animation<double> _getShapeAnimation() {
if (_controller.status == AnimationStatus.forward) {
return Tween<double>(begin: _kCornerRadius, end: 0.0).animate(
CurvedAnimation(
parent: _controller.view,
curve: const Interval(0.0, 0.3, curve: Curves.fastOutSlowIn),
),
);
} else {
return _getEmphasizedEasingAnimation(
begin: _kCornerRadius,
peak: _getPeakPoint(begin: _kCornerRadius, end: 0.0),
end: 0.0,
isForward: false,
parent: _controller.view,
);
}
}
Animation<double> _getThumbnailOpacityAnimation() {
return Tween<double>(begin: 1.0, end: 0.0).animate(
CurvedAnimation(
parent: _controller.view,
curve: _controller.status == AnimationStatus.forward
? const Interval(0.0, 0.3)
: const Interval(0.532, 0.766),
),
);
}
Animation<double> _getCartOpacityAnimation() {
return CurvedAnimation(
parent: _controller.view,
curve: _controller.status == AnimationStatus.forward
? const Interval(0.3, 0.6)
: const Interval(0.766, 1.0),
);
}
// Returns the correct width of the ExpandingBottomSheet based on the number of
// products in the cart.
double _widthFor(int numProducts) {
return switch (numProducts) {
0 => _kWidthForCartIcon,
1 => 136.0,
2 => 192.0,
3 => 248.0,
_ => 278.0,
};
}
// Returns true if the cart is open or opening and false otherwise.
bool get _isOpen {
final AnimationStatus status = _controller.status;
return status == AnimationStatus.completed || status == AnimationStatus.forward;
}
// Opens the ExpandingBottomSheet if it's closed, otherwise does nothing.
void open() {
if (!_isOpen) {
_controller.forward();
}
}
// Closes the ExpandingBottomSheet if it's open or opening, otherwise does nothing.
void close() {
if (_isOpen) {
_controller.reverse();
}
}
// Changes the padding between the start edge of the Material and the cart icon
// based on the number of products in the cart (padding increases when > 0
// products.)
EdgeInsetsDirectional _cartPaddingFor(int numProducts) {
return (numProducts == 0)
? const EdgeInsetsDirectional.only(start: 20.0, end: 8.0)
: const EdgeInsetsDirectional.only(start: 32.0, end: 8.0);
}
bool get _cartIsVisible => _thumbnailOpacityAnimation.value == 0.0;
Widget _buildThumbnails(int numProducts) {
return ExcludeSemantics(
child: Opacity(
opacity: _thumbnailOpacityAnimation.value,
child: Column(
children: <Widget>[
Row(
children: <Widget>[
AnimatedPadding(
padding: _cartPaddingFor(numProducts),
duration: const Duration(milliseconds: 225),
child: const Icon(Icons.shopping_cart),
),
Container(
// Accounts for the overflow number
width: numProducts > 3 ? _width - 94.0 : _width - 64.0,
height: _kCartHeight,
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: const ProductThumbnailRow(),
),
const ExtraProductsNumber(),
],
),
],
),
),
);
}
Widget _buildShoppingCartPage() {
return Opacity(
opacity: _cartOpacityAnimation.value,
child: const ShoppingCartPage(),
);
}
Widget _buildCart(BuildContext context, Widget? child) {
// numProducts is the number of different products in the cart (does not
// include multiples of the same product).
final AppStateModel model = ScopedModel.of<AppStateModel>(context);
final int numProducts = model.productsInCart.keys.length;
final int totalCartQuantity = model.totalCartQuantity;
final Size screenSize = MediaQuery.of(context).size;
final double screenWidth = screenSize.width;
final double screenHeight = screenSize.height;
_width = _widthFor(numProducts);
_widthAnimation = _getWidthAnimation(screenWidth);
_heightAnimation = _getHeightAnimation(screenHeight);
_shapeAnimation = _getShapeAnimation();
_thumbnailOpacityAnimation = _getThumbnailOpacityAnimation();
_cartOpacityAnimation = _getCartOpacityAnimation();
return Semantics(
button: true,
value: 'Shopping cart, $totalCartQuantity items',
child: SizedBox(
width: _widthAnimation.value,
height: _heightAnimation.value,
child: Material(
animationDuration: Duration.zero,
shape: BeveledRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(_shapeAnimation.value),
),
),
elevation: 4.0,
color: kShrinePink50,
child: _cartIsVisible
? _buildShoppingCartPage()
: _buildThumbnails(numProducts),
),
),
);
}
// Builder for the hide and reveal animation when the backdrop opens and closes
Widget _buildSlideAnimation(BuildContext context, Widget? child) {
_slideAnimation = _getEmphasizedEasingAnimation(
begin: const Offset(1.0, 0.0),
peak: const Offset(_kPeakVelocityProgress, 0.0),
end: Offset.zero,
isForward: widget.hideController.status == AnimationStatus.forward,
parent: widget.hideController,
);
return SlideTransition(
position: _slideAnimation,
child: child,
);
}
// Closes the cart if the cart is open, otherwise exits the app (this should
// only be relevant for Android).
void _handlePopInvoked(bool didPop) {
if (didPop) {
return;
}
close();
}
@override
Widget build(BuildContext context) {
return AnimatedSize(
key: _expandingBottomSheetKey,
duration: const Duration(milliseconds: 225),
curve: Curves.easeInOut,
alignment: FractionalOffset.topLeft,
child: PopScope(
canPop: !_isOpen,
onPopInvoked: _handlePopInvoked,
child: AnimatedBuilder(
animation: widget.hideController,
builder: _buildSlideAnimation,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: open,
child: ScopedModelDescendant<AppStateModel>(
builder: (BuildContext context, Widget? child, AppStateModel model) {
return AnimatedBuilder(
builder: _buildCart,
animation: _controller,
);
},
),
),
),
),
);
}
}
class ProductThumbnailRow extends StatefulWidget {
const ProductThumbnailRow({super.key});
@override
State<ProductThumbnailRow> createState() => _ProductThumbnailRowState();
}
class _ProductThumbnailRowState extends State<ProductThumbnailRow> {
final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
// _list represents what's currently on screen. If _internalList updates,
// it will need to be updated to match it.
late _ListModel _list;
// _internalList represents the list as it is updated by the AppStateModel.
late List<int> _internalList;
@override
void initState() {
super.initState();
_list = _ListModel(
listKey: _listKey,
initialItems: ScopedModel.of<AppStateModel>(context).productsInCart.keys.toList(),
removedItemBuilder: _buildRemovedThumbnail,
);
_internalList = List<int>.from(_list.list);
}
Product _productWithId(int productId) {
final AppStateModel model = ScopedModel.of<AppStateModel>(context);
final Product product = model.getProductById(productId);
return product;
}
Widget _buildRemovedThumbnail(int item, BuildContext context, Animation<double> animation) {
return ProductThumbnail(animation, animation, _productWithId(item));
}
Widget _buildThumbnail(BuildContext context, int index, Animation<double> animation) {
final Animation<double> thumbnailSize = Tween<double>(begin: 0.8, end: 1.0).animate(
CurvedAnimation(
curve: const Interval(0.33, 1.0, curve: Curves.easeIn),
parent: animation,
),
);
final Animation<double> opacity = CurvedAnimation(
curve: const Interval(0.33, 1.0),
parent: animation,
);
return ProductThumbnail(thumbnailSize, opacity, _productWithId(_list[index]));
}
// If the lists are the same length, assume nothing has changed.
// If the internalList is shorter than the ListModel, an item has been removed.
// If the internalList is longer, then an item has been added.
void _updateLists() {
// Update _internalList based on the model
_internalList = ScopedModel.of<AppStateModel>(context).productsInCart.keys.toList();
final Set<int> internalSet = Set<int>.from(_internalList);
final Set<int> listSet = Set<int>.from(_list.list);
final Set<int> difference = internalSet.difference(listSet);
if (difference.isEmpty) {
return;
}
for (final int product in difference) {
if (_internalList.length < _list.length) {
_list.remove(product);
} else if (_internalList.length > _list.length) {
_list.add(product);
}
}
while (_internalList.length != _list.length) {
int index = 0;
// Check bounds and that the list elements are the same
while (_internalList.isNotEmpty &&
_list.length > 0 &&
index < _internalList.length &&
index < _list.length &&
_internalList[index] == _list[index]) {
index++;
}
}
}
Widget _buildAnimatedList() {
return AnimatedList(
key: _listKey,
shrinkWrap: true,
itemBuilder: _buildThumbnail,
initialItemCount: _list.length,
scrollDirection: Axis.horizontal,
physics: const NeverScrollableScrollPhysics(), // Cart shouldn't scroll
);
}
@override
Widget build(BuildContext context) {
_updateLists();
return ScopedModelDescendant<AppStateModel>(
builder: (BuildContext context, Widget? child, AppStateModel model) => _buildAnimatedList(),
);
}
}
class ExtraProductsNumber extends StatelessWidget {
const ExtraProductsNumber({super.key});
// Calculates the number to be displayed at the end of the row if there are
// more than three products in the cart. This calculates overflow products,
// including their duplicates (but not duplicates of products shown as
// thumbnails).
int _calculateOverflow(AppStateModel model) {
final Map<int, int> productMap = model.productsInCart;
// List created to be able to access products by index instead of ID.
// Order is guaranteed because productsInCart returns a LinkedHashMap.
final List<int> products = productMap.keys.toList();
int overflow = 0;
final int numProducts = products.length;
if (numProducts > 3) {
for (int i = 3; i < numProducts; i++) {
overflow += productMap[products[i]]!;
}
}
return overflow;
}
Widget _buildOverflow(AppStateModel model, BuildContext context) {
if (model.productsInCart.length <= 3) {
return Container();
}
final int numOverflowProducts = _calculateOverflow(model);
// Maximum of 99 so padding doesn't get messy.
final int displayedOverflowProducts = numOverflowProducts <= 99 ? numOverflowProducts : 99;
return Text(
'+$displayedOverflowProducts',
style: Theme.of(context).primaryTextTheme.labelLarge,
);
}
@override
Widget build(BuildContext context) {
return ScopedModelDescendant<AppStateModel>(
builder: (BuildContext builder, Widget? child, AppStateModel model) => _buildOverflow(model, context),
);
}
}
class ProductThumbnail extends StatelessWidget {
const ProductThumbnail(this.animation, this.opacityAnimation, this.product, {super.key});
final Animation<double> animation;
final Animation<double> opacityAnimation;
final Product product;
@override
Widget build(BuildContext context) {
return FadeTransition(
opacity: opacityAnimation,
child: ScaleTransition(
scale: animation,
child: Container(
width: 40.0,
height: 40.0,
decoration: BoxDecoration(
image: DecorationImage(
image: ExactAssetImage(
product.assetName, // asset name
package: product.assetPackage, // asset package
),
fit: BoxFit.cover,
),
borderRadius: const BorderRadius.all(Radius.circular(10.0)),
),
margin: const EdgeInsets.only(left: 16.0),
),
),
);
}
}
// _ListModel manipulates an internal list and an AnimatedList
class _ListModel {
_ListModel({
required this.listKey,
required this.removedItemBuilder,
Iterable<int>? initialItems,
}) : _items = initialItems?.toList() ?? <int>[];
final GlobalKey<AnimatedListState> listKey;
final Widget Function(int item, BuildContext context, Animation<double> animation) removedItemBuilder;
final List<int> _items;
AnimatedListState? get _animatedList => listKey.currentState;
void add(int product) {
_insert(_items.length, product);
}
void _insert(int index, int item) {
_items.insert(index, item);
_animatedList!.insertItem(index, duration: const Duration(milliseconds: 225));
}
void remove(int product) {
final int index = _items.indexOf(product);
if (index >= 0) {
_removeAt(index);
}
}
void _removeAt(int index) {
final int removedItem = _items.removeAt(index);
_animatedList!.removeItem(index, (BuildContext context, Animation<double> animation) {
return removedItemBuilder(removedItem, context, animation);
});
}
int get length => _items.length;
int operator [](int index) => _items[index];
int indexOf(int item) => _items.indexOf(item);
List<int> get list => _items;
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/expanding_bottom_sheet.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/expanding_bottom_sheet.dart",
"repo_id": "flutter",
"token_count": 7519
} | 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';
import 'package:vector_math/vector_math_64.dart' show Vector3;
import 'transformations_demo_inertial_motion.dart';
// This widget allows 2D transform interactions on its child in relation to its
// parent. The user can transform the child by dragging to pan or pinching to
// zoom and rotate. All event callbacks for GestureDetector are supported, and
// the coordinates that are given are untransformed and in relation to the
// original position of the child.
@immutable
class GestureTransformable extends StatefulWidget {
const GestureTransformable({
super.key,
// The child to perform the transformations on.
required this.child,
// The desired visible size of the widget and the area that is receptive to
// gestures. If a widget that's as big as possible is desired, then wrap
// this in a LayoutBuilder and pass
// `Size(constraints.maxWidth, constraints.maxHeight)`.
required this.size,
// The scale will be clamped to between these values. A maxScale of null has
// no bounds. minScale must be greater than zero.
this.maxScale = 2.5,
this.minScale = 0.8,
// Transforms will be limited so that the viewport can not view beyond this
// Rect. The Rect does not rotate with the rest of the scene, so it is
// always aligned with the viewport. A null boundaryRect results in no
// limits to the distance that the viewport can be transformed to see.
this.boundaryRect,
// Initial values for the transform can be provided.
this.initialTranslation,
this.initialScale,
this.initialRotation,
// Any and all of the possible transformations can be disabled.
this.disableTranslation = false,
this.disableScale = false,
this.disableRotation = false,
// If set to true, this widget will animate back to its initial transform
// and call onResetEnd when done. When utilizing reset, onResetEnd should
// also be implemented, and it should set reset to false when called.
this.reset = false,
// Access to event callbacks from GestureDetector. Called with untransformed
// coordinates in an Offset.
this.onTapDown,
this.onTapUp,
this.onTap,
this.onTapCancel,
this.onDoubleTap,
this.onLongPress,
this.onLongPressUp,
this.onVerticalDragDown,
this.onVerticalDragStart,
this.onVerticalDragUpdate,
this.onVerticalDragEnd,
this.onVerticalDragCancel,
this.onHorizontalDragDown,
this.onHorizontalDragStart,
this.onHorizontalDragUpdate,
this.onHorizontalDragEnd,
this.onHorizontalDragCancel,
this.onPanDown,
this.onPanStart,
this.onPanUpdate,
this.onPanEnd,
this.onPanCancel,
this.onResetEnd,
this.onScaleStart,
this.onScaleUpdate,
this.onScaleEnd,
}) : assert(minScale > 0),
assert(
!reset || onResetEnd != null,
'Must implement onResetEnd to use reset.',
);
final Widget child;
final Size size;
final bool reset;
final GestureTapDownCallback? onTapDown;
final GestureTapUpCallback? onTapUp;
final GestureTapCallback? onTap;
final GestureTapCancelCallback? onTapCancel;
final GestureTapCallback? onDoubleTap;
final GestureLongPressCallback? onLongPress;
final GestureLongPressUpCallback? onLongPressUp;
final GestureDragDownCallback? onVerticalDragDown;
final GestureDragStartCallback? onVerticalDragStart;
final GestureDragUpdateCallback? onVerticalDragUpdate;
final GestureDragEndCallback? onVerticalDragEnd;
final GestureDragCancelCallback? onVerticalDragCancel;
final GestureDragDownCallback? onHorizontalDragDown;
final GestureDragStartCallback? onHorizontalDragStart;
final GestureDragUpdateCallback? onHorizontalDragUpdate;
final GestureDragEndCallback? onHorizontalDragEnd;
final GestureDragCancelCallback? onHorizontalDragCancel;
final GestureDragDownCallback? onPanDown;
final GestureDragStartCallback? onPanStart;
final GestureDragUpdateCallback? onPanUpdate;
final GestureDragEndCallback? onPanEnd;
final GestureDragCancelCallback? onPanCancel;
final VoidCallback? onResetEnd;
final GestureScaleStartCallback? onScaleStart;
final GestureScaleUpdateCallback? onScaleUpdate;
final GestureScaleEndCallback? onScaleEnd;
final double maxScale;
final double minScale;
final Rect? boundaryRect;
final bool disableTranslation;
final bool disableScale;
final bool disableRotation;
final Offset? initialTranslation;
final double? initialScale;
final double? initialRotation;
@override
State<GestureTransformable> createState() => _GestureTransformableState();
}
// A single user event can only represent one of these gestures. The user can't
// do multiple at the same time, which results in more precise transformations.
enum _GestureType {
translate,
scale,
rotate,
}
// This is public only for access from a unit test.
class _GestureTransformableState extends State<GestureTransformable> with TickerProviderStateMixin {
Animation<Offset>? _animation;
late AnimationController _controller;
Animation<Matrix4>? _animationReset;
late AnimationController _controllerReset;
// The translation that will be applied to the scene (not viewport).
// A positive x offset moves the scene right, viewport left.
// A positive y offset moves the scene down, viewport up.
Offset? _translateFromScene; // Point where a single translation began.
double? _scaleStart; // Scale value at start of scaling gesture.
double? _rotationStart = 0.0; // Rotation at start of rotation gesture.
late Rect _boundaryRect;
Matrix4 _transform = Matrix4.identity();
double _currentRotation = 0.0;
_GestureType? gestureType;
// The transformation matrix that gives the initial home position.
Matrix4 get _initialTransform {
Matrix4 matrix = Matrix4.identity();
if (widget.initialTranslation != null) {
matrix = matrixTranslate(matrix, widget.initialTranslation);
}
if (widget.initialScale != null) {
matrix = matrixScale(matrix, widget.initialScale);
}
if (widget.initialRotation != null) {
matrix = matrixRotate(matrix, widget.initialRotation, Offset.zero);
}
return matrix;
}
// Return the scene point at the given viewport point.
static Offset fromViewport(Offset viewportPoint, Matrix4 transform) {
// On viewportPoint, perform the inverse transformation of the scene to get
// where the point would be in the scene before the transformation.
final Matrix4 inverseMatrix = Matrix4.inverted(transform);
final Vector3 untransformed = inverseMatrix.transform3(Vector3(
viewportPoint.dx,
viewportPoint.dy,
0,
));
return Offset(untransformed.x, untransformed.y);
}
// Get the offset of the current widget from the global screen coordinates.
static Offset getOffset(BuildContext context) {
assert(context.findRenderObject() != null, 'The given context must have a renderObject, such as after the first build has completed.');
final RenderBox renderObject = context.findRenderObject()! as RenderBox;
return renderObject.localToGlobal(Offset.zero);
}
@override
void initState() {
super.initState();
_boundaryRect = widget.boundaryRect ?? Offset.zero & widget.size;
_transform = _initialTransform;
_controller = AnimationController(
vsync: this,
);
_controllerReset = AnimationController(
vsync: this,
);
if (widget.reset) {
_animateResetInitialize();
}
}
@override
void didUpdateWidget(GestureTransformable oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.reset && !oldWidget.reset && _animationReset == null) {
_animateResetInitialize();
} else if (!widget.reset && oldWidget.reset && _animationReset != null) {
_animateResetStop();
}
}
@override
Widget build(BuildContext context) {
// A GestureDetector allows the detection of panning and zooming gestures on
// its child, which is the CustomPaint.
return GestureDetector(
behavior: HitTestBehavior.opaque, // Necessary when translating off screen
onTapDown: widget.onTapDown == null ? null : (TapDownDetails details) {
widget.onTapDown!(TapDownDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onTapUp: widget.onTapUp == null ? null : (TapUpDetails details) {
widget.onTapUp!(TapUpDetails(
kind: details.kind,
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onTap: widget.onTap,
onTapCancel: widget.onTapCancel,
onDoubleTap: widget.onDoubleTap,
onLongPress: widget.onLongPress,
onLongPressUp: widget.onLongPressUp,
onVerticalDragDown: widget.onVerticalDragDown == null ? null : (DragDownDetails details) {
widget.onVerticalDragDown!(DragDownDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onVerticalDragStart: widget.onVerticalDragStart == null ? null : (DragStartDetails details) {
widget.onVerticalDragStart!(DragStartDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onVerticalDragUpdate: widget.onVerticalDragUpdate == null ? null : (DragUpdateDetails details) {
widget.onVerticalDragUpdate!(DragUpdateDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onVerticalDragEnd: widget.onVerticalDragEnd,
onVerticalDragCancel: widget.onVerticalDragCancel,
onHorizontalDragDown: widget.onHorizontalDragDown == null ? null : (DragDownDetails details) {
widget.onHorizontalDragDown!(DragDownDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onHorizontalDragStart: widget.onHorizontalDragStart == null ? null : (DragStartDetails details) {
widget.onHorizontalDragStart!(DragStartDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onHorizontalDragUpdate: widget.onHorizontalDragUpdate == null ? null : (DragUpdateDetails details) {
widget.onHorizontalDragUpdate!(DragUpdateDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onHorizontalDragEnd: widget.onHorizontalDragEnd,
onHorizontalDragCancel: widget.onHorizontalDragCancel,
onPanDown: widget.onPanDown == null ? null : (DragDownDetails details) {
widget.onPanDown!(DragDownDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onPanStart: widget.onPanStart == null ? null : (DragStartDetails details) {
widget.onPanStart!(DragStartDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onPanUpdate: widget.onPanUpdate == null ? null : (DragUpdateDetails details) {
widget.onPanUpdate!(DragUpdateDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onPanEnd: widget.onPanEnd,
onPanCancel: widget.onPanCancel,
onScaleEnd: _onScaleEnd,
onScaleStart: _onScaleStart,
onScaleUpdate: _onScaleUpdate,
child: ClipRect(
// The scene is panned/zoomed/rotated using this Transform widget.
child: Transform(
transform: _transform,
child: SizedBox(
height: widget.size.height,
width: widget.size.width,
child: widget.child,
),
),
),
);
}
// Return a new matrix representing the given matrix after applying the given
// translation.
Matrix4 matrixTranslate(Matrix4 matrix, Offset? translation) {
if (widget.disableTranslation || translation == Offset.zero) {
return matrix;
}
// Clamp translation so the viewport remains inside _boundaryRect.
final double scale = _transform.getMaxScaleOnAxis();
final Size scaledSize = widget.size / scale;
final Rect viewportBoundaries = Rect.fromLTRB(
_boundaryRect.left,
_boundaryRect.top,
_boundaryRect.right - scaledSize.width,
_boundaryRect.bottom - scaledSize.height,
);
// Translation is reversed (a positive translation moves the scene to the
// right, viewport to the left).
final Rect translationBoundaries = Rect.fromLTRB(
-scale * viewportBoundaries.right,
-scale * viewportBoundaries.bottom,
-scale * viewportBoundaries.left,
-scale * viewportBoundaries.top,
);
final Matrix4 nextMatrix = matrix.clone()..translate(
translation!.dx,
translation.dy,
);
final Vector3 nextTranslationVector = nextMatrix.getTranslation();
final Offset nextTranslation = Offset(
nextTranslationVector.x,
nextTranslationVector.y,
);
final bool inBoundaries = translationBoundaries.contains(
Offset(nextTranslation.dx, nextTranslation.dy),
);
if (!inBoundaries) {
return matrix;
}
return nextMatrix;
}
// Return a new matrix representing the given matrix after applying the given
// scale transform.
Matrix4 matrixScale(Matrix4 matrix, double? scale) {
if (widget.disableScale || scale == 1) {
return matrix;
}
assert(scale != 0);
// Don't allow a scale that moves the viewport outside of _boundaryRect.
final Offset tl = fromViewport(Offset.zero, _transform);
final Offset tr = fromViewport(Offset(widget.size.width, 0), _transform);
final Offset bl = fromViewport(Offset(0, widget.size.height), _transform);
final Offset br = fromViewport(
Offset(widget.size.width, widget.size.height),
_transform,
);
if (!_boundaryRect.contains(tl)
|| !_boundaryRect.contains(tr)
|| !_boundaryRect.contains(bl)
|| !_boundaryRect.contains(br)) {
return matrix;
}
// Don't allow a scale that results in an overall scale beyond min/max
// scale.
final double currentScale = _transform.getMaxScaleOnAxis();
final double totalScale = currentScale * scale!;
final double clampedTotalScale = totalScale.clamp(
widget.minScale,
widget.maxScale,
);
final double clampedScale = clampedTotalScale / currentScale;
return matrix..scale(clampedScale);
}
// Return a new matrix representing the given matrix after applying the given
// rotation transform.
// Rotating the scene cannot cause the viewport to view beyond _boundaryRect.
Matrix4 matrixRotate(Matrix4 matrix, double? rotation, Offset focalPoint) {
if (widget.disableRotation || rotation == 0) {
return matrix;
}
final Offset focalPointScene = fromViewport(focalPoint, matrix);
return matrix
..translate(focalPointScene.dx, focalPointScene.dy)
..rotateZ(-rotation!)
..translate(-focalPointScene.dx, -focalPointScene.dy);
}
// Handle the start of a gesture of _GestureType.
void _onScaleStart(ScaleStartDetails details) {
widget.onScaleStart?.call(details);
if (_controller.isAnimating) {
_controller.stop();
_controller.reset();
_animation?.removeListener(_onAnimate);
_animation = null;
}
if (_controllerReset.isAnimating) {
_animateResetStop();
}
gestureType = null;
setState(() {
_scaleStart = _transform.getMaxScaleOnAxis();
_translateFromScene = fromViewport(details.focalPoint, _transform);
_rotationStart = _currentRotation;
});
}
// Handle an update to an ongoing gesture of _GestureType.
void _onScaleUpdate(ScaleUpdateDetails details) {
double scale = _transform.getMaxScaleOnAxis();
widget.onScaleUpdate?.call(ScaleUpdateDetails(
focalPoint: fromViewport(details.focalPoint, _transform),
scale: details.scale,
rotation: details.rotation,
));
final Offset focalPointScene = fromViewport(
details.focalPoint,
_transform,
);
if (gestureType == null) {
// Decide which type of gesture this is by comparing the amount of scale
// and rotation in the gesture, if any. Scale starts at 1 and rotation
// starts at 0. Translate will have 0 scale and 0 rotation because it uses
// only one finger.
if ((details.scale - 1).abs() > details.rotation.abs()) {
gestureType = _GestureType.scale;
} else if (details.rotation != 0) {
gestureType = _GestureType.rotate;
} else {
gestureType = _GestureType.translate;
}
}
setState(() {
if (gestureType == _GestureType.scale && _scaleStart != null) {
// details.scale gives us the amount to change the scale as of the
// start of this gesture, so calculate the amount to scale as of the
// previous call to _onScaleUpdate.
final double desiredScale = _scaleStart! * details.scale;
final double scaleChange = desiredScale / scale;
_transform = matrixScale(_transform, scaleChange);
scale = _transform.getMaxScaleOnAxis();
// While scaling, translate such that the user's two fingers stay on the
// same places in the scene. That means that the focal point of the
// scale should be on the same place in the scene before and after the
// scale.
final Offset focalPointSceneNext = fromViewport(
details.focalPoint,
_transform,
);
_transform = matrixTranslate(_transform, focalPointSceneNext - focalPointScene);
} else if (gestureType == _GestureType.rotate && details.rotation != 0.0) {
final double desiredRotation = _rotationStart! + details.rotation;
_transform = matrixRotate(_transform, _currentRotation - desiredRotation, details.focalPoint);
_currentRotation = desiredRotation;
} else if (_translateFromScene != null && details.scale == 1.0) {
// Translate so that the same point in the scene is underneath the
// focal point before and after the movement.
final Offset translationChange = focalPointScene - _translateFromScene!;
_transform = matrixTranslate(_transform, translationChange);
_translateFromScene = fromViewport(details.focalPoint, _transform);
}
});
}
// Handle the end of a gesture of _GestureType.
void _onScaleEnd(ScaleEndDetails details) {
widget.onScaleEnd?.call(details);
setState(() {
_scaleStart = null;
_rotationStart = null;
_translateFromScene = null;
});
_animation?.removeListener(_onAnimate);
_controller.reset();
// If the scale ended with velocity, animate inertial movement
final double velocityTotal = details.velocity.pixelsPerSecond.dx.abs()
+ details.velocity.pixelsPerSecond.dy.abs();
if (velocityTotal == 0) {
return;
}
final Vector3 translationVector = _transform.getTranslation();
final Offset translation = Offset(translationVector.x, translationVector.y);
final InertialMotion inertialMotion = InertialMotion(details.velocity, translation);
_animation = Tween<Offset>(
begin: translation,
end: inertialMotion.finalPosition,
).animate(_controller);
_controller.duration = Duration(milliseconds: inertialMotion.duration.toInt());
_animation!.addListener(_onAnimate);
_controller.fling();
}
// Handle inertia drag animation.
void _onAnimate() {
setState(() {
// Translate _transform such that the resulting translation is
// _animation.value.
final Vector3 translationVector = _transform.getTranslation();
final Offset translation = Offset(translationVector.x, translationVector.y);
final Offset translationScene = fromViewport(translation, _transform);
final Offset animationScene = fromViewport(_animation!.value, _transform);
final Offset translationChangeScene = animationScene - translationScene;
_transform = matrixTranslate(_transform, translationChangeScene);
});
if (!_controller.isAnimating) {
_animation?.removeListener(_onAnimate);
_animation = null;
_controller.reset();
}
}
// Handle reset to home transform animation.
void _onAnimateReset() {
setState(() {
_transform = _animationReset!.value;
});
if (!_controllerReset.isAnimating) {
_animationReset?.removeListener(_onAnimateReset);
_animationReset = null;
_controllerReset.reset();
widget.onResetEnd!();
}
}
// Initialize the reset to home transform animation.
void _animateResetInitialize() {
_controllerReset.reset();
_animationReset = Matrix4Tween(
begin: _transform,
end: _initialTransform,
).animate(_controllerReset);
_controllerReset.duration = const Duration(milliseconds: 400);
_animationReset!.addListener(_onAnimateReset);
_controllerReset.forward();
}
// Stop a running reset to home transform animation.
void _animateResetStop() {
_controllerReset.stop();
_animationReset?.removeListener(_onAnimateReset);
_animationReset = null;
_controllerReset.reset();
widget.onResetEnd!();
}
@override
void dispose() {
_controller.dispose();
_controllerReset.dispose();
super.dispose();
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/transformations/transformations_demo_gesture_transformable.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/transformations/transformations_demo_gesture_transformable.dart",
"repo_id": "flutter",
"token_count": 7423
} | 545 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:string_scanner/string_scanner.dart';
class SyntaxHighlighterStyle {
const SyntaxHighlighterStyle({
this.baseStyle,
this.numberStyle,
this.commentStyle,
this.keywordStyle,
this.stringStyle,
this.punctuationStyle,
this.classStyle,
this.constantStyle,
});
static const SyntaxHighlighterStyle lightThemeStyle = SyntaxHighlighterStyle(
baseStyle: TextStyle(color: Color(0xFF000000)),
numberStyle: TextStyle(color: Color(0xFF1565C0)),
commentStyle: TextStyle(color: Color(0xFF9E9E9E)),
keywordStyle: TextStyle(color: Color(0xFF9C27B0)),
stringStyle: TextStyle(color: Color(0xFF43A047)),
punctuationStyle: TextStyle(color: Color(0xFF000000)),
classStyle: TextStyle(color: Color(0xFF512DA8)),
constantStyle: TextStyle(color: Color(0xFF795548)),
);
static const SyntaxHighlighterStyle darkThemeStyle = SyntaxHighlighterStyle(
baseStyle: TextStyle(color: Color(0xFFFFFFFF)),
numberStyle: TextStyle(color: Color(0xFF1565C0)),
commentStyle: TextStyle(color: Color(0xFF9E9E9E)),
keywordStyle: TextStyle(color: Color(0xFF80CBC4)),
stringStyle: TextStyle(color: Color(0xFF009688)),
punctuationStyle: TextStyle(color: Color(0xFFFFFFFF)),
classStyle: TextStyle(color: Color(0xFF009688)),
constantStyle: TextStyle(color: Color(0xFF795548)),
);
final TextStyle? baseStyle;
final TextStyle? numberStyle;
final TextStyle? commentStyle;
final TextStyle? keywordStyle;
final TextStyle? stringStyle;
final TextStyle? punctuationStyle;
final TextStyle? classStyle;
final TextStyle? constantStyle;
}
abstract class SyntaxHighlighter {
TextSpan format(String src);
}
class DartSyntaxHighlighter extends SyntaxHighlighter {
DartSyntaxHighlighter([this._style]) {
_spans = <_HighlightSpan>[];
_style ??= SyntaxHighlighterStyle.darkThemeStyle;
}
SyntaxHighlighterStyle? _style;
static const List<String> _keywords = <String>[
'abstract', 'as', 'assert', 'async', 'await', 'break', 'case', 'catch',
'class', 'const', 'continue', 'default', 'deferred', 'do', 'dynamic', 'else',
'enum', 'export', 'external', 'extends', 'factory', 'false', 'final',
'finally', 'for', 'get', 'if', 'implements', 'import', 'in', 'is', 'library',
'new', 'null', 'operator', 'part', 'rethrow', 'return', 'set', 'static',
'super', 'switch', 'sync', 'this', 'throw', 'true', 'try', 'typedef', 'var',
'void', 'while', 'with', 'yield',
];
static const List<String> _builtInTypes = <String>[
'int', 'double', 'num', 'bool',
];
String? _src;
late StringScanner _scanner;
late List<_HighlightSpan> _spans;
@override
TextSpan format(String? src) {
_src = src;
_scanner = StringScanner(_src!);
if (_generateSpans()) {
// Successfully parsed the code
final List<TextSpan> formattedText = <TextSpan>[];
int currentPosition = 0;
for (final _HighlightSpan span in _spans) {
if (currentPosition != span.start) {
formattedText.add(TextSpan(text: _src!.substring(currentPosition, span.start)));
}
formattedText.add(TextSpan(style: span.textStyle(_style), text: span.textForSpan(_src!)));
currentPosition = span.end;
}
if (currentPosition != _src!.length) {
formattedText.add(TextSpan(text: _src!.substring(currentPosition, _src!.length)));
}
return TextSpan(style: _style!.baseStyle, children: formattedText);
} else {
// Parsing failed, return with only basic formatting
return TextSpan(style: _style!.baseStyle, text: src);
}
}
bool _generateSpans() {
int lastLoopPosition = _scanner.position;
while (!_scanner.isDone) {
// Skip White space
_scanner.scan(RegExp(r'\s+'));
// Block comments
if (_scanner.scan(RegExp(r'/\*(.|\n)*\*/'))) {
_spans.add(_HighlightSpan(
_HighlightType.comment,
_scanner.lastMatch!.start,
_scanner.lastMatch!.end,
));
continue;
}
// Line comments
if (_scanner.scan('//')) {
final int startComment = _scanner.lastMatch!.start;
bool eof = false;
int endComment;
if (_scanner.scan(RegExp(r'.*\n'))) {
endComment = _scanner.lastMatch!.end - 1;
} else {
eof = true;
endComment = _src!.length;
}
_spans.add(_HighlightSpan(
_HighlightType.comment,
startComment,
endComment,
));
if (eof) {
break;
}
continue;
}
// Raw r"String"
if (_scanner.scan(RegExp(r'r".*"'))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch!.start,
_scanner.lastMatch!.end,
));
continue;
}
// Raw r'String'
if (_scanner.scan(RegExp(r"r'.*'"))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch!.start,
_scanner.lastMatch!.end,
));
continue;
}
// Multiline """String"""
if (_scanner.scan(RegExp(r'"""(?:[^"\\]|\\(.|\n))*"""'))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch!.start,
_scanner.lastMatch!.end,
));
continue;
}
// Multiline '''String'''
if (_scanner.scan(RegExp(r"'''(?:[^'\\]|\\(.|\n))*'''"))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch!.start,
_scanner.lastMatch!.end,
));
continue;
}
// "String"
if (_scanner.scan(RegExp(r'"(?:[^"\\]|\\.)*"'))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch!.start,
_scanner.lastMatch!.end,
));
continue;
}
// 'String'
if (_scanner.scan(RegExp(r"'(?:[^'\\]|\\.)*'"))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch!.start,
_scanner.lastMatch!.end,
));
continue;
}
// Double
if (_scanner.scan(RegExp(r'\d+\.\d+'))) {
_spans.add(_HighlightSpan(
_HighlightType.number,
_scanner.lastMatch!.start,
_scanner.lastMatch!.end,
));
continue;
}
// Integer
if (_scanner.scan(RegExp(r'\d+'))) {
_spans.add(_HighlightSpan(
_HighlightType.number,
_scanner.lastMatch!.start,
_scanner.lastMatch!.end)
);
continue;
}
// Punctuation
if (_scanner.scan(RegExp(r'[\[\]{}().!=<>&\|\?\+\-\*/%\^~;:,]'))) {
_spans.add(_HighlightSpan(
_HighlightType.punctuation,
_scanner.lastMatch!.start,
_scanner.lastMatch!.end,
));
continue;
}
// Meta data
if (_scanner.scan(RegExp(r'@\w+'))) {
_spans.add(_HighlightSpan(
_HighlightType.keyword,
_scanner.lastMatch!.start,
_scanner.lastMatch!.end,
));
continue;
}
// Words
if (_scanner.scan(RegExp(r'\w+'))) {
_HighlightType? type;
String word = _scanner.lastMatch![0]!;
if (word.startsWith('_')) {
word = word.substring(1);
}
if (_keywords.contains(word)) {
type = _HighlightType.keyword;
} else if (_builtInTypes.contains(word)) {
type = _HighlightType.keyword;
} else if (_firstLetterIsUpperCase(word)) {
type = _HighlightType.klass;
} else if (word.length >= 2 && word.startsWith('k') && _firstLetterIsUpperCase(word.substring(1))) {
type = _HighlightType.constant;
}
if (type != null) {
_spans.add(_HighlightSpan(
type,
_scanner.lastMatch!.start,
_scanner.lastMatch!.end,
));
}
}
// Check if this loop did anything
if (lastLoopPosition == _scanner.position) {
// Failed to parse this file, abort gracefully
return false;
}
lastLoopPosition = _scanner.position;
}
_simplify();
return true;
}
void _simplify() {
for (int i = _spans.length - 2; i >= 0; i -= 1) {
if (_spans[i].type == _spans[i + 1].type && _spans[i].end == _spans[i + 1].start) {
_spans[i] = _HighlightSpan(
_spans[i].type,
_spans[i].start,
_spans[i + 1].end,
);
_spans.removeAt(i + 1);
}
}
}
bool _firstLetterIsUpperCase(String str) {
if (str.isNotEmpty) {
final String first = str.substring(0, 1);
return first == first.toUpperCase();
}
return false;
}
}
enum _HighlightType {
number,
comment,
keyword,
string,
punctuation,
klass,
constant
}
class _HighlightSpan {
_HighlightSpan(this.type, this.start, this.end);
final _HighlightType type;
final int start;
final int end;
String textForSpan(String src) {
return src.substring(start, end);
}
TextStyle? textStyle(SyntaxHighlighterStyle? style) {
if (type == _HighlightType.number) {
return style!.numberStyle;
} else if (type == _HighlightType.comment) {
return style!.commentStyle;
} else if (type == _HighlightType.keyword) {
return style!.keywordStyle;
} else if (type == _HighlightType.string) {
return style!.stringStyle;
} else if (type == _HighlightType.punctuation) {
return style!.punctuationStyle;
} else if (type == _HighlightType.klass) {
return style!.classStyle;
} else if (type == _HighlightType.constant) {
return style!.constantStyle;
} else {
return style!.baseStyle;
}
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/gallery/syntax_highlighter.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/gallery/syntax_highlighter.dart",
"repo_id": "flutter",
"token_count": 4540
} | 546 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| flutter/dev/integration_tests/flutter_gallery/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "flutter",
"token_count": 32
} | 547 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_gallery/demo/material/expansion_panels_demo.dart';
import 'package:flutter_test/flutter_test.dart';
Future<void> main() async {
testWidgets('Expansion panel demo: radio tile selection changes on tap', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: ExpansionPanelsDemo()));
expect(_expandIcons, findsNWidgets(3));
await tester.tap(find.byWidget(_radioPanelExpandIcon));
await tester.pumpAndSettle();
expect(_radioFinder, findsNWidgets(3));
const int i = 1;
expect(_isRadioSelected(0), isTrue);
expect(_isRadioSelected(i), isFalse);
await tester.tap(find.byWidget(_radioListTiles[i]));
await tester.pumpAndSettle();
expect(_isRadioSelected(0), isFalse);
expect(_isRadioSelected(i), isTrue);
});
}
Finder get _expandIcons => find.byType(ExpandIcon);
Widget get _radioPanelExpandIcon => _expandIcons.evaluate().toList()[1].widget;
bool _isRadioSelected(int index) =>
_radios[index].value == _radios[index].groupValue;
List<Radio<Location>> get _radios => List<Radio<Location>>.from(
_radioFinder.evaluate().map<Widget>((Element e) => e.widget));
// [find.byType] and [find.widgetWithText] do not match subclasses; `Radio` is
// not sufficient to find a `Radio<_Location>`. Another approach is to grab the
// `runtimeType` of a dummy instance; see
// packages/flutter/test/material/radio_list_tile_test.dart.
Finder get _radioFinder =>
find.byWidgetPredicate((Widget w) => w is Radio<Location>);
List<RadioListTile<Location>> get _radioListTiles =>
List<RadioListTile<Location>>.from(
_radioListTilesFinder.evaluate().map<Widget>((Element e) => e.widget));
Finder get _radioListTilesFinder =>
find.byWidgetPredicate((Widget w) => w is RadioListTile<Location>);
| flutter/dev/integration_tests/flutter_gallery/test/demo/material/expansion_panels_demo_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/test/demo/material/expansion_panels_demo_test.dart",
"repo_id": "flutter",
"token_count": 688
} | 548 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
void main() {
group('scrolling performance test', () {
late FlutterDriver driver;
setUpAll(() async {
driver = await FlutterDriver.connect();
await driver.waitUntilFirstFrameRasterized();
});
tearDownAll(() async {
driver.close();
});
test('measure', () async {
final Timeline timeline = await driver.traceAction(() async {
await driver.tap(find.text('Material'));
final SerializableFinder demoList = find.byValueKey('GalleryDemoList');
for (int i = 0; i < 5; i++) {
await driver.scroll(demoList, 0.0, -300.0, const Duration(milliseconds: 300));
await Future<void>.delayed(const Duration(milliseconds: 500));
}
// Scroll up
for (int i = 0; i < 5; i++) {
await driver.scroll(demoList, 0.0, 300.0, const Duration(milliseconds: 300));
await Future<void>.delayed(const Duration(milliseconds: 500));
}
}, retainPriorEvents: true);
final TimelineSummary summary = TimelineSummary.summarize(timeline);
await summary.writeTimelineToFile('home_scroll_perf', pretty: true);
}, timeout: Timeout.none);
});
}
| flutter/dev/integration_tests/flutter_gallery/test_driver/scroll_perf_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/test_driver/scroll_perf_test.dart",
"repo_id": "flutter",
"token_count": 539
} | 549 |
# ios_add2app_life_cycle_flutter
A new flutter module project.
## Getting Started
For help getting started with Flutter, view our online
[documentation](https://flutter.dev/).
| flutter/dev/integration_tests/ios_add2app_life_cycle/flutterapp/README.md/0 | {
"file_path": "flutter/dev/integration_tests/ios_add2app_life_cycle/flutterapp/README.md",
"repo_id": "flutter",
"token_count": 55
} | 550 |
{
"assets" : [
{
"idiom" : "watch",
"filename" : "Circular.imageset",
"role" : "circular"
},
{
"idiom" : "watch",
"filename" : "Extra Large.imageset",
"role" : "extra-large"
},
{
"idiom" : "watch",
"filename" : "Graphic Bezel.imageset",
"role" : "graphic-bezel"
},
{
"idiom" : "watch",
"filename" : "Graphic Circular.imageset",
"role" : "graphic-circular"
},
{
"idiom" : "watch",
"filename" : "Graphic Corner.imageset",
"role" : "graphic-corner"
},
{
"idiom" : "watch",
"filename" : "Graphic Large Rectangular.imageset",
"role" : "graphic-large-rectangular"
},
{
"idiom" : "watch",
"filename" : "Modular.imageset",
"role" : "modular"
},
{
"idiom" : "watch",
"filename" : "Utilitarian.imageset",
"role" : "utilitarian"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | flutter/dev/integration_tests/ios_app_with_extensions/ios/watch Extension/Assets.xcassets/Complication.complicationset/Contents.json/0 | {
"file_path": "flutter/dev/integration_tests/ios_app_with_extensions/ios/watch Extension/Assets.xcassets/Complication.complicationset/Contents.json",
"repo_id": "flutter",
"token_count": 508
} | 551 |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder.WatchKit.Storyboard" version="3.0" toolsVersion="11134" targetRuntime="watchKit" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="3mp-fW-waa">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11106"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBWatchKitPlugin" version="11055"/>
</dependencies>
<scenes>
<!--Interface Controller-->
<scene sceneID="aou-V4-d1y">
<objects>
<hostingController id="3mp-fW-waa" customClass="HostingController"
customModuleProvider="target"/>
</objects>
</scene>
</scenes>
</document>
| flutter/dev/integration_tests/ios_app_with_extensions/ios/watch/Base.lproj/Interface.storyboard/0 | {
"file_path": "flutter/dev/integration_tests/ios_app_with_extensions/ios/watch/Base.lproj/Interface.storyboard",
"repo_id": "flutter",
"token_count": 329
} | 552 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/animation.dart';
import 'package:flutter/services.dart';
class _MarqueeText extends AnimatedWidget {
const _MarqueeText({Key? key, required Animation<double> animation})
: super(key: key, listenable: animation);
@override
Widget build(BuildContext context) {
final Animation<double> animation = listenable as Animation<double>;
return Container(
margin: EdgeInsets.only(left: animation.value),
child: const Text(
'This is Marquee',
softWrap: false,
),
);
}
}
class Marquee extends StatefulWidget {
const Marquee({this.color});
final Color? color;
@override
State<StatefulWidget> createState() => MarqueeState();
}
class MarqueeState extends State<Marquee> with SingleTickerProviderStateMixin {
late AnimationController controller;
late Animation<double> animation;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(milliseconds: 2000),
vsync: this,
);
animation = Tween<double>(begin: 0.0, end: 400.0).animate(controller);
controller.repeat();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Material(
color: widget.color,
child: Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
Align(
child: _MarqueeText(animation: animation),
alignment: Alignment.centerLeft,
),
const TextButton(child: Text('POP'), onPressed: SystemNavigator.pop),
],
),
),
);
}
}
| flutter/dev/integration_tests/ios_host_app/flutterapp/lib/marquee/0 | {
"file_path": "flutter/dev/integration_tests/ios_host_app/flutterapp/lib/marquee",
"repo_id": "flutter",
"token_count": 710
} | 553 |
#include "Generated.xcconfig"
| flutter/dev/integration_tests/ios_platform_view_tests/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "flutter/dev/integration_tests/ios_platform_view_tests/ios/Flutter/Debug.xcconfig",
"repo_id": "flutter",
"token_count": 12
} | 554 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math';
import 'package:animations/animations.dart';
import 'package:flutter/material.dart';
import '../../gallery_localizations.dart';
// BEGIN sharedYAxisTransitionDemo
class SharedYAxisTransitionDemo extends StatefulWidget {
const SharedYAxisTransitionDemo({super.key});
@override
State<SharedYAxisTransitionDemo> createState() =>
_SharedYAxisTransitionDemoState();
}
class _SharedYAxisTransitionDemoState extends State<SharedYAxisTransitionDemo>
with SingleTickerProviderStateMixin {
bool _isAlphabetical = false;
late AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 300),
vsync: this,
);
}
final ListView _recentList = ListView(
// Adding [UniqueKey] to make sure the widget rebuilds when transitioning.
key: UniqueKey(),
children: <Widget>[
for (int i = 0; i < 10; i++) _AlbumTile((i + 1).toString()),
],
);
final ListView _alphabeticalList = ListView(
// Adding [UniqueKey] to make sure the widget rebuilds when transitioning.
key: UniqueKey(),
children: <Widget>[
for (final String letter in _alphabet) _AlbumTile(letter),
],
);
static const List<String> _alphabet = <String>[
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
];
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Column(
children: <Widget>[
Text(localizations.demoSharedYAxisTitle),
Text(
'(${localizations.demoSharedYAxisDemoInstructions})',
style: Theme.of(context)
.textTheme
.titleSmall!
.copyWith(color: Colors.white),
),
],
),
),
body: Column(
children: <Widget>[
const SizedBox(height: 5),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 15),
child: Text(localizations.demoSharedYAxisAlbumCount),
),
Padding(
padding: const EdgeInsets.only(right: 7),
child: InkWell(
customBorder: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(4),
),
),
onTap: () {
if (!_isAlphabetical) {
_controller.reset();
_controller.animateTo(0.5);
} else {
_controller.animateTo(1);
}
setState(() {
_isAlphabetical = !_isAlphabetical;
});
},
child: Row(
children: <Widget>[
Text(_isAlphabetical
? localizations.demoSharedYAxisAlphabeticalSortTitle
: localizations.demoSharedYAxisRecentSortTitle),
RotationTransition(
turns: Tween<double>(begin: 0.0, end: 1.0)
.animate(_controller.view),
child: const Icon(Icons.arrow_drop_down),
),
],
),
),
),
],
),
const SizedBox(height: 10),
Expanded(
child: PageTransitionSwitcher(
reverse: _isAlphabetical,
transitionBuilder: (Widget child, Animation<double> animation, Animation<double> secondaryAnimation) {
return SharedAxisTransition(
animation: animation,
secondaryAnimation: secondaryAnimation,
transitionType: SharedAxisTransitionType.vertical,
child: child,
);
},
child: _isAlphabetical ? _alphabeticalList : _recentList,
),
),
],
),
);
}
}
class _AlbumTile extends StatelessWidget {
const _AlbumTile(this._title);
final String _title;
@override
Widget build(BuildContext context) {
final Random randomNumberGenerator = Random();
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
return Column(
children: <Widget>[
ListTile(
leading: Container(
height: 60,
width: 60,
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(4),
),
color: Colors.grey,
),
child: Padding(
padding: const EdgeInsets.all(6),
child: Image.asset(
'placeholders/placeholder_image.png',
package: 'flutter_gallery_assets',
),
),
),
title: Text(
'${localizations.demoSharedYAxisAlbumTileTitle} $_title',
),
subtitle: Text(
localizations.demoSharedYAxisAlbumTileSubtitle,
),
trailing: Text(
'${randomNumberGenerator.nextInt(50) + 10} '
'${localizations.demoSharedYAxisAlbumTileDurationUnit}',
),
),
const Divider(height: 20, thickness: 1),
],
);
}
}
// END sharedYAxisTransitionDemo
| flutter/dev/integration_tests/new_gallery/lib/demos/reference/motion_demo_shared_y_axis_transition.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/reference/motion_demo_shared_y_axis_transition.dart",
"repo_id": "flutter",
"token_count": 3017
} | 555 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import '../../data/gallery_options.dart';
import '../../gallery_localizations.dart';
import 'backdrop.dart';
import 'backlayer.dart';
import 'eat_form.dart';
import 'fly_form.dart';
import 'routes.dart' as routes;
import 'sleep_form.dart';
import 'theme.dart';
class CraneApp extends StatelessWidget {
const CraneApp({super.key});
static const String defaultRoute = routes.defaultRoute;
@override
Widget build(BuildContext context) {
return MaterialApp(
restorationScopeId: 'crane_app',
title: 'Crane',
debugShowCheckedModeBanner: false,
localizationsDelegates: GalleryLocalizations.localizationsDelegates,
supportedLocales: GalleryLocalizations.supportedLocales,
locale: GalleryOptions.of(context).locale,
initialRoute: CraneApp.defaultRoute,
routes: <String, WidgetBuilder>{
CraneApp.defaultRoute: (BuildContext context) => const _Home(),
},
theme: craneTheme.copyWith(
platform: GalleryOptions.of(context).platform,
),
);
}
}
class _Home extends StatelessWidget {
const _Home();
@override
Widget build(BuildContext context) {
return const ApplyTextOptions(
child: Backdrop(
frontLayer: SizedBox(),
backLayerItems: <BackLayerItem>[
FlyForm(),
SleepForm(),
EatForm(),
],
frontTitle: Text('CRANE'),
backTitle: Text('MENU'),
),
);
}
}
| flutter/dev/integration_tests/new_gallery/lib/studies/crane/app.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/crane/app.dart",
"repo_id": "flutter",
"token_count": 603
} | 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:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import '../../../data/gallery_options.dart';
import '../../../gallery_localizations.dart';
import '../../../layout/adaptive.dart';
import '../../../layout/text_scale.dart';
import '../colors.dart';
import '../data.dart';
import '../finance.dart';
import '../formatters.dart';
/// A page that shows a status overview.
class OverviewView extends StatefulWidget {
const OverviewView({super.key});
@override
State<OverviewView> createState() => _OverviewViewState();
}
class _OverviewViewState extends State<OverviewView> {
@override
Widget build(BuildContext context) {
final List<AlertData> alerts = DummyDataService.getAlerts(context);
if (isDisplayDesktop(context)) {
const String sortKeyName = 'Overview';
return SingleChildScrollView(
restorationId: 'overview_scroll_view',
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 24),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Flexible(
flex: 7,
child: Semantics(
sortKey: const OrdinalSortKey(1, name: sortKeyName),
child: const _OverviewGrid(spacing: 24),
),
),
const SizedBox(width: 24),
Flexible(
flex: 3,
child: SizedBox(
width: 400,
child: Semantics(
sortKey: const OrdinalSortKey(2, name: sortKeyName),
child: FocusTraversalGroup(
child: _AlertsView(alerts: alerts),
),
),
),
),
],
),
),
);
} else {
return SingleChildScrollView(
restorationId: 'overview_scroll_view',
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 12),
child: Column(
children: <Widget>[
_AlertsView(alerts: alerts.sublist(0, 1)),
const SizedBox(height: 12),
const _OverviewGrid(spacing: 12),
],
),
),
);
}
}
}
class _OverviewGrid extends StatelessWidget {
const _OverviewGrid({required this.spacing});
final double spacing;
@override
Widget build(BuildContext context) {
final List<AccountData> accountDataList = DummyDataService.getAccountDataList(context);
final List<BillData> billDataList = DummyDataService.getBillDataList(context);
final List<BudgetData> budgetDataList = DummyDataService.getBudgetDataList(context);
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
final double textScaleFactor =
GalleryOptions.of(context).textScaleFactor(context);
// Only display multiple columns when the constraints allow it and we
// have a regular text scale factor.
const int minWidthForTwoColumns = 600;
final bool hasMultipleColumns = isDisplayDesktop(context) &&
constraints.maxWidth > minWidthForTwoColumns &&
textScaleFactor <= 2;
final double boxWidth = hasMultipleColumns
? constraints.maxWidth / 2 - spacing / 2
: double.infinity;
return Wrap(
runSpacing: spacing,
children: <Widget>[
SizedBox(
width: boxWidth,
child: _FinancialView(
title: localizations.rallyAccounts,
total: sumAccountDataPrimaryAmount(accountDataList),
financialItemViews:
buildAccountDataListViews(accountDataList, context),
buttonSemanticsLabel: localizations.rallySeeAllAccounts,
order: 1,
),
),
if (hasMultipleColumns) SizedBox(width: spacing),
SizedBox(
width: boxWidth,
child: _FinancialView(
title: localizations.rallyBills,
total: sumBillDataPrimaryAmount(billDataList),
financialItemViews: buildBillDataListViews(billDataList, context),
buttonSemanticsLabel: localizations.rallySeeAllBills,
order: 2,
),
),
_FinancialView(
title: localizations.rallyBudgets,
total: sumBudgetDataPrimaryAmount(budgetDataList),
financialItemViews:
buildBudgetDataListViews(budgetDataList, context),
buttonSemanticsLabel: localizations.rallySeeAllBudgets,
order: 3,
),
],
);
});
}
}
class _AlertsView extends StatelessWidget {
const _AlertsView({this.alerts});
final List<AlertData>? alerts;
@override
Widget build(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
return Container(
padding: const EdgeInsetsDirectional.only(start: 16, top: 4, bottom: 4),
color: RallyColors.cardBackground,
child: Column(
children: <Widget>[
Container(
width: double.infinity,
padding:
isDesktop ? const EdgeInsets.symmetric(vertical: 16) : null,
child: MergeSemantics(
child: Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
children: <Widget>[
Text(localizations.rallyAlerts),
if (!isDesktop)
TextButton(
style: TextButton.styleFrom(
foregroundColor: Colors.white,
),
onPressed: () {},
child: Text(localizations.rallySeeAll),
),
],
),
),
),
for (final AlertData alert in alerts!) ...<Widget>[
Container(color: RallyColors.primaryBackground, height: 1),
_Alert(alert: alert),
]
],
),
);
}
}
class _Alert extends StatelessWidget {
const _Alert({required this.alert});
final AlertData alert;
@override
Widget build(BuildContext context) {
return MergeSemantics(
child: Container(
padding: isDisplayDesktop(context)
? const EdgeInsets.symmetric(vertical: 8)
: null,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: SelectableText(alert.message!),
),
SizedBox(
width: 100,
child: Align(
alignment: Alignment.topRight,
child: IconButton(
onPressed: () {},
icon: Icon(alert.iconData, color: RallyColors.white60),
),
),
),
],
),
),
);
}
}
class _FinancialView extends StatelessWidget {
const _FinancialView({
this.title,
this.total,
this.financialItemViews,
this.buttonSemanticsLabel,
this.order,
});
final String? title;
final String? buttonSemanticsLabel;
final double? total;
final List<FinancialEntityCategoryView>? financialItemViews;
final double? order;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
return FocusTraversalOrder(
order: NumericFocusOrder(order!),
child: ColoredBox(
color: RallyColors.cardBackground,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
MergeSemantics(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
top: 16,
left: 16,
right: 16,
),
child: SelectableText(title!),
),
Padding(
padding: const EdgeInsets.only(left: 16, right: 16),
child: SelectableText(
usdWithSignFormat(context).format(total),
style: theme.textTheme.bodyLarge!.copyWith(
fontSize: 44 / reducedTextScale(context),
fontWeight: FontWeight.w600,
),
),
),
],
),
),
...financialItemViews!
.sublist(0, math.min(financialItemViews!.length, 3)),
TextButton(
style: TextButton.styleFrom(foregroundColor: Colors.white),
onPressed: () {},
child: Text(
GalleryLocalizations.of(context)!.rallySeeAll,
semanticsLabel: buttonSemanticsLabel,
),
),
],
),
),
);
}
}
| flutter/dev/integration_tests/new_gallery/lib/studies/rally/tabs/overview.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/rally/tabs/overview.dart",
"repo_id": "flutter",
"token_count": 4547
} | 557 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/material.dart';
/// A rectangle with a smooth circular notch.
///
/// See also:
///
/// * [CircleBorder], a [ShapeBorder] that describes a circle.
class WaterfallNotchedRectangle extends NotchedShape {
/// Creates a [WaterfallNotchedRectangle].
///
/// The same object can be used to create multiple shapes.
const WaterfallNotchedRectangle();
/// Creates a [Path] that describes a rectangle with a smooth circular notch.
///
/// `host` is the bounding box for the returned shape. Conceptually this is
/// the rectangle to which the notch will be applied.
///
/// `guest` is the bounding box of a circle that the notch accommodates. All
/// points in the circle bounded by `guest` will be outside of the returned
/// path.
///
/// The notch is curve that smoothly connects the host's top edge and
/// the guest circle.
@override
Path getOuterPath(Rect host, Rect? guest) {
if (guest == null || !host.overlaps(guest)) {
return Path()..addRect(host);
}
// The guest's shape is a circle bounded by the guest rectangle.
// So the guest's radius is half the guest width.
final double notchRadius = guest.width / 2.0;
// We build a path for the notch from 3 segments:
// Segment A - a Bezier curve from the host's top edge to segment B.
// Segment B - an arc with radius notchRadius.
// Segment C - a Bezier curve from segment B back to the host's top edge.
//
// A detailed explanation and the derivation of the formulas below is
// available at: https://goo.gl/Ufzrqn
// s1, s2 are the two knobs controlling the behavior of the bezzier curve.
const double s1 = 21.0;
const double s2 = 6.0;
final double r = notchRadius;
final double a = -1.0 * r - s2;
final double b = host.top - guest.center.dy;
final double n2 = math.sqrt(b * b * r * r * (a * a + b * b - r * r));
final double p2xA = ((a * r * r) - n2) / (a * a + b * b);
final double p2xB = ((a * r * r) + n2) / (a * a + b * b);
final double p2yA = math.sqrt(r * r - p2xA * p2xA);
final double p2yB = math.sqrt(r * r - p2xB * p2xB);
final List<Offset?> p = List<Offset?>.filled(6, null);
// p0, p1, and p2 are the control points for segment A.
p[0] = Offset(a - s1, b);
p[1] = Offset(a, b);
final double cmp = b < 0 ? -1.0 : 1.0;
p[2] = cmp * p2yA > cmp * p2yB ? Offset(p2xA, p2yA) : Offset(p2xB, p2yB);
// p3, p4, and p5 are the control points for segment B, which is a mirror
// of segment A around the y axis.
p[3] = Offset(-1.0 * p[2]!.dx, p[2]!.dy);
p[4] = Offset(-1.0 * p[1]!.dx, p[1]!.dy);
p[5] = Offset(-1.0 * p[0]!.dx, p[0]!.dy);
// translate all points back to the absolute coordinate system.
for (int i = 0; i < p.length; i += 1) {
p[i] = p[i]! + guest.center;
}
return Path()
..moveTo(host.left, host.top)
..lineTo(p[0]!.dx, p[0]!.dy)
..quadraticBezierTo(p[1]!.dx, p[1]!.dy, p[2]!.dx, p[2]!.dy)
..arcToPoint(
p[3]!,
radius: Radius.circular(notchRadius),
clockwise: false,
)
..quadraticBezierTo(p[4]!.dx, p[4]!.dy, p[5]!.dx, p[5]!.dy)
..lineTo(host.right, host.top)
..lineTo(host.right, host.bottom)
..lineTo(host.left, host.bottom)
..close();
}
}
| flutter/dev/integration_tests/new_gallery/lib/studies/reply/waterfall_notched_rectangle.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/reply/waterfall_notched_rectangle.dart",
"repo_id": "flutter",
"token_count": 1400
} | 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 'package:flutter/material.dart';
import '../model/product.dart';
import 'desktop_product_columns.dart';
import 'layout_cache.dart';
/// A placeholder id for an empty element. See [_iterateUntilBalanced]
/// for more information.
const int _emptyElement = -1;
/// To avoid infinite loops, improvements to the layout are only performed
/// when a column's height changes by more than
/// [_deviationImprovementThreshold] pixels.
const int _deviationImprovementThreshold = 10;
/// Height of a product image, paired with the product's id.
class _TaggedHeightData {
const _TaggedHeightData({
required this.index,
required this.height,
});
/// The id of the corresponding product.
final int index;
/// The height of the product image.
final double height;
}
/// Converts a set of [_TaggedHeightData] elements to a list,
/// and add an empty element.
/// Used for iteration.
List<_TaggedHeightData> _toListAndAddEmpty(Set<_TaggedHeightData> set) {
final List<_TaggedHeightData> result = List<_TaggedHeightData>.from(set);
result.add(const _TaggedHeightData(index: _emptyElement, height: 0));
return result;
}
/// Encode parameters for caching.
String _encodeParameters({
required int columnCount,
required List<Product> products,
required double largeImageWidth,
required double smallImageWidth,
}) {
final String productString =
<String>[for (final Product product in products) product.id.toString()].join(',');
return '$columnCount;$productString,$largeImageWidth,$smallImageWidth';
}
/// Given a layout, replace integers by their corresponding products.
List<List<Product>> _generateLayout({
required List<Product> products,
required List<List<int>> layout,
}) {
return <List<Product>>[
for (final List<int> column in layout)
<Product>[
for (final int index in column) products[index],
]
];
}
/// Given [columnObjects], list of the set of objects in each column,
/// and [columnHeights], list of heights of each column,
/// [_iterateUntilBalanced] moves and swaps objects between columns
/// until their heights are sufficiently close to each other.
/// This prevents the layout having significant, avoidable gaps at the bottom.
void _iterateUntilBalanced(
List<Set<_TaggedHeightData>> columnObjects,
List<double> columnHeights,
) {
int failedMoves = 0;
final int columnCount = columnObjects.length;
// No need to rearrange a 1-column layout.
if (columnCount == 1) {
return;
}
while (true) {
// Loop through all possible 2-combinations of columns.
for (int source = 0; source < columnCount; ++source) {
for (int target = source + 1; target < columnCount; ++target) {
// Tries to find an object A from source column
// and an object B from target column, such that switching them
// causes the height of the two columns to be closer.
// A or B can be empty; in this case, moving an object from one
// column to the other is the best choice.
bool success = false;
final double bestHeight = (columnHeights[source] + columnHeights[target]) / 2;
final double scoreLimit = (columnHeights[source] - bestHeight).abs();
final List<_TaggedHeightData> sourceObjects = _toListAndAddEmpty(columnObjects[source]);
final List<_TaggedHeightData> targetObjects = _toListAndAddEmpty(columnObjects[target]);
_TaggedHeightData? bestA, bestB;
double? bestScore;
for (final _TaggedHeightData a in sourceObjects) {
for (final _TaggedHeightData b in targetObjects) {
if (a.index == _emptyElement && b.index == _emptyElement) {
continue;
} else {
final double score =
(columnHeights[source] - a.height + b.height - bestHeight)
.abs();
if (score < scoreLimit - _deviationImprovementThreshold) {
success = true;
if (bestScore == null || score < bestScore) {
bestScore = score;
bestA = a;
bestB = b;
}
}
}
}
}
if (!success) {
++failedMoves;
} else {
failedMoves = 0;
// Switch A and B.
if (bestA != null && bestA.index != _emptyElement) {
columnObjects[source].remove(bestA);
columnObjects[target].add(bestA);
}
if (bestB != null && bestB.index != _emptyElement) {
columnObjects[target].remove(bestB);
columnObjects[source].add(bestB);
}
columnHeights[source] += bestB!.height - bestA!.height;
columnHeights[target] += bestA.height - bestB.height;
}
// If no two columns' heights can be made closer by switching
// elements, the layout is sufficiently balanced.
if (failedMoves >= columnCount * (columnCount - 1) ~/ 2) {
return;
}
}
}
}
}
/// Given a list of numbers [data], representing the heights of each image,
/// and a list of numbers [biases], representing the heights of the space
/// above each column, [_balancedDistribution] returns a layout of [data]
/// so that the height of each column is sufficiently close to each other,
/// represented as a list of lists of integers, each integer being an ID
/// for a product.
List<List<int>> _balancedDistribution({
required int columnCount,
required List<double> data,
required List<double> biases,
}) {
assert(biases.length == columnCount);
final List<Set<_TaggedHeightData>> columnObjects = List<Set<_TaggedHeightData>>.generate(
columnCount, (int column) => <_TaggedHeightData>{});
final List<double> columnHeights = List<double>.from(biases);
for (int i = 0; i < data.length; ++i) {
final int column = i % columnCount;
columnHeights[column] += data[i];
columnObjects[column].add(_TaggedHeightData(index: i, height: data[i]));
}
_iterateUntilBalanced(columnObjects, columnHeights);
return <List<int>>[
for (final Set<_TaggedHeightData> column in columnObjects)
<int>[for (final _TaggedHeightData object in column) object.index]..sort(),
];
}
/// Generates a balanced layout for [columnCount] columns,
/// with products specified by the list [products],
/// where the larger images have width [largeImageWidth]
/// and the smaller images have width [smallImageWidth].
/// The current [context] is also given to allow caching.
List<List<Product>> balancedLayout({
required BuildContext context,
required int columnCount,
required List<Product> products,
required double largeImageWidth,
required double smallImageWidth,
}) {
final String encodedParameters = _encodeParameters(
columnCount: columnCount,
products: products,
largeImageWidth: largeImageWidth,
smallImageWidth: smallImageWidth,
);
// Check if this layout is cached.
if (LayoutCache.of(context).containsKey(encodedParameters)) {
return _generateLayout(
products: products,
layout: LayoutCache.of(context)[encodedParameters]!,
);
}
final List<double> productHeights = <double>[
for (final Product product in products)
1 / product.assetAspectRatio * (largeImageWidth + smallImageWidth) / 2 +
productCardAdditionalHeight,
];
final List<List<int>> layout = _balancedDistribution(
columnCount: columnCount,
data: productHeights,
biases: List<double>.generate(
columnCount,
(int column) => (column.isEven ? 0 : columnTopSpace),
),
);
// Add tailored layout to cache.
LayoutCache.of(context)[encodedParameters] = layout;
final List<List<Product>> result = _generateLayout(
products: products,
layout: layout,
);
return result;
}
| flutter/dev/integration_tests/new_gallery/lib/studies/shrine/supplemental/balanced_layout.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/shrine/supplemental/balanced_layout.dart",
"repo_id": "flutter",
"token_count": 2784
} | 559 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gallery/themes/material_demo_theme_data.dart';
void main() {
test('verify the activeColors of toggleable widget themes are set', () async {
const Color primaryColor = Color(0xFF6200EE);
final ThemeData themeData = MaterialDemoThemeData.themeData;
expect(
themeData.checkboxTheme.fillColor!.resolve(<MaterialState>{MaterialState.selected}),
primaryColor,
);
expect(
themeData.radioTheme.fillColor!.resolve(<MaterialState>{MaterialState.selected}),
primaryColor,
);
expect(
themeData.switchTheme.thumbColor!.resolve(<MaterialState>{MaterialState.selected}),
primaryColor,
);
expect(
themeData.switchTheme.trackColor!.resolve(<MaterialState>{MaterialState.selected}),
primaryColor.withOpacity(0.5),
);
});
}
| flutter/dev/integration_tests/new_gallery/test/theme_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/test/theme_test.dart",
"repo_id": "flutter",
"token_count": 370
} | 560 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
String? unused; // ignore: unreachable_from_main
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const Center(child: Text('hello, world'))
);
}
}
| flutter/dev/integration_tests/non_nullable/lib/main.dart/0 | {
"file_path": "flutter/dev/integration_tests/non_nullable/lib/main.dart",
"repo_id": "flutter",
"token_count": 208
} | 561 |
# release_smoke_test
A simple Flutter project used in CI to test that a release app can build and
run on a physical device.
| flutter/dev/integration_tests/release_smoke_test/README.md/0 | {
"file_path": "flutter/dev/integration_tests/release_smoke_test/README.md",
"repo_id": "flutter",
"token_count": 34
} | 562 |
org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError
android.useAndroidX=true
android.enableJetifier=true
android.useAndroidX=true
android.enableJetifier=true
| flutter/dev/integration_tests/release_smoke_test/android/gradle.properties/0 | {
"file_path": "flutter/dev/integration_tests/release_smoke_test/android/gradle.properties",
"repo_id": "flutter",
"token_count": 70
} | 563 |
package com.example.spell_check
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity()
| flutter/dev/integration_tests/spell_check/android/app/src/main/kotlin/com/example/sc_int_test/MainActivity.kt/0 | {
"file_path": "flutter/dev/integration_tests/spell_check/android/app/src/main/kotlin/com/example/sc_int_test/MainActivity.kt",
"repo_id": "flutter",
"token_count": 35
} | 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/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_driver/driver_extension.dart';
/// This application does nothing but show a screen with the flutter package
/// license in it.
void main() {
enableFlutterDriverExtension();
runApp(const ShowLicenses());
}
class ShowLicenses extends StatelessWidget {
const ShowLicenses({super.key});
Widget _buildTestResultWidget(
BuildContext context,
AsyncSnapshot<List<LicenseEntry>> snapshot,
) {
final List<LicenseEntry> entries = snapshot.data ?? <LicenseEntry>[];
String flutterPackage = '';
final List<String> flutterParagraphs = <String>[];
String enginePackage = '';
final List<String> engineParagraphs = <String>[];
for (final LicenseEntry entry in entries) {
if (entry.packages.contains('flutter')) {
flutterPackage = 'flutter';
flutterParagraphs.addAll(
entry.paragraphs.map<String>((LicenseParagraph para) => para.text),
);
}
if (entry.packages.contains('engine')) {
enginePackage = 'engine';
engineParagraphs.addAll(
entry.paragraphs.map<String>((LicenseParagraph para) => para.text),
);
}
}
final List<Widget> result = <Widget>[];
result.addAll(<Widget>[
const Text('License Check Test', key: ValueKey<String>('Header')),
Text(flutterPackage, key: const ValueKey<String>('FlutterPackage')),
Text(flutterParagraphs.join(' '), key: const ValueKey<String>('FlutterLicense')),
Text('${flutterParagraphs.length}', key: const ValueKey<String>('FlutterCount')),
Text(enginePackage, key: const ValueKey<String>('EnginePackage')),
Text(engineParagraphs.join(' '), key: const ValueKey<String>('EngineLicense')),
Text('${engineParagraphs.length}', key: const ValueKey<String>('EngineCount')),
]);
return ListView(
children: result,
);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: FutureBuilder<List<LicenseEntry>>(
initialData: const <LicenseEntry>[],
builder: _buildTestResultWidget,
future: LicenseRegistry.licenses.toList(),
),
),
);
}
}
| flutter/dev/integration_tests/ui/lib/license_check.dart/0 | {
"file_path": "flutter/dev/integration_tests/ui/lib/license_check.dart",
"repo_id": "flutter",
"token_count": 884
} | 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_driver/flutter_driver.dart';
import 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
bool _isNumeric(String s) {
return double.tryParse(s) != null;
}
// Connect and disconnect from the empty app.
void main() {
group('FrameNumber', () {
late FlutterDriver driver;
setUpAll(() async {
driver = await FlutterDriver.connect();
});
tearDownAll(() async {
await driver.close();
});
test('minFrameNumber is numeric', () async {
final SerializableFinder minFrameNumberFinder =
find.byValueKey('minFrameNumber');
await driver.waitFor(
minFrameNumberFinder,
timeout: const Duration(seconds: 5),
);
final String minFrameNumber = await driver.getText(minFrameNumberFinder);
// TODO(iskakaushik): enable the stronger check of _minFrameNumber == '1',
// once this is fixed. https://github.com/flutter/flutter/issues/86487
expect(_isNumeric(minFrameNumber), true);
}, timeout: Timeout.none);
});
}
| flutter/dev/integration_tests/ui/test_driver/frame_number_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/ui/test_driver/frame_number_test.dart",
"repo_id": "flutter",
"token_count": 419
} | 566 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:html' as html;
import 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';
import 'package:meta/dart2js.dart';
/// Expected sequence of method calls.
const List<String> callChain = <String>['baz', 'bar', 'foo'];
final List<StackFrame> expectedProfileStackFrames = callChain.map<StackFrame>((String method) {
return StackFrame(
number: -1,
packageScheme: '<unknown>',
package: '<unknown>',
packagePath: '<unknown>',
line: -1,
column: -1,
className: 'Object',
method: method,
source: '',
);
}).toList();
// TODO(yjbanov): fix these stack traces when https://github.com/flutter/flutter/issues/50753 is fixed.
const List<StackFrame> expectedDebugStackFrames = <StackFrame>[
StackFrame(
number: -1,
packageScheme: 'package',
package: 'packages',
packagePath: 'web_integration/stack_trace.dart',
line: 119,
column: 3,
className: '<unknown>',
method: 'baz',
source: '',
),
StackFrame(
number: -1,
packageScheme: 'package',
package: 'packages',
packagePath: 'web_integration/stack_trace.dart',
line: 114,
column: 3,
className: '<unknown>',
method: 'bar',
source: '',
),
StackFrame(
number: -1,
packageScheme: 'package',
package: 'packages',
packagePath: 'web_integration/stack_trace.dart',
line: 109,
column: 3,
className: '<unknown>',
method: 'foo',
source: '',
),
];
/// Tests that we do not crash while parsing Web stack traces.
///
/// This test is run in debug, profile, and release modes.
void main() {
final StringBuffer output = StringBuffer();
try {
try {
foo();
} catch (expectedError, expectedStackTrace) {
final List<StackFrame> parsedFrames = StackFrame.fromStackTrace(expectedStackTrace);
if (parsedFrames.isEmpty) {
throw Exception(
'Failed to parse stack trace. Got empty list of stack frames.\n'
'Stack trace:\n$expectedStackTrace'
);
}
// Symbols in release mode are randomly obfuscated, so there's no good way to
// validate the contents. However, profile mode can be checked.
if (kProfileMode) {
_checkStackFrameContents(parsedFrames, expectedProfileStackFrames, expectedStackTrace);
}
if (kDebugMode) {
_checkStackFrameContents(parsedFrames, expectedDebugStackFrames, expectedStackTrace);
}
}
output.writeln('--- TEST SUCCEEDED ---');
} catch (unexpectedError, unexpectedStackTrace) {
output.writeln('--- UNEXPECTED EXCEPTION ---');
output.writeln(unexpectedError);
output.writeln(unexpectedStackTrace);
output.writeln('--- TEST FAILED ---');
}
print(output);
html.HttpRequest.request(
'/test-result',
method: 'POST',
sendData: '$output',
);
}
@noInline
void foo() {
bar();
}
@noInline
void bar() {
baz();
}
@noInline
void baz() {
throw Exception('Test error message');
}
void _checkStackFrameContents(List<StackFrame> parsedFrames, List<StackFrame> expectedFrames, dynamic stackTrace) {
// Filter out stack frames outside this library so this test is less brittle.
final List<StackFrame> actual = parsedFrames
.where((StackFrame frame) => callChain.contains(frame.method))
.toList();
final bool stackFramesAsExpected = ListEquality<StackFrame>(StackFrameEquality()).equals(actual, expectedFrames);
if (!stackFramesAsExpected) {
throw Exception(
'Stack frames parsed incorrectly:\n'
'Expected:\n${expectedFrames.join('\n')}\n'
'Actual:\n${actual.join('\n')}\n'
'Stack trace:\n$stackTrace'
);
}
}
/// Use custom equality to ignore [StackFrame.source], which is not important
/// for the purposes of this test.
class StackFrameEquality implements Equality<StackFrame> {
@override
bool equals(StackFrame e1, StackFrame e2) {
return e1.number == e2.number &&
e1.packageScheme == e2.packageScheme &&
e1.package == e2.package &&
e1.packagePath == e2.packagePath &&
e1.line == e2.line &&
e1.column == e2.column &&
e1.className == e2.className &&
e1.method == e2.method;
}
@override
int hash(StackFrame e) {
return Object.hash(e.number, e.packageScheme, e.package, e.packagePath, e.line, e.column, e.className, e.method);
}
@override
bool isValidKey(Object? o) => o is StackFrame;
}
| flutter/dev/integration_tests/web/lib/stack_trace.dart/0 | {
"file_path": "flutter/dev/integration_tests/web/lib/stack_trace.dart",
"repo_id": "flutter",
"token_count": 1715
} | 567 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
// This class allows loadImage, a protected method, to be called with a custom
// ImageDecoderCallback function.
class LoadTestImageProvider extends ImageProvider<Object> {
LoadTestImageProvider(this.provider);
final ImageProvider provider;
ImageStreamCompleter testLoad(Object key, ImageDecoderCallback decode) {
return provider.loadImage(key, decode);
}
@override
Future<Object> obtainKey(ImageConfiguration configuration) {
throw UnimplementedError();
}
@override
ImageStreamCompleter loadImage(Object key, ImageDecoderCallback decode) {
throw UnimplementedError();
}
}
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('Image.network uses cacheWidth and cacheHeight', (WidgetTester tester) async {
const int expectedCacheHeight = 9;
const int expectedCacheWidth = 11;
await tester.pumpAndSettle();
final Image image = Image.network(
'assets/packages/flutter_gallery_assets/assets/icons/material/material.png',
cacheHeight: 9,
cacheWidth: 11,
);
bool called = false;
Future<ui.Codec> decode(ui.ImmutableBuffer buffer, {ui.TargetImageSizeCallback? getTargetSize}) {
return PaintingBinding.instance.instantiateImageCodecWithSize(buffer, getTargetSize: (int intrinsicWidth, int intrinsicHeight) {
expect(getTargetSize, isNotNull);
final ui.TargetImageSize targetSize = getTargetSize!(intrinsicWidth, intrinsicHeight);
expect(targetSize.width, expectedCacheWidth);
expect(targetSize.height, expectedCacheHeight);
called = true;
return targetSize;
});
}
final ImageProvider resizeImage = image.image;
expect(image.image, isA<ResizeImage>());
final LoadTestImageProvider testProvider = LoadTestImageProvider(image.image);
final ImageStreamCompleter streamCompleter = testProvider.testLoad(await resizeImage.obtainKey(ImageConfiguration.empty), decode);
final Completer<void> completer = Completer<void>();
int? imageInfoCachedWidth;
int? imageInfoCachedHeight;
streamCompleter.addListener(ImageStreamListener((ImageInfo imageInfo, bool syncCall) {
imageInfoCachedWidth = imageInfo.image.width;
imageInfoCachedHeight = imageInfo.image.height;
completer.complete();
}));
await completer.future;
expect(imageInfoCachedHeight, isNotNull);
expect(imageInfoCachedHeight, expectedCacheHeight);
expect(imageInfoCachedWidth, isNotNull);
expect(imageInfoCachedWidth, expectedCacheWidth);
expect(called, true);
});
}
| flutter/dev/integration_tests/web_e2e_tests/test_driver/cache_width_cache_height_integration.dart/0 | {
"file_path": "flutter/dev/integration_tests/web_e2e_tests/test_driver/cache_width_cache_height_integration.dart",
"repo_id": "flutter",
"token_count": 945
} | 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';
import 'package:flutter/services.dart';
void main() {
runApp(MaterialApp(
title: 'Hardware Key Demo',
home: Scaffold(
appBar: AppBar(
title: const Text('Hardware Key Demo'),
),
body: const Center(
child: HardwareKeyboardDemo(),
),
),
));
}
class HardwareKeyboardDemo extends StatefulWidget {
const HardwareKeyboardDemo({super.key});
@override
State<HardwareKeyboardDemo> createState() => _HardwareKeyboardDemoState();
}
class _HardwareKeyboardDemoState extends State<HardwareKeyboardDemo> {
final FocusNode _focusNode = FocusNode();
KeyEvent? _event;
@override
void dispose() {
_focusNode.dispose();
super.dispose();
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
setState(() {
_event = event;
});
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
final TextTheme textTheme = Theme.of(context).textTheme;
return Focus(
focusNode: _focusNode,
onKeyEvent: _handleKeyEvent,
autofocus: true,
child: AnimatedBuilder(
animation: _focusNode,
builder: (BuildContext context, Widget? child) {
if (!_focusNode.hasFocus) {
return GestureDetector(
onTap: () {
_focusNode.requestFocus();
},
child: Text('Tap to focus', style: textTheme.headlineMedium),
);
}
if (_event == null) {
return Text('Press a key', style: textTheme.headlineMedium);
}
final List<Widget> dataText = <Widget>[
Text('${_event.runtimeType}'),
if (_event?.character?.isNotEmpty ?? false) Text('character produced: "${_event?.character}"'),
];
dataText.add(Text('logical: ${_event?.logicalKey}'));
dataText.add(Text('physical: ${_event?.physicalKey}'));
if (_event?.character != null) {
dataText.add(Text('character: ${_event?.character}'));
}
final List<String> pressed = <String>['Pressed:'];
for (final LogicalKeyboardKey key in HardwareKeyboard.instance.logicalKeysPressed) {
pressed.add(key.debugName!);
}
dataText.add(Text(pressed.join(' ')));
return DefaultTextStyle(
style: textTheme.titleMedium!,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: dataText,
),
);
},
),
);
}
}
| flutter/dev/manual_tests/lib/hardware_keyboard.dart/0 | {
"file_path": "flutter/dev/manual_tests/lib/hardware_keyboard.dart",
"repo_id": "flutter",
"token_count": 1184
} | 569 |
#include "ephemeral/Flutter-Generated.xcconfig"
| flutter/dev/manual_tests/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "flutter/dev/manual_tests/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "flutter",
"token_count": 19
} | 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.
// This script generates `android/build.gradle` for each directory specify in the stdin.
// Then it generate the lockfiles for each Gradle project.
// To regenerate these files, run `find . -type d -name 'android' | dart dev/tools/bin/generate_gradle_lockfiles.dart`
import 'dart:io';
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:path/path.dart' as path;
void main(List<String> arguments) {
print(
"Usage: find . -type d -name 'android' | dart dev/tools/bin/generate_gradle_lockfiles.dart\n"
'If you would rather enter the files manually, just run `dart dev/tools/bin/generate_gradle_lockfiles.dart`,\n'
"enter the absolute paths to the app's android directory, then press CTRL-D.\n"
);
const FileSystem fileSystem = LocalFileSystem();
final List<String> androidDirectories = getFilesFromStdin();
for (final String androidDirectoryPath in androidDirectories) {
final Directory androidDirectory = fileSystem.directory(path.normalize(androidDirectoryPath));
if (!androidDirectory.existsSync()) {
throw '$androidDirectory does not exist';
}
final File rootBuildGradle = androidDirectory.childFile('build.gradle');
if (!rootBuildGradle.existsSync()) {
print('${rootBuildGradle.path} does not exist - skipping');
continue;
}
final File settingsGradle = androidDirectory.childFile('settings.gradle');
if (!settingsGradle.existsSync()) {
print('${settingsGradle.path} does not exist - skipping');
continue;
}
final File wrapperGradle = androidDirectory
.childDirectory('gradle')
.childDirectory('wrapper')
.childFile('gradle-wrapper.properties');
if (!wrapperGradle.existsSync()) {
print('${wrapperGradle.path} does not exist - skipping');
continue;
}
if (settingsGradle.readAsStringSync().contains('include_flutter.groovy')) {
print('${settingsGradle.path} add to app - skipping');
continue;
}
if (!androidDirectory.childDirectory('app').existsSync()) {
print('${rootBuildGradle.path} is not an app - skipping');
continue;
}
if (!androidDirectory.parent.childFile('pubspec.yaml').existsSync()) {
print('${rootBuildGradle.path} no pubspec.yaml in parent directory - skipping');
continue;
}
if (androidDirectory.parent.childFile('pubspec.yaml').readAsStringSync().contains('deferred-components')) {
print('${rootBuildGradle.path} uses deferred components - skipping');
continue;
}
if (!androidDirectory.parent
.childDirectory('lib')
.childFile('main.dart')
.existsSync()) {
print('${rootBuildGradle.path} no main.dart under lib - skipping');
continue;
}
print('Processing ${androidDirectory.path}');
try {
androidDirectory.childFile('buildscript-gradle.lockfile').deleteSync();
} on FileSystemException {
// noop
}
rootBuildGradle.writeAsStringSync(rootGradleFileContent);
settingsGradle.writeAsStringSync(settingGradleFile);
wrapperGradle.writeAsStringSync(wrapperGradleFileContent);
final String appDirectory = androidDirectory.parent.absolute.path;
// Fetch pub dependencies.
exec('flutter', <String>['pub', 'get'], workingDirectory: appDirectory);
// Verify that the Gradlew wrapper exists.
final File gradleWrapper = androidDirectory.childFile('gradlew');
// Generate Gradle wrapper if it doesn't exist.
if (!gradleWrapper.existsSync()) {
Process.runSync(
'flutter',
<String>['build', 'apk', '--config-only'],
workingDirectory: appDirectory,
);
}
// Generate lock files.
exec(
gradleWrapper.absolute.path,
<String>[':generateLockfiles'],
workingDirectory: androidDirectory.absolute.path,
);
print('Processed');
}
}
List<String> getFilesFromStdin() {
final List<String> files = <String>[];
while (true) {
final String? file = stdin.readLineSync();
if (file == null) {
break;
}
files.add(file);
}
return files;
}
void exec(
String cmd,
List<String> args, {
String? workingDirectory,
}) {
final ProcessResult result = Process.runSync(cmd, args, workingDirectory: workingDirectory);
if (result.exitCode != 0) {
throw ProcessException(
cmd, args, '${result.stdout}${result.stderr}', result.exitCode);
}
}
const String rootGradleFileContent = r'''
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is auto generated.
// To update all the build.gradle files in the Flutter repo,
// See dev/tools/bin/generate_gradle_lockfiles.dart.
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
dependencyLocking {
ignoredDependencies.add('io.flutter:*')
lockFile = file("${rootProject.projectDir}/project-${project.name}.lockfile")
if (!project.hasProperty('local-engine-repo')) {
lockAllConfigurations()
}
}
}
tasks.register("clean", Delete) {
delete rootProject.buildDir
}
''';
const String settingGradleFile = r'''
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is auto generated.
// To update all the settings.gradle files in the Flutter repo,
// See dev/tools/bin/generate_gradle_lockfiles.dart.
pluginManagement {
def flutterSdkPath = {
def properties = new Properties()
file("local.properties").withInputStream { properties.load(it) }
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
return flutterSdkPath
}
settings.ext.flutterSdkPath = flutterSdkPath()
includeBuild("${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle")
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
buildscript {
dependencyLocking {
lockFile = file("${rootProject.projectDir}/buildscript-gradle.lockfile")
lockAllConfigurations()
}
}
plugins {
id "dev.flutter.flutter-plugin-loader" version "1.0.0"
id "com.android.application" version "7.3.0" apply false
id "org.jetbrains.kotlin.android" version "1.7.10" apply false
}
include ":app"
''';
const String wrapperGradleFileContent = r'''
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.3-all.zip
''';
| flutter/dev/tools/bin/generate_gradle_lockfiles.dart/0 | {
"file_path": "flutter/dev/tools/bin/generate_gradle_lockfiles.dart",
"repo_id": "flutter",
"token_count": 2511
} | 571 |
{
"version": "v0_206",
"md.comp.elevated-card.container.color": "surfaceContainerLow",
"md.comp.elevated-card.container.elevation": "md.sys.elevation.level1",
"md.comp.elevated-card.container.shadow-color": "shadow",
"md.comp.elevated-card.container.shape": "md.sys.shape.corner.medium",
"md.comp.elevated-card.disabled.container.color": "surface",
"md.comp.elevated-card.disabled.container.elevation": "md.sys.elevation.level1",
"md.comp.elevated-card.disabled.container.opacity": 0.38,
"md.comp.elevated-card.dragged.container.elevation": "md.sys.elevation.level4",
"md.comp.elevated-card.dragged.state-layer.color": "onSurface",
"md.comp.elevated-card.dragged.state-layer.opacity": "md.sys.state.dragged.state-layer-opacity",
"md.comp.elevated-card.focus.container.elevation": "md.sys.elevation.level1",
"md.comp.elevated-card.focus.indicator.color": "secondary",
"md.comp.elevated-card.focus.indicator.outline.offset": "md.sys.state.focus-indicator.outer-offset",
"md.comp.elevated-card.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness",
"md.comp.elevated-card.focus.state-layer.color": "onSurface",
"md.comp.elevated-card.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.elevated-card.hover.container.elevation": "md.sys.elevation.level2",
"md.comp.elevated-card.hover.state-layer.color": "onSurface",
"md.comp.elevated-card.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.elevated-card.icon.color": "primary",
"md.comp.elevated-card.icon.size": 24.0,
"md.comp.elevated-card.pressed.container.elevation": "md.sys.elevation.level1",
"md.comp.elevated-card.pressed.state-layer.color": "onSurface",
"md.comp.elevated-card.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity"
}
| flutter/dev/tools/gen_defaults/data/card_elevated.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/card_elevated.json",
"repo_id": "flutter",
"token_count": 731
} | 572 |
{
"version": "v0_206",
"md.comp.divider.color": "outlineVariant",
"md.comp.divider.thickness": 1.0
}
| flutter/dev/tools/gen_defaults/data/divider.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/divider.json",
"repo_id": "flutter",
"token_count": 50
} | 573 |
{
"version": "v0_206",
"md.comp.primary-navigation-tab.active.focus.state-layer.color": "primary",
"md.comp.primary-navigation-tab.active.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.primary-navigation-tab.active.hover.state-layer.color": "primary",
"md.comp.primary-navigation-tab.active.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.primary-navigation-tab.active-indicator.color": "primary",
"md.comp.primary-navigation-tab.active-indicator.height": 3.0,
"md.comp.primary-navigation-tab.active.pressed.state-layer.color": "primary",
"md.comp.primary-navigation-tab.active.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.primary-navigation-tab.container.color": "surface",
"md.comp.primary-navigation-tab.container.elevation": "md.sys.elevation.level0",
"md.comp.primary-navigation-tab.container.height": 48.0,
"md.comp.primary-navigation-tab.container.shape": "md.sys.shape.corner.none",
"md.comp.primary-navigation-tab.focus.indicator.color": "secondary",
"md.comp.primary-navigation-tab.focus.indicator.outline.offset": "md.sys.state.focus-indicator.inner-offset",
"md.comp.primary-navigation-tab.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness",
"md.comp.primary-navigation-tab.inactive.focus.state-layer.color": "onSurface",
"md.comp.primary-navigation-tab.inactive.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.primary-navigation-tab.inactive.hover.state-layer.color": "onSurface",
"md.comp.primary-navigation-tab.inactive.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.primary-navigation-tab.inactive.pressed.state-layer.color": "primary",
"md.comp.primary-navigation-tab.inactive.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.primary-navigation-tab.with-icon.active.focus.icon.color": "primary",
"md.comp.primary-navigation-tab.with-icon.active.hover.icon.color": "primary",
"md.comp.primary-navigation-tab.with-icon.active.icon.color": "primary",
"md.comp.primary-navigation-tab.with-icon.active.pressed.icon.color": "primary",
"md.comp.primary-navigation-tab.with-icon-and-label-text.container.height": 64.0,
"md.comp.primary-navigation-tab.with-icon.icon.size": 24.0,
"md.comp.primary-navigation-tab.with-icon.inactive.focus.icon.color": "onSurface",
"md.comp.primary-navigation-tab.with-icon.inactive.hover.icon.color": "onSurface",
"md.comp.primary-navigation-tab.with-icon.inactive.icon.color": "onSurfaceVariant",
"md.comp.primary-navigation-tab.with-icon.inactive.pressed.icon.color": "onSurface",
"md.comp.primary-navigation-tab.with-label-text.active.focus.label-text.color": "primary",
"md.comp.primary-navigation-tab.with-label-text.active.hover.label-text.color": "primary",
"md.comp.primary-navigation-tab.with-label-text.active.label-text.color": "primary",
"md.comp.primary-navigation-tab.with-label-text.active.pressed.label-text.color": "primary",
"md.comp.primary-navigation-tab.with-label-text.inactive.focus.label-text.color": "onSurface",
"md.comp.primary-navigation-tab.with-label-text.inactive.hover.label-text.color": "onSurface",
"md.comp.primary-navigation-tab.with-label-text.inactive.label-text.color": "onSurfaceVariant",
"md.comp.primary-navigation-tab.with-label-text.inactive.pressed.label-text.color": "onSurface",
"md.comp.primary-navigation-tab.with-label-text.label-text.text-style": "titleSmall"
}
| flutter/dev/tools/gen_defaults/data/navigation_tab_primary.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/navigation_tab_primary.json",
"repo_id": "flutter",
"token_count": 1296
} | 574 |
{
"version": "v0_206",
"md.comp.outlined-text-field.caret.color": "primary",
"md.comp.outlined-text-field.container.shape": "md.sys.shape.corner.extra-small",
"md.comp.outlined-text-field.disabled.input-text.color": "onSurface",
"md.comp.outlined-text-field.disabled.input-text.opacity": 0.38,
"md.comp.outlined-text-field.disabled.label-text.color": "onSurface",
"md.comp.outlined-text-field.disabled.label-text.opacity": 0.38,
"md.comp.outlined-text-field.disabled.leading-icon.color": "onSurface",
"md.comp.outlined-text-field.disabled.leading-icon.opacity": 0.38,
"md.comp.outlined-text-field.disabled.outline.color": "onSurface",
"md.comp.outlined-text-field.disabled.outline.opacity": 0.12,
"md.comp.outlined-text-field.disabled.outline.width": 1.0,
"md.comp.outlined-text-field.disabled.supporting-text.color": "onSurface",
"md.comp.outlined-text-field.disabled.supporting-text.opacity": 0.38,
"md.comp.outlined-text-field.disabled.trailing-icon.color": "onSurface",
"md.comp.outlined-text-field.disabled.trailing-icon.opacity": 0.38,
"md.comp.outlined-text-field.error.focus.caret.color": "error",
"md.comp.outlined-text-field.error.focus.indicator.outline.color": "error",
"md.comp.outlined-text-field.error.focus.input-text.color": "onSurface",
"md.comp.outlined-text-field.error.focus.label-text.color": "error",
"md.comp.outlined-text-field.error.focus.leading-icon.color": "onSurfaceVariant",
"md.comp.outlined-text-field.error.focus.outline.color": "error",
"md.comp.outlined-text-field.error.focus.supporting-text.color": "error",
"md.comp.outlined-text-field.error.focus.trailing-icon.color": "error",
"md.comp.outlined-text-field.error.hover.input-text.color": "onSurface",
"md.comp.outlined-text-field.error.hover.label-text.color": "onErrorContainer",
"md.comp.outlined-text-field.error.hover.leading-icon.color": "onSurfaceVariant",
"md.comp.outlined-text-field.error.hover.outline.color": "onErrorContainer",
"md.comp.outlined-text-field.error.hover.supporting-text.color": "error",
"md.comp.outlined-text-field.error.hover.trailing-icon.color": "onErrorContainer",
"md.comp.outlined-text-field.error.input-text.color": "onSurface",
"md.comp.outlined-text-field.error.label-text.color": "error",
"md.comp.outlined-text-field.error.leading-icon.color": "onSurfaceVariant",
"md.comp.outlined-text-field.error.outline.color": "error",
"md.comp.outlined-text-field.error.supporting-text.color": "error",
"md.comp.outlined-text-field.error.trailing-icon.color": "error",
"md.comp.outlined-text-field.focus.indicator.outline.color": "secondary",
"md.comp.outlined-text-field.focus.indicator.outline.thickness": "md.sys.state.focus-indicator.thickness",
"md.comp.outlined-text-field.focus.input-text.color": "onSurface",
"md.comp.outlined-text-field.focus.label-text.color": "primary",
"md.comp.outlined-text-field.focus.leading-icon.color": "onSurfaceVariant",
"md.comp.outlined-text-field.focus.outline.color": "primary",
"md.comp.outlined-text-field.focus.outline.width": 2.0,
"md.comp.outlined-text-field.focus.supporting-text.color": "onSurfaceVariant",
"md.comp.outlined-text-field.focus.trailing-icon.color": "onSurfaceVariant",
"md.comp.outlined-text-field.hover.input-text.color": "onSurface",
"md.comp.outlined-text-field.hover.label-text.color": "onSurface",
"md.comp.outlined-text-field.hover.leading-icon.color": "onSurfaceVariant",
"md.comp.outlined-text-field.hover.outline.color": "onSurface",
"md.comp.outlined-text-field.hover.outline.width": 1.0,
"md.comp.outlined-text-field.hover.supporting-text.color": "onSurfaceVariant",
"md.comp.outlined-text-field.hover.trailing-icon.color": "onSurfaceVariant",
"md.comp.outlined-text-field.input-text.color": "onSurface",
"md.comp.outlined-text-field.input-text.text-style": "bodyLarge",
"md.comp.outlined-text-field.input-text.placeholder.color": "onSurfaceVariant",
"md.comp.outlined-text-field.input-text.prefix.color": "onSurfaceVariant",
"md.comp.outlined-text-field.input-text.suffix.color": "onSurfaceVariant",
"md.comp.outlined-text-field.label-text.color": "onSurfaceVariant",
"md.comp.outlined-text-field.label-text.text-style": "bodyLarge",
"md.comp.outlined-text-field.leading-icon.color": "onSurfaceVariant",
"md.comp.outlined-text-field.leading-icon.size": 24.0,
"md.comp.outlined-text-field.outline.color": "outline",
"md.comp.outlined-text-field.outline.width": 1.0,
"md.comp.outlined-text-field.supporting-text.color": "onSurfaceVariant",
"md.comp.outlined-text-field.supporting-text.text-style": "bodySmall",
"md.comp.outlined-text-field.trailing-icon.color": "onSurfaceVariant",
"md.comp.outlined-text-field.trailing-icon.size": 24.0
}
| flutter/dev/tools/gen_defaults/data/text_field_outlined.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/text_field_outlined.json",
"repo_id": "flutter",
"token_count": 1826
} | 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 'template.dart';
class CheckboxTemplate extends TokenTemplate {
const CheckboxTemplate(super.blockName, super.fileName, super.tokens, {
super.colorSchemePrefix = '_colors.',
});
@override
String generate() => '''
class _${blockName}DefaultsM3 extends CheckboxThemeData {
_${blockName}DefaultsM3(BuildContext context)
: _theme = Theme.of(context),
_colors = Theme.of(context).colorScheme;
final ThemeData _theme;
final ColorScheme _colors;
@override
MaterialStateBorderSide? get side {
return MaterialStateBorderSide.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
if (states.contains(MaterialState.selected)) {
return const BorderSide(width: ${getToken('md.comp.checkbox.unselected.disabled.outline.width')}, color: Colors.transparent);
}
return BorderSide(width: ${getToken('md.comp.checkbox.unselected.disabled.outline.width')}, color: ${componentColor('md.comp.checkbox.unselected.disabled.outline')}.withOpacity(${getToken('md.comp.checkbox.unselected.disabled.container.opacity')}));
}
if (states.contains(MaterialState.selected)) {
return const BorderSide(width: ${getToken('md.comp.checkbox.selected.outline.width')}, color: Colors.transparent);
}
if (states.contains(MaterialState.error)) {
return BorderSide(width: ${getToken('md.comp.checkbox.unselected.disabled.outline.width')}, color: ${componentColor('md.comp.checkbox.unselected.error.outline')});
}
if (states.contains(MaterialState.pressed)) {
return BorderSide(width: ${getToken('md.comp.checkbox.unselected.pressed.outline.width')}, color: ${componentColor('md.comp.checkbox.unselected.pressed.outline')});
}
if (states.contains(MaterialState.hovered)) {
return BorderSide(width: ${getToken('md.comp.checkbox.unselected.hover.outline.width')}, color: ${componentColor('md.comp.checkbox.unselected.hover.outline')});
}
if (states.contains(MaterialState.focused)) {
return BorderSide(width: ${getToken('md.comp.checkbox.unselected.focus.outline.width')}, color: ${componentColor('md.comp.checkbox.unselected.focus.outline')});
}
return BorderSide(width: ${getToken('md.comp.checkbox.unselected.outline.width')}, color: ${componentColor('md.comp.checkbox.unselected.outline')});
});
}
@override
MaterialStateProperty<Color> get fillColor {
return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
if (states.contains(MaterialState.selected)) {
return ${componentColor('md.comp.checkbox.selected.disabled.container')};
}
return Colors.transparent;
}
if (states.contains(MaterialState.selected)) {
if (states.contains(MaterialState.error)) {
return ${componentColor('md.comp.checkbox.selected.error.container')};
}
return ${componentColor('md.comp.checkbox.selected.container')};
}
return Colors.transparent;
});
}
@override
MaterialStateProperty<Color> get checkColor {
return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
if (states.contains(MaterialState.selected)) {
return ${componentColor('md.comp.checkbox.selected.disabled.icon')};
}
return Colors.transparent; // No icons available when the checkbox is unselected.
}
if (states.contains(MaterialState.selected)) {
if (states.contains(MaterialState.error)) {
return ${componentColor('md.comp.checkbox.selected.error.icon')};
}
return ${componentColor('md.comp.checkbox.selected.icon')};
}
return Colors.transparent; // No icons available when the checkbox is unselected.
});
}
@override
MaterialStateProperty<Color> get overlayColor {
return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.error)) {
if (states.contains(MaterialState.pressed)) {
return ${componentColor('md.comp.checkbox.error.pressed.state-layer')};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor('md.comp.checkbox.error.hover.state-layer')};
}
if (states.contains(MaterialState.focused)) {
return ${componentColor('md.comp.checkbox.error.focus.state-layer')};
}
}
if (states.contains(MaterialState.selected)) {
if (states.contains(MaterialState.pressed)) {
return ${componentColor('md.comp.checkbox.selected.pressed.state-layer')};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor('md.comp.checkbox.selected.hover.state-layer')};
}
if (states.contains(MaterialState.focused)) {
return ${componentColor('md.comp.checkbox.selected.focus.state-layer')};
}
return Colors.transparent;
}
if (states.contains(MaterialState.pressed)) {
return ${componentColor('md.comp.checkbox.unselected.pressed.state-layer')};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor('md.comp.checkbox.unselected.hover.state-layer')};
}
if (states.contains(MaterialState.focused)) {
return ${componentColor('md.comp.checkbox.unselected.focus.state-layer')};
}
return Colors.transparent;
});
}
@override
double get splashRadius => ${getToken('md.comp.checkbox.state-layer.size')} / 2;
@override
MaterialTapTargetSize get materialTapTargetSize => _theme.materialTapTargetSize;
@override
VisualDensity get visualDensity => _theme.visualDensity;
@override
OutlinedBorder get shape => const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(${getToken('md.comp.checkbox.unselected.outline.width')})),
);
}
''';
}
| flutter/dev/tools/gen_defaults/lib/checkbox_template.dart/0 | {
"file_path": "flutter/dev/tools/gen_defaults/lib/checkbox_template.dart",
"repo_id": "flutter",
"token_count": 2262
} | 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 'template.dart';
class NavigationBarTemplate extends TokenTemplate {
const NavigationBarTemplate(super.blockName, super.fileName, super.tokens, {
super.colorSchemePrefix = '_colors.',
super.textThemePrefix = '_textTheme.',
});
@override
String generate() => '''
class _${blockName}DefaultsM3 extends NavigationBarThemeData {
_${blockName}DefaultsM3(this.context)
: super(
height: ${getToken("md.comp.navigation-bar.container.height")},
elevation: ${elevation("md.comp.navigation-bar.container")},
labelBehavior: NavigationDestinationLabelBehavior.alwaysShow,
);
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-bar.container")};
@override Color? get shadowColor => ${colorOrTransparent("md.comp.navigation-bar.container.shadow-color")};
@override Color? get surfaceTintColor => ${colorOrTransparent("md.comp.navigation-bar.container.surface-tint-layer.color")};
@override MaterialStateProperty<IconThemeData?>? get iconTheme {
return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
return IconThemeData(
size: ${getToken("md.comp.navigation-bar.icon.size")},
color: states.contains(MaterialState.disabled)
? _colors.onSurfaceVariant.withOpacity(0.38)
: states.contains(MaterialState.selected)
? ${componentColor("md.comp.navigation-bar.active.icon")}
: ${componentColor("md.comp.navigation-bar.inactive.icon")},
);
});
}
@override Color? get indicatorColor => ${componentColor("md.comp.navigation-bar.active-indicator")};
@override ShapeBorder? get indicatorShape => ${shape("md.comp.navigation-bar.active-indicator")};
@override MaterialStateProperty<TextStyle?>? get labelTextStyle {
return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
final TextStyle style = ${textStyle("md.comp.navigation-bar.label-text")}!;
return style.apply(
color: states.contains(MaterialState.disabled)
? _colors.onSurfaceVariant.withOpacity(0.38)
: states.contains(MaterialState.selected)
? ${componentColor("md.comp.navigation-bar.active.label-text")}
: ${componentColor("md.comp.navigation-bar.inactive.label-text")}
);
});
}
}
''';
}
| flutter/dev/tools/gen_defaults/lib/navigation_bar_template.dart/0 | {
"file_path": "flutter/dev/tools/gen_defaults/lib/navigation_bar_template.dart",
"repo_id": "flutter",
"token_count": 942
} | 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 'template.dart';
class TimePickerTemplate extends TokenTemplate {
const TimePickerTemplate(super.blockName, super.fileName, super.tokens, {
super.colorSchemePrefix = '_colors.',
super.textThemePrefix = '_textTheme.'
});
static const String tokenGroup = 'md.comp.time-picker';
static const String hourMinuteComponent = '$tokenGroup.time-selector';
static const String dayPeriodComponent = '$tokenGroup.period-selector';
static const String dialComponent = '$tokenGroup.clock-dial';
static const String variant = '';
@override
String generate() => '''
class _${blockName}DefaultsM3 extends _TimePickerDefaults {
_${blockName}DefaultsM3(this.context, { this.entryMode = TimePickerEntryMode.dial });
final BuildContext context;
final TimePickerEntryMode entryMode;
late final ColorScheme _colors = Theme.of(context).colorScheme;
late final TextTheme _textTheme = Theme.of(context).textTheme;
@override
Color get backgroundColor {
return ${componentColor("$tokenGroup.container")};
}
@override
ButtonStyle get cancelButtonStyle {
return TextButton.styleFrom();
}
@override
ButtonStyle get confirmButtonStyle {
return TextButton.styleFrom();
}
@override
BorderSide get dayPeriodBorderSide {
return ${border('$dayPeriodComponent.outline')};
}
@override
Color get dayPeriodColor {
return MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return ${componentColor("$dayPeriodComponent.selected.container")};
}
// The unselected day period should match the overall picker dialog color.
// Making it transparent enables that without being redundant and allows
// the optional elevation overlay for dark mode to be visible.
return Colors.transparent;
});
}
@override
OutlinedBorder get dayPeriodShape {
return ${shape("$dayPeriodComponent.container")}.copyWith(side: dayPeriodBorderSide);
}
@override
Size get dayPeriodPortraitSize {
return ${size('$dayPeriodComponent.vertical.container')};
}
@override
Size get dayPeriodLandscapeSize {
return ${size('$dayPeriodComponent.horizontal.container')};
}
@override
Size get dayPeriodInputSize {
// Input size is eight pixels smaller than the portrait size in the spec,
// but there's not token for it yet.
return Size(dayPeriodPortraitSize.width, dayPeriodPortraitSize.height - 8);
}
@override
Color get dayPeriodTextColor {
return MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
if (states.contains(MaterialState.focused)) {
return ${componentColor("$dayPeriodComponent.selected.focus.label-text")};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor("$dayPeriodComponent.selected.hover.label-text")};
}
if (states.contains(MaterialState.pressed)) {
return ${componentColor("$dayPeriodComponent.selected.pressed.label-text")};
}
return ${componentColor("$dayPeriodComponent.selected.label-text")};
}
if (states.contains(MaterialState.focused)) {
return ${componentColor("$dayPeriodComponent.unselected.focus.label-text")};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor("$dayPeriodComponent.unselected.hover.label-text")};
}
if (states.contains(MaterialState.pressed)) {
return ${componentColor("$dayPeriodComponent.unselected.pressed.label-text")};
}
return ${componentColor("$dayPeriodComponent.unselected.label-text")};
});
}
@override
TextStyle get dayPeriodTextStyle {
return ${textStyle("$dayPeriodComponent.label-text")}!.copyWith(color: dayPeriodTextColor);
}
@override
Color get dialBackgroundColor {
return ${componentColor(dialComponent)};
}
@override
Color get dialHandColor {
return ${componentColor('$dialComponent.selector.handle.container')};
}
@override
Size get dialSize {
return ${size("$dialComponent.container")};
}
@override
double get handWidth {
return ${size("$dialComponent.selector.track.container")}.width;
}
@override
double get dotRadius {
return ${size("$dialComponent.selector.handle.container")}.width / 2;
}
@override
double get centerRadius {
return ${size("$dialComponent.selector.center.container")}.width / 2;
}
@override
Color get dialTextColor {
return MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return ${componentColor('$dialComponent.selected.label-text')};
}
return ${componentColor('$dialComponent.unselected.label-text')};
});
}
@override
TextStyle get dialTextStyle {
return ${textStyle('$dialComponent.label-text')}!;
}
@override
double get elevation {
return ${elevation("$tokenGroup.container")};
}
@override
Color get entryModeIconColor {
return _colors.onSurface;
}
@override
TextStyle get helpTextStyle {
return MaterialStateTextStyle.resolveWith((Set<MaterialState> states) {
final TextStyle textStyle = ${textStyle('$tokenGroup.headline')}!;
return textStyle.copyWith(color: ${componentColor('$tokenGroup.headline')});
});
}
@override
EdgeInsetsGeometry get padding {
return const EdgeInsets.all(24);
}
@override
Color get hourMinuteColor {
return MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
Color overlayColor = ${componentColor('$hourMinuteComponent.selected.container')};
if (states.contains(MaterialState.pressed)) {
overlayColor = ${componentColor('$hourMinuteComponent.selected.pressed.state-layer')};
} else if (states.contains(MaterialState.hovered)) {
const double hoverOpacity = ${opacity('$hourMinuteComponent.hover.state-layer.opacity')};
overlayColor = ${componentColor('$hourMinuteComponent.selected.hover.state-layer')}.withOpacity(hoverOpacity);
} else if (states.contains(MaterialState.focused)) {
const double focusOpacity = ${opacity('$hourMinuteComponent.focus.state-layer.opacity')};
overlayColor = ${componentColor('$hourMinuteComponent.selected.focus.state-layer')}.withOpacity(focusOpacity);
}
return Color.alphaBlend(overlayColor, ${componentColor('$hourMinuteComponent.selected.container')});
} else {
Color overlayColor = ${componentColor('$hourMinuteComponent.unselected.container')};
if (states.contains(MaterialState.pressed)) {
overlayColor = ${componentColor('$hourMinuteComponent.unselected.pressed.state-layer')};
} else if (states.contains(MaterialState.hovered)) {
const double hoverOpacity = ${opacity('$hourMinuteComponent.hover.state-layer.opacity')};
overlayColor = ${componentColor('$hourMinuteComponent.unselected.hover.state-layer')}.withOpacity(hoverOpacity);
} else if (states.contains(MaterialState.focused)) {
const double focusOpacity = ${opacity('$hourMinuteComponent.focus.state-layer.opacity')};
overlayColor = ${componentColor('$hourMinuteComponent.unselected.focus.state-layer')}.withOpacity(focusOpacity);
}
return Color.alphaBlend(overlayColor, ${componentColor('$hourMinuteComponent.unselected.container')});
}
});
}
@override
ShapeBorder get hourMinuteShape {
return ${shape('$hourMinuteComponent.container')};
}
@override
Size get hourMinuteSize {
return ${size('$hourMinuteComponent.container')};
}
@override
Size get hourMinuteSize24Hour {
return Size(${size('$hourMinuteComponent.24h-vertical.container')}.width, hourMinuteSize.height);
}
@override
Size get hourMinuteInputSize {
// Input size is eight pixels smaller than the regular size in the spec, but
// there's not token for it yet.
return Size(hourMinuteSize.width, hourMinuteSize.height - 8);
}
@override
Size get hourMinuteInputSize24Hour {
// Input size is eight pixels smaller than the regular size in the spec, but
// there's not token for it yet.
return Size(hourMinuteSize24Hour.width, hourMinuteSize24Hour.height - 8);
}
@override
Color get hourMinuteTextColor {
return MaterialStateColor.resolveWith((Set<MaterialState> states) {
return _hourMinuteTextColor.resolve(states);
});
}
MaterialStateProperty<Color> get _hourMinuteTextColor {
return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
if (states.contains(MaterialState.pressed)) {
return ${componentColor("$hourMinuteComponent.selected.pressed.label-text")};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor("$hourMinuteComponent.selected.hover.label-text")};
}
if (states.contains(MaterialState.focused)) {
return ${componentColor("$hourMinuteComponent.selected.focus.label-text")};
}
return ${componentColor("$hourMinuteComponent.selected.label-text")};
} else {
// unselected
if (states.contains(MaterialState.pressed)) {
return ${componentColor("$hourMinuteComponent.unselected.pressed.label-text")};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor("$hourMinuteComponent.unselected.hover.label-text")};
}
if (states.contains(MaterialState.focused)) {
return ${componentColor("$hourMinuteComponent.unselected.focus.label-text")};
}
return ${componentColor("$hourMinuteComponent.unselected.label-text")};
}
});
}
@override
TextStyle get hourMinuteTextStyle {
return MaterialStateTextStyle.resolveWith((Set<MaterialState> states) {
// TODO(tahatesser): Update this when https://github.com/flutter/flutter/issues/131247 is fixed.
// This is using the correct text style from Material 3 spec.
// https://m3.material.io/components/time-pickers/specs#fd0b6939-edab-4058-82e1-93d163945215
return switch (entryMode) {
TimePickerEntryMode.dial || TimePickerEntryMode.dialOnly
=> _textTheme.displayLarge!.copyWith(color: _hourMinuteTextColor.resolve(states)),
TimePickerEntryMode.input || TimePickerEntryMode.inputOnly
=> _textTheme.displayMedium!.copyWith(color: _hourMinuteTextColor.resolve(states)),
};
});
}
@override
InputDecorationTheme get inputDecorationTheme {
// This is NOT correct, but there's no token for
// 'time-input.container.shape', so this is using the radius from the shape
// for the hour/minute selector. It's a BorderRadiusGeometry, so we have to
// resolve it before we can use it.
final BorderRadius selectorRadius = ${shape('$hourMinuteComponent.container')}
.borderRadius
.resolve(Directionality.of(context));
return InputDecorationTheme(
contentPadding: EdgeInsets.zero,
filled: true,
// This should be derived from a token, but there isn't one for 'time-input'.
fillColor: hourMinuteColor,
// This should be derived from a token, but there isn't one for 'time-input'.
focusColor: _colors.primaryContainer,
enabledBorder: OutlineInputBorder(
borderRadius: selectorRadius,
borderSide: const BorderSide(color: Colors.transparent),
),
errorBorder: OutlineInputBorder(
borderRadius: selectorRadius,
borderSide: BorderSide(color: _colors.error, width: 2),
),
focusedBorder: OutlineInputBorder(
borderRadius: selectorRadius,
borderSide: BorderSide(color: _colors.primary, width: 2),
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: selectorRadius,
borderSide: BorderSide(color: _colors.error, width: 2),
),
hintStyle: hourMinuteTextStyle.copyWith(color: _colors.onSurface.withOpacity(0.36)),
// Prevent the error text from appearing.
// TODO(rami-a): Remove this workaround once
// https://github.com/flutter/flutter/issues/54104
// is fixed.
errorStyle: const TextStyle(fontSize: 0, height: 0),
);
}
@override
ShapeBorder get shape {
return ${shape("$tokenGroup.container")};
}
@override
MaterialStateProperty<Color?>? get timeSelectorSeparatorColor {
// TODO(tahatesser): Update this when tokens are available.
// This is taken from https://m3.material.io/components/time-pickers/specs.
return MaterialStatePropertyAll<Color>(_colors.onSurface);
}
@override
MaterialStateProperty<TextStyle?>? get timeSelectorSeparatorTextStyle {
// TODO(tahatesser): Update this when tokens are available.
// This is taken from https://m3.material.io/components/time-pickers/specs.
return MaterialStatePropertyAll<TextStyle?>(_textTheme.displayLarge);
}
}
''';
}
| flutter/dev/tools/gen_defaults/lib/time_picker_template.dart/0 | {
"file_path": "flutter/dev/tools/gen_defaults/lib/time_picker_template.dart",
"repo_id": "flutter",
"token_count": 4626
} | 578 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "key_mapping.h"
#include <glib.h>
#include <map>
#include "flutter/shell/platform/linux/fl_key_embedder_responder_private.h"
// DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT
// This file is generated by
// flutter/flutter@dev/tools/gen_keycodes/bin/gen_keycodes.dart and should not
// be edited directly.
//
// Edit the template dev/tools/gen_keycodes/data/gtk_key_mapping_cc.tmpl
// instead. See dev/tools/gen_keycodes/README.md for more information.
std::map<uint64_t, uint64_t> xkb_to_physical_key_map = {
@@@XKB_SCAN_CODE_MAP@@@
};
std::map<uint64_t, uint64_t> gtk_keyval_to_logical_key_map = {
@@@GTK_KEYVAL_CODE_MAP@@@
};
void initialize_modifier_bit_to_checked_keys(GHashTable* table) {
FlKeyEmbedderCheckedKey* data;
@@@GTK_MODIFIER_BIT_MAP@@@
}
void initialize_lock_bit_to_checked_keys(GHashTable* table) {
FlKeyEmbedderCheckedKey* data;
@@@GTK_MODE_BIT_MAP@@@
}
const std::vector<LayoutGoal> layout_goals = {
@@@LAYOUT_GOALS@@@
};
@@@MASK_CONSTANTS@@@
| flutter/dev/tools/gen_keycodes/data/gtk_key_mapping_cc.tmpl/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/data/gtk_key_mapping_cc.tmpl",
"repo_id": "flutter",
"token_count": 444
} | 579 |
{
"Backquote": "`",
"Backslash": "\\",
"BracketLeft": "[",
"BracketRight": "]",
"Comma": ",",
"Digit0": "0",
"Digit1": "1",
"Digit2": "2",
"Digit3": "3",
"Digit4": "4",
"Digit5": "5",
"Digit6": "6",
"Digit7": "7",
"Digit8": "8",
"Digit9": "9",
"Equal": "=",
"KeyA": "a",
"KeyB": "b",
"KeyC": "c",
"KeyD": "d",
"KeyE": "e",
"KeyF": "f",
"KeyG": "g",
"KeyH": "h",
"KeyI": "i",
"KeyJ": "j",
"KeyK": "k",
"KeyL": "l",
"KeyM": "m",
"KeyN": "n",
"KeyO": "o",
"KeyP": "p",
"KeyQ": "q",
"KeyR": "r",
"KeyS": "s",
"KeyT": "t",
"KeyU": "u",
"KeyV": "v",
"KeyW": "w",
"KeyX": "x",
"KeyY": "y",
"KeyZ": "z",
"Minus": "-",
"Numpad0": "0",
"Numpad1": "1",
"Numpad2": "2",
"Numpad3": "3",
"Numpad4": "4",
"Numpad5": "5",
"Numpad6": "6",
"Numpad7": "7",
"Numpad8": "8",
"Numpad9": "9",
"NumpadAdd": "+",
"NumpadComma": ",",
"NumpadDecimal": ".",
"NumpadDivide": "/",
"NumpadEqual": "=",
"NumpadMultiply": "*",
"NumpadParenLeft": "(",
"NumpadParenRight": ")",
"NumpadSubtract": "-",
"Period": ".",
"Quote": "'",
"Semicolon": ";",
"Slash": "/",
"Space": " "
}
| flutter/dev/tools/gen_keycodes/data/printable.json/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/data/printable.json",
"repo_id": "flutter",
"token_count": 657
} | 580 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:path/path.dart' as path;
import 'base_code_gen.dart';
import 'data.dart';
import 'logical_key_data.dart';
import 'physical_key_data.dart';
import 'utils.dart';
bool _isAsciiLetter(String? char) {
if (char == null) {
return false;
}
const int charUpperA = 0x41;
const int charUpperZ = 0x5A;
const int charLowerA = 0x61;
const int charLowerZ = 0x7A;
assert(char.length == 1);
final int charCode = char.codeUnitAt(0);
return (charCode >= charUpperA && charCode <= charUpperZ)
|| (charCode >= charLowerA && charCode <= charLowerZ);
}
bool _isDigit(String? char) {
if (char == null) {
return false;
}
final int charDigit0 = '0'.codeUnitAt(0);
final int charDigit9 = '9'.codeUnitAt(0);
assert(char.length == 1);
final int charCode = char.codeUnitAt(0);
return charCode >= charDigit0 && charCode <= charDigit9;
}
/// Generates the keyboard_maps.g.dart files, based on the information in the key
/// data structure given to it.
class KeyboardMapsCodeGenerator extends BaseCodeGenerator {
KeyboardMapsCodeGenerator(super.keyData, super.logicalData);
List<PhysicalKeyEntry> get _numpadKeyData {
return keyData.entries.where((PhysicalKeyEntry entry) {
return entry.constantName.startsWith('numpad') && LogicalKeyData.printable.containsKey(entry.name);
}).toList();
}
List<PhysicalKeyEntry> get _functionKeyData {
final RegExp functionKeyRe = RegExp(r'^f[0-9]+$');
return keyData.entries.where((PhysicalKeyEntry entry) {
return functionKeyRe.hasMatch(entry.constantName);
}).toList();
}
List<LogicalKeyEntry> get _numpadLogicalKeyData {
return logicalData.entries.where((LogicalKeyEntry entry) {
return entry.constantName.startsWith('numpad') && LogicalKeyData.printable.containsKey(entry.name);
}).toList();
}
/// This generates the map of GLFW number pad key codes to logical keys.
String get _glfwNumpadMap {
final OutputLines<int> lines = OutputLines<int>('GLFW numpad map');
for (final PhysicalKeyEntry entry in _numpadKeyData) {
final LogicalKeyEntry logicalKey = logicalData.entryByName(entry.name);
for (final int code in logicalKey.glfwValues) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of GLFW key codes to logical keys.
String get _glfwKeyCodeMap {
final OutputLines<int> lines = OutputLines<int>('GLFW key code map');
for (final LogicalKeyEntry entry in logicalData.entries) {
for (final int value in entry.glfwValues) {
lines.add(value, ' $value: LogicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of GTK number pad key codes to logical keys.
String get _gtkNumpadMap {
final OutputLines<int> lines = OutputLines<int>('GTK numpad map');
for (final LogicalKeyEntry entry in _numpadLogicalKeyData) {
for (final int code in entry.gtkValues) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of GTK key codes to logical keys.
String get _gtkKeyCodeMap {
final OutputLines<int> lines = OutputLines<int>('GTK key code map');
for (final LogicalKeyEntry entry in logicalData.entries) {
for (final int code in entry.gtkValues) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of XKB USB HID codes to physical keys.
String get _xkbScanCodeMap {
final OutputLines<int> lines = OutputLines<int>('GTK scancode map');
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.xKbScanCode != null) {
lines.add(entry.xKbScanCode!,
' ${toHex(entry.xKbScanCode)}: PhysicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of Android key codes to logical keys.
String get _androidKeyCodeMap {
final OutputLines<int> lines = OutputLines<int>('Android key code map');
for (final LogicalKeyEntry entry in logicalData.entries) {
for (final int code in entry.androidValues) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of Android number pad key codes to logical keys.
String get _androidNumpadMap {
final OutputLines<int> lines = OutputLines<int>('Android numpad map');
for (final LogicalKeyEntry entry in _numpadLogicalKeyData) {
for (final int code in entry.androidValues) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of Android scan codes to physical keys.
String get _androidScanCodeMap {
final OutputLines<int> lines = OutputLines<int>('Android scancode map');
for (final PhysicalKeyEntry entry in keyData.entries) {
for (final int code in entry.androidScanCodes) {
lines.add(code, ' $code: PhysicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of Windows scan codes to physical keys.
String get _windowsScanCodeMap {
final OutputLines<int> lines = OutputLines<int>('Windows scancode map');
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.windowsScanCode != null) {
lines.add(entry.windowsScanCode!, ' ${entry.windowsScanCode}: PhysicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of Windows number pad key codes to logical keys.
String get _windowsNumpadMap {
final OutputLines<int> lines = OutputLines<int>('Windows numpad map');
for (final LogicalKeyEntry entry in _numpadLogicalKeyData) {
for (final int code in entry.windowsValues) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of Windows key codes to logical keys.
String get _windowsKeyCodeMap {
final OutputLines<int> lines = OutputLines<int>('Windows key code map');
for (final LogicalKeyEntry entry in logicalData.entries) {
// Letter keys on Windows are not recorded in logical_key_data.g.json,
// because they are not used by the embedding. Add them manually.
final List<int>? keyCodes = entry.windowsValues.isNotEmpty
? entry.windowsValues
: (_isAsciiLetter(entry.keyLabel) ? <int>[entry.keyLabel!.toUpperCase().codeUnitAt(0)] :
_isDigit(entry.keyLabel) ? <int>[entry.keyLabel!.toUpperCase().codeUnitAt(0)] :
null);
if (keyCodes != null) {
for (final int code in keyCodes) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of macOS key codes to physical keys.
String get _macOSScanCodeMap {
final OutputLines<int> lines = OutputLines<int>('macOS scancode map');
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.macOSScanCode != null) {
lines.add(entry.macOSScanCode!, ' ${toHex(entry.macOSScanCode)}: PhysicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of macOS number pad key codes to logical keys.
String get _macOSNumpadMap {
final OutputLines<int> lines = OutputLines<int>('macOS numpad map');
for (final PhysicalKeyEntry entry in _numpadKeyData) {
if (entry.macOSScanCode != null) {
lines.add(entry.macOSScanCode!, ' ${toHex(entry.macOSScanCode)}: LogicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
String get _macOSFunctionKeyMap {
final OutputLines<int> lines = OutputLines<int>('macOS function key map');
for (final PhysicalKeyEntry entry in _functionKeyData) {
if (entry.macOSScanCode != null) {
lines.add(entry.macOSScanCode!, ' ${toHex(entry.macOSScanCode)}: LogicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of macOS key codes to physical keys.
String get _macOSKeyCodeMap {
final OutputLines<int> lines = OutputLines<int>('MacOS key code map');
for (final LogicalKeyEntry entry in logicalData.entries) {
for (final int code in entry.macOSKeyCodeValues) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of iOS key codes to physical keys.
String get _iOSScanCodeMap {
final OutputLines<int> lines = OutputLines<int>('iOS scancode map');
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.iOSScanCode != null) {
lines.add(entry.iOSScanCode!, ' ${toHex(entry.iOSScanCode)}: PhysicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of iOS key label to logical keys for special keys.
String get _iOSSpecialMap {
final OutputLines<int> lines = OutputLines<int>('iOS special key mapping');
kIosSpecialKeyMapping.forEach((String key, String logicalName) {
final LogicalKeyEntry entry = logicalData.entryByName(logicalName);
lines.add(entry.value, " '$key': LogicalKeyboardKey.${entry.constantName},");
});
return lines.join().trimRight();
}
/// This generates the map of iOS number pad key codes to logical keys.
String get _iOSNumpadMap {
final OutputLines<int> lines = OutputLines<int>('iOS numpad map');
for (final PhysicalKeyEntry entry in _numpadKeyData) {
if (entry.iOSScanCode != null) {
lines.add(entry.iOSScanCode!,' ${toHex(entry.iOSScanCode)}: LogicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of macOS key codes to physical keys.
String get _iOSKeyCodeMap {
final OutputLines<int> lines = OutputLines<int>('iOS key code map');
for (final LogicalKeyEntry entry in logicalData.entries) {
for (final int code in entry.iOSKeyCodeValues) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of Fuchsia key codes to logical keys.
String get _fuchsiaKeyCodeMap {
final OutputLines<int> lines = OutputLines<int>('Fuchsia key code map');
for (final LogicalKeyEntry entry in logicalData.entries) {
for (final int value in entry.fuchsiaValues) {
lines.add(value, ' ${toHex(value)}: LogicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of Fuchsia USB HID codes to physical keys.
String get _fuchsiaHidCodeMap {
final StringBuffer fuchsiaScanCodeMap = StringBuffer();
for (final PhysicalKeyEntry entry in keyData.entries) {
fuchsiaScanCodeMap.writeln(' ${toHex(entry.usbHidCode)}: PhysicalKeyboardKey.${entry.constantName},');
}
return fuchsiaScanCodeMap.toString().trimRight();
}
/// This generates the map of Web KeyboardEvent codes to logical keys.
String get _webLogicalKeyMap {
final OutputLines<String> lines = OutputLines<String>('Web logical key map');
for (final LogicalKeyEntry entry in logicalData.entries) {
for (final String name in entry.webNames) {
lines.add(name, " '$name': LogicalKeyboardKey.${entry.constantName},");
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of Web KeyboardEvent codes to physical keys.
String get _webPhysicalKeyMap {
final OutputLines<String> lines = OutputLines<String>('Web physical key map', behavior: DeduplicateBehavior.kKeep);
for (final PhysicalKeyEntry entry in keyData.entries) {
for (final String webCodes in entry.webCodes()) {
lines.add(entry.name, " '$webCodes': PhysicalKeyboardKey.${entry.constantName},");
}
}
return lines.sortedJoin().trimRight();
}
String get _webNumpadMap {
final OutputLines<String> lines = OutputLines<String>('Web numpad map');
for (final LogicalKeyEntry entry in _numpadLogicalKeyData) {
lines.add(entry.name, " '${entry.name}': LogicalKeyboardKey.${entry.constantName},");
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of Web number pad codes to logical keys.
String get _webLocationMap {
final String jsonRaw = File(path.join(dataRoot, 'web_logical_location_mapping.json')).readAsStringSync();
final Map<String, List<String?>> locationMap = parseMapOfListOfNullableString(jsonRaw);
final OutputLines<String> lines = OutputLines<String>('Web location map');
locationMap.forEach((String key, List<String?> keyNames) {
final String keyStrings = keyNames.map((String? keyName) {
final String? constantName = keyName == null ? null : logicalData.entryByName(keyName).constantName;
return constantName != null ? 'LogicalKeyboardKey.$constantName' : 'null';
}).join(', ');
lines.add(key, " '$key': <LogicalKeyboardKey?>[$keyStrings],");
});
return lines.sortedJoin().trimRight();
}
@override
String get templatePath => path.join(dataRoot, 'keyboard_maps.tmpl');
@override
Map<String, String> mappings() {
return <String, String>{
'ANDROID_SCAN_CODE_MAP': _androidScanCodeMap,
'ANDROID_KEY_CODE_MAP': _androidKeyCodeMap,
'ANDROID_NUMPAD_MAP': _androidNumpadMap,
'FUCHSIA_SCAN_CODE_MAP': _fuchsiaHidCodeMap,
'FUCHSIA_KEY_CODE_MAP': _fuchsiaKeyCodeMap,
'MACOS_SCAN_CODE_MAP': _macOSScanCodeMap,
'MACOS_NUMPAD_MAP': _macOSNumpadMap,
'MACOS_FUNCTION_KEY_MAP': _macOSFunctionKeyMap,
'MACOS_KEY_CODE_MAP': _macOSKeyCodeMap,
'IOS_SCAN_CODE_MAP': _iOSScanCodeMap,
'IOS_SPECIAL_MAP': _iOSSpecialMap,
'IOS_NUMPAD_MAP': _iOSNumpadMap,
'IOS_KEY_CODE_MAP': _iOSKeyCodeMap,
'GLFW_KEY_CODE_MAP': _glfwKeyCodeMap,
'GLFW_NUMPAD_MAP': _glfwNumpadMap,
'GTK_KEY_CODE_MAP': _gtkKeyCodeMap,
'GTK_NUMPAD_MAP': _gtkNumpadMap,
'XKB_SCAN_CODE_MAP': _xkbScanCodeMap,
'WEB_LOGICAL_KEY_MAP': _webLogicalKeyMap,
'WEB_PHYSICAL_KEY_MAP': _webPhysicalKeyMap,
'WEB_NUMPAD_MAP': _webNumpadMap,
'WEB_LOCATION_MAP': _webLocationMap,
'WINDOWS_LOGICAL_KEY_MAP': _windowsKeyCodeMap,
'WINDOWS_PHYSICAL_KEY_MAP': _windowsScanCodeMap,
'WINDOWS_NUMPAD_MAP': _windowsNumpadMap,
};
}
}
| flutter/dev/tools/gen_keycodes/lib/keyboard_maps_code_gen.dart/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/lib/keyboard_maps_code_gen.dart",
"repo_id": "flutter",
"token_count": 5706
} | 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 'localizations_utils.dart';
String generateCupertinoHeader(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/cupertino.dart';
import 'package:intl/intl.dart' as intl;
import '../cupertino_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 [getCupertinoTranslation] method at the
// bottom of this file, and used by the [_GlobalCupertinoLocalizationsDelegate.load]
// method defined in `flutter_localizations/lib/src/cupertino_localizations.dart`.''';
}
/// Returns the source of the constructor for a GlobalCupertinoLocalizations
/// subclass.
String generateCupertinoConstructor(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 [GlobalCupertinoLocalizations].
const CupertinoLocalization${locale.camelCase()}({
super.localeName = '$localeName',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});''';
}
const String cupertinoFactoryName = 'getCupertinoTranslation';
const String cupertinoFactoryDeclaration = '''
GlobalCupertinoLocalizations? getCupertinoTranslation(
Locale locale,
intl.DateFormat fullYearFormat,
intl.DateFormat dayFormat,
intl.DateFormat mediumDateFormat,
intl.DateFormat singleDigitHourFormat,
intl.DateFormat singleDigitMinuteFormat,
intl.DateFormat doubleDigitMinuteFormat,
intl.DateFormat singleDigitSecondFormat,
intl.NumberFormat decimalFormat,
) {''';
const String cupertinoFactoryArguments =
'fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat';
const String cupertinoSupportedLanguagesConstant = 'kCupertinoSupportedLanguages';
const String cupertinoSupportedLanguagesDocMacro = 'flutter.localizations.cupertino.languages';
| flutter/dev/tools/localization/gen_cupertino_localizations.dart/0 | {
"file_path": "flutter/dev/tools/localization/gen_cupertino_localizations.dart",
"repo_id": "flutter",
"token_count": 851
} | 582 |
# Tracing tests
## "Application"
The `lib/test.dart` and `lib/control.dart` files in this directory are
used by `dev/bots/test.dart`'s `runTracingTests` function to check
whether aspects of the tracing logic in the framework get compiled out
in profile and release builds. They're not meant to be run directly.
The strings in these files are used in `dev/bots/test.dart`.
## Tests
The tests in this folder must be run with `flutter test --enable-vmservice`,
since they test that trace data is written to the timeline by connecting to
the observatory.
These tests will fail if run without this flag.
| flutter/dev/tracing_tests/README.md/0 | {
"file_path": "flutter/dev/tracing_tests/README.md",
"repo_id": "flutter",
"token_count": 169
} | 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/material.dart';
/// Flutter code sample for [CupertinoContextMenu].
final DecorationTween _tween = DecorationTween(
begin: BoxDecoration(
color: CupertinoColors.systemYellow,
boxShadow: const <BoxShadow>[],
borderRadius: BorderRadius.circular(20.0),
),
end: BoxDecoration(
color: CupertinoColors.systemYellow,
boxShadow: CupertinoContextMenu.kEndBoxShadow,
borderRadius: BorderRadius.circular(20.0),
),
);
void main() => runApp(const ContextMenuApp());
class ContextMenuApp extends StatelessWidget {
const ContextMenuApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
theme: CupertinoThemeData(brightness: Brightness.light),
home: ContextMenuExample(),
);
}
}
class ContextMenuExample extends StatelessWidget {
const ContextMenuExample({super.key});
// Or just do this inline in the builder below?
static Animation<Decoration> _boxDecorationAnimation(Animation<double> animation) {
return _tween.animate(
CurvedAnimation(
parent: animation,
curve: Interval(
0.0,
CupertinoContextMenu.animationOpensAt,
),
),
);
}
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('CupertinoContextMenu Sample'),
),
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: CupertinoContextMenu.builder(
actions: <Widget>[
CupertinoContextMenuAction(
onPressed: () {
Navigator.pop(context);
},
isDefaultAction: true,
trailingIcon: CupertinoIcons.doc_on_clipboard_fill,
child: const Text('Copy'),
),
CupertinoContextMenuAction(
onPressed: () {
Navigator.pop(context);
},
trailingIcon: CupertinoIcons.share,
child: const Text('Share'),
),
CupertinoContextMenuAction(
onPressed: () {
Navigator.pop(context);
},
trailingIcon: CupertinoIcons.heart,
child: const Text('Favorite'),
),
CupertinoContextMenuAction(
onPressed: () {
Navigator.pop(context);
},
isDestructiveAction: true,
trailingIcon: CupertinoIcons.delete,
child: const Text('Delete'),
),
],
builder: (BuildContext context, Animation<double> animation) {
final Animation<Decoration> boxDecorationAnimation = _boxDecorationAnimation(animation);
return Container(
decoration:
animation.value < CupertinoContextMenu.animationOpensAt ? boxDecorationAnimation.value : null,
child: Container(
decoration: BoxDecoration(
color: CupertinoColors.systemYellow,
borderRadius: BorderRadius.circular(20.0),
),
child: const FlutterLogo(size: 500.0),
),
);
},
),
),
),
);
}
}
| flutter/examples/api/lib/cupertino/context_menu/cupertino_context_menu.1.dart/0 | {
"file_path": "flutter/examples/api/lib/cupertino/context_menu/cupertino_context_menu.1.dart",
"repo_id": "flutter",
"token_count": 1703
} | 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/cupertino.dart';
/// Flutter code sample for [showCupertinoModalPopup].
void main() => runApp(const ModalPopupApp());
class ModalPopupApp extends StatelessWidget {
const ModalPopupApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
theme: CupertinoThemeData(brightness: Brightness.light),
restorationScopeId: 'app',
home: ModalPopupExample(),
);
}
}
class ModalPopupExample extends StatelessWidget {
const ModalPopupExample({super.key});
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('Home'),
),
child: Center(
child: CupertinoButton(
onPressed: () {
Navigator.of(context).restorablePush(_modalBuilder);
},
child: const Text('Open Modal'),
),
),
);
}
@pragma('vm:entry-point')
static Route<void> _modalBuilder(BuildContext context, Object? arguments) {
return CupertinoModalPopupRoute<void>(
builder: (BuildContext context) {
return CupertinoActionSheet(
title: const Text('Title'),
message: const Text('Message'),
actions: <CupertinoActionSheetAction>[
CupertinoActionSheetAction(
child: const Text('Action One'),
onPressed: () {
Navigator.pop(context);
},
),
CupertinoActionSheetAction(
child: const Text('Action Two'),
onPressed: () {
Navigator.pop(context);
},
),
],
);
},
);
}
}
| flutter/examples/api/lib/cupertino/route/show_cupertino_modal_popup.0.dart/0 | {
"file_path": "flutter/examples/api/lib/cupertino/route/show_cupertino_modal_popup.0.dart",
"repo_id": "flutter",
"token_count": 816
} | 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';
/// Flutter code sample for [ActionIconTheme].
void main() {
runApp(const ActionIconThemeExampleApp());
}
class _CustomEndDrawerIcon extends StatelessWidget {
const _CustomEndDrawerIcon();
@override
Widget build(BuildContext context) {
final MaterialLocalizations localization = MaterialLocalizations.of(context);
return Icon(
Icons.more_horiz,
semanticLabel: localization.openAppDrawerTooltip,
);
}
}
class _CustomDrawerIcon extends StatelessWidget {
const _CustomDrawerIcon();
@override
Widget build(BuildContext context) {
final MaterialLocalizations localization = MaterialLocalizations.of(context);
return Icon(
Icons.segment,
semanticLabel: localization.openAppDrawerTooltip,
);
}
}
class ActionIconThemeExampleApp extends StatelessWidget {
const ActionIconThemeExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
useMaterial3: true,
actionIconTheme: ActionIconThemeData(
backButtonIconBuilder: (BuildContext context) {
return const Icon(Icons.arrow_back_ios_new_rounded);
},
drawerButtonIconBuilder: (BuildContext context) {
return const _CustomDrawerIcon();
},
endDrawerButtonIconBuilder: (BuildContext context) {
return const _CustomEndDrawerIcon();
},
),
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
drawer: Drawer(
child: Column(
children: <Widget>[
TextButton(child: const Text('Drawer Item'), onPressed: () {}),
],
),
),
body: const Center(
child: NextPageButton(),
),
);
}
}
class NextPageButton extends StatelessWidget {
const NextPageButton({super.key});
@override
Widget build(BuildContext context) {
return ElevatedButton.icon(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute<MySecondPage>(builder: (BuildContext context) {
return const MySecondPage();
}),
);
},
icon: const Icon(Icons.arrow_forward),
label: const Text('Next page'),
);
}
}
class MySecondPage extends StatelessWidget {
const MySecondPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Second page'),
),
endDrawer: const Drawer(),
);
}
}
| flutter/examples/api/lib/material/action_buttons/action_icon_theme.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/action_buttons/action_icon_theme.0.dart",
"repo_id": "flutter",
"token_count": 1149
} | 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 'dart:async';
import 'package:flutter/material.dart';
/// Flutter code sample for [Autocomplete] that demonstrates fetching the
/// options asynchronously and debouncing the network calls.
const Duration fakeAPIDuration = Duration(seconds: 1);
const Duration debounceDuration = Duration(milliseconds: 500);
void main() => runApp(const AutocompleteExampleApp());
class AutocompleteExampleApp extends StatelessWidget {
const AutocompleteExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Autocomplete - async and debouncing'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Type below to autocomplete the following possible results: ${_FakeAPI._kOptions}.'),
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;
// 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;
// In a real application, there should be some error handling here.
final Iterable<String> options = await _FakeAPI.search(_currentQuery!);
// 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 Autocomplete<String>(
optionsBuilder: (TextEditingValue textEditingValue) async {
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) async {
await Future<void>.delayed(fakeAPIDuration); // Fake 1 second delay.
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();
}
| flutter/examples/api/lib/material/autocomplete/autocomplete.3.dart/0 | {
"file_path": "flutter/examples/api/lib/material/autocomplete/autocomplete.3.dart",
"repo_id": "flutter",
"token_count": 1648
} | 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';
/// Flutter code sample for [Checkbox].
void main() => runApp(const CheckboxExampleApp());
class CheckboxExampleApp extends StatelessWidget {
const CheckboxExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
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 = false;
@override
Widget build(BuildContext context) {
Color getColor(Set<MaterialState> states) {
const Set<MaterialState> interactiveStates = <MaterialState>{
MaterialState.pressed,
MaterialState.hovered,
MaterialState.focused,
};
if (states.any(interactiveStates.contains)) {
return Colors.blue;
}
return Colors.red;
}
return Checkbox(
checkColor: Colors.white,
fillColor: MaterialStateProperty.resolveWith(getColor),
value: isChecked,
onChanged: (bool? value) {
setState(() {
isChecked = value!;
});
},
);
}
}
| flutter/examples/api/lib/material/checkbox/checkbox.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/checkbox/checkbox.0.dart",
"repo_id": "flutter",
"token_count": 572
} | 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.
// This example demonstrates a custom context menu in non-editable text using
// SelectionArea.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const SelectableRegionToolbarBuilderExampleApp());
const String text =
'I am some text inside of SelectionArea. Right click (desktop) or long press (mobile) me to show the customized context menu.';
class SelectableRegionToolbarBuilderExampleApp extends StatefulWidget {
const SelectableRegionToolbarBuilderExampleApp({super.key});
@override
State<SelectableRegionToolbarBuilderExampleApp> createState() => _SelectableRegionToolbarBuilderExampleAppState();
}
class _SelectableRegionToolbarBuilderExampleAppState extends State<SelectableRegionToolbarBuilderExampleApp> {
void _showDialog(BuildContext context) {
Navigator.of(context).push(
DialogRoute<void>(
context: context,
builder: (BuildContext context) => const AlertDialog(title: Text('You clicked print!')),
),
);
}
@override
void initState() {
super.initState();
// On web, disable the browser's context menu since this example uses a custom
// Flutter-rendered context menu.
if (kIsWeb) {
BrowserContextMenu.disableContextMenu();
}
}
@override
void dispose() {
if (kIsWeb) {
BrowserContextMenu.enableContextMenu();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Context menu anywhere'),
),
body: Center(
child: SizedBox(
width: 200.0,
child: SelectionArea(
contextMenuBuilder: (
BuildContext context,
SelectableRegionState selectableRegionState,
) {
return AdaptiveTextSelectionToolbar.buttonItems(
anchors: selectableRegionState.contextMenuAnchors,
buttonItems: <ContextMenuButtonItem>[
...selectableRegionState.contextMenuButtonItems,
ContextMenuButtonItem(
onPressed: () {
ContextMenuController.removeAny();
_showDialog(context);
},
label: 'Print',
),
],
);
},
child: ListView(
children: const <Widget>[
SizedBox(height: 20.0),
Text(text),
],
),
),
),
),
),
);
}
}
| flutter/examples/api/lib/material/context_menu/selectable_region_toolbar_builder.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/context_menu/selectable_region_toolbar_builder.0.dart",
"repo_id": "flutter",
"token_count": 1235
} | 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';
/// Flutter code sample for [FlexibleSpaceBar].
void main() => runApp(const MaterialApp(home: FlexibleSpaceBarExampleApp()));
class FlexibleSpaceBarExampleApp extends StatelessWidget {
const FlexibleSpaceBarExampleApp({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
slivers: <Widget>[
SliverAppBar(
stretch: true,
onStretchTrigger: () {
// Function callback for stretch
return Future<void>.value();
},
expandedHeight: 300.0,
flexibleSpace: FlexibleSpaceBar(
stretchModes: const <StretchMode>[
StretchMode.zoomBackground,
StretchMode.blurBackground,
StretchMode.fadeTitle,
],
centerTitle: true,
title: const Text('Flight Report'),
background: Stack(
fit: StackFit.expand,
children: <Widget>[
Image.network(
'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg',
fit: BoxFit.cover,
),
const DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment(0.0, 0.5),
end: Alignment.center,
colors: <Color>[
Color(0x60000000),
Color(0x00000000),
],
),
),
),
],
),
),
),
SliverList(
delegate: SliverChildListDelegate(
const <Widget>[
ListTile(
leading: Icon(Icons.wb_sunny),
title: Text('Sunday'),
subtitle: Text('sunny, h: 80, l: 65'),
),
ListTile(
leading: Icon(Icons.wb_sunny),
title: Text('Monday'),
subtitle: Text('sunny, h: 80, l: 65'),
),
// ListTiles++
],
),
),
],
),
);
}
}
| flutter/examples/api/lib/material/flexible_space_bar/flexible_space_bar.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/flexible_space_bar/flexible_space_bar.0.dart",
"repo_id": "flutter",
"token_count": 1437
} | 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';
/// 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 StatelessWidget {
const ListTileExample({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('ListTile Sample')),
body: ListView(
children: const <Widget>[
ListTile(
leading: CircleAvatar(child: Text('A')),
title: Text('Headline'),
subtitle: Text('Supporting text'),
trailing: Icon(Icons.favorite_rounded),
),
Divider(height: 0),
ListTile(
leading: CircleAvatar(child: Text('B')),
title: Text('Headline'),
subtitle: Text(
'Longer supporting text to demonstrate how the text wraps and how the leading and trailing widgets are centered vertically with the text.'),
trailing: Icon(Icons.favorite_rounded),
),
Divider(height: 0),
ListTile(
leading: CircleAvatar(child: Text('C')),
title: Text('Headline'),
subtitle: Text(
"Longer supporting text to demonstrate how the text wraps and how setting 'ListTile.isThreeLine = true' aligns leading and trailing widgets to the top vertically with the text."),
trailing: Icon(Icons.favorite_rounded),
isThreeLine: true,
),
Divider(height: 0),
],
),
);
}
}
| flutter/examples/api/lib/material/list_tile/list_tile.2.dart/0 | {
"file_path": "flutter/examples/api/lib/material/list_tile/list_tile.2.dart",
"repo_id": "flutter",
"token_count": 778
} | 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';
/// Flutter code sample for [NavigationBar].
void main() => runApp(const NavigationBarApp());
class NavigationBarApp extends StatelessWidget {
const NavigationBarApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: NavigationExample());
}
}
class NavigationExample extends StatefulWidget {
const NavigationExample({super.key});
@override
State<NavigationExample> createState() => _NavigationExampleState();
}
class _NavigationExampleState extends State<NavigationExample> {
int currentPageIndex = 0;
NavigationDestinationLabelBehavior labelBehavior = NavigationDestinationLabelBehavior.alwaysShow;
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: NavigationBar(
labelBehavior: labelBehavior,
selectedIndex: currentPageIndex,
onDestinationSelected: (int index) {
setState(() {
currentPageIndex = index;
});
},
destinations: const <Widget>[
NavigationDestination(
icon: Icon(Icons.explore),
label: 'Explore',
),
NavigationDestination(
icon: Icon(Icons.commute),
label: 'Commute',
),
NavigationDestination(
selectedIcon: Icon(Icons.bookmark),
icon: Icon(Icons.bookmark_border),
label: 'Saved',
),
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Label behavior: ${labelBehavior.name}'),
const SizedBox(height: 10),
OverflowBar(
spacing: 10.0,
children: <Widget>[
ElevatedButton(
onPressed: () {
setState(() {
labelBehavior = NavigationDestinationLabelBehavior.alwaysShow;
});
},
child: const Text('alwaysShow'),
),
ElevatedButton(
onPressed: () {
setState(() {
labelBehavior = NavigationDestinationLabelBehavior.onlyShowSelected;
});
},
child: const Text('onlyShowSelected'),
),
ElevatedButton(
onPressed: () {
setState(() {
labelBehavior = NavigationDestinationLabelBehavior.alwaysHide;
});
},
child: const Text('alwaysHide'),
),
],
),
],
),
),
);
}
}
| flutter/examples/api/lib/material/navigation_bar/navigation_bar.1.dart/0 | {
"file_path": "flutter/examples/api/lib/material/navigation_bar/navigation_bar.1.dart",
"repo_id": "flutter",
"token_count": 1417
} | 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';
/// Flutter code sample for [ReorderableListView.buildDefaultDragHandles].
void main() => runApp(const ReorderableApp());
class ReorderableApp extends StatelessWidget {
const ReorderableApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('ReorderableListView Sample')),
body: const ReorderableExample(),
),
);
}
}
class ReorderableExample extends StatefulWidget {
const ReorderableExample({super.key});
@override
State<ReorderableExample> createState() => _ReorderableExampleState();
}
class _ReorderableExampleState extends State<ReorderableExample> {
final List<int> _items = List<int>.generate(50, (int index) => index);
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
final Color oddItemColor = colorScheme.primary.withOpacity(0.05);
final Color evenItemColor = colorScheme.primary.withOpacity(0.15);
return ReorderableListView(
buildDefaultDragHandles: false,
children: <Widget>[
for (int index = 0; index < _items.length; index++)
ColoredBox(
key: Key('$index'),
color: _items[index].isOdd ? oddItemColor : evenItemColor,
child: Row(
children: <Widget>[
Container(
width: 64,
height: 64,
padding: const EdgeInsets.all(8),
child: ReorderableDragStartListener(
index: index,
child: Card(
color: colorScheme.primary,
elevation: 2,
),
),
),
Text('Item ${_items[index]}'),
],
),
),
],
onReorder: (int oldIndex, int newIndex) {
setState(() {
if (oldIndex < newIndex) {
newIndex -= 1;
}
final int item = _items.removeAt(oldIndex);
_items.insert(newIndex, item);
});
},
);
}
}
| flutter/examples/api/lib/material/reorderable_list/reorderable_list_view.build_default_drag_handles.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/reorderable_list/reorderable_list_view.build_default_drag_handles.0.dart",
"repo_id": "flutter",
"token_count": 1051
} | 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';
/// Flutter code sample for [ScaffoldState.showBottomSheet].
void main() => runApp(const ShowBottomSheetExampleApp());
class ShowBottomSheetExampleApp extends StatelessWidget {
const ShowBottomSheetExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('ScaffoldState Sample')),
body: const ShowBottomSheetExample(),
),
);
}
}
class ShowBottomSheetExample extends StatelessWidget {
const ShowBottomSheetExample({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(
child: const Text('showBottomSheet'),
onPressed: () {
Scaffold.of(context).showBottomSheet(
(BuildContext context) {
return Container(
height: 200,
color: Colors.amber,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('BottomSheet'),
ElevatedButton(
child: const Text('Close BottomSheet'),
onPressed: () {
Navigator.pop(context);
},
),
],
),
),
);
},
);
},
),
);
}
}
| flutter/examples/api/lib/material/scaffold/scaffold_state.show_bottom_sheet.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/scaffold/scaffold_state.show_bottom_sheet.0.dart",
"repo_id": "flutter",
"token_count": 863
} | 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';
/// Flutter code sample for [SwitchListTile].
void main() => runApp(const SwitchListTileApp());
class SwitchListTileApp extends StatelessWidget {
const SwitchListTileApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(appBar: AppBar(title: const Text('SwitchListTile Sample')), body: const SwitchListTileExample()),
);
}
}
class SwitchListTileExample extends StatefulWidget {
const SwitchListTileExample({super.key});
@override
State<SwitchListTileExample> createState() => _SwitchListTileExampleState();
}
class _SwitchListTileExampleState extends State<SwitchListTileExample> {
bool switchValue1 = true;
bool switchValue2 = true;
bool switchValue3 = true;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
SwitchListTile(
value: switchValue1,
onChanged: (bool? value) {
setState(() {
switchValue1 = value!;
});
},
title: const Text('Headline'),
subtitle: const Text('Supporting text'),
),
const Divider(height: 0),
SwitchListTile(
value: switchValue2,
onChanged: (bool? value) {
setState(() {
switchValue2 = value!;
});
},
title: const Text('Headline'),
subtitle: const Text(
'Longer supporting text to demonstrate how the text wraps and the switch is centered vertically with the text.'),
),
const Divider(height: 0),
SwitchListTile(
value: switchValue3,
onChanged: (bool? value) {
setState(() {
switchValue3 = value!;
});
},
title: const Text('Headline'),
subtitle: const Text(
"Longer supporting text to demonstrate how the text wraps and how setting 'SwitchListTile.isThreeLine = true' aligns the switch to the top vertically with the text."),
isThreeLine: true,
),
const Divider(height: 0),
],
),
);
}
}
| flutter/examples/api/lib/material/switch_list_tile/switch_list_tile.1.dart/0 | {
"file_path": "flutter/examples/api/lib/material/switch_list_tile/switch_list_tile.1.dart",
"repo_id": "flutter",
"token_count": 1047
} | 595 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// 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 const Tooltip(
message: 'I am a Tooltip',
child: Text('Hover over the text to show a tooltip.'),
);
}
}
| flutter/examples/api/lib/material/tooltip/tooltip.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/tooltip/tooltip.0.dart",
"repo_id": "flutter",
"token_count": 341
} | 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/material.dart';
/// Flutter code sample for [FutureBuilder].
void main() => runApp(const FutureBuilderExampleApp());
class FutureBuilderExampleApp extends StatelessWidget {
const FutureBuilderExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: FutureBuilderExample(),
);
}
}
class FutureBuilderExample extends StatefulWidget {
const FutureBuilderExample({super.key});
@override
State<FutureBuilderExample> createState() => _FutureBuilderExampleState();
}
class _FutureBuilderExampleState extends State<FutureBuilderExample> {
final Future<String> _calculation = Future<String>.delayed(
const Duration(seconds: 2),
() => 'Data Loaded',
);
@override
Widget build(BuildContext context) {
return DefaultTextStyle(
style: Theme.of(context).textTheme.displayMedium!,
textAlign: TextAlign.center,
child: FutureBuilder<String>(
future: _calculation, // a previously-obtained Future<String> or null
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
List<Widget> children;
if (snapshot.hasData) {
children = <Widget>[
const Icon(
Icons.check_circle_outline,
color: Colors.green,
size: 60,
),
Padding(
padding: const EdgeInsets.only(top: 16),
child: Text('Result: ${snapshot.data}'),
),
];
} else 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}'),
),
];
} else {
children = const <Widget>[
SizedBox(
width: 60,
height: 60,
child: CircularProgressIndicator(),
),
Padding(
padding: EdgeInsets.only(top: 16),
child: Text('Awaiting result...'),
),
];
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: children,
),
);
},
),
);
}
}
| flutter/examples/api/lib/widgets/async/future_builder.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/async/future_builder.0.dart",
"repo_id": "flutter",
"token_count": 1240
} | 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';
/// Flutter code sample for [FittedBox].
void main() => runApp(const FittedBoxApp());
class FittedBoxApp extends StatelessWidget {
const FittedBoxApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('FittedBox Sample')),
body: const Center(
child: FittedBoxExample(),
),
),
);
}
}
class FittedBoxExample extends StatelessWidget {
const FittedBoxExample({super.key});
@override
Widget build(BuildContext context) {
return Container(
height: 400,
width: 300,
color: Colors.blue,
child: const FittedBox(
// TRY THIS: Try changing the fit types to see how they change the way
// the placeholder fits into the container.
fit: BoxFit.fill,
child: Placeholder(),
),
);
}
}
| flutter/examples/api/lib/widgets/basic/fitted_box.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/basic/fitted_box.0.dart",
"repo_id": "flutter",
"token_count": 402
} | 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/foundation.dart';
import 'package:flutter/material.dart';
/// Flutter code sample for [DraggableScrollableSheet].
void main() => runApp(const DraggableScrollableSheetExampleApp());
class DraggableScrollableSheetExampleApp extends StatelessWidget {
const DraggableScrollableSheetExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue.shade100),
),
home: Scaffold(
appBar: AppBar(
title: const Text('DraggableScrollableSheet Sample'),
),
body: const DraggableScrollableSheetExample(),
),
);
}
}
class DraggableScrollableSheetExample extends StatefulWidget {
const DraggableScrollableSheetExample({super.key});
@override
State<DraggableScrollableSheetExample> createState() => _DraggableScrollableSheetExampleState();
}
class _DraggableScrollableSheetExampleState extends State<DraggableScrollableSheetExample> {
double _sheetPosition = 0.5;
final double _dragSensitivity = 600;
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
return DraggableScrollableSheet(
initialChildSize: _sheetPosition,
builder: (BuildContext context, ScrollController scrollController) {
return ColoredBox(
color: colorScheme.primary,
child: Column(
children: <Widget>[
Grabber(
onVerticalDragUpdate: (DragUpdateDetails details) {
setState(() {
_sheetPosition -= details.delta.dy / _dragSensitivity;
if (_sheetPosition < 0.25) {
_sheetPosition = 0.25;
}
if (_sheetPosition > 1.0) {
_sheetPosition = 1.0;
}
});
},
isOnDesktopAndWeb: _isOnDesktopAndWeb,
),
Flexible(
child: ListView.builder(
controller: _isOnDesktopAndWeb ? null : scrollController,
itemCount: 25,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(
'Item $index',
style: TextStyle(color: colorScheme.surface),
),
);
},
),
),
],
),
);
},
);
}
bool get _isOnDesktopAndWeb {
if (kIsWeb) {
return true;
}
switch (defaultTargetPlatform) {
case TargetPlatform.macOS:
case TargetPlatform.linux:
case TargetPlatform.windows:
return true;
case TargetPlatform.android:
case TargetPlatform.iOS:
case TargetPlatform.fuchsia:
return false;
}
}
}
/// A draggable widget that accepts vertical drag gestures
/// and this is only visible on desktop and web platforms.
class Grabber extends StatelessWidget {
const Grabber({
super.key,
required this.onVerticalDragUpdate,
required this.isOnDesktopAndWeb,
});
final ValueChanged<DragUpdateDetails> onVerticalDragUpdate;
final bool isOnDesktopAndWeb;
@override
Widget build(BuildContext context) {
if (!isOnDesktopAndWeb) {
return const SizedBox.shrink();
}
final ColorScheme colorScheme = Theme.of(context).colorScheme;
return GestureDetector(
onVerticalDragUpdate: onVerticalDragUpdate,
child: Container(
width: double.infinity,
color: colorScheme.onSurface,
child: Align(
alignment: Alignment.topCenter,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 8.0),
width: 32.0,
height: 4.0,
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8.0),
),
),
),
),
);
}
}
| flutter/examples/api/lib/widgets/draggable_scrollable_sheet/draggable_scrollable_sheet.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/draggable_scrollable_sheet/draggable_scrollable_sheet.0.dart",
"repo_id": "flutter",
"token_count": 1935
} | 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/foundation.dart';
import 'package:flutter/material.dart';
/// Flutter code sample for [ErrorWidget].
void main() {
// Set the ErrorWidget's builder before the app is started.
ErrorWidget.builder = (FlutterErrorDetails details) {
// If we're in debug mode, use the normal error widget which shows the error
// message:
if (kDebugMode) {
return ErrorWidget(details.exception);
}
// In release builds, show a yellow-on-blue message instead:
return Container(
alignment: Alignment.center,
child: Text(
'Error!\n${details.exception}',
style: const TextStyle(color: Colors.yellow),
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
),
);
};
// Start the app.
runApp(const ErrorWidgetExampleApp());
}
class ErrorWidgetExampleApp extends StatefulWidget {
const ErrorWidgetExampleApp({super.key});
@override
State<ErrorWidgetExampleApp> createState() => _ErrorWidgetExampleAppState();
}
class _ErrorWidgetExampleAppState extends State<ErrorWidgetExampleApp> {
bool throwError = false;
@override
Widget build(BuildContext context) {
if (throwError) {
// Since the error widget is only used during a build, in this contrived example,
// we purposely throw an exception in a build function.
return Builder(
builder: (BuildContext context) {
throw Exception('oh no, an error');
},
);
} else {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('ErrorWidget Sample')),
body: Center(
child: TextButton(
onPressed: () {
setState(() {
throwError = true;
});
},
child: const Text('Error Prone')),
),
),
);
}
}
}
| flutter/examples/api/lib/widgets/framework/error_widget.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/framework/error_widget.0.dart",
"repo_id": "flutter",
"token_count": 797
} | 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 'package:flutter/material.dart';
/// Flutter code sample for [SliverAnimatedOpacity].
void main() => runApp(const SliverAnimatedOpacityExampleApp());
class SliverAnimatedOpacityExampleApp extends StatelessWidget {
const SliverAnimatedOpacityExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('SliverAnimatedOpacity Sample')),
body: const Center(
child: SliverAnimatedOpacityExample(),
),
),
);
}
}
class SliverAnimatedOpacityExample extends StatefulWidget {
const SliverAnimatedOpacityExample({super.key});
@override
State<SliverAnimatedOpacityExample> createState() => _SliverAnimatedOpacityExampleState();
}
class _SliverAnimatedOpacityExampleState extends State<SliverAnimatedOpacityExample>
with SingleTickerProviderStateMixin {
bool _visible = true;
@override
Widget build(BuildContext context) {
return CustomScrollView(slivers: <Widget>[
SliverAnimatedOpacity(
opacity: _visible ? 1.0 : 0.0,
duration: const Duration(milliseconds: 500),
sliver: SliverFixedExtentList(
itemExtent: 100.0,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Container(
color: index.isEven ? Colors.indigo[200] : Colors.orange[200],
);
},
childCount: 5,
),
),
),
SliverToBoxAdapter(
child: FloatingActionButton(
onPressed: () {
setState(() {
_visible = !_visible;
});
},
tooltip: 'Toggle opacity',
child: const Icon(Icons.flip),
)),
]);
}
}
| flutter/examples/api/lib/widgets/implicit_animations/sliver_animated_opacity.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/implicit_animations/sliver_animated_opacity.0.dart",
"repo_id": "flutter",
"token_count": 787
} | 601 |
// Copyright 2014 The Flutter Authors. 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 [NavigatorState.restorablePushAndRemoveUntil].
void main() => runApp(const RestorablePushAndRemoveUntilExampleApp());
class RestorablePushAndRemoveUntilExampleApp extends StatelessWidget {
const RestorablePushAndRemoveUntilExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: RestorablePushAndRemoveUntilExample(),
);
}
}
class RestorablePushAndRemoveUntilExample extends StatefulWidget {
const RestorablePushAndRemoveUntilExample({super.key});
@override
State<RestorablePushAndRemoveUntilExample> createState() => _RestorablePushAndRemoveUntilExampleState();
}
class _RestorablePushAndRemoveUntilExampleState extends State<RestorablePushAndRemoveUntilExample> {
@pragma('vm:entry-point')
static Route<void> _myRouteBuilder(BuildContext context, Object? arguments) {
return MaterialPageRoute<void>(
builder: (BuildContext context) => const RestorablePushAndRemoveUntilExample(),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sample Code'),
),
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.of(context).restorablePushAndRemoveUntil(
_myRouteBuilder,
ModalRoute.withName('/'),
),
tooltip: 'Increment Counter',
child: const Icon(Icons.add),
),
);
}
}
| flutter/examples/api/lib/widgets/navigator/navigator_state.restorable_push_and_remove_until.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/navigator/navigator_state.restorable_push_and_remove_until.0.dart",
"repo_id": "flutter",
"token_count": 535
} | 602 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
/// Flutter code sample for [PageView].
void main() => runApp(const PageViewExampleApp());
class PageViewExampleApp extends StatelessWidget {
const PageViewExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('PageView Sample')),
body: const PageViewExample(),
),
);
}
}
class PageViewExample extends StatefulWidget {
const PageViewExample({super.key});
@override
State<PageViewExample> createState() => _PageViewExampleState();
}
class _PageViewExampleState extends State<PageViewExample> with TickerProviderStateMixin {
late PageController _pageViewController;
late TabController _tabController;
int _currentPageIndex = 0;
@override
void initState() {
super.initState();
_pageViewController = PageController();
_tabController = TabController(length: 3, vsync: this);
}
@override
void dispose() {
super.dispose();
_pageViewController.dispose();
_tabController.dispose();
}
@override
Widget build(BuildContext context) {
final TextTheme textTheme = Theme.of(context).textTheme;
return Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
PageView(
/// [PageView.scrollDirection] defaults to [Axis.horizontal].
/// Use [Axis.vertical] to scroll vertically.
controller: _pageViewController,
onPageChanged: _handlePageViewChanged,
children: <Widget>[
Center(
child: Text('First Page', style: textTheme.titleLarge),
),
Center(
child: Text('Second Page', style: textTheme.titleLarge),
),
Center(
child: Text('Third Page', style: textTheme.titleLarge),
),
],
),
PageIndicator(
tabController: _tabController,
currentPageIndex: _currentPageIndex,
onUpdateCurrentPageIndex: _updateCurrentPageIndex,
isOnDesktopAndWeb: _isOnDesktopAndWeb,
),
],
);
}
void _handlePageViewChanged(int currentPageIndex) {
if (!_isOnDesktopAndWeb) {
return;
}
_tabController.index = currentPageIndex;
setState(() {
_currentPageIndex = currentPageIndex;
});
}
void _updateCurrentPageIndex(int index) {
_tabController.index = index;
_pageViewController.animateToPage(
index,
duration: const Duration(milliseconds: 400),
curve: Curves.easeInOut,
);
}
bool get _isOnDesktopAndWeb {
if (kIsWeb) {
return true;
}
switch (defaultTargetPlatform) {
case TargetPlatform.macOS:
case TargetPlatform.linux:
case TargetPlatform.windows:
return true;
case TargetPlatform.android:
case TargetPlatform.iOS:
case TargetPlatform.fuchsia:
return false;
}
}
}
/// Page indicator for desktop and web platforms.
///
/// On Desktop and Web, drag gesture for horizontal scrolling in a PageView is disabled by default.
/// You can defined a custom scroll behavior to activate drag gestures,
/// see https://docs.flutter.dev/release/breaking-changes/default-scroll-behavior-drag.
///
/// In this sample, we use a TabPageSelector to navigate between pages,
/// in order to build natural behavior similar to other desktop applications.
class PageIndicator extends StatelessWidget {
const PageIndicator({
super.key,
required this.tabController,
required this.currentPageIndex,
required this.onUpdateCurrentPageIndex,
required this.isOnDesktopAndWeb,
});
final int currentPageIndex;
final TabController tabController;
final void Function(int) onUpdateCurrentPageIndex;
final bool isOnDesktopAndWeb;
@override
Widget build(BuildContext context) {
if (!isOnDesktopAndWeb) {
return const SizedBox.shrink();
}
final ColorScheme colorScheme = Theme.of(context).colorScheme;
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
splashRadius: 16.0,
padding: EdgeInsets.zero,
onPressed: () {
if (currentPageIndex == 0) {
return;
}
onUpdateCurrentPageIndex(currentPageIndex - 1);
},
icon: const Icon(
Icons.arrow_left_rounded,
size: 32.0,
),
),
TabPageSelector(
controller: tabController,
color: colorScheme.surface,
selectedColor: colorScheme.primary,
),
IconButton(
splashRadius: 16.0,
padding: EdgeInsets.zero,
onPressed: () {
if (currentPageIndex == 2) {
return;
}
onUpdateCurrentPageIndex(currentPageIndex + 1);
},
icon: const Icon(
Icons.arrow_right_rounded,
size: 32.0,
),
),
],
),
);
}
}
| flutter/examples/api/lib/widgets/page_view/page_view.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/page_view/page_view.0.dart",
"repo_id": "flutter",
"token_count": 2204
} | 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/material.dart';
/// Flutter code sample for a [ListView.custom] using the `findChildIndexCallback` argument.
void main() => runApp(const ListViewExampleApp());
class ListViewExampleApp extends StatelessWidget {
const ListViewExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: ListViewExample());
}
}
class ListViewExample extends StatefulWidget {
const ListViewExample({super.key});
@override
State<ListViewExample> createState() => _ListViewExampleState();
}
class _ListViewExampleState extends State<ListViewExample> {
List<String> items = <String>['1', '2', '3', '4', '5'];
void _reverse() {
setState(() {
items = items.reversed.toList();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: ListView.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({
required Key key,
required this.data,
}) : super(key: key);
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/scroll_view/list_view.1.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/scroll_view/list_view.1.dart",
"repo_id": "flutter",
"token_count": 1053
} | 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.
import 'package:flutter/material.dart';
void main() => runApp(const SliverDecorationExampleApp());
class SliverDecorationExampleApp extends StatelessWidget {
const SliverDecorationExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('SliverDecoration Sample')),
body: const SliverDecorationExample(),
),
);
}
}
class SliverDecorationExample extends StatelessWidget {
const SliverDecorationExample({super.key});
@override
Widget build(BuildContext context) {
return CustomScrollView(
slivers: <Widget>[
DecoratedSliver(
decoration: const BoxDecoration(
gradient: RadialGradient(
center: Alignment(-0.5, -0.6),
radius: 0.15,
colors: <Color>[
Color(0xFFEEEEEE),
Color(0xFF111133),
],
stops: <double>[0.9, 1.0],
),
),
sliver: SliverList(
delegate: SliverChildListDelegate(<Widget>[
const Text('Goodnight Moon'),
]),
),
),
const DecoratedSliver(
decoration: BoxDecoration(
color: Colors.amber,
borderRadius: BorderRadius.all(Radius.circular(50))
),
sliver: SliverToBoxAdapter(child: SizedBox(height: 300)),
),
],
);
}
}
| flutter/examples/api/lib/widgets/sliver/decorated_sliver.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/sliver/decorated_sliver.0.dart",
"repo_id": "flutter",
"token_count": 732
} | 605 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/material.dart';
/// Flutter code sample for [AnimatedWidget].
void main() => runApp(const AnimatedWidgetExampleApp());
class AnimatedWidgetExampleApp extends StatelessWidget {
const AnimatedWidgetExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: AnimatedWidgetExample(),
);
}
}
class SpinningContainer extends AnimatedWidget {
const SpinningContainer({
super.key,
required AnimationController controller,
}) : super(listenable: controller);
Animation<double> get _progress => listenable as Animation<double>;
@override
Widget build(BuildContext context) {
return Transform.rotate(
angle: _progress.value * 2.0 * math.pi,
child: Container(width: 200.0, height: 200.0, color: Colors.green),
);
}
}
class AnimatedWidgetExample extends StatefulWidget {
const AnimatedWidgetExample({super.key});
@override
State<AnimatedWidgetExample> createState() => _AnimatedWidgetExampleState();
}
/// [AnimationController]s can be created with `vsync: this` because of
/// [TickerProviderStateMixin].
class _AnimatedWidgetExampleState extends State<AnimatedWidgetExample> with TickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
duration: const Duration(seconds: 10),
vsync: this,
)..repeat();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SpinningContainer(controller: _controller);
}
}
| flutter/examples/api/lib/widgets/transitions/animated_widget.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/transitions/animated_widget.0.dart",
"repo_id": "flutter",
"token_count": 525
} | 606 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [TweenAnimationBuilder].
void main() => runApp(const TweenAnimationBuilderExampleApp());
class TweenAnimationBuilderExampleApp extends StatelessWidget {
const TweenAnimationBuilderExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('TweenAnimationBuilder Sample')),
body: const Center(
child: TweenAnimationBuilderExample(),
),
),
);
}
}
class TweenAnimationBuilderExample extends StatefulWidget {
const TweenAnimationBuilderExample({super.key});
@override
State<TweenAnimationBuilderExample> createState() => _TweenAnimationBuilderExampleState();
}
class _TweenAnimationBuilderExampleState extends State<TweenAnimationBuilderExample> {
double targetValue = 24.0;
@override
Widget build(BuildContext context) {
return TweenAnimationBuilder<double>(
tween: Tween<double>(begin: 0, end: targetValue),
duration: const Duration(seconds: 1),
builder: (BuildContext context, double size, Widget? child) {
return IconButton(
iconSize: size,
color: Colors.blue,
icon: child!,
onPressed: () {
setState(() {
targetValue = targetValue == 24.0 ? 48.0 : 24.0;
});
},
);
},
child: const Icon(Icons.aspect_ratio),
);
}
}
| flutter/examples/api/lib/widgets/tween_animation_builder/tween_animation_builder.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/tween_animation_builder/tween_animation_builder.0.dart",
"repo_id": "flutter",
"token_count": 598
} | 607 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter_api_samples/cupertino/list_section/list_section_inset.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Has exactly 1 CupertinoListSection inset grouped widget', (WidgetTester tester) async {
await tester.pumpWidget(
const example.CupertinoListSectionInsetApp(),
);
final Finder listSectionFinder = find.byType(CupertinoListSection);
expect(listSectionFinder, findsOneWidget);
final CupertinoListSection listSectionWidget = tester.widget<CupertinoListSection>(listSectionFinder);
expect(listSectionWidget.type, equals(CupertinoListSectionType.insetGrouped));
});
testWidgets('CupertinoListSection has 3 CupertinoListTile children', (WidgetTester tester) async {
await tester.pumpWidget(
const example.CupertinoListSectionInsetApp(),
);
expect(find.byType(CupertinoListTile), findsNWidgets(3));
});
}
| flutter/examples/api/test/cupertino/list_section/list_section_inset.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/cupertino/list_section/list_section_inset.0_test.dart",
"repo_id": "flutter",
"token_count": 371
} | 608 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter_api_samples/cupertino/slider/cupertino_slider.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
Future<void> dragSlider(WidgetTester tester, Key sliderKey) {
final Offset topLeft = tester.getTopLeft(find.byKey(sliderKey));
const double unit = CupertinoThumbPainter.radius;
const double delta = 3.0 * unit;
return tester.dragFrom(topLeft + const Offset(unit, unit), const Offset(delta, 0.0));
}
testWidgets('Can change value using CupertinoSlider', (WidgetTester tester) async {
await tester.pumpWidget(
const example.CupertinoSliderApp(),
);
// Check for the initial slider value.
expect(find.text('0.0'), findsOneWidget);
await dragSlider(tester, const Key('slider'));
await tester.pumpAndSettle();
// Check for the updated slider value.
expect(find.text('40.0'), findsOneWidget);
});
}
| flutter/examples/api/test/cupertino/slider/cupertino_slider.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/cupertino/slider/cupertino_slider.0_test.dart",
"repo_id": "flutter",
"token_count": 389
} | 609 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/material/app_bar/app_bar.1.dart' as example;
import 'package:flutter_test/flutter_test.dart';
const Offset _kOffset = Offset(0.0, -100.0);
void main() {
testWidgets('Appbar Material 3 test', (WidgetTester tester) async {
await tester.pumpWidget(
const example.AppBarApp()
);
expect(find.widgetWithText(AppBar, 'AppBar Demo'), findsOneWidget);
Material appbarMaterial = _getAppBarMaterial(tester);
expect(appbarMaterial.shadowColor, Colors.transparent);
expect(appbarMaterial.elevation, 0);
await tester.drag(find.text('Item 4'), _kOffset, touchSlopY: 0, warnIfMissed: false);
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
await tester.tap(find.text('shadow color'));
await tester.pumpAndSettle();
appbarMaterial = _getAppBarMaterial(tester);
expect(appbarMaterial.shadowColor, Colors.black);
expect(appbarMaterial.elevation, 3.0);
await tester.tap(find.text('scrolledUnderElevation: default'));
await tester.pumpAndSettle();
appbarMaterial = _getAppBarMaterial(tester);
expect(appbarMaterial.shadowColor, Colors.black);
expect(appbarMaterial.elevation, 4.0);
await tester.tap(find.text('scrolledUnderElevation: 4.0'));
await tester.pumpAndSettle();
appbarMaterial = _getAppBarMaterial(tester);
expect(appbarMaterial.shadowColor, Colors.black);
expect(appbarMaterial.elevation, 5.0);
});
}
Material _getAppBarMaterial(WidgetTester tester) {
return tester.widget<Material>(
find.descendant(
of: find.byType(AppBar),
matching: find.byType(Material),
),
);
}
| flutter/examples/api/test/material/app_bar/app_bar.1_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/app_bar/app_bar.1_test.dart",
"repo_id": "flutter",
"token_count": 672
} | 610 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/material/card/card.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Card Smoke Test', (WidgetTester tester) async {
await tester.pumpWidget(
const example.CardExampleApp(),
);
expect(find.byType(Card), findsOneWidget);
expect(find.widgetWithIcon(Card, Icons.album), findsOneWidget);
expect(find.widgetWithText(Card, 'The Enchanted Nightingale'), findsOneWidget);
expect(find.widgetWithText(Card, 'Music by Julie Gable. Lyrics by Sidney Stein.'), findsOneWidget);
expect(find.widgetWithText(Card, 'BUY TICKETS'), findsOneWidget);
expect(find.widgetWithText(Card, 'LISTEN'), findsOneWidget);
});
}
| flutter/examples/api/test/material/card/card.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/card/card.0_test.dart",
"repo_id": "flutter",
"token_count": 306
} | 611 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.