code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/ui.dart' as ui;
import '../common/test_initialization.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests();
test('Picture construction invokes onCreate once', () async {
int onCreateInvokedCount = 0;
ui.Picture? createdPicture;
ui.Picture.onCreate = (ui.Picture picture) {
onCreateInvokedCount++;
createdPicture = picture;
};
final ui.Picture picture1 = _createPicture();
expect(onCreateInvokedCount, 1);
expect(createdPicture, picture1);
final ui.Picture picture2 = _createPicture();
expect(onCreateInvokedCount, 2);
expect(createdPicture, picture2);
ui.Picture.onCreate = null;
});
test('approximateBytesUsed is available for onCreate', () async {
int pictureSize = -1;
ui.Picture.onCreate = (ui.Picture picture) =>
pictureSize = picture.approximateBytesUsed;
_createPicture();
expect(pictureSize >= 0, true);
ui.Picture.onCreate = null;
});
test('dispose() invokes onDispose once', () async {
int onDisposeInvokedCount = 0;
ui.Picture? disposedPicture;
ui.Picture.onDispose = (ui.Picture picture) {
onDisposeInvokedCount++;
disposedPicture = picture;
};
final ui.Picture picture1 = _createPicture()..dispose();
expect(onDisposeInvokedCount, 1);
expect(disposedPicture, picture1);
final ui.Picture picture2 = _createPicture()..dispose();
expect(onDisposeInvokedCount, 2);
expect(disposedPicture, picture2);
ui.Picture.onDispose = null;
});
}
ui.Picture _createPicture() {
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
const ui.Rect rect = ui.Rect.fromLTWH(0.0, 0.0, 100.0, 100.0);
canvas.clipRect(rect);
return recorder.endRecording();
}
| engine/lib/web_ui/test/ui/picture_test.dart/0 | {'file_path': 'engine/lib/web_ui/test/ui/picture_test.dart', 'repo_id': 'engine', 'token_count': 740} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This entry point is never invoked. Its purpose is to allow the vmservice's
// Dart code to built with dart_aot_app.
void main(List<String> args) {}
| engine/shell/platform/fuchsia/dart_runner/vmservice/empty.dart/0 | {'file_path': 'engine/shell/platform/fuchsia/dart_runner/vmservice/empty.dart', 'repo_id': 'engine', 'token_count': 87} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// FlutterTesterOptions=--enable-serial-gc
import 'package:litetest/litetest.dart';
int use(List<int> a) {
return a[0];
}
void main() {
test('Serial GC option test ', () async {
const bool threw = false;
for (int i = 0; i < 100; i++) {
final List<int> a = <int>[100];
use(a);
}
expect(threw, false);
});
}
| engine/testing/dart/serial_gc_test.dart/0 | {'file_path': 'engine/testing/dart/serial_gc_test.dart', 'repo_id': 'engine', 'token_count': 189} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:process/process.dart';
/// Pipes the [process] streams and writes them to [out] sink.
/// If [out] is null, then the current [Process.stdout] is used as the sink.
Future<int> pipeProcessStreams(
Process process, {
StringSink? out,
}) async {
out ??= stdout;
final Completer<void> stdoutCompleter = Completer<void>();
final StreamSubscription<String> stdoutSub = process.stdout
.transform(utf8.decoder)
.transform<String>(const LineSplitter())
.listen((String line) {
out!.writeln('[stdout] $line');
}, onDone: stdoutCompleter.complete);
final Completer<void> stderrCompleter = Completer<void>();
final StreamSubscription<String> stderrSub = process.stderr
.transform(utf8.decoder)
.transform<String>(const LineSplitter())
.listen((String line) {
out!.writeln('[stderr] $line');
}, onDone: stderrCompleter.complete);
final int exitCode = await process.exitCode;
await stderrSub.cancel();
await stdoutSub.cancel();
await stdoutCompleter.future;
await stderrCompleter.future;
return exitCode;
}
extension RunAndForward on ProcessManager {
/// Runs [cmd], and forwards the stdout and stderr pipes to the current process stdout pipe.
Future<int> runAndForward(List<String> cmd) async {
return pipeProcessStreams(await start(cmd), out: stdout);
}
}
| engine/testing/scenario_app/bin/utils/process_manager_extension.dart/0 | {'file_path': 'engine/testing/scenario_app/bin/utils/process_manager_extension.dart', 'repo_id': 'engine', 'token_count': 534} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'channel_util.dart';
import 'scenario.dart';
/// A blank page that just sends back to the platform what the set initial
/// route is.
class InitialRouteReply extends Scenario {
/// Creates the InitialRouteReply.
InitialRouteReply(super.view);
@override
void onBeginFrame(Duration duration) {
sendJsonMethodCall(
dispatcher: view.platformDispatcher,
channel: 'initial_route_test_channel',
method: view.platformDispatcher.defaultRouteName,
);
}
}
| engine/testing/scenario_app/lib/src/initial_route_reply.dart/0 | {'file_path': 'engine/testing/scenario_app/lib/src/initial_route_reply.dart', 'repo_id': 'engine', 'token_count': 199} |
//---------------------------------------------------------------------------------------------
// Copyright (c) 2022 Google LLC
// Licensed under the MIT License. See License.txt in the project root for license information.
//--------------------------------------------------------------------------------------------*/
import 'package:test/test.dart';
import 'package:web_locale_keymap/web_locale_keymap.dart';
import 'test_cases.g.dart';
void main() {
group('Win', () {
testWin(LocaleKeymap.win());
});
group('Linux', () {
testLinux(LocaleKeymap.linux());
});
group('Darwin', () {
testDarwin(LocaleKeymap.darwin());
});
}
| engine/third_party/web_locale_keymap/test/layout_mapping_test.dart/0 | {'file_path': 'engine/third_party/web_locale_keymap/test/layout_mapping_test.dart', 'repo_id': 'engine', 'token_count': 178} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:apicheck/apicheck.dart';
import 'package:litetest/litetest.dart';
import 'package:path/path.dart' as path;
void main(List<String> arguments) {
if (arguments.isEmpty) {
print('usage: dart bin/apicheck.dart path/to/engine/src/flutter');
exit(1);
}
final String flutterRoot = arguments[0];
checkApiConsistency(flutterRoot);
checkNativeApi(flutterRoot);
}
/// Verify that duplicate Flutter API is consistent between implementations.
///
/// Flutter contains API that is required to match between implementations.
/// Notably, some enums such as those used by Flutter accessibility, appear in:
/// * dart:ui (native)
/// * dart:ui (web)
/// * embedder.h
/// * Internal enumerations used by iOS/Android
///
/// WARNING: The embedder API makes strong API/ABI stability guarantees. Care
/// must be taken when adding new enums, or values to existing enums. These
/// CANNOT be removed without breaking backward compatibility, which we have
/// never done. See the note at the top of `shell/platform/embedder/embedder.h`
/// for further details.
void checkApiConsistency(String flutterRoot) {
test('AccessibilityFeatures enums match', () {
// Dart values: _kFooBarIndex = 1 << N
final List<String> uiFields = getDartClassFields(
sourcePath: path.join(flutterRoot, 'lib', 'ui', 'window.dart'),
className: 'AccessibilityFeatures',
);
// C values: kFlutterAccessibilityFeatureFooBar = 1 << N,
final List<String> embedderEnumValues = getCppEnumValues(
sourcePath: path.join(flutterRoot, 'shell', 'platform', 'embedder', 'embedder.h'),
enumName: 'FlutterAccessibilityFeature',
);
// C++ values: kFooBar = 1 << N,
final List<String> internalEnumValues = getCppEnumClassValues(
sourcePath: path.join(flutterRoot, 'lib','ui', 'window', 'platform_configuration.h'),
enumName: 'AccessibilityFeatureFlag',
);
// Java values: FOO_BAR(1 << N).
final List<String> javaEnumValues = getJavaEnumValues(
sourcePath: path.join(flutterRoot, 'shell', 'platform', 'android', 'io',
'flutter', 'view', 'AccessibilityBridge.java'),
enumName: 'AccessibilityFeature',
).map(allCapsToCamelCase).toList();
expect(embedderEnumValues, uiFields);
expect(internalEnumValues, uiFields);
expect(javaEnumValues, uiFields);
});
test('SemanticsAction enums match', () {
// Dart values: _kFooBarIndex = 1 << N.
final List<String> uiFields = getDartClassFields(
sourcePath: path.join(flutterRoot, 'lib', 'ui', 'semantics.dart'),
className: 'SemanticsAction',
);
final List<String> webuiFields = getDartClassFields(
sourcePath: path.join(flutterRoot, 'lib', 'web_ui', 'lib', 'semantics.dart'),
className: 'SemanticsAction',
);
// C values: kFlutterSemanticsActionFooBar = 1 << N.
final List<String> embedderEnumValues = getCppEnumValues(
sourcePath: path.join(flutterRoot, 'shell', 'platform', 'embedder', 'embedder.h'),
enumName: 'FlutterSemanticsAction',
);
// C++ values: kFooBar = 1 << N.
final List<String> internalEnumValues = getCppEnumClassValues(
sourcePath: path.join(flutterRoot, 'lib', 'ui', 'semantics', 'semantics_node.h'),
enumName: 'SemanticsAction',
);
// Java values: FOO_BAR(1 << N).
final List<String> javaEnumValues = getJavaEnumValues(
sourcePath: path.join(flutterRoot, 'shell', 'platform', 'android', 'io',
'flutter', 'view', 'AccessibilityBridge.java'),
enumName: 'Action',
).map(allCapsToCamelCase).toList();
expect(webuiFields, uiFields);
expect(embedderEnumValues, uiFields);
expect(internalEnumValues, uiFields);
expect(javaEnumValues, uiFields);
});
test('AppLifecycleState enums match', () {
// Dart values: _kFooBarIndex = 1 << N.
final List<String> uiFields = getDartClassFields(
sourcePath: path.join(flutterRoot, 'lib', 'ui', 'platform_dispatcher.dart'),
className: 'AppLifecycleState',
);
final List<String> webuiFields = getDartClassFields(
sourcePath: path.join(flutterRoot, 'lib', 'web_ui', 'lib', 'platform_dispatcher.dart'),
className: 'AppLifecycleState',
);
// C++ values: kFooBar = 1 << N.
final List<String> internalEnumValues = getCppEnumClassValues(
sourcePath: path.join(flutterRoot, 'shell', 'platform', 'common', 'app_lifecycle_state.h'),
enumName: 'AppLifecycleState',
);
// Java values: FOO_BAR(1 << N).
final List<String> javaEnumValues = getJavaEnumValues(
sourcePath: path.join(flutterRoot, 'shell', 'platform', 'android', 'io',
'flutter', 'embedding', 'engine', 'systemchannels', 'LifecycleChannel.java'),
enumName: 'AppLifecycleState',
).map(allCapsToCamelCase).toList();
expect(webuiFields, uiFields);
expect(internalEnumValues, uiFields);
expect(javaEnumValues, uiFields);
});
test('SemanticsFlag enums match', () {
// Dart values: _kFooBarIndex = 1 << N.
final List<String> uiFields = getDartClassFields(
sourcePath: path.join(flutterRoot, 'lib', 'ui', 'semantics.dart'),
className: 'SemanticsFlag',
);
final List<String> webuiFields = getDartClassFields(
sourcePath: path.join(flutterRoot, 'lib', 'ui', 'semantics.dart'),
className: 'SemanticsFlag',
);
// C values: kFlutterSemanticsFlagFooBar = 1 << N.
final List<String> embedderEnumValues = getCppEnumValues(
sourcePath: path.join(flutterRoot, 'shell', 'platform', 'embedder', 'embedder.h'),
enumName: 'FlutterSemanticsFlag',
);
// C++ values: kFooBar = 1 << N.
final List<String> internalEnumValues = getCppEnumClassValues(
sourcePath: path.join(flutterRoot, 'lib', 'ui', 'semantics', 'semantics_node.h'),
enumName: 'SemanticsFlags',
);
// Java values: FOO_BAR(1 << N).
final List<String> javaEnumValues = getJavaEnumValues(
sourcePath: path.join(flutterRoot, 'shell', 'platform', 'android', 'io',
'flutter', 'view', 'AccessibilityBridge.java'),
enumName: 'Flag',
).map(allCapsToCamelCase).toList();
expect(webuiFields, uiFields);
expect(embedderEnumValues, uiFields);
expect(internalEnumValues, uiFields);
expect(javaEnumValues, uiFields);
});
}
/// Returns the CamelCase equivalent of an ALL_CAPS identifier.
String allCapsToCamelCase(String identifier) {
final StringBuffer buffer = StringBuffer();
for (final String word in identifier.split('_')) {
if (word.isNotEmpty) {
buffer.write(word[0]);
}
if (word.length > 1) {
buffer.write(word.substring(1).toLowerCase());
}
}
return buffer.toString();
}
/// Verify that the native functions in the dart:ui package do not use nullable
/// parameters that map to simple types such as numbers and strings.
///
/// The Tonic argument converters used by the native function implementations
/// expect that values of these types will not be null.
class NativeFunctionVisitor extends RecursiveAstVisitor<void> {
final Set<String> simpleTypes = <String>{'int', 'double', 'bool', 'String'};
List<String> errors = <String>[];
@override
void visitNativeFunctionBody(NativeFunctionBody node) {
final MethodDeclaration? method = node.thisOrAncestorOfType<MethodDeclaration>();
if (method != null) {
if (method.parameters != null) {
check(method.toString(), method.parameters!);
}
return;
}
final FunctionDeclaration? func = node.thisOrAncestorOfType<FunctionDeclaration>();
if (func != null) {
final FunctionExpression funcExpr = func.functionExpression;
if (funcExpr.parameters != null) {
check(func.toString(), funcExpr.parameters!);
}
return;
}
throw Exception('unreachable');
}
void check(String description, FormalParameterList parameters) {
for (final FormalParameter parameter in parameters.parameters) {
TypeAnnotation? type;
if (parameter is SimpleFormalParameter) {
type = parameter.type;
} else if (parameter is DefaultFormalParameter) {
type = (parameter.parameter as SimpleFormalParameter).type;
}
if (type! is NamedType) {
final String name = (type as NamedType).name2.lexeme;
if (type.question != null && simpleTypes.contains(name)) {
errors.add(description);
return;
}
}
}
}
}
void checkNativeApi(String flutterRoot) {
test('Native API does not pass nullable parameters of simple types', () {
final NativeFunctionVisitor visitor = NativeFunctionVisitor();
visitUIUnits(flutterRoot, visitor);
expect(visitor.errors, isEmpty);
});
}
| engine/tools/api_check/test/apicheck_test.dart/0 | {'file_path': 'engine/tools/api_check/test/apicheck_test.dart', 'repo_id': 'engine', 'token_count': 3298} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert' show LineSplitter, jsonDecode;
import 'dart:io' as io show File, stderr, stdout;
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:git_repo_tools/git_repo_tools.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
import 'package:process/process.dart';
import 'package:process_runner/process_runner.dart';
import 'src/command.dart';
import 'src/lint_target.dart';
import 'src/options.dart';
const String _linterOutputHeader = '''
ββββββββββββββββββββββββββββ
β Engine Clang Tidy Linter β
ββββββββββββββββββββββββββββ
The following errors have been reported by the Engine Clang Tidy Linter. For
more information on addressing these issues please see:
https://github.com/flutter/flutter/wiki/Engine-Clang-Tidy-Linter
''';
class _ComputeJobsResult {
_ComputeJobsResult(this.jobs, this.sawMalformed);
final List<WorkerJob> jobs;
final bool sawMalformed;
}
enum _SetStatus {
Intersection,
Difference,
}
class _SetStatusCommand {
_SetStatusCommand(this.setStatus, this.command);
final _SetStatus setStatus;
final Command command;
}
/// A class that runs clang-tidy on all or only the changed files in a git
/// repo.
class ClangTidy {
/// Builds an instance of [ClangTidy] using a repo's [buildCommandPath].
///
/// ## Required
///
/// - [buildCommandsPath] is the path to the build_commands.json file.
///
/// ## Optional
///
/// - [checksArg] are specific checks for clang-tidy to do.
///
/// If omitted, checks will be determined by the `.clang-tidy` file in the
/// repo.
///
/// - [lintTarget] is what files to lint.
///
/// ## Optional (Test Overrides)
///
/// _Most usages of this class will not need to override the following, which
/// are primarily used for testing (i.e. to avoid real interaction with I/O)._
///
/// - [outSink] when provided is the destination for normal log messages.
///
/// If omitted, [io.stdout] will be used.
///
/// - [errSink] when provided is the destination for error messages.
///
/// If omitted, [io.stderr] will be used.
///
/// - [processManager] when provided is delegated to for running processes.
///
/// If omitted, [LocalProcessManager] will be used.
ClangTidy({
required io.File buildCommandsPath,
String checksArg = '',
LintTarget lintTarget = const LintChanged(),
bool fix = false,
StringSink? outSink,
StringSink? errSink,
ProcessManager processManager = const LocalProcessManager(),
}) :
options = Options(
buildCommandsPath: buildCommandsPath,
checksArg: checksArg,
lintTarget: lintTarget,
fix: fix,
errSink: errSink,
),
_outSink = outSink ?? io.stdout,
_errSink = errSink ?? io.stderr,
_processManager = processManager,
_engine = null;
/// Builds an instance of [ClangTidy] from a command line.
ClangTidy.fromCommandLine(
List<String> args, {
Engine? engine,
StringSink? outSink,
StringSink? errSink,
ProcessManager processManager = const LocalProcessManager(),
}) :
options = Options.fromCommandLine(args, errSink: errSink, engine: engine),
_outSink = outSink ?? io.stdout,
_errSink = errSink ?? io.stderr,
_processManager = processManager,
_engine = engine;
/// The [Options] that specify how this [ClangTidy] operates.
final Options options;
final StringSink _outSink;
final StringSink _errSink;
final ProcessManager _processManager;
final Engine? _engine;
late final DateTime _startTime;
/// Runs clang-tidy on the repo as specified by the [Options].
Future<int> run() async {
_startTime = DateTime.now();
if (options.help) {
options.printUsage(engine: _engine);
return 0;
}
if (options.errorMessage != null) {
options.printUsage(message: options.errorMessage, engine: _engine);
return 1;
}
_outSink.writeln(_linterOutputHeader);
final List<io.File> filesOfInterest = await computeFilesOfInterest();
if (options.verbose) {
_outSink.writeln('Checking lint in repo at ${options.repoPath.path}.');
if (options.checksArg.isNotEmpty) {
_outSink.writeln('Checking for specific checks: ${options.checks}.');
}
final int changedFilesCount = filesOfInterest.length;
switch (options.lintTarget) {
case LintAll():
_outSink.writeln('Checking all $changedFilesCount files in the repo.');
case LintChanged():
_outSink.writeln(
'Checking $changedFilesCount files that have changed since the '
'last commit.',
);
case LintHead():
_outSink.writeln(
'Checking $changedFilesCount files that have changed compared to '
'HEAD.',
);
case LintRegex(:final String regex):
_outSink.writeln(
'Checking $changedFilesCount files that match the regex "$regex".',
);
}
}
final List<Object?> buildCommandsData = jsonDecode(
options.buildCommandsPath.readAsStringSync(),
) as List<Object?>;
final List<List<Object?>> shardBuildCommandsData = options
.shardCommandsPaths
.map((io.File file) =>
jsonDecode(file.readAsStringSync()) as List<Object?>)
.toList();
final List<Command> changedFileBuildCommands = await getLintCommandsForFiles(
buildCommandsData,
filesOfInterest,
shardBuildCommandsData,
options.shardId,
);
if (changedFileBuildCommands.isEmpty) {
_outSink.writeln(
'No changed files that have build commands associated with them were '
'found.',
);
return 0;
}
if (options.verbose) {
_outSink.writeln(
'Found ${changedFileBuildCommands.length} files that have build '
'commands associated with them and can be lint checked.',
);
}
final _ComputeJobsResult computeJobsResult = await _computeJobs(
changedFileBuildCommands,
options,
);
final int computeResult = computeJobsResult.sawMalformed ? 1 : 0;
final List<WorkerJob> jobs = computeJobsResult.jobs;
final int runResult = await _runJobs(jobs);
_outSink.writeln('\n');
if (computeResult + runResult == 0) {
_outSink.writeln('No lint problems found.');
} else {
_errSink.writeln('Lint problems found.');
}
return computeResult + runResult > 0 ? 1 : 0;
}
/// The files with local modifications or all/a subset of all files.
///
/// See [LintTarget] for more information.
@visibleForTesting
Future<List<io.File>> computeFilesOfInterest() async {
switch (options.lintTarget) {
case LintAll():
return options.repoPath
.listSync(recursive: true)
.whereType<io.File>()
.toList();
case LintRegex(:final String regex):
final RegExp pattern = RegExp(regex);
return options.repoPath
.listSync(recursive: true)
.whereType<io.File>()
.where((io.File file) => pattern.hasMatch(file.path))
.toList();
case LintChanged():
final GitRepo repo = GitRepo.fromRoot(
options.repoPath,
processManager: _processManager,
verbose: options.verbose,
);
return repo.changedFiles;
case LintHead():
final GitRepo repo = GitRepo.fromRoot(
options.repoPath,
processManager: _processManager,
verbose: options.verbose,
);
return repo.changedFilesAtHead;
}
}
/// Returns f(n) = value(n * [shardCount] + [id]).
Iterable<T> _takeShard<T>(Iterable<T> values, int id, int shardCount) sync* {
int count = 0;
for (final T val in values) {
if (count % shardCount == id) {
yield val;
}
count++;
}
}
/// This returns a `_SetStatusCommand` for each [Command] in [items].
/// `Intersection` if the Command shows up in [items] and its filePath in all
/// [filePathSets], otherwise `Difference`.
Iterable<_SetStatusCommand> _calcIntersection(
Iterable<Command> items, Iterable<Set<String>> filePathSets) sync* {
bool allSetsContain(Command command) {
for (final Set<String> filePathSet in filePathSets) {
if (!filePathSet.contains(command.filePath)) {
return false;
}
}
return true;
}
for (final Command command in items) {
if (allSetsContain(command)) {
yield _SetStatusCommand(_SetStatus.Intersection, command);
} else {
yield _SetStatusCommand(_SetStatus.Difference, command);
}
}
}
/// Given a build commands json file's contents in [buildCommandsData], and
/// the [files] with local changes, compute the lint commands to run. If
/// build commands are supplied in [sharedBuildCommandsData] the intersection
/// of those build commands will be calculated and distributed across
/// instances via the [shardId].
@visibleForTesting
Future<List<Command>> getLintCommandsForFiles(
List<Object?> buildCommandsData,
List<io.File> files,
List<List<Object?>> sharedBuildCommandsData,
int? shardId,
) {
final List<Command> totalCommands = <Command>[];
if (sharedBuildCommandsData.isNotEmpty) {
final List<Command> buildCommands = <Command>[
for (final Object? data in buildCommandsData)
Command.fromMap((data as Map<String, Object?>?)!)
];
final List<Set<String>> shardFilePaths = <Set<String>>[
for (final List<Object?> list in sharedBuildCommandsData)
<String>{
for (final Object? data in list)
Command.fromMap((data as Map<String, Object?>?)!).filePath
}
];
final Iterable<_SetStatusCommand> intersectionResults =
_calcIntersection(buildCommands, shardFilePaths);
for (final _SetStatusCommand result in intersectionResults) {
if (result.setStatus == _SetStatus.Difference) {
totalCommands.add(result.command);
}
}
final List<Command> intersection = <Command>[
for (final _SetStatusCommand result in intersectionResults)
if (result.setStatus == _SetStatus.Intersection) result.command
];
// Make sure to sort results so the sharding scheme is guaranteed to work
// since we are not sure if there is a defined order in the json file.
intersection
.sort((Command x, Command y) => x.filePath.compareTo(y.filePath));
totalCommands.addAll(
_takeShard(intersection, shardId!, 1 + sharedBuildCommandsData.length));
} else {
totalCommands.addAll(<Command>[
for (final Object? data in buildCommandsData)
Command.fromMap((data as Map<String, Object?>?)!)
]);
}
return () async {
final List<Command> result = <Command>[];
for (final Command command in totalCommands) {
final LintAction lintAction = await command.lintAction;
// Short-circuit the expensive containsAny call for the many third_party files.
if (lintAction != LintAction.skipThirdParty &&
command.containsAny(files)) {
result.add(command);
}
}
return result;
}();
}
Future<_ComputeJobsResult> _computeJobs(
List<Command> commands,
Options options,
) async {
bool sawMalformed = false;
final List<WorkerJob> jobs = <WorkerJob>[];
for (final Command command in commands) {
final String relativePath = path.relative(
command.filePath,
from: options.repoPath.parent.path,
);
final LintAction action = await command.lintAction;
switch (action) {
case LintAction.skipNoLint:
_outSink.writeln('π· ignoring $relativePath (FLUTTER_NOLINT)');
case LintAction.failMalformedNoLint:
_errSink.writeln('β malformed opt-out $relativePath');
_errSink.writeln(
' Required format: // FLUTTER_NOLINT: $issueUrlPrefix/ISSUE_ID',
);
sawMalformed = true;
case LintAction.lint:
_outSink.writeln('πΆ linting $relativePath');
jobs.add(command.createLintJob(options));
case LintAction.skipThirdParty:
_outSink.writeln('π· ignoring $relativePath (third_party)');
case LintAction.skipMissing:
_outSink.writeln('π· ignoring $relativePath (missing)');
}
}
return _ComputeJobsResult(jobs, sawMalformed);
}
static Iterable<String> _trimGenerator(String output) sync* {
const LineSplitter splitter = LineSplitter();
final List<String> lines = splitter.convert(output);
bool isPrintingError = false;
for (final String line in lines) {
if (line.contains(': error:') || line.contains(': warning:')) {
isPrintingError = true;
yield line;
} else if (line == ':') {
isPrintingError = false;
} else if (isPrintingError) {
yield line;
}
}
}
/// Visible for testing.
/// Function for trimming raw clang-tidy output.
@visibleForTesting
static String trimOutput(String output) => _trimGenerator(output).join('\n');
Future<int> _runJobs(List<WorkerJob> jobs) async {
int result = 0;
final Set<String> pendingJobs = <String>{for (final WorkerJob job in jobs) job.name};
void reporter(int totalJobs, int completed, int inProgress, int pending, int failed) {
return _logWithTimestamp(ProcessPool.defaultReportToString(
totalJobs, completed, inProgress, pending, failed));
}
final ProcessPool pool = ProcessPool(
printReport: reporter,
processRunner: ProcessRunner(processManager: _processManager),
);
await for (final WorkerJob job in pool.startWorkers(jobs)) {
pendingJobs.remove(job.name);
if (pendingJobs.isNotEmpty && pendingJobs.length <= 3) {
final List<String> sortedJobs = pendingJobs.toList()..sort();
_logWithTimestamp('Still running: $sortedJobs');
}
if (job.result.exitCode == 0) {
if (options.enableCheckProfile) {
// stderr is lazily evaluated, so force it to be evaluated here.
final String stderr = job.result.stderr;
_errSink.writeln('Results of --enable-check-profile for ${job.name}:');
_errSink.writeln(stderr);
}
continue;
}
_errSink.writeln('β Failures for ${job.name}:');
if (!job.printOutput) {
final Exception? exception = job.exception;
if (exception != null) {
_errSink.writeln(trimOutput(exception.toString()));
} else {
_errSink.writeln(trimOutput(job.result.stdout));
}
}
result = 1;
}
return result;
}
void _logWithTimestamp(String message) {
final Duration elapsedTime = DateTime.now().difference(_startTime);
final String seconds = (elapsedTime.inSeconds % 60).toString().padLeft(2, '0');
_outSink.writeln('[${elapsedTime.inMinutes}:$seconds] $message');
}
}
| engine/tools/clang_tidy/lib/clang_tidy.dart/0 | {'file_path': 'engine/tools/clang_tidy/lib/clang_tidy.dart', 'repo_id': 'engine', 'token_count': 5930} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io;
import 'package:args/command_runner.dart';
import 'package:clang_tidy/clang_tidy.dart';
import 'package:path/path.dart' as path;
/// The command that implements the pre-push githook
class PrePushCommand extends Command<bool> {
@override
final String name = 'pre-push';
@override
final String description = 'Checks to run before a "git push"';
@override
Future<bool> run() async {
final Stopwatch sw = Stopwatch()..start();
final bool verbose = globalResults!['verbose']! as bool;
final bool enableClangTidy = globalResults!['enable-clang-tidy']! as bool;
final String flutterRoot = globalResults!['flutter']! as String;
if (!enableClangTidy) {
print('The clang-tidy check is disabled. To enable set the environment '
'variable PRE_PUSH_CLANG_TIDY to any value.');
}
final List<bool> checkResults = <bool>[
await _runFormatter(flutterRoot, verbose),
if (enableClangTidy)
await _runClangTidy(flutterRoot, verbose),
];
sw.stop();
io.stdout.writeln('pre-push checks finished in ${sw.elapsed}');
return !checkResults.contains(false);
}
Future<bool> _runClangTidy(String flutterRoot, bool verbose) async {
io.stdout.writeln('Starting clang-tidy checks.');
final Stopwatch sw = Stopwatch()..start();
// First ensure that out/host_debug/compile_commands.json exists by running
// //flutter/tools/gn.
io.File compileCommands = io.File(path.join(
flutterRoot,
'..',
'out',
'host_debug',
'compile_commands.json',
));
if (!compileCommands.existsSync()) {
compileCommands = io.File(path.join(
flutterRoot,
'..',
'out',
'host_debug_unopt',
'compile_commands.json',
));
if (!compileCommands.existsSync()) {
io.stderr.writeln('clang-tidy requires a fully built host_debug or '
'host_debug_unopt build directory');
return false;
}
}
final StringBuffer outBuffer = StringBuffer();
final StringBuffer errBuffer = StringBuffer();
final ClangTidy clangTidy = ClangTidy(
buildCommandsPath: compileCommands,
outSink: outBuffer,
errSink: errBuffer,
);
final int clangTidyResult = await clangTidy.run();
sw.stop();
io.stdout.writeln('clang-tidy checks finished in ${sw.elapsed}');
if (clangTidyResult != 0) {
io.stderr.write(errBuffer);
return false;
}
return true;
}
Future<bool> _runFormatter(String flutterRoot, bool verbose) async {
io.stdout.writeln('Starting formatting checks.');
final Stopwatch sw = Stopwatch()..start();
final String ext = io.Platform.isWindows ? '.bat' : '.sh';
final bool result = await _runCheck(
flutterRoot,
path.join(flutterRoot, 'ci', 'format$ext'),
<String>[],
'Formatting check',
verbose: verbose,
);
sw.stop();
io.stdout.writeln('formatting checks finished in ${sw.elapsed}');
return result;
}
Future<bool> _runCheck(
String flutterRoot,
String scriptPath,
List<String> scriptArgs,
String checkName, {
bool verbose = false,
}) async {
if (verbose) {
io.stdout.writeln('Starting "$checkName": $scriptPath');
}
final io.ProcessResult result = await io.Process.run(
scriptPath,
scriptArgs,
workingDirectory: flutterRoot,
);
if (result.exitCode != 0) {
final StringBuffer message = StringBuffer();
message.writeln('Check "$checkName" failed.');
message.writeln('command: $scriptPath ${scriptArgs.join(" ")}');
message.writeln('working directory: $flutterRoot');
message.writeln('exit code: ${result.exitCode}');
message.writeln('stdout:');
message.writeln(result.stdout);
message.writeln('stderr:');
message.writeln(result.stderr);
io.stderr.write(message.toString());
return false;
}
if (verbose) {
io.stdout.writeln('Check "$checkName" finished successfully.');
}
return true;
}
}
| engine/tools/githooks/lib/src/pre_push_command.dart/0 | {'file_path': 'engine/tools/githooks/lib/src/pre_push_command.dart', 'repo_id': 'engine', 'token_count': 1671} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io;
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:header_guard_check/header_guard_check.dart';
import 'package:litetest/litetest.dart';
import 'package:path/path.dart' as p;
Future<int> main(List<String> args) async {
void withTestRepository(String path, void Function(io.Directory) fn) {
// Create a temporary directory and delete it when we're done.
final io.Directory tempDir = io.Directory.systemTemp.createTempSync('header_guard_check_test');
final io.Directory repoDir = io.Directory(p.join(tempDir.path, path));
repoDir.createSync(recursive: true);
try {
fn(repoDir);
} finally {
tempDir.deleteSync(recursive: true);
}
}
group('HeaderGuardCheck', () {
test('by default checks all files', () {
withTestRepository('engine/src', (io.Directory repoDir) {
final io.Directory flutterDir = io.Directory(p.join(repoDir.path, 'flutter'));
flutterDir.createSync(recursive: true);
final io.File file1 = io.File(p.join(flutterDir.path, 'foo.h'));
file1.createSync(recursive: true);
final io.File file2 = io.File(p.join(flutterDir.path, 'bar.h'));
file2.createSync(recursive: true);
final io.File file3 = io.File(p.join(flutterDir.path, 'baz.h'));
file3.createSync(recursive: true);
final StringBuffer stdOut = StringBuffer();
final StringBuffer stdErr = StringBuffer();
final HeaderGuardCheck check = HeaderGuardCheck(
source: Engine.fromSrcPath(repoDir.path),
exclude: const <String>[],
stdOut: stdOut,
stdErr: stdErr,
);
expect(check.run(), completion(1));
expect(stdOut.toString(), contains('foo.h'));
expect(stdOut.toString(), contains('bar.h'));
expect(stdOut.toString(), contains('baz.h'));
});
});
test('if --include is provided, checks specific files', () {
withTestRepository('engine/src', (io.Directory repoDir) {
final io.Directory flutterDir = io.Directory(p.join(repoDir.path, 'flutter'));
flutterDir.createSync(recursive: true);
final io.File file1 = io.File(p.join(flutterDir.path, 'foo.h'));
file1.createSync(recursive: true);
final io.File file2 = io.File(p.join(flutterDir.path, 'bar.h'));
file2.createSync(recursive: true);
final io.File file3 = io.File(p.join(flutterDir.path, 'baz.h'));
file3.createSync(recursive: true);
final StringBuffer stdOut = StringBuffer();
final StringBuffer stdErr = StringBuffer();
final HeaderGuardCheck check = HeaderGuardCheck(
source: Engine.fromSrcPath(repoDir.path),
include: <String>[file1.path, file3.path],
exclude: const <String>[],
stdOut: stdOut,
stdErr: stdErr,
);
expect(check.run(), completion(1));
expect(stdOut.toString(), contains('foo.h'));
expect(stdOut.toString(), contains('baz.h'));
// TODO(matanlurey): https://github.com/flutter/flutter/issues/133569).
if (stdOut.toString().contains('bar.h')) {
// There is no not(contains(...)) matcher.
fail('bar.h should not be checked. Output: $stdOut');
}
});
});
test('if --include is provided, checks specific directories', () {
withTestRepository('engine/src', (io.Directory repoDir) {
final io.Directory flutterDir = io.Directory(p.join(repoDir.path, 'flutter'));
flutterDir.createSync(recursive: true);
// Create a sub-directory called "impeller".
final io.Directory impellerDir = io.Directory(p.join(flutterDir.path, 'impeller'));
impellerDir.createSync(recursive: true);
// Create one file in both the root and in impeller.
final io.File file1 = io.File(p.join(flutterDir.path, 'foo.h'));
file1.createSync(recursive: true);
final io.File file2 = io.File(p.join(impellerDir.path, 'bar.h'));
file2.createSync(recursive: true);
final StringBuffer stdOut = StringBuffer();
final StringBuffer stdErr = StringBuffer();
final HeaderGuardCheck check = HeaderGuardCheck(
source: Engine.fromSrcPath(repoDir.path),
include: <String>[impellerDir.path],
exclude: const <String>[],
stdOut: stdOut,
stdErr: stdErr,
);
expect(check.run(), completion(1));
expect(stdOut.toString(), contains('bar.h'));
// TODO(matanlurey): https://github.com/flutter/flutter/issues/133569).
if (stdOut.toString().contains('foo.h')) {
// There is no not(contains(...)) matcher.
fail('foo.h should not be checked. Output: $stdOut');
}
});
});
});
return 0;
}
| engine/tools/header_guard_check/test/header_guard_check_test.dart/0 | {'file_path': 'engine/tools/header_guard_check/test/header_guard_check_test.dart', 'repo_id': 'engine', 'token_count': 2069} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert' as convert;
import 'package:engine_build_configs/src/build_config.dart';
import 'package:litetest/litetest.dart';
const String buildConfigJson = '''
{
"builds": [
{
"archives": [
{
"name": "build_name",
"base_path": "base/path",
"type": "gcs",
"include_paths": ["include/path"],
"realm": "archive_realm"
}
],
"drone_dimensions": ["dimension"],
"gclient_variables": {
"variable": false
},
"gn": ["--gn-arg"],
"name": "build_name",
"ninja": {
"config": "build_name",
"targets": ["ninja_target"]
},
"tests": [
{
"language": "python3",
"name": "build_name tests",
"parameters": ["--test-params"],
"script": "test/script.py",
"contexts": ["context"]
}
],
"generators": {
"tasks": [
{
"name": "generator_task",
"parameters": ["--gen-param"],
"scripts": ["gen/script.py"]
}
]
}
}
],
"generators": {
"tasks": [
{
"name": "global generator task",
"parameters": ["--global-gen-param"],
"script": "global/gen_script.dart",
"language": "dart"
}
]
},
"tests": [
{
"name": "global test",
"recipe": "engine_v2/tester_engine",
"drone_dimensions": ["dimension"],
"gclient_variables": {
"variable": false
},
"dependencies": ["dependency"],
"test_dependencies": [
{
"dependency": "test_dependency",
"version": "git_revision:3a77d0b12c697a840ca0c7705208e8622dc94603"
}
],
"tasks": [
{
"name": "global test task",
"parameters": ["--test-parameter"],
"script": "global/test/script.py"
}
]
}
]
}
''';
int main() {
test('BuildConfig parser works', () {
final BuildConfig buildConfig = BuildConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(buildConfigJson) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.errors, isNull);
expect(buildConfig.builds.length, equals(1));
final GlobalBuild globalBuild = buildConfig.builds[0];
expect(globalBuild.name, equals('build_name'));
expect(globalBuild.gn.length, equals(1));
expect(globalBuild.gn[0], equals('--gn-arg'));
expect(globalBuild.droneDimensions.length, equals(1));
expect(globalBuild.droneDimensions[0], equals('dimension'));
final BuildNinja ninja = globalBuild.ninja;
expect(ninja.config, equals('build_name'));
expect(ninja.targets.length, equals(1));
expect(ninja.targets[0], equals('ninja_target'));
expect(globalBuild.archives.length, equals(1));
final BuildArchive buildArchive = globalBuild.archives[0];
expect(buildArchive.name, equals('build_name'));
expect(buildArchive.basePath, equals('base/path'));
expect(buildArchive.type, equals('gcs'));
expect(buildArchive.includePaths.length, equals(1));
expect(buildArchive.includePaths[0], equals('include/path'));
expect(globalBuild.tests.length, equals(1));
final BuildTest tst = globalBuild.tests[0];
expect(tst.name, equals('build_name tests'));
expect(tst.language, equals('python3'));
expect(tst.script, equals('test/script.py'));
expect(tst.parameters.length, equals(1));
expect(tst.parameters[0], equals('--test-params'));
expect(tst.contexts.length, equals(1));
expect(tst.contexts[0], equals('context'));
expect(globalBuild.generators.length, equals(1));
final BuildTask buildTask = globalBuild.generators[0];
expect(buildTask.name, equals('generator_task'));
expect(buildTask.scripts.length, equals(1));
expect(buildTask.scripts[0], equals('gen/script.py'));
expect(buildTask.parameters.length, equals(1));
expect(buildTask.parameters[0], equals('--gen-param'));
expect(buildConfig.generators.length, equals(1));
final TestTask testTask = buildConfig.generators[0];
expect(testTask.name, equals('global generator task'));
expect(testTask.language, equals('dart'));
expect(testTask.script, equals('global/gen_script.dart'));
expect(testTask.parameters.length, equals(1));
expect(testTask.parameters[0], equals('--global-gen-param'));
expect(buildConfig.tests.length, equals(1));
final GlobalTest globalTest = buildConfig.tests[0];
expect(globalTest.name, equals('global test'));
expect(globalTest.recipe, equals('engine_v2/tester_engine'));
expect(globalTest.droneDimensions.length, equals(1));
expect(globalTest.droneDimensions[0], equals('dimension'));
expect(globalTest.dependencies.length, equals(1));
expect(globalTest.dependencies[0], equals('dependency'));
expect(globalTest.tasks.length, equals(1));
final TestTask globalTestTask = globalTest.tasks[0];
expect(globalTestTask.name, equals('global test task'));
expect(globalTestTask.script, equals('global/test/script.py'));
expect(globalTestTask.language, equals('<undef>'));
});
test('BuildConfig flags invalid input', () {
const String invalidInput = '''
{
"builds": 5,
"generators": {},
"tests": []
}
''';
final BuildConfig buildConfig = BuildConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isFalse);
expect(buildConfig.errors![0], equals(
'For field "builds", expected type: list, actual type: int.',
));
});
test('GlobalBuild flags invalid input', () {
const String invalidInput = '''
{
"builds": [
{
"name": 5
}
],
"generators": {},
"tests": []
}
''';
final BuildConfig buildConfig = BuildConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.builds.length, equals(1));
expect(buildConfig.builds[0].valid, isFalse);
expect(buildConfig.builds[0].errors![0], equals(
'For field "name", expected type: string, actual type: int.',
));
});
test('BuildNinja flags invalid input', () {
const String invalidInput = '''
{
"builds": [
{
"ninja": {
"config": 5
}
}
],
"generators": {},
"tests": []
}
''';
final BuildConfig buildConfig = BuildConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.builds.length, equals(1));
expect(buildConfig.builds[0].valid, isTrue);
expect(buildConfig.builds[0].ninja.valid, isFalse);
expect(buildConfig.builds[0].ninja.errors![0], equals(
'For field "config", expected type: string, actual type: int.',
));
});
test('BuildTest flags invalid input', () {
const String invalidInput = '''
{
"builds": [
{
"tests": [
{
"language": 5
}
]
}
],
"generators": {},
"tests": []
}
''';
final BuildConfig buildConfig = BuildConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.builds.length, equals(1));
expect(buildConfig.builds[0].valid, isTrue);
expect(buildConfig.builds[0].tests[0].valid, isFalse);
expect(buildConfig.builds[0].tests[0].errors![0], equals(
'For field "language", expected type: string, actual type: int.',
));
});
test('BuildTask flags invalid input', () {
const String invalidInput = '''
{
"builds": [
{
"generators": {
"tasks": [
{
"name": 5
}
]
}
}
],
"generators": {},
"tests": []
}
''';
final BuildConfig buildConfig = BuildConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.builds.length, equals(1));
expect(buildConfig.builds[0].valid, isTrue);
expect(buildConfig.builds[0].generators[0].valid, isFalse);
expect(buildConfig.builds[0].generators[0].errors![0], equals(
'For field "name", expected type: string, actual type: int.',
));
});
test('BuildArchive flags invalid input', () {
const String invalidInput = '''
{
"builds": [
{
"archives": [
{
"name": 5
}
]
}
],
"generators": {},
"tests": []
}
''';
final BuildConfig buildConfig = BuildConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.builds.length, equals(1));
expect(buildConfig.builds[0].valid, isTrue);
expect(buildConfig.builds[0].archives[0].valid, isFalse);
expect(buildConfig.builds[0].archives[0].errors![0], equals(
'For field "name", expected type: string, actual type: int.',
));
});
test('GlobalTest flags invalid input', () {
const String invalidInput = '''
{
"tests": [
{
"name": 5
}
]
}
''';
final BuildConfig buildConfig = BuildConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.tests.length, equals(1));
expect(buildConfig.tests[0].valid, isFalse);
expect(buildConfig.tests[0].errors![0], equals(
'For field "name", expected type: string, actual type: int.',
));
});
test('TestTask flags invalid input', () {
const String invalidInput = '''
{
"tests": [
{
"tasks": [
{
"name": 5
}
]
}
]
}
''';
final BuildConfig buildConfig = BuildConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.tests.length, equals(1));
expect(buildConfig.tests[0].tasks[0].valid, isFalse);
expect(buildConfig.tests[0].tasks[0].errors![0], contains(
'For field "name", expected type: string, actual type: int.',
));
});
return 0;
}
| engine/tools/pkg/engine_build_configs/test/build_config_test.dart/0 | {'file_path': 'engine/tools/pkg/engine_build_configs/test/build_config_test.dart', 'repo_id': 'engine', 'token_count': 4373} |
export 'src/expect_error.dart' show compiles, Code, Library;
| expect_error/lib/expect_error.dart/0 | {'file_path': 'expect_error/lib/expect_error.dart', 'repo_id': 'expect_error', 'token_count': 21} |
import 'package:fast_noise_flutter_example/forms/field.dart';
import 'package:fast_noise_flutter_example/forms/string_field.dart';
import 'package:flutter/material.dart';
class IntField extends Field<int> {
const IntField({
required super.title,
required super.value,
required super.setValue,
super.key,
super.enabled,
});
@override
IntFieldState createState() => IntFieldState();
}
class IntFieldState extends State<IntField> {
@override
Widget build(BuildContext context) {
return StringField(
title: widget.title,
enabled: widget.enabled,
value: widget.value.toString(),
setValue: (v) => widget.setValue(int.parse(v)),
);
}
}
| fast_noise/example/lib/forms/int_field.dart/0 | {'file_path': 'fast_noise/example/lib/forms/int_field.dart', 'repo_id': 'fast_noise', 'token_count': 253} |
import 'package:fast_noise/fast_noise.dart';
class SimplexNoise
implements Noise2And3, Noise4, Noise2Int, Noise3Int, Noise4Int {
final int seed;
final double frequency;
SimplexNoise({
this.seed = 1337,
this.frequency = .01,
});
@override
double getNoiseInt3(int x, int y, int z) => singleSimplex3(seed, x, y, z);
@override
double getNoise3(double x, double y, double z) => singleSimplex3(
seed,
(x * frequency).toInt(),
(y * frequency).toInt(),
(z * frequency).toInt(),
);
static const double _f3 = 1.0 / 3.0;
static const double _g3 = 1.0 / 6.0;
static const double _g33 = _g3 * 3.0 - 1.0;
double singleSimplex3(int seed, int x, int y, int z) {
var t = (x + y + z) * _f3;
final i = x + t.floor();
final j = y + t.floor();
final k = z + t.floor();
t = (i + j + k) * _g3;
final x0 = x - (i - t);
final y0 = y - (j - t);
final z0 = z - (k - t);
int i1;
int j1;
int k1;
int i2;
int j2;
int k2;
if (x0 >= y0) {
if (y0 >= z0) {
i1 = 1;
j1 = 0;
k1 = 0;
i2 = 1;
j2 = 1;
k2 = 0;
} else if (x0 >= z0) {
i1 = 1;
j1 = 0;
k1 = 0;
i2 = 1;
j2 = 0;
k2 = 1;
} else // x0 < z0
{
i1 = 0;
j1 = 0;
k1 = 1;
i2 = 1;
j2 = 0;
k2 = 1;
}
} else // x0 < y0
{
if (y0 < z0) {
i1 = 0;
j1 = 0;
k1 = 1;
i2 = 0;
j2 = 1;
k2 = 1;
} else if (x0 < z0) {
i1 = 0;
j1 = 1;
k1 = 0;
i2 = 0;
j2 = 1;
k2 = 1;
} else // x0 >= z0
{
i1 = 0;
j1 = 1;
k1 = 0;
i2 = 1;
j2 = 1;
k2 = 0;
}
}
final x1 = x0 - i1 + _g3;
final y1 = y0 - j1 + _g3;
final z1 = z0 - k1 + _g3;
final x2 = x0 - i2 + _f3;
final y2 = y0 - j2 + _f3;
final z2 = z0 - k2 + _f3;
final x3 = x0 + _g33;
final y3 = y0 + _g33;
final z3 = z0 + _g33;
final double n0;
final double n1;
final double n2;
final double n3;
t = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;
if (t < 0) {
n0 = .0;
} else {
t *= t;
n0 = t * t * gradCoord3D(seed, i, j, k, x0, y0, z0);
}
t = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;
if (t < 0) {
n1 = .0;
} else {
t *= t;
n1 = t * t * gradCoord3D(seed, i + i1, j + j1, k + k1, x1, y1, z1);
}
t = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;
if (t < 0) {
n2 = .0;
} else {
t *= t;
n2 = t * t * gradCoord3D(seed, i + i2, j + j2, k + k2, x2, y2, z2);
}
t = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;
if (t < 0) {
n3 = .0;
} else {
t *= t;
n3 = t * t * gradCoord3D(seed, i + 1, j + 1, k + 1, x3, y3, z3);
}
return 32 * (n0 + n1 + n2 + n3);
}
@override
double getNoise2(double x, double y) =>
singleSimplex2(seed, (x * frequency).toInt(), (y * frequency).toInt());
@override
double getNoiseInt2(int x, int y) => singleSimplex2(seed, x, y);
static const double _f2 = 1.0 / 2.0;
static const double _g2 = 1.0 / 4.0;
double singleSimplex2(int seed, int x, int y) {
var t = (x + y) * _f2;
final i = x + t.floor();
final j = y + t.floor();
t = (i + j) * _g2;
final x0 = x - (i - t);
final y0 = y - (j - t);
final int i1;
final int j1;
if (x0 > y0) {
i1 = 1;
j1 = 0;
} else {
i1 = 0;
j1 = 1;
}
final x1 = x0 - i1 + _g2;
final y1 = y0 - j1 + _g2;
final x2 = x0 - 1 + _f2;
final y2 = y0 - 1 + _f2;
final double n0;
final double n1;
final double n2;
t = 0.5 - x0 * x0 - y0 * y0;
if (t < 0) {
n0 = .0;
} else {
t *= t;
n0 = t * t * gradCoord2D(seed, i, j, x0, y0);
}
t = 0.5 - x1 * x1 - y1 * y1;
if (t < 0) {
n1 = .0;
} else {
t *= t;
n1 = t * t * gradCoord2D(seed, i + i1, j + j1, x1, y1);
}
t = 0.5 - x2 * x2 - y2 * y2;
if (t < 0) {
n2 = .0;
} else {
t *= t;
n2 = t * t * gradCoord2D(seed, i + 1, j + 1, x2, y2);
}
return 50 * (n0 + n1 + n2);
}
@override
double getNoise4(double x, double y, double z, double w) => singleSimplex4(
seed,
(x * frequency).toInt(),
(y * frequency).toInt(),
(z * frequency).toInt(),
(w * frequency).toInt(),
);
@override
double getNoiseInt4(int x, int y, int z, int w) =>
singleSimplex4(seed, x, y, z, w);
static const List<int> _simplex4d = [
0,
1,
2,
3,
0,
1,
3,
2,
0,
0,
0,
0,
0,
2,
3,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
2,
3,
0,
0,
2,
1,
3,
0,
0,
0,
0,
0,
3,
1,
2,
0,
3,
2,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
3,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
2,
0,
3,
0,
0,
0,
0,
1,
3,
0,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
2,
3,
0,
1,
2,
3,
1,
0,
1,
0,
2,
3,
1,
0,
3,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
2,
0,
3,
1,
0,
0,
0,
0,
2,
1,
3,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
2,
0,
1,
3,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
3,
0,
1,
2,
3,
0,
2,
1,
0,
0,
0,
0,
3,
1,
2,
0,
2,
1,
0,
3,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
3,
1,
0,
2,
0,
0,
0,
0,
3,
2,
0,
1,
3,
2,
1,
0
];
static const double _f4 = (2.23606797 - 1.0) / 4.0;
static const double _g4 = (5.0 - 2.23606797) / 20.0;
double singleSimplex4(int seed, int x, int y, int z, int w) {
final double n0;
final double n1;
final double n2;
final double n3;
final double n4;
var t = (x + y + z + w) * _f4;
final i = x + t.floor();
final j = y + t.floor();
final k = z + t.floor();
final l = w + t.floor();
t = (i + j + k + l) * _g4;
final x0 = x - (i - t);
final y0 = y - (j - t);
final z0 = z - (k - t);
final w0 = w - (l - t);
var c = (x0 > y0) ? 32 : 0;
c += (x0 > z0) ? 16 : 0;
c += (y0 > z0) ? 8 : 0;
c += (x0 > w0) ? 4 : 0;
c += (y0 > w0) ? 2 : 0;
c += (z0 > w0) ? 1 : 0;
c <<= 2;
final i1 = _simplex4d[c] >= 3 ? 1 : 0;
final i2 = _simplex4d[c] >= 2 ? 1 : 0;
final i3 = _simplex4d[c++] >= 1 ? 1 : 0;
final j1 = _simplex4d[c] >= 3 ? 1 : 0;
final j2 = _simplex4d[c] >= 2 ? 1 : 0;
final j3 = _simplex4d[c++] >= 1 ? 1 : 0;
final k1 = _simplex4d[c] >= 3 ? 1 : 0;
final k2 = _simplex4d[c] >= 2 ? 1 : 0;
final k3 = _simplex4d[c++] >= 1 ? 1 : 0;
final l1 = _simplex4d[c] >= 3 ? 1 : 0;
final l2 = _simplex4d[c] >= 2 ? 1 : 0;
final l3 = _simplex4d[c] >= 1 ? 1 : 0;
final x1 = x0 - i1 + _g4;
final y1 = y0 - j1 + _g4;
final z1 = z0 - k1 + _g4;
final w1 = w0 - l1 + _g4;
final x2 = x0 - i2 + 2 * _g4;
final y2 = y0 - j2 + 2 * _g4;
final z2 = z0 - k2 + 2 * _g4;
final w2 = w0 - l2 + 2 * _g4;
final x3 = x0 - i3 + 3 * _g4;
final y3 = y0 - j3 + 3 * _g4;
final z3 = z0 - k3 + 3 * _g4;
final w3 = w0 - l3 + 3 * _g4;
final x4 = x0 - 1 + 4 * _g4;
final y4 = y0 - 1 + 4 * _g4;
final z4 = z0 - 1 + 4 * _g4;
final w4 = w0 - 1 + 4 * _g4;
t = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;
if (t < 0) {
n0 = .0;
} else {
t *= t;
n0 = t * t * gradCoord4D(seed, i, j, k, l, x0, y0, z0, w0);
}
t = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;
if (t < 0) {
n1 = .0;
} else {
t *= t;
n1 = t *
t *
gradCoord4D(seed, i + i1, j + j1, k + k1, l + l1, x1, y1, z1, w1);
}
t = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;
if (t < 0) {
n2 = .0;
} else {
t *= t;
n2 = t *
t *
gradCoord4D(seed, i + i2, j + j2, k + k2, l + l2, x2, y2, z2, w2);
}
t = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;
if (t < 0) {
n3 = .0;
} else {
t *= t;
n3 = t *
t *
gradCoord4D(seed, i + i3, j + j3, k + k3, l + l3, x3, y3, z3, w3);
}
t = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;
if (t < 0) {
n4 = .0;
} else {
t *= t;
n4 =
t * t * gradCoord4D(seed, i + 1, j + 1, k + 1, l + 1, x4, y4, z4, w4);
}
return 27 * (n0 + n1 + n2 + n3 + n4);
}
}
| fast_noise/lib/src/noise/simplex.dart/0 | {'file_path': 'fast_noise/lib/src/noise/simplex.dart', 'repo_id': 'fast_noise', 'token_count': 5940} |
import 'dart:ui';
import 'package:equatable/equatable.dart';
import 'package:fire_atlas_editor/screens/editor_screen/widgets/selection_canvas/canvas_board.dart';
import 'package:fire_atlas_editor/store/store.dart';
import 'package:fire_atlas_editor/widgets/container.dart';
import 'package:flame/flame.dart';
import 'package:flame/sprite.dart';
import 'package:flutter/material.dart' hide Image;
import 'package:slices/slices.dart';
class _SelectionCanvasSlice extends Equatable {
final String? atlasId;
final String? imageData;
final double? tileHeight;
final double? tileWidth;
_SelectionCanvasSlice.fromState(FireAtlasState state)
: atlasId = state.currentAtlas?.id,
imageData = state.currentAtlas?.imageData,
tileWidth = state.currentAtlas?.tileWidth,
tileHeight = state.currentAtlas?.tileHeight;
@override
List<Object?> get props => [atlasId, imageData, tileHeight, tileWidth];
bool isLoaded() => atlasId != null;
}
class SelectionCanvas extends StatelessWidget {
const SelectionCanvas({super.key});
@override
Widget build(BuildContext context) {
return SliceWatcher<FireAtlasState, _SelectionCanvasSlice>(
slicer: _SelectionCanvasSlice.fromState,
builder: (context, store, slice) {
if (!slice.isLoaded()) {
return const Text('No atlas selected');
}
return FContainer(
child: FutureBuilder<Image>(
future: Flame.images.fromBase64(
slice.atlasId!,
slice.imageData!,
),
builder: (ctx, snapshot) {
if (snapshot.hasData) {
return LayoutBuilder(
builder: (ctx, constraints) {
final size = Size(
constraints.maxWidth,
constraints.maxHeight,
);
return CanvasBoard(
sprite: Sprite(snapshot.data!),
size: size,
tileHeight: slice.tileHeight!,
tileWidth: slice.tileWidth!,
);
},
);
}
return const Text('Something wrong happened :(');
},
),
);
},
);
}
}
| fire-atlas/fire_atlas_editor/lib/screens/editor_screen/widgets/selection_canvas/selection_canvas.dart/0 | {'file_path': 'fire-atlas/fire_atlas_editor/lib/screens/editor_screen/widgets/selection_canvas/selection_canvas.dart', 'repo_id': 'fire-atlas', 'token_count': 1070} |
import 'package:fire_atlas_editor/services/storage/storage.dart';
import 'package:fire_atlas_editor/store/actions/editor_actions.dart';
import 'package:fire_atlas_editor/store/store.dart';
import 'package:flame/flame.dart';
import 'package:flame_fire_atlas/flame_fire_atlas.dart';
import 'package:flutter/rendering.dart';
import 'package:slices/slices.dart';
class CreateAtlasAction extends AsyncSlicesAction<FireAtlasState> {
final String id;
final String imageData;
final double tileWidth;
final double tileHeight;
CreateAtlasAction({
required this.id,
required this.imageData,
required this.tileWidth,
required this.tileHeight,
});
@override
Future<FireAtlasState> perform(_, FireAtlasState state) async {
final atlas = FireAtlas(
id: id,
imageData: imageData,
tileHeight: tileHeight,
tileWidth: tileWidth,
);
await atlas.loadImage(clearImageData: false);
return state.copyWith(
hasChanges: true,
loadedProject: Nullable(
LoadedProjectEntry(null, atlas),
),
);
}
}
class UpdateAtlasImageAction extends AsyncSlicesAction<FireAtlasState> {
final String imageData;
UpdateAtlasImageAction({required this.imageData});
@override
Future<FireAtlasState> perform(_, FireAtlasState state) async {
if (state.currentAtlas != null) {
final atlas = state.currentAtlas!;
Flame.images.clearCache();
atlas.imageData = imageData;
await atlas.loadImage(clearImageData: false);
return state.copyWith(
hasChanges: true,
loadedProject: Nullable(
state.loadedProject.value?.copyWith(project: atlas),
),
);
}
return state;
}
}
class SetSelectionAction extends SlicesAction<FireAtlasState> {
final List<BaseSelection> selections;
SetSelectionAction({
required BaseSelection selection,
}) : selections = [selection];
SetSelectionAction.multiple({
required this.selections,
});
@override
FireAtlasState perform(_, FireAtlasState state) {
final atlas = state.currentAtlas;
if (atlas != null && selections.isNotEmpty) {
for (final selection in selections) {
atlas.selections[selection.id] = selection;
}
return state.copyWith(
hasChanges: true,
selectedSelection: Nullable(selections.last),
loadedProject: Nullable(
state.loadedProject.value?.copyWith(project: atlas),
),
);
}
return state;
}
}
class SelectSelectionAction extends SlicesAction<FireAtlasState> {
final BaseSelection? selection;
SelectSelectionAction({
this.selection,
});
@override
FireAtlasState perform(_, FireAtlasState state) {
return state.copyWith(
selectedSelection: Nullable(selection),
);
}
}
class RemoveSelectedSelectionAction extends SlicesAction<FireAtlasState> {
@override
FireAtlasState perform(_, FireAtlasState state) {
final atlas = state.currentAtlas;
final selected = state.selectedSelection;
if (atlas != null && selected != null) {
atlas.selections.remove(selected.id);
return state.copyWith(
hasChanges: true,
selectedSelection: Nullable(null),
loadedProject: Nullable(
state.loadedProject.value?.copyWith(project: atlas),
),
);
}
return state;
}
}
class SaveAction extends AsyncSlicesAction<FireAtlasState> {
@override
Future<FireAtlasState> perform(
SlicesStore<FireAtlasState> store,
FireAtlasState state,
) async {
final project = state.loadedProject.value;
if (project != null) {
try {
final storage = FireAtlasStorage();
final path =
project.path ?? await storage.selectNewProjectPath(project.project);
final newState = state.copyWith(
hasChanges: false,
loadedProject: Nullable(
state.loadedProject.value?.copyWith(path: path),
),
);
await storage.saveProject(newState.loadedProject.value!);
await storage.rememberProject(newState.loadedProject.value!);
store.dispatch(
CreateMessageAction(
message: 'Atlas saved!',
type: MessageType.INFO,
),
);
return newState;
} catch (e) {
debugPrint(e.toString());
store.dispatch(
CreateMessageAction(
message: 'Error trying to save project!',
type: MessageType.ERROR,
),
);
}
}
return state;
}
}
class RenameAtlasAction extends AsyncSlicesAction<FireAtlasState> {
final String newAtlasId;
RenameAtlasAction({required this.newAtlasId});
@override
Future<FireAtlasState> perform(
SlicesStore<FireAtlasState> store,
FireAtlasState state,
) async {
final atlas = state.currentAtlas;
if (atlas == null) {
return state;
}
atlas.id = newAtlasId;
return state.copyWith(
hasChanges: true,
loadedProject: Nullable(
state.loadedProject.value?.copyWith(
project: atlas,
),
),
);
}
}
class LoadAtlasAction extends AsyncSlicesAction<FireAtlasState> {
final String path;
LoadAtlasAction(this.path);
@override
Future<FireAtlasState> perform(_, FireAtlasState state) async {
final storage = FireAtlasStorage();
final loaded = await storage.loadProject(path);
await loaded.project.loadImage(clearImageData: false);
return state.copyWith(loadedProject: Nullable(loaded));
}
}
| fire-atlas/fire_atlas_editor/lib/store/actions/atlas_actions.dart/0 | {'file_path': 'fire-atlas/fire_atlas_editor/lib/store/actions/atlas_actions.dart', 'repo_id': 'fire-atlas', 'token_count': 2157} |
bricks:
sprite_component:
path: bricks/sprite_component
sprite_animation_component:
path: bricks/sprite_animation_component
| flame-bricks/mason.yaml/0 | {'file_path': 'flame-bricks/mason.yaml', 'repo_id': 'flame-bricks', 'token_count': 46} |
name: 'Flame Format'
description: 'An opinionated action that validates a Flutter project code format'
author: 'flame-engine'
branding:
color: red
icon: code
runs:
using: 'composite'
steps:
- run: ${{ github.action_path }}/scripts/format.sh
shell: bash
| flame-format-action/action.yml/0 | {'file_path': 'flame-format-action/action.yml', 'repo_id': 'flame-format-action', 'token_count': 96} |
blank_issues_enabled: true
contact_links:
- name: I have some questions about Flame.
url: https://stackoverflow.com/tags/flame
about: Ask your questions on StackOverflow! The community is always willing to help out.
- name: Join us on Discord!
url: https://discord.gg/pxrBmy4
about: Ask your questions in our community!
| flame/.github/ISSUE_TEMPLATE/config.yml/0 | {'file_path': 'flame/.github/ISSUE_TEMPLATE/config.yml', 'repo_id': 'flame', 'token_count': 106} |
import 'package:flame/components.dart';
import 'package:flame/experimental.dart';
import 'package:flame/flame.dart';
import 'package:flame/game.dart';
import 'package:klondike/step2/components/foundation.dart';
import 'package:klondike/step2/components/pile.dart';
import 'package:klondike/step2/components/stock.dart';
import 'package:klondike/step2/components/waste.dart';
class KlondikeGame extends FlameGame {
static const double cardGap = 175.0;
static const double cardWidth = 1000.0;
static const double cardHeight = 1400.0;
static const double cardRadius = 100.0;
static final Vector2 cardSize = Vector2(cardWidth, cardHeight);
@override
Future<void> onLoad() async {
await Flame.images.load('klondike-sprites.png');
final stock = Stock()
..size = cardSize
..position = Vector2(cardGap, cardGap);
final waste = Waste()
..size = cardSize
..position = Vector2(cardWidth + 2 * cardGap, cardGap);
final foundations = List.generate(
4,
(i) => Foundation()
..size = cardSize
..position =
Vector2((i + 3) * (cardWidth + cardGap) + cardGap, cardGap),
);
final piles = List.generate(
7,
(i) => Pile()
..size = cardSize
..position = Vector2(
cardGap + i * (cardWidth + cardGap),
cardHeight + 2 * cardGap,
),
);
final world = World()
..add(stock)
..add(waste)
..addAll(foundations)
..addAll(piles);
add(world);
final camera = CameraComponent(world: world)
..viewfinder.visibleGameSize =
Vector2(cardWidth * 7 + cardGap * 8, 4 * cardHeight + 3 * cardGap)
..viewfinder.position = Vector2(cardWidth * 3.5 + cardGap * 4, 0)
..viewfinder.anchor = Anchor.topCenter;
add(camera);
}
}
Sprite klondikeSprite(double x, double y, double width, double height) {
return Sprite(
Flame.images.fromCache('klondike-sprites.png'),
srcPosition: Vector2(x, y),
srcSize: Vector2(width, height),
);
}
| flame/doc/tutorials/klondike/app/lib/step2/klondike_game.dart/0 | {'file_path': 'flame/doc/tutorials/klondike/app/lib/step2/klondike_game.dart', 'repo_id': 'flame', 'token_count': 821} |
import 'dart:ui';
import 'package:flame/components.dart';
import 'package:padracing/car.dart';
import 'package:padracing/tire.dart';
class Trail extends Component with HasPaint {
Trail({
required this.car,
required this.tire,
}) : super(priority: 1);
final Car car;
final Tire tire;
final trail = <Offset>[];
final _trailLength = 30;
@override
Future<void> onLoad() async {
paint
..color = (tire.paint.color.withOpacity(0.9))
..strokeWidth = 1.0;
}
@override
void update(double dt) {
if (tire.body.linearVelocity.length2 > 100) {
if (trail.length > _trailLength) {
trail.removeAt(0);
}
final trailPoint = tire.body.position.toOffset();
trail.add(trailPoint);
} else if (trail.isNotEmpty) {
trail.removeAt(0);
}
}
@override
void render(Canvas canvas) {
canvas.drawPoints(PointMode.polygon, trail, paint);
}
}
| flame/examples/games/padracing/lib/trail.dart/0 | {'file_path': 'flame/examples/games/padracing/lib/trail.dart', 'repo_id': 'flame', 'token_count': 377} |
// ignore_for_file: unused_element
import 'dart:ui';
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
enum ObstacleType {
cactusSmall,
cactusLarge,
}
class ObstacleTypeSettings {
const ObstacleTypeSettings._internal(
this.type, {
required this.size,
required this.y,
required this.allowedAt,
required this.multipleAt,
required this.minGap,
required this.minSpeed,
this.numFrames,
this.frameRate,
this.speedOffset,
required this.generateHitboxes,
});
final ObstacleType type;
final Vector2 size;
final double y;
final int allowedAt;
final int multipleAt;
final double minGap;
final double minSpeed;
final int? numFrames;
final double? frameRate;
final double? speedOffset;
static const maxGroupSize = 3.0;
final List<ShapeHitbox> Function() generateHitboxes;
static final cactusSmall = ObstacleTypeSettings._internal(
ObstacleType.cactusSmall,
size: Vector2(34.0, 70.0),
y: -55.0,
allowedAt: 0,
multipleAt: 1000,
minGap: 120.0,
minSpeed: 0.0,
generateHitboxes: () => <ShapeHitbox>[
RectangleHitbox(
position: Vector2(5.0, 7.0),
size: Vector2(10.0, 54.0),
),
RectangleHitbox(
position: Vector2(5.0, 7.0),
size: Vector2(12.0, 68.0),
),
RectangleHitbox(
position: Vector2(15.0, 4.0),
size: Vector2(14.0, 28.0),
),
],
);
static final cactusLarge = ObstacleTypeSettings._internal(
ObstacleType.cactusLarge,
size: Vector2(50.0, 100.0),
y: -74.0,
allowedAt: 800,
multipleAt: 1500,
minGap: 120.0,
minSpeed: 0.0,
generateHitboxes: () => <ShapeHitbox>[
RectangleHitbox(
position: Vector2(0.0, 26.0),
size: Vector2(14.0, 40.0),
),
RectangleHitbox(
position: Vector2(16.0, 0.0),
size: Vector2(14.0, 98.0),
),
RectangleHitbox(
position: Vector2(28.0, 22.0),
size: Vector2(20.0, 40.0),
),
],
);
Sprite sprite(Image spriteImage) {
switch (type) {
case ObstacleType.cactusSmall:
return Sprite(
spriteImage,
srcPosition: Vector2(446.0, 2.0),
srcSize: size,
);
case ObstacleType.cactusLarge:
return Sprite(
spriteImage,
srcPosition: Vector2(652.0, 2.0),
srcSize: size,
);
}
}
}
| flame/examples/games/trex/lib/obstacle/obstacle_type.dart/0 | {'file_path': 'flame/examples/games/trex/lib/obstacle/obstacle_type.dart', 'repo_id': 'flame', 'token_count': 1098} |
import 'dart:math' as math;
import 'package:examples/stories/bridge_libraries/forge2d/utils/boundaries.dart';
import 'package:flame/input.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
class BlobExample extends Forge2DGame with TapDetector {
static const String description = '''
In this example we show the power of joints by showing interactions between
bodies tied together.
Tap the screen to add boxes that will bounce on the "blob" in the center.
''';
@override
Future<void> onLoad() async {
final worldCenter = screenToWorld(size * camera.zoom / 2);
final blobCenter = worldCenter + Vector2(0, -30);
final blobRadius = Vector2.all(6.0);
addAll(createBoundaries(this));
add(Ground(worldCenter));
final jointDef = ConstantVolumeJointDef()
..frequencyHz = 20.0
..dampingRatio = 1.0
..collideConnected = false;
await addAll([
for (var i = 0; i < 20; i++) BlobPart(i, jointDef, blobRadius, blobCenter)
]);
world.createJoint(ConstantVolumeJoint(world, jointDef));
}
@override
void onTapDown(TapDownInfo details) {
super.onTapDown(details);
add(FallingBox(details.eventPosition.game));
}
}
class Ground extends BodyComponent {
final Vector2 worldCenter;
Ground(this.worldCenter);
@override
Body createBody() {
final shape = PolygonShape();
shape.setAsBoxXY(20.0, 0.4);
final fixtureDef = FixtureDef(shape, friction: 0.2);
final bodyDef = BodyDef(position: worldCenter.clone());
final ground = world.createBody(bodyDef);
ground.createFixture(fixtureDef);
shape.setAsBox(0.4, 20.0, Vector2(-10.0, 0.0), 0.0);
ground.createFixture(fixtureDef);
shape.setAsBox(0.4, 20.0, Vector2(10.0, 0.0), 0.0);
ground.createFixture(fixtureDef);
return ground;
}
}
class BlobPart extends BodyComponent {
final ConstantVolumeJointDef jointDef;
final int bodyNumber;
final Vector2 blobRadius;
final Vector2 blobCenter;
BlobPart(
this.bodyNumber,
this.jointDef,
this.blobRadius,
this.blobCenter,
);
@override
Body createBody() {
const nBodies = 20.0;
const bodyRadius = 0.5;
final angle = (bodyNumber / nBodies) * math.pi * 2;
final x = blobCenter.x + blobRadius.x * math.sin(angle);
final y = blobCenter.y + blobRadius.y * math.cos(angle);
final bodyDef = BodyDef(
fixedRotation: true,
position: Vector2(x, y),
type: BodyType.dynamic,
);
final body = world.createBody(bodyDef);
final shape = CircleShape()..radius = bodyRadius;
final fixtureDef = FixtureDef(
shape,
density: 1.0,
friction: 0.2,
);
body.createFixture(fixtureDef);
jointDef.addBody(body);
return body;
}
}
class FallingBox extends BodyComponent {
final Vector2 position;
FallingBox(this.position);
@override
Body createBody() {
final bodyDef = BodyDef(
type: BodyType.dynamic,
position: position,
);
final shape = PolygonShape()..setAsBoxXY(2, 4);
final body = world.createBody(bodyDef);
body.createFixtureFromShape(shape, 1.0);
return body;
}
}
| flame/examples/lib/stories/bridge_libraries/forge2d/blob_example.dart/0 | {'file_path': 'flame/examples/lib/stories/bridge_libraries/forge2d/blob_example.dart', 'repo_id': 'flame', 'token_count': 1193} |
import 'package:examples/stories/bridge_libraries/forge2d/utils/boundaries.dart';
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flame_forge2d/flame_forge2d.dart' hide Transform;
import 'package:flutter/material.dart';
class WidgetExample extends Forge2DGame with TapDetector {
static const String description = '''
This examples shows how to render a widget on top of a Forge2D body outside
of Flame.
''';
List<Function()> updateStates = [];
Map<int, Body> bodyIdMap = {};
List<int> addLaterIds = [];
Vector2 screenPosition(Body body) => worldToScreen(body.worldCenter);
WidgetExample() : super(zoom: 20, gravity: Vector2(0, 10.0));
@override
Future<void> onLoad() async {
final boundaries = createBoundaries(this);
addAll(boundaries);
}
Body createBody() {
final bodyDef = BodyDef(
angularVelocity: 3,
position: screenToWorld(
Vector2.random()..multiply(camera.viewport.effectiveSize),
),
type: BodyType.dynamic,
);
final body = world.createBody(bodyDef);
final shape = PolygonShape()..setAsBoxXY(4.6, 0.8);
final fixtureDef = FixtureDef(
shape,
density: 1.0,
restitution: 0.8,
friction: 0.2,
);
body.createFixture(fixtureDef);
return body;
}
int createBodyId() {
final id = bodyIdMap.length + addLaterIds.length;
addLaterIds.add(id);
return id;
}
@override
void update(double dt) {
super.update(dt);
addLaterIds.forEach((id) => bodyIdMap[id] = createBody());
addLaterIds.clear();
updateStates.forEach((f) => f());
}
}
class BodyWidgetExample extends StatelessWidget {
const BodyWidgetExample({super.key});
@override
Widget build(BuildContext context) {
return GameWidget<WidgetExample>(
game: WidgetExample(),
overlayBuilderMap: {
'button1': (ctx, game) {
return BodyButtonWidget(game, game.createBodyId());
},
'button2': (ctx, game) {
return BodyButtonWidget(game, game.createBodyId());
},
},
initialActiveOverlays: const ['button1', 'button2'],
);
}
}
class BodyButtonWidget extends StatefulWidget {
final WidgetExample _game;
final int _bodyId;
const BodyButtonWidget(
this._game,
this._bodyId, {
super.key,
});
@override
State<StatefulWidget> createState() {
return _BodyButtonState(_game, _bodyId);
}
}
class _BodyButtonState extends State<BodyButtonWidget> {
final WidgetExample _game;
final int _bodyId;
Body? _body;
_BodyButtonState(this._game, this._bodyId) {
_game.updateStates.add(() {
setState(() {
_body = _game.bodyIdMap[_bodyId];
});
});
}
@override
Widget build(BuildContext context) {
final body = _body;
if (body == null) {
return Container();
} else {
final bodyPosition = _game.screenPosition(body);
return Positioned(
top: bodyPosition.y - 18,
left: bodyPosition.x - 90,
child: Transform.rotate(
angle: body.angle,
child: ElevatedButton(
onPressed: () {
setState(
() => body.applyLinearImpulse(Vector2(0.0, 1000)),
);
},
child: const Text(
'Flying button!',
textScaleFactor: 2.0,
),
),
),
);
}
}
}
| flame/examples/lib/stories/bridge_libraries/forge2d/widget_example.dart/0 | {'file_path': 'flame/examples/lib/stories/bridge_libraries/forge2d/widget_example.dart', 'repo_id': 'flame', 'token_count': 1417} |
import 'package:flame/components.dart';
import 'package:flame/extensions.dart';
import 'package:flame/game.dart';
import 'package:flame/input.dart';
class PriorityExample extends FlameGame with HasTappables {
static const String description = '''
On this example, click on the square to bring them to the front by changing
the priority.
''';
PriorityExample()
: super(
children: [
Square(Vector2(100, 100)),
Square(Vector2(160, 100)),
Square(Vector2(170, 150)),
Square(Vector2(110, 150)),
],
);
}
class Square extends RectangleComponent
with HasGameRef<PriorityExample>, Tappable {
Square(Vector2 position)
: super(
position: position,
size: Vector2.all(100),
paint: PaintExtension.random(withAlpha: 0.9, base: 100),
);
@override
bool onTapDown(TapDownInfo info) {
final topComponent = gameRef.children.last;
if (topComponent != this) {
gameRef.children.changePriority(this, topComponent.priority + 1);
}
return false;
}
}
| flame/examples/lib/stories/components/priority_example.dart/0 | {'file_path': 'flame/examples/lib/stories/components/priority_example.dart', 'repo_id': 'flame', 'token_count': 436} |
import 'package:examples/commons/ember.dart';
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flutter/material.dart' show Colors;
class DraggablesExample extends FlameGame with HasDraggables {
static const String description = '''
In this example we show you can use the `Draggable` mixin on
`PositionComponent`s. Drag around the Embers and see their position
changing.
''';
final double zoom;
late final DraggableSquare square;
DraggablesExample({required this.zoom});
@override
Future<void> onLoad() async {
camera.zoom = zoom;
add(square = DraggableSquare());
add(DraggableSquare()..y = 350);
}
}
// Note: this component does not consider the possibility of multiple
// simultaneous drags with different pointerIds.
class DraggableSquare extends Ember with Draggable {
@override
bool debugMode = true;
DraggableSquare({Vector2? position})
: super(
position: position ?? Vector2.all(100),
size: Vector2.all(100),
);
Vector2? dragDeltaPosition;
@override
void update(double dt) {
super.update(dt);
debugColor = isDragged && parent is DraggablesExample
? Colors.greenAccent
: Colors.purple;
}
@override
bool onDragStart(DragStartInfo info) {
dragDeltaPosition = info.eventPosition.game - position;
return false;
}
@override
bool onDragUpdate(DragUpdateInfo info) {
if (parent is! DraggablesExample) {
return true;
}
final dragDeltaPosition = this.dragDeltaPosition;
if (dragDeltaPosition == null) {
return false;
}
position.setFrom(info.eventPosition.game - dragDeltaPosition);
return false;
}
@override
bool onDragEnd(_) {
dragDeltaPosition = null;
return false;
}
@override
bool onDragCancel() {
dragDeltaPosition = null;
return false;
}
}
| flame/examples/lib/stories/input/draggables_example.dart/0 | {'file_path': 'flame/examples/lib/stories/input/draggables_example.dart', 'repo_id': 'flame', 'token_count': 673} |
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame/parallax.dart';
class AdvancedParallaxExample extends FlameGame {
static const String description = '''
Shows how to create a parallax with different velocity deltas on each layer.
''';
final _layersMeta = {
'parallax/bg.png': 1.0,
'parallax/mountain-far.png': 1.5,
'parallax/mountains.png': 2.3,
'parallax/trees.png': 3.8,
'parallax/foreground-trees.png': 6.6,
};
@override
Future<void> onLoad() async {
final layers = _layersMeta.entries.map(
(e) => loadParallaxLayer(
ParallaxImageData(e.key),
velocityMultiplier: Vector2(e.value, 1.0),
),
);
final parallax = ParallaxComponent(
parallax: Parallax(
await Future.wait(layers),
baseVelocity: Vector2(20, 0),
),
);
add(parallax);
}
}
| flame/examples/lib/stories/parallax/advanced_parallax_example.dart/0 | {'file_path': 'flame/examples/lib/stories/parallax/advanced_parallax_example.dart', 'repo_id': 'flame', 'token_count': 385} |
import 'package:flame/components.dart';
import 'package:flame/game.dart';
class Base64SpriteExample extends FlameGame {
static const String description = '''
In this example we load a sprite from the a base64 string and put it into a
`SpriteComponent`.
''';
@override
Future<void> onLoad() async {
const exampleUrl =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/'
'9hAAAAxElEQVQ4jYWTMQ7DIAxFIeoNuAGK1K1ISL0DMwOHzNC5p6iUPeoNOEM7GZ'
'nPJ/EUbP7Lx7KtIfH91B/L++gs5m5M9NreTN/dEZiVghatwbXvY68UlksyPjprRa'
'xFGAJZg+uAuSSzzC7rEDirDYAz2wg0RjWRFa/EUwdnQnQ37QFe1Odjrw04AKTTaB'
'XPAlx8dDaXdNk4rMsc0B7ge/UcYLTZxoFizxCQ/L0DMAhaX4Mzj/uzW6phu3AvtH'
'UUU4BAWJ6t8x9N/HHcruXjwQAAAABJRU5ErkJggg==';
final image = await images.fromBase64('shield.png', exampleUrl);
add(
SpriteComponent.fromImage(
image,
position: size / 2,
size: Vector2.all(100),
anchor: Anchor.center,
),
);
}
}
| flame/examples/lib/stories/sprites/base64_sprite_example.dart/0 | {'file_path': 'flame/examples/lib/stories/sprites/base64_sprite_example.dart', 'repo_id': 'flame', 'token_count': 538} |
import 'package:dashbook/dashbook.dart';
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flutter/material.dart';
class CustomPainterExample extends FlameGame with TapDetector {
static const description = '''
Example demonstration of how to use the CustomPainterComponent.
On the screen you can see a component using a custom painter being
rendered on a FlameGame, and if you tap, that same painter is used to
show a smiley on a widget overlay.
''';
@override
Future<void> onLoad() async {
add(Player());
}
@override
void onTap() {
if (overlays.isActive('Smiley')) {
overlays.remove('Smiley');
} else {
overlays.add('Smiley');
}
}
}
Widget customPainterBuilder(DashbookContext ctx) {
return GameWidget(
game: CustomPainterExample(),
overlayBuilderMap: {
'Smiley': (context, game) {
return Center(
child: Container(
color: Colors.transparent,
width: 200,
height: 200,
child: Column(
children: [
const Text(
'Hey, I can be a widget too!',
style: TextStyle(
color: Colors.white70,
),
),
const SizedBox(height: 32),
SizedBox(
height: 132,
width: 132,
child: CustomPaint(painter: PlayerCustomPainter()),
),
],
),
),
);
},
},
);
}
class PlayerCustomPainter extends CustomPainter {
late final facePaint = Paint()..color = Colors.yellow;
late final eyesPaint = Paint()..color = Colors.black;
@override
void paint(Canvas canvas, Size size) {
final faceRadius = size.height / 2;
canvas.drawCircle(
Offset(
faceRadius,
faceRadius,
),
faceRadius,
facePaint,
);
final eyeSize = faceRadius * 0.15;
canvas.drawCircle(
Offset(
faceRadius - (eyeSize * 2),
faceRadius - eyeSize,
),
eyeSize,
eyesPaint,
);
canvas.drawCircle(
Offset(
faceRadius + (eyeSize * 2),
faceRadius - eyeSize,
),
eyeSize,
eyesPaint,
);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
class Player extends CustomPainterComponent
with HasGameRef<CustomPainterExample> {
static const speed = 150;
int direction = 1;
@override
Future<void> onLoad() async {
painter = PlayerCustomPainter();
size = Vector2.all(100);
y = 200;
}
@override
void update(double dt) {
super.update(dt);
x += speed * direction * dt;
if ((x + width >= gameRef.size.x && direction > 0) ||
(x <= 0 && direction < 0)) {
direction *= -1;
}
}
}
| flame/examples/lib/stories/widgets/custom_painter_example.dart/0 | {'file_path': 'flame/examples/lib/stories/widgets/custom_painter_example.dart', 'repo_id': 'flame', 'token_count': 1325} |
export 'src/image_composition.dart';
| flame/packages/flame/lib/image_composition.dart/0 | {'file_path': 'flame/packages/flame/lib/image_composition.dart', 'repo_id': 'flame', 'token_count': 13} |
import 'package:flame/collisions.dart';
import 'package:flame/game.dart';
/// Keeps track of all the [ShapeHitbox]s in the component tree and initiates
/// collision detection every tick.
mixin HasCollisionDetection on FlameGame {
CollisionDetection<Hitbox> _collisionDetection = StandardCollisionDetection();
CollisionDetection<Hitbox> get collisionDetection => _collisionDetection;
set collisionDetection(CollisionDetection<Hitbox> cd) {
cd.addAll(_collisionDetection.items);
_collisionDetection = cd;
}
@override
void update(double dt) {
super.update(dt);
collisionDetection.run();
}
}
| flame/packages/flame/lib/src/collisions/has_collision_detection.dart/0 | {'file_path': 'flame/packages/flame/lib/src/collisions/has_collision_detection.dart', 'repo_id': 'flame', 'token_count': 198} |
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flutter/widgets.dart' show EdgeInsets;
import 'package:meta/meta.dart';
/// The [HudMarginComponent] positions itself by a margin to the edge of the
/// screen instead of by an absolute position on the screen or on the game, so
/// if the game is resized the component will move to keep its margin.
///
/// Note that the margin is calculated to the [Anchor], not to the edge of the
/// component.
///
/// If you set the position of the component instead of a margin when
/// initializing the component, the margin to the edge of the screen from that
/// position will be used.
class HudMarginComponent<T extends FlameGame> extends PositionComponent
with HasGameRef<T> {
@override
PositionType positionType = PositionType.viewport;
/// Instead of setting a position of the [HudMarginComponent] a margin
/// from the edges of the viewport can be used instead.
EdgeInsets? margin;
HudMarginComponent({
this.margin,
super.position,
super.size,
super.scale,
super.angle,
super.anchor,
super.children,
super.priority,
}) : assert(
margin != null || position != null,
'Either margin or position must be defined',
);
@override
@mustCallSuper
Future<void> onLoad() async {
super.onLoad();
// If margin is not null we will update the position `onGameResize` instead
if (margin == null) {
final screenSize = gameRef.size;
final topLeft = anchor.toOtherAnchorPosition(
position,
Anchor.topLeft,
scaledSize,
);
final bottomRight = screenSize -
anchor.toOtherAnchorPosition(
position,
Anchor.bottomRight,
scaledSize,
);
margin = EdgeInsets.fromLTRB(
topLeft.x,
topLeft.y,
bottomRight.x,
bottomRight.y,
);
} else {
size.addListener(_updateMargins);
}
_updateMargins();
}
@override
void onGameResize(Vector2 gameSize) {
super.onGameResize(gameSize);
if (isMounted) {
_updateMargins();
}
}
void _updateMargins() {
final screenSize = positionType == PositionType.viewport
? gameRef.camera.viewport.effectiveSize
: gameRef.canvasSize;
final margin = this.margin!;
final x = margin.left != 0
? margin.left + scaledSize.x / 2
: screenSize.x - margin.right - scaledSize.x / 2;
final y = margin.top != 0
? margin.top + scaledSize.y / 2
: screenSize.y - margin.bottom - scaledSize.y / 2;
position.setValues(x, y);
position = Anchor.center.toOtherAnchorPosition(
position,
anchor,
scaledSize,
);
}
}
| flame/packages/flame/lib/src/components/input/hud_margin_component.dart/0 | {'file_path': 'flame/packages/flame/lib/src/components/input/hud_margin_component.dart', 'repo_id': 'flame', 'token_count': 1049} |
import 'package:flame/components.dart';
import 'package:flame/src/events/flame_game_mixins/has_tappables_bridge.dart';
import 'package:flame/src/game/mixins/has_tappables.dart';
import 'package:flame/src/gestures/events.dart';
import 'package:flutter/gestures.dart';
import 'package:meta/meta.dart';
/// Mixin that can be added to any [Component] allowing it to receive tap
/// events.
///
/// When using this mixin, also add [HasTappables] to your game, which handles
/// propagation of tap events from the root game to individual components.
///
/// See [MultiTapGestureRecognizer] for the description of each individual
/// event.
mixin Tappable on Component {
// bool onTap() => true;
bool onTapDown(TapDownInfo info) => true;
bool onLongTapDown(TapDownInfo info) => true;
bool onTapUp(TapUpInfo info) => true;
bool onTapCancel() => true;
int? _currentPointerId;
bool _checkPointerId(int pointerId) => _currentPointerId == pointerId;
bool handleTapDown(int pointerId, TapDownInfo info) {
if (containsPoint(eventPosition(info))) {
_currentPointerId = pointerId;
return onTapDown(info);
}
return true;
}
bool handleTapUp(int pointerId, TapUpInfo info) {
if (_checkPointerId(pointerId) && containsPoint(eventPosition(info))) {
_currentPointerId = null;
return onTapUp(info);
}
return true;
}
bool handleTapCancel(int pointerId) {
if (_checkPointerId(pointerId)) {
_currentPointerId = null;
return onTapCancel();
}
return true;
}
bool handleLongTapDown(int pointerId, TapDownInfo info) {
if (_checkPointerId(pointerId) && containsPoint(eventPosition(info))) {
return onLongTapDown(info);
}
return true;
}
@override
@mustCallSuper
void onMount() {
super.onMount();
final game = findGame()!;
assert(
game is HasTappables || game is HasTappablesBridge,
'Tappable components can only be added to a FlameGame with HasTappables',
);
}
}
| flame/packages/flame/lib/src/components/mixins/tappable.dart/0 | {'file_path': 'flame/packages/flame/lib/src/components/mixins/tappable.dart', 'repo_id': 'flame', 'token_count': 703} |
import 'package:flame/src/anchor.dart';
import 'package:flame/src/effects/anchor_by_effect.dart';
import 'package:flame/src/effects/anchor_to_effect.dart';
import 'package:flame/src/effects/controllers/effect_controller.dart';
import 'package:flame/src/effects/effect.dart';
import 'package:flame/src/effects/effect_target.dart';
import 'package:flame/src/effects/measurable_effect.dart';
import 'package:flame/src/effects/provider_interfaces.dart';
import 'package:vector_math/vector_math_64.dart';
/// Base class for effects that affect the `anchor` of their targets.
///
/// The main purpose of this class is for type reflection, for example to select
/// all effects on the target that are of "anchor" type.
///
/// Factory constructors [AnchorEffect.by] and [AnchorEffect.to] are also
/// provided for convenience.
abstract class AnchorEffect extends Effect
with EffectTarget<AnchorProvider>
implements MeasurableEffect {
AnchorEffect(
super.controller,
AnchorProvider? target, {
super.onComplete,
}) {
this.target = target;
}
factory AnchorEffect.by(
Vector2 offset,
EffectController controller, {
AnchorProvider? target,
void Function()? onComplete,
}) =>
AnchorByEffect(
offset,
controller,
target: target,
onComplete: onComplete,
);
factory AnchorEffect.to(
Anchor destination,
EffectController controller, {
AnchorProvider? target,
void Function()? onComplete,
}) =>
AnchorToEffect(
destination,
controller,
target: target,
onComplete: onComplete,
);
}
| flame/packages/flame/lib/src/effects/anchor_effect.dart/0 | {'file_path': 'flame/packages/flame/lib/src/effects/anchor_effect.dart', 'repo_id': 'flame', 'token_count': 570} |
import 'package:flame/src/effects/controllers/effect_controller.dart';
import 'package:flame/src/effects/effect.dart';
/// An effect controller that executes a list of other controllers one after
/// another.
class SequenceEffectController extends EffectController {
SequenceEffectController(List<EffectController> controllers)
: assert(controllers.isNotEmpty, 'List of controllers cannot be empty'),
assert(
!controllers.any((c) => c.isInfinite),
'Children controllers cannot be infinite',
),
children = controllers,
_currentIndex = 0,
super.empty();
/// Individual controllers in the sequence.
final List<EffectController> children;
/// The index of the controller currently being executed. This starts with 0,
/// and by the end it will be equal to `_children.length - 1`. This variable
/// is always a valid index within the `_children` list.
int _currentIndex;
@override
bool get completed {
return _currentIndex == children.length - 1 &&
children[_currentIndex].completed;
}
@override
double? get duration {
var totalDuration = 0.0;
for (final controller in children) {
final d = controller.duration;
if (d == null) {
return null;
}
totalDuration += d;
}
return totalDuration;
}
@override
bool get isRandom => children.any((c) => c.isRandom);
@override
double get progress => children[_currentIndex].progress;
@override
double advance(double dt) {
var t = children[_currentIndex].advance(dt);
while (t > 0 && _currentIndex < children.length - 1) {
_currentIndex++;
t = children[_currentIndex].advance(t);
}
return t;
}
@override
double recede(double dt) {
var t = children[_currentIndex].recede(dt);
while (t > 0 && _currentIndex > 0) {
_currentIndex--;
t = children[_currentIndex].recede(t);
}
return t;
}
@override
void setToStart() {
_currentIndex = 0;
children.forEach((c) => c.setToStart());
}
@override
void setToEnd() {
_currentIndex = children.length - 1;
children.forEach((c) => c.setToEnd());
}
@override
void onMount(Effect parent) => children.forEach((c) => c.onMount(parent));
}
| flame/packages/flame/lib/src/effects/controllers/sequence_effect_controller.dart/0 | {'file_path': 'flame/packages/flame/lib/src/effects/controllers/sequence_effect_controller.dart', 'repo_id': 'flame', 'token_count': 792} |
import 'package:flame/src/effects/controllers/effect_controller.dart';
import 'package:flame/src/effects/controllers/infinite_effect_controller.dart';
import 'package:flame/src/effects/controllers/repeated_effect_controller.dart';
import 'package:flame/src/effects/effect.dart';
/// Run multiple effects in a sequence, one after another.
///
/// The provided effects will be added as child components; however the custom
/// `updateTree()` implementation ensures that only one of them runs at any
/// point in time. The flags `paused` or `removeOnFinish` will be ignored for
/// children effects.
///
/// If the `alternate` flag is provided, then the sequence will run in the
/// reverse after it ran forward.
///
/// Parameter `repeatCount` will make the sequence repeat a certain number of
/// times. If `alternate` is also true, then the sequence will first run
/// forward, then back, and then repeat this pattern `repeatCount` times in
/// total.
///
/// The flag `infinite = true` makes the sequence repeat infinitely. This is
/// equivalent to setting `repeatCount = infinity`. If both the `infinite` and
/// the `repeatCount` parameters are given, then `infinite` takes precedence.
///
/// Note that unlike other effects, [SequenceEffect] does not take an
/// [EffectController] as a parameter. This is because the timing of a sequence
/// effect depends on the timings of individual effects, and cannot be
/// represented as a regular effect controller.
class SequenceEffect extends Effect {
factory SequenceEffect(
List<Effect> effects, {
bool alternate = false,
bool infinite = false,
int repeatCount = 1,
void Function()? onComplete,
}) {
assert(effects.isNotEmpty, 'The list of effects cannot be empty');
assert(
!(infinite && repeatCount != 1),
'Parameters infinite and repeatCount cannot be specified simultaneously',
);
EffectController ec = _SequenceEffectEffectController(effects, alternate);
if (infinite) {
ec = InfiniteEffectController(ec);
} else if (repeatCount > 1) {
ec = RepeatedEffectController(ec, repeatCount);
}
effects.forEach((e) => e.removeOnFinish = false);
return SequenceEffect._(ec, onComplete: onComplete)..addAll(effects);
}
SequenceEffect._(
super.ec, {
super.onComplete,
});
@override
void apply(double progress) {}
@override
void updateTree(double dt) {
update(dt);
// Do not update children: the controller will take care of it
}
}
/// Helper class that implements the functionality of a [SequenceEffect]. This
/// class should not be confused with `SequenceEffectController` (which runs
/// a sequence of effect controllers).
///
/// This effect controller does not strictly adheres to the interface of a
/// proper [EffectController]: in particular, its [progress] is ill-defined.
/// The provided implementation returns a value proportional to the number of
/// effects that has already completed, however this is not used anywhere since
/// `SequenceEffect.apply()` is empty.
class _SequenceEffectEffectController extends EffectController {
_SequenceEffectEffectController(
this.effects,
this.alternate,
) : super.empty();
/// The list of children effects.
final List<Effect> effects;
/// If this flag is true, then after the sequence runs to the end, it will
/// run again in the reverse order.
final bool alternate;
/// Index of the currently running effect within the [effects] list. If there
/// are n effects in total, then this runs as 0, 1, ..., n-1. After that, if
/// the effect alternates, then the `_index` continues as -1, -2, ..., -n,
/// where -1 is the last effect and -n is the first.
int _index = 0;
/// The effect that is currently being executed.
Effect get currentEffect => effects[_index < 0 ? _index + n : _index];
/// Total number of effects in this sequence.
int get n => effects.length;
@override
bool get completed => _completed;
bool _completed = false;
@override
double? get duration {
var totalDuration = 0.0;
for (final effect in effects) {
totalDuration += effect.controller.duration ?? 0;
}
if (alternate) {
totalDuration *= 2;
}
return totalDuration;
}
@override
bool get isRandom {
return effects.any((e) => e.controller.isRandom);
}
@override
double get progress => (_index + 1) / n;
@override
double advance(double dt) {
var t = dt;
for (;;) {
if (_index >= 0) {
t = currentEffect.advance(t);
if (t > 0) {
_index += 1;
if (_index == n) {
if (alternate) {
_index = -1;
} else {
_index = n - 1;
_completed = true;
break;
}
}
}
} else {
t = currentEffect.recede(t);
if (t > 0) {
_index -= 1;
if (_index < -n) {
_index = -n;
_completed = true;
break;
}
}
}
if (t == 0) {
break;
}
}
return t;
}
@override
double recede(double dt) {
if (_completed && dt > 0) {
_completed = false;
}
var t = dt;
for (;;) {
if (_index >= 0) {
t = currentEffect.recede(t);
if (t > 0) {
_index -= 1;
if (_index < 0) {
_index = 0;
break;
}
}
} else {
t = currentEffect.advance(t);
if (t > 0) {
_index += 1;
if (_index == 0) {
_index = n - 1;
}
}
}
if (t == 0) {
break;
}
}
return t;
}
@override
void setToEnd() {
if (alternate) {
_index = -n;
effects.forEach((e) => e.reset());
} else {
_index = n - 1;
effects.forEach((e) => e.resetToEnd());
}
_completed = true;
}
@override
void setToStart() {
_index = 0;
_completed = false;
effects.forEach((e) => e.reset());
}
}
| flame/packages/flame/lib/src/effects/sequence_effect.dart/0 | {'file_path': 'flame/packages/flame/lib/src/effects/sequence_effect.dart', 'repo_id': 'flame', 'token_count': 2235} |
import 'package:flame/extensions.dart';
import 'package:flame/src/events/messages/drag_end_event.dart';
import 'package:flame/src/events/messages/drag_update_event.dart';
import 'package:flame/src/events/messages/position_event.dart';
import 'package:flame/src/game/flame_game.dart';
import 'package:flame/src/gestures/events.dart';
import 'package:flutter/gestures.dart';
class DragStartEvent extends PositionEvent {
DragStartEvent(this.pointerId, DragStartDetails details)
: deviceKind = details.kind ?? PointerDeviceKind.unknown,
super(
canvasPosition: details.localPosition.toVector2(),
devicePosition: details.globalPosition.toVector2(),
);
/// The unique identifier of the drag event.
///
/// Subsequent [DragUpdateEvent] or [DragEndEvent] will carry the same pointer
/// id. This allows distinguishing multiple drags that may occur at the same
/// time on the same component.
final int pointerId;
final PointerDeviceKind deviceKind;
/// Converts this event into the legacy [DragStartInfo] representation.
DragStartInfo asInfo(FlameGame game) {
return DragStartInfo.fromDetails(
game,
DragStartDetails(
globalPosition: devicePosition.toOffset(),
localPosition: canvasPosition.toOffset(),
kind: deviceKind,
),
);
}
}
| flame/packages/flame/lib/src/events/messages/drag_start_event.dart/0 | {'file_path': 'flame/packages/flame/lib/src/events/messages/drag_start_event.dart', 'repo_id': 'flame', 'token_count': 444} |
import 'dart:math';
import 'dart:ui';
import 'package:flame/src/experimental/geometry/shapes/shape.dart';
import 'package:flame/src/game/transform2d.dart';
import 'package:vector_math/vector_math_64.dart';
/// An axis-aligned rectangle.
///
/// This is similar to ui's [Rect], except that this class is mutable and
/// conforms to the [Shape] API.
///
/// Unlike with [Rect], the [Rectangle] is always correctly oriented, in the
/// sense that its left edge is to the left from the right edge, and its top
/// edge is above the bottom edge.
///
/// The edges of a [Rectangle] can also coincide: the left edge can coincide
/// with the right edge, and the top side with the bottom.
class Rectangle extends Shape {
/// Constructs the [Rectangle] from left, top, right and bottom edges.
///
/// If the edges are given in the wrong order (e.g. `left` is to the right
/// from `right`), then they will be swapped.
Rectangle.fromLTRB(this._left, this._top, this._right, this._bottom) {
if (_left > _right) {
final tmp = _left;
_left = _right;
_right = tmp;
}
if (_top > _bottom) {
final tmp = _top;
_top = _bottom;
_bottom = tmp;
}
}
/// Constructs a [Rectangle] from two opposite corners. The points can be in
/// any disposition to each other.
factory Rectangle.fromPoints(Vector2 a, Vector2 b) =>
Rectangle.fromLTRB(a.x, a.y, b.x, b.y);
factory Rectangle.fromRect(Rect rect) =>
Rectangle.fromLTRB(rect.left, rect.top, rect.right, rect.bottom);
double _left;
double _top;
double _right;
double _bottom;
double get left => _left;
double get right => _right;
double get top => _top;
double get bottom => _bottom;
double get width => _right - _left;
double get height => _bottom - _top;
@override
Aabb2 get aabb => _aabb ??= _calculateAabb();
Aabb2? _aabb;
Aabb2 _calculateAabb() {
return Aabb2.minMax(Vector2(_left, _top), Vector2(_right, _bottom));
}
@override
bool get isConvex => true;
@override
Vector2 get center => Vector2((_left + _right) / 2, (_top + _bottom) / 2);
@override
double get perimeter => 2 * (width + height);
@override
Path asPath() {
return Path()..addRect(Rect.fromLTRB(_left, _top, _right, _bottom));
}
@override
bool containsPoint(Vector2 point) {
return point.x >= _left &&
point.y >= _top &&
point.x <= _right &&
point.y <= _bottom;
}
@override
Shape project(Transform2D transform, [Shape? target]) {
if (transform.isAxisAligned) {
final v1 = transform.localToGlobal(Vector2(_left, _top));
final v2 = transform.localToGlobal(Vector2(_right, _bottom));
final newLeft = min(v1.x, v2.x);
final newRight = max(v1.x, v2.x);
final newTop = min(v1.y, v2.y);
final newBottom = max(v1.y, v2.y);
if (target is Rectangle) {
target._left = newLeft;
target._right = newRight;
target._top = newTop;
target._bottom = newBottom;
target._aabb = null;
return target;
} else {
return Rectangle.fromLTRB(newLeft, newTop, newRight, newBottom);
}
}
throw UnimplementedError();
}
@override
void move(Vector2 offset) {
_left += offset.x;
_right += offset.x;
_top += offset.y;
_bottom += offset.y;
_aabb?.min.add(offset);
_aabb?.max.add(offset);
}
@override
Vector2 support(Vector2 direction) {
final vx = direction.x >= 0 ? _right : _left;
final vy = direction.y >= 0 ? _bottom : _top;
return Vector2(vx, vy);
}
@override
String toString() => 'Rectangle([$_left, $_top], [$_right, $_bottom])';
}
| flame/packages/flame/lib/src/experimental/geometry/shapes/rectangle.dart/0 | {'file_path': 'flame/packages/flame/lib/src/experimental/geometry/shapes/rectangle.dart', 'repo_id': 'flame', 'token_count': 1411} |
import 'dart:math';
import 'dart:ui';
import 'package:flame/src/extensions/vector2.dart';
export 'dart:ui' show Size;
extension SizeExtension on Size {
/// Creates an [Offset] from the [Size]
Offset toOffset() => Offset(width, height);
/// Creates a [Vector2] from the [Size]
Vector2 toVector2() => Vector2(width, height);
/// Creates a [Point] from the [Size]
Point toPoint() => Point(width, height);
/// Creates a [Rect] from the [Size]
Rect toRect() => Rect.fromLTWH(0, 0, width, height);
}
| flame/packages/flame/lib/src/extensions/size.dart/0 | {'file_path': 'flame/packages/flame/lib/src/extensions/size.dart', 'repo_id': 'flame', 'token_count': 181} |
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame/src/components/mixins/keyboard_handler.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// A [FlameGame] mixin that implements [KeyboardEvents] with keyboard event
/// propagation to components that are mixed with [KeyboardHandler].
///
/// Attention: should not be used alongside [KeyboardEvents] in a game subclass.
/// Using this mixin remove the necessity of [KeyboardEvents].
mixin HasKeyboardHandlerComponents on FlameGame implements KeyboardEvents {
@override
@mustCallSuper
KeyEventResult onKeyEvent(
RawKeyEvent event,
Set<LogicalKeyboardKey> keysPressed,
) {
final blockedPropagation = !propagateToChildren<KeyboardHandler>(
(KeyboardHandler child) => child.onKeyEvent(event, keysPressed),
);
// If any component received the event, return handled,
// otherwise, ignore it.
if (blockedPropagation) {
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
}
/// A [Game] mixin to make a game subclass sensitive to keyboard events.
///
/// Override [onKeyEvent] to customize the keyboard handling behavior.
mixin KeyboardEvents on Game {
KeyEventResult onKeyEvent(
RawKeyEvent event,
Set<LogicalKeyboardKey> keysPressed,
) {
assert(
this is! HasKeyboardHandlerComponents,
'A keyboard event was registered by KeyboardEvents for a game also '
'mixed with HasKeyboardHandlerComponents. Do not mix with both, '
'HasKeyboardHandlerComponents removes the necessity of KeyboardEvents',
);
return KeyEventResult.handled;
}
}
| flame/packages/flame/lib/src/game/mixins/keyboard.dart/0 | {'file_path': 'flame/packages/flame/lib/src/game/mixins/keyboard.dart', 'repo_id': 'flame', 'token_count': 523} |
import 'dart:ui';
abstract class LayerProcessor {
void process(Picture pic, Canvas canvas);
}
class ShadowProcessor extends LayerProcessor {
final Paint _shadowPaint;
final Offset offset;
ShadowProcessor({
this.offset = const Offset(10, 10),
double opacity = 0.9,
Color color = const Color(0xFF000000),
}) : _shadowPaint = Paint()
..colorFilter =
ColorFilter.mode(color.withOpacity(opacity), BlendMode.srcATop);
@override
void process(Picture pic, Canvas canvas) {
canvas.saveLayer(Rect.largest, _shadowPaint);
canvas.translate(offset.dx, offset.dy);
canvas.drawPicture(pic);
canvas.restore();
}
}
| flame/packages/flame/lib/src/layers/processors.dart/0 | {'file_path': 'flame/packages/flame/lib/src/layers/processors.dart', 'repo_id': 'flame', 'token_count': 244} |
import 'dart:ui';
import 'package:flame/src/components/mixins/single_child_particle.dart';
import 'package:flame/src/particles/curved_particle.dart';
import 'package:flame/src/particles/particle.dart';
/// A particle which rotates its child over the lifespan
/// between two given bounds in radians
class ScaledParticle extends CurvedParticle with SingleChildParticle {
@override
Particle child;
final double scale;
ScaledParticle({
required this.child,
this.scale = 1.0,
super.lifespan,
});
@override
void render(Canvas canvas) {
canvas.save();
canvas.scale(scale);
super.render(canvas);
canvas.restore();
}
}
| flame/packages/flame/lib/src/particles/scaled_particle.dart/0 | {'file_path': 'flame/packages/flame/lib/src/particles/scaled_particle.dart', 'repo_id': 'flame', 'token_count': 228} |
import 'dart:async';
import 'package:flame/cache.dart';
import 'package:flame/src/extensions/size.dart';
import 'package:flame/src/extensions/vector2.dart';
import 'package:flame/src/sprite.dart';
import 'package:flame/src/widgets/base_future_builder.dart';
import 'package:flutter/widgets.dart';
export '../sprite.dart';
/// A [StatelessWidget] that uses SpriteWidgets to render
/// a pressable button
class SpriteButton extends StatelessWidget {
/// Holds the position of the sprite on the image
final Vector2? srcPosition;
/// Holds the size of the sprite on the image
final Vector2? srcSize;
/// Holds the position of the sprite on the image
final Vector2? pressedSrcPosition;
/// Holds the size of the sprite on the image
final Vector2? pressedSrcSize;
final Widget label;
final VoidCallback onPressed;
final double width;
final double height;
/// A builder function that is called if the loading fails
final WidgetBuilder? errorBuilder;
/// A builder function that is called while the loading is on the way
final WidgetBuilder? loadingBuilder;
final FutureOr<List<Sprite>> _buttonsFuture;
SpriteButton({
required Sprite sprite,
required Sprite pressedSprite,
required this.onPressed,
required this.width,
required this.height,
required this.label,
this.srcPosition,
this.srcSize,
this.pressedSrcPosition,
this.pressedSrcSize,
super.key,
}) : _buttonsFuture = [
sprite,
pressedSprite,
],
errorBuilder = null,
loadingBuilder = null;
SpriteButton.future({
required Future<Sprite> sprite,
required Future<Sprite> pressedSprite,
required this.onPressed,
required this.width,
required this.height,
required this.label,
this.srcPosition,
this.srcSize,
this.pressedSrcPosition,
this.pressedSrcSize,
this.errorBuilder,
this.loadingBuilder,
super.key,
}) : _buttonsFuture = Future.wait([
sprite,
pressedSprite,
]);
/// Loads the images from the asset [path] and [pressedPath] and renders
/// it as a widget.
///
/// It will use the [loadingBuilder] while the image from [path] is loading.
/// To render without loading, or when you want to have a gapless playback
/// when the [path] value changes, consider loading the image beforehand
/// and direct pass it to the default constructor.
SpriteButton.asset({
required String path,
required String pressedPath,
required this.onPressed,
required this.width,
required this.height,
required this.label,
Images? images,
this.srcPosition,
this.srcSize,
this.pressedSrcPosition,
this.pressedSrcSize,
this.errorBuilder,
this.loadingBuilder,
super.key,
}) : _buttonsFuture = Future.wait([
Sprite.load(
path,
srcSize: srcSize,
srcPosition: srcPosition,
images: images,
),
Sprite.load(
pressedPath,
srcSize: pressedSrcSize,
srcPosition: pressedSrcPosition,
images: images,
),
]);
@override
Widget build(BuildContext context) {
return BaseFutureBuilder<List<Sprite>>(
future: _buttonsFuture,
builder: (_, list) {
final sprite = list[0];
final pressedSprite = list[1];
return InternalSpriteButton(
onPressed: onPressed,
label: label,
width: width,
height: height,
sprite: sprite,
pressedSprite: pressedSprite,
);
},
errorBuilder: errorBuilder,
loadingBuilder: loadingBuilder,
);
}
}
@visibleForTesting
class InternalSpriteButton extends StatefulWidget {
final VoidCallback onPressed;
final Widget label;
final Sprite sprite;
final Sprite pressedSprite;
final double width;
final double height;
const InternalSpriteButton({
required this.onPressed,
required this.label,
required this.sprite,
required this.pressedSprite,
this.width = 200,
this.height = 50,
super.key,
});
@override
State createState() => _ButtonState();
}
class _ButtonState extends State<InternalSpriteButton> {
bool _pressed = false;
@override
Widget build(_) {
final width = widget.width;
final height = widget.height;
return GestureDetector(
onTapDown: (_) {
setState(() => _pressed = true);
},
onTapUp: (_) {
setState(() => _pressed = false);
widget.onPressed.call();
},
child: Container(
width: width,
height: height,
child: CustomPaint(
painter:
_ButtonPainter(_pressed ? widget.pressedSprite : widget.sprite),
child: Center(
child: Container(
padding: _pressed ? const EdgeInsets.only(top: 5) : null,
child: widget.label,
),
),
),
),
);
}
}
class _ButtonPainter extends CustomPainter {
final Sprite _sprite;
_ButtonPainter(this._sprite);
@override
bool shouldRepaint(_ButtonPainter old) => old._sprite != _sprite;
@override
void paint(Canvas canvas, Size size) {
_sprite.render(canvas, size: size.toVector2());
}
}
| flame/packages/flame/lib/src/widgets/sprite_button.dart/0 | {'file_path': 'flame/packages/flame/lib/src/widgets/sprite_button.dart', 'repo_id': 'flame', 'token_count': 2037} |
import 'package:flame/cache.dart';
import 'package:test/test.dart';
void main() {
group('MemoryCache', () {
test('basic cache access', () {
final cache = MemoryCache<int, String>();
cache.setValue(0, 'bla');
expect(cache.getValue(0), 'bla');
});
test('containsKey', () {
final cache = MemoryCache<int, String>();
expect(cache.keys.length, 0);
cache.setValue(0, 'bla');
expect(cache.containsKey(0), true);
expect(cache.containsKey(1), false);
expect(cache.keys.length, 1);
});
test('cache size', () {
final cache = MemoryCache<int, String>(cacheSize: 1);
cache.setValue(0, 'bla');
cache.setValue(1, 'ble');
expect(cache.containsKey(0), false);
expect(cache.containsKey(1), true);
expect(cache.getValue(0), null);
expect(cache.getValue(1), 'ble');
expect(cache.size, 1);
});
});
}
| flame/packages/flame/test/cache/memory_cache_test.dart/0 | {'file_path': 'flame/packages/flame/test/cache/memory_cache_test.dart', 'repo_id': 'flame', 'token_count': 388} |
import 'package:flame/components.dart';
import 'package:flame/extensions.dart';
import 'package:flame/input.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import '../game/flame_game_test.dart';
void main() {
group('HudButtonComponent', () {
testWithGame<GameWithTappables>(
'correctly registers taps', GameWithTappables.new, (game) async {
var pressedTimes = 0;
var releasedTimes = 0;
final initialGameSize = Vector2.all(100);
final componentSize = Vector2.all(10);
const margin = EdgeInsets.only(bottom: 10, right: 10);
late final HudButtonComponent button;
game.onGameResize(initialGameSize);
await game.ensureAdd(
button = HudButtonComponent(
button: RectangleComponent(size: componentSize),
onPressed: () => pressedTimes++,
onReleased: () => releasedTimes++,
size: componentSize,
margin: margin,
),
);
expect(pressedTimes, 0);
expect(releasedTimes, 0);
game.onTapDown(1, createTapDownEvent(game));
expect(pressedTimes, 0);
expect(releasedTimes, 0);
game.onTapUp(
1,
createTapUpEvent(
game,
globalPosition: button.positionOfAnchor(Anchor.center).toOffset(),
),
);
expect(pressedTimes, 0);
expect(releasedTimes, 0);
game.onTapDown(
1,
createTapDownEvent(
game,
globalPosition: initialGameSize.toOffset() +
margin.bottomRight -
const Offset(1, 1),
),
);
expect(pressedTimes, 1);
expect(releasedTimes, 0);
game.onTapUp(
1,
createTapUpEvent(
game,
globalPosition: button.positionOfAnchor(Anchor.center).toOffset(),
),
);
expect(pressedTimes, 1);
expect(releasedTimes, 1);
});
testWithGame<GameWithTappables>(
'correctly registers taps onGameResize', GameWithTappables.new,
(game) async {
var pressedTimes = 0;
var releasedTimes = 0;
final initialGameSize = Vector2.all(100);
final componentSize = Vector2.all(10);
const margin = EdgeInsets.only(bottom: 10, right: 10);
late final HudButtonComponent button;
game.onGameResize(initialGameSize);
await game.ensureAdd(
button = HudButtonComponent(
button: RectangleComponent(size: componentSize),
onPressed: () => pressedTimes++,
onReleased: () => releasedTimes++,
size: componentSize,
margin: margin,
),
);
final previousPosition =
button.positionOfAnchor(Anchor.center).toOffset();
game.onGameResize(initialGameSize * 2);
game.onTapDown(
1,
createTapDownEvent(
game,
globalPosition: previousPosition,
),
);
game.onTapUp(
1,
createTapUpEvent(
game,
globalPosition: previousPosition,
),
);
expect(pressedTimes, 0);
expect(releasedTimes, 0);
game.onTapDown(
1,
createTapDownEvent(
game,
globalPosition:
game.size.toOffset() + margin.bottomRight - const Offset(1, 1),
),
);
expect(pressedTimes, 1);
expect(releasedTimes, 0);
game.onTapUp(
1,
createTapUpEvent(
game,
globalPosition:
game.size.toOffset() + margin.bottomRight - const Offset(1, 1),
),
);
expect(pressedTimes, 1);
expect(releasedTimes, 1);
});
});
}
| flame/packages/flame/test/components/hud_button_component_test.dart/0 | {'file_path': 'flame/packages/flame/test/components/hud_button_component_test.dart', 'repo_id': 'flame', 'token_count': 1691} |
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:test/test.dart';
enum _AnimationState {
idle,
running,
}
Future<void> main() async {
// Generate a image
final image = await generateImage();
group('SpriteAnimationGroupComponent', () {
test('returns the correct animation according to its state', () {
final animation1 = SpriteAnimation.spriteList(
[
Sprite(image),
Sprite(image),
],
stepTime: 1,
);
final animation2 = SpriteAnimation.spriteList(
[
Sprite(image),
Sprite(image),
],
stepTime: 1,
);
final component = SpriteAnimationGroupComponent<_AnimationState>(
animations: {
_AnimationState.idle: animation1,
_AnimationState.running: animation2,
},
);
// No state was specified so nothing is playing
expect(component.animation, null);
// Setting the idle state, we need to see the animation1
component.current = _AnimationState.idle;
expect(component.animation, animation1);
// Setting the running state, we need to see the animation2
component.current = _AnimationState.running;
expect(component.animation, animation2);
});
});
group('SpriteAnimationGroupComponent.shouldRemove', () {
flameGame.test('removeOnFinish is true and there is no any state yet',
(game) async {
final animation = SpriteAnimation.spriteList(
[
Sprite(image),
Sprite(image),
],
stepTime: 1,
loop: false,
);
final component = SpriteAnimationGroupComponent<_AnimationState>(
animations: {_AnimationState.idle: animation},
removeOnFinish: {_AnimationState.idle: true},
);
await game.ensureAdd(component);
expect(component.parent, game);
expect(game.children.length, 1);
game.update(2);
expect(component.parent, game);
// runs a cycle and the component should still be there
game.update(0.1);
expect(game.children.length, 1);
});
flameGame.test(
'removeOnFinish is true and current state animation#loop is false',
(game) async {
final animation = SpriteAnimation.spriteList(
[
Sprite(image),
Sprite(image),
],
stepTime: 1,
loop: false,
);
final component = SpriteAnimationGroupComponent<_AnimationState>(
animations: {_AnimationState.idle: animation},
removeOnFinish: {_AnimationState.idle: true},
current: _AnimationState.idle,
);
await game.ensureAdd(component);
expect(game.children.length, 1);
game.update(2);
// runs a cycle to remove the component
game.update(0.1);
expect(game.children.length, 0);
},
);
flameGame.test('removeOnFinish is true and current animation#loop is true',
(game) async {
final animation = SpriteAnimation.spriteList(
[
Sprite(image),
Sprite(image),
],
stepTime: 1,
// ignore: avoid_redundant_argument_values
loop: true,
);
final component = SpriteAnimationGroupComponent<_AnimationState>(
animations: {_AnimationState.idle: animation},
removeOnFinish: {_AnimationState.idle: true},
current: _AnimationState.idle,
);
await game.ensureAdd(component);
expect(component.parent, game);
expect(game.children.length, 1);
game.update(2);
expect(component.parent, game);
// runs a cycle to remove the component, but failed
game.update(0.1);
expect(game.children.length, 1);
});
flameGame
.test('removeOnFinish is false and current animation#loop is false',
(game) async {
final animation = SpriteAnimation.spriteList(
[
Sprite(image),
Sprite(image),
],
stepTime: 1,
loop: false,
);
final component = SpriteAnimationGroupComponent<_AnimationState>(
animations: {_AnimationState.idle: animation},
current: _AnimationState.idle,
// when omitted, removeOnFinish is false for all states
);
await game.ensureAdd(component);
expect(component.parent, game);
expect(game.children.length, 1);
game.update(2);
expect(component.parent, game);
// runs a cycle to remove the component, but failed
game.update(0.1);
expect(game.children.length, 1);
});
flameGame.test('removeOnFinish is false and current animation#loop is true',
(game) async {
final animation = SpriteAnimation.spriteList(
[
Sprite(image),
Sprite(image),
],
stepTime: 1,
// ignore: avoid_redundant_argument_values
loop: true,
);
final component = SpriteAnimationGroupComponent<_AnimationState>(
animations: {_AnimationState.idle: animation},
// when omitted, removeOnFinish is false for all states
current: _AnimationState.idle,
);
await game.ensureAdd(component);
expect(component.parent, game);
expect(game.children.length, 1);
game.update(2);
expect(component.parent, game);
// runs a cycle to remove the component, but failed
game.update(0.1);
expect(game.children.length, 1);
});
});
}
| flame/packages/flame/test/components/sprite_animation_group_component_test.dart/0 | {'file_path': 'flame/packages/flame/test/components/sprite_animation_group_component_test.dart', 'repo_id': 'flame', 'token_count': 2256} |
import 'package:flame/src/effects/controllers/infinite_effect_controller.dart';
import 'package:flame/src/effects/controllers/linear_effect_controller.dart';
import 'package:flame/src/effects/controllers/repeated_effect_controller.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('RepeatedEffectController', () {
test('basic properties', () {
final ec = RepeatedEffectController(LinearEffectController(1), 5);
expect(ec.isInfinite, false);
expect(ec.isRandom, false);
expect(ec.started, true);
expect(ec.completed, false);
expect(ec.duration, 5);
expect(ec.progress, 0);
expect(ec.repeatCount, 5);
expect(ec.remainingIterationsCount, 5);
});
test('reset', () {
final ec = RepeatedEffectController(LinearEffectController(1), 5);
ec.setToEnd();
expect(ec.started, true);
expect(ec.completed, true);
expect(ec.child.completed, true);
expect(ec.progress, 1);
expect(ec.remainingIterationsCount, 0);
ec.setToStart();
expect(ec.started, true);
expect(ec.completed, false);
expect(ec.child.completed, false);
expect(ec.progress, 0);
expect(ec.remainingIterationsCount, 5);
});
test('advance', () {
final ec = RepeatedEffectController(LinearEffectController(2), 5);
expect(ec.remainingIterationsCount, 5);
// First iteration
expect(ec.advance(1), 0);
expect(ec.progress, 0.5);
expect(ec.remainingIterationsCount, 5);
expect(ec.advance(1), 0);
expect(ec.progress, 1);
expect(ec.remainingIterationsCount, 5);
// Second iteration
expect(ec.advance(1), 0);
expect(ec.progress, 0.5);
expect(ec.remainingIterationsCount, 4);
expect(ec.advance(1), 0);
expect(ec.progress, 1);
expect(ec.remainingIterationsCount, 4);
// Third iteration
expect(ec.advance(1), 0);
expect(ec.progress, 0.5);
expect(ec.remainingIterationsCount, 3);
expect(ec.advance(1), 0);
expect(ec.progress, 1);
expect(ec.remainingIterationsCount, 3);
// Forth iteration
expect(ec.advance(1), 0);
expect(ec.progress, 0.5);
expect(ec.remainingIterationsCount, 2);
expect(ec.advance(1), 0);
expect(ec.progress, 1);
expect(ec.remainingIterationsCount, 2);
// Fifth iteration
expect(ec.advance(1), 0);
expect(ec.progress, 0.5);
expect(ec.remainingIterationsCount, 1);
expect(ec.advance(1), 0);
expect(ec.progress, 1);
// last iteration is consumed immediately
expect(ec.remainingIterationsCount, 0);
expect(ec.completed, true);
// Any subsequent time will be spilled over
expect(ec.advance(1), 1);
expect(ec.progress, 1);
expect(ec.completed, true);
});
test('advance 2', () {
const n = 5;
const dt = 0.17;
final nIterations = (n / dt).floor();
final ec = RepeatedEffectController(LinearEffectController(1), n);
for (var i = 0; i < nIterations; i++) {
expect(ec.advance(dt), 0);
expect(ec.progress, closeTo((i + 1) * dt % 1, 1e-15));
}
expect(ec.advance(dt), closeTo((nIterations + 1) * dt - n, 1e-15));
expect(ec.completed, true);
expect(ec.progress, 1);
});
test('recede', () {
final ec = RepeatedEffectController(LinearEffectController(2), 5);
ec.setToEnd();
expect(ec.completed, true);
expect(ec.recede(0), 0);
expect(ec.completed, true);
expect(ec.remainingIterationsCount, 0);
// Fifth iteration
expect(ec.recede(1), 0);
expect(ec.progress, 0.5);
expect(ec.completed, false);
expect(ec.remainingIterationsCount, 1);
expect(ec.recede(1), 0);
expect(ec.progress, 0);
expect(ec.remainingIterationsCount, 1);
// Forth iteration
expect(ec.recede(1), 0);
expect(ec.progress, 0.5);
expect(ec.remainingIterationsCount, 2);
expect(ec.recede(1), 0);
expect(ec.progress, 0);
expect(ec.remainingIterationsCount, 2);
// Third iteration
expect(ec.recede(1), 0);
expect(ec.progress, 0.5);
expect(ec.remainingIterationsCount, 3);
expect(ec.recede(1), 0);
expect(ec.progress, 0);
expect(ec.remainingIterationsCount, 3);
// Second iteration
expect(ec.recede(1), 0);
expect(ec.progress, 0.5);
expect(ec.remainingIterationsCount, 4);
expect(ec.recede(1), 0);
expect(ec.progress, 0);
expect(ec.remainingIterationsCount, 4);
// First iteration
expect(ec.recede(1), 0);
expect(ec.progress, 0.5);
expect(ec.remainingIterationsCount, 5);
expect(ec.recede(1), 0);
expect(ec.progress, 0);
expect(ec.remainingIterationsCount, 5);
expect(ec.started, true);
// Extra iterations
expect(ec.recede(1), 1);
expect(ec.progress, 0);
expect(ec.remainingIterationsCount, 5);
});
test('errors', () {
final ec = LinearEffectController(1);
expect(
() => RepeatedEffectController(InfiniteEffectController(ec), 1),
failsAssert('child cannot be infinite'),
);
expect(
() => RepeatedEffectController(ec, 0),
failsAssert('repeatCount must be positive'),
);
});
});
}
| flame/packages/flame/test/effects/controllers/repeated_effect_controller_test.dart/0 | {'file_path': 'flame/packages/flame/test/effects/controllers/repeated_effect_controller_test.dart', 'repo_id': 'flame', 'token_count': 2321} |
import 'package:flame/components.dart';
import 'package:flame/events.dart';
import 'package:flame/experimental.dart';
import 'package:flame/game.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('HasDraggableComponents', () {
testWidgets(
'drags are delivered to DragCallbacks components',
(tester) async {
var nDragStartCalled = 0;
var nDragUpdateCalled = 0;
var nDragEndCalled = 0;
final game = _GameWithHasDraggableComponents(
children: [
_DragCallbacksComponent(
position: Vector2(20, 20),
size: Vector2(100, 100),
onDragStart: (e) => nDragStartCalled++,
onDragUpdate: (e) => nDragUpdateCalled++,
onDragEnd: (e) => nDragEndCalled++,
)
],
);
await tester.pumpWidget(GameWidget(game: game));
await tester.pump();
await tester.pump(const Duration(milliseconds: 10));
expect(game.children.length, 1);
// regular drag
await tester.timedDragFrom(
const Offset(50, 50),
const Offset(20, 0),
const Duration(milliseconds: 100),
);
expect(nDragStartCalled, 1);
expect(nDragUpdateCalled, 8);
expect(nDragEndCalled, 1);
// cancelled drag
final gesture = await tester.startGesture(const Offset(50, 50));
await gesture.moveBy(const Offset(10, 10));
await gesture.cancel();
await tester.pump(const Duration(seconds: 1));
expect(nDragStartCalled, 2);
expect(nDragEndCalled, 2);
},
);
testWidgets(
'drag event does not affect more than one component',
(tester) async {
var nEvents = 0;
final game = _GameWithHasDraggableComponents(
children: [
_DragCallbacksComponent(
size: Vector2.all(100),
onDragStart: (e) => nEvents++,
onDragUpdate: (e) => nEvents++,
onDragEnd: (e) => nEvents++,
),
_SimpleDragCallbacksComponent(size: Vector2.all(200)),
],
);
await tester.pumpWidget(GameWidget(game: game));
await tester.pump();
await tester.pump();
expect(game.children.length, 2);
await tester.timedDragFrom(
const Offset(20, 20),
const Offset(5, 5),
const Duration(seconds: 1),
);
expect(nEvents, 0);
},
);
testWidgets(
'drag event can move outside the component bounds',
(tester) async {
final points = <Vector2>[];
final game = _GameWithHasDraggableComponents(
children: [
_DragCallbacksComponent(
size: Vector2.all(95),
position: Vector2.all(5),
onDragUpdate: (e) => points.add(e.localPosition),
),
],
);
await tester.pumpWidget(GameWidget(game: game));
await tester.pump();
await tester.pump();
expect(game.children.length, 1);
await tester.timedDragFrom(
const Offset(80, 80),
const Offset(0, 40),
const Duration(seconds: 1),
frequency: 40,
);
expect(points.length, 42);
expect(points.first, Vector2(75, 75));
expect(
points.skip(1).take(20),
List.generate(20, (i) => Vector2(75.0, 75.0 + i)),
);
expect(
points.skip(21),
everyElement(predicate((Vector2 v) => v.isNaN)),
);
},
);
testWidgets(
'game with Draggables',
(tester) async {
var nDragCallbackUpdates = 0;
var nDraggableUpdates = 0;
final game = _GameWithDualDraggableComponents(
children: [
_DragCallbacksComponent(
size: Vector2.all(100),
onDragStart: (e) => e.continuePropagation = true,
onDragUpdate: (e) => nDragCallbackUpdates++,
),
_DraggableComponent(
size: Vector2.all(100),
onDragStart: (e) => true,
onDragUpdate: (e) {
nDraggableUpdates++;
return true;
},
),
],
);
await tester.pumpWidget(GameWidget(game: game));
await tester.pump();
await tester.pump();
expect(game.children.length, 2);
await tester.timedDragFrom(
const Offset(50, 50),
const Offset(-20, 20),
const Duration(seconds: 1),
);
expect(nDragCallbackUpdates, 62);
expect(nDraggableUpdates, 62);
},
);
});
}
class _GameWithHasDraggableComponents extends FlameGame
with HasDraggableComponents {
_GameWithHasDraggableComponents({super.children});
}
class _GameWithDualDraggableComponents extends FlameGame
with HasDraggableComponents, HasDraggablesBridge {
_GameWithDualDraggableComponents({super.children});
}
class _DragCallbacksComponent extends PositionComponent with DragCallbacks {
_DragCallbacksComponent({
void Function(DragStartEvent)? onDragStart,
void Function(DragUpdateEvent)? onDragUpdate,
void Function(DragEndEvent)? onDragEnd,
super.position,
super.size,
}) : _onDragStart = onDragStart,
_onDragUpdate = onDragUpdate,
_onDragEnd = onDragEnd;
final void Function(DragStartEvent)? _onDragStart;
final void Function(DragUpdateEvent)? _onDragUpdate;
final void Function(DragEndEvent)? _onDragEnd;
@override
void onDragStart(DragStartEvent event) => _onDragStart?.call(event);
@override
void onDragUpdate(DragUpdateEvent event) => _onDragUpdate?.call(event);
@override
void onDragEnd(DragEndEvent event) => _onDragEnd?.call(event);
}
class _SimpleDragCallbacksComponent extends PositionComponent
with DragCallbacks {
_SimpleDragCallbacksComponent({super.size});
}
class _DraggableComponent extends PositionComponent with Draggable {
_DraggableComponent({
super.size,
bool Function(DragStartInfo)? onDragStart,
bool Function(DragUpdateInfo)? onDragUpdate,
bool Function(DragEndInfo)? onDragEnd,
}) : _onDragStart = onDragStart,
_onDragUpdate = onDragUpdate,
_onDragEnd = onDragEnd;
final bool Function(DragStartInfo)? _onDragStart;
final bool Function(DragUpdateInfo)? _onDragUpdate;
final bool Function(DragEndInfo)? _onDragEnd;
@override
bool onDragStart(DragStartInfo info) => _onDragStart?.call(info) ?? true;
@override
bool onDragUpdate(DragUpdateInfo info) => _onDragUpdate?.call(info) ?? true;
@override
bool onDragEnd(DragEndInfo info) => _onDragEnd?.call(info) ?? true;
}
| flame/packages/flame/test/events/flame_game_mixins/has_draggable_components_test.dart/0 | {'file_path': 'flame/packages/flame/test/events/flame_game_mixins/has_draggable_components_test.dart', 'repo_id': 'flame', 'token_count': 3032} |
import 'dart:math' as math;
import 'package:flame/extensions.dart';
import 'package:flame_test/flame_test.dart';
import 'package:test/test.dart';
void main() {
group('Rect test', () {
test('test from ui Rect to math Rectangle', () {
const r1 = Rect.fromLTWH(0, 10, 20, 30);
final r2 = r1.toMathRectangle();
expect(r2.top, r1.top);
expect(r2.bottom, r1.bottom);
expect(r2.left, r1.left);
expect(r2.right, r1.right);
expect(r2.width, r1.width);
expect(r2.height, r1.height);
});
test('test from math Rectangle to ui Rect', () {
const r1 = math.Rectangle(0, 10, 20, 30);
final r2 = r1.toRect();
expect(r2.top, r1.top);
expect(r2.bottom, r1.bottom);
expect(r2.left, r1.left);
expect(r2.right, r1.right);
expect(r2.width, r1.width);
expect(r2.height, r1.height);
});
test('test from ui Rect to RectangleComponent', () {
const r1 = Rect.fromLTWH(0, 10, 20, 30);
final r2 = r1.toRectangleComponent();
expect(r2.angle, 0);
expect(r2.position.x, r1.left);
expect(r2.position.y, r1.top);
expect(r2.size.x, r1.width);
expect(r2.size.y, r1.height);
});
test('test transform', () {
final matrix4 = Matrix4.translation(Vector3(10, 10, 0));
const input = Rect.fromLTWH(0, 0, 10, 10);
final result = input.transform(matrix4);
expect(result.topLeft.toVector2(), closeToVector(10, 10));
expect(result.bottomRight.toVector2(), closeToVector(20, 20));
});
});
}
| flame/packages/flame/test/extensions/rect_test.dart/0 | {'file_path': 'flame/packages/flame/test/extensions/rect_test.dart', 'repo_id': 'flame', 'token_count': 706} |
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class _ValidGame extends FlameGame with KeyboardEvents {}
class _InvalidGame extends FlameGame
with HasKeyboardHandlerComponents, KeyboardEvents {}
class _MockRawKeyEventData extends Mock implements RawKeyEventData {
@override
String toString({DiagnosticLevel minLevel = DiagnosticLevel.debug}) {
return super.toString();
}
}
void main() {
group('Keyboard events', () {
test(
'game with KeyboardEvents can handle key events',
() {
final validGame = _ValidGame();
final event = RawKeyDownEvent(data: _MockRawKeyEventData());
// Should just work with the default implementation
expect(
validGame.onKeyEvent(event, {}),
KeyEventResult.handled,
);
},
);
test(
'cannot mix KeyboardEvent and HasKeyboardHandlerComponents together',
() {
final invalidGame = _InvalidGame();
final event = RawKeyDownEvent(data: _MockRawKeyEventData());
// Should throw an assertion error
expect(
() => invalidGame.onKeyEvent(event, {}),
throwsA(isA<AssertionError>()),
);
},
);
});
}
| flame/packages/flame/test/game/mixins/keyboard_test.dart/0 | {'file_path': 'flame/packages/flame/test/game/mixins/keyboard_test.dart', 'repo_id': 'flame', 'token_count': 524} |
import 'package:flutter/cupertino.dart';
class LoadingWidget extends StatelessWidget {
const LoadingWidget({super.key});
@override
Widget build(BuildContext context) {
return const SizedBox();
}
}
| flame/packages/flame/test/widgets/loading_widget.dart/0 | {'file_path': 'flame/packages/flame/test/widgets/loading_widget.dart', 'repo_id': 'flame', 'token_count': 66} |
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_bloc_example/src/game/components/bullet.dart';
import 'package:flame_bloc_example/src/game/components/enemy.dart';
import 'package:flame_bloc_example/src/game/components/explosion.dart';
import 'package:flame_bloc_example/src/game/game.dart';
import 'package:flame_bloc_example/src/game_stats/bloc/game_stats_bloc.dart';
import 'package:flame_bloc_example/src/inventory/bloc/inventory_bloc.dart';
import 'package:flutter/services.dart';
class PlayerController extends Component
with
HasGameRef<SpaceShooterGame>,
FlameBlocListenable<GameStatsBloc, GameStatsState> {
@override
bool listenWhen(GameStatsState previousState, GameStatsState newState) {
return previousState.status != newState.status;
}
@override
void onNewState(GameStatsState state) {
if (state.status == GameStatus.respawn ||
state.status == GameStatus.initial) {
gameRef.statsBloc.add(const PlayerRespawned());
parent?.add(gameRef.player = PlayerComponent());
}
}
}
class PlayerComponent extends SpriteAnimationComponent
with
HasGameRef<SpaceShooterGame>,
CollisionCallbacks,
KeyboardHandler,
FlameBlocListenable<InventoryBloc, InventoryState> {
bool destroyed = false;
late Timer bulletCreator;
PlayerComponent()
: super(size: Vector2(50, 75), position: Vector2(100, 500)) {
bulletCreator = Timer(0.5, repeat: true, onTick: _createBullet);
add(RectangleHitbox());
}
@override
Future<void> onLoad() async {
await super.onLoad();
animation = await gameRef.loadSpriteAnimation(
'player.png',
SpriteAnimationData.sequenced(
stepTime: 0.2,
amount: 4,
textureSize: Vector2(32, 48),
),
);
}
InventoryState? state;
@override
void onNewState(InventoryState state) {
this.state = state;
}
void _createBullet() {
final bulletX = x + 20;
final bulletY = y + 20;
gameRef.add(
BulletComponent(
bulletX,
bulletY,
state?.weapon ?? Weapon.bullet,
),
);
}
void beginFire() {
bulletCreator.start();
}
void stopFire() {
bulletCreator.stop();
}
void move(double deltaX, double deltaY) {
x += deltaX;
y += deltaY;
}
@override
void update(double dt) {
super.update(dt);
bulletCreator.update(dt);
if (destroyed) {
removeFromParent();
}
}
void takeHit() {
gameRef.add(ExplosionComponent(x, y));
removeFromParent();
gameRef.statsBloc.add(const PlayerDied());
}
@override
bool onKeyEvent(
RawKeyEvent event,
Set<LogicalKeyboardKey> keysPressed,
) {
if (keysPressed.contains(LogicalKeyboardKey.tab)) {
gameRef.inventoryBloc.add(const NextWeaponEquipped());
return true;
}
return false;
}
@override
void onCollision(Set<Vector2> points, PositionComponent other) {
super.onCollision(points, other);
if (other is EnemyComponent) {
takeHit();
other.takeHit();
}
}
}
| flame/packages/flame_bloc/example/lib/src/game/components/player.dart/0 | {'file_path': 'flame/packages/flame_bloc/example/lib/src/game/components/player.dart', 'repo_id': 'flame', 'token_count': 1226} |
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flutter/material.dart';
/// Adds [Bloc] access to a [Component].
///
/// Useful for components that needs to only read
/// a bloc current state or to trigger an event on it
mixin FlameBlocReader<B extends BlocBase<S>, S> on Component {
late B _bloc;
/// Returns the bloc that this component is reading from
B get bloc => _bloc;
@override
@mustCallSuper
Future<void> onLoad() async {
final providers = ancestors().whereType<FlameBlocProvider<B, S>>();
assert(
providers.isNotEmpty,
'No FlameBlocProvider<$B, $S> available on the component tree',
);
final provider = providers.first;
_bloc = provider.bloc;
}
}
| flame/packages/flame_bloc/lib/src/flame_bloc_reader.dart/0 | {'file_path': 'flame/packages/flame_bloc/lib/src/flame_bloc_reader.dart', 'repo_id': 'flame', 'token_count': 280} |
import 'package:flame/components.dart';
import 'package:flame/extensions.dart';
import 'package:flame/game.dart';
import 'package:flame_forge2d/body_component.dart';
extension Forge2DCameraExtension on Camera {
/// Immediately snaps the camera to start following the [BodyComponent].
///
/// This means that the camera will move so that the position vector of the
/// component is in a fixed position on the screen.
/// That position is determined by a fraction of screen size defined by
/// [relativeOffset] (default to the center).
/// [worldBounds] can be optionally set to add boundaries to how far the
/// camera is allowed to move.
/// The component is "grabbed" by its anchor (default top left).
/// So for example if you want the center of the object to be at the fixed
/// position, set the components anchor to center.
void followBodyComponent(
BodyComponent bodyComponent, {
Anchor relativeOffset = Anchor.center,
Rect? worldBounds,
}) {
followVector2(
bodyComponent.body.position,
relativeOffset: relativeOffset,
worldBounds: worldBounds,
);
}
}
| flame/packages/flame_forge2d/lib/forge2d_camera.dart/0 | {'file_path': 'flame/packages/flame_forge2d/lib/forge2d_camera.dart', 'repo_id': 'flame', 'token_count': 324} |
export 'component/anchor_component.dart';
export 'component/angle_component.dart';
export 'component/flip_component.dart';
export 'component/particle_component.dart';
export 'component/position_component.dart';
export 'component/size_component.dart';
export 'component/sprite_component.dart';
export 'component/text_component.dart';
| flame/packages/flame_oxygen/lib/src/component.dart/0 | {'file_path': 'flame/packages/flame_oxygen/lib/src/component.dart', 'repo_id': 'flame', 'token_count': 100} |
import 'package:flame/extensions.dart';
import 'package:flame_oxygen/src/flame_world.dart';
import 'package:oxygen/oxygen.dart';
/// Allow a [System] to be part of the render loop from Flame.
mixin RenderSystem on System {
/// The world this system belongs to.
@override
FlameWorld? get world => super.world as FlameWorld?;
/// Implement this method to render the current game state in the [canvas].
void render(Canvas canvas);
@override
void execute(double delta) {
throw Exception('RenderSystem.execute is not supported in flame_oxygen');
}
}
| flame/packages/flame_oxygen/lib/src/system/render_system.dart/0 | {'file_path': 'flame/packages/flame_oxygen/lib/src/system/render_system.dart', 'repo_id': 'flame', 'token_count': 169} |
export 'src/rive_component.dart';
| flame/packages/flame_rive/lib/flame_rive.dart/0 | {'file_path': 'flame/packages/flame_rive/lib/flame_rive.dart', 'repo_id': 'flame', 'token_count': 12} |
library flame_svg;
export './svg.dart';
export './svg_component.dart';
| flame/packages/flame_svg/lib/flame_svg.dart/0 | {'file_path': 'flame/packages/flame_svg/lib/flame_svg.dart', 'repo_id': 'flame', 'token_count': 30} |
name: flame_test_example
description: Example of how to test with the flame_test package
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.17.0 <3.0.0"
dependencies:
flame: ^1.2.0
flutter:
sdk: flutter
dev_dependencies:
flame_lint: ^0.0.1
flame_test: ^1.5.0
flutter:
assets:
- assets/images/
| flame/packages/flame_test/example/pubspec.yaml/0 | {'file_path': 'flame/packages/flame_test/example/pubspec.yaml', 'repo_id': 'flame', 'token_count': 144} |
import 'package:flame_test/src/close_to_aabb.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:vector_math/vector_math_64.dart';
void main() {
group('closeToAabb', () {
test('zero aabb', () {
expect(Aabb2(), closeToAabb(Aabb2()));
expect(
Aabb2(),
closeToAabb(Aabb2.minMax(Vector2.all(1e-5), Vector2.all(1e-4)), 1e-3),
);
});
test('matches normally', () {
final aabb = Aabb2.minMax(Vector2.zero(), Vector2.all(1));
expect(aabb, closeToAabb(aabb));
expect(aabb, closeToAabb(Aabb2(), 2));
expect(
aabb,
closeToAabb(Aabb2.minMax(Vector2.all(1e-16), Vector2.all(1))),
);
});
test('fails on type mismatch', () {
try {
expect(3.14, closeToAabb(Aabb2()));
} on TestFailure catch (e) {
expect(
e.message,
contains(
'Expected: an Aabb2 object within 1e-15 of '
'Aabb2([0.0, 0.0]..[0.0, 0.0])',
),
);
expect(e.message, contains('Actual: <3.14>'));
expect(e.message, contains('Which: is not an instance of Aabb2'));
}
});
test('fails on value mismatch', () {
try {
expect(
Aabb2.minMax(Vector2.zero(), Vector2.all(1)),
closeToAabb(Aabb2(), 0.01),
);
} on TestFailure catch (e) {
expect(
e.message,
contains(
'Expected: an Aabb2 object within 0.01 of '
'Aabb2([0.0, 0.0]..[0.0, 0.0])',
),
);
expect(e.message, contains("Actual: <Instance of 'Aabb2'>"));
expect(e.message, contains('Which: max corner is at distance 1.4142'));
expect(e.message, contains('Aabb2([0.0, 0.0]..[1.0, 1.0])'));
}
});
});
}
| flame/packages/flame_test/test/close_to_aabb_test.dart/0 | {'file_path': 'flame/packages/flame_test/test/close_to_aabb_test.dart', 'repo_id': 'flame', 'token_count': 925} |
import 'dart:math';
import 'package:example/entities/circle/behaviors/behaviors.dart';
import 'package:example/entities/entities.dart';
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame_behaviors/flame_behaviors.dart';
import 'package:flutter/material.dart';
class Circle extends PositionedEntity with HasPaint {
Circle({
required double rotationSpeed,
required Vector2 velocity,
super.position,
super.size,
}) : super(
anchor: Anchor.center,
behaviors: [
PropagatingCollisionBehavior(CircleHitbox()),
CircleCollisionBehavior(),
RectangleCollisionBehavior(),
ScreenCollidingBehavior(),
MovingBehavior(velocity: velocity),
RotatingBehavior(rotationSpeed: rotationSpeed),
TappingBehavior(),
DraggingBehavior(),
],
);
final defaultColor = Colors.blue.withOpacity(0.8);
@override
void onMount() {
paint.color = defaultColor;
super.onMount();
}
@override
void render(Canvas canvas) {
final center = size / 2;
canvas.drawCircle(center.toOffset(), min(size.x, size.y) / 2, paint);
}
}
| flame_behaviors/packages/flame_behaviors/example/lib/entities/circle/circle.dart/0 | {'file_path': 'flame_behaviors/packages/flame_behaviors/example/lib/entities/circle/circle.dart', 'repo_id': 'flame_behaviors', 'token_count': 488} |
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame_behaviors/flame_behaviors.dart';
import 'package:flutter/material.dart';
/// {@template collision_behavior}
/// This behavior is used for collision between entities. The
/// [PropagatingCollisionBehavior] propagates the collision to this behavior if
/// the entity that is colliding with the [Parent] is an instance of [Collider].
/// {@endtemplate}
abstract class CollisionBehavior<Collider extends Component,
Parent extends EntityMixin> extends Behavior<Parent> {
/// {@macro collision_behavior}
CollisionBehavior({
super.children,
super.priority,
super.key,
});
/// Check if the given component is an instance of [Collider].
bool isValid(Component c) => c is Collider;
/// Called when the entity collides with [Collider].
void onCollision(Set<Vector2> intersectionPoints, Collider other) {}
/// Called when the entity starts to collides with [Collider].
void onCollisionStart(Set<Vector2> intersectionPoints, Collider other) {}
/// Called when the entity stops to collides with [Collider].
void onCollisionEnd(Collider other) {}
/// Whether the object is currently colliding with another [Collider] or not.
bool get isColliding {
final propagatingCollisionBehavior =
parent.findBehavior<PropagatingCollisionBehavior>();
return propagatingCollisionBehavior.activeCollisions
.map(propagatingCollisionBehavior._findEntity)
.whereType<Collider>()
.isNotEmpty;
}
}
/// {@template propagating_collision_behavior}
/// This behavior is used to handle collisions between entities and propagates
/// the collision through to any [CollisionBehavior]s that are attached to the
/// entity.
///
/// The [CollisionBehavior]s are filtered by the [CollisionBehavior.isValid]
/// method by checking if the colliding entity is valid for the given behavior
/// and if the colliding entity is valid the [CollisionBehavior.onCollision] is
/// called.
///
/// This allows for strongly typed collision detection. Without having to add
/// multiple collision behaviors for different types of entities or adding more
/// logic to a single collision detection behavior.
///
/// If you have an entity that does not require any [CollisionBehavior]s of its
/// own, you can just add the hitbox directly to the entity's children.
/// Any other entity that has a [CollisionBehavior] for that entity attached
/// will then be able to collide with it.
///
/// **Note**: This behavior can also be used for collisions between entities
/// and non-entity components, by passing the component's type as the
/// `Collider` to the [CollisionBehavior].
///
/// The parent to which this behavior is added should be a [PositionComponent]
/// that uses the [EntityMixin]. Flame behaviors comes with the
/// [PositionedEntity] which does exactly that but any kind of position
/// component will work.
/// {@endtemplate}
class PropagatingCollisionBehavior<Parent extends EntityMixin>
extends Behavior<Parent> with CollisionCallbacks {
/// {@macro propagating_collision_behavior}
PropagatingCollisionBehavior(
this._hitbox, {
super.priority,
super.key,
}) : super(children: [_hitbox]);
final ShapeHitbox _hitbox;
@override
@mustCallSuper
void onMount() {
assert(parent is PositionComponent, 'parent must be a PositionComponent');
super.onMount();
}
@override
Future<void> onLoad() async {
_hitbox
..onCollisionCallback = onCollision
..onCollisionStartCallback = onCollisionStart
..onCollisionEndCallback = onCollisionEnd;
parent.children.register<CollisionBehavior>();
_propagateToBehaviors = parent.children.query<CollisionBehavior>();
}
/// List of [CollisionBehavior]s to which it can propagate to.
List<CollisionBehavior> _propagateToBehaviors = [];
/// Tries to find the entity that is colliding with the given entity.
///
/// It will check if the parent is either a [PropagatingCollisionBehavior]
/// or a [Entity]. If it is neither, it will return [other].
Component? _findEntity(PositionComponent other) {
final parent = other.parent;
if (parent is! PropagatingCollisionBehavior && parent is! Entity) {
if (other is ShapeHitbox) {
return other.parent;
}
return other;
}
return parent is Entity
? parent
: (parent as PropagatingCollisionBehavior?)!.parent;
}
@override
void onCollisionStart(
Set<Vector2> intersectionPoints,
PositionComponent other,
) {
activeCollisions.add(other);
final otherEntity = _findEntity(other);
if (otherEntity == null) {
return;
}
for (final behavior in _propagateToBehaviors) {
if (behavior.isValid(otherEntity)) {
behavior.onCollisionStart(intersectionPoints, otherEntity);
}
}
return super.onCollisionStart(intersectionPoints, other);
}
@override
@mustCallSuper
void onCollision(Set<Vector2> intersectionPoints, PositionComponent other) {
final otherEntity = _findEntity(other);
if (otherEntity == null) {
return;
}
for (final behavior in _propagateToBehaviors) {
if (behavior.isValid(otherEntity)) {
behavior.onCollision(intersectionPoints, otherEntity);
}
}
super.onCollision(intersectionPoints, other);
}
@override
void onCollisionEnd(PositionComponent other) {
activeCollisions.remove(other);
final otherEntity = _findEntity(other);
if (otherEntity == null) {
return;
}
for (final behavior in _propagateToBehaviors) {
if (behavior.isValid(otherEntity)) {
behavior.onCollisionEnd(otherEntity);
}
}
return super.onCollisionEnd(other);
}
}
| flame_behaviors/packages/flame_behaviors/lib/src/behaviors/propagating_collision_behavior.dart/0 | {'file_path': 'flame_behaviors/packages/flame_behaviors/lib/src/behaviors/propagating_collision_behavior.dart', 'repo_id': 'flame_behaviors', 'token_count': 1798} |
import 'package:example/src/entities/entities.dart';
import 'package:example/src/example_game.dart';
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
final flameTester = FlameTester(ExampleGame.new);
group('ExampleGame', () {
test('can be instantiated', () {
expect(ExampleGame(), isA<ExampleGame>());
});
flameTester.testGameWidget(
'generates the correct components',
setUp: (game, tester) async {
expect(game.firstChild<FpsTextComponent>(), isNotNull);
expect(game.firstChild<ScreenHitbox>(), isNotNull);
expect(game.children.whereType<Dot>().length, equals(100));
},
);
});
}
| flame_behaviors/packages/flame_steering_behaviors/example/test/src/example_game_test.dart/0 | {'file_path': 'flame_behaviors/packages/flame_steering_behaviors/example/test/src/example_game_test.dart', 'repo_id': 'flame_behaviors', 'token_count': 283} |
import 'dart:math';
import 'package:flame/extensions.dart';
import 'package:flame_steering_behaviors/flame_steering_behaviors.dart';
import 'package:flutter/material.dart';
/// {@template wander}
/// Wander steering algorithm.
///
/// The [onNewAngle] should be used to get the [angle] value for the next
/// [Wander] creation.
/// {@endtemplate}
class Wander extends SteeringCore {
/// {@macro wander}
Wander({
required this.circleDistance,
required this.maximumAngle,
required this.angle,
required this.onNewAngle,
required this.random,
});
/// The distance to the circle center of the next target.
final double circleDistance;
/// The maximum angle used to calculate the next wander [angle].
///
/// Value is represented in radians.
final double maximumAngle;
/// The current wander angle in radians.
final double angle;
/// Called when the next [angle] value is calculated.
///
/// The next call to [Wander] expects the angle to be this value.
final ValueChanged<double> onNewAngle;
/// The random number generator used to calculate the next wander [angle].
final Random random;
@override
Vector2 getSteering(Steerable parent) {
// Calculate the circle center for the next target that is right in front
// of the parent.
final circleCenter = parent.velocity.normalized()..scale(circleDistance);
// Calculate the displacement needed for displacing the circle center.
final displacement = Vector2(0, -1)
..scale(circleDistance)
..setAngle(angle);
// Randomly pick a new angle based on the maximum angle and expose it.
onNewAngle(angle + random.nextDouble() * maximumAngle - maximumAngle * 0.5);
// Calculate the next target position by displacing the circle center.
return circleCenter.clone()..add(displacement);
}
}
extension on Vector2 {
void setAngle(double radians) {
final len = length;
x = cos(radians) * len;
y = sin(radians) * len;
}
}
| flame_behaviors/packages/flame_steering_behaviors/lib/src/steering/wander.dart/0 | {'file_path': 'flame_behaviors/packages/flame_steering_behaviors/lib/src/steering/wander.dart', 'repo_id': 'flame_behaviors', 'token_count': 611} |
import 'package:flame/extensions.dart';
import 'package:flame_steering_behaviors/flame_steering_behaviors.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import '../../helpers/helpers.dart';
void main() {
group('Separation', () {
test('calculates the acceleration needed to separate', () {
final parent = SteerableEntity(
position: Vector2.zero(),
size: Vector2.all(32),
);
final steering = Separation(
[
SteerableEntity(
position: Vector2.all(10),
size: Vector2.all(32),
),
SteerableEntity(
position: Vector2.all(20),
size: Vector2.all(32),
),
],
maxDistance: 50,
maxAcceleration: 10,
);
final linearAcceleration = steering.getSteering(parent);
expect(linearAcceleration, closeToVector(Vector2(-29.08, -29.08), 0.01));
});
test('skips self', () {
final parent = SteerableEntity(
position: Vector2.zero(),
size: Vector2.all(32),
);
final steering = Separation(
[parent],
maxDistance: 50,
maxAcceleration: 10,
);
final linearAcceleration = steering.getSteering(parent);
expect(linearAcceleration, closeToVector(Vector2(0, 0)));
});
test('does not separate if other entities are too far away', () {
final parent = SteerableEntity(position: Vector2.zero());
final steering = Separation(
[
SteerableEntity(
position: Vector2.all(36),
size: Vector2.all(32),
),
SteerableEntity(
position: Vector2.all(-36),
size: Vector2.all(32),
),
],
maxDistance: 50,
maxAcceleration: 10,
);
final linearAcceleration = steering.getSteering(parent);
expect(linearAcceleration, closeToVector(Vector2(0, 0)));
});
});
}
| flame_behaviors/packages/flame_steering_behaviors/test/src/steering/separation_test.dart/0 | {'file_path': 'flame_behaviors/packages/flame_steering_behaviors/test/src/steering/separation_test.dart', 'repo_id': 'flame_behaviors', 'token_count': 901} |
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame_centipede/src/game/game.dart';
class Bullet extends SpriteAnimationComponent
with HasGameRef<FlameCentipede>, CollisionCallbacks {
static const speed = -200.0;
static final dimensions = Vector2(4, 4);
@override
Future<void> onLoad() async {
await super.onLoad();
add(RectangleHitbox());
size = dimensions;
animation = await gameRef.loadSpriteAnimation(
'bullet.png',
SpriteAnimationData.sequenced(
amount: 3,
stepTime: 0.2,
textureSize: Vector2.all(4),
),
);
}
@override
void update(double dt) {
super.update(dt);
position.y += speed * dt;
if (toRect().bottom <= 0) {
removeFromParent();
}
}
}
| flame_centipede/lib/src/game/components/bullet.dart/0 | {'file_path': 'flame_centipede/lib/src/game/components/bullet.dart', 'repo_id': 'flame_centipede', 'token_count': 315} |
import 'package:flame/components.dart';
import 'package:flame/extensions.dart';
import 'package:flame/game.dart';
import 'package:flame/joystick.dart';
import 'package:flutter/material.dart';
import 'joystick_player.dart';
class AdvancedJoystickGame extends BaseGame with HasDraggableComponents {
Future<Sprite> loadJoystick(int idx) async {
return loadSprite(
'joystick.png',
srcPosition: Vector2(idx * 16.0, 0),
srcSize: Vector2.all(16),
);
}
@override
Future<void> onLoad() async {
final joystick = JoystickComponent(
gameRef: this,
directional: JoystickDirectional(
background: JoystickElement.sprite(await loadJoystick(0)),
knob: JoystickElement.sprite(await loadJoystick(1)),
),
actions: [
JoystickAction(
actionId: 1,
margin: const EdgeInsets.all(50),
action: JoystickElement.sprite(await loadJoystick(2)),
actionPressed: JoystickElement.sprite(await loadJoystick(4)),
),
JoystickAction(
actionId: 2,
action: JoystickElement.sprite(await loadJoystick(3)),
actionPressed: JoystickElement.sprite(await loadJoystick(5)),
margin: const EdgeInsets.only(
right: 50,
bottom: 120,
),
),
JoystickAction(
actionId: 3,
margin: const EdgeInsets.only(bottom: 50, right: 120),
enableDirection: true,
color: const Color(0xFFFF00FF),
opacityBackground: 0.1,
opacityKnob: 0.9,
),
],
);
final player = JoystickPlayer();
joystick.addObserver(player);
add(player);
add(joystick);
}
}
| flame_example/lib/stories/controls/advanced_joystick.dart/0 | {'file_path': 'flame_example/lib/stories/controls/advanced_joystick.dart', 'repo_id': 'flame_example', 'token_count': 754} |
import 'dart:math';
import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flame/extensions.dart';
import 'package:flame/game.dart';
import 'package:flame/gestures.dart';
import 'package:flutter/material.dart';
import '../../commons/square_component.dart';
class RotateEffectGame extends BaseGame with TapDetector {
SquareComponent square;
RotateEffectGame() {
add(
square = SquareComponent()
..position = Vector2.all(200)
..anchor = Anchor.center,
);
}
@override
void onTap() {
square.addEffect(
RotateEffect(
angle: 2 * pi,
isRelative: true,
duration: 5.0,
curve: Curves.bounceInOut,
),
);
}
}
| flame_example/lib/stories/effects/rotate_effect.dart/0 | {'file_path': 'flame_example/lib/stories/effects/rotate_effect.dart', 'repo_id': 'flame_example', 'token_count': 298} |
import 'package:dashbook/dashbook.dart';
import 'package:flame/game.dart';
import '../../commons/commons.dart';
import 'base64.dart';
import 'basic.dart';
import 'spritebatch.dart';
import 'spritebatch_auto_load.dart';
import 'spritesheet.dart';
void addSpritesStories(Dashbook dashbook) {
dashbook.storiesOf('Sprites')
..add(
'Basic Sprite',
(_) => GameWidget(game: BasicSpriteGame()),
codeLink: baseLink('sprites/basic.dart'),
)
..add(
'Base64 Sprite',
(_) => GameWidget(game: Base64SpriteGame()),
codeLink: baseLink('sprites/base64.dart'),
)
..add(
'Spritesheet',
(_) => GameWidget(game: SpritesheetGame()),
codeLink: baseLink('sprites/spritesheet.dart'),
)
..add(
'Spritebatch',
(_) => GameWidget(game: SpritebatchGame()),
codeLink: baseLink('sprites/spritebatch.dart'),
)
..add(
'Spritebatch Auto Load',
(_) => GameWidget(game: SpritebatchAutoLoadGame()),
codeLink: baseLink('sprites/spritebatch_auto_load.dart'),
);
}
| flame_example/lib/stories/sprites/sprites.dart/0 | {'file_path': 'flame_example/lib/stories/sprites/sprites.dart', 'repo_id': 'flame_example', 'token_count': 448} |
import 'dart:ui';
import 'package:forge2d/forge2d.dart';
import 'package:flame/components.dart';
import 'package:flame/gestures.dart';
import 'package:flame_forge2d/forge2d_game.dart';
import 'package:flame_forge2d/sprite_body_component.dart';
import 'boundaries.dart';
class Pizza extends SpriteBodyComponent {
final Vector2 _position;
Pizza(this._position, Image image) : super(Sprite(image), Vector2(10, 15));
@override
Body createBody() {
final PolygonShape shape = PolygonShape();
final vertices = [
Vector2(-size.x / 2, -size.y / 2),
Vector2(size.x / 2, -size.y / 2),
Vector2(0, size.y / 2),
];
shape.set(vertices);
final fixtureDef = FixtureDef(shape)
..userData = this // To be able to determine object in collision
..restitution = 0.3
..density = 1.0
..friction = 0.2;
final bodyDef = BodyDef()
..position = _position
..angle = (_position.x + _position.y) / 2 * 3.14
..type = BodyType.dynamic;
return world.createBody(bodyDef)..createFixture(fixtureDef);
}
}
class SpriteBodySample extends Forge2DGame with TapDetector {
late Image _pizzaImage;
SpriteBodySample() : super(gravity: Vector2(0, -10.0));
@override
Future<void> onLoad() async {
_pizzaImage = await images.load('pizza.png');
addAll(createBoundaries(this));
}
@override
void onTapDown(TapDownInfo details) {
super.onTapDown(details);
final Vector2 position = details.eventPosition.game;
add(Pizza(position, _pizzaImage));
}
}
| flame_forge2d/example/lib/sprite_body_sample.dart/0 | {'file_path': 'flame_forge2d/example/lib/sprite_body_sample.dart', 'repo_id': 'flame_forge2d', 'token_count': 583} |
import 'package:flutter_test/flutter_test.dart';
import 'package:flame_geom/int_rect.dart';
import 'package:flame_geom/int_bounds.dart';
void main() {
test('simple overlaps', () {
final i1 = IntBounds([IntRect.fromLTWH(0, 0, 1, 1)]);
final i2 = IntBounds([IntRect.fromLTWH(-10, -2, 20, 4)]);
final i3 = IntBounds([IntRect.fromLTWH(5, 0, 1, 1)]);
expect(i1.overlaps(i2), true);
expect(i2.overlaps(i1), true);
expect(i2.overlaps(i3), true);
expect(i3.overlaps(i2), true);
expect(i1.overlaps(i3), false);
expect(i3.overlaps(i1), false);
});
test('complex overlaps', () {
final i1 =
IntBounds([IntRect.fromLTWH(0, 0, 1, 1), IntRect.fromLTWH(5, 0, 1, 1)]);
final i2 = IntBounds([IntRect.fromLTWH(-10, -2, 20, 4)]);
final i3 = IntBounds([IntRect.fromLTWH(3, 0, 1, 1)]);
expect(i1.overlaps(i2), true);
expect(i2.overlaps(i1), true);
expect(i1.overlaps(i3), false);
expect(i3.overlaps(i1), false);
});
}
| flame_geom/test/int_bounds_test.dart/0 | {'file_path': 'flame_geom/test/int_bounds_test.dart', 'repo_id': 'flame_geom', 'token_count': 461} |
import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
import '../button.dart';
import '../utils/color_util.dart';
class ConsoleButton extends StatefulWidget {
final OnTapUp onTapUp;
final OnTapDown onTapDown;
final OnTap onTap;
final Color color;
final FlameShellButton button;
final double size;
ConsoleButton({
@required this.color,
@required this.button,
@required this.onTapDown,
@required this.onTapUp,
@required this.onTap,
@required this.size,
});
@override
State createState() => _ConsoleButtonState();
}
class _ConsoleButtonState extends State<ConsoleButton> {
bool _pressed = false;
void _release() {
setState(() {
_pressed = false;
});
widget.onTapUp(widget.button);
}
void _press() {
setState(() {
_pressed = true;
});
widget.onTapDown(widget.button);
}
@override
Widget build(BuildContext context) {
return Container(
width: widget.size,
height: widget.size,
child: GestureDetector(
onTapUp: (_) => _release(),
onTapDown: (_) => _press(),
onTapCancel: () => _release(),
onTap: () => widget.onTap(widget.button),
child: CustomPaint(
painter: _ButtonPainter(color: widget.color, pressed: _pressed)),
));
}
}
class _ButtonPainter extends CustomPainter {
final Color color;
final bool pressed;
_ButtonPainter({
@required this.color,
@required this.pressed,
});
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()..color = color;
final darkPaint = Paint()..color = darkenColor(color, 0.2);
canvas.drawCircle(Offset(size.width / 2, (size.height / 2) + 5),
size.width / 2, darkPaint);
canvas.drawCircle(
Offset(size.width / 2, (size.height / 2) + (pressed ? 2 : 0)),
size.width / 2,
paint);
}
@override
bool shouldRepaint(_ButtonPainter oldDelegate) => color != oldDelegate.color;
}
| flame_shells/lib/widgets/console_button.dart/0 | {'file_path': 'flame_shells/lib/widgets/console_button.dart', 'repo_id': 'flame_shells', 'token_count': 785} |
include: package:flame_lint/analysis_options.yaml | flame_splash_screen/example/analysis_options.yaml/0 | {'file_path': 'flame_splash_screen/example/analysis_options.yaml', 'repo_id': 'flame_splash_screen', 'token_count': 15} |
import 'package:flame/palette.dart';
import 'package:flutter/material.dart';
import 'package:flame/game.dart';
void main() {
final myGame = MyGame();
runApp(
GameWidget(
game: myGame,
),
);
}
class MyGame extends Game {
static const int squareSpeed = 400;
static final squarePaint = BasicPalette.white.paint;
late Rect squarePos;
int squareDirection = 1;
@override
Future<void> onLoad() async {
squarePos = Rect.fromLTWH(0, 0, 100, 100);
}
@override
void update(double dt) {
squarePos = squarePos.translate(squareSpeed * squareDirection * dt, 0);
if (squareDirection == 1 && squarePos.right > size.x) {
squareDirection = -1;
} else if (squareDirection == -1 && squarePos.left < 0) {
squareDirection = 1;
}
}
@override
void render(Canvas canvas) {
canvas.drawRect(squarePos, squarePaint);
}
}
| flame_tutorials/tutorials/1_basic_square/code/lib/main.dart/0 | {'file_path': 'flame_tutorials/tutorials/1_basic_square/code/lib/main.dart', 'repo_id': 'flame_tutorials', 'token_count': 331} |
include: package:flame_lint/analysis_options.yaml
| flappy_ember/analysis_options.yaml/0 | {'file_path': 'flappy_ember/analysis_options.yaml', 'repo_id': 'flappy_ember', 'token_count': 16} |
import 'package:equatable/equatable.dart';
enum LocationStatus { initial, loading, success, failure }
class LocationState extends Equatable {
const LocationState._({
this.status = LocationStatus.initial,
this.locations = const <String>[],
this.selectedLocation,
});
const LocationState.initial() : this._();
const LocationState.loading() : this._(status: LocationStatus.loading);
const LocationState.success(List<String> locations)
: this._(status: LocationStatus.success, locations: locations);
const LocationState.failure() : this._(status: LocationStatus.failure);
final LocationStatus status;
final List<String> locations;
final String? selectedLocation;
LocationState copyWith({String? selectedLocation}) {
return LocationState._(
locations: locations,
status: status,
selectedLocation: selectedLocation ?? this.selectedLocation,
);
}
@override
List<Object?> get props => [status, locations, selectedLocation];
}
| flow_builder/example/lib/location_flow/models/location_state.dart/0 | {'file_path': 'flow_builder/example/lib/location_flow/models/location_state.dart', 'repo_id': 'flow_builder', 'token_count': 286} |
import 'package:flutter/material.dart';
class LocationError extends StatelessWidget {
const LocationError({super.key});
@override
Widget build(BuildContext context) {
return const Text('Oops something went wrong!');
}
}
| flow_builder/example/lib/location_flow/widgets/location_error.dart/0 | {'file_path': 'flow_builder/example/lib/location_flow/widgets/location_error.dart', 'repo_id': 'flow_builder', 'token_count': 69} |
import 'design_pattern.dart';
class DesignPatternCategory {
const DesignPatternCategory({
required this.id,
required this.title,
required this.color,
required this.patterns,
});
final String id;
final String title;
final int color;
final List<DesignPattern> patterns;
factory DesignPatternCategory.fromJson(Map<String, dynamic> json) {
final designPatternJsonList = json['patterns'] as List;
final designPatternList = designPatternJsonList
.map(
(designPatternJson) => DesignPattern.fromJson(
designPatternJson as Map<String, dynamic>,
),
)
.toList();
return DesignPatternCategory(
id: json['id'] as String,
title: json['title'] as String,
color: int.parse(json['color'] as String),
patterns: designPatternList,
);
}
}
| flutter-design-patterns/lib/data/models/design_pattern_category.dart/0 | {'file_path': 'flutter-design-patterns/lib/data/models/design_pattern_category.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 315} |
import 'package:flutter/material.dart';
import '../iswitch.dart';
class AndroidSwitch implements ISwitch {
const AndroidSwitch();
@override
Widget render({required bool value, required ValueSetter<bool> onChanged}) {
return Switch(
activeColor: Colors.black,
value: value,
onChanged: onChanged,
);
}
}
| flutter-design-patterns/lib/design_patterns/abstract_factory/widgets/switches/android_switch.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/abstract_factory/widgets/switches/android_switch.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 117} |
import '../entities/customer.dart';
import '../entities/entity_base.dart';
import '../irepository.dart';
import '../istorage.dart';
class CustomersRepository implements IRepository {
const CustomersRepository(this.storage);
final IStorage storage;
@override
List<EntityBase> getAll() => storage.fetchAll<Customer>();
@override
void save(EntityBase entityBase) {
storage.store<Customer>(entityBase as Customer);
}
}
| flutter-design-patterns/lib/design_patterns/bridge/repositories/customers_repository.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/bridge/repositories/customers_repository.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 138} |
import '../ingredient.dart';
class Cheese extends Ingredient {
Cheese() {
name = 'Cheese';
allergens = ['Milk', 'Soy'];
}
}
| flutter-design-patterns/lib/design_patterns/builder/ingredients/cheese.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/builder/ingredients/cheese.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 56} |
import 'package:flutter/foundation.dart';
import 'log_level.dart';
abstract class LoggerBase {
const LoggerBase({
required this.logLevel,
LoggerBase? nextLogger,
}) : _nextLogger = nextLogger;
@protected
final LogLevel logLevel;
final LoggerBase? _nextLogger;
void logMessage(LogLevel level, String message) {
if (logLevel <= level) log(message);
_nextLogger?.logMessage(level, message);
}
void logDebug(String message) => logMessage(LogLevel.debug, message);
void logInfo(String message) => logMessage(LogLevel.info, message);
void logError(String message) => logMessage(LogLevel.error, message);
void log(String message);
}
| flutter-design-patterns/lib/design_patterns/chain_of_responsibility/logger_base.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/chain_of_responsibility/logger_base.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 218} |
export 'pizza.dart';
export 'pizza_base.dart';
export 'pizza_decorator.dart';
export 'pizza_menu.dart';
export 'pizza_topping_data.dart';
export 'pizza_toppings/pizza_toppings.dart';
| flutter-design-patterns/lib/design_patterns/decorator/decorator.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/decorator/decorator.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 76} |
class CameraApi {
const CameraApi();
bool turnCameraOn() => true;
bool turnCameraOff() => false;
}
| flutter-design-patterns/lib/design_patterns/facade/apis/camera_api.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/facade/apis/camera_api.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 35} |
import 'ipositioned_shape.dart';
import 'shape_factory.dart';
import 'shape_type.dart';
class ShapeFlyweightFactory {
ShapeFlyweightFactory({
required this.shapeFactory,
});
final ShapeFactory shapeFactory;
final Map<ShapeType, IPositionedShape> shapesMap = {};
IPositionedShape getShape(ShapeType shapeType) {
if (!shapesMap.containsKey(shapeType)) {
shapesMap[shapeType] = shapeFactory.createShape(shapeType);
}
return shapesMap[shapeType]!;
}
int getShapeInstancesCount() => shapesMap.length;
}
| flutter-design-patterns/lib/design_patterns/flyweight/shape_flyweight_factory.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/flyweight/shape_flyweight_factory.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 180} |
import '../graph.dart';
import '../tree_iterators/depth_first_iterator.dart';
import '../tree_iterators/itree_iterator.dart';
import 'itree_collection.dart';
class DepthFirstTreeCollection implements ITreeCollection {
const DepthFirstTreeCollection(this.graph);
final Graph graph;
@override
ITreeIterator createIterator() => DepthFirstIterator(this);
@override
String getTitle() => 'Depth-first';
}
| flutter-design-patterns/lib/design_patterns/iterator/tree_collections/depth_first_tree_collection.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/iterator/tree_collections/depth_first_tree_collection.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 124} |
import 'package:flutter/material.dart';
class Shape {
Shape.initial()
: color = Colors.black,
height = 150.0,
width = 150.0;
Shape.copy(Shape shape)
: color = shape.color,
height = shape.height,
width = shape.width;
Color color;
double height;
double width;
}
| flutter-design-patterns/lib/design_patterns/memento/command_design_pattern/shape.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/memento/command_design_pattern/shape.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 132} |
export 'shape.dart';
export 'shapes/circle.dart';
export 'shapes/rectangle.dart';
| flutter-design-patterns/lib/design_patterns/prototype/prototype.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/prototype/prototype.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 31} |
import 'package:flutter/widgets.dart';
import 'state_context.dart';
abstract interface class IState {
Future<void> nextState(StateContext context);
Widget render();
}
| flutter-design-patterns/lib/design_patterns/state/istate.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/state/istate.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 55} |
class XmlStudentsApi {
static const _studentsXml = '''
<?xml version="1.0"?>
<students>
<student>
<fullname>John Doe (XML)</fullname>
<age>12</age>
<height>1.62</height>
<weight>53</weight>
</student>
<student>
<fullname>Emma Doe (XML)</fullname>
<age>15</age>
<height>1.55</height>
<weight>50</weight>
</student>
<student>
<fullname>Michael Roe (XML)</fullname>
<age>18</age>
<height>1.85</height>
<weight>89</weight>
</student>
<student>
<fullname>Emma Roe (XML)</fullname>
<age>20</age>
<height>1.66</height>
<weight>79</weight>
</student>
</students>
''';
const XmlStudentsApi();
String getStudentsXml() => _studentsXml;
}
| flutter-design-patterns/lib/design_patterns/template_method/apis/xml_students_api.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/template_method/apis/xml_students_api.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 372} |
export 'directory.dart';
export 'file.dart';
export 'files/index.dart';
export 'ifile.dart';
export 'ivisitor.dart';
export 'visitors/human_readable_visitor.dart';
export 'visitors/xml_visitor.dart';
| flutter-design-patterns/lib/design_patterns/visitor/visitor.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/visitor/visitor.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 75} |
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import '../../../constants/constants.dart';
import '../../../helpers/dart_syntax_highlighter.dart';
import '../../../helpers/url_launcher.dart';
import '../../../widgets/image_view.dart';
class RichMarkdownBody extends StatelessWidget {
const RichMarkdownBody({this.data, super.key});
final String? data;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final textTheme = theme.textTheme;
final bodyMedium = textTheme.bodyMedium;
final fontSize = bodyMedium?.fontSize ?? 14.0;
return MarkdownBody(
selectable: true,
fitContent: false,
styleSheet: MarkdownStyleSheet(
h1: textTheme.headlineMedium,
h2: textTheme.titleLarge,
h3: textTheme.titleMedium,
h4: textTheme.titleMedium,
h5: textTheme.titleMedium,
h6: textTheme.titleLarge,
p: bodyMedium,
blockSpacing: LayoutConstants.spaceM,
blockquotePadding: const EdgeInsets.symmetric(
horizontal: LayoutConstants.paddingM * 1.5,
vertical: LayoutConstants.paddingM,
),
horizontalRuleDecoration: BoxDecoration(
border: Border(
top: BorderSide(
color: theme.colorScheme.primary.withOpacity(0.2),
width: 3,
),
),
),
blockquoteDecoration: BoxDecoration(
color: theme.colorScheme.surface.withOpacity(0.2),
border: Border(
left: BorderSide(
color: theme.colorScheme.surface,
width: LayoutConstants.spaceS,
),
),
),
codeblockDecoration: BoxDecoration(
color: theme.colorScheme.surface,
borderRadius: BorderRadius.circular(LayoutConstants.spaceS),
border: Border.all(
color: theme.colorScheme.outline.withOpacity(0.2),
),
),
a: bodyMedium?.copyWith(
color: theme.colorScheme.primary,
decoration: TextDecoration.underline,
),
blockquote: bodyMedium?.copyWith(
color: theme.colorScheme.onSurface.withOpacity(0.6),
),
code: bodyMedium?.copyWith(
color: theme.colorScheme.onSurface,
backgroundColor: theme.colorScheme.surface,
),
em: bodyMedium?.copyWith(fontStyle: FontStyle.italic),
strong: bodyMedium?.copyWith(fontWeight: FontWeight.bold),
img: bodyMedium,
listBullet: bodyMedium?.copyWith(
color: textTheme.bodySmall?.color,
),
listBulletPadding: const EdgeInsets.symmetric(
horizontal: LayoutConstants.paddingXS,
),
tableBody: bodyMedium?.copyWith(
color: textTheme.bodyMedium?.color?.withOpacity(0.8),
),
tableHead: bodyMedium?.copyWith(
fontSize: fontSize + 2,
color: textTheme.bodyLarge?.color,
),
tableHeadAlign: TextAlign.center,
tableCellsPadding: const EdgeInsets.all(LayoutConstants.paddingM),
tableBorder: TableBorder.all(
color: theme.colorScheme.onSurface.withOpacity(0.6),
),
),
onTapLink: (_, link, __) => UrlLauncher.launchUrl(link ?? ''),
syntaxHighlighter: DartSyntaxHighlighter(context),
imageBuilder: (uri, _, __) => GestureDetector(
onTap: () => Navigator.of(context).push(
PageRouteBuilder(
pageBuilder: (_, __, ___) => ImageView(uri: uri),
),
),
child: Hero(
tag: uri,
child: Image.asset(uri.path),
),
),
data: data ?? '',
);
}
}
| flutter-design-patterns/lib/modules/design_pattern_details/widgets/rich_markdown_body.dart/0 | {'file_path': 'flutter-design-patterns/lib/modules/design_pattern_details/widgets/rich_markdown_body.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 1719} |
import 'package:flutter/material.dart';
import '../../../../constants/constants.dart';
import '../../../../design_patterns/bridge/bridge.dart';
class CustomersDatatable extends StatelessWidget {
final List<Customer> customers;
const CustomersDatatable({
required this.customers,
});
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
columnSpacing: LayoutConstants.spaceM,
horizontalMargin: LayoutConstants.marginM,
headingRowHeight: LayoutConstants.spaceXL,
dataRowMinHeight: LayoutConstants.spaceXL,
columns: const <DataColumn>[
DataColumn(
label: Text(
'Name',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.0),
),
),
DataColumn(
label: Text(
'E-mail',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.0),
),
),
],
rows: <DataRow>[
for (var customer in customers)
DataRow(
cells: <DataCell>[
DataCell(Text(customer.name)),
DataCell(Text(customer.email)),
],
),
],
),
);
}
}
| flutter-design-patterns/lib/widgets/design_patterns/bridge/data_tables/customers_data_table.dart/0 | {'file_path': 'flutter-design-patterns/lib/widgets/design_patterns/bridge/data_tables/customers_data_table.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 624} |
import 'package:flutter/material.dart';
import 'file.dart';
final class ImageFile extends File {
const ImageFile({
required super.title,
required super.size,
}) : super(icon: Icons.image);
}
| flutter-design-patterns/lib/widgets/design_patterns/composite/files/image_file.dart/0 | {'file_path': 'flutter-design-patterns/lib/widgets/design_patterns/composite/files/image_file.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 70} |
import 'package:flutter/material.dart';
import '../../../constants/constants.dart';
import '../../../design_patterns/interpreter/interpreter.dart';
import '../../platform_specific/platform_button.dart';
class ExpressionSection extends StatefulWidget {
final String postfixExpression;
const ExpressionSection({
required this.postfixExpression,
});
@override
_ExpressionSectionState createState() => _ExpressionSectionState();
}
class _ExpressionSectionState extends State<ExpressionSection> {
final _expressionContext = ExpressionContext();
final List<String> _solutionSteps = [];
void _solvePrefixExpression() {
final solutionSteps = <String>[];
final expression =
ExpressionHelpers.buildExpressionTree(widget.postfixExpression);
final result = expression.interpret(_expressionContext);
solutionSteps
..addAll(_expressionContext.getSolutionSteps())
..add('Result: $result');
setState(() => _solutionSteps.addAll(solutionSteps));
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
widget.postfixExpression,
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: LayoutConstants.spaceM),
AnimatedCrossFade(
duration: const Duration(milliseconds: 250),
firstChild: PlatformButton(
materialColor: Colors.black,
materialTextColor: Colors.white,
onPressed: _solvePrefixExpression,
text: 'Solve',
),
secondChild: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
for (var solutionStep in _solutionSteps)
Text(
solutionStep,
style: Theme.of(context).textTheme.titleSmall,
)
],
),
crossFadeState: _solutionSteps.isEmpty
? CrossFadeState.showFirst
: CrossFadeState.showSecond,
),
const SizedBox(height: LayoutConstants.spaceXL),
],
);
}
}
| flutter-design-patterns/lib/widgets/design_patterns/interpreter/expression_section.dart/0 | {'file_path': 'flutter-design-patterns/lib/widgets/design_patterns/interpreter/expression_section.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 895} |
import 'package:flutter/material.dart';
import '../../../../constants/constants.dart';
import '../../../../design_patterns/proxy/proxy.dart';
import 'customer_info_group.dart';
class CustomerDetailsColumn extends StatelessWidget {
final CustomerDetails customerDetails;
const CustomerDetailsColumn({
required this.customerDetails,
});
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
CustomerInfoGroup(
label: 'E-mail',
text: customerDetails.email,
),
const SizedBox(height: LayoutConstants.spaceL),
CustomerInfoGroup(
label: 'Position',
text: customerDetails.position,
),
const SizedBox(height: LayoutConstants.spaceL),
CustomerInfoGroup(
label: 'Hobby',
text: customerDetails.hobby,
),
],
);
}
}
| flutter-design-patterns/lib/widgets/design_patterns/proxy/customer_details_dialog/customer_details_column.dart/0 | {'file_path': 'flutter-design-patterns/lib/widgets/design_patterns/proxy/customer_details_dialog/customer_details_column.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 398} |
import 'package:flutter/material.dart';
import '../../../constants/constants.dart';
import '../../../design_patterns/template_method/template_method.dart';
import 'students_section.dart';
class TemplateMethodExample extends StatelessWidget {
const TemplateMethodExample();
@override
Widget build(BuildContext context) {
return const ScrollConfiguration(
behavior: ScrollBehavior(),
child: SingleChildScrollView(
padding: EdgeInsets.symmetric(
horizontal: LayoutConstants.paddingL,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
StudentsSection(
bmiCalculator: StudentsXmlBmiCalculator(),
headerText: 'Students from XML data source:',
),
SizedBox(height: LayoutConstants.spaceL),
StudentsSection(
bmiCalculator: StudentsJsonBmiCalculator(),
headerText: 'Students from JSON data source:',
),
SizedBox(height: LayoutConstants.spaceL),
StudentsSection(
bmiCalculator: TeenageStudentsJsonBmiCalculator(),
headerText: 'Students from JSON data source (teenagers only):',
),
],
),
),
);
}
}
| flutter-design-patterns/lib/widgets/design_patterns/template_method/template_method_example.dart/0 | {'file_path': 'flutter-design-patterns/lib/widgets/design_patterns/template_method/template_method_example.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 566} |
import 'package:flutter_festival/domain/storage/storage_service.dart';
import 'package:hive_flutter/hive_flutter.dart';
class HiveStorageService implements StorageService {
late Box _hiveAppBox;
Future<void> _openBoxes() async {
_hiveAppBox = await Hive.openBox(StorageBoxNames.appBox);
}
@override
Future<void> init() async {
await Hive.initFlutter();
await _openBoxes();
}
Box _getTargetBox(String? boxName) {
switch (boxName) {
case StorageBoxNames.appBox:
return _hiveAppBox;
default:
return _hiveAppBox;
}
}
@override
Future<void> remove(String key,
{String boxName = StorageBoxNames.appBox}) async {
_getTargetBox(boxName).delete(key);
}
@override
dynamic get(String key, {String boxName = StorageBoxNames.appBox}) {
return _getTargetBox(boxName).get(key);
}
@override
dynamic getAll({String boxName = StorageBoxNames.appBox}) {
return _getTargetBox(boxName).values.toList();
}
@override
bool has(String key, {String? boxName}) {
return _getTargetBox(boxName).containsKey(key);
}
@override
Future<void> set(String? key, dynamic data,
{String boxName = StorageBoxNames.appBox}) async {
_getTargetBox(boxName).put(key, data);
}
@override
Future<void> clear() async {
await _hiveAppBox.clear();
}
@override
Future<void> clearBox({String boxName = StorageBoxNames.appBox}) async {
await _getTargetBox(boxName).clear();
}
}
| flutter-festival-session/lib/domain/storage/hive_storage_service.dart/0 | {'file_path': 'flutter-festival-session/lib/domain/storage/hive_storage_service.dart', 'repo_id': 'flutter-festival-session', 'token_count': 550} |
import 'package:flutter/material.dart';
import 'package:flutter_festival/i18n/translations.dart';
import 'package:flutter_festival/ui/styles/app_text_styles.dart';
class AnimatedAlignAndOpacityExample extends StatefulWidget {
const AnimatedAlignAndOpacityExample({Key? key}) : super(key: key);
@override
_AnimatedAlignAndOpacityExampleState createState() =>
_AnimatedAlignAndOpacityExampleState();
}
class _AnimatedAlignAndOpacityExampleState
extends State<AnimatedAlignAndOpacityExample> {
final Duration animationDuration = const Duration(milliseconds: 300);
bool showText = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => setState(() => showText = !showText),
child: Container(
padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 17),
width: double.infinity,
child: Stack(
children: [
Positioned.fill(
child: Container(
decoration: BoxDecoration(
color: Colors.deepPurple.shade300,
borderRadius: BorderRadius.circular(15)),
child: AnimatedAlign(
alignment: showText
? const AlignmentDirectional(-0.9, -1.25)
: Alignment.center,
duration: animationDuration,
child: Text(
Translations.of(context)!
.get(showText ? 'More Text' : 'Tap to Read More...'),
style: AppTextStyles.h1,
),
),
),
),
AnimatedOpacity(
opacity: showText ? 1 : 0,
duration: animationDuration,
child: Padding(
padding: const EdgeInsets.all(10),
child: Text(Translations.of(context)!.get('dummy_text')),
),
)
],
),
),
);
}
}
| flutter-festival-session/lib/ui/implicit_animations/widgets/animated_align_and_opacity_example.dart/0 | {'file_path': 'flutter-festival-session/lib/ui/implicit_animations/widgets/animated_align_and_opacity_example.dart', 'repo_id': 'flutter-festival-session', 'token_count': 962} |
/*
* Copyright 2019 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import 'dart:async';
import 'package:meta/meta.dart';
import 'package:test/test.dart';
/// Test data for the CommonTestConfigUtils test.
/// The outline for this file is pretty-printed in custom_outline.txt.
///
/// To update the outline, open this file in a debugging IntelliJ instance, then
/// set a breakpoint in the ActiveEditorsOutlineService's OutlineListener call
/// to `notifyOutlineUpdated`, then look at the Flutter Outline for this file.
/// This will break at the outline and allow you to copy its json value.
///
/// You can pretty-print the json using the pretty_print.dart script at
/// testData/sample_tests/bin/pretty_print.dart.
// TODO: use an API on the Dart Analyzer to update this outline more easily.
void main() {
group('group 0', () {
test('test 0', () {
print('test contents');
});
testWidgets('test widgets 0', (tester) async {
print('test widgets contents');
});
nonTest('not a test');
});
test('test 1', () {});
nonGroup('not a group', () {
g('custom group', () {
t('custom test');
});
});
}
@isTestGroup
void g(String name, void Function() callback) {}
@isTest
void t(String name) {}
void nonGroup(String name, void Function() callback) {}
void nonTest(String name) {}
// This is a similar signature to the testWidgets method from Flutter.
@isTest
void testWidgets(String name, Future<void> Function(Object tester) test) {
test(Object());
}
| flutter-intellij/flutter-idea/testData/sample_tests/test/custom_test.dart/0 | {'file_path': 'flutter-intellij/flutter-idea/testData/sample_tests/test/custom_test.dart', 'repo_id': 'flutter-intellij', 'token_count': 505} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.