code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
// Copyright 2020 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
/// Defines the data types for this project.
library;
import 'package:json_annotation/json_annotation.dart';
import 'package:path/path.dart' as path;
import 'package:samples_index/src/util.dart' as util;
part 'data.g.dart';
/// The full list of samples
@JsonSerializable(
// Use anyMap and checked for more useful YAML parsing errors. See
// package:checked_yaml docs for details.
anyMap: true,
checked: true)
class Index {
final List<Sample> samples;
Index(this.samples);
factory Index.fromJson(Map<dynamic, dynamic> json) => _$IndexFromJson(json);
Map<String, dynamic> toJson() => _$IndexToJson(this);
}
/// A sample to be displayed in the app.
@JsonSerializable(anyMap: true, checked: true)
class Sample {
/// The name of the sample.
final String name;
/// The author of the sample. Typically "Flutter"
final String? author;
/// Screenshots of the sample. At least 1 screenshot is required.
final List<Screenshot> screenshots;
/// A link to the source code.
final String source;
/// A link to this sample running in the browser.
final String? web;
/// 3-5 sentences describing the sample.
final String description;
/// The difficulty level. Values are either 'beginner', 'intermediate', or
/// 'advanced'.
final String? difficulty;
/// List of widgets or Flutter APIs used by the sample. e.g. "AnimatedBuilder"
/// or "ChangeNotifier".
final List<String> widgets;
/// List of packages or Flutter libraries used by the sample. third-party
/// packages.
final List<String> packages;
/// Arbitrary tags to associate with this sample.
final List<String> tags;
/// Supported platforms. Values are either 'ios', 'android', 'desktop', and
/// 'web'
final List<String> platforms;
/// The type of the sample. Supported values are either 'sample' or
/// 'demo'.
final String type;
/// The date this sample was created.
final DateTime? date;
/// The Flutter channel this sample runs on. Either 'stable', 'dev' or
/// 'master'.
final String? channel;
Sample({
required this.name,
this.author = 'Flutter',
required this.screenshots,
required this.source,
this.web,
required this.description,
this.difficulty = 'beginner',
this.widgets = const [],
this.packages = const [],
this.tags = const [],
this.platforms = const [],
required this.type,
this.date,
this.channel,
});
factory Sample.fromJson(Map<dynamic, dynamic> json) => _$SampleFromJson(json);
Map<String, dynamic> toJson() => _$SampleToJson(this);
String get thumbnail {
var screenshotUrl = screenshots.first.url;
var prefix = path.dirname(screenshotUrl);
var filename = path.basenameWithoutExtension(screenshotUrl);
return path.join(prefix, '${filename}_thumb.png');
}
String get searchAttributes {
var buf = StringBuffer();
buf.write(name.toLowerCase());
buf.write(' ');
for (final tag in tags) {
buf.write('tag:${tag.toLowerCase()} ');
// Allow tags to be searched without the tag: prefix
buf.write('${tag.toLowerCase()} ');
}
for (final platform in platforms) {
buf.write('platform:$platform ');
// Allow platforms to be searched without the tag: prefix
buf.write('$platform ');
}
for (final widget in widgets) {
buf.write('widget:$widget ');
}
for (final package in packages) {
buf.write('package:$package ');
}
buf.write('type:$type ');
return buf.toString().trim();
}
String get filename {
var nameWithoutChars = name.replaceAll(RegExp(r'[^A-Za-z0-9\-\_\ ]'), '');
var nameWithUnderscores = nameWithoutChars.replaceAll(' ', '_');
var snake = util.snakeCase(nameWithUnderscores);
var s = snake.replaceAll('__', '_');
return s;
}
String get shortDescription {
if (description.length < 64) {
return description;
}
return '${description.substring(0, 64)}...';
}
}
/// A screenshot of a sample
@JsonSerializable(anyMap: true, checked: true)
class Screenshot {
final String url;
final String alt;
Screenshot(this.url, this.alt);
factory Screenshot.fromJson(Map<dynamic, dynamic> json) =>
_$ScreenshotFromJson(json);
Map<String, dynamic> toJson() => _$ScreenshotToJson(this);
}
|
samples/web/samples_index/lib/src/data.dart/0
|
{'file_path': 'samples/web/samples_index/lib/src/data.dart', 'repo_id': 'samples', 'token_count': 1490}
|
import 'dart:html';
import 'package:mdc_web/mdc_web.dart';
import 'package:samples_index/browser.dart';
/// The Material text input for searching
late final MDCTextField searchBar;
late final MDCChipSet chipSet;
/// The current set of query parameters that determine how the cards are
/// filtered. e.g. {'search': 'kittens', 'platform': 'ios'}
final queryParams = <String, String>{};
const searchKey = 'search';
const typeKey = 'type';
const platformKey = 'platform';
void main() {
// Initialize Material components
MDCFloatingLabel(querySelector('.mdc-floating-label')!);
searchBar = MDCTextField(querySelector('#search-bar')!);
MDCRipple(querySelector('#clear-button')!);
// Listen for hash changes
window.onHashChange.listen((_) {
queryParams.clear();
queryParams.addAll(parseHash(window.location.hash));
setSearchBarText();
setSelectedChips();
filterCards();
});
// Use a ripple effect on all cards
querySelectorAll('.mdc-card__primary-action').forEach((el) => MDCRipple(el)
// Navigate to the description page when tapped
..listen('click', (e) {
window.location.href = el.attributes['href']!;
}));
// Filter cards on each keypress
searchBar.listen('keydown', (e) async {
await Future(() {});
handleSearch();
});
// Update the URL only when the user is done typing in the search bar
searchBar.listen('change', (e) {
queryParams[searchKey] = searchBar.value!;
updateHash();
});
// Update the hash, cards, and text input when the clear button is pressed
querySelector('#clear-button')!.onClick.listen((e) {
queryParams.remove('search');
updateHash();
setSearchBarText();
filterCards();
});
// Initialize chips
chipSet = MDCChipSet(querySelector('.mdc-chip-set')!);
chipSet.listen('MDCChip:selection', (e) {
// Get the query parameters for this chip
var selectedChipIndex = chipSet.chips.indexWhere((chip) => chip.selected!);
var chipParams = paramsForChip(selectedChipIndex);
// Overwrite query parameters with new ones
queryParams.remove(typeKey);
queryParams.remove(platformKey);
queryParams.addAll(chipParams);
updateHash();
filterCards();
});
// Apply the search from the hash in the URL
queryParams.addAll(parseHash(window.location.hash));
setSearchBarText();
setSelectedChips();
// Filter cards if a filter is being applied
if (queryParams.isNotEmpty) {
filterCards();
}
}
void setSearchBarText() {
var search = queryParams[searchKey] ?? '';
searchBar.value = search;
}
void setSelectedChips() {
var type = queryParams.containsKey(typeKey) ? queryParams[typeKey] : '';
if (type!.isNotEmpty) {
if (type == 'sample') {
chipSet.chips[1].selected = true;
}
}
// Apply the platform from the hash in the URL
var platform =
queryParams.containsKey(platformKey) ? queryParams[platformKey] : '';
if (platform!.isNotEmpty) {
if (platform == 'web') {
chipSet.chips[2].selected = true;
}
}
if (platform.isEmpty && type.isEmpty) {
chipSet.chips[0].selected = true;
}
}
void handleSearch() {
var search = searchBar.value;
queryParams[searchKey] = search!;
filterCards();
}
void updateHash() {
if (queryParams.isEmpty) {
_replaceHash('');
return;
}
_replaceHash(formatHash(queryParams));
}
void _replaceHash(String hash) {
var currentUri = Uri.parse(window.location.href);
window.history
.replaceState(null, '', currentUri.replace(fragment: hash).toString());
}
void filterCards() {
// The search query, e.g. 'kittens platform:web'
var searchQuery = searchQueryFromParams(queryParams);
// Filter out all elements with non-matching search-attrs
var elements = querySelectorAll('[search-attrs]');
for (final element in elements) {
var searchAttributes = element.attributes['search-attrs'];
if (matchesQuery(searchQuery, searchAttributes!)) {
element.hidden = false;
} else {
element.hidden = true;
}
}
}
Map<String, String> paramsForChip(int index) => switch (index) {
1 => {typeKey: 'sample'},
2 => {platformKey: 'web'},
_ => {}
};
|
samples/web/samples_index/web/main.dart/0
|
{'file_path': 'samples/web/samples_index/web/main.dart', 'repo_id': 'samples', 'token_count': 1468}
|
name: scroll_behavior
version: 0.0.1
description: work in progress
author: Remi Rousselet <darky12s@gmail.com>
homepage: https://github.com/rrousselGit/scroll-behavior
environment:
sdk: ">=2.0.0-dev.68.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
|
scroll-behaviors/pubspec.yaml/0
|
{'file_path': 'scroll-behaviors/pubspec.yaml', 'repo_id': 'scroll-behaviors', 'token_count': 105}
|
import 'package:bloc/bloc.dart';
import 'package:sealed_unions/sealed_unions.dart';
enum HelperEvent2 { event2 }
class HelperState2 extends Union2Impl<State1, State2> {
HelperState2._(Union2<State1, State2> union) : super(union);
factory HelperState2.first() => HelperState2._(unions.first(State1()));
factory HelperState2.second() => HelperState2._(unions.second(State2()));
static final Doublet<State1, State2> unions = const Doublet<State1, State2>();
}
class State1 {}
class State2 {}
class HelperBloc2 extends Bloc<HelperEvent2, HelperState2> {
HelperBloc2() : super(HelperState2.first()) {
on<HelperEvent2>((event, emit) {
switch (event) {
case HelperEvent2.event2:
return emit(HelperState2.second());
}
});
}
}
|
sealed_flutter_bloc/test/helpers/helper_bloc2.dart/0
|
{'file_path': 'sealed_flutter_bloc/test/helpers/helper_bloc2.dart', 'repo_id': 'sealed_flutter_bloc', 'token_count': 300}
|
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sealed_flutter_bloc/sealed_flutter_bloc.dart';
import 'helpers/helper_bloc9.dart';
void main() {
group('SealedBlocBuilder9', () {
const targetKey1 = Key('__target1__');
const targetKey2 = Key('__target2__');
const targetKey3 = Key('__target3__');
const targetKey4 = Key('__target4__');
const targetKey5 = Key('__target5__');
const targetKey6 = Key('__target6__');
const targetKey7 = Key('__target7__');
const targetKey8 = Key('__target8__');
const targetKey9 = Key('__target9__');
testWidgets('should render properly', (tester) async {
final bloc = HelperBloc9();
await tester.pumpWidget(
SealedBlocBuilder9<HelperBloc9, HelperState9, State1, State2, State3,
State4, State5, State6, State7, State8, State9>(
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),
(fifth) => const SizedBox(key: targetKey5),
(sixth) => const SizedBox(key: targetKey6),
(seventh) => const SizedBox(key: targetKey7),
(eighth) => const SizedBox(key: targetKey8),
(ninth) => const SizedBox(key: targetKey9),
);
},
),
);
expect(find.byKey(targetKey1), findsOneWidget);
bloc.add(HelperEvent9.event2);
await tester.pumpAndSettle();
expect(find.byKey(targetKey2), findsOneWidget);
bloc.add(HelperEvent9.event3);
await tester.pumpAndSettle();
expect(find.byKey(targetKey3), findsOneWidget);
bloc.add(HelperEvent9.event4);
await tester.pumpAndSettle();
expect(find.byKey(targetKey4), findsOneWidget);
bloc.add(HelperEvent9.event5);
await tester.pumpAndSettle();
expect(find.byKey(targetKey5), findsOneWidget);
bloc.add(HelperEvent9.event6);
await tester.pumpAndSettle();
expect(find.byKey(targetKey6), findsOneWidget);
bloc.add(HelperEvent9.event7);
await tester.pumpAndSettle();
expect(find.byKey(targetKey7), findsOneWidget);
bloc.add(HelperEvent9.event8);
await tester.pumpAndSettle();
expect(find.byKey(targetKey8), findsOneWidget);
bloc.add(HelperEvent9.event9);
await tester.pumpAndSettle();
expect(find.byKey(targetKey9), findsOneWidget);
});
});
}
|
sealed_flutter_bloc/test/sealed_bloc_builder9_test.dart/0
|
{'file_path': 'sealed_flutter_bloc/test/sealed_bloc_builder9_test.dart', 'repo_id': 'sealed_flutter_bloc', 'token_count': 1166}
|
name: service_locator_workshop
description: A sample command-line application.
version: 1.0.0
environment:
sdk: '>=3.0.0 <4.0.0'
dependencies:
meta: ^1.9.1
dev_dependencies:
lints: ^2.1.1
test: ^1.24.4
benchmark_harness: ^2.2.2
get_it: ^7.6.0
ioc_container: ^1.0.12
|
service_locator_workshop/pubspec.yaml/0
|
{'file_path': 'service_locator_workshop/pubspec.yaml', 'repo_id': 'service_locator_workshop', 'token_count': 132}
|
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shopping_ui/data/models/shoe.dart';
import 'package:shopping_ui/presentation/blocs/cart_bloc/cart_bloc.dart';
import 'package:shopping_ui/presentation/providers/cart_provider.dart';
/// A button widget that adds or removes a shoe from the cart.
class AddToCartButton extends StatelessWidget {
/// Constructs an [AddToCartButton] with the given [shoe].
const AddToCartButton(
this.shoe, {
super.key,
});
/// The [Shoe] to add or remove from the cart.
final Shoe shoe;
@override
Widget build(BuildContext context) {
return Selector<CartProvider, List<Shoe>>(
selector: (_, provider) => provider.currentCartItems,
builder: (context, shoes, __) {
return AnimatedSwitcher(
duration: const Duration(
seconds: 2,
),
switchInCurve: Curves.bounceIn,
switchOutCurve: Curves.bounceOut,
child: shoes.contains(
shoe,
)
? ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(
16,
),
backgroundColor: Colors.purple,
shape: const CircleBorder(),
),
onPressed: () {},
child: const Icon(
Icons.check,
size: 18,
),
)
: ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(
16,
),
backgroundColor: Colors.purple,
),
onPressed: () {
context.read<CartBloc>().add(
AddItemToCartEvent(
shoe: shoe,
),
);
},
child: const Text(
'ADD TO CART',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14,
),
),
),
);
},
);
}
}
|
shopping-ui-BLoC/lib/presentation/widgets/add_to_cart_button.dart/0
|
{'file_path': 'shopping-ui-BLoC/lib/presentation/widgets/add_to_cart_button.dart', 'repo_id': 'shopping-ui-BLoC', 'token_count': 1307}
|
export 'weather.dart';
|
simple_weather/lib/service/models/models.dart/0
|
{'file_path': 'simple_weather/lib/service/models/models.dart', 'repo_id': 'simple_weather', 'token_count': 8}
|
import 'package:flutter/material.dart';
import '../../widgets/label.dart';
import './game_modal.dart';
class GameOver extends StatelessWidget {
final VoidCallback restartGame;
final String label;
GameOver({this.restartGame, this.label});
@override
Widget build(ctx) {
return GameModal(
title: Label(label: label, fontSize: 45, fontColor: Color(0xFF94b0c2)),
primaryButtonLabel: 'Restart',
primaryButtonPress: restartGame,
secondaryButtonLabel: 'Home',
secondaryButtonPress: () {
Navigator.of(ctx).pushReplacementNamed("/title");
},
);
}
}
|
snake-chef/snake_chef/lib/game/widgets/game_over.dart/0
|
{'file_path': 'snake-chef/snake_chef/lib/game/widgets/game_over.dart', 'repo_id': 'snake-chef', 'token_count': 226}
|
import 'package:flame/flame.dart';
import 'dart:convert';
import './game/stage.dart';
class StageLoader {
static const STAGE_COUNT = 60;
static Future<Stage> loadStage(int id) async {
final raw = await Flame.assets.readFile("stages/${id ?? 0}.json");
final json = jsonDecode(raw);
return Stage.fromJson(json);
}
}
|
snake-chef/snake_chef/lib/stage_loader.dart/0
|
{'file_path': 'snake-chef/snake_chef/lib/stage_loader.dart', 'repo_id': 'snake-chef', 'token_count': 122}
|
import 'package:authentication_ui/app.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const App());
}
|
speedcode_authentication-ui/lib/main.dart/0
|
{'file_path': 'speedcode_authentication-ui/lib/main.dart', 'repo_id': 'speedcode_authentication-ui', 'token_count': 44}
|
// Copyright (c) 2014, Google Inc. 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 'dart:convert';
import 'dart:io' as io;
import 'dart:math';
import 'package:args/args.dart';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as path;
import 'package:pedantic/pedantic.dart';
import 'package:stagehand/src/common.dart';
import 'package:stagehand/stagehand.dart';
import 'package:usage/usage_io.dart';
import 'version.dart';
const String appName = 'stagehand';
const String appPubInfo = 'https://pub.dev/packages/$appName.json';
// The Google Analytics tracking ID for stagehand.
const String _gaTrackingId = 'UA-26406144-31';
class CliApp {
static final Duration _timeout = const Duration(milliseconds: 500);
final List<Generator> generators;
final CliLogger logger;
GeneratorTarget target;
Analytics analytics;
io.Directory _cwd;
bool _firstScreen = true;
CliApp(this.generators, this.logger, [this.target]) {
assert(generators != null);
assert(logger != null);
analytics = AnalyticsIO(_gaTrackingId, appName, packageVersion)
// These `cdX` values MUST be tightly coordinated with Analytics config
// DO NOT modify unless you're certain what you're doing.
// Contact kevmoo@ if you have questions
..setSessionValue('cd1', io.Platform.operatingSystem)
..setSessionValue('cd3', io.Platform.version.split(' ').first);
generators.sort();
}
io.Directory get cwd => _cwd ?? io.Directory.current;
/// An override for the directory to generate into; public for testing.
set cwd(io.Directory value) {
_cwd = value;
}
Future process(List<String> args) async {
var argParser = _createArgParser();
ArgResults options;
try {
options = argParser.parse(args);
} catch (e, st) {
// FormatException: Could not find an option named "foo".
if (e is FormatException) {
_out('Error: ${e.message}');
return Future.error(ArgError(e.message));
} else {
return Future.error(e, st);
}
}
if (options.wasParsed('analytics')) {
analytics.enabled = options['analytics'];
_out("Analytics ${analytics.enabled ? 'enabled' : 'disabled'}.");
if (analytics.enabled) unawaited(analytics.sendScreenView('analytics'));
return analytics.waitForLastPing(timeout: _timeout);
}
// This hidden option is used so that our build bots don't emit data.
if (options['mock-analytics']) {
analytics = AnalyticsMock();
}
if (options['version']) {
_out('$appName version: $packageVersion');
return http.get(appPubInfo).then((response) {
List versions = jsonDecode(response.body)['versions'];
if (packageVersion != versions.last) {
_out('Version ${versions.last} is available! Run `pub global activate'
' $appName` to get the latest.');
}
}).catchError((e) => null);
}
if (options['help'] || args.isEmpty) {
// Prompt to opt into advanced analytics.
if (analytics.firstRun) {
_out('''
Welcome to Stagehand! We collect anonymous usage statistics and crash reports in
order to improve the tool (http://goo.gl/6wsncI). Would you like to opt-in to
additional analytics to help us improve Stagehand [y/yes/no]?''');
await io.stdout.flush();
var response = io.stdin.readLineSync();
response = response.toLowerCase().trim();
analytics.enabled = (response == 'y' || response == 'yes');
_out('');
}
_screenView(options['help'] ? 'help' : 'main');
_usage(argParser);
return analytics.waitForLastPing(timeout: _timeout);
}
// The `--machine` option emits the list of available generators to stdout
// as JSON. This is useful for tools that don't want to have to parse the
// output of `--help`. It's an undocumented command line flag, and may go
// away or change.
if (options['machine']) {
_screenView('machine');
logger.stdout(_createMachineInfo(generators));
return analytics.waitForLastPing(timeout: _timeout);
}
if (options.rest.isEmpty) {
logger.stderr('No generator specified.\n');
_usage(argParser);
return Future.error(ArgError('no generator specified'));
}
if (options.rest.length >= 2) {
logger.stderr('Error: too many arguments given.\n');
_usage(argParser);
return Future.error(ArgError('invalid generator'));
}
var generatorName = options.rest.first;
var generator = _getGenerator(generatorName);
if (generator == null) {
logger.stderr("'$generatorName' is not a valid generator.\n");
_usage(argParser);
return Future.error(ArgError('invalid generator'));
}
var dir = cwd;
if (!options['override'] && !await _isDirEmpty(dir)) {
logger.stderr(
'The current directory is not empty. Please create a new project directory, or '
'use --override to force generation into the current directory.');
return Future.error(ArgError('project directory not empty'));
}
// Normalize the project name.
var projectName = path.basename(dir.path);
projectName = normalizeProjectName(projectName);
target ??= _DirectoryGeneratorTarget(logger, dir);
_out('Creating $generatorName application `$projectName`:');
_screenView('create');
unawaited(analytics.sendEvent('create', generatorName,
label: generator.description));
String author = options['author'];
if (!options.wasParsed('author')) {
try {
var result = io.Process.runSync('git', ['config', 'user.name']);
if (result.exitCode == 0) author = result.stdout.trim();
} catch (exception) {
// NOOP
}
}
var email = 'email@example.com';
try {
var result = io.Process.runSync('git', ['config', 'user.email']);
if (result.exitCode == 0) email = result.stdout.trim();
} catch (exception) {
// NOOP
}
var vars = {'author': author, 'email': email};
var f = generator.generate(projectName, target, additionalVars: vars);
return f.then((_) {
_out('${generator.numFiles()} files written.');
var message = generator.getInstallInstructions();
if (message != null && message.isNotEmpty) {
message = message.trim();
message = message.split('\n').map((line) => '--> $line').join('\n');
_out('\n$message');
}
}).then((_) {
return analytics.waitForLastPing(timeout: _timeout);
});
}
ArgParser _createArgParser() {
var argParser = ArgParser();
argParser.addFlag('analytics',
negatable: true,
help: 'Opt out of anonymous usage and crash reporting.');
argParser.addFlag('help', abbr: 'h', negatable: false, help: 'Help!');
argParser.addFlag('version',
negatable: false, help: 'Display the version for $appName.');
argParser.addOption('author',
defaultsTo: '<your name>',
help: 'The author name to use for file headers.');
// Really, really generate into the current directory.
argParser.addFlag('override', negatable: false, hide: true);
// Output the list of available projects as JSON to stdout.
argParser.addFlag('machine', negatable: false, hide: true);
// Mock out analytics - for use on our testing bots.
argParser.addFlag('mock-analytics', negatable: false, hide: true);
return argParser;
}
String _createMachineInfo(List<Generator> generators) {
var itor = generators.map((Generator generator) {
var m = {
'name': generator.id,
'label': generator.label,
'description': generator.description,
'categories': generator.categories
};
if (generator.entrypoint != null) {
m['entrypoint'] = generator.entrypoint.path;
}
return m;
});
return json.encode(itor.toList());
}
void _usage(ArgParser argParser) {
_out(
'Stagehand will generate the given application type into the current directory.');
_out('');
_out('usage: $appName <generator-name>');
_out(argParser.usage);
_out('');
_out('Available generators:');
var len = generators.fold(0, (int length, g) => max(length, g.id.length));
generators
.map((g) => ' ${g.id.padRight(len)} - ${g.description}')
.forEach(logger.stdout);
}
Generator _getGenerator(String id) {
return generators.firstWhere((g) => g.id == id, orElse: () => null);
}
void _out(String str) => logger.stdout(str);
void _screenView(String view) {
// If the user hasn't opted in, only send a version check - no page data.
if (!analytics.enabled) view = 'main';
Map<String, String> params;
if (_firstScreen) {
params = {'sc': 'start'};
_firstScreen = false;
}
analytics.sendScreenView(view, parameters: params);
}
/// Returns true if the given directory does not contain non-symlinked,
/// non-hidden subdirectories.
static Future<bool> _isDirEmpty(io.Directory dir) async {
var isHiddenDir = (dir) => path.basename(dir.path).startsWith('.');
return dir
.list(followLinks: false)
.where((entity) => entity is io.Directory)
.where((entity) => !isHiddenDir(entity))
.isEmpty;
}
}
class ArgError implements Exception {
final String message;
ArgError(this.message);
@override
String toString() => message;
}
class CliLogger {
void stdout(String message) => print(message);
void stderr(String message) => print(message);
}
class _DirectoryGeneratorTarget extends GeneratorTarget {
final CliLogger logger;
final io.Directory dir;
_DirectoryGeneratorTarget(this.logger, this.dir) {
dir.createSync();
}
@override
Future createFile(String filePath, List<int> contents) {
var file = io.File(path.join(dir.path, filePath));
logger.stdout(' ${file.path}');
return file
.create(recursive: true)
.then((_) => file.writeAsBytes(contents));
}
}
|
stagehand/lib/src/cli_app.dart/0
|
{'file_path': 'stagehand/lib/src/cli_app.dart', 'repo_id': 'stagehand', 'token_count': 3714}
|
// Generated code. Do not modify.
const packageVersion = '3.3.9';
|
stagehand/lib/src/version.dart/0
|
{'file_path': 'stagehand/lib/src/version.dart', 'repo_id': 'stagehand', 'token_count': 22}
|
import 'dart:io';
import 'package:args/args.dart';
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as io;
// For Google Cloud Run, set _hostname to '0.0.0.0'.
const _hostname = 'localhost';
void main(List<String> args) async {
var parser = ArgParser()..addOption('port', abbr: 'p');
var result = parser.parse(args);
// For Google Cloud Run, we respect the PORT environment variable
var portStr = result['port'] ?? Platform.environment['PORT'] ?? '8080';
var port = int.tryParse(portStr);
if (port == null) {
stdout.writeln('Could not parse port value "$portStr" into a number.');
// 64: command line usage error
exitCode = 64;
return;
}
var handler = const shelf.Pipeline()
.addMiddleware(shelf.logRequests())
.addHandler(_echoRequest);
var server = await io.serve(handler, _hostname, port);
print('Serving at http://${server.address.host}:${server.port}');
}
shelf.Response _echoRequest(shelf.Request request) =>
shelf.Response.ok('Request for "${request.url}"');
|
stagehand/templates/server-shelf/bin/server.dart/0
|
{'file_path': 'stagehand/templates/server-shelf/bin/server.dart', 'repo_id': 'stagehand', 'token_count': 367}
|
name: __projectName__
description: A simple StageXL web app.
# version: 1.0.0
#homepage: https://www.example.com
environment:
sdk: '>=2.8.1 <3.0.0'
dependencies:
stagexl: ^1.4.4
dev_dependencies:
build_runner: ^1.10.0
build_web_compilers: ^2.11.0
pedantic: ^1.9.0
|
stagehand/templates/web-stagexl/pubspec.yaml/0
|
{'file_path': 'stagehand/templates/web-stagexl/pubspec.yaml', 'repo_id': 'stagehand', 'token_count': 124}
|
import 'package:flutter/material.dart';
import 'package:starterproject/services/web_services.dart';
import 'package:starterproject/ui/screens/home_screen.dart';
import 'package:starterproject/ui/widget/circular_bar.dart';
void main() =>runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
// WebServices().fetchPosts();
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomeScreen(),
);
}
}
|
starter_project/lib/main.dart/0
|
{'file_path': 'starter_project/lib/main.dart', 'repo_id': 'starter_project', 'token_count': 224}
|
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
/// IO version of websocket implementation
/// Used in Flutter mobile version
WebSocketChannel connectWebSocket(String url, {Iterable<String> protocols}) =>
IOWebSocketChannel.connect(url, protocols: protocols);
|
stream-chat-flutter/packages/stream_chat/lib/src/api/web_socket_channel_io.dart/0
|
{'file_path': 'stream-chat-flutter/packages/stream_chat/lib/src/api/web_socket_channel_io.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 90}
|
import 'package:json_annotation/json_annotation.dart';
import 'package:stream_chat/src/models/attachment.dart';
import 'package:stream_chat/src/models/reaction.dart';
import 'package:stream_chat/src/models/serialization.dart';
import 'package:stream_chat/src/models/user.dart';
import 'package:uuid/uuid.dart';
part 'message.g.dart';
class _PinExpires {
const _PinExpires();
}
const _pinExpires = _PinExpires();
/// Enum defining the status of a sending message
enum MessageSendingStatus {
/// Message is being sent
sending,
/// Message is being updated
updating,
/// Message is being deleted
deleting,
/// Message failed to send
failed,
/// Message failed to updated
// ignore: constant_identifier_names
failed_update,
/// Message failed to delete
// ignore: constant_identifier_names
failed_delete,
/// Message correctly sent
sent,
}
/// The class that contains the information about a message
@JsonSerializable()
class Message {
/// Constructor used for json serialization
Message({
String id,
this.text,
this.type,
this.attachments,
this.mentionedUsers,
this.silent,
this.shadowed,
this.reactionCounts,
this.reactionScores,
this.latestReactions,
this.ownReactions,
this.parentId,
this.quotedMessage,
this.quotedMessageId,
this.replyCount = 0,
this.threadParticipants,
this.showInChannel,
this.command,
this.createdAt,
this.updatedAt,
this.user,
this.pinned = false,
this.pinnedAt,
DateTime pinExpires,
this.pinnedBy,
this.extraData,
this.deletedAt,
this.status = MessageSendingStatus.sent,
this.skipPush,
}) : id = id ?? Uuid().v4(),
pinExpires = pinExpires?.toUtc();
/// Create a new instance from a json
factory Message.fromJson(Map<String, dynamic> json) => _$MessageFromJson(
Serialization.moveToExtraDataFromRoot(json, topLevelFields));
/// The message ID. This is either created by Stream or set client side when
/// the message is added.
final String id;
/// The text of this message
final String text;
/// The status of a sending message
@JsonKey(ignore: true)
final MessageSendingStatus status;
/// The message type
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final String type;
/// The list of attachments, either provided by the user or generated from a
/// command or as a result of URL scraping.
@JsonKey(includeIfNull: false)
final List<Attachment> attachments;
/// The list of user mentioned in the message
@JsonKey(toJson: Serialization.userIds)
final List<User> mentionedUsers;
/// A map describing the count of number of every reaction
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final Map<String, int> reactionCounts;
/// A map describing the count of score of every reaction
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final Map<String, int> reactionScores;
/// The latest reactions to the message created by any user.
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final List<Reaction> latestReactions;
/// The reactions added to the message by the current user.
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final List<Reaction> ownReactions;
/// The ID of the parent message, if the message is a thread reply.
final String parentId;
/// A quoted reply message
@JsonKey(toJson: Serialization.readOnly)
final Message quotedMessage;
/// The ID of the quoted message, if the message is a quoted reply.
final String quotedMessageId;
/// Reserved field indicating the number of replies for this message.
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final int replyCount;
/// Reserved field indicating the thread participants for this message.
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final List<User> threadParticipants;
/// Check if this message needs to show in the channel.
final bool showInChannel;
/// If true the message is silent
final bool silent;
/// If true the message will not send a push notification
final bool skipPush;
/// If true the message is shadowed
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final bool shadowed;
/// A used command name.
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final String command;
/// Reserved field indicating when the message was created.
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final DateTime createdAt;
/// Reserved field indicating when the message was updated last time.
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final DateTime updatedAt;
/// User who sent the message
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final User user;
/// If true the message is pinned
final bool pinned;
/// Reserved field indicating when the message was pinned
@JsonKey(toJson: Serialization.readOnly)
final DateTime pinnedAt;
/// Reserved field indicating when the message will expire
///
/// if `null` message has no expiry
final DateTime pinExpires;
/// Reserved field indicating who pinned the message
@JsonKey(toJson: Serialization.readOnly)
final User pinnedBy;
/// Message custom extraData
@JsonKey(includeIfNull: false)
final Map<String, dynamic> extraData;
/// True if the message is a system info
bool get isSystem => type == 'system';
/// True if the message has been deleted
bool get isDeleted => type == 'deleted';
/// True if the message is ephemeral
bool get isEphemeral => type == 'ephemeral';
/// Reserved field indicating when the message was deleted.
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final DateTime deletedAt;
/// Known top level fields.
/// Useful for [Serialization] methods.
static const topLevelFields = [
'id',
'text',
'type',
'silent',
'attachments',
'latest_reactions',
'shadowed',
'own_reactions',
'mentioned_users',
'reaction_counts',
'reaction_scores',
'silent',
'parent_id',
'quoted_message',
'quoted_message_id',
'reply_count',
'thread_participants',
'show_in_channel',
'command',
'created_at',
'updated_at',
'deleted_at',
'user',
'pinned',
'pinned_at',
'pin_expires',
'pinned_by',
'skip_push',
];
/// Serialize to json
Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot(
_$MessageToJson(this), topLevelFields);
/// Creates a copy of [Message] with specified attributes overridden.
Message copyWith({
String id,
String text,
String type,
List<Attachment> attachments,
List<User> mentionedUsers,
Map<String, int> reactionCounts,
Map<String, int> reactionScores,
List<Reaction> latestReactions,
List<Reaction> ownReactions,
String parentId,
Message quotedMessage,
String quotedMessageId,
int replyCount,
List<User> threadParticipants,
bool showInChannel,
bool shadowed,
bool silent,
String command,
DateTime createdAt,
DateTime updatedAt,
DateTime deletedAt,
User user,
bool pinned,
DateTime pinnedAt,
Object pinExpires = _pinExpires,
User pinnedBy,
Map<String, dynamic> extraData,
MessageSendingStatus status,
bool skipPush,
}) {
assert(() {
if (pinExpires is! DateTime &&
pinExpires != null &&
pinExpires is! _PinExpires) {
throw ArgumentError('`pinExpires` can only be set as DateTime or null');
}
return true;
}(), 'Validate type for pinExpires');
return Message(
id: id ?? this.id,
text: text ?? this.text,
type: type ?? this.type,
attachments: attachments ?? this.attachments,
mentionedUsers: mentionedUsers ?? this.mentionedUsers,
reactionCounts: reactionCounts ?? this.reactionCounts,
reactionScores: reactionScores ?? this.reactionScores,
latestReactions: latestReactions ?? this.latestReactions,
ownReactions: ownReactions ?? this.ownReactions,
parentId: parentId ?? this.parentId,
quotedMessage: quotedMessage ?? this.quotedMessage,
quotedMessageId: quotedMessageId ?? this.quotedMessageId,
replyCount: replyCount ?? this.replyCount,
threadParticipants: threadParticipants ?? this.threadParticipants,
showInChannel: showInChannel ?? this.showInChannel,
command: command ?? this.command,
createdAt: createdAt ?? this.createdAt,
silent: silent ?? this.silent,
extraData: extraData ?? this.extraData,
user: user ?? this.user,
shadowed: shadowed ?? this.shadowed,
updatedAt: updatedAt ?? this.updatedAt,
deletedAt: deletedAt ?? this.deletedAt,
status: status ?? this.status,
pinned: pinned ?? this.pinned,
pinnedAt: pinnedAt ?? this.pinnedAt,
pinnedBy: pinnedBy ?? this.pinnedBy,
pinExpires: pinExpires == _pinExpires ? this.pinExpires : pinExpires,
skipPush: skipPush ?? this.skipPush,
);
}
/// Returns a new [Message] that is a combination of this message and the
/// given [other] message.
Message merge(Message other) {
if (other == null) return this;
return copyWith(
id: other.id,
text: other.text,
type: other.type,
attachments: other.attachments,
mentionedUsers: other.mentionedUsers,
reactionCounts: other.reactionCounts,
reactionScores: other.reactionScores,
latestReactions: other.latestReactions,
ownReactions: other.ownReactions,
parentId: other.parentId,
quotedMessage: other.quotedMessage,
quotedMessageId: other.quotedMessageId,
replyCount: other.replyCount,
threadParticipants: other.threadParticipants,
showInChannel: other.showInChannel,
command: other.command,
createdAt: other.createdAt,
silent: other.silent,
extraData: other.extraData,
user: other.user,
shadowed: other.shadowed,
updatedAt: other.updatedAt,
deletedAt: other.deletedAt,
status: other.status,
pinned: other.pinned,
pinnedAt: other.pinnedAt,
pinExpires: other.pinExpires,
pinnedBy: other.pinnedBy,
);
}
}
/// A translated message
/// It has an additional property called [i18n]
@JsonSerializable()
class TranslatedMessage extends Message {
/// Constructor used for json serialization
TranslatedMessage(this.i18n);
/// Create a new instance from a json
factory TranslatedMessage.fromJson(Map<String, dynamic> json) =>
_$TranslatedMessageFromJson(
Serialization.moveToExtraDataFromRoot(json, topLevelFields),
);
/// A Map of
final Map<String, String> i18n;
/// Known top level fields.
/// Useful for [Serialization] methods.
static final topLevelFields = [
'i18n',
...Message.topLevelFields,
];
/// Serialize to json
@override
Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot(
_$TranslatedMessageToJson(this),
topLevelFields,
);
}
|
stream-chat-flutter/packages/stream_chat/lib/src/models/message.dart/0
|
{'file_path': 'stream-chat-flutter/packages/stream_chat/lib/src/models/message.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 3811}
|
import 'package:stream_chat/src/platform_detector/platform_detector.dart';
/// Version running on web
PlatformType get currentPlatform => PlatformType.web;
|
stream-chat-flutter/packages/stream_chat/lib/src/platform_detector/platform_detector_web.dart/0
|
{'file_path': 'stream-chat-flutter/packages/stream_chat/lib/src/platform_detector/platform_detector_web.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 43}
|
import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/models/device.dart';
void main() {
group('src/models/device', () {
const jsonExample = r'''{
"id": "device-id",
"push_provider": "push-provider"
}''';
test('should parse json correctly', () {
final device = Device.fromJson(json.decode(jsonExample));
expect(device.id, 'device-id');
expect(device.pushProvider, 'push-provider');
});
test('should serialize to json correctly', () {
final device = Device(id: 'device-id', pushProvider: 'push-provider');
expect(
device.toJson(),
{
'id': 'device-id',
'push_provider': 'push-provider',
},
);
});
});
}
|
stream-chat-flutter/packages/stream_chat/test/src/models/device_test.dart/0
|
{'file_path': 'stream-chat-flutter/packages/stream_chat/test/src/models/device_test.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 325}
|
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:stream_chat_flutter/src/stream_svg_icon.dart';
import '../stream_chat_flutter.dart';
extension on Duration {
String format() {
final s = '$this'.split('.')[0].padLeft(8, '0');
if (s.startsWith('00:')) {
return s.replaceFirst('00:', '');
}
return s;
}
}
class MediaListView extends StatefulWidget {
final List<String> selectedIds;
final void Function(AssetEntity media) onSelect;
const MediaListView({
Key key,
this.selectedIds = const [],
this.onSelect,
}) : super(key: key);
@override
_MediaListViewState createState() => _MediaListViewState();
}
class _MediaListViewState extends State<MediaListView> {
final _media = <AssetEntity>[];
final ScrollController _scrollController = ScrollController();
int _currentPage = 0;
@override
Widget build(BuildContext context) {
return LazyLoadScrollView(
onEndOfPage: () async => _getMedia(),
child: GridView.builder(
itemCount: _media.length,
controller: _scrollController,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
itemBuilder: (
context,
position,
) {
final media = _media.elementAt(position);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 1.0, vertical: 1.0),
child: InkWell(
onTap: () {
if (widget.onSelect != null) {
widget.onSelect(media);
}
},
child: Stack(
children: [
AspectRatio(
aspectRatio: 1.0,
child: FadeInImage(
fadeInDuration: Duration(milliseconds: 300),
placeholder: AssetImage(
'images/placeholder.png',
package: 'stream_chat_flutter',
),
image: MediaThumbnailProvider(
media: media,
),
fit: BoxFit.cover,
),
),
Positioned.fill(
child: IgnorePointer(
child: AnimatedOpacity(
duration: Duration(milliseconds: 300),
opacity: widget.selectedIds.any((id) => id == media.id)
? 1.0
: 0.0,
child: Container(
color: StreamChatTheme.of(context)
.colorTheme
.black
.withOpacity(0.5),
alignment: Alignment.topRight,
padding: const EdgeInsets.only(
top: 8,
right: 8,
),
child: CircleAvatar(
radius: 12,
backgroundColor:
StreamChatTheme.of(context).colorTheme.white,
child: StreamSvgIcon.check(
size: 24,
color:
StreamChatTheme.of(context).colorTheme.black,
),
),
),
),
),
),
if (media.type == AssetType.video) ...[
Positioned(
left: 8,
bottom: 10,
child: SvgPicture.asset(
'svgs/video_call_icon.svg',
package: 'stream_chat_flutter',
),
),
Positioned(
right: 4,
bottom: 10,
child: Text(
media.videoDuration.format(),
style: TextStyle(
color: StreamChatTheme.of(context).colorTheme.white,
),
),
),
]
],
),
),
);
},
),
);
}
@override
void initState() {
super.initState();
_getMedia();
}
void _getMedia() async {
final assetList = await PhotoManager.getAssetPathList(
hasAll: true,
).then((value) {
if (value?.isNotEmpty == true) {
return value.singleWhere((element) => element.isAll);
}
});
if (assetList == null) {
return;
}
final media = await assetList.getAssetListPaged(_currentPage, 50);
if (media.isNotEmpty) {
setState(() {
_media.addAll(media);
});
}
++_currentPage;
}
}
class MediaThumbnailProvider extends ImageProvider<MediaThumbnailProvider> {
const MediaThumbnailProvider({
@required this.media,
}) : assert(media != null);
final AssetEntity media;
@override
ImageStreamCompleter load(key, decode) {
return MultiFrameImageStreamCompleter(
codec: _loadAsync(key, decode),
scale: 1.0,
informationCollector: () sync* {
yield ErrorDescription('Id: ${media?.id}');
},
);
}
Future<ui.Codec> _loadAsync(
MediaThumbnailProvider key, DecoderCallback decode) async {
assert(key == this);
final bytes = await media.thumbData;
if (bytes?.isNotEmpty != true) return null;
return await decode(bytes);
}
@override
Future<MediaThumbnailProvider> obtainKey(ImageConfiguration configuration) {
return SynchronousFuture<MediaThumbnailProvider>(this);
}
@override
bool operator ==(dynamic other) {
if (other.runtimeType != runtimeType) return false;
final MediaThumbnailProvider typedOther = other;
return media?.id == typedOther.media?.id;
}
@override
int get hashCode => media?.id?.hashCode ?? 0;
@override
String toString() => '$runtimeType("${media?.id}")';
}
|
stream-chat-flutter/packages/stream_chat_flutter/lib/src/media_list_view.dart/0
|
{'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/lib/src/media_list_view.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 3391}
|
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_portal/flutter_portal.dart';
import 'package:stream_chat_flutter/src/stream_chat_theme.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart';
/// Widget used to provide information about the chat to the widget tree
///
/// class MyApp extends StatelessWidget {
/// final StreamChatClient client;
///
/// MyApp(this.client);
///
/// @override
/// Widget build(BuildContext context) {
/// return MaterialApp(
/// home: Container(
/// child: StreamChat(
/// client: client,
/// child: ChannelListPage(),
/// ),
/// ),
/// );
/// }
/// }
///
/// Use [StreamChat.of] to get the current [StreamChatState] instance.
class StreamChat extends StatefulWidget {
final StreamChatClient client;
final Widget child;
final StreamChatThemeData streamChatThemeData;
/// The amount of time that will pass before disconnecting the client in the background
final Duration backgroundKeepAlive;
/// Handler called whenever the [client] receives a new [Event] while the app
/// is in background. Can be used to display various notifications depending
/// upon the [Event.type]
final EventHandler onBackgroundEventReceived;
StreamChat({
Key key,
@required this.client,
@required this.child,
this.streamChatThemeData,
this.onBackgroundEventReceived,
this.backgroundKeepAlive = const Duration(minutes: 1),
}) : super(
key: key,
);
@override
StreamChatState createState() => StreamChatState();
/// Use this method to get the current [StreamChatState] instance
static StreamChatState of(BuildContext context) {
StreamChatState streamChatState;
streamChatState = context.findAncestorStateOfType<StreamChatState>();
if (streamChatState == null) {
throw Exception(
'You must have a StreamChat widget at the top of your widget tree');
}
return streamChatState;
}
}
/// The current state of the StreamChat widget
class StreamChatState extends State<StreamChat> {
StreamChatClient get client => widget.client;
@override
Widget build(BuildContext context) {
final theme = _getTheme(context, widget.streamChatThemeData);
return Portal(
child: StreamChatTheme(
data: theme,
child: Builder(
builder: (context) {
final materialTheme = Theme.of(context);
final streamTheme = StreamChatTheme.of(context);
return Theme(
data: materialTheme.copyWith(
primaryIconTheme: streamTheme.primaryIconTheme,
accentColor: streamTheme.colorTheme.accentBlue,
scaffoldBackgroundColor: streamTheme.colorTheme.white,
),
child: StreamChatCore(
client: client,
onBackgroundEventReceived: widget.onBackgroundEventReceived,
backgroundKeepAlive: widget.backgroundKeepAlive,
child: widget.child,
),
);
},
),
),
);
}
StreamChatThemeData _getTheme(
BuildContext context,
StreamChatThemeData themeData,
) {
final defaultTheme = StreamChatThemeData.getDefaultTheme(Theme.of(context));
return defaultTheme.merge(themeData) ?? themeData;
}
/// The current user
User get user => widget.client.state.user;
/// The current user as a stream
Stream<User> get userStream => widget.client.state.userStream;
@override
void initState() {
super.initState();
}
}
|
stream-chat-flutter/packages/stream_chat_flutter/lib/src/stream_chat.dart/0
|
{'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/lib/src/stream_chat.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 1344}
|
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:stream_chat_flutter/src/reaction_bubble.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'mocks.dart';
void main() {
testWidgets(
'it should show no reactions',
(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: StreamChatTheme(
data: StreamChatThemeData(),
child: Container(
child: ReactionBubble(
reactions: [],
borderColor: Colors.black,
backgroundColor: Colors.white,
maskColor: Colors.white,
),
),
),
),
);
expect(find.byKey(Key('StreamSvgIcon-Icon_thumbs_up_reaction.svg')),
findsNothing);
},
);
testWidgets(
'it should show a like',
(WidgetTester tester) async {
final client = MockClient();
final clientState = MockClientState();
final themeData = ThemeData();
when(client.state).thenReturn(clientState);
when(clientState.user).thenReturn(OwnUser(id: 'user-id'));
await tester.pumpWidget(
MaterialApp(
theme: themeData,
home: StreamChat(
client: client,
streamChatThemeData: StreamChatThemeData.getDefaultTheme(themeData),
child: Container(
child: ReactionBubble(
reactions: [
Reaction(
type: 'like',
user: User(id: 'test'),
),
],
borderColor: Colors.black,
backgroundColor: Colors.white,
maskColor: Colors.white,
),
),
),
),
);
expect(find.byKey(Key('StreamSvgIcon-Icon_thumbs_up_reaction.svg')),
findsOneWidget);
},
);
testWidgets(
'it should show two reactions',
(WidgetTester tester) async {
final client = MockClient();
final clientState = MockClientState();
final themeData = ThemeData();
when(client.state).thenReturn(clientState);
when(clientState.user).thenReturn(OwnUser(id: 'user-id'));
await tester.pumpWidget(
MaterialApp(
theme: themeData,
home: StreamChat(
client: client,
streamChatThemeData: StreamChatThemeData.getDefaultTheme(themeData),
child: Container(
child: ReactionBubble(
reactions: [
Reaction(
type: 'like',
user: User(id: 'test'),
),
Reaction(
type: 'love',
user: User(id: 'test'),
),
],
borderColor: Colors.black,
backgroundColor: Colors.white,
maskColor: Colors.white,
),
),
),
),
);
expect(find.byKey(Key('StreamSvgIcon-Icon_thumbs_up_reaction.svg')),
findsOneWidget);
expect(find.byKey(Key('StreamSvgIcon-Icon_love_reaction.svg')),
findsOneWidget);
},
);
}
|
stream-chat-flutter/packages/stream_chat_flutter/test/src/reaction_bubble_test.dart/0
|
{'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/test/src/reaction_bubble_test.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 1697}
|
import 'dart:async';
import 'package:fake_async/fake_async.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart';
import 'package:mockito/mockito.dart';
import 'mocks.dart';
class MockShowLocalNotifications extends Mock {
void call(Event event);
}
void main() {
testWidgets(
'StreamChatCore.of(context) should throw an exception',
(WidgetTester tester) async {
await tester.pumpWidget(
Builder(
builder: (context) {
expect(() => StreamChatCore.of(context), throwsException);
return Container();
},
),
);
},
);
testWidgets(
'StreamChatCore.of(context) should return the StreamChatCore ancestor',
(WidgetTester tester) async {
final client = MockClient();
await tester.pumpWidget(
StreamChatCore(
client: client,
child: Builder(
builder: (context) {
final sc = StreamChatCore.of(context);
expect(sc, isNotNull);
return Container();
},
),
),
);
},
);
testWidgets(
'StreamChatCore.of(context).client should return the client',
(WidgetTester tester) async {
final client = MockClient();
final clientState = MockClientState();
when(client.state).thenReturn(clientState);
when(clientState.user).thenReturn(
OwnUser(
id: 'test',
),
);
final userStream = Stream<OwnUser>.value(
OwnUser(
id: 'test',
),
);
when(clientState.userStream).thenAnswer(
(_) => userStream,
);
await tester.pumpWidget(
StreamChatCore(
client: client,
child: Builder(
builder: (context) {
final sc = StreamChatCore.of(context);
expect(sc.client, client);
expect(sc.user, client.state.user);
expect(sc.userStream, userStream);
return Container();
},
),
),
);
},
);
testWidgets(
'StreamChatCore should disconnect on background',
(WidgetTester tester) async {
fakeAsync((_async) {
final client = MockClient();
final clientState = MockClientState();
final channel = MockChannel();
when(client.state).thenReturn(clientState);
when(clientState.user).thenReturn(
OwnUser(
id: 'test',
),
);
final showLocalNotificationMock = MockShowLocalNotifications().call;
final eventStreamController = StreamController<Event>();
when(client.on()).thenAnswer((_) => eventStreamController.stream);
when(client.channel('test', id: 'testid')).thenReturn(channel);
final scKey = GlobalKey<StreamChatCoreState>();
tester.pumpWidget(
StreamChatCore(
key: scKey,
client: client,
onBackgroundEventReceived: showLocalNotificationMock,
backgroundKeepAlive: const Duration(seconds: 4),
child: Builder(
builder: (context) {
return Container();
},
),
),
);
final sc = scKey.currentState;
sc.didChangeAppLifecycleState(AppLifecycleState.paused);
_async.elapse(Duration(seconds: 5));
verify(client.disconnect()).called(1);
eventStreamController.close();
});
},
);
testWidgets(
'StreamChatCore should handle notifications when on background and connected',
(WidgetTester tester) async {
final client = MockClient();
final clientState = MockClientState();
final channel = MockChannel();
when(client.state).thenReturn(clientState);
when(clientState.user).thenReturn(
OwnUser(
id: 'test',
),
);
final showLocalNotificationMock = MockShowLocalNotifications().call;
final eventStreamController = StreamController<Event>();
when(client.on()).thenAnswer((_) => eventStreamController.stream);
when(client.channel('test', id: 'testid')).thenReturn(channel);
final scKey = GlobalKey<StreamChatCoreState>();
await tester.pumpWidget(
StreamChatCore(
key: scKey,
client: client,
onBackgroundEventReceived: showLocalNotificationMock,
backgroundKeepAlive: const Duration(seconds: 4),
child: Builder(
builder: (context) {
return Container();
},
),
),
);
final sc = scKey.currentState;
sc.didChangeAppLifecycleState(AppLifecycleState.paused);
final event = Event(
type: EventType.messageNew,
message: Message(text: 'hey'),
channelType: 'test',
channelId: 'testid',
user: User(id: 'other user'),
);
eventStreamController.add(event);
await untilCalled(showLocalNotificationMock(event));
verify(showLocalNotificationMock(event)).called(1);
eventStreamController.close();
},
);
}
|
stream-chat-flutter/packages/stream_chat_flutter_core/test/stream_chat_core_test.dart/0
|
{'file_path': 'stream-chat-flutter/packages/stream_chat_flutter_core/test/stream_chat_core_test.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 2292}
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'member_dao.dart';
// **************************************************************************
// DaoGenerator
// **************************************************************************
mixin _$MemberDaoMixin on DatabaseAccessor<MoorChatDatabase> {
$MembersTable get members => attachedDatabase.members;
$UsersTable get users => attachedDatabase.users;
}
|
stream-chat-flutter/packages/stream_chat_persistence/lib/src/dao/member_dao.g.dart/0
|
{'file_path': 'stream-chat-flutter/packages/stream_chat_persistence/lib/src/dao/member_dao.g.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 97}
|
import 'package:moor/moor_web.dart';
import 'package:stream_chat_persistence/src/stream_chat_persistence_client.dart';
import 'package:stream_chat_persistence/src/db/moor_chat_database.dart';
/// A Helper class to construct new instances of [MoorChatDatabase] specifically
/// for Web applications
class SharedDB {
/// Returns a new instance of [WebDatabase] created using [userId].
///
/// Generally used with [ConnectionMode.regular].
static Future<WebDatabase> constructDatabase(
String userId, {
bool logStatements = false,
bool persistOnDisk = true, // ignored on web
}) async {
final dbName = 'db_$userId';
return WebDatabase(dbName, logStatements: logStatements);
}
/// Returns a new instance of [MoorChatDatabase] creating using the
/// default constructor.
///
/// Generally used with [ConnectionMode.background].
static MoorChatDatabase constructMoorChatDatabase(
String userId, {
bool logStatements = false,
}) {
final dbName = 'db_$userId';
return MoorChatDatabase(dbName, logStatements: logStatements);
}
}
|
stream-chat-flutter/packages/stream_chat_persistence/lib/src/db/shared/web_db.dart/0
|
{'file_path': 'stream-chat-flutter/packages/stream_chat_persistence/lib/src/db/shared/web_db.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 333}
|
include: package:very_good_analysis/analysis_options.yaml
|
stream_listener/packages/flutter_stream_listener/example/analysis_options.yaml/0
|
{'file_path': 'stream_listener/packages/flutter_stream_listener/example/analysis_options.yaml', 'repo_id': 'stream_listener', 'token_count': 16}
|
import 'dart:async';
/// Mixin which enables multiple stream subscriptions
/// and exposes overrides for [onData], [onError], and [onDone] callbacks.
mixin StreamListenerMixin {
final _subscriptions = <StreamSubscription<dynamic>>[];
/// Invokes [Stream.listen] on the provided [Stream]
/// and propagates emitted data to the
/// [onData], [onError], and [onDone] methods.
///
/// Note: All [StreamListenerMixin] instances which
/// invoke [subscribe] must also invoke [cancel] in order to
/// cancel all pending `StreamSubscriptions`.
void subscribe(Stream stream) {
_subscriptions.add(stream.listen(
(data) => onData(stream, data),
onDone: () => onDone(stream),
onError: (error, stackTrace) => onError(stream, error, stackTrace),
cancelOnError: cancelOnError(stream),
));
}
/// Invoked for each data event from the `stream`.
void onData(Stream stream, dynamic data) {}
/// Invoked on stream errors with the error object and possibly a stack trace.
void onError(Stream stream, dynamic error, StackTrace stackTrace) {}
/// Invoked if the stream closes.
void onDone(Stream stream) {}
/// Flag to determine whether or not to cancel the
/// subscription if an error is emitted.
/// Defaults to false.
bool cancelOnError(Stream stream) => false;
/// Cancels all existing `StreamSubscriptions`.
/// If [subscribe] is invoked, then [cancel] should
/// also be invoked when subscriptions are no longer needed.
void cancel() {
for (final s in _subscriptions) {
s.cancel();
}
_subscriptions.clear();
}
}
|
stream_listener/packages/stream_listener/lib/src/stream_listener_mixin.dart/0
|
{'file_path': 'stream_listener/packages/stream_listener/lib/src/stream_listener_mixin.dart', 'repo_id': 'stream_listener', 'token_count': 494}
|
import 'dart:async';
import 'package:flame/components.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class CameraDebugger extends RectangleComponent {
CameraDebugger({
super.position,
}) : super(
paint: Paint()..color = Colors.pink.withOpacity(0.5),
size: Vector2.all(150),
priority: 100,
anchor: Anchor.center,
);
final _direction = Vector2.zero();
late final TextComponent _text;
double _speed = 300;
double get speed => _speed;
@override
void update(double dt) {
super.update(dt);
position += _direction * _speed * dt;
_text.text = 'X: ${position.x.toStringAsFixed(2)}'
'\nY: ${position.y.toStringAsFixed(2)}'
'\nSpeed: $speed';
}
@override
FutureOr<void> onLoad() async {
await super.onLoad();
add(
_text = TextComponent(
anchor: Anchor.center,
position: size / 2,
),
);
add(
KeyboardListenerComponent(
keyDown: {
LogicalKeyboardKey.keyW: (_) {
_direction.y = -1;
return false;
},
LogicalKeyboardKey.keyS: (_) {
_direction.y = 1;
return false;
},
LogicalKeyboardKey.keyA: (_) {
_direction.x = -1;
return false;
},
LogicalKeyboardKey.keyD: (_) {
_direction.x = 1;
return false;
},
LogicalKeyboardKey.keyM: (_) {
_speed = 900;
return false;
},
},
keyUp: {
LogicalKeyboardKey.keyW: (_) {
if (_direction.y == -1) {
_direction.y = 0;
}
return false;
},
LogicalKeyboardKey.keyS: (_) {
if (_direction.y == 1) {
_direction.y = 0;
}
return false;
},
LogicalKeyboardKey.keyA: (_) {
if (_direction.x == -1) {
_direction.x = 0;
}
return false;
},
LogicalKeyboardKey.keyD: (_) {
if (_direction.x == 1) {
_direction.x = 0;
}
return false;
},
LogicalKeyboardKey.keyM: (_) {
_speed = 300;
return false;
},
},
),
);
}
}
|
super_dash/lib/game/components/camera_debugger.dart/0
|
{'file_path': 'super_dash/lib/game/components/camera_debugger.dart', 'repo_id': 'super_dash', 'token_count': 1291}
|
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:super_dash/game/bloc/game_bloc.dart';
import 'package:super_dash/gen/assets.gen.dart';
import 'package:super_dash/l10n/l10n.dart';
class ScoreLabel extends StatelessWidget {
const ScoreLabel({super.key});
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final textTheme = Theme.of(context).textTheme;
final score = context.select(
(GameBloc bloc) => bloc.state.score,
);
return SafeArea(
child: TraslucentBackground(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(30),
border: Border.all(
color: Colors.white,
),
gradient: const [
Color(0xFFEAFFFE),
Color(0xFFC9D9F1),
],
child: Padding(
padding: const EdgeInsets.all(10),
child: Row(
children: [
Assets.images.trophy.image(
width: 40,
height: 40,
),
const SizedBox(width: 10),
Text(
l10n.gameScoreLabel(score),
style: textTheme.titleLarge?.copyWith(
color: const Color(0xFF4D5B92),
),
),
],
),
),
),
);
}
}
|
super_dash/lib/game/widgets/score_label.dart/0
|
{'file_path': 'super_dash/lib/game/widgets/score_label.dart', 'repo_id': 'super_dash', 'token_count': 719}
|
export 'bottom_bar.dart';
export 'game_intro_buttons.dart';
|
super_dash/lib/game_intro/widgets/widgets.dart/0
|
{'file_path': 'super_dash/lib/game_intro/widgets/widgets.dart', 'repo_id': 'super_dash', 'token_count': 24}
|
export 'atlases_view.dart';
export 'map_tester_view.dart';
|
super_dash/lib/map_tester/view/view.dart/0
|
{'file_path': 'super_dash/lib/map_tester/view/view.dart', 'repo_id': 'super_dash', 'token_count': 24}
|
export 'score_overview_page.dart';
|
super_dash/lib/score/score_overview/view/view.dart/0
|
{'file_path': 'super_dash/lib/score/score_overview/view/view.dart', 'repo_id': 'super_dash', 'token_count': 13}
|
/// A library for building UI components for the game.
library app_ui;
export 'src/layout/layout.dart';
export 'src/routes/routes.dart';
export 'src/theme/theme.dart';
export 'src/widgets/widgets.dart';
|
super_dash/packages/app_ui/lib/app_ui.dart/0
|
{'file_path': 'super_dash/packages/app_ui/lib/app_ui.dart', 'repo_id': 'super_dash', 'token_count': 73}
|
name: app_ui
description: App UI Package of the Super Dash game.
version: 0.1.0+1
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
flutter: ">=3.10.0"
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^1.0.0
very_good_analysis: ^5.1.0
flutter:
fonts:
- family: Google Sans
fonts:
- asset: assets/fonts/GoogleSansText-Regular.ttf
- asset: assets/fonts/GoogleSansText-Bold.ttf
weight: 700
|
super_dash/packages/app_ui/pubspec.yaml/0
|
{'file_path': 'super_dash/packages/app_ui/pubspec.yaml', 'repo_id': 'super_dash', 'token_count': 229}
|
/// A repository to access leaderboard data in Firebase Cloud Firestore.
library leaderboard_repository;
export 'src/leaderboard_repository.dart';
export 'src/models/models.dart';
|
super_dash/packages/leaderboard_repository/lib/leaderboard_repository.dart/0
|
{'file_path': 'super_dash/packages/leaderboard_repository/lib/leaderboard_repository.dart', 'repo_id': 'super_dash', 'token_count': 53}
|
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:super_dash/game/bloc/game_bloc.dart';
void main() {
group('GameState', () {
test(
'initial state score is 0',
() => expect(GameState.initial().score, isZero),
);
test('supports value comparisons', () {
expect(GameState.initial(), GameState.initial());
});
test('returns same object when no properties are passed', () {
expect(GameState.initial().copyWith(), GameState.initial());
});
test('returns object with updated score when score is passed', () {
expect(
GameState.initial().copyWith(score: 100),
GameState(score: 100, currentLevel: 1, currentSection: 0),
);
});
test(
'returns object with updated scocurrentLevelre when score is passed',
() {
expect(
GameState.initial().copyWith(currentLevel: 2),
GameState(score: 0, currentLevel: 2, currentSection: 0),
);
},
);
test('returns object with updated currentSection when score is passed', () {
expect(
GameState.initial().copyWith(currentSection: 3),
GameState(score: 0, currentLevel: 1, currentSection: 3),
);
});
});
}
|
super_dash/test/game/bloc/game_state_test.dart/0
|
{'file_path': 'super_dash/test/game/bloc/game_state_test.dart', 'repo_id': 'super_dash', 'token_count': 486}
|
import 'property_editor.dart';
class StringEditor extends PropertyEditor<String> {
@override
String convert(String value) => value;
@override
bool validate(String value) => true;
}
|
super_flutter_maker/game/lib/models/property_editors/string_editor.dart/0
|
{'file_path': 'super_flutter_maker/game/lib/models/property_editors/string_editor.dart', 'repo_id': 'super_flutter_maker', 'token_count': 55}
|
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:super_flutter_maker/models/challenge.dart';
import '../../models/challenge_widget.dart';
import '../../repository/challenges_repository.dart';
import '../../util.dart';
import 'builder_view.dart';
import 'preview_view.dart';
const SLIDER_COUNT = 3;
const TextStyle buttonsStyle = TextStyle(color: Colors.white, fontSize: 20);
class GameScreen extends StatefulWidget {
const GameScreen({Key key, this.id}) : super(key: key);
final String id;
@override
_GameScreenState createState() => _GameScreenState(this.id);
}
class _GameScreenState extends State<GameScreen> {
final SwiperController swiperController = SwiperController();
Challenge challenge;
ChallengeWidget currentWidget;
_GameScreenState(String id) {
challenge = ChallengeRepository().getChallenge(id);
currentWidget = null;
}
updateWidgetTree(ChallengeWidget newWidgetTree) {
setState(() {
currentWidget = newWidgetTree;
});
}
_snack(String msg) {
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text(msg),
));
}
doVerify() {
bool isEqual = currentWidget != null && challenge.child.toJson() == currentWidget.toJson();
_snack(isEqual ? 'Well done, you won!! 🎉' : 'Oops! Not quite right :(');
}
Widget slider(BuildContext context) {
return Swiper(
itemBuilder: (BuildContext context, int index) {
switch (index) {
case 0:
return PreviewView(challenge.child, null);
case 1:
return BuilderView(currentWidget, updateWidgetTree);
case 2:
return PreviewView(currentWidget, doVerify);
default:
return Text('Loading...');
}
},
itemCount: SLIDER_COUNT,
loop: false,
pagination: null,
control: null,
controller: swiperController,
);
}
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(color: Colors.cyan),
child: SafeArea(
child: Stack(
children: [
Container(
child: slider(context),
padding: EdgeInsets.only(top: 64.0),
),
Positioned(
top: 8.0,
left: 0.0,
right: 0.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
GestureDetector(
child: pad(Icon(Icons.arrow_back, color: Colors.white)),
onTap: () {
Navigator.of(context).pop();
},
),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FlatButton(
child: Text('Goal', style: buttonsStyle),
onPressed: () => swiperController.move(0),
),
FlatButton(
child: Text('Builder', style: buttonsStyle),
onPressed: () => swiperController.move(1),
),
FlatButton(
child: Text('Preview', style: buttonsStyle),
onPressed: () => swiperController.move(2),
),
],
),
),
],
),
)
],
),
),
);
}
}
|
super_flutter_maker/game/lib/screens/game_screen/game_screen.dart/0
|
{'file_path': 'super_flutter_maker/game/lib/screens/game_screen/game_screen.dart', 'repo_id': 'super_flutter_maker', 'token_count': 1826}
|
import 'package:clock/clock.dart';
import 'package:tailor_made/domain.dart';
import 'package:uuid/uuid.dart';
class ContactsMockImpl extends Contacts {
@override
Stream<List<ContactEntity>> fetchAll(String? userId) async* {
yield <ContactEntity>[
ContactEntity(
reference: const ReferenceEntity(id: 'id', path: 'path'),
userID: '1',
id: '',
fullname: '',
phone: '',
location: '',
imageUrl: '',
createdAt: clock.now(),
),
];
}
@override
Future<ContactEntity> create(String userId, CreateContactData data) async {
final String id = const Uuid().v4();
return ContactEntity(
reference: ReferenceEntity(id: id, path: 'path'),
userID: '1',
id: id,
fullname: '',
phone: '',
location: '',
imageUrl: '',
createdAt: clock.now(),
);
}
@override
Future<bool> update(
String userId, {
required ReferenceEntity reference,
String? fullname,
String? phone,
String? location,
String? imageUrl,
Map<String, double>? measurements,
}) async =>
true;
}
|
tailor_made/lib/data/repositories/contacts/contacts_mock_impl.dart/0
|
{'file_path': 'tailor_made/lib/data/repositories/contacts/contacts_mock_impl.dart', 'repo_id': 'tailor_made', 'token_count': 472}
|
import 'package:tailor_made/domain.dart';
class StatsMockImpl extends Stats {
@override
Stream<StatsEntity> fetch(String userId) async* {
yield const StatsEntity(
contacts: StatsItemEntity(),
gallery: StatsItemEntity(),
jobs: StatsItemEntity(),
payments: StatsItemEntity(),
);
}
}
|
tailor_made/lib/data/repositories/stats/stats_mock_impl.dart/0
|
{'file_path': 'tailor_made/lib/data/repositories/stats/stats_mock_impl.dart', 'repo_id': 'tailor_made', 'token_count': 113}
|
import 'dart:async';
import 'package:rxdart/transformers.dart';
import 'package:tailor_made/core.dart';
import '../entities/account_entity.dart';
import '../entities/auth_exception.dart';
import '../repositories/accounts.dart';
class SignInUseCase {
const SignInUseCase({required Accounts accounts}) : _accounts = accounts;
final Accounts _accounts;
Future<AccountEntity> call() async {
final Completer<AccountEntity> completer = Completer<AccountEntity>();
late StreamSubscription<void> sub;
sub = _accounts.onAuthStateChanged.whereType<String>().listen(
(_) {
completer.complete(_accounts.fetch());
sub.cancel();
},
onError: (Object error, StackTrace stackTrace) {
completer.completeError(error, stackTrace);
sub.cancel();
},
);
try {
await _accounts.signIn();
} on AuthException catch (error, stackTrace) {
if (error is AuthExceptionFailed) {
AppLog.e(error, stackTrace);
}
rethrow;
}
return completer.future;
}
}
|
tailor_made/lib/domain/use_cases/sign_in_use_case.dart/0
|
{'file_path': 'tailor_made/lib/domain/use_cases/sign_in_use_case.dart', 'repo_id': 'tailor_made', 'token_count': 413}
|
import 'package:flutter/material.dart';
import 'package:tailor_made/domain.dart';
import 'package:tailor_made/presentation/routing.dart';
class GalleryGridItem extends StatelessWidget {
const GalleryGridItem({super.key, required this.image});
final ImageEntity image;
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
return Hero(
tag: image.src,
child: DecoratedBox(
decoration: BoxDecoration(
color: colorScheme.outlineVariant,
image: DecorationImage(fit: BoxFit.cover, image: NetworkImage(image.src)),
),
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: () => context.router.toGalleryImage(
src: image.src,
contactID: image.contactID,
jobID: image.jobID,
),
),
),
),
);
}
}
|
tailor_made/lib/presentation/screens/gallery/widgets/gallery_grid_item.dart/0
|
{'file_path': 'tailor_made/lib/presentation/screens/gallery/widgets/gallery_grid_item.dart', 'repo_id': 'tailor_made', 'token_count': 411}
|
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:tailor_made/domain.dart';
import 'account_provider.dart';
import 'registry_provider.dart';
part 'jobs_provider.g.dart';
@Riverpod(dependencies: <Object>[registry, account])
Stream<List<JobEntity>> jobs(JobsRef ref) async* {
final AccountEntity account = await ref.watch(accountProvider.future);
yield* ref.read(registryProvider).get<Jobs>().fetchAll(account.uid);
}
|
tailor_made/lib/presentation/state/jobs_provider.dart/0
|
{'file_path': 'tailor_made/lib/presentation/state/jobs_provider.dart', 'repo_id': 'tailor_made', 'token_count': 153}
|
import 'package:flutter/material.dart';
import '../theme.dart';
import '../utils.dart';
import 'app_icon.dart';
import 'custom_app_bar.dart';
class AppCrashErrorView extends StatelessWidget {
const AppCrashErrorView({super.key});
@override
Widget build(BuildContext context) {
final ThemeData theme = context.theme;
final TextTheme textTheme = theme.textTheme;
final L10n l10n = context.l10n;
return Scaffold(
appBar: CustomAppBar.empty,
body: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
const SizedBox(height: 40),
const Align(alignment: Alignment.centerLeft, child: AppIcon()),
const SizedBox(height: 38),
Text(
l10n.crashViewTitleMessage,
style: textTheme.displaySmall!.copyWith(
height: 1.08,
fontWeight: AppFontWeight.light,
color: theme.colorScheme.onBackground,
),
),
const SizedBox(height: 35),
Text.rich(
TextSpan(
children: <TextSpan>[
TextSpan(
text: l10n.crashViewQuoteMessage,
style: textTheme.headlineSmall!.copyWith(height: 1.5),
),
TextSpan(text: ' — ', style: textTheme.titleMedium),
TextSpan(
text: l10n.crashViewQuoteAuthor,
style: textTheme.titleMedium!.copyWith(fontStyle: FontStyle.italic),
),
],
),
),
const SizedBox(height: 24),
Text(
l10n.crashViewBugMessage1,
style: textTheme.titleMedium!.copyWith(height: 1.45),
),
const SizedBox(height: 24),
Text(
l10n.crashViewBugMessage2,
style: textTheme.titleMedium!.copyWith(height: 1.45),
),
const SizedBox(height: 24),
],
),
),
);
}
}
|
tailor_made/lib/presentation/widgets/app_crash_error_view.dart/0
|
{'file_path': 'tailor_made/lib/presentation/widgets/app_crash_error_view.dart', 'repo_id': 'tailor_made', 'token_count': 1141}
|
import 'package:collection/collection.dart';
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:meta/meta.dart';
import '../../core/services/src/user_service.dart';
part 'user.g.dart';
/// A class representing a user.
@immutable
@JsonSerializable()
class User extends Equatable {
const User({
this.id,
this.name,
this.email,
this.profileImage,
this.username,
this.password,
});
/// The unique identifier of the user.
final String? id;
/// The name of the user.
final String? name;
/// The email address of the user.
final String? email;
/// The URL of the user's profile image.
final String? profileImage;
/// The username of the user.
final String? username;
/// The password of the user.
final String? password;
/// Creates a new instance of `User` with updated values.
User copyWith({
String? id,
String? name,
String? email,
String? profileImage,
String? username,
String? password,
}) {
return User(
id: id ?? this.id,
name: name ?? this.name,
email: email ?? this.email,
profileImage: profileImage ?? this.profileImage,
username: username ?? this.username,
password: password ?? this.password,
);
}
/// Converts a JSON object to an instance of `User`.
static User fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
/// Converts an instance of `User` to a JSON object.
Map<String, dynamic> toJson() => _$UserToJson(this);
@override
List<Object?> get props {
return [
id,
name,
email,
profileImage,
username,
password,
];
}
}
/// Extension on [User] class to provide login validation functionality.
extension LoginValidator on User {
/// Validates if the email and password fields of a user are valid for login.
///
/// Returns a [String] error message if the validation fails, otherwise returns null.
String? validateLogin() {
if (email == null || email!.isEmpty) {
return 'Please enter your email';
}
if (password == null || password!.isEmpty) {
return 'Please enter your password';
}
if (!RegExp(r'^[a-zA-Z0-9+._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$')
.hasMatch(email!)) {
return 'Invalid email format';
}
return null;
}
}
/// Extension on the User class to validate user signup information.
extension SignupValidator on User {
/// Validates the user's signup information.
/// Returns a string error message if any of the information is invalid,
/// or null if all information is valid.
String? validateSignup() {
if (name == null || name!.isEmpty) {
return 'Please enter your name';
}
if (email == null || email!.isEmpty) {
return 'Please enter your email';
}
if (!RegExp(r'^[a-zA-Z0-9+._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
.hasMatch(email!)) {
return 'Invalid email format';
}
if (username == null || username!.isEmpty) {
return 'Please enter a username';
}
if (password == null || password!.isEmpty) {
return 'Please enter a password';
}
if (password!.length < 6) {
return 'Password must be at least 6 characters';
}
return null;
}
}
/// Extension for the `User` class that adds a method to check if a user with
/// the same email already exists in the database.
extension UserExtension on User {
/// Checks if a user with the same email already exists in the database.
///
/// Returns `true` if the user exists, `false` otherwise.
Future<User?> getUser(
UserService userService,
) async {
final user = (await userService.getUsers())
.firstWhereOrNull((user) => user.email == email);
return user;
}
}
|
talk-stream-backend/packages/auth_data_source/lib/src/models/user.dart/0
|
{'file_path': 'talk-stream-backend/packages/auth_data_source/lib/src/models/user.dart', 'repo_id': 'talk-stream-backend', 'token_count': 1340}
|
class AppRoutes {
static const String splash = '/splash';
static const String webAuth = '/web_auth';
static const String signIn = '/signIn';
static const String signUp = '/signUp';
static const String counter = '/counter';
static const String home = '/home';
static const String chat = '/chat';
static const String mobileAllUsers = '/mobile_all_users';
static const String mobileChatDetails = '/mobile_chat_details';
static const String contacts = '/contacts';
}
|
talk-stream/lib/app/src/constants/app_routes.dart/0
|
{'file_path': 'talk-stream/lib/app/src/constants/app_routes.dart', 'repo_id': 'talk-stream', 'token_count': 130}
|
// ignore_for_file: public_member_api_docs
part of 'signin_cubit.dart';
@immutable
abstract class SigninState {}
class SigninInitial extends SigninState {}
class SigninLoading extends SigninState {}
class SigninLoaded extends SigninState {
SigninLoaded({
required this.user,
});
final User user;
}
class SigninError extends SigninState {
SigninError({
required this.errorMessage,
});
final String errorMessage;
}
|
talk-stream/lib/auth/cubits/signin_state.dart/0
|
{'file_path': 'talk-stream/lib/auth/cubits/signin_state.dart', 'repo_id': 'talk-stream', 'token_count': 142}
|
import 'dart:convert';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:talk_stream/app/core/locator.dart';
import 'package:talk_stream/app/core/services/src/http_service.dart';
import 'package:talk_stream/app/src/constants/server_constants.dart';
import 'package:talk_stream/chat/models/chat.dart';
part 'chat_state.dart';
class ChatCubit extends Cubit<ChatState> {
ChatCubit() : super(ChatInitial());
Future<void> fetchRecentChats(
String userId, {
bool reload = true,
}) async {
if (reload) {
emit(ChatLoading());
}
final httpService = locator<HttpService>();
try {
final result = await httpService.get(
'/chat/get_chats',
headers: {
...serverHeaders,
'userId': userId,
},
);
if (!reload) {
emit(ChatInitial());
}
emit(
ChatLoaded(
chats: (jsonDecode(result.body) as List).map((e) {
return Chat.fromJson(e as Map<String, dynamic>);
}).toList(),
),
);
} on HttpException catch (e) {
emit(
ChatError(
errorMessage: e.message,
),
);
} catch (e) {
emit(
ChatError(
errorMessage: e.toString(),
),
);
}
}
}
|
talk-stream/lib/chat/cubits/chat_cubit.dart/0
|
{'file_path': 'talk-stream/lib/chat/cubits/chat_cubit.dart', 'repo_id': 'talk-stream', 'token_count': 610}
|
import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:flutter/material.dart';
class BottomChatField extends StatefulWidget {
const BottomChatField({
required this.onSend,
super.key,
});
final void Function(String) onSend;
@override
State<BottomChatField> createState() => _BottomChatFieldState();
}
class _BottomChatFieldState extends State<BottomChatField> {
final TextEditingController _textEditingController = TextEditingController();
bool _isComposing = false;
bool _showingEmojis = false;
@override
Widget build(BuildContext context) {
return DecoratedBox(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.3),
blurRadius: 5,
),
],
),
child: SafeArea(
child: Column(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Expanded(
child: Container(
margin:
const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
// color: Colors.grey[200],
borderRadius: BorderRadius.circular(24),
),
child: Row(
children: <Widget>[
IconButton(
icon: Icon(
_showingEmojis
? Icons.close
: Icons.insert_emoticon,
),
onPressed: () {
_showingEmojis = !_showingEmojis;
setState(() {});
// Implement emoji picker or open keyboard
},
),
Expanded(
child: TextField(
controller: _textEditingController,
maxLines: null,
onChanged: (String text) {
setState(() {
_isComposing = text.isNotEmpty;
});
},
decoration: const InputDecoration.collapsed(
hintText: 'Type a message',
),
),
),
IconButton(
icon: const Icon(Icons.attach_file),
onPressed: () {
// Implement file picker or open camera/gallery
},
),
IconButton(
icon: const Icon(Icons.send),
onPressed: _isComposing
? () {
widget.onSend(_textEditingController.text);
_textEditingController.clear();
setState(() {
_isComposing = false;
});
}
: null,
),
],
),
),
),
],
),
if (_showingEmojis)
SizedBox(
height: 300,
width: double.infinity,
child: EmojiPicker(
onEmojiSelected: (emoji, category) {
setState(() {
_textEditingController.text =
_textEditingController.text + category.emoji;
});
},
),
),
],
),
),
);
}
}
|
talk-stream/lib/chat/view/widgets/bottom_chat_field.dart/0
|
{'file_path': 'talk-stream/lib/chat/view/widgets/bottom_chat_field.dart', 'repo_id': 'talk-stream', 'token_count': 2602}
|
name: talk_stream
description: A Very Good Project created by Very Good CLI.
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.19.0 <3.0.0"
dependencies:
bloc: ^8.1.1
collection: ^1.17.0
emoji_picker_flutter: ^1.5.2
equatable: ^2.0.5
flutter:
sdk: flutter
flutter_bloc: ^8.1.2
flutter_localizations:
sdk: flutter
font_awesome_flutter: ^10.4.0
get_it: ^7.2.0
go_router: ^6.5.1
google_fonts: ^4.0.3
http: ^0.13.5
image_picker: ^0.8.7
intl: ^0.17.0
json_annotation: ^4.8.0
json_serializable: ^6.6.1
meta: ^1.8.0
nested: ^1.0.0
timeago: ^3.3.0
web_socket_channel: ^2.3.0
dev_dependencies:
bloc_test: ^9.1.1
build_runner: ^2.3.3
flutter_test:
sdk: flutter
mocktail: ^0.3.0
very_good_analysis: ^4.0.0
flutter:
uses-material-design: true
generate: true
|
talk-stream/pubspec.yaml/0
|
{'file_path': 'talk-stream/pubspec.yaml', 'repo_id': 'talk-stream', 'token_count': 407}
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:convert';
import 'dart:core';
import 'package:dartz/dartz.dart';
import 'package:mongo_dart/mongo_dart.dart';
import 'package:team_ship_dart_frog/data/models/client_error.dart';
import 'package:team_ship_dart_frog/data/models/user.dart';
class CreateProjectParams {
final String name;
final String base64Image;
final String description;
final String? githubRepo;
final String? websiteUrl;
final String? twitterUrl;
final String? linkedinUrl;
final List<Map<String, int>> stackAndCount;
final String? createdAt;
final String? updatedAt;
final String? projectType;
final bool? shouldCreateRepo;
final Map<String, dynamic> duration;
CreateProjectParams({
required this.name,
required this.base64Image,
required this.description,
this.githubRepo,
this.websiteUrl,
this.twitterUrl,
this.linkedinUrl,
required this.stackAndCount,
this.createdAt,
this.updatedAt,
this.projectType,
this.shouldCreateRepo,
required this.duration,
});
Map<String, dynamic> toMap() {
return <String, dynamic>{
'name': name,
'base64Image': base64Image,
'description': description,
'githubRepo': githubRepo,
'websiteUrl': websiteUrl,
'twitterUrl': twitterUrl,
'linkedinUrl': linkedinUrl,
'stackAndCount': stackAndCount,
'createdAt': createdAt,
'updatedAt': updatedAt,
'projectType': projectType,
'shouldCreateRepo': shouldCreateRepo,
'duration': duration,
};
}
factory CreateProjectParams.fromMap(Map<String, dynamic> map) {
return CreateProjectParams(
name: map['name'] as String,
base64Image: map['base64Image'] as String,
description: map['description'] as String,
githubRepo:
map['githubRepo'] != null ? map['githubRepo'] as String : null,
websiteUrl:
map['websiteUrl'] != null ? map['websiteUrl'] as String : null,
twitterUrl:
map['twitterUrl'] != null ? map['twitterUrl'] as String : null,
linkedinUrl:
map['linkedinUrl'] != null ? map['linkedinUrl'] as String : null,
stackAndCount: List<Map<String, int>>.from(
(map['stackAndCount'] as List).map(
(x) => x,
),
),
createdAt: map['createdAt'] != null ? map['createdAt'] as String : null,
updatedAt: map['updatedAt'] != null ? map['updatedAt'] as String : null,
projectType:
map['projectType'] != null ? map['projectType'] as String : null,
shouldCreateRepo: map['shouldCreateRepo'] != null
? map['shouldCreateRepo'] as bool
: null,
duration: Map<String, dynamic>.from(
map['duration'] as Map<String, dynamic>,
),
);
}
String toJson() => json.encode(toMap());
///
Future<Either<ClientError, Map<String, dynamic>>> createProject(
DbCollection collection,
User user,
) async {
final data = {
...toMap(),
'creator': user.toMap(),
};
final result = await collection.insertOne(data);
if (result.hasWriteErrors) {
return left(
ClientError(
message: 'an error occured trying to create project',
),
);
}
return right(data);
}
factory CreateProjectParams.fromJson(String source) =>
CreateProjectParams.fromMap(
json.decode(source) as Map<String, dynamic>,
);
}
|
teamship-dart-frog/lib/data/params/create_project_params.dart/0
|
{'file_path': 'teamship-dart-frog/lib/data/params/create_project_params.dart', 'repo_id': 'teamship-dart-frog', 'token_count': 1350}
|
import 'dart:io';
import 'package:dart_frog/dart_frog.dart';
import 'package:team_ship_dart_frog/data/models/client_data.dart';
import 'package:team_ship_dart_frog/data/models/client_error.dart';
import 'package:team_ship_dart_frog/data/models/user.dart';
import 'package:team_ship_dart_frog/data/params/create_project_params.dart';
import 'package:team_ship_dart_frog/server/db_connection.dart';
Future<Response> onRequest(RequestContext context) async {
final user = context.read<User>();
final body = await context.request.body();
final method = context.request.method;
final params = CreateProjectParams.fromJson(body);
final db = await connection.db;
final collection = db.collection('projects');
if (method != HttpMethod.post) {
return Response(
statusCode: HttpStatus.methodNotAllowed,
body: ClientError(
message: 'Method not allowed',
).toJson(),
);
}
final createProject = await params.createProject(
collection,
user,
);
return createProject.fold(
(err) => Response(
statusCode: HttpStatus.badRequest,
body: err.toJson(),
),
(data) {
return Response(
body: ClientData(
message: 'Project created',
data: data,
).toJson(),
);
},
);
}
|
teamship-dart-frog/routes/api/v1/project/create.dart/0
|
{'file_path': 'teamship-dart-frog/routes/api/v1/project/create.dart', 'repo_id': 'teamship-dart-frog', 'token_count': 490}
|
// 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.
import 'dart:async';
import 'package:async/async.dart';
import 'package:path/path.dart' as p;
import 'package:stream_channel/stream_channel.dart';
import 'package:test/test.dart';
void main() {
group('spawnHybridUri():', () {
test('loads a file in a separate isolate connected via StreamChannel',
() async {
expect(spawnHybridUri('util/emits_numbers.dart').stream.toList(),
completion(equals([1, 2, 3])));
});
test('resolves root-relative URIs relative to the package root', () async {
expect(spawnHybridUri('/test/util/emits_numbers.dart').stream.toList(),
completion(equals([1, 2, 3])));
});
test('supports Uri objects', () async {
expect(
spawnHybridUri(Uri.parse('util/emits_numbers.dart')).stream.toList(),
completion(equals([1, 2, 3])));
});
test('supports package: uris referencing the root package', () async {
expect(
spawnHybridUri(Uri.parse('package:spawn_hybrid/emits_numbers.dart'))
.stream
.toList(),
completion(equals([1, 2, 3])));
});
test('supports package: uris referencing dependency packages', () async {
expect(
spawnHybridUri(Uri.parse('package:other_package/emits_numbers.dart'))
.stream
.toList(),
completion(equals([1, 2, 3])));
});
test('rejects non-String, non-Uri objects', () {
expect(() => spawnHybridUri(123), throwsArgumentError);
});
test('passes a message to the hybrid isolate', () async {
expect(
spawnHybridUri('util/echos_message.dart', message: 123).stream.first,
completion(equals(123)));
expect(
spawnHybridUri('util/echos_message.dart', message: 'wow')
.stream
.first,
completion(equals('wow')));
});
test('emits an error from the stream channel if the isolate fails to load',
() {
expect(spawnHybridUri('non existent file').stream.first,
throwsA(TypeMatcher<Exception>()));
});
});
group('spawnHybridCode()', () {
test('loads the code in a separate isolate connected via StreamChannel',
() {
expect(spawnHybridCode('''
import "package:stream_channel/stream_channel.dart";
void hybridMain(StreamChannel channel) {
channel.sink..add(1)..add(2)..add(3)..close();
}
''').stream.toList(), completion(equals([1, 2, 3])));
});
test('allows a first parameter with type StreamChannel<Object?>', () {
expect(spawnHybridCode('''
import "package:stream_channel/stream_channel.dart";
void hybridMain(StreamChannel<Object?> channel) {
channel.sink..add(1)..add(2)..add(null)..close();
}
''').stream.toList(), completion(equals([1, 2, null])));
});
test('gives a good error when the StreamChannel type is not supported', () {
expect(
spawnHybridCode('''
import "package:stream_channel/stream_channel.dart";
void hybridMain(StreamChannel<Object> channel) {
channel.sink..add(1)..add(2)..add(3)..close();
}
''').stream,
emitsError(isA<Exception>().having(
(e) => e.toString(),
'toString',
contains(
'The first parameter to the top-level hybridMain() must be a '
'StreamChannel<dynamic> or StreamChannel<Object?>. More specific '
'types such as StreamChannel<Object> are not supported.'))));
});
test('can use dart:io even when run from a browser', () async {
var path = p.join('test', 'hybrid_test.dart');
expect(spawnHybridCode("""
import 'dart:io';
import 'package:stream_channel/stream_channel.dart';
void hybridMain(StreamChannel channel) {
channel.sink
..add(File(r"$path").readAsStringSync())
..close();
}
""").stream.first, completion(contains('hybrid emits numbers')));
}, testOn: 'browser');
test('forwards data from the test to the hybrid isolate', () async {
var channel = spawnHybridCode('''
import "package:stream_channel/stream_channel.dart";
void hybridMain(StreamChannel channel) {
channel.stream.listen((num) {
channel.sink.add(num + 1);
});
}
''');
channel.sink
..add(1)
..add(2)
..add(3);
expect(channel.stream.take(3).toList(), completion(equals([2, 3, 4])));
});
test('passes an initial message to the hybrid isolate', () {
var code = '''
import "package:stream_channel/stream_channel.dart";
void hybridMain(StreamChannel channel, Object message) {
channel.sink..add(message)..close();
}
''';
expect(spawnHybridCode(code, message: [1, 2, 3]).stream.first,
completion(equals([1, 2, 3])));
expect(spawnHybridCode(code, message: {'a': 'b'}).stream.first,
completion(equals({'a': 'b'})));
});
test('allows the hybrid isolate to send errors across the stream channel',
() {
var channel = spawnHybridCode('''
import "package:stack_trace/stack_trace.dart";
import "package:stream_channel/stream_channel.dart";
void hybridMain(StreamChannel channel) {
channel.sink.addError("oh no!", Trace.current());
}
''');
channel.stream.listen(null, onError: expectAsync2((error, stackTrace) {
expect(error.toString(), equals('oh no!'));
expect(stackTrace.toString(), contains('hybridMain'));
}));
});
test('sends an unhandled synchronous error across the stream channel', () {
var channel = spawnHybridCode('''
import "package:stream_channel/stream_channel.dart";
void hybridMain(StreamChannel channel) {
throw "oh no!";
}
''');
channel.stream.listen(null, onError: expectAsync2((error, stackTrace) {
expect(error.toString(), equals('oh no!'));
expect(stackTrace.toString(), contains('hybridMain'));
}));
});
test('sends an unhandled asynchronous error across the stream channel', () {
var channel = spawnHybridCode('''
import 'dart:async';
import "package:stream_channel/stream_channel.dart";
void hybridMain(StreamChannel channel) {
scheduleMicrotask(() {
throw "oh no!";
});
}
''');
channel.stream.listen(null, onError: expectAsync2((error, stackTrace) {
expect(error.toString(), equals('oh no!'));
expect(stackTrace.toString(), contains('hybridMain'));
}));
});
test('deserializes TestFailures as TestFailures', () {
var channel = spawnHybridCode('''
import "package:stream_channel/stream_channel.dart";
import "package:test/test.dart";
void hybridMain(StreamChannel channel) {
throw TestFailure("oh no!");
}
''');
expect(channel.stream.first, throwsA(TypeMatcher<TestFailure>()));
});
test('gracefully handles an unserializable message in the VM', () {
var channel = spawnHybridCode('''
import "package:stream_channel/stream_channel.dart";
void hybridMain(StreamChannel channel) {}
''');
expect(() => channel.sink.add([].iterator), throwsArgumentError);
});
test('gracefully handles an unserializable message in the browser',
() async {
var channel = spawnHybridCode('''
import 'package:stream_channel/stream_channel.dart';
void hybridMain(StreamChannel channel) {}
''');
expect(() => channel.sink.add([].iterator), throwsArgumentError);
}, testOn: 'browser');
test('gracefully handles an unserializable message in the hybrid isolate',
() {
var channel = spawnHybridCode('''
import "package:stream_channel/stream_channel.dart";
void hybridMain(StreamChannel channel) {
channel.sink.add([].iterator);
}
''');
channel.stream.listen(null, onError: expectAsync1((error) {
expect(error.toString(), contains("can't be JSON-encoded."));
}));
});
test('forwards prints from the hybrid isolate', () {
expect(() async {
var channel = spawnHybridCode('''
import "package:stream_channel/stream_channel.dart";
void hybridMain(StreamChannel channel) {
print("hi!");
channel.sink.add(null);
}
''');
await channel.stream.first;
}, prints('hi!\n'));
});
// This takes special handling, since the code is packed into a data: URI
// that's imported, URIs don't escape $ by default, and $ isn't allowed in
// imports.
test('supports a dollar character in the hybrid code', () {
expect(spawnHybridCode(r'''
import "package:stream_channel/stream_channel.dart";
void hybridMain(StreamChannel channel) {
var value = "bar";
channel.sink.add("foo${value}baz");
}
''').stream.first, completion('foobarbaz'));
});
test('closes the channel when the hybrid isolate exits', () {
var channel = spawnHybridCode('''
import "dart:isolate";
hybridMain(_) {
Isolate.current.kill();
}
''');
expect(channel.stream.toList(), completion(isEmpty));
});
group('closes the channel when the test finishes by default', () {
late StreamChannel channel;
test('test 1', () {
channel = spawnHybridCode('''
import 'package:stream_channel/stream_channel.dart';
void hybridMain(StreamChannel channel) {}
''');
});
test('test 2', () async {
var isDone = false;
channel.stream.listen(null, onDone: () => isDone = true);
await pumpEventQueue();
expect(isDone, isTrue);
});
});
group('persists across multiple tests with stayAlive: true', () {
late StreamQueue queue;
late StreamSink sink;
setUpAll(() {
var channel = spawnHybridCode('''
import "package:stream_channel/stream_channel.dart";
void hybridMain(StreamChannel channel) {
channel.stream.listen((message) {
channel.sink.add(message);
});
}
''', stayAlive: true);
queue = StreamQueue(channel.stream);
sink = channel.sink;
});
test('echoes a number', () {
expect(queue.next, completion(equals(123)));
sink.add(123);
});
test('echoes a string', () {
expect(queue.next, completion(equals('wow')));
sink.add('wow');
});
});
test('can opt out of null safety', () async {
expect(spawnHybridCode('''
// @dart=2.9
import "package:stream_channel/stream_channel.dart";
// Would cause an error in null safety mode.
int x;
void hybridMain(StreamChannel channel) {
channel.sink..add(1)..add(2)..add(3)..close();
}
''').stream.toList(), completion(equals([1, 2, 3])));
});
test('opts in to null safety by default', () async {
expect(spawnHybridCode('''
import "package:stream_channel/stream_channel.dart";
// Use some null safety syntax
int? x;
void hybridMain(StreamChannel channel) {
channel.sink..add(1)..add(2)..add(3)..close();
}
''').stream.toList(), completion(equals([1, 2, 3])));
});
});
}
|
test/integration_tests/spawn_hybrid/test/hybrid_test.dart/0
|
{'file_path': 'test/integration_tests/spawn_hybrid/test/hybrid_test.dart', 'repo_id': 'test', 'token_count': 5095}
|
// 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.
import 'package:checks/context.dart';
import 'core.dart' show HasField;
extension IterableChecks<T> on Check<Iterable<T>> {
Check<int> get length => has((l) => l.length, 'length');
Check<T> get first => has((l) => l.first, 'first element');
Check<T> get last => has((l) => l.last, 'last element');
Check<T> get single => has((l) => l.single, 'single element');
void isEmpty() {
context.expect(() => const ['is empty'], (actual) {
if (actual.isEmpty) return null;
return Rejection(actual: literal(actual), which: ['is not empty']);
});
}
void isNotEmpty() {
context.expect(() => const ['is not empty'], (actual) {
if (actual.isNotEmpty) return null;
return Rejection(actual: literal(actual), which: ['is not empty']);
});
}
/// Expects that the iterable contains [element] according to
/// [Iterable.contains].
void contains(T element) {
context.expect(() {
return [
'contains ${literal(element)}',
];
}, (actual) {
if (actual.isEmpty) return Rejection(actual: 'an empty iterable');
if (actual.contains(element)) return null;
return Rejection(
actual: literal(actual),
which: ['does not contain ${literal(element)}']);
});
}
/// Expects that the iterable contains at least on element such that
/// [elementCondition] is satisfied.
void any(void Function(Check<T>) elementCondition) {
context.expect(() {
final conditionDescription = describe(elementCondition);
assert(conditionDescription.isNotEmpty);
return [
'contains a value that:',
...conditionDescription,
];
}, (actual) {
if (actual.isEmpty) return Rejection(actual: 'an empty iterable');
for (var e in actual) {
if (softCheck(e, elementCondition) == null) return null;
}
return Rejection(
actual: '${literal(actual)}',
which: ['Contains no matching element']);
});
}
}
|
test/pkgs/checks/lib/src/extensions/iterable.dart/0
|
{'file_path': 'test/pkgs/checks/lib/src/extensions/iterable.dart', 'repo_id': 'test', 'token_count': 796}
|
# Disallow duplicate test names in this package
allow_duplicate_test_names: false
# 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]
test_on: linux
chrome: {add_tags: [dart2js]}
safari:
add_tags: [dart2js]
test_on: mac-os
ie:
add_tags: [dart2js]
test_on: windows
skip: https://github.com/dart-lang/test/issues/1614
# 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_on: linux
|
test/pkgs/test/dart_test.yaml/0
|
{'file_path': 'test/pkgs/test/dart_test.yaml', 'repo_id': 'test', 'token_count': 459}
|
// 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 'package:test/test.dart';
import 'package:test_descriptor/test_descriptor.dart' as d;
import '../../io.dart';
void main() {
setUpAll(precompileTestExecutable);
test('prints the platform name when running on multiple platforms', () async {
await d.file('test.dart', '''
import 'dart:async';
import 'package:path/path.dart' as p;
import 'package:test/test.dart';
void main() {
test("success", () {});
}
''').create();
var test = await runTest(
['-p', 'chrome', '-p', 'vm', '-j', '1', 'test.dart'],
reporter: 'compact');
expect(test.stdout, containsInOrder(['[Chrome]', '[VM]']));
await test.shouldExit(0);
}, tags: 'chrome');
}
|
test/pkgs/test/test/runner/browser/compact_reporter_test.dart/0
|
{'file_path': 'test/pkgs/test/test/runner/browser/compact_reporter_test.dart', 'repo_id': 'test', 'token_count': 330}
|
// 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 'dart:convert';
import 'dart:io';
import 'package:test/test.dart';
import 'package:test_descriptor/test_descriptor.dart' as d;
import '../../io.dart';
void main() {
setUpAll(precompileTestExecutable);
test('shuffles test order when passed a seed', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("test 1", () {});
test("test 2", () {});
test("test 3", () {});
test("test 4", () {});
}
''').create();
// Test with a given seed
var test =
await runTest(['test.dart', '--test-randomize-ordering-seed=987654']);
expect(
test.stdout,
containsInOrder([
'+0: test 4',
'+1: test 3',
'+2: test 1',
'+3: test 2',
'+4: All tests passed!'
]));
await test.shouldExit(0);
// Do not shuffle when passed 0
test = await runTest(['test.dart', '--test-randomize-ordering-seed=0']);
expect(
test.stdout,
containsInOrder([
'+0: test 1',
'+1: test 2',
'+2: test 3',
'+3: test 4',
'+4: All tests passed!'
]));
await test.shouldExit(0);
// Do not shuffle when passed nothing
test = await runTest(['test.dart']);
expect(
test.stdout,
containsInOrder([
'+0: test 1',
'+1: test 2',
'+2: test 3',
'+3: test 4',
'+4: All tests passed!'
]));
await test.shouldExit(0);
// Shuffle when passed random
test =
await runTest(['test.dart', '--test-randomize-ordering-seed=random']);
expect(
test.stdout,
emitsInAnyOrder([
contains('Shuffling test order with --test-randomize-ordering-seed'),
isNot(contains(
'Shuffling test order with --test-randomize-ordering-seed=0'))
]));
await test.shouldExit(0);
// Doesn't log about shuffling with the json reporter
test = await runTest(
['test.dart', '--test-randomize-ordering-seed=random', '-r', 'json']);
expect(test.stdout, neverEmits(contains('Shuffling test order')));
await test.shouldExit(0);
});
test('test shuffling can be disabled in dart_test.yml', () async {
await d
.file(
'dart_test.yaml',
jsonEncode({
'tags': {
'doNotShuffle': {'allow_test_randomization': false}
}
}))
.create();
await d.file('test.dart', '''
@Tags(['doNotShuffle'])
import 'package:test/test.dart';
void main() {
test("test 1", () {});
test("test 2", () {});
test("test 3", () {});
test("test 4", () {});
}
''').create();
var test =
await runTest(['test.dart', '--test-randomize-ordering-seed=987654']);
expect(
test.stdout,
containsInOrder([
'+0: test 1',
'+1: test 2',
'+2: test 3',
'+3: test 4',
'+4: All tests passed!'
]));
await test.shouldExit(0);
});
test('shuffles each suite with the same seed', () async {
await d.file('1_test.dart', '''
import 'package:test/test.dart';
void main() {
test("test 1.1", () {});
test("test 1.2", () {});
test("test 1.3", () {});
}
''').create();
await d.file('2_test.dart', '''
import 'package:test/test.dart';
void main() {
test("test 2.1", () {});
test("test 2.2", () {});
test("test 2.3", () {});
}
''').create();
var test = await runTest(['.', '--test-randomize-ordering-seed=12345']);
expect(
test.stdout,
emitsInAnyOrder([
containsInOrder([
'.${Platform.pathSeparator}1_test.dart: test 1.2',
'.${Platform.pathSeparator}1_test.dart: test 1.3',
'.${Platform.pathSeparator}1_test.dart: test 1.1'
]),
containsInOrder([
'.${Platform.pathSeparator}2_test.dart: test 2.2',
'.${Platform.pathSeparator}2_test.dart: test 2.3',
'.${Platform.pathSeparator}2_test.dart: test 2.1'
]),
contains('+6: All tests passed!')
]));
await test.shouldExit(0);
});
test('shuffles groups as well as tests in groups', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
group("Group 1", () {
test("test 1.1", () {});
test("test 1.2", () {});
test("test 1.3", () {});
test("test 1.4", () {});
});
group("Group 2", () {
test("test 2.1", () {});
test("test 2.2", () {});
test("test 2.3", () {});
test("test 2.4", () {});
});
}
''').create();
// Test with a given seed
var test =
await runTest(['test.dart', '--test-randomize-ordering-seed=123']);
expect(
test.stdout,
containsInOrder([
'+0: Group 2 test 2.4',
'+1: Group 2 test 2.2',
'+2: Group 2 test 2.1',
'+3: Group 2 test 2.3',
'+4: Group 1 test 1.4',
'+5: Group 1 test 1.2',
'+6: Group 1 test 1.1',
'+7: Group 1 test 1.3',
'+8: All tests passed!'
]));
await test.shouldExit(0);
});
test('shuffles nested groups', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
group("Group 1", () {
test("test 1.1", () {});
test("test 1.2", () {});
group("Group 2", () {
test("test 2.3", () {});
test("test 2.4", () {});
});
});
}
''').create();
var test =
await runTest(['test.dart', '--test-randomize-ordering-seed=123']);
expect(
test.stdout,
containsInOrder([
'+0: Group 1 test 1.1',
'+1: Group 1 Group 2 test 2.4',
'+2: Group 1 Group 2 test 2.3',
'+3: Group 1 test 1.2',
'+4: All tests passed!'
]));
await test.shouldExit(0);
});
}
|
test/pkgs/test/test/runner/configuration/randomize_order_test.dart/0
|
{'file_path': 'test/pkgs/test/test/runner/configuration/randomize_order_test.dart', 'repo_id': 'test', 'token_count': 3145}
|
// 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_core/src/util/exit_codes.dart' as exit_codes;
import 'package:test_descriptor/test_descriptor.dart' as d;
import '../io.dart';
void main() {
setUpAll(precompileTestExecutable);
group('with test.dart?name="name" query', () {
test('selects tests with matching names', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("selected 1", () {});
test("nope", () => throw TestFailure("oh no"));
test("selected 2", () {});
}
''').create();
var test = await runTest(['test.dart?name=selected']);
expect(
test.stdout,
emitsThrough(contains('+2: All tests passed!')),
);
await test.shouldExit(0);
});
test('supports RegExp syntax', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("test 1", () {});
test("test 2", () => throw TestFailure("oh no"));
test("test 3", () {});
}
''').create();
var test = await runTest(['test.dart?name=test [13]']);
expect(
test.stdout,
emitsThrough(contains('+2: All tests passed!')),
);
await test.shouldExit(0);
});
test('applies only to the associated file', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("selected 1", () {});
test("selected 2", () => throw TestFailure("oh no"));
}
''').create();
await d.file('test2.dart', '''
import 'package:test/test.dart';
void main() {
test("selected 1", () => throw TestFailure("oh no"));
test("selected 2", () {});
}
''').create();
var test = await runTest(
['test.dart?name=selected 1', 'test2.dart?name=selected 2'],
);
expect(
test.stdout,
emitsThrough(contains('+2: All tests passed!')),
);
await test.shouldExit(0);
});
test('selects more narrowly when passed multiple times', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("selected 1", () {});
test("nope", () => throw TestFailure("oh no"));
test("selected 2", () {});
}
''').create();
var test = await runTest(['test.dart?name=selected&name=1']);
expect(
test.stdout,
emitsThrough(contains('+1: All tests passed!')),
);
await test.shouldExit(0);
});
test('applies to directories', () async {
await d.dir('dir', [
d.file('first_test.dart', '''
import 'package:test/test.dart';
void main() {
test("selected 1", () {});
test("selected 2", () => throw TestFailure("oh no"));
}
'''),
d.file('second_test.dart', '''
import 'package:test/test.dart';
void main() {
test("selected 1", () {});
test("selected 2", () => throw TestFailure("oh no"));
}
''')
]).create();
var test = await runTest(['dir?name=selected 1']);
expect(
test.stdout,
emitsThrough(contains('+2: All tests passed!')),
);
await test.shouldExit(0);
});
test('produces an error when no tests match', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("test", () {});
}
''').create();
var test = await runTest(['test.dart?name=no']);
expect(
test.stderr,
emitsThrough(contains('No tests were found.')),
);
await test.shouldExit(exit_codes.noTestsRan);
});
test("doesn't filter out load exceptions", () async {
var test = await runTest(['file?name=name']);
expect(
test.stdout,
containsInOrder([
'-1: loading file [E]',
' Failed to load "file": Does not exist.'
]),
);
await test.shouldExit(1);
});
});
group('with test.dart?full-name query,', () {
test('matches with the complete test name', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("selected", () {});
test("nope", () => throw TestFailure("oh no"));
test("selected nope", () => throw TestFailure("oh no"));
}
''').create();
var test = await runTest(['test.dart?full-name=selected']);
expect(
test.stdout,
emitsThrough(contains('+1: All tests passed!')),
);
await test.shouldExit(0);
});
test("doesn't support RegExp syntax", () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("test 1", () => throw TestFailure("oh no"));
test("test 2", () => throw TestFailure("oh no"));
test("test [12]", () {});
}
''').create();
var test = await runTest(['test.dart?full-name=test [12]']);
expect(
test.stdout,
emitsThrough(contains('+1: All tests passed!')),
);
await test.shouldExit(0);
});
test('applies only to the associated file', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("selected 1", () {});
test("selected 2", () => throw TestFailure("oh no"));
}
''').create();
await d.file('test2.dart', '''
import 'package:test/test.dart';
void main() {
test("selected 1", () => throw TestFailure("oh no"));
test("selected 2", () {});
}
''').create();
var test = await runTest(
['test.dart?full-name=selected 1', 'test2.dart?full-name=selected 2'],
);
expect(
test.stdout,
emitsThrough(contains('+2: All tests passed!')),
);
await test.shouldExit(0);
});
test('produces an error when no tests match', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("test", () {});
}
''').create();
var test = await runTest(['test.dart?full-name=no match']);
expect(
test.stderr,
emitsThrough(contains('No tests were found.')),
);
await test.shouldExit(exit_codes.noTestsRan);
});
});
test('test?name="name" and --name narrow the selection', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("selected 1", () {});
test("nope 1", () => throw TestFailure("oh no"));
test("selected 2", () => throw TestFailure("oh no"));
test("nope 2", () => throw TestFailure("oh no"));
}
''').create();
var test = await runTest(['--name', '1', 'test.dart?name=selected']);
expect(
test.stdout,
emitsThrough(contains('+1: All tests passed!')),
);
await test.shouldExit(0);
});
test('test?name="name" and test?full-name="name" throws', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("selected 1", () {});
test("nope 1", () => throw TestFailure("oh no"));
test("selected 2", () => throw TestFailure("oh no"));
test("nope 2", () => throw TestFailure("oh no"));
}
''').create();
var test = await runTest(['test.dart?name=selected&full-name=selected 1']);
await test.shouldExit(64);
});
group('with the --name flag,', () {
test('selects tests with matching names', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("selected 1", () {});
test("nope", () => throw TestFailure("oh no"));
test("selected 2", () {});
}
''').create();
var test = await runTest(['--name', 'selected', 'test.dart']);
expect(test.stdout, emitsThrough(contains('+2: All tests passed!')));
await test.shouldExit(0);
});
test('supports RegExp syntax', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("test 1", () {});
test("test 2", () => throw TestFailure("oh no"));
test("test 3", () {});
}
''').create();
var test = await runTest(['--name', 'test [13]', 'test.dart']);
expect(test.stdout, emitsThrough(contains('+2: All tests passed!')));
await test.shouldExit(0);
});
test('selects more narrowly when passed multiple times', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("selected 1", () {});
test("nope", () => throw TestFailure("oh no"));
test("selected 2", () {});
}
''').create();
var test =
await runTest(['--name', 'selected', '--name', '1', 'test.dart']);
expect(test.stdout, emitsThrough(contains('+1: All tests passed!')));
await test.shouldExit(0);
});
test('produces an error when no tests match', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("test", () {});
}
''').create();
var test = await runTest(['--name', 'no match', 'test.dart']);
expect(
test.stderr,
emitsThrough(
contains('No tests match regular expression "no match".')));
await test.shouldExit(exit_codes.noTestsRan);
});
test("doesn't filter out load exceptions", () async {
var test = await runTest(['--name', 'name', 'file']);
expect(
test.stdout,
containsInOrder([
'-1: loading file [E]',
' Failed to load "file": Does not exist.'
]));
await test.shouldExit(1);
});
});
group('with the --plain-name flag,', () {
test('selects tests with matching names', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("selected 1", () {});
test("nope", () => throw TestFailure("oh no"));
test("selected 2", () {});
}
''').create();
var test = await runTest(['--plain-name', 'selected', 'test.dart']);
expect(test.stdout, emitsThrough(contains('+2: All tests passed!')));
await test.shouldExit(0);
});
test("doesn't support RegExp syntax", () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("test 1", () => throw TestFailure("oh no"));
test("test 2", () => throw TestFailure("oh no"));
test("test [12]", () {});
}
''').create();
var test = await runTest(['--plain-name', 'test [12]', 'test.dart']);
expect(test.stdout, emitsThrough(contains('+1: All tests passed!')));
await test.shouldExit(0);
});
test('selects more narrowly when passed multiple times', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("selected 1", () {});
test("nope", () => throw TestFailure("oh no"));
test("selected 2", () {});
}
''').create();
var test = await runTest(
['--plain-name', 'selected', '--plain-name', '1', 'test.dart']);
expect(test.stdout, emitsThrough(contains('+1: All tests passed!')));
await test.shouldExit(0);
});
test('produces an error when no tests match', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("test", () {});
}
''').create();
var test = await runTest(['--plain-name', 'no match', 'test.dart']);
expect(test.stderr, emitsThrough(contains('No tests match "no match".')));
await test.shouldExit(exit_codes.noTestsRan);
});
});
test('--name and --plain-name together narrow the selection', () async {
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("selected 1", () {});
test("nope", () => throw TestFailure("oh no"));
test("selected 2", () {});
}
''').create();
var test =
await runTest(['--name', '.....', '--plain-name', 'e', 'test.dart']);
expect(test.stdout, emitsThrough(contains('+2: All tests passed!')));
await test.shouldExit(0);
});
}
|
test/pkgs/test/test/runner/name_test.dart/0
|
{'file_path': 'test/pkgs/test/test/runner/name_test.dart', 'repo_id': 'test', 'token_count': 5742}
|
// 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 'dart:convert';
import 'dart:isolate';
import 'package:package_config/package_config.dart';
import 'package:test/test.dart';
import 'package:test_core/src/util/io.dart';
import 'package:test_descriptor/test_descriptor.dart' as d;
import '../io.dart';
void main() {
late PackageConfig currentPackageConfig;
setUpAll(() async {
await precompileTestExecutable();
currentPackageConfig =
await loadPackageConfigUri((await Isolate.packageConfig)!);
});
setUp(() async {
await d
.file('package_config.json',
jsonEncode(PackageConfig.toJson(currentPackageConfig)))
.create();
});
group('for suite', () {
test('runs a test suite on a matching platform', () async {
await _writeTestFile('vm_test.dart', suiteTestOn: 'vm');
var test = await runTest(['vm_test.dart']);
expect(test.stdout, emitsThrough(contains('All tests passed!')));
await test.shouldExit(0);
});
test("doesn't run a test suite on a non-matching platform", () async {
await _writeTestFile('vm_test.dart', suiteTestOn: 'vm');
var test = await runTest(['--platform', 'chrome', 'vm_test.dart']);
expect(test.stdout, emitsThrough(contains('No tests ran.')));
await test.shouldExit(79);
}, tags: 'chrome');
test('runs a test suite on a matching operating system', () async {
await _writeTestFile('os_test.dart', suiteTestOn: currentOS.identifier);
var test = await runTest(['os_test.dart']);
expect(test.stdout, emitsThrough(contains('All tests passed!')));
await test.shouldExit(0);
});
test("doesn't run a test suite on a non-matching operating system",
() async {
await _writeTestFile('os_test.dart',
suiteTestOn: otherOS, loadable: false);
var test = await runTest(['os_test.dart']);
expect(test.stdout, emitsThrough(contains('No tests ran.')));
await test.shouldExit(79);
});
test('only loads matching files when loading as a group', () async {
await _writeTestFile('vm_test.dart', suiteTestOn: 'vm');
await _writeTestFile('browser_test.dart',
suiteTestOn: 'browser', loadable: false);
await _writeTestFile('this_os_test.dart',
suiteTestOn: currentOS.identifier);
await _writeTestFile('other_os_test.dart',
suiteTestOn: otherOS, loadable: false);
var test = await runTest(['.']);
expect(test.stdout, emitsThrough(contains('+2: All tests passed!')));
await test.shouldExit(0);
});
});
group('for group', () {
test('runs a VM group on the VM', () async {
await _writeTestFile('vm_test.dart', groupTestOn: 'vm');
var test = await runTest(['vm_test.dart']);
expect(test.stdout, emitsThrough(contains('All tests passed!')));
await test.shouldExit(0);
});
test("doesn't run a Browser group on the VM", () async {
await _writeTestFile('browser_test.dart', groupTestOn: 'browser');
var test = await runTest(['browser_test.dart']);
expect(test.stdout, emitsThrough(contains('No tests ran.')));
await test.shouldExit(79);
});
test('runs a browser group on a browser', () async {
await _writeTestFile('browser_test.dart', groupTestOn: 'browser');
var test = await runTest(['--platform', 'chrome', 'browser_test.dart']);
expect(test.stdout, emitsThrough(contains('All tests passed!')));
await test.shouldExit(0);
}, tags: 'chrome');
test("doesn't run a VM group on a browser", () async {
await _writeTestFile('vm_test.dart', groupTestOn: 'vm');
var test = await runTest(['--platform', 'chrome', 'vm_test.dart']);
expect(test.stdout, emitsThrough(contains('No tests ran.')));
await test.shouldExit(79);
}, tags: 'chrome');
});
group('for test', () {
test('runs a VM test on the VM', () async {
await _writeTestFile('vm_test.dart', testTestOn: 'vm');
var test = await runTest(['vm_test.dart']);
expect(test.stdout, emitsThrough(contains('All tests passed!')));
await test.shouldExit(0);
});
test("doesn't run a browser test on the VM", () async {
await _writeTestFile('browser_test.dart', testTestOn: 'browser');
var test = await runTest(['browser_test.dart']);
expect(test.stdout, emitsThrough(contains('No tests ran.')));
await test.shouldExit(79);
});
test('runs a browser test on a browser', () async {
await _writeTestFile('browser_test.dart', testTestOn: 'browser');
var test = await runTest(['--platform', 'chrome', 'browser_test.dart']);
expect(test.stdout, emitsThrough(contains('All tests passed!')));
await test.shouldExit(0);
}, tags: 'chrome');
test("doesn't run a VM test on a browser", () async {
await _writeTestFile('vm_test.dart', testTestOn: 'vm');
var test = await runTest(['--platform', 'chrome', 'vm_test.dart']);
expect(test.stdout, emitsThrough(contains('No tests ran.')));
await test.shouldExit(79);
}, tags: 'chrome');
});
group('with suite, group, and test selectors', () {
test('runs the test if all selectors match', () async {
await _writeTestFile('vm_test.dart',
suiteTestOn: '!browser', groupTestOn: '!js', testTestOn: 'vm');
var test = await runTest(['vm_test.dart']);
expect(test.stdout, emitsThrough(contains('All tests passed!')));
await test.shouldExit(0);
});
test("doesn't runs the test if the suite doesn't match", () async {
await _writeTestFile('vm_test.dart',
suiteTestOn: 'browser', groupTestOn: '!js', testTestOn: 'vm');
var test = await runTest(['vm_test.dart']);
expect(test.stdout, emitsThrough(contains('No tests ran.')));
await test.shouldExit(79);
});
test("doesn't runs the test if the group doesn't match", () async {
await _writeTestFile('vm_test.dart',
suiteTestOn: '!browser', groupTestOn: 'browser', testTestOn: 'vm');
var test = await runTest(['vm_test.dart']);
expect(test.stdout, emitsThrough(contains('No tests ran.')));
await test.shouldExit(79);
});
test("doesn't runs the test if the test doesn't match", () async {
await _writeTestFile('vm_test.dart',
suiteTestOn: '!browser', groupTestOn: '!js', testTestOn: 'browser');
var test = await runTest(['vm_test.dart']);
expect(test.stdout, emitsThrough(contains('No tests ran.')));
await test.shouldExit(79);
});
});
}
/// Writes a test file with some platform selectors to [filename].
///
/// Each of [suiteTestOn], [groupTestOn], and [testTestOn] is a platform
/// selector that's suite-, group-, and test-level respectively. If [loadable]
/// is `false`, the test file will be made unloadable on the Dart VM.
Future<void> _writeTestFile(String filename,
{String? suiteTestOn,
String? groupTestOn,
String? testTestOn,
bool loadable = true}) {
var buffer = StringBuffer();
if (suiteTestOn != null) buffer.writeln("@TestOn('$suiteTestOn')");
if (!loadable) buffer.writeln("import 'dart:js_util';");
buffer
..writeln("import 'package:test/test.dart';")
..writeln('void main() {')
..writeln(" group('group', () {");
if (testTestOn != null) {
buffer.writeln(" test('test', () {}, testOn: '$testTestOn');");
} else {
buffer.writeln(" test('test', () {});");
}
if (groupTestOn != null) {
buffer.writeln(" }, testOn: '$groupTestOn');");
} else {
buffer.writeln(' });');
}
buffer.writeln('}');
return d.file(filename, buffer.toString()).create();
}
|
test/pkgs/test/test/runner/test_on_test.dart/0
|
{'file_path': 'test/pkgs/test/test/runner/test_on_test.dart', 'repo_id': 'test', 'token_count': 2968}
|
// 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.
/// {@canonicalFor on_platform.OnPlatform}
/// {@canonicalFor retry.Retry}
/// {@canonicalFor skip.Skip}
/// {@canonicalFor tags.Tags}
/// {@canonicalFor test_on.TestOn}
/// {@canonicalFor timeout.Timeout}
@Deprecated('package:test_api is not intended for general use. '
'Please use package:test.')
library test_api.scaffolding;
export 'src/backend/configuration/on_platform.dart' show OnPlatform;
export 'src/backend/configuration/retry.dart' show Retry;
export 'src/backend/configuration/skip.dart' show Skip;
export 'src/backend/configuration/tags.dart' show Tags;
export 'src/backend/configuration/test_on.dart' show TestOn;
export 'src/backend/configuration/timeout.dart' show Timeout;
export 'src/scaffolding/spawn_hybrid.dart' show spawnHybridUri, spawnHybridCode;
export 'src/scaffolding/test_structure.dart'
show group, test, setUp, setUpAll, tearDown, tearDownAll, addTearDown;
export 'src/scaffolding/utils.dart'
show pumpEventQueue, printOnFailure, markTestSkipped;
|
test/pkgs/test_api/lib/scaffolding.dart/0
|
{'file_path': 'test/pkgs/test_api/lib/scaffolding.dart', 'repo_id': 'test', 'token_count': 400}
|
// 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.
/// An enum of all operating systems supported by Dart.
///
/// This is used for selecting which operating systems a test can run on. Even
/// for browser tests, this indicates the operating system of the machine
/// running the test runner.
class OperatingSystem {
/// Microsoft Windows.
static const windows = OperatingSystem._('Windows', 'windows');
/// Mac OS X.
static const macOS = OperatingSystem._('OS X', 'mac-os');
/// GNU/Linux.
static const linux = OperatingSystem._('Linux', 'linux');
/// Android.
///
/// Since this is the operating system the test runner is running on, this
/// won't be true when testing remotely on an Android browser.
static const android = OperatingSystem._('Android', 'android');
/// iOS.
///
/// Since this is the operating system the test runner is running on, this
/// won't be true when testing remotely on an iOS browser.
static const iOS = OperatingSystem._('iOS', 'ios');
/// No operating system.
///
/// This is used when running in the browser, or if an unrecognized operating
/// system is used. It can't be referenced by name in platform selectors.
static const none = OperatingSystem._('none', 'none');
/// A list of all instances of [OperatingSystem] other than [none].
static const all = [windows, macOS, linux, android, iOS];
/// Finds an operating system by its name.
///
/// If no operating system is found, returns [none].
static OperatingSystem find(String identifier) =>
all.firstWhere((platform) => platform.identifier == identifier,
orElse: () => none);
/// Finds an operating system by the return value from `dart:io`'s
/// `Platform.operatingSystem`.
///
/// If no operating system is found, returns [none].
static OperatingSystem findByIoName(String name) {
switch (name) {
case 'windows':
return windows;
case 'macos':
return macOS;
case 'linux':
return linux;
case 'android':
return android;
case 'ios':
return iOS;
default:
return none;
}
}
/// The human-friendly of the operating system.
final String name;
/// The identifier used to look up the operating system.
final String identifier;
/// Whether this is a POSIX-ish operating system.
bool get isPosix => this != windows && this != none;
const OperatingSystem._(this.name, this.identifier);
@override
String toString() => name;
}
|
test/pkgs/test_api/lib/src/backend/operating_system.dart/0
|
{'file_path': 'test/pkgs/test_api/lib/src/backend/operating_system.dart', 'repo_id': 'test', 'token_count': 771}
|
// 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:matcher/matcher.dart';
import 'package:test_api/hooks.dart';
import 'async_matcher.dart';
import 'util/pretty_print.dart';
/// The type used for functions that can be used to build up error reports
/// upon failures in [expect].
@Deprecated('Will be removed in 0.13.0.')
typedef ErrorFormatter = String Function(dynamic actual, Matcher matcher,
String? reason, Map matchState, bool verbose);
/// Assert that [actual] matches [matcher].
///
/// This is the main assertion function. [reason] is optional and is typically
/// not supplied, as a reason is generated from [matcher]; if [reason]
/// is included it is appended to the reason generated by the matcher.
///
/// [matcher] can be a value in which case it will be wrapped in an
/// [equals] matcher.
///
/// If the assertion fails a [TestFailure] is thrown.
///
/// If [skip] is a String or `true`, the assertion is skipped. The arguments are
/// still evaluated, but [actual] is not verified to match [matcher]. If
/// [actual] is a [Future], the test won't complete until the future emits a
/// value.
///
/// If [skip] is a string, it should explain why the assertion is skipped; this
/// reason will be printed when running the test.
///
/// Certain matchers, like [completion] and [throwsA], either match or fail
/// asynchronously. When you use [expect] with these matchers, it ensures that
/// the test doesn't complete until the matcher has either matched or failed. If
/// you want to wait for the matcher to complete before continuing the test, you
/// can call [expectLater] instead and `await` the result.
void expect(actual, matcher,
{String? reason,
skip,
@Deprecated('Will be removed in 0.13.0.') bool verbose = false,
@Deprecated('Will be removed in 0.13.0.') ErrorFormatter? formatter}) {
_expect(actual, matcher,
reason: reason, skip: skip, verbose: verbose, formatter: formatter);
}
/// Just like [expect], but returns a [Future] that completes when the matcher
/// has finished matching.
///
/// For the [completes] and [completion] matchers, as well as [throwsA] and
/// related matchers when they're matched against a [Future], the returned
/// future completes when the matched future completes. For the [prints]
/// matcher, it completes when the future returned by the callback completes.
/// Otherwise, it completes immediately.
///
/// If the matcher fails asynchronously, that failure is piped to the returned
/// future where it can be handled by user code.
Future expectLater(actual, matcher, {String? reason, skip}) =>
_expect(actual, matcher, reason: reason, skip: skip);
/// The implementation of [expect] and [expectLater].
Future _expect(actual, matcher,
{String? reason, skip, bool verbose = false, ErrorFormatter? formatter}) {
final test = TestHandle.current;
formatter ??= (actual, matcher, reason, matchState, verbose) {
var mismatchDescription = StringDescription();
matcher.describeMismatch(actual, mismatchDescription, matchState, verbose);
return formatFailure(matcher, actual, mismatchDescription.toString(),
reason: reason);
};
if (skip != null && skip is! bool && skip is! String) {
throw ArgumentError.value(skip, 'skip', 'must be a bool or a String');
}
matcher = wrapMatcher(matcher);
if (skip != null && skip != false) {
String message;
if (skip is String) {
message = 'Skip expect: $skip';
} else if (reason != null) {
message = 'Skip expect ($reason).';
} else {
var description = StringDescription().addDescriptionOf(matcher);
message = 'Skip expect ($description).';
}
test.markSkipped(message);
return Future.sync(() {});
}
if (matcher is AsyncMatcher) {
// Avoid async/await so that expect() throws synchronously when possible.
var result = matcher.matchAsync(actual);
expect(result,
anyOf([equals(null), TypeMatcher<Future>(), TypeMatcher<String>()]),
reason: 'matchAsync() may only return a String, a Future, or null.');
if (result is String) {
fail(formatFailure(matcher, actual, result, reason: reason));
} else if (result is Future) {
final outstandingWork = test.markPending();
return result.then((realResult) {
if (realResult == null) return;
fail(formatFailure(matcher as Matcher, actual, realResult as String,
reason: reason));
}).whenComplete(() {
// Always remove this, in case the failure is caught and handled
// gracefully.
outstandingWork.complete();
});
}
return Future.sync(() {});
}
var matchState = {};
try {
if ((matcher as Matcher).matches(actual, matchState)) {
return Future.sync(() {});
}
} catch (e, trace) {
reason ??= '$e at $trace';
}
fail(formatter(actual, matcher as Matcher, reason, matchState, verbose));
}
/// Convenience method for throwing a new [TestFailure] with the provided
/// [message].
Never fail(String message) => throw TestFailure(message);
// The default error formatter.
@Deprecated('Will be removed in 0.13.0.')
String formatFailure(Matcher expected, actual, String which, {String? reason}) {
var buffer = StringBuffer();
buffer.writeln(indent(prettyPrint(expected), first: 'Expected: '));
buffer.writeln(indent(prettyPrint(actual), first: ' Actual: '));
if (which.isNotEmpty) buffer.writeln(indent(which, first: ' Which: '));
if (reason != null) buffer.writeln(reason);
return buffer.toString();
}
|
test/pkgs/test_api/lib/src/expect/expect.dart/0
|
{'file_path': 'test/pkgs/test_api/lib/src/expect/expect.dart', 'repo_id': 'test', 'token_count': 1784}
|
// 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:test/test.dart';
import '../../utils.dart';
void main() {
group('[throwsArgumentError]', () {
test('passes when a ArgumentError is thrown', () {
expect(() => throw ArgumentError(''), throwsArgumentError);
});
test('fails when a non-ArgumentError is thrown', () async {
var liveTest = await runTestBody(() {
expect(() => throw Exception(), throwsArgumentError);
});
expectTestFailed(liveTest,
startsWith("Expected: throws <Instance of 'ArgumentError'>"));
});
});
group('[throwsConcurrentModificationError]', () {
test('passes when a ConcurrentModificationError is thrown', () {
expect(() => throw ConcurrentModificationError(''),
throwsConcurrentModificationError);
});
test('fails when a non-ConcurrentModificationError is thrown', () async {
var liveTest = await runTestBody(() {
expect(() => throw Exception(), throwsConcurrentModificationError);
});
expectTestFailed(
liveTest,
startsWith(
"Expected: throws <Instance of 'ConcurrentModificationError'>"));
});
});
group('[throwsCyclicInitializationError]', () {
test('passes when a CyclicInitializationError is thrown', () {
expect(() => throw CyclicInitializationError(''),
throwsCyclicInitializationError);
});
test('fails when a non-CyclicInitializationError is thrown', () async {
var liveTest = await runTestBody(() {
expect(() => throw Exception(), throwsCyclicInitializationError);
});
expectTestFailed(
liveTest,
startsWith(
"Expected: throws <Instance of 'CyclicInitializationError'>"));
});
});
group('[throwsException]', () {
test('passes when a Exception is thrown', () {
expect(() => throw Exception(''), throwsException);
});
test('fails when a non-Exception is thrown', () async {
var liveTest = await runTestBody(() {
expect(() => throw 'oh no', throwsException);
});
expectTestFailed(
liveTest, startsWith("Expected: throws <Instance of 'Exception'>"));
});
});
group('[throwsFormatException]', () {
test('passes when a FormatException is thrown', () {
expect(() => throw FormatException(''), throwsFormatException);
});
test('fails when a non-FormatException is thrown', () async {
var liveTest = await runTestBody(() {
expect(() => throw Exception(), throwsFormatException);
});
expectTestFailed(liveTest,
startsWith("Expected: throws <Instance of 'FormatException'>"));
});
});
group('[throwsNoSuchMethodError]', () {
test('passes when a NoSuchMethodError is thrown', () {
expect(() {
(1 as dynamic).notAMethodOnInt();
}, throwsNoSuchMethodError);
});
test('fails when a non-NoSuchMethodError is thrown', () async {
var liveTest = await runTestBody(() {
expect(() => throw Exception(), throwsNoSuchMethodError);
});
expectTestFailed(liveTest,
startsWith("Expected: throws <Instance of 'NoSuchMethodError'>"));
});
});
group('[throwsNullThrownError]', () {
test('passes when a NullThrownError is thrown', () {
// Throwing null is no longer allowed with NNBD, but we do want to allow
// it from legacy code and should be able to catch those errors.
expect(() => throw NullThrownError(), throwsNullThrownError);
});
test('fails when a non-NullThrownError is thrown', () async {
var liveTest = await runTestBody(() {
expect(() => throw Exception(), throwsNullThrownError);
});
expectTestFailed(liveTest,
startsWith("Expected: throws <Instance of '$NullThrownError'>"));
});
});
group('[throwsRangeError]', () {
test('passes when a RangeError is thrown', () {
expect(() => throw RangeError(''), throwsRangeError);
});
test('fails when a non-RangeError is thrown', () async {
var liveTest = await runTestBody(() {
expect(() => throw Exception(), throwsRangeError);
});
expectTestFailed(
liveTest, startsWith("Expected: throws <Instance of 'RangeError'>"));
});
});
group('[throwsStateError]', () {
test('passes when a StateError is thrown', () {
expect(() => throw StateError(''), throwsStateError);
});
test('fails when a non-StateError is thrown', () async {
var liveTest = await runTestBody(() {
expect(() => throw Exception(), throwsStateError);
});
expectTestFailed(
liveTest, startsWith("Expected: throws <Instance of 'StateError'>"));
});
});
group('[throwsUnimplementedError]', () {
test('passes when a UnimplementedError is thrown', () {
expect(() => throw UnimplementedError(''), throwsUnimplementedError);
});
test('fails when a non-UnimplementedError is thrown', () async {
var liveTest = await runTestBody(() {
expect(() => throw Exception(), throwsUnimplementedError);
});
expectTestFailed(liveTest,
startsWith("Expected: throws <Instance of 'UnimplementedError'>"));
});
});
group('[throwsUnsupportedError]', () {
test('passes when a UnsupportedError is thrown', () {
expect(() => throw UnsupportedError(''), throwsUnsupportedError);
});
test('fails when a non-UnsupportedError is thrown', () async {
var liveTest = await runTestBody(() {
expect(() => throw Exception(), throwsUnsupportedError);
});
expectTestFailed(liveTest,
startsWith("Expected: throws <Instance of 'UnsupportedError'>"));
});
});
}
|
test/pkgs/test_api/test/frontend/matcher/throws_type_test.dart/0
|
{'file_path': 'test/pkgs/test_api/test/frontend/matcher/throws_type_test.dart', 'repo_id': 'test', 'token_count': 2149}
|
// Copyright (c) 2020, 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.
// ignore: deprecated_member_use
export 'package:test_api/backend.dart' show SuitePlatform, Runtime;
export 'package:test_core/src/runner/configuration.dart' show Configuration;
export 'package:test_core/src/runner/environment.dart'
show PluginEnvironment, Environment;
export 'package:test_core/src/runner/hack_register_platform.dart'
show registerPlatformPlugin;
export 'package:test_core/src/runner/platform.dart' show PlatformPlugin;
export 'package:test_core/src/runner/plugin/platform_helpers.dart'
show deserializeSuite;
export 'package:test_core/src/runner/runner_suite.dart'
show RunnerSuite, RunnerSuiteController;
export 'package:test_core/src/runner/suite.dart' show SuiteConfiguration;
|
test/pkgs/test_core/lib/src/platform.dart/0
|
{'file_path': 'test/pkgs/test_core/lib/src/platform.dart', 'repo_id': 'test', 'token_count': 281}
|
// 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 'dart:math';
import 'package:async/async.dart' hide Result;
import 'package:collection/collection.dart';
import 'package:pool/pool.dart';
import 'package:test_api/src/backend/group.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/invoker.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/live_test.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/live_test_controller.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/message.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/state.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/test.dart'; // ignore: implementation_imports
import 'coverage_stub.dart' if (dart.library.io) 'coverage.dart';
import 'live_suite.dart';
import 'live_suite_controller.dart';
import 'load_suite.dart';
import 'runner_suite.dart';
import 'util/iterable_set.dart';
/// An [Engine] manages a run that encompasses multiple test suites.
///
/// Test suites are provided by passing them into [suiteSink]. Once all suites
/// have been provided, the user should close [suiteSink] to indicate this.
/// [run] won't terminate until [suiteSink] is closed. Suites will be run in the
/// order they're provided to [suiteSink]. Tests within those suites will
/// likewise be run in the order they're declared.
///
/// The current status of every test is visible via [liveTests]. [onTestStarted]
/// can also be used to be notified when a test is about to be run.
///
/// The engine has some special logic for [LoadSuite]s and the tests they
/// contain, referred to as "load tests". Load tests exist to provide visibility
/// into the process of loading test files. As long as that process is
/// proceeding normally users usually don't care about it, so the engine does
/// not include them in [liveTests] and other collections.
/// If a load test fails, it will be added to [failed] and [liveTests].
///
/// The test suite loaded by a load suite will be automatically be run by the
/// engine; it doesn't need to be added to [suiteSink] manually.
///
/// Load tests will always be emitted through [onTestStarted] so users can watch
/// their event streams once they start running.
class Engine {
/// Whether [run] has been called yet.
var _runCalled = false;
/// Whether [close] has been called.
var _closed = false;
/// Whether [close] was called before all the tests finished running.
///
/// This is `null` if close hasn't been called and the tests are still
/// running, `true` if close was called before the tests finished running, and
/// `false` if the tests finished running before close was called.
bool? _closedBeforeDone;
/// The coverage output directory.
String? _coverage;
/// The seed used to generate randomness for test case shuffling.
///
/// If null or zero no shuffling will occur.
/// The same seed will shuffle the tests in the same way every time.
int? testRandomizeOrderingSeed;
/// A pool that limits the number of test suites running concurrently.
final Pool _runPool;
/// A completer that will complete when this engine is unpaused.
///
/// `null` if this engine is not paused.
Completer? _pauseCompleter;
/// A future that completes once this is unpaused.
///
/// If this engine isn't paused, this future completes immediately.
Future get _onUnpaused =>
_pauseCompleter == null ? Future.value() : _pauseCompleter!.future;
/// Whether all tests passed or were skipped.
///
/// This fires once all tests have completed and [suiteSink] has been closed.
/// This will be `null` if [close] was called before all the tests finished
/// running.
Future<bool?> get success async {
await Future.wait(<Future>[_group.future, _runPool.done], eagerError: true);
if (_closedBeforeDone!) return null;
return liveTests.every((liveTest) =>
liveTest.state.result.isPassing &&
liveTest.state.status == Status.complete);
}
/// A group of futures for each test suite.
final _group = FutureGroup();
/// All of the engine's stream subscriptions.
final _subscriptions = <StreamSubscription>{};
/// A sink used to pass [RunnerSuite]s in to the engine to run.
///
/// Suites may be added as quickly as they're available; the Engine will only
/// run as many as necessary at a time based on its concurrency settings.
///
/// Suites added to the sink will be closed by the engine based on its
/// internal logic.
Sink<RunnerSuite> get suiteSink => DelegatingSink(_suiteController.sink);
final _suiteController = StreamController<RunnerSuite>();
/// All the [RunnerSuite]s added to [suiteSink] so far.
///
/// Note that if a [LoadSuite] is added, this will only contain that suite,
/// not the suite it loads.
Set<RunnerSuite> get addedSuites => UnmodifiableSetView(_addedSuites);
final _addedSuites = <RunnerSuite>{};
/// A broadcast stream that emits each [RunnerSuite] as it's added to the
/// engine via [suiteSink].
///
/// Note that if a [LoadSuite] is added, this will only return that suite, not
/// the suite it loads.
///
/// This is guaranteed to fire after the suite is added to [addedSuites].
Stream<RunnerSuite> get onSuiteAdded => _onSuiteAddedController.stream;
final _onSuiteAddedController = StreamController<RunnerSuite>.broadcast();
/// A broadcast stream that emits each [LiveSuite] as it's loaded.
///
/// Note that unlike [onSuiteAdded], for suites that are loaded using
/// [LoadSuite]s, both the [LoadSuite] and the suite it loads will eventually
/// be emitted by this stream.
Stream<LiveSuite> get onSuiteStarted => _onSuiteStartedController.stream;
final _onSuiteStartedController = StreamController<LiveSuite>.broadcast();
/// All the currently-known tests that have run or are running.
///
/// These are [LiveTest]s, representing the in-progress state of each test.
/// Tests that have not yet begun running are marked [Status.pending]; tests
/// that have finished are marked [Status.complete].
///
/// This is guaranteed to contain the same tests as the union of [passed],
/// [skipped], [failed], and [active].
///
/// [LiveTest.run] must not be called on these tests.
Set<LiveTest> get liveTests =>
UnionSet.from([passed, skipped, failed, IterableSet(active)],
disjoint: true);
/// A stream that emits each [LiveTest] as it's about to start running.
///
/// This is guaranteed to fire before [LiveTest.onStateChange] first fires.
Stream<LiveTest> get onTestStarted => _onTestStartedGroup.stream;
final _onTestStartedGroup = StreamGroup<LiveTest>.broadcast();
/// The set of tests that have completed and been marked as passing.
Set<LiveTest> get passed => _passedGroup.set;
final _passedGroup = UnionSetController<LiveTest>(disjoint: true);
/// The set of tests that have completed and been marked as skipped.
Set<LiveTest> get skipped => _skippedGroup.set;
final _skippedGroup = UnionSetController<LiveTest>(disjoint: true);
/// The set of tests that have completed and been marked as failing or error.
Set<LiveTest> get failed => _failedGroup.set;
final _failedGroup = UnionSetController<LiveTest>(disjoint: true);
/// The tests that are still running, in the order they began running.
List<LiveTest> get active => UnmodifiableListView(_active);
final _active = QueueList<LiveTest>();
/// The suites that are still loading, in the order they began.
List<LiveTest> get activeSuiteLoads =>
UnmodifiableListView(_activeSuiteLoads);
final _activeSuiteLoads = <LiveTest>{};
/// The set of tests that have been marked for restarting.
///
/// This is always a subset of [active]. Once a test in here has finished
/// running, it's run again.
final _restarted = <LiveTest>{};
/// Whether this engine is idle—that is, not currently executing a test.
bool get isIdle => _group.isIdle;
/// A broadcast stream that fires an event whenever [isIdle] switches from
/// `false` to `true`.
Stream get onIdle => _group.onIdle;
/// Creates an [Engine] that will run all tests provided via [suiteSink].
///
/// [concurrency] controls how many suites are loaded and ran at once, and
/// defaults to 1.
///
/// [testRandomizeOrderingSeed] configures test case shuffling within each
/// test suite.
/// Any non-zero value will enable shuffling using this value as a seed.
/// Omitting this argument or passing `0` disables shuffling.
///
/// [coverage] specifies a directory to output coverage information.
Engine({int? concurrency, String? coverage, this.testRandomizeOrderingSeed})
: _runPool = Pool(concurrency ?? 1),
_coverage = coverage {
_group.future.then((_) {
_onTestStartedGroup.close();
_onSuiteStartedController.close();
_closedBeforeDone ??= false;
}).onError((_, __) {
// Don't top-level errors. They'll be thrown via [success] anyway.
});
}
/// Creates an [Engine] that will run all tests in [suites].
///
/// An engine constructed this way will automatically close its [suiteSink],
/// meaning that no further suites may be provided.
///
/// [concurrency] controls how many suites are run at once. If [runSkipped] is
/// `true`, skipped tests will be run as though they weren't skipped.
factory Engine.withSuites(List<RunnerSuite> suites,
{int? concurrency, String? coverage}) {
var engine = Engine(concurrency: concurrency, coverage: coverage);
for (var suite in suites) {
engine.suiteSink.add(suite);
}
engine.suiteSink.close();
return engine;
}
/// Runs all tests in all suites defined by this engine.
///
/// This returns `true` if all tests succeed, and `false` otherwise. It will
/// only return once all tests have finished running and [suiteSink] has been
/// closed.
///
/// If [success] completes with `null` this will complete with `null`.
Future<bool?> run() {
if (_runCalled) {
throw StateError('Engine.run() may not be called more than once.');
}
_runCalled = true;
var subscription = _suiteController.stream.listen(null);
subscription
..onData((suite) {
_addedSuites.add(suite);
_onSuiteAddedController.add(suite);
_group.add(() async {
var resource = await _runPool.request();
LiveSuiteController? controller;
try {
if (suite is LoadSuite) {
await _onUnpaused;
controller = await _addLoadSuite(suite);
if (controller == null) return;
} else {
controller = LiveSuiteController(suite);
}
_addLiveSuite(controller.liveSuite);
if (_closed) return;
await _runGroup(controller, controller.liveSuite.suite.group, []);
controller.noMoreLiveTests();
if (_coverage != null) await writeCoverage(_coverage!, controller);
} finally {
resource.allowRelease(() => controller?.close());
}
}());
})
..onDone(() {
_subscriptions.remove(subscription);
_onSuiteAddedController.close();
_group.close();
_runPool.close();
});
_subscriptions.add(subscription);
return success;
}
/// Runs all the entries in [group] in sequence.
///
/// [suiteController] is the controller fo the suite that contains [group].
/// [parents] is a list of groups that contain [group]. It may be modified,
/// but it's guaranteed to be in its original state once this function has
/// finished.
Future _runGroup(LiveSuiteController suiteController, Group group,
List<Group> parents) async {
parents.add(group);
try {
var suiteConfig = suiteController.liveSuite.suite.config;
var skipGroup = !suiteConfig.runSkipped && group.metadata.skip;
var setUpAllSucceeded = true;
if (!skipGroup && group.setUpAll != null) {
var liveTest = group.setUpAll!
.load(suiteController.liveSuite.suite, groups: parents);
await _runLiveTest(suiteController, liveTest, countSuccess: false);
setUpAllSucceeded = liveTest.state.result.isPassing;
}
if (!_closed && setUpAllSucceeded) {
// shuffle the group entries
var entries = group.entries.toList();
if (suiteConfig.allowTestRandomization &&
testRandomizeOrderingSeed != null &&
testRandomizeOrderingSeed! > 0) {
entries.shuffle(Random(testRandomizeOrderingSeed));
}
for (var entry in entries) {
if (_closed) return;
if (entry is Group) {
await _runGroup(suiteController, entry, parents);
} else if (!suiteConfig.runSkipped && entry.metadata.skip) {
await _runSkippedTest(suiteController, entry as Test, parents);
} else {
var test = entry as Test;
await _runLiveTest(suiteController,
test.load(suiteController.liveSuite.suite, groups: parents));
}
}
}
// Even if we're closed or setUpAll failed, we want to run all the
// teardowns to ensure that any state is properly cleaned up.
if (!skipGroup && group.tearDownAll != null) {
var liveTest = group.tearDownAll!
.load(suiteController.liveSuite.suite, groups: parents);
await _runLiveTest(suiteController, liveTest, countSuccess: false);
if (_closed) await liveTest.close();
}
} finally {
parents.remove(group);
}
}
/// Runs [liveTest] using [suiteController].
///
/// If [countSuccess] is `true` (the default), the test is put into [passed]
/// if it succeeds. Otherwise, it's removed from [liveTests] entirely.
Future _runLiveTest(LiveSuiteController suiteController, LiveTest liveTest,
{bool countSuccess = true}) async {
await _onUnpaused;
_active.add(liveTest);
var subscription = liveTest.onStateChange.listen(null);
subscription
..onData((state) {
if (state.status != Status.complete) return;
_active.remove(liveTest);
})
..onDone(() {
_subscriptions.remove(subscription);
});
_subscriptions.add(subscription);
suiteController.reportLiveTest(liveTest, countSuccess: countSuccess);
// Schedule a microtask to ensure that [onTestStarted] fires before the
// first [LiveTest.onStateChange] event.
await Future.microtask(liveTest.run);
// Once the test finishes, use [new Future] to do a coarse-grained event
// loop pump to avoid starving non-microtask events.
await Future(() {});
if (!_restarted.contains(liveTest)) return;
await _runLiveTest(suiteController, liveTest.copy(),
countSuccess: countSuccess);
_restarted.remove(liveTest);
}
/// Runs a dummy [LiveTest] for a test marked as "skip".
///
/// [suiteController] is the controller for the suite that contains [test].
/// [parents] is a list of groups that contain [test].
Future _runSkippedTest(LiveSuiteController suiteController, Test test,
List<Group> parents) async {
await _onUnpaused;
var skipped = LocalTest(test.name, test.metadata, () {}, trace: test.trace);
late LiveTestController controller;
controller =
LiveTestController(suiteController.liveSuite.suite, skipped, () {
controller.setState(const State(Status.running, Result.success));
controller.setState(const State(Status.running, Result.skipped));
if (skipped.metadata.skipReason != null) {
controller
.message(Message.skip('Skip: ${skipped.metadata.skipReason}'));
}
controller.setState(const State(Status.complete, Result.skipped));
controller.completer.complete();
}, () {}, groups: parents);
return await _runLiveTest(suiteController, controller);
}
/// Closes [liveTest] and tells the engine to re-run it once it's done
/// running.
///
/// Returns the same future as [LiveTest.close].
Future restartTest(LiveTest liveTest) async {
if (_activeSuiteLoads.contains(liveTest)) {
throw ArgumentError("Can't restart a load test.");
}
if (!_active.contains(liveTest)) {
throw StateError("Can't restart inactive test "
'"${liveTest.test.name}".');
}
_restarted.add(liveTest);
_active.remove(liveTest);
await liveTest.close();
}
/// Runs [suite] and returns the [LiveSuiteController] for the suite it loads.
///
/// Returns `null` if the suite fails to load.
Future<LiveSuiteController?> _addLoadSuite(LoadSuite suite) async {
var controller = LiveSuiteController(suite);
_addLiveSuite(controller.liveSuite);
var liveTest = suite.test.load(suite);
_activeSuiteLoads.add(liveTest);
var subscription = liveTest.onStateChange.listen(null);
subscription
..onData((state) {
if (state.status != Status.complete) return;
_activeSuiteLoads.remove(liveTest);
})
..onDone(() {
_subscriptions.remove(subscription);
});
_subscriptions.add(subscription);
controller.reportLiveTest(liveTest, countSuccess: false);
controller.noMoreLiveTests();
// Schedule a microtask to ensure that [onTestStarted] fires before the
// first [LiveTest.onStateChange] event.
await Future.microtask(liveTest.run);
var innerSuite = await suite.suite;
if (innerSuite == null) return null;
var innerController = LiveSuiteController(innerSuite);
unawaited(innerController.liveSuite.onClose.whenComplete(() {
// When the main suite is closed, close the load suite and its test as
// well. This doesn't release any resources, but it does close streams
// which indicates that the load test won't experience an error in the
// future.
liveTest.close();
controller.close();
}));
return innerController;
}
/// Add [liveSuite] and the information it exposes to the engine's
/// informational streams and collections.
void _addLiveSuite(LiveSuite liveSuite) {
_onSuiteStartedController.add(liveSuite);
_onTestStartedGroup.add(liveSuite.onTestStarted);
_passedGroup.add(liveSuite.passed);
_skippedGroup.add(liveSuite.skipped);
_failedGroup.add(liveSuite.failed);
}
/// Pauses the engine.
///
/// This pauses all streams and keeps any new suites from being loaded or
/// tests from being run until [resume] is called.
///
/// This does nothing if the engine is already paused. Pauses are *not*
/// cumulative.
void pause() {
if (_pauseCompleter != null) return;
_pauseCompleter = Completer();
for (var subscription in _subscriptions) {
subscription.pause();
}
}
void resume() {
if (_pauseCompleter == null) return;
_pauseCompleter!.complete();
_pauseCompleter = null;
for (var subscription in _subscriptions) {
subscription.resume();
}
}
/// Signals that the caller is done paying attention to test results and the
/// engine should release any resources it has allocated.
///
/// Any actively-running tests are also closed. VM tests are allowed to finish
/// running so that any modifications they've made to the filesystem can be
/// cleaned up.
///
/// **Note that closing the engine is not the same as closing [suiteSink].**
/// Closing [suiteSink] indicates that no more input will be provided, closing
/// the engine indicates that no more output should be emitted.
Future close() async {
_closed = true;
if (_closedBeforeDone != null) _closedBeforeDone = true;
await _suiteController.close();
await _onSuiteAddedController.close();
// Close the running tests first so that we're sure to wait for them to
// finish before we close their suites and cause them to become unloaded.
var allLiveTests = liveTests.toSet()..addAll(_activeSuiteLoads);
var futures = allLiveTests.map((liveTest) => liveTest.close()).toList();
// Closing the run pool will close the test suites as soon as their tests
// are done. For browser suites this is effectively immediate since their
// tests shut down as soon as they're closed, but for VM suites we may need
// to wait for tearDowns or tearDownAlls to run.
futures.add(_runPool.close());
await Future.wait(futures, eagerError: true);
}
}
|
test/pkgs/test_core/lib/src/runner/engine.dart/0
|
{'file_path': 'test/pkgs/test_core/lib/src/runner/engine.dart', 'repo_id': 'test', 'token_count': 6822}
|
// 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:stream_channel/stream_channel.dart';
// ignore: deprecated_member_use
import 'package:test_api/backend.dart'
show RemoteListener, StackTraceFormatter, StackTraceMapper;
/// Returns a channel that will emit a serialized representation of the tests
/// defined in [getMain].
///
/// This channel is used to control the tests. Platform plugins should forward
/// it `deserializeSuite`. It's guaranteed to communicate using only
/// JSON-serializable values.
///
/// Any errors thrown within [getMain], synchronously or not, will be forwarded
/// to the load test for this suite. Prints will similarly be forwarded to that
/// test's print stream.
///
/// If [hidePrints] is `true` (the default), calls to `print()` within this
/// suite will not be forwarded to the parent zone's print handler. However, the
/// caller may want them to be forwarded in (for example) a browser context
/// where they'll be visible in the development console.
///
/// If [beforeLoad] is passed, it's called before the tests have been declared
/// for this worker.
StreamChannel<Object?> serializeSuite(Function Function() getMain,
{bool hidePrints = true,
Future Function(
StreamChannel<Object?> Function(String name) suiteChannel)?
beforeLoad}) =>
RemoteListener.start(
getMain,
hidePrints: hidePrints,
beforeLoad: beforeLoad,
);
/// Sets the stack trace mapper for the current test suite.
///
/// This is used to convert JavaScript stack traces into their Dart equivalents
/// using source maps. It should be set before any tests run, usually in the
/// `onLoad()` callback to [serializeSuite].
void setStackTraceMapper(StackTraceMapper mapper) {
var formatter = StackTraceFormatter.current;
if (formatter == null) {
throw StateError(
'setStackTraceMapper() may only be called within a test worker.');
}
formatter.configure(mapper: mapper);
}
|
test/pkgs/test_core/lib/src/runner/plugin/remote_platform_helpers.dart/0
|
{'file_path': 'test/pkgs/test_core/lib/src/runner/plugin/remote_platform_helpers.dart', 'repo_id': 'test', 'token_count': 626}
|
// Copyright (c) 2020, 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 'dart:convert';
import 'dart:io';
import 'package:async/async.dart';
import 'package:frontend_server_client/frontend_server_client.dart';
import 'package:path/path.dart' as p;
import 'package:pool/pool.dart';
import 'package:test_api/backend.dart'; // ignore: deprecated_member_use
import '../../util/dart.dart';
import '../../util/package_config.dart';
import '../package_version.dart';
class CompilationResponse {
final String? compilerOutput;
final int errorCount;
final Uri? kernelOutputUri;
const CompilationResponse(
{this.compilerOutput, this.errorCount = 0, this.kernelOutputUri});
static const _wasShutdown = CompilationResponse(
errorCount: 1, compilerOutput: 'Compiler no longer active.');
}
class TestCompiler {
final _closeMemo = AsyncMemoizer<void>();
/// Each language version that appears in test files gets its own compiler,
/// to ensure that all language modes are supported (such as sound and
/// unsound null safety).
final _compilerForLanguageVersion =
<String, _TestCompilerForLanguageVersion>{};
/// A prefix used for the dill files for each compiler that is created.
final String _dillCachePrefix;
/// No work is done until the first call to [compile] is received, at which
/// point the compiler process is started.
TestCompiler(this._dillCachePrefix);
/// Compiles [mainDart], using a separate compiler per language version of
/// the tests.
Future<CompilationResponse> compile(Uri mainDart, Metadata metadata) async {
if (_closeMemo.hasRun) return CompilationResponse._wasShutdown;
var languageVersionComment = metadata.languageVersionComment ??
await rootPackageLanguageVersionComment;
var compiler = _compilerForLanguageVersion.putIfAbsent(
languageVersionComment,
() => _TestCompilerForLanguageVersion(
_dillCachePrefix, languageVersionComment));
return compiler.compile(mainDart);
}
Future<void> dispose() => _closeMemo.runOnce(() => Future.wait([
for (var compiler in _compilerForLanguageVersion.values)
compiler.dispose(),
]));
}
class _TestCompilerForLanguageVersion {
final _closeMemo = AsyncMemoizer();
final _compilePool = Pool(1);
final String _dillCachePath;
FrontendServerClient? _frontendServerClient;
final String _languageVersionComment;
late final _outputDill =
File(p.join(_outputDillDirectory.path, 'output.dill'));
final _outputDillDirectory =
Directory.systemTemp.createTempSync('dart_test.');
// Used to create unique file names for final kernel files.
int _compileNumber = 0;
// The largest incremental dill file we created, will be cached under
// the `.dart_tool` dir at the end of compilation.
File? _dillToCache;
_TestCompilerForLanguageVersion(
String dillCachePrefix, this._languageVersionComment)
: _dillCachePath = '$dillCachePrefix.'
'${_dillCacheSuffix(_languageVersionComment, enabledExperiments)}';
String _generateEntrypoint(Uri testUri) {
return '''
$_languageVersionComment
import "dart:isolate";
import "package:test_core/src/bootstrap/vm.dart";
import "$testUri" as test;
void main(_, SendPort sendPort) {
internalBootstrapVmTest(() => test.main, sendPort);
}
''';
}
Future<CompilationResponse> compile(Uri mainUri) =>
_compilePool.withResource(() => _compile(mainUri));
Future<CompilationResponse> _compile(Uri mainUri) async {
_compileNumber++;
if (_closeMemo.hasRun) return CompilationResponse._wasShutdown;
CompileResult? compilerOutput;
final tempFile = File(p.join(_outputDillDirectory.path, 'test.dart'))
..writeAsStringSync(_generateEntrypoint(mainUri));
final testCache = File(_dillCachePath);
try {
if (_frontendServerClient == null) {
if (await testCache.exists()) {
await testCache.copy(_outputDill.path);
}
compilerOutput = await _createCompiler(tempFile.uri);
} else {
compilerOutput =
await _frontendServerClient!.compile(<Uri>[tempFile.uri]);
}
} catch (e, s) {
if (_closeMemo.hasRun) return CompilationResponse._wasShutdown;
return CompilationResponse(errorCount: 1, compilerOutput: '$e\n$s');
} finally {
_frontendServerClient?.accept();
_frontendServerClient?.reset();
}
// The client is guaranteed initialized at this point.
final outputPath = compilerOutput?.dillOutput;
if (outputPath == null) {
return CompilationResponse(
compilerOutput: compilerOutput?.compilerOutputLines.join('\n'),
errorCount: compilerOutput?.errorCount ?? 0);
}
final outputFile = File(outputPath);
final kernelReadyToRun =
await outputFile.copy('${tempFile.path}_$_compileNumber.dill');
// Keep the `_dillToCache` file up-to-date and use the size of the
// kernel file as an approximation for how many packages are included.
// Larger files are preferred, since re-using more packages will reduce the
// number of files the frontend server needs to load and parse.
if (_dillToCache == null ||
(_dillToCache!.lengthSync() < kernelReadyToRun.lengthSync())) {
_dillToCache = kernelReadyToRun;
}
return CompilationResponse(
compilerOutput: compilerOutput?.compilerOutputLines.join('\n'),
errorCount: compilerOutput?.errorCount ?? 0,
kernelOutputUri: kernelReadyToRun.absolute.uri);
}
Future<CompileResult?> _createCompiler(Uri testUri) async {
final platformDill = 'lib/_internal/vm_platform_strong.dill';
final sdkRoot =
p.relative(p.dirname(p.dirname(Platform.resolvedExecutable)));
var client = _frontendServerClient = await FrontendServerClient.start(
testUri.toString(),
_outputDill.path,
platformDill,
enabledExperiments: enabledExperiments,
sdkRoot: sdkRoot,
packagesJson: (await packageConfigUri).toFilePath(),
printIncrementalDependencies: false,
);
return client.compile();
}
Future<void> dispose() => _closeMemo.runOnce(() async {
await _compilePool.close();
if (_dillToCache != null) {
var testCache = File(_dillCachePath);
if (!testCache.parent.existsSync()) {
testCache.parent.createSync(recursive: true);
}
_dillToCache!.copySync(_dillCachePath);
}
_frontendServerClient?.kill();
_frontendServerClient = null;
if (_outputDillDirectory.existsSync()) {
_outputDillDirectory.deleteSync(recursive: true);
}
});
}
/// Computes a unique dill cache suffix for each [languageVersionComment]
/// and [enabledExperiments] combination.
String _dillCacheSuffix(
String languageVersionComment, List<String> enabledExperiments) {
var identifierString =
StringBuffer(languageVersionComment.replaceAll(' ', ''));
for (var experiment in enabledExperiments) {
identifierString.writeln(experiment);
}
return base64.encode(utf8.encode(identifierString.toString()));
}
|
test/pkgs/test_core/lib/src/runner/vm/test_compiler.dart/0
|
{'file_path': 'test/pkgs/test_core/lib/src/runner/vm/test_compiler.dart', 'repo_id': 'test', 'token_count': 2572}
|
# See https://pub.dev/packages/mono_repo
sdk:
- dev
stages:
- analyze_and_format:
- group:
- format
- analyze: --fatal-infos
sdk: dev
- group:
- analyze
sdk: pubspec
|
test/pkgs/test_core/mono_pkg.yaml/0
|
{'file_path': 'test/pkgs/test_core/mono_pkg.yaml', 'repo_id': 'test', 'token_count': 89}
|
# This file contains configurations to run customer_tests using
# GitHub actions. To learn more about github actions and how to
# update this file please refer to https://docs.github.com/en/actions.
name: Tests
on:
push:
branches:
- main
pull_request:
# Declare default permissions as read only.
permissions: read-all
jobs:
linux_tests:
runs-on: ubuntu-latest
strategy:
matrix:
include:
- name: shard 1 of 3
shard-index: 0
- name: shard 2 of 3
shard-index: 1
- name: shard 3 of 3
shard-index: 2
steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11
- name: ${{ matrix.name }}
run: scripts/verify_tests_on_main.sh --shards 3 --shard-index ${{ matrix.shard-index }}
skp_generator_tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11
- name: skp_generator
run: (cd skp_generator && ./build.sh)
windows_tests:
runs-on: windows-latest
strategy:
matrix:
include:
- name: shard 1 of 5
shard-index: 0
- name: shard 2 of 5
shard-index: 1
- name: shard 3 of 5
shard-index: 2
- name: shard 4 of 5
shard-index: 3
- name: shard 5 of 5
shard-index: 4
steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11
- name: ${{ matrix.name }}
run: scripts\verify_tests_on_main.bat --shards 5 --shard-index ${{ matrix.shard-index }}
macos_tests:
runs-on: macos-latest
strategy:
matrix:
include:
- name: shard 1 of 2
shard-index: 0
- name: shard 2 of 2
shard-index: 1
steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11
- name: ${{ matrix.name }}
run: scripts/verify_tests_on_main.sh --shards 2 --shard-index ${{ matrix.shard-index }}
|
tests/.github/workflows/tests.yml/0
|
{'file_path': 'tests/.github/workflows/tests.yml', 'repo_id': 'tests', 'token_count': 976}
|
name: example
description: A new Flutter project.
publish_to: 'none'
version: 0.1.0
environment:
sdk: '>=3.1.4 <4.0.0'
dependencies:
flutter:
sdk: flutter
textura:
path: ../
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
flutter:
uses-material-design: true
|
textura/example/pubspec.yaml/0
|
{'file_path': 'textura/example/pubspec.yaml', 'repo_id': 'textura', 'token_count': 137}
|
import 'dart:math';
import 'package:flutter/rendering.dart';
class LinenTextureRenderObject extends RenderProxyBox {
@override
bool hitTestSelf(Offset position) => true;
@override
void paint(PaintingContext context, Offset offset) {
context.canvas.save();
context.canvas.translate(offset.dx, offset.dy);
const beige = Color(0xFFF5F5DC); // Defining a custom beige color
final basePaint = Paint()
..color = beige
..style = PaintingStyle.fill;
// Fill the canvas with the base color
context.canvas.drawRect(offset & size, basePaint);
final random = Random(0);
final linePaint = Paint()..strokeWidth = 1;
// Draw horizontal lines
for (var y = 0.0; y <= size.height; y += 5) {
linePaint.color = beige.withOpacity(0.5 + random.nextDouble() * 0.5);
context.canvas.drawLine(Offset(0, y), Offset(size.width, y), linePaint);
}
// Draw vertical lines
for (var x = 0.0; x <= size.width; x += 5) {
linePaint.color = beige.withOpacity(0.5 + random.nextDouble() * 0.5);
context.canvas.drawLine(Offset(x, 0), Offset(x, size.height), linePaint);
}
context.canvas.restore();
super.paint(context, offset);
}
}
|
textura/lib/src/textures/fabrics/linen.dart/0
|
{'file_path': 'textura/lib/src/textures/fabrics/linen.dart', 'repo_id': 'textura', 'token_count': 464}
|
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class FoamTextureRenderObject extends RenderProxyBox {
@override
bool hitTestSelf(Offset position) => true;
@override
void paint(PaintingContext context, Offset offset) {
context.canvas.save();
context.canvas.translate(offset.dx, offset.dy);
final basePaint = Paint()
..color = Colors.white // Base color of the foam
..style = PaintingStyle.fill;
// Fill the canvas with the base color
context.canvas.drawRect(offset & size, basePaint);
final bubblePaint = Paint()
..color = Colors.grey.withOpacity(0.1); // Color of the bubbles
final random = Random(0);
// Add circles of varying sizes and opacities to simulate bubbles
for (var i = 0; i < 500; i++) {
final x = random.nextDouble() * size.width;
final y = random.nextDouble() * size.height;
final radius = random.nextDouble() * 20;
context.canvas.drawCircle(Offset(x, y), radius, bubblePaint);
}
context.canvas.restore();
super.paint(context, offset);
}
}
|
textura/lib/src/textures/miscellaneous/foam.dart/0
|
{'file_path': 'textura/lib/src/textures/miscellaneous/foam.dart', 'repo_id': 'textura', 'token_count': 392}
|
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class GrassTextureRenderObject 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 ground color
final basePaint = Paint()
..color = Colors.green[800]!
..style = PaintingStyle.fill;
canvas.drawRect(offset & size, basePaint);
// Adding grass blades for texture
final grassPaint = Paint()
..color = Colors.green[600]!
..style = PaintingStyle.stroke;
final random = Random(0);
const grassBladeCount = 500;
for (var i = 0; i < grassBladeCount; i++) {
final x = random.nextDouble() * size.width;
final y = random.nextDouble() * size.height;
final height = random.nextDouble() * 20 + 10;
final curveX = x + random.nextDouble() * 10 - 5;
final path = Path()
..moveTo(x, y)
..quadraticBezierTo(curveX, y - height / 2, x, y - height);
canvas.drawPath(path, grassPaint);
}
// Painting the child with an offset
if (child != null) {
context.paintChild(child!, offset);
}
}
}
|
textura/lib/src/textures/nature/grass.dart/0
|
{'file_path': 'textura/lib/src/textures/nature/grass.dart', 'repo_id': 'textura', 'token_count': 503}
|
import 'dart:math';
import 'package:flutter/rendering.dart';
class MosaicTextureRenderObject extends RenderProxyBox {
@override
bool hitTestSelf(Offset position) => true;
@override
void paint(PaintingContext context, Offset offset) {
context.canvas.save();
context.canvas.translate(offset.dx, offset.dy);
final random = Random(0);
const mosaicTileSize = 20.0;
// Drawing mosaic tiles
for (var x = 0.0; x < size.width; x += mosaicTileSize) {
for (var y = 0.0; y < size.height; y += mosaicTileSize) {
final mosaicPaint = Paint()
..color = Color.fromRGBO(
random.nextInt(256),
random.nextInt(256),
random.nextInt(256),
1,
);
context.canvas.drawRect(
Rect.fromLTWH(x, y, mosaicTileSize, mosaicTileSize),
mosaicPaint,
);
}
}
context.canvas.restore();
super.paint(context, offset);
}
}
|
textura/lib/src/textures/patterns/mosaic.dart/0
|
{'file_path': 'textura/lib/src/textures/patterns/mosaic.dart', 'repo_id': 'textura', 'token_count': 416}
|
// import 'dart:async';
// import 'package:flutter/foundation.dart';
// import 'package:flutter/material.dart';
// import 'package:flutter/widgets.dart';
// import 'package:three_dart/three_dart.dart' as three;
// import 'package:three_dart_jsm/three_dart_jsm.dart' as three_jsm;
// class webgpu_rtt extends StatefulWidget {
// String fileName;
// webgpu_rtt({Key? key, required this.fileName}) : super(key: key);
// _MyAppState createState() => _MyAppState();
// }
// class _MyAppState extends State<webgpu_rtt> {
// three.WebGPURenderer? renderer;
// int? fboId;
// late double width;
// late double height;
// Size? screenSize;
// late three.Scene scene;
// late three.Camera camera;
// late three.Mesh mesh;
// num dpr = 1.0;
// bool verbose = true;
// bool disposed = false;
// bool loaded = false;
// late three.Object3D box;
// late three.Texture texture;
// late three.WebGLMultisampleRenderTarget renderTarget;
// @override
// void initState() {
// super.initState();
// }
// // Platform messages are asynchronous, so we initialize in an async method.
// Future<void> initPlatformState() async {
// width = screenSize!.width;
// height = screenSize!.height;
// init();
// }
// initSize(BuildContext context) {
// if (screenSize != null) {
// return;
// }
// final mqd = MediaQuery.of(context);
// screenSize = mqd.size;
// dpr = mqd.devicePixelRatio;
// initPlatformState();
// }
// @override
// Widget build(BuildContext context) {
// return Scaffold(
// appBar: AppBar(
// title: Text(widget.fileName),
// ),
// body: Builder(
// builder: (BuildContext context) {
// initSize(context);
// return SingleChildScrollView(child: _build(context));
// },
// ),
// floatingActionButton: FloatingActionButton(
// child: const Text("render"),
// onPressed: () {
// clickRender();
// },
// ),
// );
// }
// Widget _build(BuildContext context) {
// return Column(
// children: [
// Container(
// child: Stack(
// children: [
// Container(
// width: width,
// height: height,
// color: Colors.black,
// )
// ],
// ),
// ),
// ],
// );
// }
// init() {
// camera = new three.PerspectiveCamera( 70, width / height, 0.1, 10 );
// camera.position.z = 4;
// scene = new three.Scene();
// scene.background = new three.Color( 0x222222 );
// // textured mesh
// var geometryBox = new three.BoxGeometry();
// var materialBox = new three.MeshBasicNodeMaterial(null);
// materialBox.colorNode = new three.ColorNode( new three.Color(1.0, 1.0, 0.5) );
// box = new three.Mesh( geometryBox, materialBox );
// scene.add( box );
// renderer = new three.WebGPURenderer({
// "width": 300,
// "height": 300,
// "antialias": true
// });
// renderer!.setPixelRatio( dpr );
// renderer!.setSize( width.toInt(), height.toInt() );
// renderer!.init();
// var pars = three.WebGLRenderTargetOptions({"format": three.RGBAFormat});
// renderTarget = three.WebGLMultisampleRenderTarget(
// (width * dpr), (height * dpr), pars);
// renderTarget.samples = 4;
// renderer!.setRenderTarget(renderTarget);
// // sourceTexture = renderer!.getRenderTargetGLTexture(renderTarget);
// }
// animate() {
// box.rotation.x += 0.01;
// box.rotation.y += 0.02;
// renderer!.render( scene, camera );
// Future.delayed(const Duration(milliseconds: 33), () {
// animate();
// });
// }
// clickRender() {
// box.rotation.x += 0.01;
// box.rotation.y += 0.02;
// renderer!.render( scene, camera );
// }
// @override
// void dispose() {
// print(" dispose ............. ");
// disposed = true;
// super.dispose();
// }
// }
|
three_dart/example/lib/webgpu_rtt.dart/0
|
{'file_path': 'three_dart/example/lib/webgpu_rtt.dart', 'repo_id': 'three_dart', 'token_count': 1767}
|
import 'package:flutter_gl/flutter_gl.dart';
import 'package:three_dart/three3d/constants.dart';
import 'package:three_dart/three3d/core/interleaved_buffer.dart';
abstract class BaseBufferAttribute<TData extends NativeArray> {
late TData array;
late int itemSize;
InterleavedBuffer? data;
late String type;
// 保持可空
// 在 Mesh.updateMorphTargets 里当name是null时使用index替换
String? name;
int count = 0;
bool normalized = false;
int usage = StaticDrawUsage;
int version = 0;
Map<String, int>? updateRange;
void Function()? onUploadCallback;
int? buffer;
int? elementSize;
BaseBufferAttribute();
}
|
three_dart/lib/three3d/core/base_buffer_attribute.dart/0
|
{'file_path': 'three_dart/lib/three3d/core/base_buffer_attribute.dart', 'repo_id': 'three_dart', 'token_count': 235}
|
import 'package:flutter_gl/flutter_gl.dart';
import 'package:three_dart/three3d/core/index.dart';
import 'package:three_dart/three3d/math/index.dart';
class LatheGeometry extends BufferGeometry {
LatheGeometry(
points, {
segments = 12,
phiStart = 0,
double phiLength = Math.pi * 2,
}) : super() {
type = 'LatheGeometry';
parameters = {
"points": points,
"segments": segments,
"phiStart": phiStart,
"phiLength": phiLength,
};
segments = Math.floor(segments);
// clamp phiLength so it's in range of [ 0, 2PI ]
phiLength = MathUtils.clamp(phiLength, 0, Math.pi * 2);
// buffers
var indices = [];
List<double> vertices = [];
List<double> uvs = [];
var initNormals = [];
List<double> normals = [];
// helper variables
var inverseSegments = 1.0 / segments;
var vertex = Vector3.init();
var uv = Vector2(null, null);
var normal = Vector3();
var curNormal = Vector3();
var prevNormal = Vector3();
double dx = 0;
double dy = 0;
// pre-compute normals for initial "meridian"
for (var j = 0; j <= (points.length - 1); j++) {
// special handling for 1st vertex on path
if (j == 0) {
dx = points[j + 1].x - points[j].x;
dy = points[j + 1].y - points[j].y;
normal.x = dy * 1.0;
normal.y = -dx;
normal.z = dy * 0.0;
prevNormal.copy(normal);
normal.normalize();
initNormals.addAll([normal.x, normal.y, normal.z]);
} else if (j == points.length - 1) {
// special handling for last Vertex on path
initNormals.addAll([prevNormal.x, prevNormal.y, prevNormal.z]);
} else {
// default handling for all vertices in between
dx = points[j + 1].x - points[j].x;
dy = points[j + 1].y - points[j].y;
normal.x = dy * 1.0;
normal.y = -dx;
normal.z = dy * 0.0;
curNormal.copy(normal);
normal.x += prevNormal.x;
normal.y += prevNormal.y;
normal.z += prevNormal.z;
normal.normalize();
initNormals.addAll([normal.x, normal.y, normal.z]);
prevNormal.copy(curNormal);
}
}
// generate vertices, uvs and normals
// generate vertices and uvs
for (var i = 0; i <= segments; i++) {
var phi = phiStart + i * inverseSegments * phiLength;
var sin = Math.sin(phi);
var cos = Math.cos(phi);
for (var j = 0; j <= (points.length - 1); j++) {
// vertex
vertex.x = points[j].x * sin;
vertex.y = points[j].y;
vertex.z = points[j].x * cos;
vertices.addAll([vertex.x.toDouble(), vertex.y.toDouble(), vertex.z.toDouble()]);
// uv
uv.x = i / segments;
uv.y = j / (points.length - 1);
uvs.addAll([uv.x.toDouble(), uv.y.toDouble()]);
// normal
var x = initNormals[3 * j + 0] * sin;
var y = initNormals[3 * j + 1];
var z = initNormals[3 * j + 0] * cos;
normals.addAll([x, y, z]);
}
}
// indices
for (var i = 0; i < segments; i++) {
for (var j = 0; j < (points.length - 1); j++) {
var base = j + i * points.length;
var a = base;
var b = base + points.length;
var c = base + points.length + 1;
var d = base + 1;
// faces
indices.addAll([a, b, d]);
indices.addAll([c, d, b]);
}
}
// build geometry
setIndex(indices);
setAttribute('position', Float32BufferAttribute(Float32Array.from(vertices), 3, false));
setAttribute('uv', Float32BufferAttribute(Float32Array.from(uvs), 2, false));
setAttribute('normal', Float32BufferAttribute(Float32Array.from(normals), 3, false));
}
}
|
three_dart/lib/three3d/geometries/lathe_geometry.dart/0
|
{'file_path': 'three_dart/lib/three3d/geometries/lathe_geometry.dart', 'repo_id': 'three_dart', 'token_count': 1680}
|
import 'package:three_dart/three3d/core/object_3d.dart';
import 'package:three_dart/three3d/lights/light.dart';
import 'package:three_dart/three3d/math/color.dart';
class HemisphereLight extends Light {
HemisphereLight(skyColor, groundColor, [double intensity = 1.0]) : super(skyColor, intensity) {
type = 'HemisphereLight';
position.copy(Object3D.defaultUp);
isHemisphereLight = true;
updateMatrix();
if (groundColor is Color) {
this.groundColor = groundColor;
} else if (groundColor is int) {
this.groundColor = Color.fromHex(groundColor);
} else {
throw ("HemisphereLight init groundColor type is not support $groundColor ");
}
}
@override
copy(Object3D source, [bool? recursive]) {
super.copy(source);
HemisphereLight source1 = source as HemisphereLight;
groundColor!.copy(source1.groundColor!);
return this;
}
}
|
three_dart/lib/three3d/lights/hemisphere_light.dart/0
|
{'file_path': 'three_dart/lib/three3d/lights/hemisphere_light.dart', 'repo_id': 'three_dart', 'token_count': 319}
|
import 'dart:async';
import 'package:three_dart/three3d/loaders/cache.dart';
import 'package:three_dart/three3d/loaders/loader.dart';
import 'image_loader_for_app.dart' if (dart.library.js) 'image_loader_for_web.dart';
class ImageLoader extends Loader {
ImageLoader(manager) : super(manager) {
flipY = true;
}
@override
loadAsync(url, [Function? onProgress]) async {
var completer = Completer();
load(url, (buffer) {
completer.complete(buffer);
}, onProgress, () {});
return completer.future;
}
@override
load(url, onLoad, [onProgress, onError]) async {
if (path != "" && url is String) {
url = path + url;
}
url = manager.resolveURL(url);
var cached = Cache.get(url);
if (cached != null) {
manager.itemStart(url);
Future.delayed(Duration(milliseconds: 0), () {
onLoad(cached);
manager.itemEnd(url);
});
return cached;
}
final resp = await ImageLoaderLoader.loadImage(url, flipY);
onLoad(resp);
return resp;
}
}
|
three_dart/lib/three3d/loaders/image_loader.dart/0
|
{'file_path': 'three_dart/lib/three3d/loaders/image_loader.dart', 'repo_id': 'three_dart', 'token_count': 423}
|
import 'package:three_dart/three3d/materials/line_basic_material.dart';
import 'package:three_dart/three3d/materials/material.dart';
class LineDashedMaterial extends LineBasicMaterial {
LineDashedMaterial([Map<String, dynamic>? parameters]) : super() {
type = 'LineDashedMaterial';
scale = 1;
dashSize = 3;
gapSize = 1;
setValues(parameters);
}
@override
LineDashedMaterial copy(Material source) {
super.copy(source);
scale = source.scale;
dashSize = source.dashSize;
gapSize = source.gapSize;
return this;
}
}
|
three_dart/lib/three3d/materials/line_dashed_material.dart/0
|
{'file_path': 'three_dart/lib/three3d/materials/line_dashed_material.dart', 'repo_id': 'three_dart', 'token_count': 204}
|
import 'dart:math' as math;
class Math {
static double infinity = double.maxFinite;
static const double pi = math.pi;
static double ln2 = math.ln2;
static const double epsilon = 4.94065645841247E-324;
static double log2e = math.log2e;
static double maxValue = double.maxFinite;
static double ln10 = math.ln10;
static double sqrt1_2 = math.sqrt1_2;
// TODO
static int maxSafeInteger = 9007199254740991;
static T min<T extends num>(T x, T y) {
return math.min(x, y);
}
static num min3(num x, num y, num z) {
return min(min(x, y), z);
}
static T max<T extends num>(T x, T y) {
return math.max(x, y);
}
static num max3(num x, num y, num z) {
return max(max(x, y), z);
}
static int floor(num x) {
return x.floor();
}
static int ceil(num x) {
return x.ceil();
}
static int round(num x) {
return x.round();
}
static double sqrt(num x) {
return math.sqrt(x);
}
static num abs(num x) {
return x.abs();
}
static double atan2(num x, num y) {
return math.atan2(x, y);
}
static double cos(num x) {
return math.cos(x);
}
static double sin(num x) {
return math.sin(x);
}
static double acos(num x) {
return math.acos(x);
}
static double asin(num x) {
return math.asin(x);
}
static double random() {
return math.Random().nextDouble();
}
static double randomFromA2B(num a, num b) {
var result = random() * (b - a) + a;
return result;
}
static num pow(num x, num y) {
return math.pow(x, y);
}
static num log(num x) {
return math.log(x);
}
static double tan(num x) {
return math.tan(x);
}
static double atan(double x) {
return math.atan(x);
}
static double sign(double x) {
return x.sign;
}
static double exp(num x) {
return math.exp(x);
}
static double log2(num x) {
return log(x) / ln2;
}
// Random float from <low, high> interval
static double randFloat(num low, num high) {
return low + Math.random() * (high - low);
}
// Random float from <-range/2, range/2> interval
static double randFloatSpread(num range) {
return range * (0.5 - Math.random());
}
}
bool isFinite(num v) {
return v != Math.infinity || v != -Math.infinity;
}
|
three_dart/lib/three3d/math/math.dart/0
|
{'file_path': 'three_dart/lib/three3d/math/math.dart', 'repo_id': 'three_dart', 'token_count': 906}
|
import 'package:three_dart/three3d/core/object_3d.dart';
class Bone extends Object3D {
Bone() : super() {
type = 'Bone';
}
@override
Bone clone([bool? recursive]) {
return Bone()..copy(this, recursive);
}
}
|
three_dart/lib/three3d/objects/bone.dart/0
|
{'file_path': 'three_dart/lib/three3d/objects/bone.dart', 'repo_id': 'three_dart', 'token_count': 87}
|
String alphamapFragment = """
#ifdef USE_ALPHAMAP
diffuseColor.a *= texture2D( alphaMap, vUv ).g;
#endif
""";
|
three_dart/lib/three3d/renderers/shaders/shader_chunk/alphamap_fragment.glsl.dart/0
|
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/alphamap_fragment.glsl.dart', 'repo_id': 'three_dart', 'token_count': 49}
|
String clippingPlanesVertex = """
#if NUM_CLIPPING_PLANES > 0
vClipPosition = - mvPosition.xyz;
#endif
""";
|
three_dart/lib/three3d/renderers/shaders/shader_chunk/clipping_planes_vertex.glsl.dart/0
|
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/clipping_planes_vertex.glsl.dart', 'repo_id': 'three_dart', 'token_count': 45}
|
String encodingsFragment = """
gl_FragColor = linearToOutputTexel( gl_FragColor );
""";
|
three_dart/lib/three3d/renderers/shaders/shader_chunk/encodings_fragment.glsl.dart/0
|
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/encodings_fragment.glsl.dart', 'repo_id': 'three_dart', 'token_count': 29}
|
String mapParsFragment = """
#ifdef USE_MAP
uniform sampler2D map;
#endif
""";
|
three_dart/lib/three3d/renderers/shaders/shader_chunk/map_pars_fragment.glsl.dart/0
|
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/map_pars_fragment.glsl.dart', 'repo_id': 'three_dart', 'token_count': 33}
|
import 'package:three_dart/three3d/renderers/web_gl_render_target.dart';
import 'package:three_dart/three3d/textures/index.dart';
class WebGL3DRenderTarget extends WebGLRenderTarget {
WebGL3DRenderTarget(int width, int height, int depth) : super(width, height) {
this.depth = depth;
texture = Data3DTexture(null, width, height, depth);
texture.isRenderTargetTexture = true;
}
}
|
three_dart/lib/three3d/renderers/web_gl_3d_render_target.dart/0
|
{'file_path': 'three_dart/lib/three3d/renderers/web_gl_3d_render_target.dart', 'repo_id': 'three_dart', 'token_count': 138}
|
import 'package:three_dart/three3d/cameras/index.dart';
import 'package:three_dart/three3d/lights/index.dart';
import 'package:three_dart/three3d/renderers/webgl/index.dart';
import 'package:three_dart/three3d/weak_map.dart';
class WebGLRenderState {
late WebGLLights lights;
WebGLExtensions extensions;
WebGLCapabilities capabilities;
List<Light> lightsArray = [];
List<Light> shadowsArray = [];
WebGLRenderState(this.extensions, this.capabilities) {
lights = WebGLLights(extensions, capabilities);
}
RenderState get state {
return RenderState(lights, lightsArray, shadowsArray);
}
void init() {
lightsArray.length = 0;
shadowsArray.length = 0;
}
void pushLight(Light light) {
lightsArray.add(light);
}
void pushShadow(Light shadowLight) {
shadowsArray.add(shadowLight);
}
void setupLights([bool? physicallyCorrectLights]) {
lights.setup(lightsArray, physicallyCorrectLights);
}
void setupLightsView(Camera camera) {
lights.setupView(lightsArray, camera);
}
}
class WebGLRenderStates {
WebGLExtensions extensions;
WebGLCapabilities capabilities;
var renderStates = WeakMap();
WebGLRenderStates(this.extensions, this.capabilities);
WebGLRenderState get(scene, {int renderCallDepth = 0}) {
WebGLRenderState renderState;
if (renderStates.has(scene) == false) {
renderState = WebGLRenderState(extensions, capabilities);
renderStates.add(key: scene, value: [renderState]);
} else {
if (renderCallDepth >= renderStates.get(scene).length) {
renderState = WebGLRenderState(extensions, capabilities);
renderStates.get(scene).add(renderState);
} else {
renderState = renderStates.get(scene)[renderCallDepth];
}
}
return renderState;
}
void dispose() {
renderStates = WeakMap();
}
}
class RenderState {
WebGLLights lights;
List<Light> lightsArray;
List<Light> shadowsArray;
RenderState(this.lights, this.lightsArray, this.shadowsArray);
}
|
three_dart/lib/three3d/renderers/webgl/web_gl_render_states.dart/0
|
{'file_path': 'three_dart/lib/three3d/renderers/webgl/web_gl_render_states.dart', 'repo_id': 'three_dart', 'token_count': 692}
|
import 'package:flutter_gl/flutter_gl.dart';
import 'package:three_dart/three_dart.dart';
T? arrayMin<T extends num>(List<T> array) {
if (array.isEmpty) return null; //return 9999999;
var min = array[0];
for (var i = 1, l = array.length; i < l; ++i) {
if (array[i] < min) min = array[i];
}
return min;
}
T? arrayMax<T extends num>(List<T> array) {
if (array.isEmpty) return null; // return -99999999;
var max = array[0];
for (var i = 1, l = array.length; i < l; ++i) {
if (array[i] > max) max = array[i];
}
return max;
}
// var TYPED_ARRAYS = {
// Int8Array: Int8Array,
// Uint8Array: Uint8Array,
// // Workaround for IE11 pre KB2929437. See #11440
// Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
// Int16Array: Int16Array,
// Uint16Array: Uint16Array,
// Int32Array: Int32Array,
// Uint32Array: Uint32Array,
// Float32Array: Float32Array,
// Float64Array: Float64Array
// };
NativeArray getTypedArray(String type, List buffer) {
if (type == "Uint32Array" || type == "Uint32List") {
return Uint32Array.from(List<int>.from(buffer));
} else if (type == "Uint16Array" || type == "Uint16List") {
return Uint16Array.from(List<int>.from(buffer));
} else if (type == "Float32Array" || type == "Float32List") {
return Float32Array.from(List<double>.from(buffer));
} else {
throw (" Util.dart getTypedArray type: $type is not support ");
}
}
BufferAttribute getTypedAttribute(NativeArray array, int itemSize, [bool normalized = false]) {
if (array is Uint32Array) {
return Uint32BufferAttribute(array, itemSize, normalized);
} else if (array is Uint16Array) {
return Uint16BufferAttribute(array, itemSize, normalized);
} else if (array is Float32Array) {
return Float32BufferAttribute(array, itemSize, normalized);
} else {
throw (" Util.dart getTypedArray type: $array is not support ");
}
}
|
three_dart/lib/three3d/utils.dart/0
|
{'file_path': 'three_dart/lib/three3d/utils.dart', 'repo_id': 'three_dart', 'token_count': 732}
|
part of tiled;
/// Below is Tiled's documentation about how this structure is represented
/// on XML files:
///
/// <export>
///
/// * target: The last file this map was exported to.
/// * format: The short name of the last format this map was exported as.
class Export {
String format;
String target;
Export({
required this.format,
required this.target,
});
Export.parse(Parser parser)
: this(
format: parser.getString('format'),
target: parser.getString('target'),
);
}
|
tiled.dart/packages/tiled/lib/src/editor_setting/export.dart/0
|
{'file_path': 'tiled.dart/packages/tiled/lib/src/editor_setting/export.dart', 'repo_id': 'tiled.dart', 'token_count': 174}
|
part of tiled;
/// abstract class to be implemented for an external tileset data provider.
abstract class TsxProvider {
/// Unique filename for the tileset to be loaded. This should match the
/// 'source' property in the map.tmx file.
String get filename;
/// Retrieves the external tileset data given the tileset filename.
Parser getSource(String filename);
/// Used when provider implementations cache the data. Returns the cached
/// data for the exernal tileset.
Parser? getCachedSource();
/// Parses a file returning a [TsxProvider].
static Future<TsxProvider> parse(String key) {
throw UnimplementedError();
}
}
|
tiled.dart/packages/tiled/lib/src/tsx_provider.dart/0
|
{'file_path': 'tiled.dart/packages/tiled/lib/src/tsx_provider.dart', 'repo_id': 'tiled.dart', 'token_count': 175}
|
import 'dart:io';
import 'dart:ui';
import 'package:flutter_test/flutter_test.dart';
import 'package:tiled/tiled.dart';
void main() {
late TiledMap mapTmx;
late TiledMap mapTmxBase64Gzip;
setUp(() {
final f1 = File('./test/fixtures/test.tmx').readAsString().then((xml) {
mapTmx = TileMapParser.parseTmx(xml);
});
final f2 =
File('./test/fixtures/test_base64_gzip.tmx').readAsString().then((xml) {
mapTmxBase64Gzip = TileMapParser.parseTmx(xml);
});
return Future.wait([f1, f2]);
});
group('Layer.fromXML', () {
test('supports gzip', () {
final layer = mapTmx.layers.whereType<TileLayer>().first;
List<int> getDataRow(int idx) {
return layer.tileData![idx].map((e) => e.tile).toList();
}
expect(getDataRow(0), equals([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
expect(getDataRow(1), equals([0, 1, 0, 0, 0, 0, 0, 0, 0, 0]));
expect(getDataRow(2), equals([0, 0, 1, 0, 0, 0, 0, 0, 0, 0]));
expect(getDataRow(3), equals([0, 0, 0, 1, 0, 0, 0, 0, 0, 0]));
expect(getDataRow(4), equals([0, 0, 0, 0, 1, 0, 0, 0, 0, 0]));
expect(getDataRow(5), equals([0, 0, 0, 0, 0, 1, 0, 0, 0, 0]));
expect(getDataRow(6), equals([0, 0, 0, 0, 0, 0, 1, 0, 0, 0]));
expect(getDataRow(7), equals([0, 0, 0, 0, 0, 0, 0, 1, 0, 0]));
expect(getDataRow(8), equals([0, 0, 0, 0, 0, 0, 0, 0, 1, 0]));
expect(getDataRow(9), equals([0, 0, 0, 0, 0, 0, 0, 0, 0, 1]));
});
test('supports zlib', () {
final layer = mapTmxBase64Gzip.layers.whereType<TileLayer>().first;
List<int> getDataRow(int idx) {
return layer.tileData![idx].map((e) => e.tile).toList();
}
expect(getDataRow(0), equals([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
expect(getDataRow(1), equals([0, 1, 0, 0, 0, 0, 0, 0, 0, 0]));
expect(getDataRow(2), equals([0, 0, 1, 0, 0, 0, 0, 0, 0, 0]));
expect(getDataRow(3), equals([0, 0, 0, 1, 0, 0, 0, 0, 0, 0]));
expect(getDataRow(4), equals([0, 0, 0, 0, 1, 0, 0, 0, 0, 0]));
expect(getDataRow(5), equals([0, 0, 0, 0, 0, 1, 0, 0, 0, 0]));
expect(getDataRow(6), equals([0, 0, 0, 0, 0, 0, 1, 0, 0, 0]));
expect(getDataRow(7), equals([0, 0, 0, 0, 0, 0, 0, 1, 0, 0]));
expect(getDataRow(8), equals([0, 0, 0, 0, 0, 0, 0, 0, 1, 0]));
expect(getDataRow(9), equals([0, 0, 0, 0, 0, 0, 0, 0, 0, 1]));
});
});
group('Layer.tiles', () {
late TileLayer layer;
setUp(() {
layer = mapTmx.layers.whereType<TileLayer>().first;
});
test('is the expected size of 100', () {
expect(layer.tileData!.length, equals(10));
layer.tileData!.forEach((row) {
expect(row.length, equals(10));
});
});
test('parsed colors', () {
expect(layer.tintColorHex, equals('#ffaabb'));
expect(
layer.tintColor,
equals(Color(int.parse('0xffffaabb'))),
);
});
});
}
|
tiled.dart/packages/tiled/test/layer_test.dart/0
|
{'file_path': 'tiled.dart/packages/tiled/test/layer_test.dart', 'repo_id': 'tiled.dart', 'token_count': 1430}
|
import 'package:time/time.dart';
void main() async {
// Num Extensions
print(1.weeks);
print(1.5.weeks);
print(7.days);
print(7.5.days);
print(22.hours);
print(22.5.hours);
print(45.minutes);
print(45.5.minutes);
print(30.seconds);
print(30.5.seconds);
print(15.milliseconds);
print(15.5.milliseconds);
print(10.microseconds);
print(10.5.microseconds);
print(5.nanoseconds);
print(5.5.nanoseconds);
// Delay for 5 seconds
await 5.seconds.delay;
// DateTime Extensions
print(DateTime.now() + 7.days);
print(DateTime.now() - 7.days);
print(
DateTime(2019, 2, 4, 24, 50, 45, 1, 1).copyWith(
year: 2021,
month: 10,
day: 28,
hour: 12,
minute: 45,
second: 10,
millisecond: 0,
microsecond: 12,
),
);
// Duration Extensions
print(7.days.inWeeks);
print(7.days.fromNow);
print(7.days.ago);
DateTime.now().to(1.weeks.fromNow, by: 1.days).forEach(print);
}
|
time.dart/example/time_example.dart/0
|
{'file_path': 'time.dart/example/time_example.dart', 'repo_id': 'time.dart', 'token_count': 422}
|
on: push
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/setup-java@v1
with:
java-version: '12.x'
- uses: subosito/flutter-action@v1
with:
channel: 'stable'
- run: flutter pub get
- run: flutter build apk
# - run: flutter analyze
- run: flutter test
- run: flutter test --coverage
- uses: codecov/codecov-action@v1.0.2
with:
token: ${{secrets.CODECOV_TOKEN}}
file: ./coverage/lcov.info
|
travel_ui/.github/workflows/codecov.yml/0
|
{'file_path': 'travel_ui/.github/workflows/codecov.yml', 'repo_id': 'travel_ui', 'token_count': 257}
|
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:travel_ui/app/presentation/ui/widgets/favorite_places_title_widget.dart';
import 'package:travel_ui/app/presentation/ui/widgets/place_widget.dart';
import 'package:travel_ui/src/res/svgs.dart';
import 'package:travel_ui/src/utils/margins/x_margin.dart';
import 'package:travel_ui/src/utils/margins/y_margin.dart';
import 'package:travel_ui/src/values/colors.dart';
import '../../../../src/constants/constants.dart';
import '../../../models/place.dart';
class HomePage extends StatefulWidget {
const HomePage({
super.key,
});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final labels = ['Camping', 'Mountain', 'Hiking', 'Climbing', 'Skiing'];
ScrollController? _scrollController;
bool lastStatus = true;
double height = 200;
void _scrollListener() {
if (_isShrink != lastStatus) {
setState(() {
lastStatus = _isShrink;
});
}
}
bool get _isShrink {
return _scrollController != null &&
_scrollController!.hasClients &&
_scrollController!.offset > (height - kToolbarHeight);
}
@override
void initState() {
super.initState();
_scrollController = ScrollController()..addListener(_scrollListener);
}
@override
void dispose() {
_scrollController?.removeListener(_scrollListener);
_scrollController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 28.0,
),
child: NestedScrollView(
controller: _scrollController,
headerSliverBuilder: (context, innerBoxIsScrolled) {
return [
SliverAppBar(
elevation: 0,
pinned: true,
backgroundColor: Colors.white,
leading: const Offstage(),
expandedHeight: 387,
flexibleSpace: FlexibleSpaceBar(
collapseMode: CollapseMode.parallax,
title: _isShrink ? const FavoritePlacesTitleWidget() : null,
background: SafeArea(
child: AnimatedOpacity(
duration: const Duration(
milliseconds: 500,
),
opacity: _isShrink ? 0 : 1,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const YMargin(12),
Row(
children: [
Container(
height: 48,
width: 48,
decoration: BoxDecoration(
color: kGrayColor.withOpacity(0.2),
borderRadius: BorderRadius.circular(
8,
),
image: const DecorationImage(
image: CachedNetworkImageProvider(
myAvatarUrl,
),
fit: BoxFit.cover,
),
),
),
const XMargin(16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text(
'Howdy',
style: TextStyle(
color: kGrayColor,
fontSize: 12,
fontWeight: FontWeight.w400,
),
),
Text(
'Julius Czar',
style: TextStyle(
color: Color(0xFF1E1E1E),
fontSize: 18,
fontWeight: FontWeight.w600,
),
)
],
),
),
CircleAvatar(
backgroundColor: kPrimaryColor,
radius: 22,
child: SvgPicture.asset(
kHomeNotificationSvg,
height: 18,
),
)
],
),
const YMargin(28),
const Text(
'Where would you\nlike to go?',
style: TextStyle(
color: Colors.black,
fontSize: 32,
fontWeight: FontWeight.w600,
),
),
const YMargin(20),
Row(
children: [
Expanded(
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10),
),
boxShadow: [
BoxShadow(
color: kGrayColor.withOpacity(0.1),
spreadRadius: 5,
blurRadius: 7,
offset: const Offset(
0, 3), // changes position of shadow
),
],
),
child: TextFormField(
decoration: const InputDecoration(
contentPadding: EdgeInsets.symmetric(
horizontal: 12,
vertical: 13,
),
border: InputBorder.none,
hintText: 'Search Location',
),
),
),
),
const XMargin(20),
Container(
height: 48,
width: 48,
decoration: BoxDecoration(
color: kPrimaryColor,
borderRadius: BorderRadius.circular(
8,
),
),
child: Center(
child: SvgPicture.asset(
kHomeFilterSvg,
height: 14,
),
),
),
],
),
const YMargin(30),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: labels.map(
(label) {
final index = labels.indexOf(label);
return Container(
padding: const EdgeInsets.all(10),
margin: EdgeInsets.only(
left: index == 0 ? 0 : 10,
right: index == labels.length - 1 ? 0 : 10,
),
decoration: BoxDecoration(
color: index == 0
? kPrimaryColor
: Colors.transparent,
borderRadius: BorderRadius.circular(
8,
),
border: index == 0
? null
: Border.all(
color: kGrayColor,
),
),
child: Center(
child: Text(
label,
style: TextStyle(
color: index == 0
? Colors.white
: kGrayColor,
fontSize: 12,
fontWeight: FontWeight.w400,
),
),
),
);
},
).toList(),
),
),
const YMargin(36),
const FavoritePlacesTitleWidget(),
],
),
),
),
),
),
];
},
body: CustomScrollView(
scrollBehavior: const ScrollBehavior(),
slivers: [
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return PlaceWidget(
place: Place.places[index],
);
},
childCount: Place.places.length,
),
),
],
),
),
);
}
}
|
travel_ui/lib/app/presentation/ui/pages/home_page.dart/0
|
{'file_path': 'travel_ui/lib/app/presentation/ui/pages/home_page.dart', 'repo_id': 'travel_ui', 'token_count': 7517}
|
import 'dart:collection';
import 'dart:ui';
import 'package:flame/components.dart';
import 'package:trex/game/collision/collision_box.dart';
import 'package:trex/game/custom/util.dart';
import 'package:trex/game/horizon/config.dart';
import '../game.dart';
import 'config.dart';
import 'obstacle_type.dart';
class ObstacleManager extends PositionComponent with HasGameRef<TRexGame> {
ObstacleManager(this.dimensions);
ListQueue<ObstacleType> history = ListQueue();
final HorizonDimensions dimensions;
@override
void update(double dt) {
for (final c in children) {
final cloud = c as Obstacle;
cloud.y = y + cloud.type.y - 75;
}
final speed = gameRef.currentSpeed;
if (children.isNotEmpty) {
final lastObstacle = children.last as Obstacle?;
if (lastObstacle != null &&
!lastObstacle.followingObstacleCreated &&
lastObstacle.isVisible &&
(lastObstacle.x + lastObstacle.width + lastObstacle.gap) <
dimensions.width) {
addNewObstacle(speed);
lastObstacle.followingObstacleCreated = true;
}
} else {
addNewObstacle(speed);
}
super.update(dt);
}
void addNewObstacle(double speed) {
if (speed == 0) {
return;
}
final type = getRandomNum(0.0, 1.0).round() == 0
? ObstacleType.cactusSmall
: ObstacleType.cactusLarge;
if (duplicateObstacleCheck(type) || speed < type.multipleSpeed) {
return;
} else {
final obstacle = Obstacle(
type: type,
spriteImage: gameRef.spriteImage,
speed: speed,
gapCoefficient: gameRef.config.gapCoefficient,
dimensions: dimensions,
);
obstacle.x = gameRef.size.x;
add(obstacle);
history.addFirst(type);
if (history.length > 1) {
final sublist =
history.toList().sublist(0, gameRef.config.maxObstacleDuplication);
history = ListQueue.from(sublist);
}
}
}
bool duplicateObstacleCheck(ObstacleType nextType) {
int duplicateCount = 0;
for (final c in history) {
duplicateCount += c.type == nextType.type ? 1 : 0;
}
return duplicateCount >= gameRef.config.maxObstacleDuplication;
}
void reset() {
children.clear();
history.clear();
}
}
class Obstacle extends SpriteComponent with HasGameRef<TRexGame> {
Obstacle({
required this.type,
required Image spriteImage,
required double speed,
required double gapCoefficient,
required HorizonDimensions dimensions,
double xOffset = 0.0,
}) : super(
sprite: type.getSprite(spriteImage),
) {
x = dimensions.width + xOffset;
if (internalSize > 1 && type.multipleSpeed > speed) {
internalSize = 1;
}
width = type.width * internalSize;
height = type.height;
gap = computeGap(gapCoefficient, speed);
final actualSrc = sprite!.src;
sprite!.src = Rect.fromLTWH(
actualSrc.left,
actualSrc.top,
width,
actualSrc.height,
);
}
final ObstacleConfig config = ObstacleConfig();
bool followingObstacleCreated = false;
late double gap;
late int internalSize = getRandomNum(
1.0,
config.maxObstacleLength / 1,
).floor();
ObstacleType type;
late List<CollisionBox> collisionBoxes = [
for (final box in type.collisionBoxes) CollisionBox.from(box)
];
bool get isVisible => (x + width) > 0;
double computeGap(double gapCoefficient, double speed) {
final minGap = (width * speed * type.minGap * gapCoefficient).round() / 1;
final maxGap = (minGap * config.maxGapCoefficient).round() / 1;
return getRandomNum(minGap, maxGap);
}
@override
void update(double dt) {
if (shouldRemove) {
return;
}
final increment = gameRef.currentSpeed * 50 * dt;
x -= increment;
if (!isVisible) {
removeFromParent();
}
super.update(dt);
}
}
|
trex-flame/lib/game/obstacle/obstacle.dart/0
|
{'file_path': 'trex-flame/lib/game/obstacle/obstacle.dart', 'repo_id': 'trex-flame', 'token_count': 1575}
|
steps:
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
args: ['gsutil', 'cp', 'surveys/*.json', 'gs://flutter-uxr/surveys']
options:
logging: CLOUD_LOGGING_ONLY
|
uxr/cloudbuild/gcs.yaml/0
|
{'file_path': 'uxr/cloudbuild/gcs.yaml', 'repo_id': 'uxr', 'token_count': 76}
|
// 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';
void main() {
runApp(BooksApp());
}
class Book {
final String title;
final String author;
Book(this.title, this.author);
}
class AppState extends ChangeNotifier {
List<Book> books = [
Book('Stranger in a Strange Land', 'Robert A. Heinlein'),
Book('Foundation', 'Isaac Asimov'),
Book('Fahrenheit 451', 'Ray Bradbury'),
];
String? _filter;
String? get filter => _filter;
set filter(String? filter) {
_filter = filter;
notifyListeners();
}
}
class BooksApp extends StatefulWidget {
@override
State<StatefulWidget> createState() => _BooksAppState();
}
class _BooksAppState extends State<BooksApp> {
final BookRouterDelegate _routerDelegate = BookRouterDelegate();
final BookRouteInformationParser _routeInformationParser =
BookRouteInformationParser();
@override
void dispose() {
_routerDelegate.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Books App',
routerDelegate: _routerDelegate,
routeInformationParser: _routeInformationParser,
);
}
}
class BookRouteInformationParser extends RouteInformationParser<BookRoutePath> {
@override
Future<BookRoutePath> parseRouteInformation(
RouteInformation routeInformation) async {
final uri = Uri.parse(routeInformation.location!);
var filter = uri.queryParameters['filter'];
return BookRoutePath(filter);
}
@override
RouteInformation restoreRouteInformation(BookRoutePath path) {
var filter = path.filter;
var uri =
Uri(path: '/', queryParameters: <String, dynamic>{'filter': filter});
return RouteInformation(location: uri.toString());
}
}
class BookRouterDelegate extends RouterDelegate<BookRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<BookRoutePath> {
@override
final GlobalKey<NavigatorState> navigatorKey;
final AppState _appState;
BookRouterDelegate()
: navigatorKey = GlobalKey<NavigatorState>(),
_appState = AppState() {
_appState.addListener(() => notifyListeners());
}
@override
BookRoutePath get currentConfiguration {
return BookRoutePath(_appState.filter);
}
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
MaterialPage(
key: ValueKey('BooksListPage'),
child: BooksListScreen(
books: _appState.books,
filter: _appState.filter,
onFilterChanged: (filter) {
_appState.filter = filter;
},
),
),
],
onPopPage: (route, result) {
return route.didPop(result);
},
);
}
@override
Future<void> setNewRoutePath(BookRoutePath path) async {
_appState.filter = path.filter;
}
}
class BookRoutePath {
String? filter;
BookRoutePath(this.filter);
}
class BooksListScreen extends StatelessWidget {
final List<Book> books;
final String? filter;
final ValueChanged onFilterChanged;
BooksListScreen({
required this.books,
required this.onFilterChanged,
this.filter,
});
@override
Widget build(BuildContext context) {
final filter = this.filter;
return Scaffold(
appBar: AppBar(),
body: ListView(
children: [
TextField(
decoration: InputDecoration(
hintText: 'filter',
),
onSubmitted: onFilterChanged,
),
for (var book in books)
if (filter == null || book.title.toLowerCase().contains(filter))
ListTile(
title: Text(book.title),
subtitle: Text(book.author),
)
],
),
);
}
}
|
uxr/nav2-usability/scenario_code/lib/deeplink-queryparam/router.dart/0
|
{'file_path': 'uxr/nav2-usability/scenario_code/lib/deeplink-queryparam/router.dart', 'repo_id': 'uxr', 'token_count': 1498}
|
// 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';
void main() {
runApp(BooksApp());
}
// The state of the bottom navigation bar
enum AppPage {
newBooks, // /books/new
allBooks, // /books/all
settings, // /settings
}
class AppState extends ChangeNotifier {
AppPage _page = AppPage.newBooks;
AppPage get page => _page;
set page(AppPage s) {
_page = s;
notifyListeners();
}
}
class BooksApp extends StatefulWidget {
@override
_BooksAppState createState() => _BooksAppState();
}
class _BooksAppState extends State<BooksApp> {
final BookRouterDelegate _routerDelegate = BookRouterDelegate();
final BookRouteInformationParser _routeInformationParser =
BookRouteInformationParser();
@override
void dispose() {
_routerDelegate.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Books App',
routerDelegate: _routerDelegate,
routeInformationParser: _routeInformationParser,
);
}
}
class BookRouteInformationParser extends RouteInformationParser<AppRoutePath> {
@override
Future<AppRoutePath> parseRouteInformation(
RouteInformation routeInformation) async {
var uri = Uri.parse(routeInformation.location!);
if (uri.pathSegments.isEmpty) {
return NewBooksRoutePath();
}
if (uri.pathSegments.length == 1) {
if (uri.pathSegments[0] == 'books') return NewBooksRoutePath();
if (uri.pathSegments[0] == 'settings') return SettingsRoutePath();
}
if (uri.pathSegments.length == 2) {
if (uri.pathSegments[1] == 'new') return NewBooksRoutePath();
if (uri.pathSegments[1] == 'all') return AllBooksRoutePath();
}
return NewBooksRoutePath();
}
@override
RouteInformation restoreRouteInformation(AppRoutePath path) {
late final location;
if (path is NewBooksRoutePath) {
location = '/books/new';
} else if (path is AllBooksRoutePath) {
location = '/books/all';
} else if (path is SettingsRoutePath) {
location = '/settings';
}
return RouteInformation(location: location);
}
}
class BookRouterDelegate extends RouterDelegate<AppRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<AppRoutePath> {
@override
final GlobalKey<NavigatorState> navigatorKey;
final AppState _appState = AppState();
late final OverlayEntry _overlayEntry =
OverlayEntry(builder: _overlayEntryBuilder);
BookRouterDelegate() : navigatorKey = GlobalKey<NavigatorState>() {
_appState.addListener(handleAppStateChanged);
}
void handleAppStateChanged() {
notifyListeners();
_overlayEntry.markNeedsBuild();
}
@override
Future<void> setNewRoutePath(AppRoutePath path) async {
if (path is NewBooksRoutePath) {
_appState.page = AppPage.newBooks;
} else if (path is AllBooksRoutePath) {
_appState.page = AppPage.allBooks;
} else if (path is SettingsRoutePath) {
_appState.page = AppPage.settings;
}
}
@override
void dispose() {
_appState.dispose();
super.dispose();
}
@override
AppRoutePath get currentConfiguration {
if (_appState.page == AppPage.newBooks) {
return NewBooksRoutePath();
} else if (_appState.page == AppPage.allBooks) {
return AllBooksRoutePath();
} else if (_appState.page == AppPage.settings) {
return SettingsRoutePath();
}
return AppRoutePath();
}
@override
Widget build(BuildContext context) {
return Overlay(
initialEntries: [_overlayEntry],
);
}
Widget _overlayEntryBuilder(BuildContext context) {
return Scaffold(
body: Navigator(
key: navigatorKey,
pages: [
if (_appState.page == AppPage.settings)
FadeTransitionPage(
key: ValueKey('SettingsScreen'),
child: SettingsScreen(),
),
if (_appState.page == AppPage.newBooks ||
_appState.page == AppPage.allBooks)
FadeTransitionPage(
key: ValueKey('BooksScreen'),
child: BooksScreen(
onTabSelected: (int idx) {
if (idx == 0) {
_appState.page = AppPage.newBooks;
} else {
_appState.page = AppPage.allBooks;
}
},
appPage: _appState.page,
),
),
],
onPopPage: (route, result) {
return route.didPop(result);
},
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _appState.page == AppPage.settings ? 1 : 0,
onTap: (idx) {
if (idx == 0) {
_appState.page = AppPage.newBooks;
} else {
_appState.page = AppPage.settings;
}
},
items: [
BottomNavigationBarItem(
label: 'Books',
icon: Icon(Icons.chrome_reader_mode_outlined),
),
BottomNavigationBarItem(
label: 'Settings',
icon: Icon(Icons.settings),
),
],
),
);
}
}
class AppRoutePath {}
class NewBooksRoutePath extends AppRoutePath {}
class AllBooksRoutePath extends AppRoutePath {}
class SettingsRoutePath extends AppRoutePath {}
class BooksScreen extends StatefulWidget {
final AppPage appPage;
final ValueChanged<int> onTabSelected;
BooksScreen({
Key? key,
required this.appPage,
required this.onTabSelected,
}) : super(key: key);
@override
_BooksScreenState createState() => _BooksScreenState();
}
class _BooksScreenState extends State<BooksScreen>
with SingleTickerProviderStateMixin {
late final TabController _tabController;
@override
void initState() {
super.initState();
var initialIndex = widget.appPage == AppPage.newBooks ? 0 : 1;
_tabController =
TabController(length: 2, vsync: this, initialIndex: initialIndex);
}
@override
void didUpdateWidget(BooksScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.appPage == AppPage.newBooks) {
_tabController.index = 0;
} else {
_tabController.index = 1;
}
}
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
TabBar(
controller: _tabController,
onTap: widget.onTabSelected,
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 FadeTransitionPage extends Page {
final Widget child;
FadeTransitionPage({LocalKey? key, required this.child}) : super(key: key);
@override
Route createRoute(BuildContext context) {
return PageBasedFadeTransitionRoute(this);
}
}
class PageBasedFadeTransitionRoute extends PageRoute {
PageBasedFadeTransitionRoute(Page page)
: super(
settings: page,
);
@override
Color? get barrierColor => null;
@override
String? get barrierLabel => null;
@override
Duration get transitionDuration => const Duration(milliseconds: 300);
@override
bool get maintainState => true;
@override
Widget buildPage(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation) {
var curveTween = CurveTween(curve: Curves.easeIn);
return FadeTransition(
opacity: animation.drive(curveTween),
child: (settings as FadeTransitionPage).child,
);
}
@override
Widget buildTransitions(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation, Widget child) {
return child;
}
}
|
uxr/nav2-usability/scenario_code/lib/nested-routing/router.dart/0
|
{'file_path': 'uxr/nav2-usability/scenario_code/lib/nested-routing/router.dart', 'repo_id': 'uxr', 'token_count': 3472}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.