code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
// Copyright 2021 The Flutter team. 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 p; import 'common.dart'; import 'fix_base_tags.dart'; const ignoredDirectories = ['_tool', '_packages', 'samples_index']; void main() async { final packageDirs = [ ...listPackageDirs(Directory.current) .map((path) => p.relative(path, from: Directory.current.path)) .where((path) => !ignoredDirectories.contains(path)) ]; print('Building the sample index...'); await _run('samples_index', 'flutter', ['pub', 'get']); await _run('samples_index', 'flutter', ['pub', 'run', 'grinder', 'deploy']); // Create the directory each Flutter Web sample lives in Directory(p.join(Directory.current.path, 'samples_index', 'public', 'web')) .createSync(recursive: true); for (var i = 0; i < packageDirs.length; i++) { var directory = packageDirs[i]; logWrapped(ansiMagenta, '\n$directory (${i + 1} of ${packageDirs.length})'); // Create the target directory var directoryName = p.basename(directory); var sourceBuildDir = p.join(Directory.current.path, directory, 'build', 'web'); var targetDirectory = p.join(Directory.current.path, 'samples_index', 'public', 'web', directoryName); // Build the sample and copy the files await _run(directory, 'flutter', ['pub', 'get']); await _run(directory, 'flutter', ['build', 'web']); await _run(directory, 'mv', [sourceBuildDir, targetDirectory]); } // Update the <base href> tags in each index.html file await fixBaseTags(); } // Invokes run() and exits if the sub-process failed. Future<void> _run( String workingDir, String commandName, List<String> args) async { var success = await run(workingDir, commandName, args); if (!success) { exit(1); } }
samples/web/_tool/build_ci.dart/0
{'file_path': 'samples/web/_tool/build_ci.dart', 'repo_id': 'samples', 'token_count': 658}
import 'dart:html'; import 'package:mdc_web/mdc_web.dart'; import 'package:samples_index/src/carousel.dart'; void main() { querySelectorAll('.mdc-card__primary-action').forEach((el) => MDCRipple(el)); // Initialize carousel // This carousel will use the div slider-container as the base // withArrowKeyControl is used to listen for arrow key up events Carousel.init(withArrowKeyControl: true); }
samples/web/samples_index/web/description.dart/0
{'file_path': 'samples/web/samples_index/web/description.dart', 'repo_id': 'samples', 'token_count': 137}
name: ng_companion description: A flutter app with a counter that can be manipulated from JS. publish_to: 'none' version: 1.0.0 environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^3.0.0 flutter: uses-material-design: true assets: - assets/
samples/web_embedding/ng-flutter/flutter/pubspec.yaml/0
{'file_path': 'samples/web_embedding/ng-flutter/flutter/pubspec.yaml', 'repo_id': 'samples', 'token_count': 137}
name: example description: A new Flutter project. version: 1.0.0+1 publish_to: none environment: sdk: ">=2.19.0 <3.0.0" dependencies: flutter: sdk: flutter sealed_flutter_bloc: ^8.0.0 flutter: uses-material-design: true
sealed_flutter_bloc/example/pubspec.yaml/0
{'file_path': 'sealed_flutter_bloc/example/pubspec.yaml', 'repo_id': 'sealed_flutter_bloc', 'token_count': 103}
import 'package:bloc/bloc.dart' as bloc; import 'package:flutter/widgets.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:sealed_unions/sealed_unions.dart'; /// {@macro sealedblocwidgetbuilder} typedef WidgetSealedJoin8<A, B, C, D, E, F, G, H> = Widget Function( Widget Function(A) mapFirst, Widget Function(B) mapSecond, Widget Function(C) mapThird, Widget Function(D) mapFourth, Widget Function(E) mapFifth, Widget Function(F) mapSixth, Widget Function(G) mapSeventh, Widget Function(H) mapEighth, ); /// {@macro sealedblocwidgetbuilder} typedef SealedBlocWidgetBuilder8<S extends Union8<A, B, C, D, E, F, G, H>, A, B, C, D, E, F, G, H> = Widget Function( BuildContext context, WidgetSealedJoin8<A, B, C, D, E, F, G, H>, ); /// {@macro sealedblocbuilder} class SealedBlocBuilder8< Bloc extends bloc.BlocBase<State>, State extends Union8<A, B, C, D, E, F, G, H>, A, B, C, D, E, F, G, H> extends BlocBuilderBase<Bloc, State> { /// {@macro sealedblocbuilder} const SealedBlocBuilder8({ Key? key, required this.builder, Bloc? bloc, BlocBuilderCondition<State>? buildWhen, }) : super(key: key, bloc: bloc, buildWhen: buildWhen); /// {@macro sealedblocwidgetbuilder} final SealedBlocWidgetBuilder8<State, A, B, C, D, E, F, G, H> builder; @override Widget build(BuildContext context, State state) => builder(context, state.join); }
sealed_flutter_bloc/lib/src/sealed_bloc_builder/sealed_bloc_builder8.dart/0
{'file_path': 'sealed_flutter_bloc/lib/src/sealed_bloc_builder/sealed_bloc_builder8.dart', 'repo_id': 'sealed_flutter_bloc', 'token_count': 607}
import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:sealed_flutter_bloc/sealed_flutter_bloc.dart'; import 'helpers/helper_bloc4.dart'; void main() { group('SealedBlocBuilder4', () { const targetKey1 = Key('__target1__'); const targetKey2 = Key('__target2__'); const targetKey3 = Key('__target3__'); const targetKey4 = Key('__target4__'); testWidgets('should render properly', (tester) async { final bloc = HelperBloc4(); await tester.pumpWidget( SealedBlocBuilder4<HelperBloc4, HelperState4, State1, State2, State3, State4>( bloc: bloc, builder: (context, states) { return states( (first) => const SizedBox(key: targetKey1), (second) => const SizedBox(key: targetKey2), (third) => const SizedBox(key: targetKey3), (fourth) => const SizedBox(key: targetKey4), ); }, ), ); expect(find.byKey(targetKey1), findsOneWidget); bloc.add(HelperEvent4.event2); await tester.pumpAndSettle(); expect(find.byKey(targetKey2), findsOneWidget); bloc.add(HelperEvent4.event3); await tester.pumpAndSettle(); expect(find.byKey(targetKey3), findsOneWidget); bloc.add(HelperEvent4.event4); await tester.pumpAndSettle(); expect(find.byKey(targetKey4), findsOneWidget); }); }); }
sealed_flutter_bloc/test/sealed_bloc_builder4_test.dart/0
{'file_path': 'sealed_flutter_bloc/test/sealed_bloc_builder4_test.dart', 'repo_id': 'sealed_flutter_bloc', 'token_count': 652}
export 'post_repository.dart';
sealed_flutter_bloc_samples/sealed_flutter_infinite_list/lib/repositories/repositories.dart/0
{'file_path': 'sealed_flutter_bloc_samples/sealed_flutter_infinite_list/lib/repositories/repositories.dart', 'repo_id': 'sealed_flutter_bloc_samples', 'token_count': 12}
import 'dart:convert'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:http/http.dart' as http; import 'package:pub_semver/pub_semver.dart'; part 'pub.freezed.dart'; part 'pub.g.dart'; Future<PubVersionResponse?> fetchPubVersions(String packageName) async { final response = await http.get( Uri.parse('https://pub.dev/api/packages/$packageName'), ); if (response.statusCode != 200) return null; return PubVersionResponse.fromJson( jsonDecode(response.body) as Map<String, Object?>, ); } @freezed class PubVersionResponse with _$PubVersionResponse { factory PubVersionResponse({ required PubVersion latest, required List<PubVersion> versions, }) = _PubVersionResponse; PubVersionResponse._(); factory PubVersionResponse.fromJson(Map<String, Object?> json) => _$PubVersionResponseFromJson(json); bool hasVersion(Version version) => latest.version == version || versions.any((element) => element.version == version); } @freezed class PubVersion with _$PubVersion { factory PubVersion({ @VersionConverter() required Version version, }) = _PubVersion; factory PubVersion.fromJson(Map<String, Object?> json) => _$PubVersionFromJson(json); } class VersionConverter extends JsonConverter<Version, String> { const VersionConverter(); @override Version fromJson(String json) => Version.parse(json); @override String toJson(Version object) => object.toString(); }
semantic_changelog/lib/src/pub.dart/0
{'file_path': 'semantic_changelog/lib/src/pub.dart', 'repo_id': 'semantic_changelog', 'token_count': 483}
// ignore_for_file: public_member_api_docs, sort_constructors_first part of 'shoe_bloc.dart'; @immutable abstract class ShoeState {} @immutable class ShoeInitial extends ShoeState {} @immutable class ShoeStateLoading extends ShoeState {} @immutable class ShoeStateLoaded extends ShoeState { final List<Shoe> shoes; ShoeStateLoaded({ required this.shoes, }); } @immutable class ShoeStateError extends ShoeState { ShoeStateError({ required this.errorMessage, }); final String errorMessage; }
shopping-ui-BLoC/lib/presentation/blocs/shoe_bloc/shoe_state.dart/0
{'file_path': 'shopping-ui-BLoC/lib/presentation/blocs/shoe_bloc/shoe_state.dart', 'repo_id': 'shopping-ui-BLoC', 'token_count': 174}
export 'meta_weather_api_client.dart'; export 'models/models.dart';
simple_weather/lib/api/api.dart/0
{'file_path': 'simple_weather/lib/api/api.dart', 'repo_id': 'simple_weather', 'token_count': 24}
import 'package:flutter/material.dart'; class WeatherLoading extends StatelessWidget { const WeatherLoading({Key key}) : super(key: key); @override Widget build(BuildContext context) { final theme = Theme.of(context); return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: [ const Text( '⛅', style: TextStyle(fontSize: 64), ), Text( 'Loading Weather', style: theme.textTheme.headline5, ), const Padding( padding: EdgeInsets.all(16.0), child: CircularProgressIndicator(), ), ], ); } }
simple_weather/lib/app/weather/widgets/weather_loading.dart/0
{'file_path': 'simple_weather/lib/app/weather/widgets/weather_loading.dart', 'repo_id': 'simple_weather', 'token_count': 309}
import 'package:snake_chef/game/assets.dart'; import 'package:snake_chef/game/stage.dart'; import 'dart:ui'; void renderIngredient(Canvas canvas, Ingredient ingredient, Rect rect) { Ingredients.getSprite(ingredient)?.renderRect(canvas, rect); }
snake-chef/snake_chef/lib/game/ingredient_renderer.dart/0
{'file_path': 'snake-chef/snake_chef/lib/game/ingredient_renderer.dart', 'repo_id': 'snake-chef', 'token_count': 88}
import 'package:flutter/material.dart'; import '../../widgets/direction_pad.dart'; import '../../widgets/action_button.dart'; class GamepadPreview extends StatelessWidget { final double size; final double opacity; final double borderPercent; GamepadPreview({ this.size, this.opacity, this.borderPercent, }); @override Widget build(ctx) { return LayoutBuilder(builder: (ctx, constraints) { final gamepadButtonSize = size * constraints.maxHeight; return Container( width: constraints.maxWidth, height: constraints.maxHeight, color: Color(0xFF1a1c2c), child: Stack( children: [ Positioned( left: 0, bottom: 0, child: DirectionPad( containerSize: gamepadButtonSize, opacity: opacity, borderPercent: borderPercent, ), ), Positioned( right: 0, bottom: 0, child: ActionButton( dpadSize: gamepadButtonSize, opacity: opacity, borderPercent: borderPercent, ), ), ], ), ); }); } }
snake-chef/snake_chef/lib/screens/gamepad_config/preview.dart/0
{'file_path': 'snake-chef/snake_chef/lib/screens/gamepad_config/preview.dart', 'repo_id': 'snake-chef', 'token_count': 610}
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gl/flutter_gl.dart'; import 'package:solar_system/models/config_options.dart'; import 'package:solar_system/models/planet.dart'; import 'package:solar_system/res/assets/textures.dart'; import 'package:solar_system/res/extensions/planet_extension.dart'; import 'package:solar_system/widgets/credit_widget.dart'; import 'package:solar_system/widgets/scene_title_widget.dart'; import 'package:three_dart/three_dart.dart' as three; import 'package:three_dart_jsm/three_dart_jsm.dart' as three_jsm; class HomeScene extends StatefulWidget { const HomeScene({super.key}); @override State<HomeScene> createState() => _HomeSceneState(); } class _HomeSceneState extends State<HomeScene> { /// Keys late final GlobalKey<three_jsm.DomLikeListenableState> _domLikeKey; /// three three.WebGLRenderer? renderer; three.WebGLRenderTarget? renderTarget; /// GL late FlutterGlPlugin three3dRender; /// config late double width; late double height; late three.Scene _scene; late three.Camera _camera; Size? screenSize; double dpr = 1; late int sourceTexture; /// planets late three.Mesh _sun; late Planet _planet; @override void initState() { super.initState(); _domLikeKey = GlobalKey(); _planet = const Planet(); } @override Widget build(BuildContext context) { return three_jsm.DomLikeListenable( key: _domLikeKey, builder: (context) { _initSize(); return Scaffold( body: Column( children: [ Stack( children: [ Container( width: width, height: height, color: Colors.black, child: Builder( builder: (BuildContext context) { if (three3dRender.isInitialized) { if (kIsWeb) { return HtmlElementView( viewType: three3dRender.textureId!.toString(), ); } return Texture( textureId: three3dRender.textureId!, ); } return Container(); }, ), ), const SceneTitileWidget(), const Positioned( bottom: 20, left: 20, child: CreditWidget(), ), ], ), ], ), ); }, ); } void _initSize() { if (screenSize != null) { return; } final mediaQuery = MediaQuery.of(context); screenSize = mediaQuery.size; dpr = mediaQuery.devicePixelRatio; _initPlatformState(); } Future<void> _initPlatformState() async { width = screenSize!.width; height = screenSize!.height; three3dRender = FlutterGlPlugin(); final options = ConfigOptions( antialias: true, alpha: true, width: width.toInt(), height: height.toInt(), dpr: dpr, ); await three3dRender.initialize(options: options.toMap()); setState(() {}); Future.delayed(const Duration(milliseconds: 100), () async { await three3dRender.prepareContext(); await _initScene(); }); } Future<void> _initScene() async { await _initRenderer(); _scene = three.Scene(); _camera = three.PerspectiveCamera(45, width / height, 0.1, 1000); final orbit = three_jsm.OrbitControls(_camera, _domLikeKey); _camera.position.set(190, 140, 140); orbit.update(); /// final ambientLight = three.AmbientLight(0x333333); _scene.add(ambientLight); /// final backgroundTextureLoader = three.TextureLoader(null); final backgroundTexture = await backgroundTextureLoader.loadAsync( textureStars, ); /// final sunGeo = three.SphereGeometry(16, 30, 30); final sunTextureLoader = three.TextureLoader(null); final sunMat = three.MeshBasicMaterial({ 'map': await sunTextureLoader.loadAsync( textureSun, ), }); _sun = three.Mesh(sunGeo, sunMat); _scene.add(_sun); _planet = await _planet.initializePlanets(_scene); final pointLight = three.PointLight(0xFFFFFFFF, 2, 300); _scene ..add(pointLight) ..background = backgroundTexture; /// await _planet.animate( sun: _sun, planet: _planet, render: () { renderer!.render(_scene, _camera); }, ); } Future<void> _initRenderer() async { final options = ConfigOptions( antialias: true, alpha: true, width: width, height: height, gl: three3dRender.gl, ); renderer = three.WebGLRenderer( options.toMap(), ); renderer!.setPixelRatio(dpr); renderer!.setSize(width, height); renderer!.shadowMap.enabled = true; if (!kIsWeb) { final pars = three.WebGLRenderTargetOptions({'format': three.RGBAFormat}); renderTarget = three.WebGLRenderTarget( (width * dpr).toInt(), (height * dpr).toInt(), pars, ); renderTarget!.samples = 4; renderer!.setRenderTarget(renderTarget); sourceTexture = renderer!.getRenderTargetGLTexture(renderTarget!); } else { renderTarget = null; } } }
solar-system/lib/scenes/home_scene.dart/0
{'file_path': 'solar-system/lib/scenes/home_scene.dart', 'repo_id': 'solar-system', 'token_count': 2504}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'web_angular.dart'; // ************************************************************************** // DataGenerator // ************************************************************************** const _data = <String>[ '.gitignore', 'text', ''' IyBGaWxlcyBhbmQgZGlyZWN0b3JpZXMgY3JlYXRlZCBieSBwdWIKLmRhcnRfdG9vbC8KLnBhY2th Z2VzCgojIENvbnZlbnRpb25hbCBkaXJlY3RvcnkgZm9yIGJ1aWxkIG91dHB1dHMKYnVpbGQvCgoj IERpcmVjdG9yeSBjcmVhdGVkIGJ5IGRhcnRkb2MKZG9jL2FwaS8K''', 'CHANGELOG.md', 'text', 'IyMgMS4wLjAKCi0gSW5pdGlhbCB2ZXJzaW9uLCBjcmVhdGVkIGJ5IFN0YWdlaGFuZAo=', 'README.md', 'text', ''' IyBfX3Byb2plY3ROYW1lX18KCkEgd2ViIGFwcCB0aGF0IHVzZXMgW0FuZ3VsYXJEYXJ0XShodHRw czovL2FuZ3VsYXJkYXJ0LmRldikgYW5kCltBbmd1bGFyRGFydCBDb21wb25lbnRzXShodHRwczov L2FuZ3VsYXJkYXJ0LmRldi9jb21wb25lbnRzKS4KCkNyZWF0ZWQgZnJvbSB0ZW1wbGF0ZXMgbWFk ZSBhdmFpbGFibGUgYnkgU3RhZ2VoYW5kIHVuZGVyIGEgQlNELXN0eWxlCltsaWNlbnNlXShodHRw czovL2dpdGh1Yi5jb20vZGFydC1sYW5nL3N0YWdlaGFuZC9ibG9iL21hc3Rlci9MSUNFTlNFKS4K''', 'analysis_options.yaml', 'text', ''' IyBEZWZpbmVzIGEgZGVmYXVsdCBzZXQgb2YgbGludCBydWxlcyBlbmZvcmNlZCBmb3IKIyBwcm9q ZWN0cyBhdCBHb29nbGUuIEZvciBkZXRhaWxzIGFuZCByYXRpb25hbGUsCiMgc2VlIGh0dHBzOi8v Z2l0aHViLmNvbS9kYXJ0LWxhbmcvcGVkYW50aWMjZW5hYmxlZC1saW50cy4KaW5jbHVkZTogcGFj a2FnZTpwZWRhbnRpYy9hbmFseXNpc19vcHRpb25zLnlhbWwKCiMgRm9yIGxpbnQgcnVsZXMgYW5k IGRvY3VtZW50YXRpb24sIHNlZSBodHRwOi8vZGFydC1sYW5nLmdpdGh1Yi5pby9saW50ZXIvbGlu dHMuCiMgVW5jb21tZW50IHRvIHNwZWNpZnkgYWRkaXRpb25hbCBydWxlcy4KIyBsaW50ZXI6CiMg ICBydWxlczoKIyAgICAgLSBjYW1lbF9jYXNlX3R5cGVzCgphbmFseXplcjoKICBleGNsdWRlOiBb YnVpbGQvKipdCiAgZXJyb3JzOgogICAgdXJpX2hhc19ub3RfYmVlbl9nZW5lcmF0ZWQ6IGlnbm9y ZQogICMgQW5ndWxhciBwbHVnaW4gc3VwcG9ydCBpcyBpbiBiZXRhLiBZb3UncmUgd2VsY29tZSB0 byB0cnkgaXQgYW5kIHJlcG9ydAogICMgaXNzdWVzOiBodHRwczovL2dpdGh1Yi5jb20vZGFydC1s YW5nL2FuZ3VsYXJfYW5hbHl6ZXJfcGx1Z2luL2lzc3VlcwogICMgcGx1Z2luczoKICAgICMgLSBh bmd1bGFyCg==''', 'lib/app_component.css', 'text', ''' Omhvc3QgewogICAgLyogVGhpcyBpcyBlcXVpdmFsZW50IG9mIHRoZSAnYm9keScgc2VsZWN0b3Ig b2YgYSBwYWdlLiAqLwp9Cg==''', 'lib/app_component.dart', 'text', ''' aW1wb3J0ICdwYWNrYWdlOmFuZ3VsYXIvYW5ndWxhci5kYXJ0JzsKCmltcG9ydCAnc3JjL3RvZG9f bGlzdC90b2RvX2xpc3RfY29tcG9uZW50LmRhcnQnOwoKLy8gQW5ndWxhckRhcnQgaW5mbzogaHR0 cHM6Ly9hbmd1bGFyZGFydC5kZXYKLy8gQ29tcG9uZW50cyBpbmZvOiBodHRwczovL2FuZ3VsYXJk YXJ0LmRldi9jb21wb25lbnRzCgpAQ29tcG9uZW50KAogIHNlbGVjdG9yOiAnbXktYXBwJywKICBz dHlsZVVybHM6IFsnYXBwX2NvbXBvbmVudC5jc3MnXSwKICB0ZW1wbGF0ZVVybDogJ2FwcF9jb21w b25lbnQuaHRtbCcsCiAgZGlyZWN0aXZlczogW1RvZG9MaXN0Q29tcG9uZW50XSwKKQpjbGFzcyBB cHBDb21wb25lbnQgewogIC8vIE5vdGhpbmcgaGVyZSB5ZXQuIEFsbCBsb2dpYyBpcyBpbiBUb2Rv TGlzdENvbXBvbmVudC4KfQo=''', 'lib/app_component.html', 'text', ''' PGgxPk15IEZpcnN0IEFuZ3VsYXJEYXJ0IEFwcDwvaDE+Cgo8dG9kby1saXN0PjwvdG9kby1saXN0 Pgo=''', 'lib/src/todo_list/todo_list_component.css', 'text', ''' dWwgewogIGxpc3Qtc3R5bGU6IG5vbmU7CiAgcGFkZGluZy1sZWZ0OiAwOwp9CgpsaSB7CiAgbGlu ZS1oZWlnaHQ6IDNlbTsKfQoKbGk6aG92ZXIgewogIGJhY2tncm91bmQtY29sb3I6ICNFRUVFRUU7 Cn0KCmxpIG1hdGVyaWFsLWNoZWNrYm94IHsKICB2ZXJ0aWNhbC1hbGlnbjogbWlkZGxlOwp9Cgps aSBtYXRlcmlhbC1mYWIgewogIGZsb2F0OiByaWdodDsKICB2ZXJ0aWNhbC1hbGlnbjogbWlkZGxl Owp9CgouZG9uZSB7CiAgdGV4dC1kZWNvcmF0aW9uOiBsaW5lLXRocm91Z2g7Cn0K''', 'lib/src/todo_list/todo_list_component.dart', 'text', ''' aW1wb3J0ICdkYXJ0OmFzeW5jJzsKCmltcG9ydCAncGFja2FnZTphbmd1bGFyL2FuZ3VsYXIuZGFy dCc7CmltcG9ydCAncGFja2FnZTphbmd1bGFyX2NvbXBvbmVudHMvYW5ndWxhcl9jb21wb25lbnRz LmRhcnQnOwoKaW1wb3J0ICd0b2RvX2xpc3Rfc2VydmljZS5kYXJ0JzsKCkBDb21wb25lbnQoCiAg c2VsZWN0b3I6ICd0b2RvLWxpc3QnLAogIHN0eWxlVXJsczogWyd0b2RvX2xpc3RfY29tcG9uZW50 LmNzcyddLAogIHRlbXBsYXRlVXJsOiAndG9kb19saXN0X2NvbXBvbmVudC5odG1sJywKICBkaXJl Y3RpdmVzOiBbCiAgICBNYXRlcmlhbENoZWNrYm94Q29tcG9uZW50LAogICAgTWF0ZXJpYWxGYWJD b21wb25lbnQsCiAgICBNYXRlcmlhbEljb25Db21wb25lbnQsCiAgICBtYXRlcmlhbElucHV0RGly ZWN0aXZlcywKICAgIE5nRm9yLAogICAgTmdJZiwKICBdLAogIHByb3ZpZGVyczogW0NsYXNzUHJv dmlkZXIoVG9kb0xpc3RTZXJ2aWNlKV0sCikKY2xhc3MgVG9kb0xpc3RDb21wb25lbnQgaW1wbGVt ZW50cyBPbkluaXQgewogIGZpbmFsIFRvZG9MaXN0U2VydmljZSB0b2RvTGlzdFNlcnZpY2U7Cgog IExpc3Q8U3RyaW5nPiBpdGVtcyA9IFtdOwogIFN0cmluZyBuZXdUb2RvID0gJyc7CgogIFRvZG9M aXN0Q29tcG9uZW50KHRoaXMudG9kb0xpc3RTZXJ2aWNlKTsKCiAgQG92ZXJyaWRlCiAgRnV0dXJl PE51bGw+IG5nT25Jbml0KCkgYXN5bmMgewogICAgaXRlbXMgPSBhd2FpdCB0b2RvTGlzdFNlcnZp Y2UuZ2V0VG9kb0xpc3QoKTsKICB9CgogIHZvaWQgYWRkKCkgewogICAgaXRlbXMuYWRkKG5ld1Rv ZG8pOwogICAgbmV3VG9kbyA9ICcnOwogIH0KCiAgU3RyaW5nIHJlbW92ZShpbnQgaW5kZXgpID0+ IGl0ZW1zLnJlbW92ZUF0KGluZGV4KTsKfQo=''', 'lib/src/todo_list/todo_list_component.html', 'text', ''' PCEtLSBDb21wb25lbnRzIGluZm86IGh0dHBzOi8vYW5ndWxhcmRhcnQuZGV2L2NvbXBvbmVudHMg LS0+CjxkaXY+CiAgPG1hdGVyaWFsLWlucHV0IGxhYmVsPSJXaGF0IGRvIHlvdSBuZWVkIHRvIGRv PyIKICAgICAgICAgICAgICAgICAgYXV0b0ZvY3VzIGZsb2F0aW5nTGFiZWwgc3R5bGU9IndpZHRo OjgwJSIKICAgICAgICAgICAgICAgICAgWyhuZ01vZGVsKV09Im5ld1RvZG8iCiAgICAgICAgICAg ICAgICAgIChrZXl1cC5lbnRlcik9ImFkZCgpIj4KICA8L21hdGVyaWFsLWlucHV0PgoKICA8bWF0 ZXJpYWwtZmFiIG1pbmkgcmFpc2VkCiAgICAgICAgICAgICAgICAodHJpZ2dlcik9ImFkZCgpIgog ICAgICAgICAgICAgICAgW2Rpc2FibGVkXT0ibmV3VG9kby5pc0VtcHR5Ij4KICAgIDxtYXRlcmlh bC1pY29uIGljb249ImFkZCI+PC9tYXRlcmlhbC1pY29uPgogIDwvbWF0ZXJpYWwtZmFiPgo8L2Rp dj4KCjxwICpuZ0lmPSJpdGVtcy5pc0VtcHR5Ij4KICBOb3RoaW5nIHRvIGRvISBBZGQgaXRlbXMg YWJvdmUuCjwvcD4KCjxkaXYgKm5nSWY9Iml0ZW1zLmlzTm90RW1wdHkiPgogIDx1bD4KICAgICAg PGxpICpuZ0Zvcj0ibGV0IGl0ZW0gb2YgaXRlbXM7IGxldCBpPWluZGV4Ij4KICAgICAgICA8bWF0 ZXJpYWwtY2hlY2tib3ggI2RvbmUgbWF0ZXJpYWxUb29sdGlwPSJNYXJrIGl0ZW0gYXMgZG9uZSI+ CiAgICAgICAgPC9tYXRlcmlhbC1jaGVja2JveD4KICAgICAgICA8c3BhbiBbY2xhc3MuZG9uZV09 ImRvbmUuY2hlY2tlZCI+e3tpdGVtfX08L3NwYW4+CiAgICAgICAgPG1hdGVyaWFsLWZhYiBtaW5p ICh0cmlnZ2VyKT0icmVtb3ZlKGkpIj4KICAgICAgICAgIDxtYXRlcmlhbC1pY29uIGljb249ImRl bGV0ZSI+PC9tYXRlcmlhbC1pY29uPgogICAgICAgIDwvbWF0ZXJpYWwtZmFiPgogICAgICA8L2xp PgogIDwvdWw+CjwvZGl2Pgo=''', 'lib/src/todo_list/todo_list_service.dart', 'text', ''' aW1wb3J0ICdkYXJ0OmFzeW5jJzsKCmltcG9ydCAncGFja2FnZTphbmd1bGFyL2NvcmUuZGFydCc7 CgovLy8gTW9jayBzZXJ2aWNlIGVtdWxhdGluZyBhY2Nlc3MgdG8gYSB0by1kbyBsaXN0IHN0b3Jl ZCBvbiBhIHNlcnZlci4KQEluamVjdGFibGUoKQpjbGFzcyBUb2RvTGlzdFNlcnZpY2UgewogIExp c3Q8U3RyaW5nPiBtb2NrVG9kb0xpc3QgPSA8U3RyaW5nPltdOwoKICBGdXR1cmU8TGlzdDxTdHJp bmc+PiBnZXRUb2RvTGlzdCgpIGFzeW5jID0+IG1vY2tUb2RvTGlzdDsKfQo=''', 'pubspec.yaml', 'text', ''' bmFtZTogX19wcm9qZWN0TmFtZV9fCmRlc2NyaXB0aW9uOiBBIHdlYiBhcHAgdGhhdCB1c2VzIEFu Z3VsYXJEYXJ0IENvbXBvbmVudHMKIyB2ZXJzaW9uOiAxLjAuMAojIGhvbWVwYWdlOiBodHRwczov L3d3dy5leGFtcGxlLmNvbQoKZW52aXJvbm1lbnQ6CiAgc2RrOiAnPj0yLjguMSA8My4wLjAnCgpk ZXBlbmRlbmNpZXM6CiAgYW5ndWxhcjogXjUuMy4xCiAgYW5ndWxhcl9jb21wb25lbnRzOiBeMC4x My4wKzEKCmRldl9kZXBlbmRlbmNpZXM6CiAgYW5ndWxhcl90ZXN0OiBeMi4zLjAKICBidWlsZF9y dW5uZXI6IF4xLjkuMAogIGJ1aWxkX3Rlc3Q6IF4xLjAuMAogIGJ1aWxkX3dlYl9jb21waWxlcnM6 IF4yLjEwLjAKICBwZWRhbnRpYzogXjEuOS4wCiAgdGVzdDogXjEuNi4zCg==''', 'test/app_test.dart', 'text', ''' QFRlc3RPbignYnJvd3NlcicpCmltcG9ydCAncGFja2FnZTphbmd1bGFyX3Rlc3QvYW5ndWxhcl90 ZXN0LmRhcnQnOwppbXBvcnQgJ3BhY2thZ2U6dGVzdC90ZXN0LmRhcnQnOwppbXBvcnQgJ3BhY2th Z2U6X19wcm9qZWN0TmFtZV9fL2FwcF9jb21wb25lbnQuZGFydCc7CmltcG9ydCAncGFja2FnZTpf X3Byb2plY3ROYW1lX18vYXBwX2NvbXBvbmVudC50ZW1wbGF0ZS5kYXJ0JyBhcyBuZzsKCnZvaWQg bWFpbigpIHsKICBmaW5hbCB0ZXN0QmVkID0KICAgICAgTmdUZXN0QmVkLmZvckNvbXBvbmVudDxB cHBDb21wb25lbnQ+KG5nLkFwcENvbXBvbmVudE5nRmFjdG9yeSk7CiAgTmdUZXN0Rml4dHVyZTxB cHBDb21wb25lbnQ+IGZpeHR1cmU7CgogIHNldFVwKCgpIGFzeW5jIHsKICAgIGZpeHR1cmUgPSBh d2FpdCB0ZXN0QmVkLmNyZWF0ZSgpOwogIH0pOwoKICB0ZWFyRG93bihkaXNwb3NlQW55UnVubmlu Z1Rlc3QpOwoKICB0ZXN0KCdoZWFkaW5nJywgKCkgewogICAgZXhwZWN0KGZpeHR1cmUudGV4dCwg Y29udGFpbnMoJ015IEZpcnN0IEFuZ3VsYXJEYXJ0IEFwcCcpKTsKICB9KTsKCiAgLy8gVGVzdGlu ZyBpbmZvOiBodHRwczovL2FuZ3VsYXJkYXJ0LmRldi9ndWlkZS90ZXN0aW5nCn0K''', 'web/favicon.png', 'binary', ''' iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAKLElEQVR4AeVbA3yj2xOd4tm2bdu2 bdu2/V6DZm00apZvbduNs1nvNs0XVBvU85/5Z/uUmyZfkm95fr+pkTkz98zJvTewxdAPdwW9/wbo 4r0LdN69YYfAt1OLwRy6CEyBn+i9FfQSFpS6sUBlX1GoceiIiGug3+pdYbuDPnw6GAKfgFGaB8ZA MwzeiFBejVDmp+RtTAARsRwLSuhjtcMKWsdPoPVcxITBNgtL9dFgDr5MCU+giMDgekq6BuljBIOU iLKqBAF/VGwKKxOwiQxrc4HaPg+0to+gk+dU2CZg9B0IxvDDYApZKNEQDKpDsNRS0kFOuD2EBCRF CZGhcRIZHv6ZCJExHrSul6CX90jYqtAnuBclfSut696U+DquMidOH4uTzoAAMRkuLNAyGfYg6UU5 6NwPQu/1+2+h9sadScCuoCTUVOnlYApT0vVpkhbEwCqEEjEBqcmwMRFMCJOxDrTOnqBz3QxdHHuC okAsgDLpHDAEvyIxW0Ki1srrGsxhTkZ+0ATY0yzhXjpa879zcvKDCGjvCg4PqG0loHFdBhbHzpA3 mKUTwBh6C0zBaVTtuFDMsomBfvxwaQQ/nFqJ8PNSTiinSIinhzuktUBtWwwa5xfQyXVWliYlcCiY q5+gpP+kqOX2JjHLMmlx9Xc3B9BT34LuUBx3V1sRsusCQfAkcfIk4a6IEzFTQOd8jTrjWOgQhtr9 wOC/hxRbT+HnhMFSl1rBc6z+QzNrsR0P/rkG4RfZXSBXPGuoK4ZBqetxen+YYIRJ75NBEYtZnqOI Yqq/Cdsxee1GLKIOgDwmLxZPcp06L0KpQwVJMEn3UdXzn7Cg+ldPrMHmNvwLza1teKVxBcKvy/jB KhvUDVBS8ZiAAP8l9ABbaJ0rTICE5jUN+F/onTWbhwASS9DabxEIX9Wx9ADr87fmBUHe//RRYYxQ +f+L+sZWPLWPG+E3BUlIeI6Y2FrrcW8w+teBWcH1P8CPGncUU+GPBQEeicoSoLIGoPP8AyAJU7GY zM1CmvHKJE+j7/ChQfTHWzEVfJEmPKSLQ7kuUJFXUNuXkw7tAULo/aPIxytW/Y+XbsR0eHdKpXJd oHHzaJzIrhaEMPh70BhUpPp7lSeMTzo4gnHcQ2ND+F2ZCVCoshohJYz+LxQhgKr/1Jw6zBSPjFir jDHSengCqCElDNLTMDj/BBRTzAk2YaaYui6CRX8oYIxKiQCV9aUOOkC6CUw8BgN5NT43Ta5B8jpJ mFAZxwmU7H/R3NaGV5sUMEbkBEFjux9SwuI/i0hoyKsZKpNw+PoGFOHuKWG8Z8Q6FMHkyrcxsrIA tpINvrKDDogcQg86TF2Qt+TPHRPGeEty+b0kiHsY/binzoHe6mSCNja14ml9PfkbiSU2JqAO1J4j ICVG4u7U/m4wh/PW/t28MRThG2sUob+PqlyB386uQhHUC4P5G4kqG5Pgg67W/Trc9SECpoOlNi+j 7+jhQQw3tibb3qY2PHEEkTygCoFa8+ReLrLCySOyKtKMh3V15Gckqp1MwuL0u0X6QHleRiGNvq+t ERTBvCaOUPb3piivdTOteRE+nOrLTxdoPbwE/oS0MEolREDO1d/XEsTVkeSq8jS4kaYCL492Anjm 32RZJZwUrlAD7pkPY8QmSG3vD2lh8L+Tsxeg5F6aX48iLAo34S7Gf2+Lw+/LcBeVFRf5xXrx2Mi1 uXcBEQBq+5eZdMADpAE5VX9nSnBxuBlFeHNhPS+PpHMBTvCtSZUowowNESymn8mpC2iPEEqsT0Ba DPRdyVveWXsBqv5d02qxDZPBzwQPGRpkkpIJoHHHguePJhPHU/S68pW8VHLcCLHdCWnRXzqBHmA0 242RAr0fx/oaUYQunhgTlPJkiBPssjSEIljctdkboxIrG6EGKHWeCQIIdoelyqw2Rim5S8ZXY6NA zWJUxrNGhxH6s/htigE+amsrJ5aIn5bi2f09GBPsGEWbW/HMfh7+uWxNUBh03oMgLXhOGqSldHyd FQH9V8VRhIqaZrxkbBgvGlf9d4wJ4cWGFXhxmfevuJSiIhBHEXSLszRGKjsTsAr4HDMjGKRxMKhW ru0lcxPCOjI5IrRh5mhL8cMB0ofDuzrl22ONiwmYCt9+WwgZwRjoI9sLUPV/cURRaXwyvUp+F7AJ UlsHQcYwSN/K8gKk6gcODmJlrBWVhoeeOO2lZe8g2wN0kkGA/wVZBNBcf5vm++bCU6PX8cSQ6QEq XoeMYQ7clpgCgYwPOu21zbi5MKcymjBGcjZCtLZHIGOYAudRcs2kBRkedNahCA0tyLqAn9Bu8Kei WFKPn86owk+n+5Lik2k+VC0MIk0/8fMJy0rxSBRvhLSBxnYtZIwB64+g5GozMUNFFNMk8X7feF8j L4/U0c9Hip6wwcIgtZ9L1RZh2PI6/n6mp0ERKHUcLe/ej0FaAeZw2upfNbGaraoQj86q5Z/J+o4Q k/DqhA0oQoxa42yxMRKZIAl6eA6UcaERC+kBzgFLTdqzPtMasWnhp8L7WAKsEdkT8Hvq5weMTkuC 6cVQ7WQCKuRfwNRLQ+mUqEPjc1qKg07Gr44oVz/nW2KcYPdlIRQhGGvBI7unMUZaN+vAaJANQ6C0 QzNEyald4vUZT/h+Jil3AqjFLzd4saVVTPRnM0TGKGkjxJAFAdKHdGMk5eg7bGgQpRQHnWMqG7BA nLx8AiiKKWZXRlAEb00j7lPKxqijCxH277IgwP8oWGpTGp+PlqQ+6Hx4pkD8ZBAgEsOXx6/HVHhm TAfGiE2QyvosyIYxeA35gDaKpOrvPyiI66MtKMIaEr+9y8XilzUBtMb52DwUE4thRaCDm2YaJ4LG eS/IRlnlKdQFjURAkvKfQ4cdrP7G1f8O/trz8+oEa18uAWIS3p5ciXxiZHT+OwwUJ/R08c8INkIq mkHnOQdkg+/hshcYEhFflSMixCFOVj4BYkFMEeJdoMSt8yrBRkiGKAucCKZgDyIgziMx5zNDMQHK XIRQ21oKNU4zaN1nQ84whS4hEkaAOdRGwrj1EsCmR/P/mErW9wbIO0zBO4iMuewQactMYQLkX5qm xCto4/NRZV9pwpbSGHiOiHAJbpUqTIDA5/M6V9vXUeLvKHhlXgDD2v2gPPQZ3yvmzRN6ryABAoHT ejjxGtC6fhHf/VUG4guW5pCOOiHCHUHdoSwBWjcn3kQCNwC6LD8NthqU+c6n5AeBMdRKQpl/Aljc 1A4iwDFWfMtja4ExfBN1wzS+cEmRMwGJpN1MwELQ2h/gp+qw1aPHop3AKD0JpoCNlwWYw/IJUCUE jt6vojX+2rb5gkp9eG8Sxw9ofG7gZ5b0XkyASOA0jhCoHd9BtxUHbw+vHD2SiCgBU7h2k1AKCLAm Wl3liBeq7L1orJ0E2x2MVWcQEXrSiGaw1LUT0P4SOK76n6DzXAzbPUzBa4mECWAIbBprzjmgc90F OxRYzQf63qNZ/j3ovLvAFsL/AD2paxVjuEZQAAAAAElFTkSuQmCC''', 'web/index.html', 'text', ''' PCFET0NUWVBFIGh0bWw+CjxodG1sPgogIDxoZWFkPgogICAgPHRpdGxlPl9fcHJvamVjdE5hbWVf XzwvdGl0bGU+CiAgICA8bWV0YSBjaGFyc2V0PSJ1dGYtOCI+CiAgICA8bWV0YSBuYW1lPSJ2aWV3 cG9ydCIgY29udGVudD0id2lkdGg9ZGV2aWNlLXdpZHRoLCBpbml0aWFsLXNjYWxlPTEiPgogICAg PGxpbmsgcmVsPSJzdHlsZXNoZWV0IiBocmVmPSJzdHlsZXMuY3NzIj4KICAgIDxsaW5rIHJlbD0i aWNvbiIgdHlwZT0iaW1hZ2UvcG5nIiBocmVmPSJmYXZpY29uLnBuZyI+CiAgICA8c2NyaXB0IGRl ZmVyIHNyYz0ibWFpbi5kYXJ0LmpzIj48L3NjcmlwdD4KICA8L2hlYWQ+CiAgPGJvZHk+CiAgICA8 bXktYXBwPkxvYWRpbmcuLi48L215LWFwcD4KICA8L2JvZHk+CjwvaHRtbD4K''', 'web/main.dart', 'text', ''' aW1wb3J0ICdwYWNrYWdlOmFuZ3VsYXIvYW5ndWxhci5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOl9f cHJvamVjdE5hbWVfXy9hcHBfY29tcG9uZW50LnRlbXBsYXRlLmRhcnQnIGFzIG5nOwoKdm9pZCBt YWluKCkgewogIHJ1bkFwcChuZy5BcHBDb21wb25lbnROZ0ZhY3RvcnkpOwp9Cg==''', 'web/styles.css', 'text', ''' QGltcG9ydCB1cmwoaHR0cHM6Ly9mb250cy5nb29nbGVhcGlzLmNvbS9jc3M/ZmFtaWx5PVJvYm90 byk7CkBpbXBvcnQgdXJsKGh0dHBzOi8vZm9udHMuZ29vZ2xlYXBpcy5jb20vY3NzP2ZhbWlseT1N YXRlcmlhbCtJY29ucyk7Cgpib2R5IHsKICBtYXgtd2lkdGg6IDYwMHB4OwogIG1hcmdpbjogMCBh dXRvOwogIHBhZGRpbmc6IDV2dzsKfQoKKiB7CiAgZm9udC1mYW1pbHk6IFJvYm90bywgSGVsdmV0 aWNhLCBBcmlhbCwgc2Fucy1zZXJpZjsKfQo=''' ];
stagehand/lib/src/generators/web_angular.g.dart/0
{'file_path': 'stagehand/lib/src/generators/web_angular.g.dart', 'repo_id': 'stagehand', 'token_count': 9210}
name: __projectName__ description: A sample command-line application. # version: 1.0.0 # homepage: https://www.example.com environment: sdk: '>=2.8.1 <3.0.0' #dependencies: # path: ^1.7.0 dev_dependencies: pedantic: ^1.9.0 test: ^1.14.4
stagehand/templates/console-full/pubspec.yaml/0
{'file_path': 'stagehand/templates/console-full/pubspec.yaml', 'repo_id': 'stagehand', 'token_count': 106}
import 'package:__projectName__/__projectName__.dart'; import 'package:test/test.dart'; void main() { group('A group of tests', () { Awesome awesome; setUp(() { awesome = Awesome(); }); test('First Test', () { expect(awesome.isAwesome, isTrue); }); }); }
stagehand/templates/package-simple/test/__projectName___test.dart/0
{'file_path': 'stagehand/templates/package-simple/test/__projectName___test.dart', 'repo_id': 'stagehand', 'token_count': 116}
import 'package:json_annotation/json_annotation.dart'; import 'package:stream_chat/src/client.dart'; import 'package:stream_chat/src/models/channel_model.dart'; import 'package:stream_chat/src/models/channel_state.dart'; import 'package:stream_chat/src/models/device.dart'; import 'package:stream_chat/src/models/event.dart'; import 'package:stream_chat/src/models/member.dart'; import 'package:stream_chat/src/models/message.dart'; import 'package:stream_chat/src/models/reaction.dart'; import 'package:stream_chat/src/models/read.dart'; import 'package:stream_chat/src/models/user.dart'; part 'responses.g.dart'; class _BaseResponse { String duration; } /// Model response for [StreamChatClient.resync] api call @JsonSerializable(createToJson: false) class SyncResponse extends _BaseResponse { /// The list of events List<Event> events; /// Create a new instance from a json static SyncResponse fromJson(Map<String, dynamic> json) => _$SyncResponseFromJson(json); } /// Model response for [StreamChatClient.queryChannels] api call @JsonSerializable(createToJson: false) class QueryChannelsResponse extends _BaseResponse { /// List of channels state returned by the query List<ChannelState> channels; /// Create a new instance from a json static QueryChannelsResponse fromJson(Map<String, dynamic> json) => _$QueryChannelsResponseFromJson(json); } /// Model response for [StreamChatClient.queryChannels] api call @JsonSerializable(createToJson: false) class TranslateMessageResponse extends _BaseResponse { /// List of channels state returned by the query TranslatedMessage message; /// Create a new instance from a json static TranslateMessageResponse fromJson(Map<String, dynamic> json) => _$TranslateMessageResponseFromJson(json); } /// Model response for [StreamChatClient.queryChannels] api call @JsonSerializable(createToJson: false) class QueryMembersResponse extends _BaseResponse { /// List of channels state returned by the query List<Member> members; /// Create a new instance from a json static QueryMembersResponse fromJson(Map<String, dynamic> json) => _$QueryMembersResponseFromJson(json); } /// Model response for [StreamChatClient.queryUsers] api call @JsonSerializable(createToJson: false) class QueryUsersResponse extends _BaseResponse { /// List of users returned by the query List<User> users; /// Create a new instance from a json static QueryUsersResponse fromJson(Map<String, dynamic> json) => _$QueryUsersResponseFromJson(json); } /// Model response for [channel.getReactions] api call @JsonSerializable(createToJson: false) class QueryReactionsResponse extends _BaseResponse { /// List of reactions returned by the query List<Reaction> reactions; /// Create a new instance from a json static QueryReactionsResponse fromJson(Map<String, dynamic> json) => _$QueryReactionsResponseFromJson(json); } /// Model response for [Channel.getReplies] api call @JsonSerializable(createToJson: false) class QueryRepliesResponse extends _BaseResponse { /// List of messages returned by the api call List<Message> messages; /// Create a new instance from a json static QueryRepliesResponse fromJson(Map<String, dynamic> json) => _$QueryRepliesResponseFromJson(json); } /// Model response for [StreamChatClient.getDevices] api call @JsonSerializable(createToJson: false) class ListDevicesResponse extends _BaseResponse { /// List of user devices List<Device> devices; /// Create a new instance from a json static ListDevicesResponse fromJson(Map<String, dynamic> json) => _$ListDevicesResponseFromJson(json); } /// Model response for [Channel.sendFile] api call @JsonSerializable(createToJson: false) class SendFileResponse extends _BaseResponse { /// The url of the uploaded file String file; /// Create a new instance from a json static SendFileResponse fromJson(Map<String, dynamic> json) => _$SendFileResponseFromJson(json); } /// Model response for [Channel.sendImage] api call @JsonSerializable(createToJson: false) class SendImageResponse extends _BaseResponse { /// The url of the uploaded file String file; /// Create a new instance from a json static SendImageResponse fromJson(Map<String, dynamic> json) => _$SendImageResponseFromJson(json); } /// Model response for [Channel.sendReaction] api call @JsonSerializable(createToJson: false) class SendReactionResponse extends _BaseResponse { /// Message returned by the api call Message message; /// The reaction created by the api call Reaction reaction; /// Create a new instance from a json static SendReactionResponse fromJson(Map<String, dynamic> json) => _$SendReactionResponseFromJson(json); } /// Model response for [StreamChatClient.connectGuestUser] api call @JsonSerializable(createToJson: false) class ConnectGuestUserResponse extends _BaseResponse { /// Guest user access token String accessToken; /// Guest user User user; /// Create a new instance from a json static ConnectGuestUserResponse fromJson(Map<String, dynamic> json) => _$ConnectGuestUserResponseFromJson(json); } /// Model response for [StreamChatClient.updateUser] api call @JsonSerializable(createToJson: false) class UpdateUsersResponse extends _BaseResponse { /// Updated users Map<String, User> users; /// Create a new instance from a json static UpdateUsersResponse fromJson(Map<String, dynamic> json) => _$UpdateUsersResponseFromJson(json); } /// Model response for [StreamChatClient.updateMessage] api call @JsonSerializable(createToJson: false) class UpdateMessageResponse extends _BaseResponse { /// Message returned by the api call Message message; /// Create a new instance from a json static UpdateMessageResponse fromJson(Map<String, dynamic> json) => _$UpdateMessageResponseFromJson(json); } /// Model response for [Channel.sendMessage] api call @JsonSerializable(createToJson: false) class SendMessageResponse extends _BaseResponse { /// Message returned by the api call Message message; /// Create a new instance from a json static SendMessageResponse fromJson(Map<String, dynamic> json) => _$SendMessageResponseFromJson(json); } /// Model response for [StreamChatClient.getMessage] api call @JsonSerializable(createToJson: false) class GetMessageResponse extends _BaseResponse { /// Message returned by the api call Message message; /// Channel of the message ChannelModel channel; /// Create a new instance from a json static GetMessageResponse fromJson(Map<String, dynamic> json) { final res = _$GetMessageResponseFromJson(json); final jsonChannel = res.message?.extraData?.remove('channel'); if (jsonChannel != null) { res.channel = ChannelModel.fromJson(jsonChannel); } return res; } } /// Model response for [StreamChatClient.search] api call @JsonSerializable(createToJson: false) class SearchMessagesResponse extends _BaseResponse { /// List of messages returned by the api call List<GetMessageResponse> results; /// Create a new instance from a json static SearchMessagesResponse fromJson(Map<String, dynamic> json) => _$SearchMessagesResponseFromJson(json); } /// Model response for [Channel.getMessagesById] api call @JsonSerializable(createToJson: false) class GetMessagesByIdResponse extends _BaseResponse { /// Message returned by the api call List<Message> messages; /// Create a new instance from a json static GetMessagesByIdResponse fromJson(Map<String, dynamic> json) => _$GetMessagesByIdResponseFromJson(json); } /// Model response for [Channel.update] api call @JsonSerializable(createToJson: false) class UpdateChannelResponse extends _BaseResponse { /// Updated channel ChannelModel channel; /// Channel members List<Member> members; /// Message returned by the api call Message message; /// Create a new instance from a json static UpdateChannelResponse fromJson(Map<String, dynamic> json) => _$UpdateChannelResponseFromJson(json); } /// Model response for [Channel.updatePartial] api call @JsonSerializable(createToJson: false) class PartialUpdateChannelResponse extends _BaseResponse { /// Updated channel ChannelModel channel; /// Channel members List<Member> members; /// Create a new instance from a json static PartialUpdateChannelResponse fromJson(Map<String, dynamic> json) => _$PartialUpdateChannelResponseFromJson(json); } /// Model response for [Channel.inviteMembers] api call @JsonSerializable(createToJson: false) class InviteMembersResponse extends _BaseResponse { /// Updated channel ChannelModel channel; /// Channel members List<Member> members; /// Message returned by the api call Message message; /// Create a new instance from a json static InviteMembersResponse fromJson(Map<String, dynamic> json) => _$InviteMembersResponseFromJson(json); } /// Model response for [Channel.removeMembers] api call @JsonSerializable(createToJson: false) class RemoveMembersResponse extends _BaseResponse { /// Updated channel ChannelModel channel; /// Channel members List<Member> members; /// Message returned by the api call Message message; /// Create a new instance from a json static RemoveMembersResponse fromJson(Map<String, dynamic> json) => _$RemoveMembersResponseFromJson(json); } /// Model response for [Channel.sendAction] api call @JsonSerializable(createToJson: false) class SendActionResponse extends _BaseResponse { /// Message returned by the api call Message message; /// Create a new instance from a json static SendActionResponse fromJson(Map<String, dynamic> json) => _$SendActionResponseFromJson(json); } /// Model response for [Channel.addMembers] api call @JsonSerializable(createToJson: false) class AddMembersResponse extends _BaseResponse { /// Updated channel ChannelModel channel; /// Channel members List<Member> members; /// Message returned by the api call Message message; /// Create a new instance from a json static AddMembersResponse fromJson(Map<String, dynamic> json) => _$AddMembersResponseFromJson(json); } /// Model response for [Channel.acceptInvite] api call @JsonSerializable(createToJson: false) class AcceptInviteResponse extends _BaseResponse { /// Updated channel ChannelModel channel; /// Channel members List<Member> members; /// Message returned by the api call Message message; /// Create a new instance from a json static AcceptInviteResponse fromJson(Map<String, dynamic> json) => _$AcceptInviteResponseFromJson(json); } /// Model response for [Channel.rejectInvite] api call @JsonSerializable(createToJson: false) class RejectInviteResponse extends _BaseResponse { /// Updated channel ChannelModel channel; /// Channel members List<Member> members; /// Message returned by the api call Message message; /// Create a new instance from a json static RejectInviteResponse fromJson(Map<String, dynamic> json) => _$RejectInviteResponseFromJson(json); } /// Model response for empty responses @JsonSerializable(createToJson: false) class EmptyResponse extends _BaseResponse { /// Create a new instance from a json static EmptyResponse fromJson(Map<String, dynamic> json) => _$EmptyResponseFromJson(json); } /// Model response for [Channel.query] api call @JsonSerializable(createToJson: false) class ChannelStateResponse extends _BaseResponse { /// Updated channel ChannelModel channel; /// List of messages returned by the api call List<Message> messages; /// Channel members List<Member> members; /// Number of users watching the channel int watcherCount; /// List of read states List<Read> read; /// Create a new instance from a json static ChannelStateResponse fromJson(Map<String, dynamic> json) => _$ChannelStateResponseFromJson(json); }
stream-chat-flutter/packages/stream_chat/lib/src/api/responses.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat/lib/src/api/responses.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 3443}
import 'package:json_annotation/json_annotation.dart'; part 'action.g.dart'; /// The class that contains the information about an action @JsonSerializable() class Action { /// Constructor used for json serialization Action({this.name, this.style, this.text, this.type, this.value}); /// Create a new instance from a json factory Action.fromJson(Map<String, dynamic> json) => _$ActionFromJson(json); /// The name of the action final String name; /// The style of the action final String style; /// The test of the action final String text; /// The type of the action final String type; /// The value of the action final String value; /// Serialize to json Map<String, dynamic> toJson() => _$ActionToJson(this); }
stream-chat-flutter/packages/stream_chat/lib/src/models/action.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat/lib/src/models/action.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 224}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'device.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** Device _$DeviceFromJson(Map json) { return Device( id: json['id'] as String, pushProvider: json['push_provider'] as String, ); } Map<String, dynamic> _$DeviceToJson(Device instance) => <String, dynamic>{ 'id': instance.id, 'push_provider': instance.pushProvider, };
stream-chat-flutter/packages/stream_chat/lib/src/models/device.g.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat/lib/src/models/device.g.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 160}
import 'package:json_annotation/json_annotation.dart'; import 'package:stream_chat/src/models/serialization.dart'; part 'user.g.dart'; /// The class that defines the user model @JsonSerializable() class User { /// Constructor used for json serialization User({ this.id, this.role, this.createdAt, this.updatedAt, this.lastActive, this.online, this.extraData, this.banned, this.teams, }); /// Create a new instance from a json factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson( Serialization.moveToExtraDataFromRoot(json, topLevelFields)); /// Use this named constructor to create a new user instance User.init( this.id, { this.online, this.extraData, }) : createdAt = null, updatedAt = null, lastActive = null, banned = null, teams = null, role = null; /// Known top level fields. /// Useful for [Serialization] methods. static const topLevelFields = [ 'id', 'role', 'created_at', 'updated_at', 'last_active', 'online', 'banned', 'teams', ]; /// User id final String id; /// User role @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) final String role; /// User role @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) final List<String> teams; /// Date of user creation @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) final DateTime createdAt; /// Date of last user update @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) final DateTime updatedAt; /// Date of last user connection @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) final DateTime lastActive; /// True if user is online @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) final bool online; /// True if user is banned from the chat @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) final bool banned; /// Map of custom user extraData @JsonKey(includeIfNull: false) final Map<String, dynamic> extraData; @override int get hashCode => id.hashCode; /// Shortcut for user name String get name => (extraData?.containsKey('name') == true && extraData['name'] != '') ? extraData['name'] : id; @override bool operator ==(Object other) => identical(this, other) || other is User && runtimeType == other.runtimeType && id == other.id; /// Serialize to json Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot(_$UserToJson(this), topLevelFields); }
stream-chat-flutter/packages/stream_chat/lib/src/models/user.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat/lib/src/models/user.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 935}
import 'dart:convert'; import 'package:test/test.dart'; import 'package:stream_chat/src/models/action.dart'; void main() { group('src/models/action', () { const jsonExample = r'''{ "name": "name", "style": "style", "text": "text", "type": "type", "value": "value" }'''; test('should parse json correctly', () { final action = Action.fromJson(json.decode(jsonExample)); expect(action.name, 'name'); expect(action.style, 'style'); expect(action.text, 'text'); expect(action.type, 'type'); expect(action.value, 'value'); }); test('should serialize to json correctly', () { final action = Action( name: 'name', style: 'style', text: 'text', type: 'type', value: 'value', ); expect( action.toJson(), { 'name': 'name', 'style': 'style', 'text': 'text', 'type': 'type', 'value': 'value', }, ); }); }); }
stream-chat-flutter/packages/stream_chat/test/src/models/action_test.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat/test/src/models/action_test.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 478}
import 'package:flutter/material.dart'; import '../stream_chat_flutter.dart'; import 'channel_info.dart'; import 'option_list_tile.dart'; class ChannelBottomSheet extends StatefulWidget { final VoidCallback onViewInfoTap; ChannelBottomSheet({this.onViewInfoTap}); @override _ChannelBottomSheetState createState() => _ChannelBottomSheetState(); } class _ChannelBottomSheetState extends State<ChannelBottomSheet> { bool _showActions = true; @override Widget build(BuildContext context) { var channel = StreamChannel.of(context).channel; var members = channel.state.members; var userAsMember = members.firstWhere((e) => e.user.id == StreamChat.of(context).user.id); var isOwner = userAsMember.role == 'owner'; return Material( color: StreamChatTheme.of(context).colorTheme.white, clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0), ), ), child: !_showActions ? SizedBox() : ListView( shrinkWrap: true, children: [ SizedBox( height: 24.0, ), Center( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: ChannelName( textStyle: StreamChatTheme.of(context).textTheme.headlineBold, ), ), ), SizedBox( height: 5.0, ), Center( child: ChannelInfo( showTypingIndicator: false, channel: StreamChannel.of(context).channel, textStyle: StreamChatTheme.of(context) .channelPreviewTheme .subtitle, ), ), SizedBox( height: 17.0, ), if (channel.isDistinct && channel.memberCount == 2) Column( children: [ UserAvatar( user: members .firstWhere( (e) => e.user.id != userAsMember.user.id) .user, constraints: BoxConstraints( maxHeight: 64.0, maxWidth: 64.0, ), borderRadius: BorderRadius.circular(32.0), onlineIndicatorConstraints: BoxConstraints.tight(Size(12.0, 12.0)), ), SizedBox( height: 6.0, ), Text( members .firstWhere( (e) => e.user.id != userAsMember.user.id) .user .name, style: StreamChatTheme.of(context).textTheme.footnoteBold, maxLines: 1, overflow: TextOverflow.ellipsis, ), ], ), if (!(channel.isDistinct && channel.memberCount == 2)) Container( height: 94.0, alignment: Alignment.center, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: members.length, shrinkWrap: true, itemBuilder: (context, index) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: Column( children: [ UserAvatar( user: members[index].user, constraints: BoxConstraints.tightFor( height: 64.0, width: 64.0, ), borderRadius: BorderRadius.circular(32.0), onlineIndicatorConstraints: BoxConstraints.tight(Size(12.0, 12.0)), ), SizedBox( height: 6.0, ), Text( members[index].user.name, style: StreamChatTheme.of(context) .textTheme .footnoteBold, maxLines: 1, overflow: TextOverflow.ellipsis, ), ], ), ); }, ), ), SizedBox( height: 24.0, ), OptionListTile( leading: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: StreamSvgIcon.user( color: StreamChatTheme.of(context).colorTheme.grey, ), ), title: 'View Info', onTap: widget.onViewInfoTap, ), if (!channel.isDistinct) OptionListTile( leading: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: StreamSvgIcon.userRemove( color: StreamChatTheme.of(context).colorTheme.grey, ), ), title: 'Leave Group', onTap: () async { setState(() { _showActions = false; }); await _showLeaveDialog(); setState(() { _showActions = true; }); }, ), if (isOwner) OptionListTile( leading: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: StreamSvgIcon.delete( color: StreamChatTheme.of(context).colorTheme.accentRed, ), ), title: 'Delete Conversation', titleColor: StreamChatTheme.of(context).colorTheme.accentRed, onTap: () async { setState(() { _showActions = false; }); await _showDeleteDialog(); setState(() { _showActions = true; }); }, ), OptionListTile( leading: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: StreamSvgIcon.closeSmall( color: StreamChatTheme.of(context).colorTheme.grey, ), ), title: 'Cancel', onTap: () { Navigator.pop(context); }, ), ], ), ); } Future<void> _showDeleteDialog() async { final res = await showConfirmationDialog( context, title: 'Delete Conversation', okText: 'DELETE', question: 'Are you sure you want to delete this conversation?', cancelText: 'CANCEL', icon: StreamSvgIcon.delete( color: StreamChatTheme.of(context).colorTheme.accentRed, ), ); var channel = StreamChannel.of(context).channel; if (res == true) { await channel.delete(); Navigator.pop(context); } } Future<void> _showLeaveDialog() async { final res = await showConfirmationDialog( context, title: 'Leave conversation', okText: 'LEAVE', question: 'Are you sure you want to leave this conversation?', cancelText: 'CANCEL', icon: StreamSvgIcon.userRemove( color: StreamChatTheme.of(context).colorTheme.accentRed, ), ); if (res == true) { final channel = StreamChannel.of(context).channel; await channel.removeMembers([StreamChat.of(context).user.id]); Navigator.pop(context); } } }
stream-chat-flutter/packages/stream_chat_flutter/lib/src/channel_bottom_sheet.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/lib/src/channel_bottom_sheet.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 5550}
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import '../stream_chat_flutter.dart'; class GroupImage extends StatelessWidget { const GroupImage({ Key key, @required this.images, this.constraints, this.onTap, this.borderRadius, this.selected = false, this.selectionColor, this.selectionThickness = 4, }) : super(key: key); final List<String> images; final BoxConstraints constraints; final VoidCallback onTap; final bool selected; final BorderRadius borderRadius; final Color selectionColor; final double selectionThickness; @override Widget build(BuildContext context) { var avatar; final streamChatTheme = StreamChatTheme.of(context); avatar = GestureDetector( onTap: onTap, child: ClipRRect( borderRadius: borderRadius ?? StreamChatTheme.of(context) .ownMessageTheme .avatarTheme .borderRadius, child: Container( constraints: constraints ?? StreamChatTheme.of(context) .ownMessageTheme .avatarTheme .constraints, decoration: BoxDecoration( color: StreamChatTheme.of(context).colorTheme.accentBlue, ), child: Flex( direction: Axis.vertical, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Flexible( fit: FlexFit.tight, child: Flex( direction: Axis.horizontal, crossAxisAlignment: CrossAxisAlignment.stretch, children: images .take(2) .map((url) => Flexible( fit: FlexFit.tight, child: FittedBox( fit: BoxFit.cover, clipBehavior: Clip.antiAlias, child: Transform.scale( scale: 1.2, child: CachedNetworkImage( imageUrl: url, fit: BoxFit.cover, ), ), ), )) .toList(), ), ), if (images.length > 2) Flexible( fit: FlexFit.tight, child: Flex( direction: Axis.horizontal, crossAxisAlignment: CrossAxisAlignment.stretch, children: images .skip(2) .map((url) => Flexible( fit: FlexFit.tight, child: FittedBox( fit: BoxFit.cover, clipBehavior: Clip.antiAlias, child: Transform.scale( scale: 1.2, child: CachedNetworkImage( imageUrl: url, fit: BoxFit.cover, ), ), ), )) .toList(), ), ), ], ), ), ), ); if (selected) { avatar = ClipRRect( borderRadius: (borderRadius ?? streamChatTheme.ownMessageTheme.avatarTheme.borderRadius) + BorderRadius.circular(selectionThickness), child: Container( color: selectionColor ?? StreamChatTheme.of(context).colorTheme.accentBlue, height: 64.0, width: 64.0, child: Padding( padding: EdgeInsets.all(selectionThickness), child: avatar, ), ), ); } return avatar; } }
stream-chat-flutter/packages/stream_chat_flutter/lib/src/group_image.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/lib/src/group_image.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 2454}
import 'dart:math'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart'; import 'package:video_player/video_player.dart'; import 'attachment/attachment.dart'; import 'extension.dart'; import 'message_text.dart'; import 'stream_chat_theme.dart'; import 'user_avatar.dart'; import 'utils.dart'; typedef QuotedMessageAttachmentThumbnailBuilder = Widget Function( BuildContext, Attachment, ); class _VideoAttachmentThumbnail extends StatefulWidget { final Size size; final Attachment attachment; const _VideoAttachmentThumbnail({ Key key, @required this.attachment, this.size = const Size(32, 32), }) : super(key: key); @override _VideoAttachmentThumbnailState createState() => _VideoAttachmentThumbnailState(); } class _VideoAttachmentThumbnailState extends State<_VideoAttachmentThumbnail> { VideoPlayerController _controller; @override void initState() { super.initState(); _controller = VideoPlayerController.network(widget.attachment.assetUrl) ..initialize().then((_) { setState(() {}); //when your thumbnail will show. }); } @override void dispose() { super.dispose(); _controller.dispose(); } @override Widget build(BuildContext context) { return Container( height: widget.size.height, width: widget.size.width, child: _controller.value.isInitialized ? VideoPlayer(_controller) : CircularProgressIndicator()); } } /// class QuotedMessageWidget extends StatelessWidget { /// The message final Message message; /// The message theme final MessageTheme messageTheme; /// If true the widget will be mirrored final bool reverse; /// If true the message will show a grey border final bool showBorder; /// limit of the text message shown final int textLimit; /// Map that defines a thumbnail builder for an attachment type final Map<String, QuotedMessageAttachmentThumbnailBuilder> attachmentThumbnailBuilders; final EdgeInsetsGeometry padding; final GestureTapCallback onTap; /// QuotedMessageWidget({ Key key, @required this.message, @required this.messageTheme, this.reverse = false, this.showBorder = false, this.textLimit = 170, this.attachmentThumbnailBuilders, this.padding = const EdgeInsets.all(8), this.onTap, }) : super(key: key); bool get _hasAttachments => message.attachments?.isNotEmpty == true; bool get _containsScrapeUrl => message.attachments?.any((element) => element.ogScrapeUrl != null) == true; bool get _containsText => message?.text?.isNotEmpty == true; @override Widget build(BuildContext context) { return Padding( padding: padding, child: InkWell( onTap: onTap, child: Row( crossAxisAlignment: CrossAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: [ Flexible(child: _buildMessage(context)), SizedBox(width: 8), _buildUserAvatar(), ], ), ), ); } Widget _buildMessage(BuildContext context) { final isOnlyEmoji = message.text.isOnlyEmoji; var msg = _hasAttachments && !_containsText ? message.copyWith(text: message.attachments.last?.title ?? '') : message; if (msg.text.length > textLimit) { msg = msg.copyWith(text: '${msg.text.substring(0, textLimit - 3)}...'); } final children = [ if (_hasAttachments) _parseAttachments(context), if (msg.text.isNotEmpty) Flexible( child: Transform( transform: Matrix4.rotationY(reverse ? pi : 0), alignment: Alignment.center, child: MessageText( message: msg, messageTheme: isOnlyEmoji && _containsText ? messageTheme.copyWith( messageText: messageTheme.messageText.copyWith( fontSize: 32, )) : messageTheme.copyWith( messageText: messageTheme.messageText.copyWith( fontSize: 12, )), ), ), ), ].insertBetween(const SizedBox(width: 8)); return Container( decoration: BoxDecoration( color: _getBackgroundColor(context), border: showBorder ? Border.all( color: StreamChatTheme.of(context).colorTheme.greyGainsboro, ) : null, borderRadius: BorderRadius.only( topRight: Radius.circular(12), topLeft: Radius.circular(12), bottomLeft: Radius.circular(12), ), ), padding: const EdgeInsets.all(8), child: Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: reverse ? MainAxisAlignment.end : MainAxisAlignment.start, children: reverse ? children.reversed.toList() : children, ), ); } Widget _buildUrlAttachment(Attachment attachment) { final size = Size(32, 32); if (attachment.thumbUrl != null) { return Container( height: size.height, width: size.width, decoration: BoxDecoration( image: DecorationImage( fit: BoxFit.cover, image: CachedNetworkImageProvider( attachment.imageUrl, ), ), ), ); } return AttachmentError(size: size); } Widget _parseAttachments(BuildContext context) { Widget child; Attachment attachment; if (_containsScrapeUrl) { attachment = message.attachments.firstWhere( (element) => element.ogScrapeUrl != null, ); child = _buildUrlAttachment(attachment); } else { QuotedMessageAttachmentThumbnailBuilder attachmentBuilder; attachment = message.attachments.last; if (attachmentThumbnailBuilders?.containsKey(attachment?.type) == true) { attachmentBuilder = attachmentThumbnailBuilders[attachment?.type]; } attachmentBuilder = _defaultAttachmentBuilder[attachment?.type]; if (attachmentBuilder == null) { child = Offstage(); } child = attachmentBuilder(context, attachment); } child = AbsorbPointer(child: child); return Transform( transform: Matrix4.rotationY(reverse ? pi : 0), alignment: Alignment.center, child: Material( clipBehavior: Clip.antiAlias, type: MaterialType.transparency, shape: attachment.type == 'file' ? null : _getDefaultShape(context), child: child, ), ); } ShapeBorder _getDefaultShape(BuildContext context) { return RoundedRectangleBorder( side: BorderSide(width: 0.0, color: Colors.transparent), borderRadius: BorderRadius.circular(8), ); } Widget _buildUserAvatar() { return Transform( transform: Matrix4.rotationY(reverse ? pi : 0), alignment: Alignment.center, child: UserAvatar( user: message.user, constraints: BoxConstraints.tightFor( height: 24, width: 24, ), showOnlineStatus: false, ), ); } Map<String, QuotedMessageAttachmentThumbnailBuilder> get _defaultAttachmentBuilder { return { 'image': (_, attachment) { return ImageAttachment( attachment: attachment, message: message, messageTheme: messageTheme, size: Size(32, 32), ); }, 'video': (_, attachment) { return _VideoAttachmentThumbnail( key: ValueKey(attachment.assetUrl), attachment: attachment, ); }, 'giphy': (_, attachment) { final size = Size(32, 32); return CachedNetworkImage( height: size?.height, width: size?.width, placeholder: (_, __) { return Container( width: size?.width, height: size?.height, child: Center( child: CircularProgressIndicator(), ), ); }, imageUrl: attachment.thumbUrl ?? attachment.imageUrl ?? attachment.assetUrl, errorWidget: (context, url, error) { return AttachmentError(size: size); }, fit: BoxFit.cover, ); }, 'file': (_, attachment) { return Container( height: 32, width: 32, child: getFileTypeImage(attachment.extraData['mime_type']), ); }, }; } Color _getBackgroundColor(BuildContext context) { if (_containsScrapeUrl) { return StreamChatTheme.of(context).colorTheme.blueAlice; } return messageTheme.messageBackgroundColor; } }
stream-chat-flutter/packages/stream_chat_flutter/lib/src/quoted_message_widget.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/lib/src/quoted_message_widget.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 3749}
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart'; import '../stream_chat_flutter.dart'; class UserAvatar extends StatelessWidget { const UserAvatar({ Key key, @required this.user, this.constraints, this.onlineIndicatorConstraints, this.onTap, this.onLongPress, this.showOnlineStatus = true, this.borderRadius, this.onlineIndicatorAlignment = Alignment.topRight, this.selected = false, this.selectionColor, this.selectionThickness = 4, }) : super(key: key); final User user; final Alignment onlineIndicatorAlignment; final BoxConstraints constraints; final BorderRadius borderRadius; final BoxConstraints onlineIndicatorConstraints; final void Function(User) onTap; final void Function(User) onLongPress; final bool showOnlineStatus; final bool selected; final Color selectionColor; final double selectionThickness; @override Widget build(BuildContext context) { final hasImage = user.extraData?.containsKey('image') == true && user.extraData['image'] != null && user.extraData['image'] != ''; final streamChatTheme = StreamChatTheme.of(context); Widget avatar = FittedBox( fit: BoxFit.cover, child: ClipRRect( clipBehavior: Clip.antiAlias, borderRadius: borderRadius ?? streamChatTheme.ownMessageTheme.avatarTheme.borderRadius, child: Container( constraints: constraints ?? streamChatTheme.ownMessageTheme.avatarTheme.constraints, decoration: BoxDecoration( color: streamChatTheme.colorTheme.accentBlue, ), child: hasImage ? CachedNetworkImage( filterQuality: FilterQuality.high, imageUrl: user.extraData['image'], errorWidget: (_, __, ___) { return streamChatTheme.defaultUserImage(context, user); }, fit: BoxFit.cover, ) : streamChatTheme.defaultUserImage(context, user), ), ), ); if (selected) { avatar = ClipRRect( borderRadius: (borderRadius ?? streamChatTheme.ownMessageTheme.avatarTheme.borderRadius) + BorderRadius.circular(selectionThickness), child: Container( constraints: constraints ?? streamChatTheme.ownMessageTheme.avatarTheme.constraints, color: selectionColor ?? StreamChatTheme.of(context).colorTheme.accentBlue, child: Padding( padding: EdgeInsets.all(selectionThickness), child: avatar, ), ), ); } return GestureDetector( onTap: onTap != null ? () => onTap(user) : null, onLongPress: onLongPress != null ? () => onLongPress(user) : null, child: Stack( children: <Widget>[ avatar, if (showOnlineStatus && user.online == true) Positioned.fill( child: Align( alignment: onlineIndicatorAlignment, child: Material( type: MaterialType.circle, color: streamChatTheme.colorTheme.white, child: Container( margin: const EdgeInsets.all(2.0), constraints: onlineIndicatorConstraints ?? BoxConstraints.tightFor( width: 8, height: 8, ), child: Material( shape: CircleBorder(), color: streamChatTheme.colorTheme.accentGreen, ), ), ), ), ), ], ), ); } }
stream-chat-flutter/packages/stream_chat_flutter/lib/src/user_avatar.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/lib/src/user_avatar.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 1828}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'channel_query_dao.dart'; // ************************************************************************** // DaoGenerator // ************************************************************************** mixin _$ChannelQueryDaoMixin on DatabaseAccessor<MoorChatDatabase> { $ChannelQueriesTable get channelQueries => attachedDatabase.channelQueries; $ChannelsTable get channels => attachedDatabase.channels; $UsersTable get users => attachedDatabase.users; }
stream-chat-flutter/packages/stream_chat_persistence/lib/src/dao/channel_query_dao.g.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat_persistence/lib/src/dao/channel_query_dao.g.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 121}
import 'package:moor/moor.dart'; import 'package:stream_chat/stream_chat.dart'; import 'package:stream_chat_persistence/src/converter/converter.dart'; import 'package:stream_chat_persistence/src/dao/dao.dart'; import 'package:stream_chat_persistence/src/db/shared/shared_db.dart'; import 'package:stream_chat_persistence/src/entity/entity.dart'; part 'moor_chat_database.g.dart'; LazyDatabase _openConnection( String userId, { bool logStatements = false, bool persistOnDisk = true, }) => LazyDatabase(() async => SharedDB.constructDatabase( userId, logStatements: logStatements, persistOnDisk: persistOnDisk, )); /// A chat database implemented using moor @UseMoor(tables: [ Channels, Messages, PinnedMessages, Reactions, Users, Members, Reads, ChannelQueries, ConnectionEvents, ], daos: [ UserDao, ChannelDao, MessageDao, PinnedMessageDao, MemberDao, ReactionDao, ReadDao, ChannelQueryDao, ConnectionEventDao, ]) class MoorChatDatabase extends _$MoorChatDatabase { /// Creates a new moor chat database instance MoorChatDatabase( this._userId, { logStatements = false, bool persistOnDisk = true, }) : super(_openConnection( _userId, logStatements: logStatements, persistOnDisk: persistOnDisk, )); /// Instantiate a new database instance MoorChatDatabase.connect( this._userId, DatabaseConnection connection, ) : super.connect(connection); final String _userId; /// User id to which the database is connected String get userId => _userId; // you should bump this number whenever you change or add a table definition. @override int get schemaVersion => 2; @override MigrationStrategy get migration => MigrationStrategy( onUpgrade: (openingDetails, before, after) async { if (before != after) { final m = createMigrator(); for (final table in allTables) { await m.deleteTable(table.actualTableName); await m.createTable(table); } } }, ); /// Closes the database instance Future<void> disconnect() => close(); }
stream-chat-flutter/packages/stream_chat_persistence/lib/src/db/moor_chat_database.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat_persistence/lib/src/db/moor_chat_database.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 824}
import 'package:stream_chat/stream_chat.dart'; import 'package:stream_chat_persistence/src/db/moor_chat_database.dart'; /// Useful mapping functions for [ChannelEntity] extension ChannelEntityX on ChannelEntity { /// Maps a [ChannelEntity] into [ChannelModel] ChannelModel toChannelModel({User createdBy}) { final config = ChannelConfig.fromJson(this.config ?? {}); return ChannelModel( id: id, config: config, type: type, frozen: frozen, createdAt: createdAt, updatedAt: updatedAt, memberCount: memberCount, cid: cid, lastMessageAt: lastMessageAt, deletedAt: deletedAt, extraData: extraData, createdBy: createdBy, ); } /// Maps a [ChannelEntity] into [ChannelState] ChannelState toChannelState({ User createdBy, List<Member> members, List<Read> reads, List<Message> messages, List<Message> pinnedMessages, }) => ChannelState( members: members, read: reads, messages: messages, pinnedMessages: pinnedMessages, channel: toChannelModel(createdBy: createdBy), ); } /// Useful mapping functions for [ChannelModel] extension ChannelModelX on ChannelModel { /// Maps a [ChannelModel] into [ChannelEntity] ChannelEntity toEntity() => ChannelEntity( id: id, type: type, cid: cid, config: config.toJson(), frozen: frozen, lastMessageAt: lastMessageAt, createdAt: createdAt, updatedAt: updatedAt, deletedAt: deletedAt, memberCount: memberCount, createdById: createdBy.id, extraData: extraData, ); }
stream-chat-flutter/packages/stream_chat_persistence/lib/src/mapper/channel_mapper.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat_persistence/lib/src/mapper/channel_mapper.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 653}
import 'dart:async'; import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flutter/widgets.dart'; import 'package:super_dash/game/game.dart'; class PlayerControllerBehavior extends Behavior<Player> { @visibleForTesting bool doubleJumpUsed = false; double _jumpTimer = 0; @override FutureOr<void> onLoad() async { await super.onLoad(); parent.gameRef.addInputListener(_handleInput); } @override void onRemove() { super.onRemove(); parent.gameRef.removeInputListener(_handleInput); } void _handleInput() { if (parent.isDead || parent.isPlayerTeleporting || parent.isPlayerRespawning || parent.isGoingToGameOver) { return; } // Do nothing when there is a jump cool down if (_jumpTimer >= 0) { return; } // If is no walking, start walking if (!parent.walking) { parent.walking = true; return; } // If is walking, jump if (parent.walking && parent.isOnGround) { parent ..jumpEffects() ..jumping = true; _jumpTimer = 0.04; return; } // If is walking and double jump is enabled, double jump if (parent.walking && !parent.isOnGround && parent.hasGoldenFeather && !doubleJumpUsed) { parent ..doubleJumpEffects() ..jumping = true; _jumpTimer = 0.06; doubleJumpUsed = true; return; } } @override void update(double dt) { super.update(dt); if (parent.isDead && parent.jumping) { parent.jumping = false; } if (parent.isDead || parent.isPlayerTeleporting || parent.isGoingToGameOver) { return; } if (_jumpTimer >= 0) { _jumpTimer -= dt; if (_jumpTimer <= 0) { parent.jumping = false; } } if (_jumpTimer <= 0 && parent.isOnGround && parent.walking) { parent.setRunningState(); } if (doubleJumpUsed && parent.isOnGround) { doubleJumpUsed = false; } } }
super_dash/lib/game/behaviors/player_controller_behavior.dart/0
{'file_path': 'super_dash/lib/game/behaviors/player_controller_behavior.dart', 'repo_id': 'super_dash', 'token_count': 843}
export 'behaviors/behaviors.dart'; export 'bloc/game_bloc.dart'; export 'components/components.dart'; export 'entities/entities.dart'; export 'super_dash_game.dart'; export 'view/view.dart'; export 'widgets/widgets.dart';
super_dash/lib/game/game.dart/0
{'file_path': 'super_dash/lib/game/game.dart', 'repo_id': 'super_dash', 'token_count': 86}
import 'dart:ui'; import 'package:app_ui/app_ui.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:super_dash/constants/constants.dart'; import 'package:super_dash/gen/assets.gen.dart'; import 'package:super_dash/l10n/l10n.dart'; import 'package:url_launcher/url_launcher_string.dart'; class GameInfoDialog extends StatelessWidget { const GameInfoDialog({super.key}); static PageRoute<void> route() { return HeroDialogRoute( builder: (_) => BackdropFilter( filter: ImageFilter.blur(sigmaX: 8, sigmaY: 8), child: const GameInfoDialog(), ), ); } @override Widget build(BuildContext context) { final l10n = context.l10n; final bodyStyle = AppTextStyles.bodyLarge; const highlightColor = Color(0xFF9CECCD); final linkStyle = AppTextStyles.bodyLarge.copyWith( color: highlightColor, decoration: TextDecoration.underline, decorationColor: highlightColor, ); return AppDialog( border: Border.all(color: Colors.white24), child: Column( mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 24), Assets.images.gameLogo.image(width: 230), const SizedBox(height: 40), Padding( padding: const EdgeInsets.symmetric(horizontal: 32), child: Column( children: [ Text( l10n.aboutSuperDash, style: Theme.of(context).textTheme.headlineSmall, ), const SizedBox(height: 24), RichText( textAlign: TextAlign.center, text: TextSpan( style: bodyStyle, children: [ TextSpan(text: l10n.learn), TextSpan( text: l10n.howWeBuiltSuperDash, style: linkStyle, recognizer: TapGestureRecognizer() ..onTap = () => launchUrlString(Urls.howWeBuilt), ), TextSpan( text: l10n.inFlutterAndGrabThe, ), TextSpan( text: l10n.openSourceCode, style: linkStyle, recognizer: TapGestureRecognizer() ..onTap = () => launchUrlString(Urls.githubRepo), ), ], ), ), const SizedBox(height: 24), Text( l10n.otherLinks, style: bodyStyle, ), const SizedBox(height: 16), RichText( text: TextSpan( text: l10n.flutterGames, style: linkStyle, recognizer: TapGestureRecognizer() ..onTap = () => launchUrlString(Urls.flutterGames), ), ), RichText( text: TextSpan( text: l10n.privacyPolicy, style: linkStyle, recognizer: TapGestureRecognizer() ..onTap = () => launchUrlString(Urls.privacyPolicy), ), ), RichText( text: TextSpan( text: l10n.termsOfService, style: linkStyle, recognizer: TapGestureRecognizer() ..onTap = () => launchUrlString(Urls.termsOfService), ), ), ], ), ), const SizedBox(height: 40), ], ), ); } }
super_dash/lib/game_intro/view/game_info_dialog.dart/0
{'file_path': 'super_dash/lib/game_intro/view/game_info_dialog.dart', 'repo_id': 'super_dash', 'token_count': 2200}
export 'initials_form_view.dart'; export 'input_initials_page.dart';
super_dash/lib/score/input_initials/view/view.dart/0
{'file_path': 'super_dash/lib/score/input_initials/view/view.dart', 'repo_id': 'super_dash', 'token_count': 26}
import 'package:intl/intl.dart'; import 'package:share_plus/share_plus.dart'; import 'package:url_launcher/url_launcher_string.dart'; class ShareController { ShareController({required this.gameUrl}); final String gameUrl; String _postContent(int score) { final formatter = NumberFormat('#,###'); final scoreFormatted = formatter.format(score); return 'Seen the latest #FlutterGame? I scored $scoreFormatted on ' '#SuperDash. Can you beat my score?'; } String _twitterUrl(String content) => 'https://twitter.com/intent/tweet?text=$content $gameUrl'; String facebookUrl(String content) => 'https://www.facebook.com/sharer.php?u=$gameUrl'; String _encode(String content) => content.replaceAll(' ', '%20').replaceAll('#', '%23'); Future<bool> shareOnTwitter(int score) async { final content = _postContent(score); final url = _encode(_twitterUrl(content)); return launchUrlString(url); } Future<bool> shareOnFacebook(int score) async { final content = _postContent(score); final url = _encode(facebookUrl(content)); return launchUrlString(url); } Future<void> shareMobile(int score) async { final content = _postContent(score); await Share.share(content); } }
super_dash/lib/share/share.dart/0
{'file_path': 'super_dash/lib/share/share.dart', 'repo_id': 'super_dash', 'token_count': 428}
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; /// {@template app_dialog} /// A dialog with a close button in the top right corner. /// {@endtemplate} class AppDialog extends StatelessWidget { /// {@macro app_dialog} const AppDialog({ required this.child, this.showCloseButton = true, this.backgroundColor = const Color(0xE51B1B36), this.gradient = const LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [ Color.fromARGB(81, 177, 177, 177), Color.fromARGB(51, 54, 53, 103), Color.fromARGB(230, 27, 27, 54), ], stops: [0.05, 0.5, 1], ), this.borderRadius = const BorderRadius.all(Radius.circular(24)), this.border, this.imageProvider, super.key, }); /// The content of the dialog. final Widget child; /// Whether to show a close button in the top right corner. final bool showCloseButton; /// The background color of the dialog. Shown behind the [gradient]. final Color? backgroundColor; /// The gradient of the dialog. Shown on top of the [backgroundColor]. final LinearGradient? gradient; /// The border radius of the dialog. final BorderRadius borderRadius; /// The border of the dialog. final BoxBorder? border; /// The background image of the dialog. Setting the image makes the [gradient] /// and [backgroundColor] invisible. Also removes the border. final ImageProvider<Object>? imageProvider; @override Widget build(BuildContext context) { return Dialog( backgroundColor: Colors.transparent, elevation: 0, shape: RoundedRectangleBorder(borderRadius: borderRadius), child: AppCard( border: border, gradient: gradient, backgroundColor: backgroundColor, borderRadius: borderRadius, imageProvider: imageProvider, child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ if (showCloseButton) ...[ Row( mainAxisAlignment: MainAxisAlignment.end, children: [ GameIconButton( icon: Icons.close, onPressed: () => Navigator.of(context).pop(), ), ], ), ], child, ], ), ), ), ); } }
super_dash/packages/app_ui/lib/src/widgets/app_dialog.dart/0
{'file_path': 'super_dash/packages/app_ui/lib/src/widgets/app_dialog.dart', 'repo_id': 'super_dash', 'token_count': 1069}
import 'package:authentication_repository/authentication_repository.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('User', () { test('supports value equality', () { const userA = User(id: 'A'); const secondUserA = User(id: 'A'); const userB = User(id: 'B'); expect(userA, equals(secondUserA)); expect(userA, isNot(equals(userB))); }); }); }
super_dash/packages/authentication_repository/test/src/models/user_test.dart/0
{'file_path': 'super_dash/packages/authentication_repository/test/src/models/user_test.dart', 'repo_id': 'super_dash', 'token_count': 167}
// ignore_for_file: prefer_const_constructors import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:mocktail/mocktail.dart'; import 'package:super_dash/leaderboard/bloc/leaderboard_bloc.dart'; class _MockLeaderboardRepository extends Mock implements LeaderboardRepository {} class _FakeLeaderboardEntryData extends Fake implements LeaderboardEntryData {} void main() { group('LeaderboardBloc', () { late LeaderboardRepository leaderboardRepository; late LeaderboardEntryData leaderboardEntryData; setUp(() { leaderboardRepository = _MockLeaderboardRepository(); leaderboardEntryData = _FakeLeaderboardEntryData(); }); test( 'default state is LeaderboardInitial', () => expect( LeaderboardBloc(leaderboardRepository: leaderboardRepository).state, isA<LeaderboardInitial>(), ), ); blocTest<LeaderboardBloc, LeaderboardState>( 'emits [LeaderboardLoading, LeaderboardLoaded] ' 'when LeaderboardTop10Requested is added and repository returns data', setUp: () { when(leaderboardRepository.fetchTop10Leaderboard).thenAnswer( (_) async => [leaderboardEntryData], ); }, build: () => LeaderboardBloc( leaderboardRepository: leaderboardRepository, ), act: (bloc) => bloc.add(LeaderboardTop10Requested()), expect: () => [ LeaderboardLoading(), LeaderboardLoaded(entries: [leaderboardEntryData]), ], ); blocTest<LeaderboardBloc, LeaderboardState>( 'emits [LeaderboardLoading, LeaderboardError] ' 'when LeaderboardTop10Requested is added and repository fails', setUp: () { when( leaderboardRepository.fetchTop10Leaderboard, ).thenThrow(Exception()); }, build: () => LeaderboardBloc( leaderboardRepository: leaderboardRepository, ), act: (bloc) => bloc.add(LeaderboardTop10Requested()), expect: () => [ LeaderboardLoading(), LeaderboardError(), ], ); }); }
super_dash/test/leaderboard/bloc/leaderboard_bloc_test.dart/0
{'file_path': 'super_dash/test/leaderboard/bloc/leaderboard_bloc_test.dart', 'repo_id': 'super_dash', 'token_count': 818}
import 'package:flutter/material.dart'; class BuilderScreen extends StatelessWidget { const BuilderScreen({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Builder Screen')), body: Container( child: Text('TODO: builder...'), ), ); } }
super_flutter_maker/game/lib/screens/builder_screen/builder_screen.dart/0
{'file_path': 'super_flutter_maker/game/lib/screens/builder_screen/builder_screen.dart', 'repo_id': 'super_flutter_maker', 'token_count': 130}
name: sync_stream_controller version: 1.0.0 description: A custom stream controller that synchroneously send events, even on listening. homepage: https://github.com/rrousselGit/sync_stream_controller author: Remi Rousselet <darky12s@gmail.com> environment: sdk: ">=2.0.0 <3.0.0" dependencies: dev_dependencies: test: ^1.3.4
sync_stream_controller/pubspec.yaml/0
{'file_path': 'sync_stream_controller/pubspec.yaml', 'repo_id': 'sync_stream_controller', 'token_count': 119}
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart' as firebase; import 'package:firebase_crashlytics/firebase_crashlytics.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:meta/meta.dart'; import 'analytics.dart'; import 'auth.dart'; import 'cloud_db.dart'; import 'cloud_storage.dart'; import 'crashlytics.dart'; class Firebase { const Firebase._({ required this.db, required this.auth, required this.storage, required this.crashlytics, required this.analytics, }); static Future<Firebase> initialize({ required firebase.FirebaseOptions? options, required bool isAnalyticsEnabled, @visibleForTesting String? name, @visibleForTesting FirebaseAnalytics? analytics, @visibleForTesting FirebaseAuth? auth, @visibleForTesting FirebaseFirestore? firestore, @visibleForTesting FirebaseCrashlytics? crashlytics, @visibleForTesting GoogleSignIn? googleSignIn, }) async { await firebase.Firebase.initializeApp(name: name, options: options); // coverage:ignore-start, somehow no way to cover this line final FirebaseAnalytics firebaseAnalytics = analytics ?? FirebaseAnalytics.instance; // coverage:ignore-end await firebaseAnalytics.setAnalyticsCollectionEnabled(isAnalyticsEnabled); return Firebase._( db: CloudDb(firestore ?? FirebaseFirestore.instance), auth: Auth(auth ?? FirebaseAuth.instance, googleSignIn ?? GoogleSignIn()), storage: CloudStorage(FirebaseStorage.instance), crashlytics: Crashlytics(crashlytics ?? FirebaseCrashlytics.instance), analytics: CloudAnalytics(firebaseAnalytics), ); } final CloudDb db; final Auth auth; final CloudStorage storage; final Crashlytics crashlytics; final CloudAnalytics analytics; }
tailor_made/lib/data/network/firebase/firebase.dart/0
{'file_path': 'tailor_made/lib/data/network/firebase/firebase.dart', 'repo_id': 'tailor_made', 'token_count': 658}
typedef ImageFileReference = ({String src, String path});
tailor_made/lib/domain/entities/image_file_reference.dart/0
{'file_path': 'tailor_made/lib/domain/entities/image_file_reference.dart', 'repo_id': 'tailor_made', 'token_count': 15}
import 'package:tailor_made/domain.dart'; abstract class Measures { Stream<List<MeasureEntity>> fetchAll(String userId); Future<bool> create( List<BaseMeasureEntity> measures, String userId, { required MeasureGroup group, required String unit, }); Future<bool> deleteGroup(List<MeasureEntity> measures, String userId); Future<bool> deleteOne(ReferenceEntity reference); Future<bool> update(Iterable<BaseMeasureEntity> measures, String userId); Future<bool> updateOne( ReferenceEntity reference, { String? name, }); }
tailor_made/lib/domain/repositories/measures.dart/0
{'file_path': 'tailor_made/lib/domain/repositories/measures.dart', 'repo_id': 'tailor_made', 'token_count': 172}
import 'package:flutter/material.dart'; import 'package:tailor_made/presentation/widgets.dart'; import '../../../utils.dart'; class ContactsFilterButton extends StatelessWidget { const ContactsFilterButton({super.key, required this.sortType, required this.onTapSort}); final ContactsSortType sortType; final ValueSetter<ContactsSortType> onTapSort; @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final TextStyle optionTheme = theme.textTheme.bodyMedium!; final ColorScheme colorScheme = theme.colorScheme; final L10n l10n = context.l10n; return SizedBox.fromSize( size: const Size.square(48.0), child: Stack( children: <Widget>[ Positioned.fill( child: PopupMenuButton<ContactsSortType>( icon: const Icon(Icons.filter_list), onSelected: onTapSort, itemBuilder: (BuildContext context) => <_Option>[ for (final ContactsSortType item in ContactsSortType.values) _Option( enabled: sortType != item, style: optionTheme.copyWith(color: _colorTestFn(item, colorScheme)), text: item.caption(l10n), type: item, ), ], ), ), Align( alignment: const Alignment(0.75, -0.5), child: sortType != ContactsSortType.reset ? Dots(color: colorScheme.secondary) : null, ), ], ), ); } Color? _colorTestFn(ContactsSortType type, ColorScheme colorScheme) => sortType == type ? colorScheme.secondary : null; } class _Option extends PopupMenuItem<ContactsSortType> { _Option({ required super.enabled, required this.text, required this.type, required this.style, }) : super(value: type, child: Text(text, style: style)); final String text; final ContactsSortType type; final TextStyle style; } extension on ContactsSortType { String caption(L10n l10n) => switch (this) { ContactsSortType.recent => l10n.sortByJobsCaption, ContactsSortType.jobs => l10n.sortByNameCaption, ContactsSortType.completed => l10n.sortByCompletedCaption, ContactsSortType.pending => l10n.sortByPendingCaption, ContactsSortType.names => l10n.sortByRecentCaption, ContactsSortType.reset => l10n.noSortCaption, }; }
tailor_made/lib/presentation/screens/contacts/widgets/contacts_filter_button.dart/0
{'file_path': 'tailor_made/lib/presentation/screens/contacts/widgets/contacts_filter_button.dart', 'repo_id': 'tailor_made', 'token_count': 1044}
import 'package:flutter/material.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:tailor_made/presentation/theme.dart'; import '../../../utils.dart'; class OutDatedPage extends StatelessWidget { const OutDatedPage({super.key, required this.onUpdate}); final VoidCallback onUpdate; @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final TextStyle textTheme = theme.textTheme.bodyLarge!; final ColorScheme colorScheme = theme.colorScheme; final L10n l10n = context.l10n; return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: <Widget>[ SpinKitFadingCube(color: colorScheme.outlineVariant), const SizedBox(height: 48.0), Text( l10n.outOfDateTitle, style: textTheme.copyWith(color: Colors.black87, fontWeight: AppFontWeight.bold), textAlign: TextAlign.center, ), const SizedBox(height: 16.0), Padding( padding: const EdgeInsets.symmetric(horizontal: 64.0), child: Text( l10n.outOfDateMessage, style: textTheme.copyWith(color: colorScheme.outline), textAlign: TextAlign.center, ), ), const SizedBox(height: 32.0), ElevatedButton.icon( style: ElevatedButton.styleFrom( backgroundColor: colorScheme.secondary, shape: const StadiumBorder(), ), onPressed: onUpdate, icon: const Icon(Icons.get_app), label: Text(l10n.outOfDateUpdateCaption), ), ], ), ); } }
tailor_made/lib/presentation/screens/homepage/widgets/out_dated.dart/0
{'file_path': 'tailor_made/lib/presentation/screens/homepage/widgets/out_dated.dart', 'repo_id': 'tailor_made', 'token_count': 814}
import 'package:flutter/material.dart'; import 'package:tailor_made/presentation/widgets.dart'; import '../../../theme.dart'; import '../../../utils.dart'; class MeasureEditDialog extends StatefulWidget { const MeasureEditDialog({ super.key, required this.title, required this.value, }); final String title; final String value; @override State<MeasureEditDialog> createState() => _MeasureEditDialogState(); } class _MeasureEditDialogState extends State<MeasureEditDialog> { late final TextEditingController _controller = TextEditingController(text: widget.value); @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final ColorScheme colorScheme = theme.colorScheme; final L10n l10n = context.l10n; return Align( alignment: const FractionalOffset(0.0, 0.25), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 32.0), child: Material( borderRadius: BorderRadius.circular(4.0), child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ const SizedBox(height: 16.0), Center(child: Text(widget.title, style: theme.textTheme.bodySmallLight)), const SizedBox(height: 8.0), Padding( padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 16.0), child: TextField( textCapitalization: TextCapitalization.words, controller: _controller, onSubmitted: (_) => _handleSubmit(), ), ), const SizedBox(height: 4.0), Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ AppClearButton( onPressed: Navigator.of(context).pop, color: colorScheme.outline, child: Text(l10n.cancelCaption), ), const SizedBox(width: 16.0), AppClearButton(onPressed: _handleSubmit, child: Text(l10n.doneCaption)), const SizedBox(width: 16.0), ], ), const SizedBox(height: 8.0), ], ), ), ), ); } void _handleSubmit() { final String newValue = _controller.text.trim(); if (newValue.length > 1) { Navigator.of(context).pop(newValue); } } }
tailor_made/lib/presentation/screens/measures/widgets/measure_edit_dialog.dart/0
{'file_path': 'tailor_made/lib/presentation/screens/measures/widgets/measure_edit_dialog.dart', 'repo_id': 'tailor_made', 'token_count': 1178}
import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:tailor_made/domain.dart'; import 'account_provider.dart'; import 'registry_provider.dart'; import 'settings_provider.dart'; part 'account_notifier_provider.g.dart'; @Riverpod(dependencies: <Object>[registry, account, settings]) class AccountNotifier extends _$AccountNotifier { @override Future<AccountEntity> build() async => ref.watch(accountProvider.future); void updateStoreName(String name) async { final AccountEntity account = state.requireValue; await ref.read(registryProvider).get<Accounts>().updateAccount( account.uid, id: account.reference.id, path: account.reference.path, storeName: name, ); ref.invalidate(accountProvider); } void readNotice() async { final AccountEntity account = state.requireValue; await ref.read(registryProvider).get<Accounts>().updateAccount( account.uid, id: account.reference.id, path: account.reference.path, hasReadNotice: true, ); ref.invalidate(accountProvider); } void sendRating(int rating) async { final AccountEntity account = state.requireValue; await ref.read(registryProvider).get<Accounts>().updateAccount( account.uid, id: account.reference.id, path: account.reference.path, hasSendRating: true, rating: rating, ); ref.invalidate(accountProvider); } void premiumSetup() async { final SettingEntity settings = await ref.watch(settingsProvider.future); await ref.read(registryProvider).get<Accounts>().signUp( state.requireValue.copyWith( status: AccountStatus.pending, notice: settings.premiumNotice, hasReadNotice: false, hasPremiumEnabled: true, ), ); ref.invalidate(accountProvider); } }
tailor_made/lib/presentation/state/account_notifier_provider.dart/0
{'file_path': 'tailor_made/lib/presentation/state/account_notifier_provider.dart', 'repo_id': 'tailor_made', 'token_count': 749}
export 'widgets/app_back_button.dart'; export 'widgets/app_circle_avatar.dart'; export 'widgets/app_clear_button.dart'; export 'widgets/app_close_button.dart'; export 'widgets/app_crash_error_view.dart'; export 'widgets/app_icon.dart'; export 'widgets/custom_app_bar.dart'; export 'widgets/dots.dart'; export 'widgets/empty_result_view.dart'; export 'widgets/error_view.dart'; export 'widgets/form_section_header.dart'; export 'widgets/loading_spinner.dart'; export 'widgets/primary_button.dart'; export 'widgets/snackbar/app_snack_bar.dart'; export 'widgets/snackbar/snack_bar_provider.dart'; export 'widgets/touchable_opacity.dart'; export 'widgets/upload_photo.dart';
tailor_made/lib/presentation/widgets.dart/0
{'file_path': 'tailor_made/lib/presentation/widgets.dart', 'repo_id': 'tailor_made', 'token_count': 258}
export '';
talk-stream-backend/lib/chat/chat.dart/0
{'file_path': 'talk-stream-backend/lib/chat/chat.dart', 'repo_id': 'talk-stream-backend', 'token_count': 4}
export 'src/user_service.dart';
talk-stream-backend/packages/auth_data_source/lib/core/services/services.dart/0
{'file_path': 'talk-stream-backend/packages/auth_data_source/lib/core/services/services.dart', 'repo_id': 'talk-stream-backend', 'token_count': 12}
import 'package:chat_data_source/src/models/chat.dart'; import 'models/message.dart'; abstract class ChatDatasource { Future<List<Chat>> getChats(String userId); Future<Message> sendMessage(Message message); }
talk-stream-backend/packages/chat_data_source/lib/src/chat_data_source.dart/0
{'file_path': 'talk-stream-backend/packages/chat_data_source/lib/src/chat_data_source.dart', 'repo_id': 'talk-stream-backend', 'token_count': 71}
import 'package:get_it/get_it.dart'; import 'package:talk_stream/app/core/services/services.dart'; final locator = GetIt.instance; void setupLocator() { locator ..registerSingleton<HttpService>( HttpService( baseUrl: 'http://127.0.0.1:8080', ), ) ..registerSingleton<WebSocketService>( WebSocketService(), ) ..registerLazySingleton<GoRouterService>( GoRouterService.new, ); }
talk-stream/lib/app/core/locator.dart/0
{'file_path': 'talk-stream/lib/app/core/locator.dart', 'repo_id': 'talk-stream', 'token_count': 181}
import 'package:flutter/material.dart'; class ResponsiveView extends StatelessWidget { const ResponsiveView({ required this.mobileView, required this.webView, super.key, }); final Widget mobileView; final Widget webView; @override Widget build(BuildContext context) { return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { final screenWidth = constraints.maxWidth; return AnimatedSwitcher( duration: const Duration(milliseconds: 500), child: screenWidth < 600 ? mobileView : webView, transitionBuilder: (child, animation) { return ScaleTransition( scale: animation, child: child, ); }, ); }, ); } }
talk-stream/lib/app/view/widgets/responsive_view.dart/0
{'file_path': 'talk-stream/lib/app/view/widgets/responsive_view.dart', 'repo_id': 'talk-stream', 'token_count': 318}
// **Web Version** // *Still In Progres** import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:image_picker/image_picker.dart'; import 'package:talk_stream/app/src/constants/string_constant.dart'; import 'package:talk_stream/app/src/extensions/context_extensions.dart'; import 'package:talk_stream/app/view/widgets/custom_text_field.dart'; import 'package:talk_stream/app/view/widgets/margins/y_margin.dart'; import 'package:talk_stream/auth/auth.dart'; import 'package:talk_stream/auth/cubits/auth_cubit.dart'; class WebSignUpWidget extends StatefulWidget { const WebSignUpWidget({ required this.onSwitch, super.key, }); final VoidCallback onSwitch; @override State<WebSignUpWidget> createState() => _WebSignUpWidgetState(); } class _WebSignUpWidgetState extends State<WebSignUpWidget> { late TextEditingController _nameController; late TextEditingController _emailController; late TextEditingController _passwordController; late TextEditingController _usernameController; // ioHtml.File? _imageFile; final ImagePicker _picker = ImagePicker(); Uint8List? _pickedFileBytes; Future<void> _pickImage(ImageSource source) async { final pickedFile = await _picker.pickImage(source: source); if (pickedFile != null) { _pickedFileBytes = await pickedFile.readAsBytes(); setState(() { // _imageFile = ioHtml.File(pickedFile.path); }); } } @override void initState() { super.initState(); _emailController = TextEditingController(); _nameController = TextEditingController(); _usernameController = TextEditingController(); _passwordController = TextEditingController(); } @override Widget build(BuildContext context) { return BlocProvider( create: (context) => SignupCubit(), child: BlocListener<SignupCubit, SignupState>( listener: (context, state) async { if (state is SignupError) { context.showInAppNotifications( state.errorMessage, ); } }, child: SignUpView( widget.onSwitch, _pickImage, emailController: _emailController, nameController: _nameController, usernameController: _usernameController, passwordController: _passwordController, // imageFile: _imageFile, pickedFileBytes: _pickedFileBytes, ), ), ); } @override void dispose() { _nameController.dispose(); _emailController.dispose(); _passwordController.dispose(); super.dispose(); } } class SignUpView extends StatelessWidget { const SignUpView( this.onSwitch, this._pickImage, { required this.emailController, required this.nameController, required this.passwordController, required this.usernameController, required this.pickedFileBytes, super.key, }); final VoidCallback onSwitch; final void Function(ImageSource source) _pickImage; final TextEditingController nameController; final TextEditingController emailController; final TextEditingController passwordController; final TextEditingController usernameController; final Uint8List? pickedFileBytes; @override Widget build(BuildContext context) { final authCubit = context.read<AuthCubit>(); return Column( children: [ GestureDetector( onTap: () => _pickImage(ImageSource.gallery), child: CircleAvatar( radius: 50, backgroundColor: const Color(0xFF1F1F1F), backgroundImage: pickedFileBytes != null ? MemoryImage(pickedFileBytes!) : null, child: pickedFileBytes == null ? const Icon( Icons.person, size: 50, color: Colors.grey, ) : null, ), ), CustomTextField( label: AppString.username, icon: FontAwesomeIcons.user, hintText: AppString.enterUsername, controller: usernameController, ), const YMargin(24), CustomTextField( label: AppString.name, icon: FontAwesomeIcons.user, hintText: AppString.enterName, controller: nameController, ), const YMargin(24), CustomTextField( label: AppString.email, icon: FontAwesomeIcons.envelope, hintText: AppString.enterEmail, controller: emailController, ), const YMargin(24), CustomTextField( label: AppString.password, icon: FontAwesomeIcons.lock, hintText: AppString.enterPassword, controller: passwordController, obscureText: true, ), const SizedBox(height: 44), SizedBox( width: double.infinity, height: 48, child: BlocBuilder<SignupCubit, SignupState>( builder: (context, state) { return ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFF121212), ), onPressed: () async { if (pickedFileBytes == null) { context.showInAppNotifications( AppString.selectPicture, ); return; } await context.read<SignupCubit>().signup( User( email: emailController.text, name: nameController.text, password: passwordController.text, username: usernameController.text, profileImage: String.fromCharCodes(pickedFileBytes!), ), authCubit, ); // if (_formKey.currentState!.validate()) { // // submit the form // } }, child: state is SignupLoading ? const SizedBox( height: 18, width: 18, child: CircularProgressIndicator( valueColor: AlwaysStoppedAnimation(Colors.white), strokeWidth: 2, ), ) : const Text( AppString.signUp, style: TextStyle( fontWeight: FontWeight.w500, fontSize: 16, color: Colors.white, ), ), ); }, ), ), const YMargin(24), Center( child: TextButton( onPressed: onSwitch, child: RichText( text: TextSpan( text: 'Already have an account? ', style: GoogleFonts.dmSans( fontWeight: FontWeight.w400, fontSize: 14, color: const Color(0xFF121212), ), children: [ TextSpan( text: 'Login here.', style: GoogleFonts.dmSans( fontWeight: FontWeight.w500, fontSize: 14, color: const Color(0xFF121212), ), ), ], ), ), ), ) ], ); } }
talk-stream/lib/auth/view/widgets/web_sign_up_widget.dart/0
{'file_path': 'talk-stream/lib/auth/view/widgets/web_sign_up_widget.dart', 'repo_id': 'talk-stream', 'token_count': 3849}
import 'package:flutter/material.dart'; import 'package:talk_stream/app/view/widgets/responsive_view.dart'; import 'package:talk_stream/chat/view/mobile_chat_page.dart'; import 'package:talk_stream/chat/view/web_chat_page.dart'; class ChatPage extends StatelessWidget { const ChatPage({super.key}); @override Widget build(BuildContext context) { return const ChatView(); } } class ChatView extends StatelessWidget { const ChatView({super.key}); @override Widget build(BuildContext context) { return ResponsiveView( mobileView: MobileChatPage(), webView: const WebChatPage(), ); } }
talk-stream/lib/chat/view/chat_page.dart/0
{'file_path': 'talk-stream/lib/chat/view/chat_page.dart', 'repo_id': 'talk-stream', 'token_count': 212}
// ignore_for_file: public_member_api_docs, sort_constructors_first import 'dart:convert'; class ClientData { final String message; final Map<String, dynamic> data; final String? token; ClientData({ this.token, required this.message, required this.data, }); Map<String, dynamic> toMap() { return <String, dynamic>{ 'message': message, 'data': data, 'token': token, }; } factory ClientData.fromMap(Map<String, dynamic> map) { return ClientData( message: map['message'] as String, data: Map<String, dynamic>.from( map['data'] as Map<String, dynamic>, ), ); } String toJson() => json.encode(toMap()); factory ClientData.fromJson(String source) => ClientData.fromMap(json.decode(source) as Map<String, dynamic>); }
teamship-dart-frog/lib/data/models/client_data.dart/0
{'file_path': 'teamship-dart-frog/lib/data/models/client_data.dart', 'repo_id': 'teamship-dart-frog', 'token_count': 309}
name: team_ship_dart_frog description: An new Dart Frog application version: 1.0.0+1 publish_to: none environment: sdk: ">=2.18.0 <3.0.0" dependencies: dart_frog: ^0.2.0 dart_jsonwebtoken: ^2.4.2 dartz: ^0.10.1 equatable: ^2.0.5 github: ^9.5.0 json_serializable: ^6.5.3 mongo_dart: ^0.7.4+1 dev_dependencies: mocktail: ^0.3.0 test: ^1.19.2 very_good_analysis: ^3.1.0
teamship-dart-frog/pubspec.yaml/0
{'file_path': 'teamship-dart-frog/pubspec.yaml', 'repo_id': 'teamship-dart-frog', 'token_count': 194}
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // TODO Add doc about how failure strings work. import 'dart:async'; import 'package:test_api/hooks.dart'; import 'describe.dart'; /// A target for checking expectations against a value in a test. /// /// A Check my have a real value, in which case the expectations can be /// validated or rejected; or it may be a placeholder, in which case /// expectations describe what would be checked but cannot be rejected. /// /// Expectations are defined as extension methods specialized on the generic /// [T]. Expectations can use the [ContextExtension] to interact with the /// [Context] for this check. class Check<T> { final Context<T> _context; Check._(this._context); /// Mark the currently running test as skipped and return a [Check] that will /// ignore all expectations. /// /// Any expectations against the return value will not be checked and will not /// be included in the "Expected" or "Actual" string representations of a /// failure. /// /// ```dart /// checkThat(actual) /// ..stillChecked() /// ..skip('reason the expectation is temporarily not met').notChecked(); /// ``` /// /// If `skip` is used in a callback passed to `softCheck` or `describe` it /// will still mark the test as skipped, even though failing the expectation /// would not have otherwise caused the test to fail. Check<T> skip(String message) { TestHandle.current.markSkipped(message); return Check._(_SkippedContext()); } } /// Creates a [Check] that can be used to validate expectations against [value]. /// /// Expectations that are not satisfied throw a [TestFailure] to interrupt the /// currently running test and mark it as failed. /// /// If [because] is passed it will be included as a "Reason:" line in failure /// messages. /// /// ```dart /// checkThat(actual).equals(expected); /// ``` Check<T> checkThat<T>(T value, {String? because}) => Check._(_TestContext._( value: _Present(value), // TODO - switch between "a" and "an" label: 'a $T', reason: because, fail: (m, _) => throw TestFailure(m), allowAsync: true)); /// Checks whether [value] satisfies all expectations invoked in [condition]. /// /// Returns `null` if all expectations are satisfied, otherwise returns the /// [Rejection] for the first expectation that fails. /// /// Asynchronous expectations are not allowed in [condition] and will cause a /// runtime error if they are used. Rejection? softCheck<T>(T value, void Function(Check<T>) condition) { Rejection? rejection; final check = Check<T>._(_TestContext._( value: _Present(value), fail: (_, r) { rejection = r; }, allowAsync: false)); condition(check); return rejection; } /// Creates a description of the expectations checked by [condition]. /// /// The strings are individual lines of a description. /// The description of an expectation may be one or more adjacent lines. /// /// Matches the "Expected: " lines in the output of a failure message if a value /// did not meet the last expectation in [condition], without the first labeled /// line. Iterable<String> describe<T>(void Function(Check<T>) condition) { final context = _TestContext<T>._( value: _Absent(), fail: (_, __) { throw UnimplementedError(); }, allowAsync: false); condition(Check._(context)); return context.expected.skip(1); } extension ContextExtension<T> on Check<T> { /// The expectations and nesting context for this check. Context<T> get context => _context; } /// The expectation and nesting context already applied to a [Check]. /// /// This is the surface of interaction for expectation extension method /// implementations. /// /// The `expect` and `expectAsync` can test the value and optionally reject it. /// The `nest` and `nestAsync` can test the value, and also extract some other /// property from it for further checking. abstract class Context<T> { /// Expect that [predicate] will not return a [Rejection] for the checked /// value. /// /// The property that is asserted by this expectation is described by /// [clause]. Often this is a single statement like "equals <1>" or "is /// greater than 10", but it may be multiple lines such as describing that an /// Iterable contains an element meeting a complex expectation. If any element /// in the returned iterable contains a newline it may cause problems with /// indentation in the output. void expect( Iterable<String> Function() clause, Rejection? Function(T) predicate); /// Expect that [predicate] will not result in a [Rejection] for the checked /// value. /// /// The property that is asserted by this expectation is described by /// [clause]. Often this is a single statement like "equals <1>" or "is /// greater than 10", but it may be multiple lines such as describing that an /// Iterable contains an element meeting a complex expectation. If any element /// in the returned iterable contains a newline it may cause problems with /// indentation in the output. /// /// Some context may disallow asynchronous expectations, for instance in /// [softCheck] which must synchronously check the value. In those contexts /// this method will throw. Future<void> expectAsync<R>(Iterable<String> Function() clause, FutureOr<Rejection?> Function(T) predicate); /// Extract a property from the value for further checking. /// /// If the property cannot be extracted, [extract] should return an /// [Extracted.rejection] describing the problem. Otherwise it should return /// an [Extracted.value]. /// /// The [label] will be used preceding "that:" in a description. Expectations /// applied to the returned [Check] will follow the label, indented by two /// more spaces. /// /// If [atSameLevel] is true then [R] should be a subtype of [T], and a /// returned [Extracted.value] should be the same instance as passed value. /// This may be useful to refine the type for further checks. In this case the /// label is used like a single line "clause" passed to [expect], and /// expectations applied to the return [Check] will behave as if they were /// applied to the Check for this context. Check<R> nest<R>(String label, Extracted<R> Function(T) extract, {bool atSameLevel = false}); /// Extract an asynchronous property from the value for further checking. /// /// If the property cannot be extracted, [extract] should return an /// [Extracted.rejection] describing the problem. Otherwise it should return /// an [Extracted.value]. /// /// The [label] will be used preceding "that:" in a description. Expectations /// applied to the returned [Check] will follow the label, indented by two /// more spaces. /// /// Some context may disallow asynchronous expectations, for instance in /// [softCheck] which must synchronously check the value. In those contexts /// this method will throw. Future<Check<R>> nestAsync<R>( String label, FutureOr<Extracted<R>> Function(T) extract); } /// A property extracted from a value being checked, or a rejection. class Extracted<T> { final Rejection? rejection; final T? value; Extracted.rejection({required String actual, Iterable<String>? which}) : this.rejection = Rejection(actual: actual, which: which), this.value = null; Extracted.value(this.value) : this.rejection = null; Extracted._(this.rejection) : this.value = null; Extracted<R> _map<R>(R Function(T) transform) { if (rejection != null) return Extracted._(rejection); return Extracted.value(transform(value as T)); } } abstract class _Optional<T> { R? apply<R extends FutureOr<Rejection?>>(R Function(T) callback); Future<Extracted<_Optional<R>>> mapAsync<R>( FutureOr<Extracted<R>> Function(T) transform); Extracted<_Optional<R>> map<R>(Extracted<R> Function(T) transform); } class _Present<T> implements _Optional<T> { final T value; _Present(this.value); @override R? apply<R extends FutureOr<Rejection?>>(R Function(T) c) => c(value); @override Future<Extracted<_Present<R>>> mapAsync<R>( FutureOr<Extracted<R>> Function(T) transform) async { final transformed = await transform(value); return transformed._map((v) => _Present(v)); } @override Extracted<_Present<R>> map<R>(Extracted<R> Function(T) transform) => transform(value)._map((v) => _Present(v)); } class _Absent<T> implements _Optional<T> { @override R? apply<R extends FutureOr<Rejection?>>(R Function(T) c) => null; @override Future<Extracted<_Absent<R>>> mapAsync<R>( FutureOr<Extracted<R>> Function(T) transform) async => Extracted.value(_Absent<R>()); @override Extracted<_Absent<R>> map<R>(FutureOr<Extracted<R>> Function(T) transform) => Extracted.value(_Absent<R>()); } class _TestContext<T> implements Context<T>, _ClauseDescription { final _Optional<T> _value; final _TestContext<dynamic>? _parent; final List<_ClauseDescription> _clauses; final List<_TestContext> _aliases; // The "a value" in "a value that:". final String _label; final String? _reason; final void Function(String, Rejection?) _fail; final bool _allowAsync; _TestContext._({ required _Optional<T> value, required void Function(String, Rejection?) fail, required bool allowAsync, String? label, String? reason, }) : _value = value, _label = label ?? '', _reason = reason, _fail = fail, _allowAsync = allowAsync, _parent = null, _clauses = [], _aliases = []; _TestContext._alias(_TestContext original, this._value) : _parent = original._parent, _clauses = original._clauses, _aliases = original._aliases, _fail = original._fail, _allowAsync = original._allowAsync, // Properties that are never read from an aliased context _label = '', _reason = null; _TestContext._child(this._value, this._label, _TestContext<dynamic> parent) : _parent = parent, _fail = parent._fail, _allowAsync = parent._allowAsync, _clauses = [], _aliases = [], // Properties that are never read from any context other than root _reason = null; @override void expect( Iterable<String> Function() clause, Rejection? Function(T) predicate) { _clauses.add(_StringClause(clause)); final rejection = _value.apply(predicate); if (rejection != null) { _fail(_failure(rejection), rejection); } } @override Future<void> expectAsync<R>(Iterable<String> Function() clause, FutureOr<Rejection?> Function(T) predicate) async { if (!_allowAsync) { throw StateError( 'Async expectations cannot be used in a synchronous check'); } _clauses.add(_StringClause(clause)); final outstandingWork = TestHandle.current.markPending(); final rejection = await _value.apply(predicate); outstandingWork.complete(); if (rejection == null) return; _fail(_failure(rejection), rejection); } String _failure(Rejection rejection) { final root = _root; return [ ..._prefixFirst('Expected: ', root.expected), ..._prefixFirst('Actual: ', root.actual(rejection, this)), if (_reason != null) 'Reason: $_reason', ].join('\n'); } @override Check<R> nest<R>(String label, Extracted<R> Function(T) extract, {bool atSameLevel = false}) { final result = _value.map(extract); final rejection = result.rejection; if (rejection != null) { _clauses.add(_StringClause(() => [label])); _fail(_failure(rejection), rejection); } final value = result.value ?? _Absent<R>(); final _TestContext<R> context; if (atSameLevel) { context = _TestContext._alias(this, value); _aliases.add(context); _clauses.add(_StringClause(() => [label])); } else { context = _TestContext._child(value, label, this); _clauses.add(context); } return Check._(context); } @override Future<Check<R>> nestAsync<R>( String label, FutureOr<Extracted<R>> Function(T) extract) async { if (!_allowAsync) { throw StateError( 'Async expectations cannot be used in a synchronous check'); } final outstandingWork = TestHandle.current.markPending(); final result = await _value.mapAsync(extract); outstandingWork.complete(); final rejection = result.rejection; if (rejection != null) { _clauses.add(_StringClause(() => [label])); _fail(_failure(rejection), rejection); } // TODO - does this need null fallback instead? final value = result.value as _Optional<R>; final context = _TestContext<R>._child(value, label, this); _clauses.add(context); return Check._(context); } _TestContext get _root { _TestContext<dynamic> current = this; while (current._parent != null) { current = current._parent!; } return current; } @override Iterable<String> get expected { assert(_clauses.isNotEmpty); return [ '$_label that:', for (var clause in _clauses) ...indent(clause.expected), ]; } @override Iterable<String> actual(Rejection rejection, Context<dynamic> failedContext) { if (identical(failedContext, this) || _aliases.contains(failedContext)) { final which = rejection.which; return [ if (_parent != null) '$_label that:', '${_parent != null ? 'Actual: ' : ''}${rejection.actual}', if (which != null && which.isNotEmpty) ..._prefixFirst('Which: ', which) ]; } else { return [ '$_label that:', for (var clause in _clauses) ...indent(clause.actual(rejection, failedContext)) ]; } } } class _SkippedContext<T> implements Context<T> { @override void expect( Iterable<String> Function() clause, Rejection? Function(T) predicate) { // Ignore } @override Future<void> expectAsync<R>(Iterable<String> Function() clause, FutureOr<Rejection?> Function(T) predicate) async { // Ignore } @override Check<R> nest<R>(String label, Extracted<R> Function(T p1) extract, {bool atSameLevel = false}) { return Check._(_SkippedContext()); } @override Future<Check<R>> nestAsync<R>( String label, FutureOr<Extracted<R>> Function(T p1) extract) async { return Check._(_SkippedContext()); } } abstract class _ClauseDescription { Iterable<String> get expected; Iterable<String> actual(Rejection rejection, Context<dynamic> context); } class _StringClause implements _ClauseDescription { final Iterable<String> Function() _expected; @override Iterable<String> get expected => _expected(); _StringClause(this._expected); // Assumes this will never get called when it was this clause that failed // because the TestContext that fails never inspect it's clauses and just // prints the failed one. // TODO: better way to model this? @override Iterable<String> actual(Rejection rejection, Context<dynamic> context) => expected; } /// A description of a value that failed an expectation. class Rejection { /// A description of the actual value as it relates to the expectation. /// /// This may use [literal] to show a String representation of the value, or it /// may be a description of a specific aspect of the value. For instance an /// expectation that a Future completes to a value may describe the actual as /// "A Future that completes to an error". /// /// This is printed following an "Actual: " label in the output of a failure /// message. The message will be indented to the level of the expectation in /// the description, and printed following the descriptions of any /// expectations that have already passed. final String actual; /// A description of the way that [actual] failed to meet the expectation. /// /// An expectation can provide extra detail, or focus attention on a specific /// part of the value. For instance when comparing multiple elements in a /// collection, the rejection may describe that the value "has an unequal /// value at index 3". /// /// Lines should be separate values in the iterable, if any element contains a /// newline it may cause problems with indentation in the output. /// /// When provided, this is printed following a "Which: " label at the end of /// the output for the failure message. final Iterable<String>? which; Rejection({required this.actual, this.which}); } Iterable<String> _prefixFirst(String prefix, Iterable<String> lines) sync* { var isFirst = true; for (var line in lines) { if (isFirst) { yield '$prefix$line'; isFirst = false; } else { yield line; } } }
test/pkgs/checks/lib/src/checks.dart/0
{'file_path': 'test/pkgs/checks/lib/src/checks.dart', 'repo_id': 'test', 'token_count': 5449}
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library test.src.runner.browser.post_message_channel; import 'dart:js_util'; import 'package:js/js.dart'; import 'package:stream_channel/stream_channel.dart'; import 'dom.dart' as dom; // Avoid using this from dart:html to work around dart-lang/sdk#32113. @JS('window.parent.postMessage') external void _postParentMessage(Object message, String targetOrigin); /// Constructs a [StreamChannel] wrapping [MessageChannel] communication with /// the host page. StreamChannel<Object?> postMessageChannel() { var controller = StreamChannelController<Object?>(sync: true); // Listen for a message from the host that transfers a message port, then // cancel the subscription. This is important to prevent multiple // subscriptions if the test is ever hot restarted. late final dom.Subscription subscription; subscription = dom.Subscription(dom.window, 'message', allowInterop((dom.Event event) { // A message on the Window can theoretically come from any website. It's // very unlikely that a malicious site would care about hacking someone's // unit tests, let alone be able to find the test server while it's // running, but it's good practice to check the origin anyway. final message = event as dom.MessageEvent; if (message.origin == dom.window.location.origin && message.data == 'port') { subscription.cancel(); var port = message.ports.first; port.start(); var portSubscription = dom.Subscription(port, 'message', allowInterop((dom.Event event) { controller.local.sink.add((event as dom.MessageEvent).data); })); controller.local.stream.listen((data) { port.postMessage({'data': data}); }, onDone: () { port.postMessage({'event': 'done'}); portSubscription.cancel(); }); } })); // Send a ready message once we're listening so the host knows it's safe to // start sending events. // TODO(nweiz): Stop manually adding href here once issue 22554 is fixed. _postParentMessage( jsify({'href': dom.window.location.href, 'ready': true}) as Object, dom.window.location.origin); return controller.foreign; }
test/pkgs/test/lib/src/runner/browser/post_message_channel.dart/0
{'file_path': 'test/pkgs/test/lib/src/runner/browser/post_message_channel.dart', 'repo_id': 'test', 'token_count': 748}
name: test version: 1.21.6 description: >- A full featured library for writing and running Dart tests across platforms. repository: https://github.com/dart-lang/test/tree/master/pkgs/test environment: sdk: '>=2.18.0 <3.0.0' dependencies: analyzer: '>=2.0.0 <6.0.0' async: ^2.5.0 boolean_selector: ^2.1.0 collection: ^1.15.0 coverage: ^1.0.1 http_multi_server: ^3.0.0 io: ^1.0.0 js: ^0.6.4 node_preamble: ^2.0.0 package_config: ^2.0.0 path: ^1.8.0 pool: ^1.5.0 shelf: ^1.0.0 shelf_packages_handler: ^3.0.0 shelf_static: ^1.0.0 shelf_web_socket: ^1.0.0 source_span: ^1.8.0 stack_trace: ^1.10.0 stream_channel: ^2.1.0 typed_data: ^1.3.0 web_socket_channel: ^2.0.0 webkit_inspection_protocol: ^1.0.0 yaml: ^3.0.0 # Use an exact version until the test_api and test_core package are stable. test_api: 0.4.14 test_core: 0.4.18 dev_dependencies: fake_async: ^1.0.0 glob: ^2.0.0 lints: '>=1.0.0 <3.0.0' test_descriptor: ^2.0.0 test_process: ^2.0.0 dependency_overrides: test_core: path: ../test_core test_api: path: ../test_api
test/pkgs/test/pubspec.yaml/0
{'file_path': 'test/pkgs/test/pubspec.yaml', 'repo_id': 'test', 'token_count': 531}
// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. @TestOn('vm') import 'dart:convert'; import 'package:path/path.dart' as p; import 'package:test/test.dart'; import 'package:test_descriptor/test_descriptor.dart' as d; import '../../io.dart'; void main() { setUpAll(precompileTestExecutable); group('duplicate names', () { group('can be disabled for', () { for (var function in ['group', 'test']) { test('${function}s', () async { await d .file('dart_test.yaml', jsonEncode({'allow_duplicate_test_names': false})) .create(); var testName = 'test'; await d.file('test.dart', ''' import 'package:test/test.dart'; void main() { $function("$testName", () {}); $function("$testName", () {}); } ''').create(); var test = await runTest([ 'test.dart', '--configuration', p.join(d.sandbox, 'dart_test.yaml') ]); expect( test.stdout, emitsThrough(contains( 'A test with the name "$testName" was already declared.'))); await test.shouldExit(1); }); } }); group('are allowed by default for', () { for (var function in ['group', 'test']) { test('${function}s', () async { var testName = 'test'; await d.file('test.dart', ''' import 'package:test/test.dart'; void main() { $function("$testName", () {}); $function("$testName", () {}); // Needed so at least one test runs when testing groups. test('a test', () { expect(true, isTrue); }); } ''').create(); var test = await runTest( ['test.dart'], ); expect(test.stdout, emitsThrough(contains('All tests passed!'))); await test.shouldExit(0); }); } }); }); }
test/pkgs/test/test/runner/configuration/duplicate_names_test.dart/0
{'file_path': 'test/pkgs/test/test/runner/configuration/duplicate_names_test.dart', 'repo_id': 'test', 'token_count': 1055}
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. @TestOn('vm') import 'dart:async'; import 'package:path/path.dart' as p; import 'package:test/test.dart'; import 'package:test_descriptor/test_descriptor.dart' as d; import '../io.dart'; import 'json_reporter_utils.dart'; void main() { setUpAll(precompileTestExecutable); test('runs several successful tests and reports when each completes', () { return _expectReport(''' test('success 1', () {}); test('success 2', () {}); test('success 3', () {}); ''', [ [ suiteJson(0), testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 3), testStartJson(3, 'success 1', line: 6, column: 7), testDoneJson(3), testStartJson(4, 'success 2', line: 7, column: 7), testDoneJson(4), testStartJson(5, 'success 3', line: 8, column: 7), testDoneJson(5), ] ], doneJson()); }); test('runs several failing tests and reports when each fails', () { return _expectReport(''' test('failure 1', () => throw TestFailure('oh no')); test('failure 2', () => throw TestFailure('oh no')); test('failure 3', () => throw TestFailure('oh no')); ''', [ [ suiteJson(0), testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 3), testStartJson(3, 'failure 1', line: 6, column: 7), errorJson(3, 'oh no', isFailure: true), testDoneJson(3, result: 'failure'), testStartJson(4, 'failure 2', line: 7, column: 7), errorJson(4, 'oh no', isFailure: true), testDoneJson(4, result: 'failure'), testStartJson(5, 'failure 3', line: 8, column: 7), errorJson(5, 'oh no', isFailure: true), testDoneJson(5, result: 'failure'), ] ], doneJson(success: false)); }); test('includes the full stack trace with --verbose-trace', () async { await d.file('test.dart', ''' import 'dart:async'; import 'package:test/test.dart'; void main() { test("failure", () => throw "oh no"); } ''').create(); var test = await runTest(['--verbose-trace', 'test.dart'], reporter: 'json'); expect(test.stdout, emitsThrough(contains('dart:async'))); await test.shouldExit(1); }); test('runs failing tests along with successful tests', () { return _expectReport(''' test('failure 1', () => throw TestFailure('oh no')); test('success 1', () {}); test('failure 2', () => throw TestFailure('oh no')); test('success 2', () {}); ''', [ [ suiteJson(0), testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 4), testStartJson(3, 'failure 1', line: 6, column: 7), errorJson(3, 'oh no', isFailure: true), testDoneJson(3, result: 'failure'), testStartJson(4, 'success 1', line: 7, column: 7), testDoneJson(4), testStartJson(5, 'failure 2', line: 8, column: 7), errorJson(5, 'oh no', isFailure: true), testDoneJson(5, result: 'failure'), testStartJson(6, 'success 2', line: 9, column: 7), testDoneJson(6), ] ], doneJson(success: false)); }); test('gracefully handles multiple test failures in a row', () { return _expectReport(''' // This completer ensures that the test isolate isn't killed until all // errors have been thrown. var completer = Completer(); test('failures', () { Future.microtask(() => throw 'first error'); Future.microtask(() => throw 'second error'); Future.microtask(() => throw 'third error'); Future.microtask(completer.complete); }); test('wait', () => completer.future); ''', [ [ suiteJson(0), testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 2), testStartJson(3, 'failures', line: 9, column: 7), errorJson(3, 'first error'), errorJson(3, 'second error'), errorJson(3, 'third error'), testDoneJson(3, result: 'error'), testStartJson(4, 'wait', line: 15, column: 7), testDoneJson(4), ] ], doneJson(success: false)); }); test('gracefully handles a test failing after completion', () { return _expectReport(''' // These completers ensure that the first test won't fail until the second // one is running, and that the test isolate isn't killed until all errors // have been thrown. var waitStarted = Completer(); var testDone = Completer(); test('failure', () { waitStarted.future.then((_) { Future.microtask(testDone.complete); throw 'oh no'; }); }); test('wait', () { waitStarted.complete(); return testDone.future; }); ''', [ [ suiteJson(0), testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 2), testStartJson(3, 'failure', line: 11, column: 7), testDoneJson(3), testStartJson(4, 'wait', line: 17, column: 7), errorJson(3, 'oh no'), errorJson( 3, 'This test failed after it had already completed. Make sure to ' 'use [expectAsync]\n' 'or the [completes] matcher when testing async code.'), testDoneJson(4), ] ], doneJson(success: false)); }); test('reports each test in its proper groups', () { return _expectReport(''' group('group 1', () { group('.2', () { group('.3', () { test('success', () {}); }); }); test('success1', () {}); test('success2', () {}); }); ''', [ [ suiteJson(0), testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 3), groupJson(3, name: 'group 1', parentID: 2, testCount: 3, line: 6, column: 7), groupJson(4, name: 'group 1 .2', parentID: 3, line: 7, column: 9), groupJson(5, name: 'group 1 .2 .3', parentID: 4, line: 8, column: 11), testStartJson(6, 'group 1 .2 .3 success', groupIDs: [2, 3, 4, 5], line: 9, column: 13), testDoneJson(6), testStartJson(7, 'group 1 success1', groupIDs: [2, 3], line: 13, column: 9), testDoneJson(7), testStartJson(8, 'group 1 success2', groupIDs: [2, 3], line: 14, column: 9), testDoneJson(8), ] ], doneJson()); }); group('print:', () { test('handles multiple prints', () { return _expectReport(''' test('test', () { print("one"); print("two"); print("three"); print("four"); }); ''', [ [ suiteJson(0), testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ groupJson(2), testStartJson(3, 'test', line: 6, column: 9), printJson(3, 'one'), printJson(3, 'two'), printJson(3, 'three'), printJson(3, 'four'), testDoneJson(3), ] ], doneJson()); }); test('handles a print after the test completes', () { return _expectReport(''' // This completer ensures that the test isolate isn't killed until all // prints have happened. var testDone = Completer(); var waitStarted = Completer(); test('test', () async { waitStarted.future.then((_) { Future(() => print("one")); Future(() => print("two")); Future(() => print("three")); Future(() => print("four")); Future(testDone.complete); }); }); test('wait', () { waitStarted.complete(); return testDone.future; }); ''', [ [ suiteJson(0), testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 2), testStartJson(3, 'test', line: 10, column: 9), testDoneJson(3), testStartJson(4, 'wait', line: 20, column: 9), printJson(3, 'one'), printJson(3, 'two'), printJson(3, 'three'), printJson(3, 'four'), testDoneJson(4), ] ], doneJson()); }); test('interleaves prints and errors', () { return _expectReport(''' // This completer ensures that the test isolate isn't killed until all // prints have happened. var completer = Completer(); test('test', () { scheduleMicrotask(() { print("three"); print("four"); throw "second error"; }); scheduleMicrotask(() { print("five"); print("six"); completer.complete(); }); print("one"); print("two"); throw "first error"; }); test('wait', () => completer.future); ''', [ [ suiteJson(0), testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 2), testStartJson(3, 'test', line: 9, column: 9), printJson(3, 'one'), printJson(3, 'two'), errorJson(3, 'first error'), printJson(3, 'three'), printJson(3, 'four'), errorJson(3, 'second error'), printJson(3, 'five'), printJson(3, 'six'), testDoneJson(3, result: 'error'), testStartJson(4, 'wait', line: 27, column: 9), testDoneJson(4), ] ], doneJson(success: false)); }); }); group('skip:', () { test('reports skipped tests', () { return _expectReport(''' test('skip 1', () {}, skip: true); test('skip 2', () {}, skip: true); test('skip 3', () {}, skip: true); ''', [ [ suiteJson(0), testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 3), testStartJson(3, 'skip 1', skip: true, line: 6, column: 9), testDoneJson(3, skipped: true), testStartJson(4, 'skip 2', skip: true, line: 7, column: 9), testDoneJson(4, skipped: true), testStartJson(5, 'skip 3', skip: true, line: 8, column: 9), testDoneJson(5, skipped: true), ] ], doneJson()); }); test('reports skipped groups', () { return _expectReport(''' group('skip', () { test('success 1', () {}); test('success 2', () {}); test('success 3', () {}); }, skip: true); ''', [ [ suiteJson(0), testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 3), groupJson(3, name: 'skip', parentID: 2, skip: true, testCount: 3, line: 6, column: 9), testStartJson(4, 'skip success 1', groupIDs: [2, 3], skip: true, line: 7, column: 11), testDoneJson(4, skipped: true), testStartJson(5, 'skip success 2', groupIDs: [2, 3], skip: true, line: 8, column: 11), testDoneJson(5, skipped: true), testStartJson(6, 'skip success 3', groupIDs: [2, 3], skip: true, line: 9, column: 11), testDoneJson(6, skipped: true), ] ], doneJson()); }); test('reports the skip reason if available', () { return _expectReport(''' test('skip 1', () {}, skip: 'some reason'); test('skip 2', () {}, skip: 'or another'); ''', [ [ suiteJson(0), testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 2), testStartJson(3, 'skip 1', skip: 'some reason', line: 6, column: 9), printJson(3, 'Skip: some reason', type: 'skip'), testDoneJson(3, skipped: true), testStartJson(4, 'skip 2', skip: 'or another', line: 7, column: 9), printJson(4, 'Skip: or another', type: 'skip'), testDoneJson(4, skipped: true), ] ], doneJson()); }); test('runs skipped tests with --run-skipped', () { return _expectReport( ''' test('skip 1', () {}, skip: 'some reason'); test('skip 2', () {}, skip: 'or another'); ''', [ [ suiteJson(0), testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 2), testStartJson(3, 'skip 1', line: 6, column: 9), testDoneJson(3), testStartJson(4, 'skip 2', line: 7, column: 9), testDoneJson(4), ] ], doneJson(), args: ['--run-skipped']); }); }); group('reports line and column numbers for', () { test('the first call to setUpAll()', () { return _expectReport(''' setUpAll(() {}); setUpAll(() {}); setUpAll(() {}); test('success', () {}); ''', [ [ suiteJson(0), testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 1), testStartJson(3, '(setUpAll)', line: 6, column: 9), testDoneJson(3, hidden: true), testStartJson(4, 'success', line: 9, column: 9), testDoneJson(4), testStartJson(5, '(tearDownAll)'), testDoneJson(5, hidden: true), ] ], doneJson()); }); test('the first call to tearDownAll()', () { return _expectReport(''' tearDownAll(() {}); tearDownAll(() {}); tearDownAll(() {}); test('success', () {}); ''', [ [ testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ suiteJson(0), groupJson(2, testCount: 1), testStartJson(3, 'success', line: 9, column: 9), testDoneJson(3), testStartJson(4, '(tearDownAll)', line: 6, column: 9), testDoneJson(4, hidden: true), ] ], doneJson()); }); test('a test compiled to JS', () { return _expectReport( ''' test('success', () {}); ''', [ [ suiteJson(0, platform: 'chrome'), testStartJson(1, 'compiling test.dart', groupIDs: []), printJson( 1, isA<String>().having((s) => s.split('\n'), 'lines', contains(startsWith('Compiled')))), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 1), testStartJson(3, 'success', line: 6, column: 9), testDoneJson(3), ] ], doneJson(), args: ['-p', 'chrome']); }, tags: ['chrome'], skip: 'https://github.com/dart-lang/test/issues/872'); test('the root suite if applicable', () { return _expectReport( ''' customTest('success 1', () {}); test('success 2', () {}); ''', [ [ suiteJson(0), testStartJson(1, 'loading test.dart', groupIDs: []), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 2), testStartJson(3, 'success 1', line: 3, column: 60, url: p.toUri(p.join(d.sandbox, 'common.dart')).toString(), rootColumn: 7, rootLine: 7, rootUrl: p.toUri(p.join(d.sandbox, 'test.dart')).toString()), testDoneJson(3), testStartJson(4, 'success 2', line: 8, column: 7), testDoneJson(4), ] ], doneJson(), externalLibraries: { 'common.dart': ''' import 'package:test/test.dart'; void customTest(String name, dynamic Function() testFn) => test(name, testFn); ''', }); }); }); test( "doesn't report line and column information for a test compiled to JS " 'with --js-trace', () { return _expectReport( ''' test('success', () {}); ''', [ [ suiteJson(0, platform: 'chrome'), testStartJson(1, 'compiling test.dart', groupIDs: []), printJson( 1, isA<String>().having((s) => s.split('\n'), 'lines', contains(startsWith('Compiled')))), testDoneJson(1, hidden: true), ], [ groupJson(2, testCount: 1), testStartJson(3, 'success'), testDoneJson(3), ], ], doneJson(), args: ['-p', 'chrome', '--js-trace']); }, tags: ['chrome']); } /// Asserts that the tests defined by [tests] produce the JSON events in /// [expected]. /// /// If [externalLibraries] are provided it should be a map of relative file /// paths to contents. All libraries will be added as imports to the test, and /// files will be created for them. Future<void> _expectReport(String tests, List<List<Object /*Map|Matcher*/ >> expected, Map<Object, Object> done, {List<String> args = const [], Map<String, String> externalLibraries = const {}}) async { var testContent = StringBuffer(''' import 'dart:async'; import 'package:test/test.dart'; '''); for (var entry in externalLibraries.entries) { testContent.writeln("import '${entry.key}';"); await d.file(entry.key, entry.value).create(); } testContent ..writeln('void main() {') ..writeln(tests) ..writeln('}'); await d.file('test.dart', testContent.toString()).create(); var test = await runTest(['test.dart', '--chain-stack-traces', ...args], reporter: 'json'); await test.shouldExit(); var stdoutLines = await test.stdoutStream().toList(); return expectJsonReport(stdoutLines, test.pid, expected, done); }
test/pkgs/test/test/runner/json_reporter_test.dart/0
{'file_path': 'test/pkgs/test/test/runner/json_reporter_test.dart', 'repo_id': 'test', 'token_count': 9418}
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. @TestOn('vm') import 'package:test/test.dart'; import 'package:test_descriptor/test_descriptor.dart' as d; import '../io.dart'; void main() { setUpAll(precompileTestExecutable); group('a skipped expect', () { test('marks the test as skipped', () async { await d.file('test.dart', ''' import 'package:test/test.dart'; void main() { test("skipped", () => expect(1, equals(2), skip: true)); } ''').create(); var test = await runTest(['test.dart']); expect(test.stdout, emitsThrough(contains('~1: All tests skipped.'))); await test.shouldExit(0); }); test('prints the skip reason if there is one', () async { await d.file('test.dart', ''' import 'package:test/test.dart'; void main() { test("skipped", () => expect(1, equals(2), reason: "1 is 2", skip: "is failing")); } ''').create(); var test = await runTest(['test.dart']); expect( test.stdout, containsInOrder([ '+0: skipped', ' Skip expect: is failing', '~1: All tests skipped.' ])); await test.shouldExit(0); }); test("prints the expect reason if there's no skip reason", () async { await d.file('test.dart', ''' import 'package:test/test.dart'; void main() { test("skipped", () => expect(1, equals(2), reason: "1 is 2", skip: true)); } ''').create(); var test = await runTest(['test.dart']); expect( test.stdout, containsInOrder([ '+0: skipped', ' Skip expect (1 is 2).', '~1: All tests skipped.' ])); await test.shouldExit(0); }); test('prints the matcher description if there are no reasons', () async { await d.file('test.dart', ''' import 'package:test/test.dart'; void main() { test("skipped", () => expect(1, equals(2), skip: true)); } ''').create(); var test = await runTest(['test.dart']); expect( test.stdout, containsInOrder([ '+0: skipped', ' Skip expect (<2>).', '~1: All tests skipped.' ])); await test.shouldExit(0); }); test('still allows the test to fail', () async { await d.file('test.dart', ''' import 'package:test/test.dart'; void main() { test("failing", () { expect(1, equals(2), skip: true); expect(1, equals(2)); }); } ''').create(); var test = await runTest(['test.dart']); expect( test.stdout, containsInOrder([ '+0: failing', ' Skip expect (<2>).', '+0 -1: failing [E]', ' Expected: <2>', ' Actual: <1>', '+0 -1: Some tests failed.' ])); await test.shouldExit(1); }); }); group('markTestSkipped', () { test('prints the skip reason', () async { await d.file('test.dart', ''' import 'package:test/test.dart'; void main() { test('skipped', () { markTestSkipped('some reason'); }); } ''').create(); var test = await runTest(['test.dart']); expect( test.stdout, containsInOrder([ '+0: skipped', ' some reason', '~1: All tests skipped.', ])); await test.shouldExit(0); }); test('still allows the test to fail', () async { await d.file('test.dart', ''' import 'package:test/test.dart'; void main() { test('failing', () { markTestSkipped('some reason'); expect(1, equals(2)); }); } ''').create(); var test = await runTest(['test.dart']); expect( test.stdout, containsInOrder([ '+0: failing', ' some reason', '+0 -1: failing [E]', ' Expected: <2>', ' Actual: <1>', '+0 -1: Some tests failed.' ])); await test.shouldExit(1); }); test('error when called after the test succeeded', () async { await d.file('test.dart', ''' import 'dart:async'; import 'package:test/test.dart'; void main() { var skipCompleter = Completer(); var waitCompleter = Completer(); test('skip', () { skipCompleter.future.then((_) { waitCompleter.complete(); markTestSkipped('some reason'); }); }); // Trigger the skip completer in a following test to ensure that it // only fires after skip has completed successfully. test('wait', () async { skipCompleter.complete(); await waitCompleter.future; }); } ''').create(); var test = await runTest(['test.dart']); expect( test.stdout, containsInOrder([ '+0: skip', '+1: wait', '+0 -1: skip', 'This test was marked as skipped after it had already completed. ' 'Make sure to use', '[expectAsync] or the [completes] matcher when testing async code.', '+1 -1: Some tests failed.' ])); await test.shouldExit(1); }); }); group('errors', () { test('when called after the test succeeded', () async { await d.file('test.dart', ''' import 'dart:async'; import 'package:test/test.dart'; void main() { var skipCompleter = Completer(); var waitCompleter = Completer(); test("skip", () { skipCompleter.future.then((_) { waitCompleter.complete(); expect(1, equals(2), skip: true); }); }); // Trigger the skip completer in a following test to ensure that it // only fires after skip has completed successfully. test("wait", () async { skipCompleter.complete(); await waitCompleter.future; }); } ''').create(); var test = await runTest(['test.dart']); expect( test.stdout, containsInOrder([ '+0: skip', '+1: wait', '+0 -1: skip', 'This test was marked as skipped after it had already completed. ' 'Make sure to use', '[expectAsync] or the [completes] matcher when testing async code.', '+1 -1: Some tests failed.' ])); await test.shouldExit(1); }); test('when an invalid type is used for skip', () async { await d.file('test.dart', ''' import 'package:test/test.dart'; void main() { test("failing", () { expect(1, equals(2), skip: 10); }); } ''').create(); var test = await runTest(['test.dart']); expect( test.stdout, containsInOrder( ['Invalid argument (skip)', '+0 -1: Some tests failed.'])); await test.shouldExit(1); }); }); }
test/pkgs/test/test/runner/skip_expect_test.dart/0
{'file_path': 'test/pkgs/test/test/runner/skip_expect_test.dart', 'repo_id': 'test', 'token_count': 3658}
# Fold frames from helper packages we use in our tests, but not from test # itself. fold_stack_frames: except: - shelf_test_handler - stream_channel - test_descriptor - test_process presets: # "-P terse-trace" folds frames from test's implementation to make the output # less verbose when terse-trace: fold_stack_frames: except: [test] tags: browser: timeout: 2x # Browsers can sometimes randomly time out while starting, especially on # Travis which is pretty slow. Don't retry locally because it makes # debugging more annoying. presets: {travis: {retry: 3}} dart2js: add_tags: [browser] timeout: 2x firefox: {add_tags: [dart2js]} chrome: {add_tags: [dart2js]} phantomjs: {add_tags: [dart2js]} safari: add_tags: [dart2js] test_on: mac-os ie: add_tags: [dart2js] test_on: windows # Tests that run pub. These tests may need to be excluded when there are local # dependency_overrides. pub: timeout: 2x # Tests that use Node.js. These tests may need to be excluded on systems that # don't have Node installed. node: timeout: 2x
test/pkgs/test_api/dart_test.yaml/0
{'file_path': 'test/pkgs/test_api/dart_test.yaml', 'repo_id': 'test', 'token_count': 408}
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. 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:stack_trace/stack_trace.dart'; import 'closed_exception.dart'; import 'declarer.dart'; import 'group.dart'; import 'live_test.dart'; import 'live_test_controller.dart'; import 'message.dart'; import 'metadata.dart'; import 'state.dart'; import 'suite.dart'; import 'suite_platform.dart'; import 'test.dart'; import 'test_failure.dart'; import 'util/pretty_print.dart'; /// A test in this isolate. class LocalTest extends Test { @override final String name; @override final Metadata metadata; @override final Trace? trace; /// Whether this is a test defined using `setUpAll()` or `tearDownAll()`. final bool isScaffoldAll; /// The test body. final Function() _body; /// Whether the test is run in its own error zone. final bool _guarded; /// Creates a new [LocalTest]. /// /// If [guarded] is `true`, the test is run in its own error zone, and any /// errors that escape that zone cause the test to fail. If it's `false`, it's /// the caller's responsibility to invoke [LiveTest.run] in the context of a /// call to [Invoker.guard]. LocalTest(this.name, this.metadata, this._body, {this.trace, bool guarded = true, this.isScaffoldAll = false}) : _guarded = guarded; LocalTest._(this.name, this.metadata, this._body, this.trace, this._guarded, this.isScaffoldAll); /// Loads a single runnable instance of this test. @override LiveTest load(Suite suite, {Iterable<Group>? groups}) { var invoker = Invoker._(suite, this, groups: groups, guarded: _guarded); return invoker.liveTest; } @override Test? forPlatform(SuitePlatform platform) { if (!metadata.testOn.evaluate(platform)) return null; return LocalTest._(name, metadata.forPlatform(platform), _body, trace, _guarded, isScaffoldAll); } } /// The class responsible for managing the lifecycle of a single local test. /// /// The current invoker is accessible within the zone scope of the running test /// using [Invoker.current]. It's used to track asynchronous callbacks and /// report asynchronous errors. class Invoker { /// The live test being driven by the invoker. /// /// This provides a view into the state of the test being executed. LiveTest get liveTest => _controller; late final LiveTestController _controller; /// Whether to run this test in its own error zone. final bool _guarded; /// Whether the user code is allowed to interact with the invoker despite it /// being closed. /// /// A test is generally closed because the runner is shutting down (in /// response to a signal) or because the test's suite is finished. /// Typically calls to [addTearDown] and [addOutstandingCallback] are only /// allowed before the test is closed. Tear down callbacks, however, are /// allowed to perform these interactions to facilitate resource cleanup on a /// best-effort basis, so the invoker is made to appear open only within the /// zones running the teardown callbacks. bool get _forceOpen => Zone.current[_forceOpenForTearDownKey] as bool; /// An opaque object used as a key in the zone value map to identify /// [_forceOpen]. /// /// This is an instance variable to ensure that multiple invokers don't step /// on one anothers' toes. final _forceOpenForTearDownKey = Object(); /// Whether the test has been closed. /// /// Once the test is closed, [expect] and [expectAsync] will throw /// [ClosedException]s whenever accessed to help the test stop executing as /// soon as possible. bool get closed => !_forceOpen && _onCloseCompleter.isCompleted; /// A future that completes once the test has been closed. Future<void> get onClose => _onCloseCompleter.future; final _onCloseCompleter = Completer<void>(); /// The test being run. LocalTest get _test => liveTest.test as LocalTest; /// The outstanding callback counter for the current zone. _AsyncCounter get _outstandingCallbacks { var counter = Zone.current[_counterKey] as _AsyncCounter?; if (counter != null) return counter; throw StateError("Can't add or remove outstanding callbacks outside " 'of a test body.'); } /// All the zones created by [_waitForOutstandingCallbacks], in the order they /// were created. /// /// This is used to throw timeout errors in the most recent zone. final _outstandingCallbackZones = <Zone>[]; /// An opaque object used as a key in the zone value map to identify /// [_outstandingCallbacks]. /// /// This is an instance variable to ensure that multiple invokers don't step /// on one anothers' toes. final _counterKey = Object(); /// The number of times this [liveTest] has been run. int _runCount = 0; /// The current invoker, or `null` if none is defined. /// /// An invoker is only set within the zone scope of a running test. static Invoker? get current { // TODO(nweiz): Use a private symbol when dart2js supports it (issue 17526). return Zone.current[#test.invoker] as Invoker?; } /// Runs [callback] in a zone where unhandled errors from [LiveTest]s are /// caught and dispatched to the appropriate [Invoker]. static T? guard<T>(T Function() callback) => runZoned<T?>(callback, zoneSpecification: ZoneSpecification( // Use [handleUncaughtError] rather than [onError] so we can // capture [zone] and with it the outstanding callback counter for // the zone in which [error] was thrown. handleUncaughtError: (self, _, zone, error, stackTrace) { var invoker = zone[#test.invoker] as Invoker?; if (invoker != null) { self.parent!.run(() => invoker._handleError(zone, error, stackTrace)); } else { self.parent!.handleUncaughtError(error, stackTrace); } })); /// The timer for tracking timeouts. /// /// This will be `null` until the test starts running. Timer? _timeoutTimer; /// The tear-down functions to run when this test finishes. final _tearDowns = <Function()>[]; /// Messages to print if and when this test fails. final _printsOnFailure = <String>[]; Invoker._(Suite suite, LocalTest test, {Iterable<Group>? groups, bool guarded = true}) : _guarded = guarded { _controller = LiveTestController( suite, test, _onRun, _onCloseCompleter.complete, groups: groups); } /// Runs [callback] after this test completes. /// /// The [callback] may return a [Future]. Like all tear-downs, callbacks are /// run in the reverse of the order they're declared. void addTearDown(dynamic Function() callback) { if (closed) throw ClosedException(); if (_test.isScaffoldAll) { Declarer.current!.addTearDownAll(callback); } else { _tearDowns.add(callback); } } /// Tells the invoker that there's a callback running that it should wait for /// before considering the test successful. /// /// Each call to [addOutstandingCallback] should be followed by a call to /// [removeOutstandingCallback] once the callback is no longer running. Note /// that only successful tests wait for outstanding callbacks; as soon as a /// test experiences an error, any further calls to [addOutstandingCallback] /// or [removeOutstandingCallback] will do nothing. /// /// Throws a [ClosedException] if this test has been closed. void addOutstandingCallback() { if (closed) throw ClosedException(); _outstandingCallbacks.increment(); } /// Tells the invoker that a callback declared with [addOutstandingCallback] /// is no longer running. void removeOutstandingCallback() { heartbeat(); _outstandingCallbacks.decrement(); } /// Run [tearDowns] in reverse order. /// /// An exception thrown in a tearDown callback will cause the test to fail, if /// it isn't already failing, but it won't prevent the remaining callbacks /// from running. This invoker will not be closeable within the zone that the /// teardowns are running in. Future<void> runTearDowns(List<FutureOr<void> Function()> tearDowns) { heartbeat(); return runZoned(() async { while (tearDowns.isNotEmpty) { var completer = Completer(); addOutstandingCallback(); _waitForOutstandingCallbacks(() { Future.sync(tearDowns.removeLast()).whenComplete(completer.complete); }).then((_) => removeOutstandingCallback()).unawaited; await completer.future; } }, zoneValues: {_forceOpenForTearDownKey: true}); } /// Runs [fn] and completes once [fn] and all outstanding callbacks registered /// within [fn] have completed. /// /// Outstanding callbacks registered within [fn] will *not* be registered as /// outstanding callback outside of [fn]. Future<void> _waitForOutstandingCallbacks(FutureOr<void> Function() fn) { heartbeat(); Zone? zone; var counter = _AsyncCounter(); runZoned(() async { zone = Zone.current; _outstandingCallbackZones.add(zone!); await fn(); counter.decrement(); }, zoneValues: {_counterKey: counter}); return counter.onZero.whenComplete(() { _outstandingCallbackZones.remove(zone!); }); } /// Notifies the invoker that progress is being made. /// /// Each heartbeat resets the timeout timer. This helps ensure that /// long-running tests that still make progress don't time out. void heartbeat() { if (liveTest.isComplete) return; if (_timeoutTimer != null) _timeoutTimer!.cancel(); if (liveTest.suite.ignoreTimeouts == true) return; const defaultTimeout = Duration(seconds: 30); var timeout = liveTest.test.metadata.timeout.apply(defaultTimeout); if (timeout == null) return; String message() { var message = 'Test timed out after ${niceDuration(timeout)}.'; if (timeout == defaultTimeout) { message += ' See https://pub.dev/packages/test#timeouts'; } return message; } _timeoutTimer = Zone.root.createTimer(timeout, () { _outstandingCallbackZones.last.run(() { _handleError(Zone.current, TimeoutException(message(), timeout)); }); }); } /// Marks the current test as skipped. /// /// If passed, [message] is emitted as a skip message. /// /// Note that this *does not* mark the test as complete. That is, it sets /// the result to [Result.skipped], but doesn't change the state. void skip([String? message]) { if (liveTest.state.shouldBeDone) { // Set the state explicitly so we don't get an extra error about the test // failing after being complete. _controller.setState(const State(Status.complete, Result.error)); throw 'This test was marked as skipped after it had already completed. ' 'Make sure to use\n' '[expectAsync] or the [completes] matcher when testing async code.'; } if (message != null) _controller.message(Message.skip(message)); // TODO: error if the test is already complete. _controller.setState(const State(Status.pending, Result.skipped)); } /// Prints [message] if and when this test fails. void printOnFailure(String message) { message = message.trim(); if (liveTest.state.result.isFailing) { _print('\n$message'); } else { _printsOnFailure.add(message); } } /// Notifies the invoker of an asynchronous error. /// /// The [zone] is the zone in which the error was thrown. void _handleError(Zone zone, Object error, [StackTrace? stackTrace]) { // Ignore errors propagated from previous test runs if (_runCount != zone[#runCount]) return; // Get the chain information from the zone in which the error was thrown. zone.run(() { if (stackTrace == null) { stackTrace = Chain.current(); } else { stackTrace = Chain.forTrace(stackTrace!); } }); // Store these here because they'll change when we set the state below. var shouldBeDone = liveTest.state.shouldBeDone; if (error is! TestFailure) { _controller.setState(const State(Status.complete, Result.error)); } else if (liveTest.state.result != Result.error) { _controller.setState(const State(Status.complete, Result.failure)); } _controller.addError(error, stackTrace!); zone.run(() => _outstandingCallbacks.complete()); if (_printsOnFailure.isNotEmpty) { _print(_printsOnFailure.join('\n\n')); _printsOnFailure.clear(); } // If a test was supposed to be done but then had an error, that indicates // that it was poorly-written and could be flaky. if (!shouldBeDone) return; // However, users don't think of load tests as "tests", so the error isn't // helpful for them. if (liveTest.suite.isLoadSuite) return; _handleError( zone, 'This test failed after it had already completed. Make sure to use ' '[expectAsync]\n' 'or the [completes] matcher when testing async code.', stackTrace); } /// The method that's run when the test is started. void _onRun() { _controller.setState(const State(Status.running, Result.success)); _runCount++; Chain.capture(() { _guardIfGuarded(() { runZoned(() async { // Run the test asynchronously so that the "running" state change // has a chance to hit its event handler(s) before the test produces // an error. If an error is emitted before the first state change is // handled, we can end up with [onError] callbacks firing before the // corresponding [onStateChange], which violates the timing // guarantees. // // Use the event loop over the microtask queue to avoid starvation. await Future(() {}); await _waitForOutstandingCallbacks(_test._body); await _waitForOutstandingCallbacks(() => runTearDowns(_tearDowns)); if (_timeoutTimer != null) _timeoutTimer!.cancel(); if (liveTest.state.result != Result.success && _runCount < liveTest.test.metadata.retry + 1) { _controller.message(Message.print('Retry: ${liveTest.test.name}')); _onRun(); return; } _controller.setState(State(Status.complete, liveTest.state.result)); _controller.completer.complete(); }, zoneValues: { #test.invoker: this, _forceOpenForTearDownKey: false, #runCount: _runCount, }, zoneSpecification: ZoneSpecification(print: (_, __, ___, line) => _print(line))); }); }, when: liveTest.test.metadata.chainStackTraces, errorZone: false); } /// Runs [callback], in a [Invoker.guard] context if [_guarded] is `true`. void _guardIfGuarded(void Function() callback) { if (_guarded) { Invoker.guard(callback); } else { callback(); } } /// Prints [text] as a message to [_controller]. void _print(String text) => _controller.message(Message.print(text)); } /// A manually incremented/decremented counter that completes a [Future] the /// first time it reaches zero or is forcefully completed. class _AsyncCounter { var _count = 1; /// A Future that completes the first time the counter reaches 0. Future<void> get onZero => _completer.future; final _completer = Completer<void>(); void increment() { _count++; } void decrement() { _count--; if (_count != 0) return; if (_completer.isCompleted) return; _completer.complete(); } /// Force [onZero] to complete. /// /// No effect if [onZero] has already completed. void complete() { if (!_completer.isCompleted) _completer.complete(); } } extension<T> on Future<T> { void get unawaited {} }
test/pkgs/test_api/lib/src/backend/invoker.dart/0
{'file_path': 'test/pkgs/test_api/lib/src/backend/invoker.dart', 'repo_id': 'test', 'token_count': 5352}
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. 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:stack_trace/stack_trace.dart'; import 'group.dart'; import 'group_entry.dart'; import 'live_test.dart'; import 'metadata.dart'; import 'suite.dart'; import 'suite_platform.dart'; /// A single test. /// /// A test is immutable and stateless, which means that it can't be run /// directly. To run one, load a live version using [Test.load] and run it using /// [LiveTest.run]. abstract class Test implements GroupEntry { @override String get name; @override Metadata get metadata; @override Trace? get trace; /// Loads a live version of this test, which can be used to run it a single /// time. /// /// [suite] is the suite within which this test is being run. If [groups] is /// passed, it's the list of groups containing this test; otherwise, it /// defaults to just containing `suite.group`. LiveTest load(Suite suite, {Iterable<Group>? groups}); @override Test? forPlatform(SuitePlatform platform); @override Test? filter(bool Function(Test) callback) => callback(this) ? this : null; }
test/pkgs/test_api/lib/src/backend/test.dart/0
{'file_path': 'test/pkgs/test_api/lib/src/backend/test.dart', 'repo_id': 'test', 'token_count': 379}
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:test/test.dart'; import '../utils.dart'; void main() { group('returned Future from expectLater()', () { test('completes immediately for a sync matcher', () { expect(expectLater(true, isTrue), completes); }); test('contains the expect failure', () { expect(expectLater(Future.value(true), completion(isFalse)), throwsA(isTestFailure(anything))); }); test('contains an async error', () { expect(expectLater(Future.error('oh no'), completion(isFalse)), throwsA('oh no')); }); }); group('an async matcher that fails synchronously', () { test('throws synchronously', () { expect(() => expect(() {}, throws), throwsA(isTestFailure(anything))); }); test('can be used with synchronous operators', () { expect(() {}, isNot(throws)); }); }); }
test/pkgs/test_api/test/frontend/expect_test.dart/0
{'file_path': 'test/pkgs/test_api/test/frontend/expect_test.dart', 'repo_id': 'test', 'token_count': 368}
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. @Deprecated('package:test_core is not intended for general use. ' 'Please use package:test.') library test_core.backend; //ignore: deprecated_member_use export 'package:test_api/backend.dart' show Metadata, PlatformSelector, Runtime, SuitePlatform; export 'src/runner/configuration.dart' show Configuration; export 'src/runner/configuration/custom_runtime.dart' show CustomRuntime; export 'src/runner/configuration/runtime_settings.dart' show RuntimeSettings; export 'src/runner/parse_metadata.dart' show parseMetadata; export 'src/runner/suite.dart' show SuiteConfiguration;
test/pkgs/test_core/lib/backend.dart/0
{'file_path': 'test/pkgs/test_core/lib/backend.dart', 'repo_id': 'test', 'token_count': 232}
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. 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 'dart:math' as math; import 'package:glob/glob.dart'; /// The default number of test suites to run at once. /// /// This defaults to half the available processors, since presumably some of /// them will be used for the OS and other processes. final defaultConcurrency = math.max(1, Platform.numberOfProcessors ~/ 2); /// The default filename pattern. /// /// This is stored here so that we don't have to recompile it multiple times. final defaultFilename = Glob('*_test.dart');
test/pkgs/test_core/lib/src/runner/configuration/values.dart/0
{'file_path': 'test/pkgs/test_core/lib/src/runner/configuration/values.dart', 'repo_id': 'test', 'token_count': 197}
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. 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/utilities.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:path/path.dart' as p; import 'package:source_span/source_span.dart'; import 'package:test_api/scaffolding.dart' // ignore: deprecated_member_use show Timeout; import 'package:test_api/src/backend/metadata.dart'; // ignore: implementation_imports import 'package:test_api/src/backend/platform_selector.dart'; // ignore: implementation_imports import 'package:test_api/src/backend/util/identifier_regex.dart'; // ignore: implementation_imports import '../util/dart.dart'; import '../util/pair.dart'; /// Parse the test metadata for the test file at [path] with [contents]. /// /// The [platformVariables] are the set of variables that are valid for platform /// selectors in suite metadata, in addition to the built-in variables that are /// allowed everywhere. /// /// Throws an [AnalysisError] if parsing fails or a [FormatException] if the /// test annotations are incorrect. Metadata parseMetadata( String path, String contents, Set<String> platformVariables) => _Parser(path, contents, platformVariables).parse(); /// A parser for test suite metadata. class _Parser { /// The path to the test suite. final String _path; /// The set of variables that are valid for platform selectors, in addition to /// the built-in variables that are allowed everywhere. final Set<String> _platformVariables; /// All annotations at the top of the file. late final List<Annotation> _annotations; /// All prefixes defined by imports in this file. late final Set<String> _prefixes; /// The actual contents of the file. final String _contents; /// The language version override comment if one was present, otherwise null. String? _languageVersionComment; _Parser(this._path, this._contents, this._platformVariables) { var result = parseString(content: _contents, path: _path, throwIfDiagnostics: false); var directives = result.unit.directives; _annotations = directives.isEmpty ? [] : directives.first.metadata; _languageVersionComment = result.unit.languageVersionToken?.value(); // We explicitly *don't* just look for "package:test" imports here, // because it could be re-exported from another library. _prefixes = directives .map((directive) { if (directive is ImportDirective) { return directive.prefix?.name; } else { return null; } }) .whereType<String>() .toSet(); } /// Parses the metadata. Metadata parse() { Timeout? timeout; PlatformSelector? testOn; Object? /*String|bool*/ skip; Map<PlatformSelector, Metadata>? onPlatform; Set<String>? tags; int? retry; for (var annotation in _annotations) { var pair = _resolveConstructor(annotation.name, annotation.constructorName); var name = pair.first; var constructorName = pair.last; if (name == 'TestOn') { _assertSingle(testOn, 'TestOn', annotation); testOn = _parseTestOn(annotation); } else if (name == 'Timeout') { _assertSingle(timeout, 'Timeout', annotation); timeout = _parseTimeout(annotation, constructorName); } else if (name == 'Skip') { _assertSingle(skip, 'Skip', annotation); skip = _parseSkip(annotation); } else if (name == 'OnPlatform') { _assertSingle(onPlatform, 'OnPlatform', annotation); onPlatform = _parseOnPlatform(annotation); } else if (name == 'Tags') { _assertSingle(tags, 'Tags', annotation); tags = _parseTags(annotation); } else if (name == 'Retry') { retry = _parseRetry(annotation); } } return Metadata( testOn: testOn, timeout: timeout, skip: skip == null ? null : true, skipReason: skip is String ? skip : null, onPlatform: onPlatform, tags: tags, retry: retry, languageVersionComment: _languageVersionComment); } /// Parses a `@TestOn` annotation. /// /// [annotation] is the annotation. PlatformSelector _parseTestOn(Annotation annotation) => _parsePlatformSelector(annotation.arguments!.arguments.first); /// Parses an [expression] that should contain a string representing a /// [PlatformSelector]. PlatformSelector _parsePlatformSelector(Expression expression) { var literal = _parseString(expression); return _contextualize( literal, () => PlatformSelector.parse(literal.stringValue!) ..validate(_platformVariables)); } /// Parses a `@Retry` annotation. /// /// [annotation] is the annotation. int _parseRetry(Annotation annotation) => _parseInt(annotation.arguments!.arguments.first); /// Parses a `@Timeout` annotation. /// /// [annotation] is the annotation. [constructorName] is the name of the named /// constructor for the annotation, if any. Timeout _parseTimeout(Annotation annotation, String? constructorName) { if (constructorName == 'none') { return Timeout.none; } var args = annotation.arguments!.arguments; if (constructorName == null) return Timeout(_parseDuration(args.first)); return Timeout.factor(_parseNum(args.first)); } /// Parses a `Timeout` constructor. Timeout _parseTimeoutConstructor(Expression constructor) { var name = _findConstructorName(constructor, 'Timeout'); var arguments = _parseArguments(constructor); if (name == null) return Timeout(_parseDuration(arguments.first)); if (name == 'factor') return Timeout.factor(_parseNum(arguments.first)); throw SourceSpanFormatException('Invalid timeout', _spanFor(constructor)); } /// Parses a `@Skip` annotation. /// /// [annotation] is the annotation. /// /// Returns either `true` or a reason string. dynamic _parseSkip(Annotation annotation) { var args = annotation.arguments!.arguments; return args.isEmpty ? true : _parseString(args.first).stringValue; } /// Parses a `Skip` constructor. /// /// Returns either `true` or a reason string. dynamic _parseSkipConstructor(Expression constructor) { _findConstructorName(constructor, 'Skip'); var arguments = _parseArguments(constructor); return arguments.isEmpty ? true : _parseString(arguments.first).stringValue; } /// Parses a `@Tags` annotation. /// /// [annotation] is the annotation. Set<String> _parseTags(Annotation annotation) { return _parseList(annotation.arguments!.arguments.first) .map((tagExpression) { var name = _parseString(tagExpression).stringValue!; if (name.contains(anchoredHyphenatedIdentifier)) return name; throw SourceSpanFormatException( 'Invalid tag name. Tags must be (optionally hyphenated) Dart ' 'identifiers.', _spanFor(tagExpression)); }).toSet(); } /// Parses an `@OnPlatform` annotation. /// /// [annotation] is the annotation. Map<PlatformSelector, Metadata> _parseOnPlatform(Annotation annotation) { return _parseMap(annotation.arguments!.arguments.first, key: (key) { return _parsePlatformSelector(key); }, value: (value) { var expressions = <AstNode>[]; if (value is ListLiteral) { expressions = _parseList(value); } else if (value is InstanceCreationExpression || value is PrefixedIdentifier || value is MethodInvocation) { expressions = [value]; } else { throw SourceSpanFormatException( 'Expected a Timeout, Skip, or List of those.', _spanFor(value)); } Timeout? timeout; Object? skip; for (var expression in expressions) { if (expression is InstanceCreationExpression) { var className = _resolveConstructor( expression.constructorName.type.name, expression.constructorName.name) .first; if (className == 'Timeout') { _assertSingle(timeout, 'Timeout', expression); timeout = _parseTimeoutConstructor(expression); continue; } else if (className == 'Skip') { _assertSingle(skip, 'Skip', expression); skip = _parseSkipConstructor(expression); continue; } } else if (expression is PrefixedIdentifier && expression.prefix.name == 'Timeout') { if (expression.identifier.name != 'none') { throw SourceSpanFormatException( 'Undefined value.', _spanFor(expression)); } _assertSingle(timeout, 'Timeout', expression); timeout = Timeout.none; continue; } else if (expression is MethodInvocation) { var className = _typeNameFromMethodInvocation(expression, ['Timeout', 'Skip']); if (className == 'Timeout') { _assertSingle(timeout, 'Timeout', expression); timeout = _parseTimeoutConstructor(expression); continue; } else if (className == 'Skip') { _assertSingle(skip, 'Skip', expression); skip = _parseSkipConstructor(expression); continue; } } throw SourceSpanFormatException( 'Expected a Timeout or Skip.', _spanFor(expression)); } return Metadata.parse(timeout: timeout, skip: skip); }); } /// Parses a `const Duration` expression. Duration _parseDuration(Expression expression) { _findConstructorName(expression, 'Duration'); var arguments = _parseArguments(expression); var values = _parseNamedArguments(arguments) .map((key, value) => MapEntry(key, _parseInt(value))); return Duration( days: values['days'] ?? 0, hours: values['hours'] ?? 0, minutes: values['minutes'] ?? 0, seconds: values['seconds'] ?? 0, milliseconds: values['milliseconds'] ?? 0, microseconds: values['microseconds'] ?? 0); } Map<String, Expression> _parseNamedArguments( NodeList<Expression> arguments) => { for (var a in arguments.whereType<NamedExpression>()) a.name.label.name: a.expression }; /// Asserts that [existing] is null. /// /// [name] is the name of the annotation and [node] is its location, used for /// error reporting. void _assertSingle(Object? existing, String name, AstNode node) { if (existing == null) return; throw SourceSpanFormatException( 'Only a single $name may be used.', _spanFor(node)); } NodeList<Expression> _parseArguments(Expression expression) { if (expression is InstanceCreationExpression) { return expression.argumentList.arguments; } if (expression is MethodInvocation) { return expression.argumentList.arguments; } throw SourceSpanFormatException( 'Expected an instantiation', _spanFor(expression)); } /// Resolves a constructor name from its type [identifier] and its /// [constructorName]. /// /// Since the parsed file isn't fully resolved, this is necessary to /// disambiguate between prefixed names and named constructors. Pair<String, String?> _resolveConstructor( Identifier identifier, SimpleIdentifier? constructorName) { // The syntax is ambiguous between named constructors and prefixed // annotations, so we need to resolve that ambiguity using the known // prefixes. The analyzer parses "new x.y()" as prefix "x", annotation "y", // and named constructor null. It parses "new x.y.z()" as prefix "x", // annotation "y", and named constructor "z". String className; String? namedConstructor; if (identifier is PrefixedIdentifier && !_prefixes.contains(identifier.prefix.name) && constructorName == null) { className = identifier.prefix.name; namedConstructor = identifier.identifier.name; } else { className = identifier is PrefixedIdentifier ? identifier.identifier.name : identifier.name; if (constructorName != null) namedConstructor = constructorName.name; } return Pair(className, namedConstructor); } /// Parses a constructor invocation for [className]. /// /// Returns the name of the named constructor used, or null if the default /// constructor is used. /// If [expression] is not an instantiation of a [className] throws. String? _findConstructorName(Expression expression, String className) { if (expression is InstanceCreationExpression) { return _findConstructornameFromInstantiation(expression, className); } if (expression is MethodInvocation) { return _findConstructorNameFromMethod(expression, className); } throw SourceSpanFormatException( 'Expected a $className.', _spanFor(expression)); } String? _findConstructornameFromInstantiation( InstanceCreationExpression constructor, String className) { var pair = _resolveConstructor(constructor.constructorName.type.name, constructor.constructorName.name); var actualClassName = pair.first; var constructorName = pair.last; if (actualClassName != className) { throw SourceSpanFormatException( 'Expected a $className.', _spanFor(constructor)); } return constructorName; } String? _findConstructorNameFromMethod( MethodInvocation constructor, String className) { var target = constructor.target; if (target != null) { // target could be an import prefix or a different class. Assume that // named constructor on a different class won't match the class name we // are looking for. // Example: `test.Timeout()` if (constructor.methodName.name == className) return null; // target is an optionally prefixed class, method is named constructor // Examples: `Timeout.factor(2)`, `test.Timeout.factor(2)` String? parsedName; if (target is SimpleIdentifier) parsedName = target.name; if (target is PrefixedIdentifier) parsedName = target.identifier.name; if (parsedName != className) { throw SourceSpanFormatException( 'Expected a $className.', _spanFor(constructor)); } return constructor.methodName.name; } // No target, must be an unnamed constructor // Example `Timeout()` if (constructor.methodName.name != className) { throw SourceSpanFormatException( 'Expected a $className.', _spanFor(constructor)); } return null; } /// Returns a type from [candidates] that _may_ be a type instantiated by /// [constructor]. /// /// This can be fooled - for instance the invocation `foo.Bar()` may look like /// a prefixed instantiation of a `Bar` even though it is a named constructor /// instantiation of a `foo`, or a method invocation on a variable `foo`, or /// ... /// /// Similarly `Baz.another` may look like the named constructor invocation of /// a `Baz`even though it is a prefixed instantiation of an `another`, or a /// method invocation on a variable `Baz`, or ... String? _typeNameFromMethodInvocation( MethodInvocation constructor, List<String> candidates) { var methodName = constructor.methodName.name; // Examples: `Timeout()`, `test.Timeout()` if (candidates.contains(methodName)) return methodName; var target = constructor.target; // Example: `SomeOtherClass()` if (target == null) return null; if (target is SimpleIdentifier) { // Example: `Timeout.factor()` if (candidates.contains(target.name)) return target.name; } if (target is PrefixedIdentifier) { // Looks like `some_prefix.SomeTarget.someMethod` - "SomeTarget" is the // only potential type name. // Example: `test.Timeout.factor()` if (candidates.contains(target.identifier.name)) { return target.identifier.name; } } return null; } /// Parses a Map literal. /// /// By default, returns [Expression] keys and values. These can be overridden /// with the [key] and [value] parameters. Map<K, V> _parseMap<K, V>(Expression expression, {K Function(Expression)? key, V Function(Expression)? value}) { key ??= (expression) => expression as K; value ??= (expression) => expression as V; if (expression is! SetOrMapLiteral) { throw SourceSpanFormatException('Expected a Map.', _spanFor(expression)); } var map = <K, V>{}; for (var element in expression.elements) { if (element is MapLiteralEntry) { map[key(element.key)] = value(element.value); } else { throw SourceSpanFormatException( 'Expected a map entry.', _spanFor(element)); } } return map; } /// Parses a List literal. List<Expression> _parseList(Expression expression) { if (expression is! ListLiteral) { throw SourceSpanFormatException('Expected a List.', _spanFor(expression)); } var list = expression; return list.elements.map((e) { if (e is! Expression) { throw SourceSpanFormatException( 'Expected only literal elements.', _spanFor(e)); } return e; }).toList(); } /// Parses a constant number literal. num _parseNum(Expression expression) { if (expression is IntegerLiteral && expression.value != null) { return expression.value!; } if (expression is DoubleLiteral) return expression.value; throw SourceSpanFormatException('Expected a number.', _spanFor(expression)); } /// Parses a constant int literal. int _parseInt(Expression expression) { if (expression is IntegerLiteral && expression.value != null) { return expression.value!; } throw SourceSpanFormatException( 'Expected an integer.', _spanFor(expression)); } /// Parses a constant String literal. StringLiteral _parseString(Expression expression) { if (expression is StringLiteral && expression.stringValue != null) { return expression; } throw SourceSpanFormatException( 'Expected a String literal.', _spanFor(expression)); } /// Creates a [SourceSpan] for [node]. SourceSpan _spanFor(AstNode node) { // Load a SourceFile from scratch here since we're only ever going to emit // one error per file anyway. return SourceFile.fromString(_contents, url: p.toUri(_path)) .span(node.offset, node.end); } /// Runs [fn] and contextualizes any [SourceSpanFormatException]s that occur /// in it relative to [literal]. T _contextualize<T>(StringLiteral literal, T Function() fn) { try { return fn(); } on SourceSpanFormatException catch (error) { var file = SourceFile.fromString(_contents, url: p.toUri(_path)); var span = contextualizeSpan(error.span!, literal, file); if (span == null) rethrow; throw SourceSpanFormatException(error.message, span); } } }
test/pkgs/test_core/lib/src/runner/parse_metadata.dart/0
{'file_path': 'test/pkgs/test_core/lib/src/runner/parse_metadata.dart', 'repo_id': 'test', 'token_count': 6752}
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. 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:boolean_selector/boolean_selector.dart'; import 'package:collection/collection.dart'; import 'package:source_span/source_span.dart'; import 'package:test_api/scaffolding.dart' // ignore: deprecated_member_use show Timeout; import 'package:test_api/src/backend/metadata.dart'; // ignore: implementation_imports import 'package:test_api/src/backend/platform_selector.dart'; // ignore: implementation_imports import 'package:test_api/src/backend/runtime.dart'; // ignore: implementation_imports import 'package:test_api/src/backend/suite_platform.dart'; // ignore: implementation_imports import 'runtime_selection.dart'; /// Suite-level configuration. /// /// This tracks configuration that can differ from suite to suite. class SuiteConfiguration { /// Empty configuration with only default values. /// /// Using this is slightly more efficient than manually constructing a new /// configuration with no arguments. static final empty = SuiteConfiguration._( allowDuplicateTestNames: null, allowTestRandomization: null, jsTrace: null, runSkipped: null, dart2jsArgs: null, precompiledPath: null, patterns: null, runtimes: null, includeTags: null, excludeTags: null, tags: null, onPlatform: null, metadata: null, line: null, col: null, ignoreTimeouts: null); /// Whether or not duplicate test (or group) names are allowed within the same /// test suite. // // TODO: Change the default https://github.com/dart-lang/test/issues/1571 bool get allowDuplicateTestNames => _allowDuplicateTestNames ?? true; final bool? _allowDuplicateTestNames; /// Whether test randomization should be allowed for this test. bool get allowTestRandomization => _allowTestRandomization ?? true; final bool? _allowTestRandomization; /// Whether JavaScript stack traces should be left as-is or converted to /// Dart-like traces. bool get jsTrace => _jsTrace ?? false; final bool? _jsTrace; /// Whether skipped tests should be run. bool get runSkipped => _runSkipped ?? false; final bool? _runSkipped; /// The path to a mirror of this package containing HTML that points to /// precompiled JS. /// /// This is used by the internal Google test runner so that test compilation /// can more effectively make use of Google's build tools. final String? precompiledPath; /// Additional arguments to pass to dart2js. /// /// Note that this if multiple suites run the same JavaScript on different /// runtimes, and they have different [dart2jsArgs], only one (undefined) /// suite's arguments will be used. final List<String> dart2jsArgs; /// The patterns to match against test names to decide which to run. /// /// All patterns must match in order for a test to be run. /// /// If empty, all tests should be run. final Set<Pattern> patterns; /// The set of runtimes on which to run tests. List<String> get runtimes => _runtimes == null ? const ['vm'] : List.unmodifiable(_runtimes!.map((runtime) => runtime.name)); final List<RuntimeSelection>? _runtimes; /// Only run tests whose tags match this selector. /// /// When [merge]d, this is intersected with the other configuration's included /// tags. final BooleanSelector includeTags; /// Do not run tests whose tags match this selector. /// /// When [merge]d, this is unioned with the other configuration's /// excluded tags. final BooleanSelector excludeTags; /// Configuration for particular tags. /// /// The keys are tag selectors, and the values are configurations for tests /// whose tags match those selectors. final Map<BooleanSelector, SuiteConfiguration> tags; /// Configuration for particular platforms. /// /// The keys are platform selectors, and the values are configurations for /// those platforms. These configuration should only contain test-level /// configuration fields, but that isn't enforced. final Map<PlatformSelector, SuiteConfiguration> onPlatform; /// The global test metadata derived from this configuration. Metadata get metadata { if (tags.isEmpty && onPlatform.isEmpty) return _metadata; return _metadata.change( forTag: tags.map((key, config) => MapEntry(key, config.metadata)), onPlatform: onPlatform.map((key, config) => MapEntry(key, config.metadata))); } final Metadata _metadata; /// The set of tags that have been declared in any way in this configuration. late final Set<String> knownTags = UnmodifiableSetView({ ...includeTags.variables, ...excludeTags.variables, ..._metadata.tags, for (var selector in tags.keys) ...selector.variables, for (var configuration in tags.values) ...configuration.knownTags, for (var configuration in onPlatform.values) ...configuration.knownTags, }); /// Only run tests that originate from this line in a test file. final int? line; /// Only run tests that original from this column in a test file. final int? col; /// Whether or not timeouts should be ignored. final bool? _ignoreTimeouts; bool get ignoreTimeouts => _ignoreTimeouts ?? false; factory SuiteConfiguration( {required bool? allowDuplicateTestNames, required bool? allowTestRandomization, required bool? jsTrace, required bool? runSkipped, required Iterable<String>? dart2jsArgs, required String? precompiledPath, required Iterable<Pattern>? patterns, required Iterable<RuntimeSelection>? runtimes, required BooleanSelector? includeTags, required BooleanSelector? excludeTags, required Map<BooleanSelector, SuiteConfiguration>? tags, required Map<PlatformSelector, SuiteConfiguration>? onPlatform, required int? line, required int? col, required bool? ignoreTimeouts, // Test-level configuration required Timeout? timeout, required bool? verboseTrace, required bool? chainStackTraces, required bool? skip, required int? retry, required String? skipReason, required PlatformSelector? testOn, required Iterable<String>? addTags}) { var config = SuiteConfiguration._( allowDuplicateTestNames: allowDuplicateTestNames, allowTestRandomization: allowTestRandomization, jsTrace: jsTrace, runSkipped: runSkipped, dart2jsArgs: dart2jsArgs, precompiledPath: precompiledPath, patterns: patterns, runtimes: runtimes, includeTags: includeTags, excludeTags: excludeTags, tags: tags, onPlatform: onPlatform, line: line, col: col, ignoreTimeouts: ignoreTimeouts, metadata: Metadata( timeout: timeout, verboseTrace: verboseTrace, chainStackTraces: chainStackTraces, skip: skip, retry: retry, skipReason: skipReason, testOn: testOn, tags: addTags)); return config._resolveTags(); } /// A constructor that doesn't require all of its options to be passed. /// /// This should only be used in situations where you really only want to /// configure a specific restricted set of options. factory SuiteConfiguration._unsafe( {bool? allowDuplicateTestNames, bool? allowTestRandomization, bool? jsTrace, bool? runSkipped, Iterable<String>? dart2jsArgs, String? precompiledPath, Iterable<Pattern>? patterns, Iterable<RuntimeSelection>? runtimes, BooleanSelector? includeTags, BooleanSelector? excludeTags, Map<BooleanSelector, SuiteConfiguration>? tags, Map<PlatformSelector, SuiteConfiguration>? onPlatform, int? line, int? col, bool? ignoreTimeouts, // Test-level configuration Timeout? timeout, bool? verboseTrace, bool? chainStackTraces, bool? skip, int? retry, String? skipReason, PlatformSelector? testOn, Iterable<String>? addTags}) => SuiteConfiguration( allowDuplicateTestNames: allowDuplicateTestNames, allowTestRandomization: allowTestRandomization, jsTrace: jsTrace, runSkipped: runSkipped, dart2jsArgs: dart2jsArgs, precompiledPath: precompiledPath, patterns: patterns, runtimes: runtimes, includeTags: includeTags, excludeTags: excludeTags, tags: tags, onPlatform: onPlatform, line: line, col: col, ignoreTimeouts: ignoreTimeouts, timeout: timeout, verboseTrace: verboseTrace, chainStackTraces: chainStackTraces, skip: skip, retry: retry, skipReason: skipReason, testOn: testOn, addTags: addTags); /// A specialized constructor for only configuring the runtimes. factory SuiteConfiguration.runtimes(Iterable<RuntimeSelection> runtimes) => SuiteConfiguration._unsafe(runtimes: runtimes); /// A specialized constructor for only configuring runSkipped. factory SuiteConfiguration.runSkipped(bool runSkipped) => SuiteConfiguration._unsafe(runSkipped: runSkipped); /// A specialized constructor for only configuring the timeout. factory SuiteConfiguration.timeout(Timeout timeout) => SuiteConfiguration._unsafe(timeout: timeout); /// Creates new SuiteConfiguration. /// /// Unlike [SuiteConfiguration.new], this assumes [tags] is already /// resolved. SuiteConfiguration._({ required bool? allowDuplicateTestNames, required bool? allowTestRandomization, required bool? jsTrace, required bool? runSkipped, required Iterable<String>? dart2jsArgs, required this.precompiledPath, required Iterable<Pattern>? patterns, required Iterable<RuntimeSelection>? runtimes, required BooleanSelector? includeTags, required BooleanSelector? excludeTags, required Map<BooleanSelector, SuiteConfiguration>? tags, required Map<PlatformSelector, SuiteConfiguration>? onPlatform, required Metadata? metadata, required this.line, required this.col, required bool? ignoreTimeouts, }) : _allowDuplicateTestNames = allowDuplicateTestNames, _allowTestRandomization = allowTestRandomization, _jsTrace = jsTrace, _runSkipped = runSkipped, dart2jsArgs = _list(dart2jsArgs) ?? const [], patterns = UnmodifiableSetView(patterns?.toSet() ?? {}), _runtimes = _list(runtimes), includeTags = includeTags ?? BooleanSelector.all, excludeTags = excludeTags ?? BooleanSelector.none, tags = _map(tags), onPlatform = _map(onPlatform), _ignoreTimeouts = ignoreTimeouts, _metadata = metadata ?? Metadata.empty; /// Creates a new [SuiteConfiguration] that takes its configuration from /// [metadata]. factory SuiteConfiguration.fromMetadata(Metadata metadata) => SuiteConfiguration._( tags: metadata.forTag.map((key, child) => MapEntry(key, SuiteConfiguration.fromMetadata(child))), onPlatform: metadata.onPlatform.map((key, child) => MapEntry(key, SuiteConfiguration.fromMetadata(child))), metadata: metadata.change(forTag: {}, onPlatform: {}), allowDuplicateTestNames: null, allowTestRandomization: null, jsTrace: null, runSkipped: null, dart2jsArgs: null, precompiledPath: null, patterns: null, runtimes: null, includeTags: null, excludeTags: null, line: null, col: null, ignoreTimeouts: null, ); /// Returns an unmodifiable copy of [input]. /// /// If [input] is `null` or empty, this returns `null`. static List<T>? _list<T>(Iterable<T>? input) { if (input == null) return null; var list = List<T>.unmodifiable(input); if (list.isEmpty) return null; return list; } /// Returns an unmodifiable copy of [input] or an empty unmodifiable map. static Map<K, V> _map<K, V>(Map<K, V>? input) { if (input == null || input.isEmpty) return const <Never, Never>{}; return Map.unmodifiable(input); } /// Merges this with [other]. /// /// For most fields, if both configurations have values set, [other]'s value /// takes precedence. However, certain fields are merged together instead. /// This is indicated in those fields' documentation. SuiteConfiguration merge(SuiteConfiguration other) { if (this == SuiteConfiguration.empty) return other; if (other == SuiteConfiguration.empty) return this; var config = SuiteConfiguration._( allowDuplicateTestNames: other._allowDuplicateTestNames ?? _allowDuplicateTestNames, allowTestRandomization: other._allowTestRandomization ?? _allowTestRandomization, jsTrace: other._jsTrace ?? _jsTrace, runSkipped: other._runSkipped ?? _runSkipped, dart2jsArgs: dart2jsArgs.toList()..addAll(other.dart2jsArgs), precompiledPath: other.precompiledPath ?? precompiledPath, patterns: patterns.union(other.patterns), runtimes: other._runtimes ?? _runtimes, includeTags: includeTags.intersection(other.includeTags), excludeTags: excludeTags.union(other.excludeTags), tags: _mergeConfigMaps(tags, other.tags), onPlatform: _mergeConfigMaps(onPlatform, other.onPlatform), line: other.line ?? line, col: other.col ?? col, ignoreTimeouts: other._ignoreTimeouts ?? _ignoreTimeouts, metadata: metadata.merge(other.metadata)); return config._resolveTags(); } /// Returns a copy of this configuration with the given fields updated. /// /// Note that unlike [merge], this has no merging behavior—the old value is /// always replaced by the new one. SuiteConfiguration change( {bool? allowDuplicateTestNames, bool? allowTestRandomization, bool? jsTrace, bool? runSkipped, Iterable<String>? dart2jsArgs, String? precompiledPath, Iterable<Pattern>? patterns, Iterable<RuntimeSelection>? runtimes, BooleanSelector? includeTags, BooleanSelector? excludeTags, Map<BooleanSelector, SuiteConfiguration>? tags, Map<PlatformSelector, SuiteConfiguration>? onPlatform, int? line, int? col, bool? ignoreTimeouts, // Test-level configuration Timeout? timeout, bool? verboseTrace, bool? chainStackTraces, bool? skip, int? retry, String? skipReason, PlatformSelector? testOn, Iterable<String>? addTags}) { var config = SuiteConfiguration._( allowDuplicateTestNames: allowDuplicateTestNames ?? _allowDuplicateTestNames, allowTestRandomization: allowTestRandomization ?? _allowTestRandomization, jsTrace: jsTrace ?? _jsTrace, runSkipped: runSkipped ?? _runSkipped, dart2jsArgs: dart2jsArgs?.toList() ?? this.dart2jsArgs, precompiledPath: precompiledPath ?? this.precompiledPath, patterns: patterns ?? this.patterns, runtimes: runtimes ?? _runtimes, includeTags: includeTags ?? this.includeTags, excludeTags: excludeTags ?? this.excludeTags, tags: tags ?? this.tags, onPlatform: onPlatform ?? this.onPlatform, line: line ?? this.line, col: col ?? this.col, ignoreTimeouts: ignoreTimeouts ?? _ignoreTimeouts, metadata: _metadata.change( timeout: timeout, verboseTrace: verboseTrace, chainStackTraces: chainStackTraces, skip: skip, retry: retry, skipReason: skipReason, testOn: testOn, tags: addTags?.toSet())); return config._resolveTags(); } /// Throws a [FormatException] if this refers to any undefined runtimes. void validateRuntimes(List<Runtime> allRuntimes) { var validVariables = allRuntimes.map((runtime) => runtime.identifier).toSet(); _metadata.validatePlatformSelectors(validVariables); var runtimes = _runtimes; if (runtimes != null) { for (var selection in runtimes) { if (!allRuntimes .any((runtime) => runtime.identifier == selection.name)) { if (selection.span != null) { throw SourceSpanFormatException( 'Unknown platform "${selection.name}".', selection.span); } else { throw FormatException('Unknown platform "${selection.name}".'); } } } } onPlatform.forEach((selector, config) { selector.validate(validVariables); config.validateRuntimes(allRuntimes); }); } /// Returns a copy of this with all platform-specific configuration from /// [onPlatform] resolved. SuiteConfiguration forPlatform(SuitePlatform platform) { if (onPlatform.isEmpty) return this; var config = this; onPlatform.forEach((platformSelector, platformConfig) { if (!platformSelector.evaluate(platform)) return; config = config.merge(platformConfig); }); return config.change(onPlatform: {}); } /// Merges two maps whose values are [SuiteConfiguration]s. /// /// Any overlapping keys in the maps have their configurations merged in the /// returned map. Map<T, SuiteConfiguration> _mergeConfigMaps<T>( Map<T, SuiteConfiguration> map1, Map<T, SuiteConfiguration> map2) => mergeMaps(map1, map2, value: (config1, config2) => config1.merge(config2)); SuiteConfiguration _resolveTags() { // If there's no tag-specific configuration, or if none of it applies, just // return the configuration as-is. if (_metadata.tags.isEmpty || tags.isEmpty) return this; // Otherwise, resolve the tag-specific components. var newTags = Map<BooleanSelector, SuiteConfiguration>.from(tags); var merged = tags.keys.fold(empty, (SuiteConfiguration merged, selector) { if (!selector.evaluate(_metadata.tags.contains)) return merged; return merged.merge(newTags.remove(selector)!); }); if (merged == empty) return this; return change(tags: newTags).merge(merged); } }
test/pkgs/test_core/lib/src/runner/suite.dart/0
{'file_path': 'test/pkgs/test_core/lib/src/runner/suite.dart', 'repo_id': 'test', 'token_count': 6687}
// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// A regular expression matching terminal color codes. final _colorCode = RegExp('\u001b\\[[0-9;]+m'); /// Returns [str] without any color codes. String withoutColors(String str) => str.replaceAll(_colorCode, ''); /// A regular expression matching a single vowel. final _vowel = RegExp('[aeiou]'); /// Returns [noun] with an indefinite article ("a" or "an") added, based on /// whether its first letter is a vowel. String a(String noun) => noun.startsWith(_vowel) ? 'an $noun' : 'a $noun'; /// Indent each line in [string] by 2 spaces. String indent(String text) { var lines = text.split('\n'); if (lines.length == 1) return ' $text'; var buffer = StringBuffer(); for (var line in lines.take(lines.length - 1)) { buffer.writeln(' $line'); } buffer.write(' ${lines.last}'); return buffer.toString(); } /// Truncates [text] to fit within [maxLength]. /// /// This will try to truncate along word boundaries and preserve words both at /// the beginning and the end of [text]. String truncate(String text, int maxLength) { // Return the full message if it fits. if (text.length <= maxLength) return text; // If we can fit the first and last three words, do so. var words = text.split(' '); if (words.length > 1) { var i = words.length; var length = words.first.length + 4; do { i--; length += 1 + words[i].length; } while (length <= maxLength && i > 0); if (length > maxLength || i == 0) i++; if (i < words.length - 4) { // Require at least 3 words at the end. var buffer = StringBuffer(); buffer.write(words.first); buffer.write(' ...'); for (; i < words.length; i++) { buffer.write(' '); buffer.write(words[i]); } return buffer.toString(); } } // Otherwise truncate to return the trailing text, but attempt to start at // the beginning of a word. var result = text.substring(text.length - maxLength + 4); var firstSpace = result.indexOf(' '); if (firstSpace > 0) { result = result.substring(firstSpace); } return '...$result'; }
test/pkgs/test_core/lib/src/util/pretty_print.dart/0
{'file_path': 'test/pkgs/test_core/lib/src/util/pretty_print.dart', 'repo_id': 'test', 'token_count': 780}
// Copyright 2014 The Flutter Authors. 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/widgets.dart'; class PageFlipTest extends StatelessWidget { const PageFlipTest({ Key? key, required this.angle, }) : assert(angle >= 0.0), assert(angle < 0.5), super(key: key); // 0.0, 0.097, 0.194 final double angle; @override Widget build(BuildContext context) { return Transform( transform: (Matrix4.rotationY(angle * math.pi)..setEntry(3, 0, angle * 0.008)) * Matrix4.diagonal3Values((1.0 - angle), (1.0 - angle), 1.0), alignment: Alignment.center, child: GridPaper( interval: 256.0, child: Container( margin: const EdgeInsets.all(20.0), alignment: Alignment.center, decoration: BoxDecoration( color: const Color(0xFF006666), border: Border.all(color: const Color(0xFF0000FF), width: 8.0), ), child: const Text('My name\'s not Kirk... It\'s Skywalker.', style: TextStyle(fontSize: 64.0, color: Color(0xFFFFFF00)), textAlign: TextAlign.center, textDirection: TextDirection.ltr, ), ), ), ); } }
tests/skp_generator/lib/tests/page_flip.dart/0
{'file_path': 'tests/skp_generator/lib/tests/page_flip.dart', 'repo_id': 'tests', 'token_count': 587}
import 'package:flutter/rendering.dart'; import 'package:textura/src/enums/textura_type.dart'; import 'package:textura/src/textures/fabrics/denim.dart'; import 'package:textura/src/textures/fabrics/fabric.dart'; import 'package:textura/src/textures/fabrics/furry.dart'; import 'package:textura/src/textures/fabrics/linen.dart'; import 'package:textura/src/textures/fabrics/silk.dart'; import 'package:textura/src/textures/fabrics/suede.dart'; import 'package:textura/src/textures/materials/asphalt.dart'; import 'package:textura/src/textures/materials/brick_wall.dart'; import 'package:textura/src/textures/materials/concrete.dart'; import 'package:textura/src/textures/materials/granite.dart'; import 'package:textura/src/textures/materials/leather.dart'; import 'package:textura/src/textures/materials/marble.dart'; import 'package:textura/src/textures/materials/metal_texture.dart'; import 'package:textura/src/textures/materials/rubber.dart'; import 'package:textura/src/textures/materials/rusted_metal.dart'; import 'package:textura/src/textures/materials/steel.dart'; import 'package:textura/src/textures/materials/wood_grain.dart'; import 'package:textura/src/textures/miscellaneous/canvas.dart'; import 'package:textura/src/textures/miscellaneous/dna.dart'; import 'package:textura/src/textures/miscellaneous/foam.dart'; import 'package:textura/src/textures/miscellaneous/game_pixels.dart'; import 'package:textura/src/textures/miscellaneous/graffiti.dart'; import 'package:textura/src/textures/miscellaneous/graph_paper.dart'; import 'package:textura/src/textures/miscellaneous/mud.dart'; import 'package:textura/src/textures/miscellaneous/music_sheet.dart'; import 'package:textura/src/textures/miscellaneous/newsprint.dart'; import 'package:textura/src/textures/miscellaneous/paper.dart'; import 'package:textura/src/textures/miscellaneous/perforated_metal.dart'; import 'package:textura/src/textures/miscellaneous/roadways.dart'; import 'package:textura/src/textures/miscellaneous/spider_web.dart'; import 'package:textura/src/textures/miscellaneous/train_tracks.dart'; import 'package:textura/src/textures/miscellaneous/water.dart'; import 'package:textura/src/textures/nature/clouds.dart'; import 'package:textura/src/textures/nature/constellations.dart'; import 'package:textura/src/textures/nature/galaxy.dart'; import 'package:textura/src/textures/nature/grass.dart'; import 'package:textura/src/textures/nature/leaves.dart'; import 'package:textura/src/textures/nature/sand.dart'; import 'package:textura/src/textures/nature/solar_system.dart'; import 'package:textura/src/textures/nature/stars.dart'; import 'package:textura/src/textures/nature/sunset.dart'; import 'package:textura/src/textures/patterns/bubble.dart'; import 'package:textura/src/textures/patterns/camo.dart'; import 'package:textura/src/textures/patterns/celtic_knots.dart'; import 'package:textura/src/textures/patterns/chequered.dart'; import 'package:textura/src/textures/patterns/chessboard.dart'; import 'package:textura/src/textures/patterns/city_maps.dart'; import 'package:textura/src/textures/patterns/greek_keys.dart'; import 'package:textura/src/textures/patterns/grid.dart'; import 'package:textura/src/textures/patterns/honeycomb.dart'; import 'package:textura/src/textures/patterns/leopard.dart'; import 'package:textura/src/textures/patterns/mosaic.dart'; import 'package:textura/src/textures/patterns/spirals.dart'; import 'package:textura/src/textures/patterns/zebra.dart'; import 'package:textura/src/textures/technology/circuitry.dart'; import 'package:textura/src/textures/technology/glitch.dart'; import 'package:textura/src/textures/technology/holographic.dart'; /// Extension on `TextureType` to provide a convenient way to access the /// corresponding `RenderBox`. /// It maps each texture type to its respective `RenderBox` object, which is /// used to draw the texture. /// /// Sample Usage: /// ```dart /// final renderObject = TextureType.asphalt.renderObject; /// ``` extension TextureTypeExtension on TextureType { /// Gets the `RenderBox` corresponding to the texture type. /// This `RenderBox` is used to draw the texture. RenderBox get renderObject { switch (this) { case TextureType.asphalt: return AsphaltTextureRenderObject(); case TextureType.brickWall: return BrickWallTextureRenderObject(); case TextureType.bubble: return BubbleTextureRenderObject(); case TextureType.camo: return CamoTextureRenderObject(); case TextureType.canvas: return CanvasTextureRenderObject(); case TextureType.celticKnots: return CelticKnotsTextureRenderObject(); case TextureType.chequered: return ChequeredTextureRenderObject(); case TextureType.chessboard: return ChessboardTextureRenderObject(); case TextureType.circuitry: return CircuitryTextureRenderObject(); case TextureType.cityMaps: return CityMapsTextureRenderObject(); case TextureType.clouds: return CloudsTextureRenderObject(); case TextureType.concrete: return ConcreteTextureRenderObject(); case TextureType.constellations: return ConstellationsTextureRenderObject(); case TextureType.denim: return DenimTextureRenderObject(); case TextureType.dna: return DNATextureRenderObject(); case TextureType.fabricTexture: return FabricTextureRenderObject(); case TextureType.foam: return FoamTextureRenderObject(); case TextureType.furry: return FurryTextureRenderObject(); case TextureType.galaxy: return GalaxyTextureRenderObject(); case TextureType.gamePixels: return GamePixelsTextureRenderObject(); case TextureType.glitch: return GlitchRenderObject(); case TextureType.graffiti: return GraffitiTextureRenderObject(); case TextureType.granite: return GraniteTextureRenderObject(); case TextureType.graphPaper: return GraphPaperTextureRenderObject(); case TextureType.grass: return GrassTextureRenderObject(); case TextureType.greekKeys: return GreekKeysTextureRenderObject(); case TextureType.grid: return GridTextureRenderObject(); case TextureType.holographic: return HolographicTextureRenderObject(); case TextureType.honeycomb: return HoneycombTextureRenderObject(); case TextureType.leather: return LeatherTextureRenderObject(); case TextureType.leaves: return LeavesTextureRenderObject(); case TextureType.leopard: return LeopardTextureRenderObject(); case TextureType.linen: return LinenTextureRenderObject(); case TextureType.marble: return MarbleTextureRenderObject(); case TextureType.metalTexture: return MetalTextureRenderObject(); case TextureType.mosaic: return MosaicTextureRenderObject(); case TextureType.mud: return MudTextureRenderObject(); case TextureType.musicSheet: return MusicSheetTextureRenderObject(); case TextureType.newsprint: return NewsprintTextureRenderObject(); case TextureType.paper: return PaperTextureRenderObject(); case TextureType.perforatedMetal: return PerforatedMetalTextureRenderObject(); case TextureType.roadways: return RoadwaysTextureRenderObject(); case TextureType.rubber: return RubberTextureRenderObject(); case TextureType.rustedMetal: return RustedMetalTextureRenderObject(); case TextureType.sand: return SandTextureRenderObject(); case TextureType.silk: return SilkTextureRenderObject(); case TextureType.solarSystem: return SolarSystemTextureRenderObject(); case TextureType.spiderWeb: return SpiderWebTextureRenderObject(); case TextureType.spirals: return SpiralsTextureRenderObject(); case TextureType.star: return StarsTextureRenderObject(); case TextureType.steel: return SteelTextureRenderObject(); case TextureType.suede: return SuedeTextureRenderObject(); case TextureType.sunset: return SunsetTextureRenderObject(); case TextureType.trainTracks: return TrainTracksTextureRenderObject(); case TextureType.water: return WaterTextureRenderObject(); case TextureType.woodGrain: return WoodGrainTextureRenderObject(); case TextureType.zebra: return ZebraTextureRenderObject(); } } }
textura/lib/src/extensions/texture_type_extension.dart/0
{'file_path': 'textura/lib/src/extensions/texture_type_extension.dart', 'repo_id': 'textura', 'token_count': 3058}
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class RustedMetalTextureRenderObject extends RenderBox with RenderObjectWithChildMixin { @override void performLayout() { child?.layout(constraints, parentUsesSize: true); size = constraints.biggest; } @override void paint(PaintingContext context, Offset offset) { final canvas = context.canvas; // Base metal color final basePaint = Paint() ..color = Colors.brown[900]! ..style = PaintingStyle.fill; canvas.drawRect(offset & size, basePaint); // Adding rust patches for texture final rustPaint = Paint() ..color = Colors.orange[700]! ..style = PaintingStyle.fill; final random = Random(0); const rustPatchCount = 50; for (var i = 0; i < rustPatchCount; i++) { final x = random.nextDouble() * size.width; final y = random.nextDouble() * size.height; final radius = random.nextDouble() * 20; canvas.drawCircle(Offset(x, y), radius, rustPaint); } // Painting the child with an offset if (child != null) { context.paintChild(child!, offset); } } }
textura/lib/src/textures/materials/rusted_metal.dart/0
{'file_path': 'textura/lib/src/textures/materials/rusted_metal.dart', 'repo_id': 'textura', 'token_count': 429}
import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class TrainTracksTextureRenderObject extends RenderProxyBox { @override void paint(PaintingContext context, Offset offset) { context.paintChild(child!, offset); final canvas = context.canvas; final paint = Paint() ..color = Colors.grey[700]! ..style = PaintingStyle.stroke ..strokeWidth = 2; final width = child!.size.width; final height = child!.size.height; const trackDistance = 20; const sleeperLength = 10; const sleeperDistance = 30; for (var x = 0.0; x < width; x += trackDistance) { canvas.drawLine(Offset(x, 0), Offset(x, height), paint); } for (var y = 0.0; y < height; y += sleeperDistance) { for (var x = 0.0; x < width; x += trackDistance * 2) { canvas.drawRect( Rect.fromPoints( Offset(x, y), Offset(x + sleeperLength, y + 5), ), paint, ); } } } }
textura/lib/src/textures/miscellaneous/train_tracks.dart/0
{'file_path': 'textura/lib/src/textures/miscellaneous/train_tracks.dart', 'repo_id': 'textura', 'token_count': 417}
import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class CityMapsTextureRenderObject extends RenderProxyBox { @override void paint(PaintingContext context, Offset offset) { super.paint(context, offset); final canvas = context.canvas; final roadPaint = Paint() ..color = Colors.grey ..style = PaintingStyle.stroke ..strokeWidth = 3.0; final buildingPaint = Paint() ..color = Colors.brown[300]! ..style = PaintingStyle.fill; const blockSize = 40.0; for (var x = 0.0; x < size.width; x += blockSize) { for (var y = 0.0; y < size.height; y += blockSize) { if ((x + y) % (blockSize * 2) == 0) { final building = Rect.fromLTWH(x, y, blockSize, blockSize); canvas.drawRect(building, buildingPaint); } } } for (var x = 0.0; x < size.width; x += blockSize) { canvas.drawLine(Offset(x, 0), Offset(x, size.height), roadPaint); } for (var y = 0.0; y < size.height; y += blockSize) { canvas.drawLine(Offset(0, y), Offset(size.width, y), roadPaint); } } }
textura/lib/src/textures/patterns/city_maps.dart/0
{'file_path': 'textura/lib/src/textures/patterns/city_maps.dart', 'repo_id': 'textura', 'token_count': 461}
include: package:lints/recommended.yaml analyzer: errors: prefer_typing_uninitialized_variables: ignore undefined_prefixed_name: ignore todo: ignore
three_dart/analysis_options.yaml/0
{'file_path': 'three_dart/analysis_options.yaml', 'repo_id': 'three_dart', 'token_count': 57}
import 'package:example/example_page.dart'; import 'package:example/home_page.dart'; import 'package:flutter/material.dart'; class ExampleApp extends StatefulWidget { const ExampleApp({Key? key}) : super(key: key); @override State<ExampleApp> createState() => _MyAppState(); } class _MyAppState extends State<ExampleApp> { final AppRouterDelegate _routerDelegate = AppRouterDelegate(); final AppRouteInformationParser _routeInformationParser = AppRouteInformationParser(); @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return MaterialApp.router( title: 'Example app', routerDelegate: _routerDelegate, routeInformationParser: _routeInformationParser, ); } } class AppRouteInformationParser extends RouteInformationParser<AppRoutePath> { @override Future<AppRoutePath> parseRouteInformation(RouteInformation routeInformation) async { final uri = Uri.parse(routeInformation.location!); // Handle '/' if (uri.pathSegments.isEmpty) { return AppRoutePath.home(); } // Handle '/examples/:id' if (uri.pathSegments.length == 2) { if (uri.pathSegments[0] != 'examples') return AppRoutePath.unknown(); var remaining = uri.pathSegments[1]; var id = remaining; // if (id == null) return AppRoutePath.unknown(); return AppRoutePath.details(id); } // Handle unknown routes return AppRoutePath.unknown(); } @override RouteInformation? restoreRouteInformation(AppRoutePath configuration) { if (configuration.isUnknown) { return const RouteInformation(location: '/404'); } if (configuration.isHomePage) { return const RouteInformation(location: '/'); } if (configuration.isDetailsPage) { return RouteInformation(location: '/examples/${configuration.id}'); } return null; } } class AppRouterDelegate extends RouterDelegate<AppRoutePath> with ChangeNotifier, PopNavigatorRouterDelegateMixin<AppRoutePath> { @override final GlobalKey<NavigatorState> navigatorKey; String? _selectedExample; bool show404 = false; AppRouterDelegate() : navigatorKey = GlobalKey<NavigatorState>(); @override AppRoutePath get currentConfiguration { if (show404) { return AppRoutePath.unknown(); } return _selectedExample == null ? AppRoutePath.home() : AppRoutePath.details(_selectedExample); } @override Widget build(BuildContext context) { return Navigator( key: navigatorKey, pages: [ MaterialPage( key: const ValueKey('HomePage'), child: HomePage(chooseExample: (id) { _handleExampleTapped(id); }), ), if (show404) const MaterialPage(key: ValueKey('UnknownPage'), child: UnknownScreen()) else if (_selectedExample != null) MaterialPage( key: const ValueKey('ExamplePage'), child: Builder( builder: (BuildContext context) { return ExamplePage(id: _selectedExample); }, )) ], onPopPage: (route, result) { if (!route.didPop(result)) { return false; } // Update the list of pages by setting _selectedBook to null _selectedExample = null; show404 = false; notifyListeners(); return true; }, ); } @override Future<void> setNewRoutePath(AppRoutePath configuration) async { if (configuration.isUnknown) { _selectedExample = null; show404 = true; return; } if (configuration.isDetailsPage) { if (configuration.id == null) { show404 = true; return; } _selectedExample = configuration.id; } else { _selectedExample = null; } show404 = false; } void _handleExampleTapped(String id) { _selectedExample = id; notifyListeners(); } } class AppRoutePath { final String? id; final bool isUnknown; AppRoutePath.home() : id = null, isUnknown = false; AppRoutePath.details(this.id) : isUnknown = false; AppRoutePath.unknown() : id = null, isUnknown = true; bool get isHomePage => id == null; bool get isDetailsPage => id != null; } class UnknownScreen extends StatelessWidget { const UnknownScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: const Center( child: Text('404!'), ), ); } }
three_dart/example/lib/example_app.dart/0
{'file_path': 'three_dart/example/lib/example_app.dart', 'repo_id': 'three_dart', 'token_count': 1743}
/// Fake Blob for fit web code when in App & Desktop class Blob { dynamic data; late Map<String, dynamic> options; Blob(this.data, this.options); } createObjectURL(blob) { return blob; }
three_dart/lib/extra/blob.dart/0
{'file_path': 'three_dart/lib/extra/blob.dart', 'repo_id': 'three_dart', 'token_count': 68}
library cameras; export 'array_camera.dart'; export 'camera.dart'; export 'cube_camera.dart'; export 'orthographic_camera.dart'; export 'perspective_camera.dart'; export 'stereo_camera.dart';
three_dart/lib/three3d/cameras/index.dart/0
{'file_path': 'three_dart/lib/three3d/cameras/index.dart', 'repo_id': 'three_dart', 'token_count': 67}
import 'package:three_dart/three3d/extras/core/curve.dart'; import 'package:three_dart/three3d/math/index.dart'; class LineCurve extends Curve { LineCurve(Vector2 v1, Vector2 v2) { type = 'LineCurve'; isLineCurve = true; this.v1 = v1; this.v2 = v2; } LineCurve.fromJSON(Map<String, dynamic> json) { super.fromJSON(json); type = 'LineCurve'; isLineCurve = true; v1 = Vector2().fromArray(json["v1"]); v2 = Vector2().fromArray(json["v2"]); } @override getPoint(t, optionalTarget) { var point = optionalTarget ?? Vector2(null, null); if (t == 1) { point.copy(v2); } else { point.copy(v2).sub(v1); point.multiplyScalar(t).add(v1); } return point; } // Line curve is linear, so we can overwrite default getPointAt @override getPointAt(u, optionalTarget) { return getPoint(u, optionalTarget); } @override getTangent(t, [optionalTarget]) { var tangent = optionalTarget ?? Vector2(null, null); tangent.copy(v2).sub(v1).normalize(); return tangent; } @override copy(source) { super.copy(source); v1.copy(source.v1); v2.copy(source.v2); return this; } @override toJSON() { var data = super.toJSON(); data["v1"] = v1.toArray(); data["v2"] = v2.toArray(); return data; } } class LineCurve3 extends Curve { late Vector3 vec1; late Vector3 vec2; LineCurve3(this.vec1, this.vec2) { isLineCurve = true; type = 'LineCurve3'; } LineCurve3.fromJSON(Map<String, dynamic> json) { arcLengthDivisions = json["arcLengthDivisions"]; isLineCurve = true; type = 'LineCurve3'; vec1 = Vector3.fromJSON(json['vec1']); vec2 = Vector3.fromJSON(json['vec2']); } @override getPoint(t, optionalTarget) { var point = optionalTarget ?? Vector3(null, null, null); if (t == 1) { point.copy(vec2); } else { point.copy(vec2).sub(vec1); point.multiplyScalar(t).add(vec1); } return point; } // Line curve is linear, so we can overwrite default getPointAt @override getPointAt(u, optionalTarget) { return getPoint(u, optionalTarget); } @override getTangent(t, [optionalTarget]) { var tangent = optionalTarget ?? Vector3(null, null, null); tangent.copy(vec2).sub(vec1).normalize(); return tangent; } @override copy(source) { super.copy(source); isLineCurve = true; vec1.copy(source.vec1); vec2.copy(source.vec2); return this; } @override toJSON() { var data = super.toJSON(); data["vec1"] = vec1.toArray(); data["vec2"] = vec2.toArray(); return data; } }
three_dart/lib/three3d/extras/curves/line_curve.dart/0
{'file_path': 'three_dart/lib/three3d/extras/curves/line_curve.dart', 'repo_id': 'three_dart', 'token_count': 1122}
import 'package:three_dart/three3d/geometries/polyhedron_geometry.dart'; import 'package:three_dart/three3d/math/index.dart'; class DodecahedronGeometry extends PolyhedronGeometry { DodecahedronGeometry.create( vertices, indices, radius, detail, ) : super( vertices, indices, radius, detail, ) { type = "DodecahedronGeometry"; parameters = { "radius": radius, "detail": detail, }; } factory DodecahedronGeometry([ num radius = 1, int detail = 0, ]) { var t = (1 + Math.sqrt(5)) / 2; var r = 1 / t; List<num> vertices = [ // (±1, ±1, ±1) -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, // (0, ±1/φ, ±φ) 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0) -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ) -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r ]; List<num> indices = [ 3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9 ]; return DodecahedronGeometry.create(vertices, indices, radius, detail); } }
three_dart/lib/three3d/geometries/dodecahedron_geometry.dart/0
{'file_path': 'three_dart/lib/three3d/geometries/dodecahedron_geometry.dart', 'repo_id': 'three_dart', 'token_count': 1485}
import 'package:three_dart/three3d/constants.dart'; import 'package:three_dart/three3d/materials/material.dart'; import 'package:three_dart/three3d/math/index.dart'; class MeshToonMaterial extends Material { MeshToonMaterial([Map<String, dynamic>? parameters]) : super() { defines = {'TOON': ''}; type = 'MeshToonMaterial'; color = Color.fromHex(0xffffff); map = null; gradientMap = null; lightMap = null; lightMapIntensity = 1.0; aoMap = null; aoMapIntensity = 1.0; emissive = Color.fromHex(0x000000); emissiveIntensity = 1.0; emissiveMap = null; bumpMap = null; bumpScale = 1; normalMap = null; normalMapType = TangentSpaceNormalMap; normalScale = Vector2(1, 1); displacementMap = null; displacementScale = 1; displacementBias = 0; alphaMap = null; wireframe = false; wireframeLinewidth = 1; wireframeLinecap = 'round'; wireframeLinejoin = 'round'; fog = true; setValues(parameters); } @override MeshToonMaterial copy(Material source) { super.copy(source); color.copy(source.color); map = source.map; gradientMap = source.gradientMap; lightMap = source.lightMap; lightMapIntensity = source.lightMapIntensity; aoMap = source.aoMap; aoMapIntensity = source.aoMapIntensity; emissive?.copy(source.emissive!); emissiveMap = source.emissiveMap; emissiveIntensity = source.emissiveIntensity; bumpMap = source.bumpMap; bumpScale = source.bumpScale; normalMap = source.normalMap; normalMapType = source.normalMapType; normalScale?.copy(source.normalScale!); displacementMap = source.displacementMap; displacementScale = source.displacementScale; displacementBias = source.displacementBias; alphaMap = source.alphaMap; wireframe = source.wireframe; wireframeLinewidth = source.wireframeLinewidth; wireframeLinecap = source.wireframeLinecap; wireframeLinejoin = source.wireframeLinejoin; fog = source.fog; return this; } }
three_dart/lib/three3d/materials/mesh_toon_material.dart/0
{'file_path': 'three_dart/lib/three3d/materials/mesh_toon_material.dart', 'repo_id': 'three_dart', 'token_count': 779}
String fogVertex = """ #ifdef USE_FOG vFogDepth = - mvPosition.z; #endif """;
three_dart/lib/three3d/renderers/shaders/shader_chunk/fog_vertex.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/fog_vertex.glsl.dart', 'repo_id': 'three_dart', 'token_count': 36}
String normalParsFragment = """ #ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif """;
three_dart/lib/three3d/renderers/shaders/shader_chunk/normal_pars_fragment.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/normal_pars_fragment.glsl.dart', 'repo_id': 'three_dart', 'token_count': 76}
String skinningVertex = """ #ifdef USE_SKINNING vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); vec4 skinned = vec4( 0.0 ); skinned += boneMatX * skinVertex * skinWeight.x; skinned += boneMatY * skinVertex * skinWeight.y; skinned += boneMatZ * skinVertex * skinWeight.z; skinned += boneMatW * skinVertex * skinWeight.w; transformed = ( bindMatrixInverse * skinned ).xyz; #endif """;
three_dart/lib/three3d/renderers/shaders/shader_chunk/skinning_vertex.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/skinning_vertex.glsl.dart', 'repo_id': 'three_dart', 'token_count': 143}
String spriteVert = """ uniform float rotation; uniform vec2 center; #include <common> #include <uv_pars_vertex> #include <fog_pars_vertex> #include <logdepthbuf_pars_vertex> #include <clipping_planes_pars_vertex> void main() { #include <uv_vertex> vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 ); vec2 scale; scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) ); scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) ); #ifndef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) scale *= - mvPosition.z; #endif vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; vec2 rotatedPosition; rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; mvPosition.xy += rotatedPosition; gl_Position = projectionMatrix * mvPosition; #include <logdepthbuf_vertex> #include <clipping_planes_vertex> #include <fog_vertex> } """;
three_dart/lib/three3d/renderers/shaders/shader_lib/sprite_vert.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_lib/sprite_vert.glsl.dart', 'repo_id': 'three_dart', 'token_count': 410}
import 'package:three_dart/three3d/math/index.dart'; class FogBase { String name = ""; late Color color; bool isFog = false; bool isFogExp2 = false; toJSON() { throw (" need implement .... "); } } class Fog extends FogBase { late num near; late num far; Fog(color, num? near, num? far) { isFog = true; name = ''; if (color is int) { this.color = Color(0, 0, 0).setHex(color); } else if (color is Color) { this.color = color; } else { throw (" Fog color type: ${color.runtimeType} is not support ... "); } this.near = near ?? 1; this.far = far ?? 1000; } clone() { return Fog(color, near, far); } @override toJSON(/* meta */) { return {"type": 'Fog', "color": color.getHex(), "near": near, "far": far}; } }
three_dart/lib/three3d/scenes/fog.dart/0
{'file_path': 'three_dart/lib/three3d/scenes/fog.dart', 'repo_id': 'three_dart', 'token_count': 330}
name: cicd on: push: branches: - main pull_request: types: [opened, reopened, synchronize] jobs: # BEGIN LINTING STAGE dartdoc: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: subosito/flutter-action@v1 with: channel: 'stable' - uses: flame-engine/flame-dartdoc-action@v2 analyze: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: subosito/flutter-action@v2 - uses: bluefireteam/melos-action@v3 - name: "Analyze with latest stable" uses: invertase/github-action-dart-analyzer@v2.0.0 with: fatal-infos: true format: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: subosito/flutter-action@v2 with: cache: true - uses: bluefireteam/melos-action@v3 - name: Run format run: melos format-check # END LINTING STAGE # BEGIN TESTING STAGE test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: subosito/flutter-action@v2 with: cache: true - uses: bluefireteam/melos-action@v3 - name: Run tests run: melos test # END TESTING STAGE
tiled.dart/.github/workflows/cicd.yaml/0
{'file_path': 'tiled.dart/.github/workflows/cicd.yaml', 'repo_id': 'tiled.dart', 'token_count': 597}
part of tiled; /// Below is Tiled's documentation about how this structure is represented /// on XML files: /// /// <point> /// Used to mark an object as a point. /// The existing x and y attributes are used to determine the position of the /// point. class Point { double x; double y; Point({required this.x, required this.y}); Point.parse(Parser parser) : this( x: parser.getDouble('x'), y: parser.getDouble('y'), ); factory Point.parseFromString(String point) { final split = point.split(','); return Point( x: double.parse(split[0]), y: double.parse(split[1]), ); } }
tiled.dart/packages/tiled/lib/src/common/point.dart/0
{'file_path': 'tiled.dart/packages/tiled/lib/src/common/point.dart', 'repo_id': 'tiled.dart', 'token_count': 233}
part of tiled; /// Below is Tiled's documentation about how this structure is represented /// on XML files: /// /// <tileoffset> /// /// x: Horizontal offset in pixels. (defaults to 0) /// y: Vertical offset in pixels (positive is down, defaults to 0) /// /// This element is used to specify an offset in pixels, to be applied when /// drawing a tile from the related tileset. /// When not present, no offset is applied. class TileOffset { int x; int y; TileOffset({ required this.x, required this.y, }); TileOffset.parse(Parser parser) : this( x: parser.getInt('x', defaults: 0), y: parser.getInt('y', defaults: 0), ); }
tiled.dart/packages/tiled/lib/src/tileset/tile_offset.dart/0
{'file_path': 'tiled.dart/packages/tiled/lib/src/tileset/tile_offset.dart', 'repo_id': 'tiled.dart', 'token_count': 228}
name: tiled_workspace environment: sdk: ">=3.0.0 <4.0.0" dev_dependencies: melos: ^3.0.0
tiled.dart/pubspec.yaml/0
{'file_path': 'tiled.dart/pubspec.yaml', 'repo_id': 'tiled.dart', 'token_count': 50}
linter: rules: - always_declare_return_types - always_put_control_body_on_new_line - always_put_required_named_parameters_first - always_require_non_null_named_parameters - always_specify_types - annotate_overrides - avoid_annotating_with_dynamic - avoid_as - avoid_bool_literals_in_conditional_expressions - avoid_catches_without_on_clauses - avoid_catching_errors - avoid_classes_with_only_static_members - avoid_double_and_int_checks - avoid_empty_else - avoid_equals_and_hash_code_on_mutable_classes - avoid_escaping_inner_quotes - avoid_field_initializers_in_const_classes - avoid_function_literals_in_foreach_calls - avoid_implementing_value_types - avoid_init_to_null - avoid_js_rounded_ints - avoid_null_checks_in_equality_operators - avoid_positional_boolean_parameters - avoid_print - avoid_private_typedef_functions - avoid_redundant_argument_values - avoid_relative_lib_imports - avoid_renaming_method_parameters - avoid_return_types_on_setters - avoid_returning_null - avoid_returning_null_for_future - avoid_returning_null_for_void - avoid_returning_this - avoid_setters_without_getters - avoid_shadowing_type_parameters - avoid_single_cascade_in_expression_statements - avoid_slow_async_io - avoid_types_as_parameter_names - avoid_types_on_closure_parameters - avoid_unnecessary_containers - avoid_unused_constructor_parameters - avoid_void_async - avoid_web_libraries_in_flutter - await_only_futures - camel_case_extensions - camel_case_types - cancel_subscriptions - cascade_invocations - close_sinks - comment_references - constant_identifier_names - control_flow_in_finally - curly_braces_in_flow_control_structures - diagnostic_describe_all_properties - directives_ordering - empty_catches - empty_constructor_bodies - empty_statements - file_names - flutter_style_todos - hash_and_equals - implementation_imports - invariant_booleans - iterable_contains_unrelated_type - join_return_with_assignment - leading_newlines_in_multiline_strings - library_names - library_prefixes - lines_longer_than_80_chars - list_remove_unrelated_type - literal_only_boolean_expressions - missing_whitespace_between_adjacent_strings - no_adjacent_strings_in_list - no_duplicate_case_values - no_logic_in_create_state - no_runtimeType_toString - non_constant_identifier_names - null_closures - omit_local_variable_types - one_member_abstracts - only_throw_errors - overridden_fields - package_api_docs - package_names - package_prefixed_library_names - parameter_assignments - prefer_adjacent_string_concatenation - prefer_asserts_in_initializer_lists - prefer_asserts_with_message - prefer_collection_literals - prefer_conditional_assignment - prefer_const_constructors - prefer_const_constructors_in_immutables - prefer_const_declarations - prefer_const_literals_to_create_immutables - prefer_constructors_over_static_methods - prefer_contains - prefer_double_quotes - prefer_equal_for_default_values - prefer_expression_function_bodies - prefer_final_fields - prefer_final_in_for_each - prefer_final_locals - prefer_for_elements_to_map_fromIterable - prefer_foreach - prefer_function_declarations_over_variables - prefer_generic_function_type_aliases - prefer_if_elements_to_conditional_expressions - prefer_if_null_operators - prefer_initializing_formals - prefer_inlined_adds - prefer_int_literals - prefer_interpolation_to_compose_strings - prefer_is_empty - prefer_is_not_empty - prefer_is_not_operator - prefer_iterable_whereType - prefer_mixin - prefer_null_aware_operators - prefer_relative_imports - prefer_single_quotes - prefer_spread_collections - prefer_typing_uninitialized_variables - prefer_void_to_null - provide_deprecation_message - public_member_api_docs - recursive_getters - slash_for_doc_comments - sort_child_properties_last - sort_constructors_first - sort_pub_dependencies - sort_unnamed_constructors_first - test_types_in_equals - throw_in_finally - type_annotate_public_apis - type_init_formals - unawaited_futures - unnecessary_await_in_return - unnecessary_brace_in_string_interps - unnecessary_const - unnecessary_final - unnecessary_getters_setters - unnecessary_lambdas - unnecessary_new - unnecessary_null_aware_assignments - unnecessary_null_in_if_null_operators - unnecessary_overrides - unnecessary_parenthesis - unnecessary_raw_strings - unnecessary_statements - unnecessary_string_escapes - unnecessary_string_interpolations - unnecessary_this - unrelated_type_equality_checks - unsafe_html - use_full_hex_values_for_flutter_colors - use_function_type_syntax_for_parameters - use_key_in_widget_constructors - use_raw_strings - use_rethrow_when_possible - use_setters_to_change_properties - use_string_buffers - use_to_and_as_if_applicable - valid_regexps - void_checks
todos/all_lint_rules.yaml/0
{'file_path': 'todos/all_lint_rules.yaml', 'repo_id': 'todos', 'token_count': 2431}
import 'package:flutter/material.dart'; class YMargin extends StatelessWidget { const YMargin(this.value, {Key? key}) : super(key: key); final double? value; @override Widget build(BuildContext context) { return SizedBox( height: value, ); } }
travel_ui/lib/src/utils/margins/y_margin.dart/0
{'file_path': 'travel_ui/lib/src/utils/margins/y_margin.dart', 'repo_id': 'travel_ui', 'token_count': 99}
flutter_icons: image_path_android: "assets/icon.png" image_path_ios: "assets/icon.png" android: true ios: true
trex-flame/flutter_launcher_icons.yaml/0
{'file_path': 'trex-flame/flutter_launcher_icons.yaml', 'repo_id': 'trex-flame', 'token_count': 46}
import 'dart:ui'; import 'package:flame/components.dart'; import '../custom/util.dart'; import '../game.dart'; import 'config.dart'; class Cloud extends SpriteComponent { Cloud({ required this.config, required Image spriteImage, }) : cloudGap = getRandomNum( config.minCloudGap, config.maxCloudGap, ), super( sprite: Sprite( spriteImage, srcPosition: Vector2(166.0, 2.0), srcSize: Vector2(config.width, config.height), ), ); final CloudConfig config; final double cloudGap; @override void update(double dt) { super.update(dt); if (shouldRemove) { return; } x -= (parent as CloudManager).cloudSpeed.ceil() * 50 * dt; if (!isVisible) { removeFromParent(); } } bool get isVisible { return x + config.width > 0; } @override void onGameResize(Vector2 gameSize) { super.onGameResize(gameSize); y = ((absolutePosition.y / 2 - (config.maxSkyLevel - config.minSkyLevel)) + getRandomNum(config.minSkyLevel, config.maxSkyLevel)) - absolutePositionOf(absoluteTopLeftPosition).y; } } class CloudManager extends PositionComponent with HasGameRef<TRexGame> { CloudManager({ required this.horizonConfig, }); final HorizonConfig horizonConfig; late final CloudConfig cloudConfig = CloudConfig(); void addCloud() { final cloud = Cloud( config: cloudConfig, spriteImage: gameRef.spriteImage, ); cloud.x = gameRef.size.x + cloudConfig.width + 10; cloud.y = ((absolutePosition.y / 2 - (cloudConfig.maxSkyLevel - cloudConfig.minSkyLevel)) + getRandomNum(cloudConfig.minSkyLevel, cloudConfig.maxSkyLevel)) - absolutePosition.y; add(cloud); } double get cloudSpeed => horizonConfig.bgCloudSpeed / 1000 * gameRef.currentSpeed; @override void update(double dt) { super.update(dt); final int numClouds = children.length; if (numClouds > 0) { final lastCloud = children.last as Cloud; if (numClouds < horizonConfig.maxClouds && (gameRef.size.x / 2 - lastCloud.x) > lastCloud.cloudGap) { addCloud(); } } else { addCloud(); } } void reset() { children.clear(); } }
trex-flame/lib/game/horizon/clouds.dart/0
{'file_path': 'trex-flame/lib/game/horizon/clouds.dart', 'repo_id': 'trex-flame', 'token_count': 937}
name: union description: Type safe union types for dart, by using extensions from Dart 2.6 version: 0.0.4-nullsafety.1 homepage: https://github.com/rrousselGit/union authors: - Remi Rousselet <darky12s@gmail.com> environment: sdk: ">=2.12.0-0 <3.0.0" dev_dependencies: test: ^1.16.0-nullsafety.12
union/pubspec.yaml/0
{'file_path': 'union/pubspec.yaml', 'repo_id': 'union', 'token_count': 120}
// Copyright 2021, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Deeplink query parameters example /// Done using go_router import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; void main() { runApp(BooksApp()); } class Book { final String title; final String author; Book(this.title, this.author); } class BooksApp extends StatelessWidget { final List<Book> books = [ Book('Stranger in a Strange Land', 'Robert A. Heinlein'), Book('Foundation', 'Isaac Asimov'), Book('Fahrenheit 451', 'Ray Bradbury'), ]; @override Widget build(BuildContext context) { return MaterialApp.router( routeInformationParser: _router.routeInformationParser, routerDelegate: _router.routerDelegate, ); } late final _router = GoRouter( routes: [ GoRoute( path: '/', pageBuilder: (context, state) => MaterialPage( key: state.pageKey, child: BooksListScreen( books: books, filter: state.queryParams['filter'], ), ), ), ], errorPageBuilder: (context, state) => MaterialPage( key: state.pageKey, child: ErrorScreen(state.error), ), ); } class BooksListScreen extends StatelessWidget { final List<Book> books; final String? filter; BooksListScreen({required this.books, required this.filter}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: ListView( children: [ TextField( decoration: InputDecoration( hintText: 'filter', ), onSubmitted: (value) => context.go('/?filter=$value'), ), for (var book in books) if (filter == null || book.title.toLowerCase().contains(filter!)) ListTile( title: Text(book.title), subtitle: Text(book.author), ) ], ), ); } } class ErrorScreen extends StatelessWidget { const ErrorScreen(this.error, {Key? key}) : super(key: key); final Exception? error; @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text('Page Not Found')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(error?.toString() ?? 'page not found'), TextButton( onPressed: () => context.go('/'), child: const Text('Home'), ), ], ), ), ); }
uxr/nav2-usability/scenario_code/lib/deeplink-queryparam/deeplink_queryparam_go_router.dart/0
{'file_path': 'uxr/nav2-usability/scenario_code/lib/deeplink-queryparam/deeplink_queryparam_go_router.dart', 'repo_id': 'uxr', 'token_count': 1177}
// Copyright 2021, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Nested example /// Done using go_router import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; void main() { runApp(BooksApp()); } class BooksApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp.router( routeInformationParser: _router.routeInformationParser, routerDelegate: _router.routerDelegate, ); } late final _router = GoRouter( routes: [ GoRoute( path: '/', redirect: (_) => '/books/new', ), GoRoute( path: '/books/:kind(all|new)', pageBuilder: (context, state) => CustomTransitionPage( key: state.pageKey, child: AppScreen( currentIndex: 0, child: BooksScreen( selectedTab: state.params['kind'] == 'new' ? 0 : 1, ), ), transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) => FadeTransition(opacity: animation, child: child), ), ), GoRoute( path: '/settings', pageBuilder: (context, state) => CustomTransitionPage( key: state.pageKey, child: AppScreen( currentIndex: 1, child: SettingsScreen(), ), transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) => FadeTransition(opacity: animation, child: child), ), ), ], errorPageBuilder: (context, state) => MaterialPage( key: state.pageKey, child: ErrorScreen(state.error), ), ); } class AppScreen extends StatelessWidget { final int currentIndex; final Widget child; const AppScreen({ Key? key, required this.currentIndex, required this.child, }) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( body: child, bottomNavigationBar: BottomNavigationBar( currentIndex: currentIndex, onTap: (idx) { if (idx == 0) { context.go('/books/new'); } else { context.go('/settings'); } }, items: [ BottomNavigationBarItem( label: 'Books', icon: Icon(Icons.chrome_reader_mode_outlined), ), BottomNavigationBarItem( label: 'Settings', icon: Icon(Icons.settings), ), ], ), ); } } class BooksScreen extends StatefulWidget { final int selectedTab; BooksScreen({ Key? key, required this.selectedTab, }) : super(key: key); @override _BooksScreenState createState() => _BooksScreenState(); } class _BooksScreenState extends State<BooksScreen> with SingleTickerProviderStateMixin { late final TabController _tabController; @override void initState() { _tabController = TabController(length: 2, vsync: this, initialIndex: widget.selectedTab); super.initState(); } @override void didChangeDependencies() { super.didChangeDependencies(); _tabController.animateTo(widget.selectedTab); } void dispose() { _tabController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( children: [ TabBar( controller: _tabController, onTap: (int index) => context.go(index == 1 ? '/books/all' : '/books/new'), labelColor: Theme.of(context).primaryColor, tabs: [ Tab(icon: Icon(Icons.bathtub), text: 'New'), Tab(icon: Icon(Icons.group), text: 'All'), ], ), Expanded( child: TabBarView( controller: _tabController, children: [ NewBooksScreen(), AllBooksScreen(), ], ), ), ], ); } } class SettingsScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text('Settings'), ), ); } } class AllBooksScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text('All Books'), ), ); } } class NewBooksScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text('New Books'), ), ); } } class ErrorScreen extends StatelessWidget { const ErrorScreen(this.error, {Key? key}) : super(key: key); final Exception? error; @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text('Page Not Found')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(error?.toString() ?? 'page not found'), TextButton( onPressed: () => context.go('/'), child: const Text('Home'), ), ], ), ), ); }
uxr/nav2-usability/scenario_code/lib/nested-routing/nested_routing_go_router.dart/0
{'file_path': 'uxr/nav2-usability/scenario_code/lib/nested-routing/nested_routing_go_router.dart', 'repo_id': 'uxr', 'token_count': 2443}
// Copyright 2021, the Flutter project authors. Please see the AUTHORS file // for details. 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:beamer/beamer.dart'; void main() { runApp(BooksApp()); } class Book { final String title; final Author author; Book(this.title, this.author); } class Author { String name; Author(this.name); } final List<Book> books = [ Book('Stranger in a Strange Land', Author('Robert A. Heinlein')), Book('Foundation', Author('Isaac Asimov')), Book('Fahrenheit 451', Author('Ray Bradbury')), ]; List<Author> get authors => books.map<Author>((book) => book.author).toList(); class BooksLocation extends BeamLocation { BooksLocation(BeamState state) : super(state); @override List<String> get pathBlueprints => ['/books/:bookId']; @override List<BeamPage> buildPages(BuildContext context, BeamState state) { String? rawBookId = state.pathParameters['bookId']; int? bookId = rawBookId != null ? int.parse(rawBookId) : null; return [ BeamPage( key: ValueKey('books'), child: BooksListScreen( books: books, onTapped: (book) => update( (state) => state.copyWith( pathBlueprintSegments: ['books', ':bookId'], pathParameters: {'bookId': books.indexOf(book).toString()}, ), ), // OR // onTapped: (book) => // Beamer.of(context).beamToNamed('/books/${books.indexOf(book)}'), ), ), if (bookId != null) BeamPage( key: ValueKey('books-$bookId'), child: BookDetailsScreen( book: books[bookId], onAuthorTapped: (author) => Beamer.of(context).update( state: BeamState( pathBlueprintSegments: ['authors', ':authorId'], pathParameters: { 'authorId': authors.indexOf(author).toString() }, ), ), // OR // onAuthorTapped: (author) => Beamer.of(context) // .beamToNamed('/authors/${authors.indexOf(author)}'), ), ), ]; } } class AuthorsLocation extends BeamLocation { AuthorsLocation(BeamState state) : super(state); @override List<String> get pathBlueprints => ['/authors/:authorId']; @override List<BeamPage> buildPages(BuildContext context, BeamState state) { String? rawAuthorId = state.pathParameters['authorId']; int? authorId = rawAuthorId != null ? int.parse(rawAuthorId) : null; return [ if (state.pathBlueprintSegments.contains('authors')) BeamPage( key: ValueKey('authors'), child: AuthorsListScreen( authors: authors, onTapped: (author) => update( (state) => state.copyWith( pathBlueprintSegments: state.pathBlueprintSegments ..add(':authorId'), pathParameters: { 'authorId': authors.indexOf(author).toString() }, ), ), // OR // onTapped: (author) => Beamer.of(context) // .beamToNamed('/authors/${authors.indexOf(author)}'), onGoToBooksTapped: () => Beamer.of(context).update( state: BeamState(), ), // OR // onGoToBooksTapped: () => Beamer.of(context).beamToNamed('/'), ), ), if (authorId != null) BeamPage( key: ValueKey('author-$authorId'), child: AuthorDetailsScreen( author: authors[authorId], ), ), ]; } } class BooksApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp.router( title: 'Books App', routerDelegate: BeamerDelegate( locationBuilder: (state) { if (state.uri.path.contains('authors')) { return AuthorsLocation(state); } return BooksLocation(state); }, ), routeInformationParser: BeamerParser(), ); } } class BooksListScreen extends StatelessWidget { final List<Book> books; final ValueChanged<Book> onTapped; BooksListScreen({ required this.books, required this.onTapped, }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: ListView( children: [ for (var book in books) ListTile( title: Text(book.title), subtitle: Text(book.author.name), onTap: () => onTapped(book), ) ], ), ); } } class AuthorsListScreen extends StatelessWidget { final List<Author> authors; final ValueChanged<Author> onTapped; final VoidCallback onGoToBooksTapped; AuthorsListScreen({ required this.authors, required this.onTapped, required this.onGoToBooksTapped, }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: ListView( children: [ ElevatedButton( onPressed: onGoToBooksTapped, child: Text('Go to Books Screen'), ), for (var author in authors) ListTile( title: Text(author.name), onTap: () => onTapped(author), ) ], ), ); } } class BookDetailsScreen extends StatelessWidget { final Book book; final ValueChanged<Author> onAuthorTapped; BookDetailsScreen({ required this.book, required this.onAuthorTapped, }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(book.title, style: Theme.of(context).textTheme.headline6), ElevatedButton( onPressed: () { onAuthorTapped(book.author); }, child: Text(book.author.name), ), ], ), ), ); } } class AuthorDetailsScreen extends StatelessWidget { final Author author; AuthorDetailsScreen({ required this.author, }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(author.name, style: Theme.of(context).textTheme.headline6), ], ), ), ); } }
uxr/nav2-usability/scenario_code/lib/skipping-stacks/skipping_stacks_beamer.dart/0
{'file_path': 'uxr/nav2-usability/scenario_code/lib/skipping-stacks/skipping_stacks_beamer.dart', 'repo_id': 'uxr', 'token_count': 3079}