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 'dart:async';
import 'dart:convert';
import 'dart:io';
class ShellProcess {
final Completer<Uri> _vmServiceUriCompleter = Completer<Uri>();
final Process _process;
ShellProcess(this._process) {
// Scan stdout and scrape the VM Service Uri.
_process.stdout
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen((String line) {
final uri = _extractVMServiceUri(line);
if (uri != null) {
_vmServiceUriCompleter.complete(uri);
}
});
}
Future<bool> kill() async {
return _process.kill();
}
Future<Uri> waitForVMService() async {
return _vmServiceUriCompleter.future;
}
Uri? _extractVMServiceUri(String str) {
final listeningMessageRegExp = RegExp(
r'The Dart VM service is listening on ((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+)',
);
final match = listeningMessageRegExp.firstMatch(str);
if (match != null) {
return Uri.parse(match[1]!);
}
return null;
}
}
class ShellLauncher {
final List<String> args = <String>[
'--vm-service-port=0',
'--non-interactive',
'--run-forever',
'--disable-service-auth-codes',
];
final String shellExecutablePath;
final String mainDartPath;
final bool startPaused;
ShellLauncher(this.shellExecutablePath, this.mainDartPath, this.startPaused,
List<String> extraArgs) {
args.addAll(extraArgs);
args.add(mainDartPath);
}
Future<ShellProcess?> launch() async {
try {
final List<String> shellArguments = <String>[];
if (startPaused) {
shellArguments.add('--start-paused');
}
shellArguments.addAll(args);
print('Launching $shellExecutablePath $shellArguments');
final Process process =
await Process.start(shellExecutablePath, shellArguments);
return ShellProcess(process);
} catch (e) {
print('Error launching shell: $e');
return null;
}
}
}
| engine/shell/testing/observatory/launcher.dart/0 | {'file_path': 'engine/shell/testing/observatory/launcher.dart', 'repo_id': 'engine', 'token_count': 826} |
// 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:ui';
import 'package:litetest/litetest.dart';
void main() {
test('Image constructor and dispose invokes onCreate once', () async {
// We test constructor and dispose in one test because
// litetest runs the tests in parallel and static handlers
// are shared between tests.
int onCreateInvokedCount = 0;
Image? createdImage;
int onDisposeInvokedCount = 0;
Image? disposedImage;
Image.onCreate = (Image image) {
onCreateInvokedCount++;
createdImage = image;
};
Image.onDispose = (Image image) {
onDisposeInvokedCount++;
disposedImage = image;
};
final Image image1 = await _createImage()..dispose();
expect(onCreateInvokedCount, 1);
expect(createdImage, image1);
expect(onDisposeInvokedCount, 1);
expect(disposedImage, image1);
final Image image2 = await _createImage()..dispose();
expect(onCreateInvokedCount, 2);
expect(createdImage, image2);
expect(onDisposeInvokedCount, 2);
expect(disposedImage, image2);
Image.onCreate = null;
Image.onDispose = null;
});
}
Future<Image> _createImage() => _createPicture().toImage(10, 10);
Picture _createPicture() {
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 100.0);
canvas.clipRect(rect);
return recorder.endRecording();
}
| engine/testing/dart/image_events_test.dart/0 | {'file_path': 'engine/testing/dart/image_events_test.dart', 'repo_id': 'engine', 'token_count': 545} |
// 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:developer' as developer;
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:litetest/litetest.dart';
import 'package:vm_service/vm_service.dart' as vms;
import 'package:vm_service/vm_service_io.dart';
import '../impeller_enabled.dart';
void main() {
test('Setting invalid directory returns an error', () async {
vms.VmService? vmService;
try {
final developer.ServiceProtocolInfo info = await developer.Service.getInfo();
if (info.serverUri == null) {
fail('This test must not be run with --disable-vm-service.');
}
vmService = await vmServiceConnectUri(
'ws://localhost:${info.serverUri!.port}${info.serverUri!.path}ws',
);
final String viewId = await getViewId(vmService);
dynamic error;
try {
await vmService.callMethod(
'_flutter.setAssetBundlePath',
args: <String, Object>{'viewId': viewId, 'assetDirectory': ''},
);
} catch (err) {
error = err;
}
expect(error != null, true);
} finally {
await vmService?.dispose();
}
});
test('Can return whether or not impeller is enabled', () async {
vms.VmService? vmService;
try {
final developer.ServiceProtocolInfo info = await developer.Service.getInfo();
if (info.serverUri == null) {
fail('This test must not be run with --disable-vm-service.');
}
vmService = await vmServiceConnectUri(
'ws://localhost:${info.serverUri!.port}${info.serverUri!.path}ws',
);
final String? isolateId = await getIsolateId(vmService);
final vms.Response response = await vmService.callServiceExtension(
'ext.ui.window.impellerEnabled',
isolateId: isolateId,
);
expect(response.json!['enabled'], impellerEnabled);
} finally {
await vmService?.dispose();
}
});
test('Reload fonts request sends font change notification', () async {
vms.VmService? vmService;
try {
final developer.ServiceProtocolInfo info =
await developer.Service.getInfo();
if (info.serverUri == null) {
fail('This test must not be run with --disable-vm-service.');
}
final Completer<String> completer = Completer<String>();
ui.channelBuffers.setListener(
'flutter/system',
(ByteData? data, ui.PlatformMessageResponseCallback callback) {
final ByteBuffer buffer = data!.buffer;
final Uint8List list = buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
completer.complete(utf8.decode(list));
},
);
vmService = await vmServiceConnectUri(
'ws://localhost:${info.serverUri!.port}${info.serverUri!.path}ws',
);
final String viewId = await getViewId(vmService);
final vms.Response fontChangeResponse = await vmService.callMethod(
'_flutter.reloadAssetFonts',
args: <String, Object>{'viewId': viewId},
);
expect(fontChangeResponse.type, 'Success');
expect(
await completer.future,
'{"type":"fontsChange"}',
);
} finally {
await vmService?.dispose();
ui.channelBuffers.clearListener('flutter/system');
}
});
}
Future<String> getViewId(vms.VmService vmService) async {
final vms.Response response = await vmService.callMethod('_flutter.listViews');
final List<Object?>? rawViews = response.json!['views'] as List<Object?>?;
return (rawViews![0]! as Map<String, Object?>?)!['id']! as String;
}
Future<String?> getIsolateId(vms.VmService vmService) async {
final vms.VM vm = await vmService.getVM();
for (final vms.IsolateRef isolate in vm.isolates!) {
if (isolate.isSystemIsolate ?? false) {
continue;
}
return isolate.id;
}
return null;
}
| engine/testing/dart/observatory/vmservice_methods_test.dart/0 | {'file_path': 'engine/testing/dart/observatory/vmservice_methods_test.dart', 'repo_id': 'engine', 'token_count': 1580} |
// 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:collection';
import 'dart:io' show stdout;
import 'dart:isolate';
import 'test.dart';
/// A suite of tests, added with the [test] method, which will be run in a
/// following event.
class TestSuite {
/// Creates a new [TestSuite] with logs written to [logger] and callbacks
/// given by [lifecycle].
TestSuite({
StringSink? logger,
Lifecycle? lifecycle,
}) :
_logger = logger ?? stdout,
_lifecycle = lifecycle ?? _DefaultLifecycle();
final Lifecycle _lifecycle;
final StringSink _logger;
bool _testQueuePrimed = false;
final Queue<Test> _testQueue = Queue<Test>();
final Map<String, Test> _runningTests = <String, Test>{};
/// Adds a test to the test suite.
void test(
String name,
dynamic Function() body, {
bool skip = false,
}) {
if (_runningTests.isNotEmpty) {
throw StateError(
'Test "$name" added after tests have started to run. '
'Calls to test() must be synchronous with main().',
);
}
if (skip) {
_logger.writeln('Test "$name": Skipped');
_primeQueue();
return;
}
_pushTest(name, body);
}
void _primeQueue() {
if (!_testQueuePrimed) {
// All tests() must be added synchronously with main, so we can enqueue an
// event to start all tests to run after main() is done.
Timer.run(_startAllTests);
_testQueuePrimed = true;
}
}
void _pushTest(
String name,
dynamic Function() body,
) {
final Test newTest = Test(name, body, logger: _logger);
_testQueue.add(newTest);
newTest.state = TestState.queued;
_primeQueue();
}
void _startAllTests() {
for (final Test t in _testQueue) {
_runningTests[t.name] = t;
t.run(onDone: () {
_runningTests.remove(t.name);
if (_runningTests.isEmpty) {
_lifecycle.onDone(_testQueue);
}
});
}
_lifecycle.onStart();
if (_testQueue.isEmpty) {
_logger.writeln('All tests skipped.');
_lifecycle.onDone(_testQueue);
}
}
}
/// Callbacks for the lifecycle of a [TestSuite].
abstract class Lifecycle {
/// Called after a test suite has started.
void onStart();
/// Called after the last test in a test suite has completed.
void onDone(Queue<Test> tests);
}
class _DefaultLifecycle implements Lifecycle {
final ReceivePort _suitePort = ReceivePort('Suite port');
late Queue<Test> _tests;
@override
void onStart() {
_suitePort.listen((dynamic msg) {
_suitePort.close();
_processResults();
});
}
@override
void onDone(Queue<Test> tests) {
_tests = tests;
_suitePort.sendPort.send(null);
}
void _processResults() {
bool testsSucceeded = true;
for (final Test t in _tests) {
testsSucceeded = testsSucceeded && (t.state == TestState.succeeded);
}
if (!testsSucceeded) {
throw 'A test failed';
}
}
}
| engine/testing/litetest/lib/src/test_suite.dart/0 | {'file_path': 'engine/testing/litetest/lib/src/test_suite.dart', 'repo_id': 'engine', 'token_count': 1194} |
// 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.
class Target {
const Target(this.stringValue, this.intValue, this.targetValue);
final String stringValue;
final int intValue;
final Target? targetValue;
void hit() {
print('$stringValue $intValue');
}
}
class ExtendsTarget extends Target {
const ExtendsTarget(super.stringValue, super.intValue, super.targetValue);
}
class ImplementsTarget implements Target {
const ImplementsTarget(this.stringValue, this.intValue, this.targetValue);
@override
final String stringValue;
@override
final int intValue;
@override
final Target? targetValue;
@override
void hit() {
print('ImplementsTarget - $stringValue $intValue');
}
}
mixin MixableTarget {
String get val;
void hit() {
print(val);
}
}
class MixedInTarget with MixableTarget {
const MixedInTarget(this.val);
@override
final String val;
}
| engine/tools/const_finder/test/fixtures/lib/target.dart/0 | {'file_path': 'engine/tools/const_finder/test/fixtures/lib/target.dart', 'repo_id': 'engine', 'token_count': 317} |
include: ../../analysis_options.yaml
linter:
rules:
avoid_print: false
only_throw_errors: false
public_member_api_docs: false
| engine/tools/licenses/analysis_options.yaml/0 | {'file_path': 'engine/tools/licenses/analysis_options.yaml', 'repo_id': 'engine', 'token_count': 54} |
# 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.
name: path_ops
description: A Dart FFI wrapper for Skia PathKit.
version: 0.0.0
publish_to: none
homepage: https://github.com/flutter/engine/tree/main/tools/path_ops
environment:
sdk: '>=3.2.0-0 <4.0.0'
dev_dependencies:
litetest: any
dependency_overrides:
async_helper:
path: ../../../../third_party/dart/pkg/async_helper
expect:
path: ../../../../third_party/dart/pkg/expect
litetest:
path: ../../../testing/litetest
meta:
path: ../../../../third_party/dart/pkg/meta
smith:
path: ../../../../third_party/dart/pkg/smith
| engine/tools/path_ops/dart/pubspec.yaml/0 | {'file_path': 'engine/tools/path_ops/dart/pubspec.yaml', 'repo_id': 'engine', 'token_count': 279} |
name: web_engine_tester
# Keep the SDK version range in sync with lib/web_ui/pubspec.yaml
environment:
sdk: '>=3.2.0-0 <4.0.0'
dependencies:
js: 0.6.4
stream_channel: 2.1.1
test: 1.24.8
webkit_inspection_protocol: 1.0.0
stack_trace: 1.10.0
ui:
path: ../../lib/web_ui
| engine/web_sdk/web_engine_tester/pubspec.yaml/0 | {'file_path': 'engine/web_sdk/web_engine_tester/pubspec.yaml', 'repo_id': 'engine', 'token_count': 136} |
github: [felangel]
| equatable/.github/FUNDING.yml/0 | {'file_path': 'equatable/.github/FUNDING.yml', 'repo_id': 'equatable', 'token_count': 8} |
// ignore_for_file: avoid_print
import 'package:equatable/equatable.dart';
class Credentials extends Equatable {
const Credentials({required this.username, required this.password});
final String username;
final String password;
@override
List<Object> get props => [username, password];
@override
bool get stringify => false;
}
class EquatableDateTime extends DateTime with EquatableMixin {
EquatableDateTime(
int year, [
int month = 1,
int day = 1,
int hour = 0,
int minute = 0,
int second = 0,
int millisecond = 0,
int microsecond = 0,
]) : super(year, month, day, hour, minute, second, millisecond, microsecond);
@override
List<Object> get props {
return [year, month, day, hour, minute, second, millisecond, microsecond];
}
@override
bool get stringify => true;
}
void main() {
// Extending Equatable
const credentialsA = Credentials(username: 'Joe', password: 'password123');
const credentialsB = Credentials(username: 'Bob', password: 'password!');
const credentialsC = Credentials(username: 'Bob', password: 'password!');
print(credentialsA == credentialsA); // true
print(credentialsB == credentialsB); // true
print(credentialsC == credentialsC); // true
print(credentialsA == credentialsB); // false
print(credentialsB == credentialsC); // true
print(credentialsA); // Credentials
// Equatable Mixin
final dateTimeA = EquatableDateTime(2019);
final dateTimeB = EquatableDateTime(2019, 2, 20, 19, 46);
final dateTimeC = EquatableDateTime(2019, 2, 20, 19, 46);
print(dateTimeA == dateTimeA); // true
print(dateTimeB == dateTimeB); // true
print(dateTimeC == dateTimeC); // true
print(dateTimeA == dateTimeB); // false
print(dateTimeB == dateTimeC); // true
print(dateTimeA); // EquatableDateTime(2019, 1, 1, 0, 0, 0, 0, 0)
}
| equatable/example/main.dart/0 | {'file_path': 'equatable/example/main.dart', 'repo_id': 'equatable', 'token_count': 603} |
import 'package:expect_error/expect_error.dart';
import 'package:test/test.dart';
import '../utils.dart';
Future<void> main() async {
final library = await Library.parseFromStacktrace();
test('can use relative imports based on the file location', () async {
final liveTest = await runTestBody(() async {
await expectLater(library.withCode('''
import 'counter.dart';
void main() {
final counter = Counter();
}
'''), compiles);
});
expectTestPassed(liveTest);
});
test('can manually specify the file path', () async {
final library = Library(
packageName: 'expect_error',
path: 'test/foo.dart',
);
final liveTest = await runTestBody(() async {
await expectLater(library.withCode('''
import 'imports/counter.dart';
void main() {
final counter = Counter();
}
'''), compiles);
});
expectTestPassed(liveTest);
});
}
| expect_error/test/imports/import_test.dart/0 | {'file_path': 'expect_error/test/imports/import_test.dart', 'repo_id': 'expect_error', 'token_count': 308} |
include: package:flame_lint/analysis_options.yaml | fast_noise/analysis_options.yaml/0 | {'file_path': 'fast_noise/analysis_options.yaml', 'repo_id': 'fast_noise', 'token_count': 15} |
import 'package:fast_noise/fast_noise.dart';
enum ParameterNames {
interp,
fractalType,
octaves,
gain,
lacunarity,
cellularDistanceFunction,
cellularReturnType,
}
final _fractalParameters = {
ParameterNames.fractalType,
ParameterNames.octaves,
ParameterNames.gain,
ParameterNames.lacunarity,
};
final Map<NoiseType, Set<ParameterNames>> parametersPerNoiseType = {
NoiseType.cellular: {
ParameterNames.cellularDistanceFunction,
ParameterNames.cellularReturnType,
},
NoiseType.cubic: {},
NoiseType.cubicFractal: _fractalParameters,
NoiseType.perlin: {ParameterNames.interp},
NoiseType.perlinFractal: {ParameterNames.interp, ..._fractalParameters},
NoiseType.simplex: {},
NoiseType.simplexFractal: _fractalParameters,
NoiseType.value: {ParameterNames.interp},
NoiseType.valueFractal: {ParameterNames.interp, ..._fractalParameters},
NoiseType.whiteNoise: {},
};
| fast_noise/example/lib/parameter_names.dart/0 | {'file_path': 'fast_noise/example/lib/parameter_names.dart', 'repo_id': 'fast_noise', 'token_count': 322} |
import 'package:fast_noise/fast_noise.dart';
Noise2And3 buildNoise({
int seed = 1337,
double frequency = .01,
Interp interp = Interp.quintic,
NoiseType noiseType = NoiseType.simplex,
int octaves = 3,
double lacunarity = 2.0,
double gain = .5,
FractalType fractalType = FractalType.fbm,
CellularDistanceFunction cellularDistanceFunction =
CellularDistanceFunction.euclidean,
CellularReturnType cellularReturnType = CellularReturnType.cellValue,
}) {
switch (noiseType) {
case NoiseType.cellular:
return CellularNoise(
seed: seed,
frequency: frequency,
cellularDistanceFunction: cellularDistanceFunction,
cellularReturnType: cellularReturnType,
);
case NoiseType.cubic:
return CubicNoise(
seed: seed,
frequency: frequency,
);
case NoiseType.cubicFractal:
return CubicFractalNoise(
seed: seed,
frequency: frequency,
fractalType: fractalType,
octaves: octaves,
gain: gain,
lacunarity: lacunarity,
);
case NoiseType.perlin:
return PerlinNoise(
seed: seed,
frequency: frequency,
interp: interp,
);
case NoiseType.perlinFractal:
return PerlinFractalNoise(
seed: seed,
frequency: frequency,
interp: interp,
fractalType: fractalType,
octaves: octaves,
gain: gain,
lacunarity: lacunarity,
);
case NoiseType.simplex:
return SimplexNoise(
seed: seed,
frequency: frequency,
);
case NoiseType.simplexFractal:
return SimplexFractalNoise(
seed: seed,
frequency: frequency,
fractalType: fractalType,
octaves: octaves,
gain: gain,
lacunarity: lacunarity,
);
case NoiseType.value:
return ValueNoise(
seed: seed,
frequency: frequency,
interp: interp,
);
case NoiseType.valueFractal:
return ValueFractalNoise(
seed: seed,
frequency: frequency,
interp: interp,
fractalType: fractalType,
octaves: octaves,
gain: gain,
lacunarity: lacunarity,
);
case NoiseType.whiteNoise:
return WhiteNoise(
seed: seed,
);
}
}
| fast_noise/lib/src/noise_factory.dart/0 | {'file_path': 'fast_noise/lib/src/noise_factory.dart', 'repo_id': 'fast_noise', 'token_count': 1041} |
import 'package:finance_ui/src/ui/screens/start_screen.dart';
import 'package:flutter/material.dart';
class FinanceUI extends StatelessWidget {
const FinanceUI({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Finance UI',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
fontFamily: 'poppins',
),
home: const StartScreen(),
);
}
}
| finance-ui/lib/finance_ui.dart/0 | {'file_path': 'finance-ui/lib/finance_ui.dart', 'repo_id': 'finance-ui', 'token_count': 189} |
import 'package:fire_atlas_editor/main_app.dart';
import 'package:fire_atlas_editor/services/storage/storage.dart';
import 'package:fire_atlas_editor/store/store.dart';
import 'package:flutter/material.dart';
import 'package:slices/slices.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final storage = FireAtlasStorage();
final themeValue =
await storage.getConfig(kThemeMode, ThemeMode.light.toString());
final currentTheme = themeValue == ThemeMode.light.toString()
? ThemeMode.light
: ThemeMode.dark;
final store = SlicesStore<FireAtlasState>(
FireAtlasState.empty(
currentTheme: currentTheme,
),
);
runApp(FireAtlasApp(store: store));
}
| fire-atlas/fire_atlas_editor/lib/main.dart/0 | {'file_path': 'fire-atlas/fire_atlas_editor/lib/main.dart', 'repo_id': 'fire-atlas', 'token_count': 250} |
import 'package:fire_atlas_editor/store/actions/editor_actions.dart';
import 'package:fire_atlas_editor/store/store.dart';
import 'package:fire_atlas_editor/utils/validators.dart';
import 'package:fire_atlas_editor/widgets/button.dart';
import 'package:fire_atlas_editor/widgets/image_selection_container.dart';
import 'package:fire_atlas_editor/widgets/input_text_row.dart';
import 'package:fire_atlas_editor/widgets/text.dart';
import 'package:flutter/material.dart' hide Image;
import 'package:slices/slices.dart';
class AtlasOptionsContainer extends StatefulWidget {
final void Function() onCancel;
final Function(String, String, double, double) onConfirm;
const AtlasOptionsContainer({
required this.onCancel,
required this.onConfirm,
super.key,
});
@override
State createState() => _AtlasOptionsContainerState();
}
class _AtlasOptionsContainerState extends State<AtlasOptionsContainer> {
String? _imageData;
String? _imageName;
late final TextEditingController atlasNameController;
late final TextEditingController tileWidthController;
late final TextEditingController tileHeightController;
@override
void initState() {
super.initState();
atlasNameController = TextEditingController();
tileWidthController = TextEditingController();
tileHeightController = TextEditingController();
}
@override
void dispose() {
atlasNameController.dispose();
tileWidthController.dispose();
tileHeightController.dispose();
super.dispose();
}
void _confirm() {
final store = SlicesProvider.of<FireAtlasState>(context);
final tileWidthRaw = tileWidthController.text;
final tileHeightRaw = tileHeightController.text;
final atlasName = atlasNameController.text;
if (atlasName.isEmpty) {
store.dispatch(
CreateMessageAction(
message: 'Atlas name is required',
type: MessageType.ERROR,
),
);
return;
}
if (tileWidthRaw.isEmpty) {
store.dispatch(
CreateMessageAction(
message: 'Tile Width is required',
type: MessageType.ERROR,
),
);
return;
}
if (tileHeightRaw.isEmpty) {
store.dispatch(
CreateMessageAction(
message: 'Tile Height is required',
type: MessageType.ERROR,
),
);
return;
}
if (tileWidthRaw.isNotEmpty && !isValidNumber(tileWidthRaw)) {
store.dispatch(
CreateMessageAction(
message: 'Tile Width must be a number',
type: MessageType.ERROR,
),
);
return;
}
if (tileHeightRaw.isNotEmpty && !isValidNumber(tileHeightRaw)) {
store.dispatch(
CreateMessageAction(
message: 'Tile Height must be a number',
type: MessageType.ERROR,
),
);
return;
}
if (_imageData == null) {
store.dispatch(
CreateMessageAction(
message: 'An image must be selected',
type: MessageType.ERROR,
),
);
return;
}
widget.onConfirm(
atlasName,
_imageData!,
double.parse(tileWidthRaw),
double.parse(tileHeightRaw),
);
}
void _cancel() {
widget.onCancel();
}
@override
Widget build(BuildContext ctx) {
return Container(
width: 600,
height: 400,
color: Theme.of(ctx).dialogBackgroundColor,
padding: const EdgeInsets.all(20),
child: Column(
children: [
const FTitle(title: 'New atlas'),
const SizedBox(height: 20),
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
flex: 5,
child: Column(
children: [
InputTextRow(
label: 'Atlas name:',
inputController: atlasNameController,
),
const SizedBox(height: 40),
InputTextRow(
label: 'Tile Width:',
inputController: tileWidthController,
),
const SizedBox(height: 40),
InputTextRow(
label: 'Tile Height:',
inputController: tileHeightController,
),
],
),
),
Expanded(
flex: 5,
child: ImageSelectionContainer(
imageData: _imageData,
imageName: _imageName,
onSelectImage: (imageName, imageData) {
setState(() {
_imageData = imageData;
_imageName = imageName;
});
},
),
),
],
),
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FButton(
label: 'Cancel',
onSelect: _cancel,
),
const SizedBox(width: 20),
FButton(
label: 'Ok',
onSelect: _confirm,
),
],
),
],
),
);
}
}
| fire-atlas/fire_atlas_editor/lib/screens/open_screen/widgets/atlas_options_container.dart/0 | {'file_path': 'fire-atlas/fire_atlas_editor/lib/screens/open_screen/widgets/atlas_options_container.dart', 'repo_id': 'fire-atlas', 'token_count': 2679} |
import 'package:flutter/material.dart';
class FButton extends StatelessWidget {
final bool selected;
final String label;
final bool disabled;
final double? width;
final EdgeInsets? padding;
final void Function() onSelect;
const FButton({
required this.label,
required this.onSelect,
super.key,
this.selected = false,
this.disabled = false,
this.width,
this.padding,
});
@override
Widget build(BuildContext ctx) {
final theme = Theme.of(ctx);
final color = selected ? theme.primaryColor : theme.indicatorColor;
return Container(
padding: padding,
child: Opacity(
opacity: disabled ? 0.6 : 1,
child: ElevatedButton(
style: ButtonStyle(backgroundColor: MaterialStateProperty.all(color)),
onPressed: () {
if (!disabled) {
onSelect();
}
},
child: Container(
width: width,
child: Text(
label,
textAlign: TextAlign.center,
),
),
),
),
);
}
}
| fire-atlas/fire_atlas_editor/lib/widgets/button.dart/0 | {'file_path': 'fire-atlas/fire_atlas_editor/lib/widgets/button.dart', 'repo_id': 'fire-atlas', 'token_count': 484} |
import 'package:flutter/material.dart';
import 'package:flame/game.dart';
import 'package:flame/flare_animation.dart';
import 'package:flame/components/flare_component.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Home(),
routes: {
'/game': (BuildContext context) => GameWidget(),
'/base-game': (BuildContext context) => BaseGameWidget(),
}
);
}
}
class FlareGame extends Game {
FlareAnimation _flareAnimation;
FlareGame() {
_start();
}
void _start() async {
_flareAnimation = await FlareAnimation.load("assets/Bob_Minion.flr");
_flareAnimation.updateAnimation("Stand");
_flareAnimation
..width = 306
..height = 228;
}
@override
void update(double dt) {
if (_flareAnimation != null)
_flareAnimation.update(dt);
}
@override
void render(Canvas canvas) {
canvas.save();
if (_flareAnimation != null) {
canvas.translate(200, 100);
canvas.rotate(1.5);
_flareAnimation.render(canvas, x: 0, y: 0);
}
canvas.restore();
}
}
class FlareBaseGame extends BaseGame {
bool debugMode() => true;
FlareBaseGame() {
final flareAnimation =
FlareComponent("assets/Bob_Minion.flr", "Stand", 306, 228)
..x = 200
..y = 100
..angle = 1.5;
add(flareAnimation);
}
}
class GameWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FlareGame().widget;
}
}
class BaseGameWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FlareBaseGame().widget;
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: [
SizedBox(height: 50),
RaisedButton(
child: Text('Game'),
onPressed: () {
Navigator.of(context).pushNamed('/game');
}
),
RaisedButton(
child: Text('BaseGame'),
onPressed: () {
Navigator.of(context).pushNamed('/base-game');
}
),
]
);
}
}
| flame-examples/flare_rotation/lib/main.dart/0 | {'file_path': 'flame-examples/flare_rotation/lib/main.dart', 'repo_id': 'flame-examples', 'token_count': 1004} |
import 'package:flutter/material.dart';
import 'package:flame/flame.dart';
import './game.dart';
void main() async {
final screenSize = await Flame.util.initialDimensions();
runApp(IsoGame(screenSize).widget);
}
| flame-examples/isometric/lib/main.dart/0 | {'file_path': 'flame-examples/isometric/lib/main.dart', 'repo_id': 'flame-examples', 'token_count': 73} |
import 'dart:ui';
import 'package:flame/experimental.dart';
import 'package:flame/extensions.dart';
import 'package:flame_forge2d/flame_forge2d.dart' hide Particle, World;
import 'package:flutter/material.dart' hide Image, Gradient;
import 'package:padracing/game_colors.dart';
import 'package:padracing/lap_line.dart';
import 'package:padracing/padracing_game.dart';
import 'package:padracing/tire.dart';
class Car extends BodyComponent<PadRacingGame> {
Car({required this.playerNumber, required this.cameraComponent})
: super(
priority: 3,
paint: Paint()..color = colors[playerNumber],
);
static final colors = [
GameColors.green.color,
GameColors.blue.color,
];
late final List<Tire> tires;
final ValueNotifier<int> lapNotifier = ValueNotifier<int>(1);
final int playerNumber;
final Set<LapLine> passedStartControl = {};
final CameraComponent cameraComponent;
late final Image _image;
final size = const Size(6, 10);
final scale = 10.0;
late final _renderPosition = -size.toOffset() / 2;
late final _scaledRect = (size * scale).toRect();
late final _renderRect = _renderPosition & size;
final vertices = <Vector2>[
Vector2(1.5, -5.0),
Vector2(3.0, -2.5),
Vector2(2.8, 0.5),
Vector2(1.0, 5.0),
Vector2(-1.0, 5.0),
Vector2(-2.8, 0.5),
Vector2(-3.0, -2.5),
Vector2(-1.5, -5.0),
];
@override
Future<void> onLoad() async {
await super.onLoad();
final recorder = PictureRecorder();
final canvas = Canvas(recorder, _scaledRect);
final path = Path();
final bodyPaint = Paint()..color = paint.color;
for (var i = 0.0; i < _scaledRect.width / 4; i++) {
bodyPaint.color = bodyPaint.color.darken(0.1);
path.reset();
final offsetVertices = vertices
.map(
(v) =>
v.toOffset() * scale -
Offset(i * v.x.sign, i * v.y.sign) +
_scaledRect.bottomRight / 2,
)
.toList();
path.addPolygon(offsetVertices, true);
canvas.drawPath(path, bodyPaint);
}
final picture = recorder.endRecording();
_image = await picture.toImage(
_scaledRect.width.toInt(),
_scaledRect.height.toInt(),
);
}
@override
Body createBody() {
final startPosition =
Vector2(20, 30) + Vector2(15, 0) * playerNumber.toDouble();
final def = BodyDef()
..type = BodyType.dynamic
..position = startPosition;
final body = world.createBody(def)
..userData = this
..angularDamping = 3.0;
final shape = PolygonShape()..set(vertices);
final fixtureDef = FixtureDef(shape)
..density = 0.2
..restitution = 2.0;
body.createFixture(fixtureDef);
final jointDef = RevoluteJointDef()
..bodyA = body
..enableLimit = true
..lowerAngle = 0.0
..upperAngle = 0.0
..localAnchorB.setZero();
tires = List.generate(4, (i) {
final isFrontTire = i <= 1;
final isLeftTire = i.isEven;
return Tire(
car: this,
pressedKeys: gameRef.pressedKeySets[playerNumber],
isFrontTire: isFrontTire,
isLeftTire: isLeftTire,
jointDef: jointDef,
isTurnableTire: isFrontTire,
);
});
gameRef.cameraWorld.addAll(tires);
return body;
}
@override
void update(double dt) {
cameraComponent.viewfinder.position = body.position;
}
@override
void render(Canvas canvas) {
canvas.drawImageRect(
_image,
_scaledRect,
_renderRect,
paint,
);
}
@override
void onRemove() {
for (final tire in tires) {
tire.removeFromParent();
}
}
}
| flame/examples/games/padracing/lib/car.dart/0 | {'file_path': 'flame/examples/games/padracing/lib/car.dart', 'repo_id': 'flame', 'token_count': 1571} |
name: trex_game
description: A clone of the classic browser T-Rex game.
homepage: https://github.com/flame-engine/flame/tree/main/examples/games/trex/
publish_to: 'none'
version: 0.1.0
environment:
sdk: ">=2.17.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flame: ^1.2.0
flutter:
sdk: flutter
dev_dependencies:
flame_lint: ^0.0.1
flutter:
uses-material-design: true
assets:
- assets/images/
| flame/examples/games/trex/pubspec.yaml/0 | {'file_path': 'flame/examples/games/trex/pubspec.yaml', 'repo_id': 'flame', 'token_count': 181} |
import 'package:examples/stories/bridge_libraries/forge2d/utils/balls.dart';
import 'package:examples/stories/bridge_libraries/forge2d/utils/boundaries.dart';
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart' hide Draggable;
class DraggableExample extends Forge2DGame with HasDraggables {
static const description = '''
In this example we use Flame's normal `Draggable` mixin to give impulses to
a ball when we are dragging it around. If you are interested in dragging
bodies around, also have a look at the MouseJointExample.
''';
DraggableExample() : super(gravity: Vector2.all(0.0));
@override
Future<void> onLoad() async {
final boundaries = createBoundaries(this);
boundaries.forEach(add);
final center = screenToWorld(camera.viewport.effectiveSize / 2);
add(DraggableBall(center));
}
}
class DraggableBall extends Ball with Draggable {
DraggableBall(super.position) : super(radius: 5) {
originalPaint = Paint()..color = Colors.amber;
paint = originalPaint;
}
@override
bool onDragStart(DragStartInfo info) {
paint = randomPaint();
return true;
}
@override
bool onDragUpdate(DragUpdateInfo info) {
body.applyLinearImpulse(info.delta.game * 1000);
return true;
}
@override
bool onDragEnd(DragEndInfo info) {
paint = originalPaint;
return true;
}
}
| flame/examples/lib/stories/bridge_libraries/forge2d/draggable_example.dart/0 | {'file_path': 'flame/examples/lib/stories/bridge_libraries/forge2d/draggable_example.dart', 'repo_id': 'flame', 'token_count': 508} |
import 'dart:ui';
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flame/palette.dart';
class FixedResolutionExample extends FlameGame
with ScrollDetector, ScaleDetector {
static const description = '''
This example shows how to create a viewport with a fixed resolution.
It is useful when you want the visible part of the game to be the same on
all devices no matter the actual screen size of the device.
Resize the window or change device orientation to see the difference.
''';
final Vector2 viewportResolution;
FixedResolutionExample({
required this.viewportResolution,
});
@override
Future<void> onLoad() async {
final flameSprite = await loadSprite('layers/player.png');
camera.viewport = FixedResolutionViewport(viewportResolution);
camera.setRelativeOffset(Anchor.topLeft);
camera.speed = 1;
add(Background());
add(
SpriteComponent(
position: camera.viewport.effectiveSize / 2,
sprite: flameSprite,
size: Vector2(149, 211),
)..anchor = Anchor.center,
);
}
}
class Background extends PositionComponent with HasGameRef {
@override
int priority = -1;
late Paint white;
late final Rect hugeRect;
Background() : super(size: Vector2.all(100000));
@override
Future<void> onLoad() async {
white = BasicPalette.white.paint();
hugeRect = size.toRect();
}
@override
void render(Canvas c) {
c.drawRect(hugeRect, white);
}
}
| flame/examples/lib/stories/camera_and_viewport/fixed_resolution_example.dart/0 | {'file_path': 'flame/examples/lib/stories/camera_and_viewport/fixed_resolution_example.dart', 'repo_id': 'flame', 'token_count': 519} |
import 'dart:math';
import 'package:flame/effects.dart';
import 'package:flame/game.dart';
import 'package:flame/geometry.dart';
import 'package:flutter/material.dart';
class MoveEffectExample extends FlameGame {
static const description = '''
Top square has `MoveEffect.to` effect that makes the component move along a
straight line back and forth. The effect uses a non-linear progression
curve, which makes the movement non-uniform.
The middle green square has a combination of two movement effects: a
`MoveEffect.to` and a `MoveEffect.by` which forces it to periodically jump.
The purple square executes a sequence of shake effects.
At the bottom there are 60 more components which demonstrate movement along
an arbitrary path using `MoveEffect.along`.
''';
@override
void onMount() {
const tau = Transform2D.tau;
camera.viewport = FixedResolutionViewport(Vector2(400, 600));
final paint1 = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 5.0
..color = Colors.deepOrange;
final paint2 = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 5.0
..color = Colors.greenAccent;
final paint3 = Paint()..color = const Color(0xffb372dc);
// Red square, moving back and forth
add(
RectangleComponent.square(
position: Vector2(20, 50),
size: 20,
paint: paint1,
)..add(
MoveEffect.to(
Vector2(380, 50),
EffectController(
duration: 3,
reverseDuration: 3,
infinite: true,
curve: Curves.easeOut,
),
),
),
);
// Green square, moving and jumping
add(
RectangleComponent.square(
position: Vector2(20, 150),
size: 20,
paint: paint2,
)
..add(
MoveEffect.to(
Vector2(380, 150),
EffectController(
duration: 3,
reverseDuration: 3,
infinite: true,
),
),
)
..add(
MoveEffect.by(
Vector2(0, -50),
EffectController(
duration: 0.25,
reverseDuration: 0.25,
startDelay: 1,
atMinDuration: 2,
curve: Curves.ease,
infinite: true,
),
),
),
);
add(
RectangleComponent.square(
size: 15,
position: Vector2(40, 240),
paint: paint3,
)..add(
SequenceEffect(
[
MoveEffect.by(
Vector2(5, 0),
NoiseEffectController(duration: 1, frequency: 20),
),
MoveEffect.by(Vector2.zero(), LinearEffectController(2)),
MoveEffect.by(
Vector2(0, 10),
NoiseEffectController(duration: 1, frequency: 10),
),
],
infinite: true,
),
),
);
final path1 = Path()..moveTo(200, 250);
for (var i = 1; i <= 5; i++) {
final x = 200 + 100 * sin(i * tau * 2 / 5);
final y = 350 - 100 * cos(i * tau * 2 / 5);
path1.lineTo(x, y);
}
for (var i = 0; i < 40; i++) {
add(
CircleComponent(radius: 5)
..position = Vector2(0, -1000)
..add(
MoveAlongPathEffect(
path1,
EffectController(
duration: 10,
startDelay: i * 0.2,
infinite: true,
),
absolute: true,
),
),
);
}
final path2 = Path()..addOval(const Rect.fromLTRB(80, 230, 320, 470));
for (var i = 0; i < 20; i++) {
add(
RectangleComponent.square(size: 10)
..paint = (Paint()..color = Colors.tealAccent)
..add(
MoveAlongPathEffect(
path2,
EffectController(
duration: 6,
startDelay: i * 0.3,
infinite: true,
),
oriented: true,
),
),
);
}
}
}
| flame/examples/lib/stories/effects/move_effect_example.dart/0 | {'file_path': 'flame/examples/lib/stories/effects/move_effect_example.dart', 'repo_id': 'flame', 'token_count': 2109} |
import 'package:examples/stories/input/joystick_player.dart';
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame/palette.dart';
import 'package:flutter/painting.dart';
class JoystickExample extends FlameGame with HasDraggables {
static const String description = '''
In this example we showcase how to use the joystick by creating simple
`CircleComponent`s that serve as the joystick's knob and background.
Steer the player by using the joystick.
''';
late final JoystickPlayer player;
late final JoystickComponent joystick;
@override
Future<void> onLoad() async {
final knobPaint = BasicPalette.blue.withAlpha(200).paint();
final backgroundPaint = BasicPalette.blue.withAlpha(100).paint();
joystick = JoystickComponent(
knob: CircleComponent(radius: 30, paint: knobPaint),
background: CircleComponent(radius: 100, paint: backgroundPaint),
margin: const EdgeInsets.only(left: 40, bottom: 40),
);
player = JoystickPlayer(joystick);
add(player);
add(joystick);
}
}
| flame/examples/lib/stories/input/joystick_example.dart/0 | {'file_path': 'flame/examples/lib/stories/input/joystick_example.dart', 'repo_id': 'flame', 'token_count': 345} |
import 'package:dashbook/dashbook.dart';
import 'package:examples/commons/commons.dart';
import 'package:examples/stories/parallax/advanced_parallax_example.dart';
import 'package:examples/stories/parallax/animation_parallax_example.dart';
import 'package:examples/stories/parallax/basic_parallax_example.dart';
import 'package:examples/stories/parallax/component_parallax_example.dart';
import 'package:examples/stories/parallax/no_fcs_parallax_example.dart';
import 'package:examples/stories/parallax/sandbox_layer_parallax_example.dart';
import 'package:examples/stories/parallax/small_parallax_example.dart';
import 'package:flame/game.dart';
import 'package:flame/parallax.dart';
import 'package:flutter/painting.dart';
void addParallaxStories(Dashbook dashbook) {
dashbook.storiesOf('Parallax')
..add(
'Basic',
(_) => GameWidget(game: BasicParallaxExample()),
codeLink: baseLink('parallax/basic_parallax_example.dart'),
info: BasicParallaxExample.description,
)
..add(
'Component',
(_) => GameWidget(game: ComponentParallaxExample()),
codeLink: baseLink('parallax/component_parallax_example.dart'),
info: ComponentParallaxExample.description,
)
..add(
'Animation',
(_) => GameWidget(game: AnimationParallaxExample()),
codeLink: baseLink('parallax/animation_parallax_example.dart'),
info: AnimationParallaxExample.description,
)
..add(
'Non-fullscreen',
(_) => GameWidget(game: SmallParallaxExample()),
codeLink: baseLink('parallax/small_parallax_example.dart'),
info: SmallParallaxExample.description,
)
..add(
'No FCS',
(_) => GameWidget(game: NoFCSParallaxExample()),
codeLink: baseLink('parallax/no_fcs_parallax_example.dart'),
info: NoFCSParallaxExample.description,
)
..add(
'Advanced',
(_) => GameWidget(game: AdvancedParallaxExample()),
codeLink: baseLink('parallax/advanced_parallax_example.dart'),
info: AdvancedParallaxExample.description,
)
..add(
'Layer sandbox',
(context) {
return GameWidget(
game: SandboxLayerParallaxExample(
planeSpeed: Vector2(
context.numberProperty('plane x speed', 0),
context.numberProperty('plane y speed', 0),
),
planeRepeat: context.listProperty(
'plane repeat strategy',
ImageRepeat.noRepeat,
ImageRepeat.values,
),
planeFill: context.listProperty(
'plane fill strategy',
LayerFill.none,
LayerFill.values,
),
planeAlignment: context.listProperty(
'plane alignment strategy',
Alignment.center,
[
Alignment.topLeft,
Alignment.topRight,
Alignment.center,
Alignment.topCenter,
Alignment.centerLeft,
Alignment.bottomLeft,
Alignment.bottomRight,
Alignment.bottomCenter,
],
),
),
);
},
codeLink: baseLink('parallax/sandbox_layer_parallax_example.dart'),
info: SandboxLayerParallaxExample.description,
);
}
| flame/examples/lib/stories/parallax/parallax.dart/0 | {'file_path': 'flame/examples/lib/stories/parallax/parallax.dart', 'repo_id': 'flame', 'token_count': 1486} |
import 'package:dashbook/dashbook.dart';
import 'package:examples/commons/commons.dart';
import 'package:examples/stories/sprites/base64_sprite_example.dart';
import 'package:examples/stories/sprites/basic_sprite_example.dart';
import 'package:examples/stories/sprites/sprite_group_example.dart';
import 'package:examples/stories/sprites/spritebatch_example.dart';
import 'package:examples/stories/sprites/spritebatch_load_example.dart';
import 'package:examples/stories/sprites/spritesheet_example.dart';
import 'package:flame/game.dart';
void addSpritesStories(Dashbook dashbook) {
dashbook.storiesOf('Sprites')
..add(
'Basic Sprite',
(_) => GameWidget(game: BasicSpriteExample()),
codeLink: baseLink('sprites/basic_sprite_example.dart'),
info: BasicSpriteExample.description,
)
..add(
'Base64 Sprite',
(_) => GameWidget(game: Base64SpriteExample()),
codeLink: baseLink('sprites/base64_sprite_example.dart'),
info: Base64SpriteExample.description,
)
..add(
'Spritesheet',
(_) => GameWidget(game: SpritesheetExample()),
codeLink: baseLink('sprites/spritesheet_example.dart'),
info: SpritesheetExample.description,
)
..add(
'Spritebatch',
(_) => GameWidget(game: SpritebatchExample()),
codeLink: baseLink('sprites/spritebatch_example.dart'),
info: SpritebatchExample.description,
)
..add(
'Spritebatch Auto Load',
(_) => GameWidget(game: SpritebatchLoadExample()),
codeLink: baseLink('sprites/spritebatch_load_example.dart'),
info: SpritebatchLoadExample.description,
)
..add(
'SpriteGroup',
(_) => GameWidget(game: SpriteGroupExample()),
codeLink: baseLink('sprites/sprite_group_example.dart'),
info: SpriteGroupExample.description,
);
}
| flame/examples/lib/stories/sprites/sprites.dart/0 | {'file_path': 'flame/examples/lib/stories/sprites/sprites.dart', 'repo_id': 'flame', 'token_count': 706} |
import 'dart:math';
import 'package:dashbook/dashbook.dart';
import 'package:flame/widgets.dart';
import 'package:flutter/material.dart';
final anchorOptions = Anchor.values.map((e) => e.name).toList();
Widget spriteWidgetBuilder(DashbookContext ctx) {
return Container(
width: ctx.numberProperty('container width', 400),
height: ctx.numberProperty('container height', 200),
decoration: BoxDecoration(border: Border.all(color: Colors.amber)),
child: SpriteWidget.asset(
path: 'shield.png',
angle: pi / 180 * ctx.numberProperty('angle (deg)', 0),
anchor: Anchor.valueOf(
ctx.listProperty('anchor', 'center', anchorOptions),
),
),
);
}
| flame/examples/lib/stories/widgets/sprite_widget_example.dart/0 | {'file_path': 'flame/examples/lib/stories/widgets/sprite_widget_example.dart', 'repo_id': 'flame', 'token_count': 251} |
@Deprecated('Use the cache.dart file instead, will be removed in v1.3.0')
export 'src/cache/assets_cache.dart';
@Deprecated('Use the cache.dart file instead, will be removed in v1.3.0')
export 'src/cache/images.dart';
| flame/packages/flame/lib/assets.dart/0 | {'file_path': 'flame/packages/flame/lib/assets.dart', 'repo_id': 'flame', 'token_count': 76} |
export 'src/anchor.dart';
export 'src/particles/accelerated_particle.dart';
export 'src/particles/animation_particle.dart';
export 'src/particles/circle_particle.dart';
export 'src/particles/component_particle.dart';
export 'src/particles/composed_particle.dart';
export 'src/particles/computed_particle.dart';
export 'src/particles/curved_particle.dart';
export 'src/particles/image_particle.dart';
export 'src/particles/moving_particle.dart';
export 'src/particles/paint_particle.dart';
export 'src/particles/particle.dart';
export 'src/particles/rotating_particle.dart';
export 'src/particles/scaled_particle.dart';
export 'src/particles/sprite_particle.dart';
export 'src/particles/translated_particle.dart';
| flame/packages/flame/lib/particles.dart/0 | {'file_path': 'flame/packages/flame/lib/particles.dart', 'repo_id': 'flame', 'token_count': 260} |
// ignore_for_file: comment_references
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
/// A [Hitbox] in the shape of a rectangle (a simplified polygon).
class RectangleHitbox extends RectangleComponent with ShapeHitbox {
@override
final bool shouldFillParent;
RectangleHitbox({
super.position,
super.size,
super.angle,
super.anchor,
super.priority,
}) : shouldFillParent = size == null && position == null;
/// With this constructor you define the [RectangleHitbox] in relation to
/// the [parentSize]. For example having [relation] as of (0.8, 0.5) would
/// create a rectangle that fills 80% of the width and 50% of the height of
/// [parentSize].
RectangleHitbox.relative(
super.relation, {
super.position,
required super.parentSize,
double super.angle,
super.anchor,
}) : shouldFillParent = false,
super.relative(
shrinkToBounds: true,
);
@override
void fillParent() {
refreshVertices(
newVertices: RectangleComponent.sizeToVertices(size, anchor),
);
}
}
| flame/packages/flame/lib/src/collisions/hitboxes/rectangle_hitbox.dart/0 | {'file_path': 'flame/packages/flame/lib/src/collisions/hitboxes/rectangle_hitbox.dart', 'repo_id': 'flame', 'token_count': 378} |
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flutter/widgets.dart' show EdgeInsets;
import 'package:meta/meta.dart';
/// The [ComponentViewportMargin] positions itself by a margin to the edge of
/// the [Viewport] 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.
mixin ComponentViewportMargin on PositionComponent, HasGameRef {
@override
PositionType positionType = PositionType.viewport;
/// Instead of setting a position of the [PositionComponent] that uses
/// [ComponentViewportMargin] a margin from the edges of the viewport can be
/// used instead.
EdgeInsets? margin;
@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
@mustCallSuper
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/mixins/component_viewport_margin.dart/0 | {'file_path': 'flame/packages/flame/lib/src/components/mixins/component_viewport_margin.dart', 'repo_id': 'flame', 'token_count': 932} |
/// Used to define which coordinate system a given top-level component respects.
///
/// Normally components live in the "game" coordinate system, which just means
/// they respect both the camera and viewport.
enum PositionType {
/// Default type. Respects camera and viewport (applied on top of widget).
game,
/// Respects viewport only (ignores camera) (applied on top of widget).
viewport,
/// Position in relation to the coordinate system of the Flutter game widget
/// (i.e. the raw canvas).
widget,
}
| flame/packages/flame/lib/src/components/position_type.dart/0 | {'file_path': 'flame/packages/flame/lib/src/components/position_type.dart', 'repo_id': 'flame', 'token_count': 134} |
import 'package:flame/src/effects/controllers/effect_controller.dart';
import 'package:flame/src/effects/effect.dart';
/// An effect controller that waits for [delay] seconds before running the
/// child controller. While waiting, the progress will be reported at 0.
class DelayedEffectController extends EffectController {
DelayedEffectController(EffectController child, {required this.delay})
: assert(delay >= 0, 'Delay must be non-negative: $delay'),
_child = child,
_timer = 0,
super.empty();
final EffectController _child;
final double delay;
double _timer;
@override
bool get isRandom => _child.isRandom;
@override
bool get started => _timer == delay;
@override
bool get completed => started && _child.completed;
@override
double get progress => started ? _child.progress : 0;
@override
double? get duration {
final d = _child.duration;
return d == null ? null : d + delay;
}
@override
double advance(double dt) {
if (_timer == delay) {
return _child.advance(dt);
}
_timer += dt;
if (_timer > delay) {
final t = _child.advance(_timer - delay);
_timer = delay;
return t;
} else {
return 0;
}
}
@override
double recede(double dt) {
if (_timer == delay) {
_timer -= _child.recede(dt);
} else {
_timer -= dt;
}
if (_timer < 0) {
final leftoverTime = -_timer;
_timer = 0;
return leftoverTime;
}
return 0;
}
@override
void setToStart() {
_timer = 0;
}
@override
void setToEnd() {
_timer = delay;
_child.setToEnd();
}
@override
void onMount(Effect parent) => _child.onMount(parent);
}
| flame/packages/flame/lib/src/effects/controllers/delayed_effect_controller.dart/0 | {'file_path': 'flame/packages/flame/lib/src/effects/controllers/delayed_effect_controller.dart', 'repo_id': 'flame', 'token_count': 640} |
import 'package:flame/src/effects/effect.dart';
/// Mixin adds field [target] of type [T] to an [Effect]. The target can be
/// either set explicitly by the effect class, or acquired automatically from
/// the effect's parent when mounting.
///
/// The type [T] can be either a Component subclass, or one of the property
/// providers defined in "provider_interfaces.dart".
mixin EffectTarget<T> on Effect {
T get target => _target!;
T? _target;
set target(T? value) {
_target = value;
}
@override
void onMount() {
if (_target == null) {
final parent = ancestors().firstWhere((c) => c is! Effect);
if (parent is! T) {
throw UnsupportedError('Can only apply this effect to $T');
}
_target = parent as T;
}
}
}
| flame/packages/flame/lib/src/effects/effect_target.dart/0 | {'file_path': 'flame/packages/flame/lib/src/effects/effect_target.dart', 'repo_id': 'flame', 'token_count': 260} |
import 'package:flame/src/events/interfaces/multi_drag_listener.dart';
import 'package:flame/src/game/mixins/game.dart';
import 'package:flutter/gestures.dart';
import 'package:meta/meta.dart';
/// Helper class to convert drag API as expected by the
/// [ImmediateMultiDragGestureRecognizer] into the API expected by Flame's
/// [MultiDragListener].
@internal
class FlameDragAdapter implements Drag {
FlameDragAdapter(this._game, Offset startPoint) {
start(startPoint);
}
final MultiDragListener _game;
late final int _id;
static int _globalIdCounter = 0;
void start(Offset point) {
final event = DragStartDetails(
sourceTimeStamp: Duration.zero,
globalPosition: point,
localPosition: (_game as Game).renderBox.globalToLocal(point),
);
_id = _globalIdCounter++;
_game.handleDragStart(_id, event);
}
@override
void update(DragUpdateDetails event) => _game.handleDragUpdate(_id, event);
@override
void end(DragEndDetails event) => _game.handleDragEnd(_id, event);
@override
void cancel() => _game.handleDragCancel(_id);
}
| flame/packages/flame/lib/src/events/flame_drag_adapter.dart/0 | {'file_path': 'flame/packages/flame/lib/src/events/flame_drag_adapter.dart', 'repo_id': 'flame', 'token_count': 360} |
import 'package:flame/extensions.dart';
import 'package:flame/src/events/component_mixins/tap_callbacks.dart';
import 'package:flame/src/events/flame_game_mixins/has_tappable_components.dart';
import 'package:flame/src/events/messages/position_event.dart';
import 'package:flame/src/events/messages/tap_cancel_event.dart';
import 'package:flame/src/events/messages/tap_up_event.dart';
import 'package:flame/src/game/mixins/game.dart';
import 'package:flame/src/gestures/events.dart';
import 'package:flutter/gestures.dart';
/// The event propagated through the Flame engine when the user starts a touch
/// on the game canvas.
///
/// This is a [PositionEvent], where the position is the point of touch.
///
/// In order for a component to be eligible to receive this event, it must add
/// the [TapCallbacks] mixin, and the game object should have the
/// [HasTappableComponents] mixin.
class TapDownEvent extends PositionEvent {
TapDownEvent(this.pointerId, TapDownDetails details)
: deviceKind = details.kind ?? PointerDeviceKind.unknown,
super(
canvasPosition: details.localPosition.toVector2(),
devicePosition: details.globalPosition.toVector2(),
);
/// The unique identifier of the tap event.
///
/// Subsequent [TapUpEvent] or [TapCancelEvent] will carry the same pointer
/// id. This allows distinguishing multiple taps that may occur simultaneously
/// on the same component.
final int pointerId;
final PointerDeviceKind deviceKind;
/// Converts this event into the legacy [TapDownInfo] representation.
TapDownInfo asInfo(Game game) {
return TapDownInfo.fromDetails(
game,
TapDownDetails(
globalPosition: devicePosition.toOffset(),
localPosition: canvasPosition.toOffset(),
kind: deviceKind,
),
);
}
}
| flame/packages/flame/lib/src/events/messages/tap_down_event.dart/0 | {'file_path': 'flame/packages/flame/lib/src/events/messages/tap_down_event.dart', 'repo_id': 'flame', 'token_count': 587} |
import 'dart:ui';
import 'package:flame/src/anchor.dart';
import 'package:flame/src/components/component.dart';
import 'package:flame/src/effects/provider_interfaces.dart';
import 'package:flame/src/experimental/camera_component.dart';
import 'package:meta/meta.dart';
import 'package:vector_math/vector_math_64.dart';
/// [Viewport] is a part of a [CameraComponent] system.
///
/// The viewport describes a "window" through which the underlying game world
/// is observed. At the same time, the viewport is agnostic of the game world,
/// and only contain properties that describe the "window" itself. These
/// properties are: the window's size, shape, and position on the screen.
///
/// There are several implementations of [Viewport], which differ by their
/// shape, and also by their behavior in response to changes to the canvas size.
/// Users may also create their own implementations.
///
/// A viewport establishes its own local coordinate system, with the origin at
/// the top left corner of the viewport's bounding box.
abstract class Viewport extends Component
implements AnchorProvider, PositionProvider, SizeProvider {
Viewport({super.children});
/// Position of the viewport's anchor in the parent's coordinate frame.
///
/// Changing this position will move the viewport around the screen, but will
/// not affect which portion of the game world is visible. Thus, the game
/// world will appear as a static picture inside the viewport.
@override
Vector2 get position => _position;
final Vector2 _position = Vector2.zero();
@override
set position(Vector2 value) => _position.setFrom(value);
/// The logical "center" of the viewport.
///
/// This point will be used to establish the placement of the viewport in the
/// parent's coordinate frame.
@override
Anchor anchor = Anchor.topLeft;
/// Size of the viewport, i.e. its width and height.
///
/// This property represents the bounding box of the viewport. If the viewport
/// is rectangular in shape, then [size] describes the dimensions of that
/// rectangle. If the viewport has any other shape (for example, circular),
/// then [size] describes the dimensions of the bounding box of the viewport.
///
/// Changing the size at runtime triggers the [onViewportResize] event. The
/// size cannot be negative.
@override
Vector2 get size => _size;
final Vector2 _size = Vector2.zero();
@override
set size(Vector2 value) {
assert(
value.x >= 0 && value.y >= 0,
"Viewport's size cannot be negative: $value",
);
_size.setFrom(value);
if (isMounted) {
camera.viewfinder.onViewportResize();
}
onViewportResize();
}
/// Reference to the parent camera.
CameraComponent get camera => parent! as CameraComponent;
/// Apply clip mask to the [canvas].
///
/// The mask must be in the viewport's local coordinate system, where the
/// top left corner of the viewport has coordinates (0, 0). The overall size
/// of the clip mask's shape must match the [size] of the viewport.
///
/// This API must be implemented by all viewports.
void clip(Canvas canvas);
/// Tests whether the given point lies within the viewport.
///
/// This method must be consistent with the action of [clip], in the sense
/// that [containsLocalPoint] must return true if and only if that point on
/// the canvas is not clipped by [clip].
@override
bool containsLocalPoint(Vector2 point);
/// Override in order to perform a custom action upon resize.
///
/// A typical use-case would be to adjust the viewport's clip mask to match
/// the new size.
@protected
void onViewportResize();
@mustCallSuper
@override
void onMount() {
assert(
parent! is CameraComponent,
'A Viewport may only be attached to a CameraComponent',
);
}
}
| flame/packages/flame/lib/src/experimental/viewport.dart/0 | {'file_path': 'flame/packages/flame/lib/src/experimental/viewport.dart', 'repo_id': 'flame', 'token_count': 1092} |
import 'dart:math' as math;
import 'package:flame/extensions.dart';
import 'package:flame/game.dart';
/// A viewport is a class that potentially translates and resizes the screen.
/// The reason you might want to have a viewport is to make sure you handle any
/// screen size and resolution correctly depending on your needs.
///
/// Not only screens can have endless configurations of width and height with
/// different ratios, you can also embed games as widgets within a Flutter app.
/// In fact, the size of the game can even change dynamically (if the layout
/// changes or in desktop, for example).
///
/// For some simple games, that is not an issue. The game will just adapt
/// to fit the screen, so if the game world is 1:1 with screen it will just
/// be bigger or smaller. But if you want a consistent experience across
/// platforms and players, you should use a viewport.
///
/// When using a viewport, [resize] should be called by the engine with
/// the raw canvas size (on startup and subsequent resizes) and that will
/// configure [effectiveSize] and [canvasSize].
///
/// The Viewport can also apply an offset to render and clip the canvas adding
/// borders (clipping) when necessary.
/// When rendering, call [render] and put all your rendering inside the lambda
/// so that the correct transformations are applied.
///
/// You can think of a Viewport as mechanism to watch a wide-screen movie on a
/// square monitor. You can stretch the movie to fill the square, but the width
/// and height will be stretched by different amounts, causing distortion. You
/// can fill in the smallest dimension and crop the biggest (that causes
/// cropping). Or you can fill in the biggest and add black bars to cover the
/// unused space on the smallest (this is the [FixedResolutionViewport]).
///
/// The other option is to not use a viewport ([DefaultViewport]) and have
/// your game dynamically render itself to fill in the existing space (basically
/// this means generating either a wide-screen or a square movie on the fly).
/// The disadvantage is that different players on different devices will see
/// different games. For example a hidden door because it's too far away to
/// render in Screen 1 might be visible on Screen 2. Specially if it's an
/// online/competitive game, it can give unfair advantages to users with certain
/// screen resolutions. If you want to "play director" and know exactly what
/// every player is seeing at every time, you should use a Viewport.
abstract class Viewport extends Projector {
/// This configures the viewport with a new raw canvas size.
/// It should immediately affect [effectiveSize] and [canvasSize].
/// This must be called by the engine at startup and also whenever the
/// size changes.
void resize(Vector2 newCanvasSize);
/// Applies to the Canvas all necessary transformations to apply this
/// viewport.
void apply(Canvas c);
/// This transforms the canvas so that the coordinate system is viewport-
/// -aware. All your rendering logic should be put inside the lambda.
void render(Canvas c, void Function(Canvas) renderGame) {
c.save();
apply(c);
renderGame(c);
c.restore();
}
/// This returns the effective size, after viewport transformation.
/// This is not the game widget size but for all intents and purposes,
/// inside your game, this size should be used as the real one.
Vector2 get effectiveSize;
/// This returns the real widget size (well actually the logical Flutter
/// size of your widget). This is the raw canvas size as it would be without
/// any viewport.
///
/// You probably don't need to care about this if you are using a viewport.
Vector2? canvasSize;
}
/// This is the default viewport if you want no transformation.
/// The raw canvasSize is just propagated to the effective size and no
/// translation is applied.
/// This basically no-ops the viewport.
class DefaultViewport extends Viewport {
@override
void apply(Canvas c) {}
@override
void resize(Vector2 newCanvasSize) {
canvasSize = newCanvasSize.clone();
}
@override
Vector2 get effectiveSize => canvasSize!;
@override
Vector2 projectVector(Vector2 vector) => vector;
@override
Vector2 unprojectVector(Vector2 vector) => vector;
@override
Vector2 scaleVector(Vector2 vector) => vector;
@override
Vector2 unscaleVector(Vector2 vector) => vector;
}
/// This is the most common viewport if you want to have full control of what
/// the game looks like. Basically this viewport makes sure the ratio between
/// width and height is *always* the same in your game, no matter the platform.
///
/// To accomplish this you choose a virtual size that will always match the
/// effective size.
///
/// Under the hood, the Viewport will try to expand (or contract) the virtual
/// size so that it fits the most of the screen as it can. So for example,
/// if the viewport happens to be the same ratio of the screen, it will resize
/// to fit 100%. But if they are different ratios, it will resize the most it
/// can and then will add black (color is configurable) borders.
///
/// Then, inside your game, you can always assume the game size is the fixed
/// dimension that you provided.
///
/// Normally you can pick a virtual size that has the same ratio as the most
/// used device for your game (like a pretty standard mobile ratio if you
/// are doing a mobile game) and then in most cases this will apply no
/// transformation whatsoever, and if the a device with a different ratio is
/// used it will try to adapt the best as possible.
class FixedResolutionViewport extends Viewport {
/// By default, this viewport will clip anything rendered outside.
/// Use this variable to control that behaviour.
bool clip;
@override
late Vector2 effectiveSize;
final Vector2 _scaledSize = Vector2.zero();
Vector2 get scaledSize => _scaledSize.clone();
final Vector2 _resizeOffset = Vector2.zero();
Vector2 get resizeOffset => _resizeOffset.clone();
late double _scale;
double get scale => _scale;
/// The matrix used for scaling and translating the canvas
final Matrix4 _transform = Matrix4.identity();
/// The Rect that is used to clip the canvas
late Rect _clipRect;
FixedResolutionViewport(this.effectiveSize, {this.clip = true});
@override
void resize(Vector2 newCanvasSize) {
canvasSize = newCanvasSize.clone();
_scale = math.min(
canvasSize!.x / effectiveSize.x,
canvasSize!.y / effectiveSize.y,
);
_scaledSize
..setFrom(effectiveSize)
..scale(_scale);
_resizeOffset
..setFrom(canvasSize!)
..sub(_scaledSize)
..scale(0.5);
_clipRect = _resizeOffset & _scaledSize;
_transform.setIdentity();
_transform.translate(_resizeOffset.x, _resizeOffset.y);
_transform.scale(_scale, _scale, 1);
}
@override
void apply(Canvas c) {
if (clip) {
c.clipRect(_clipRect);
}
c.transform(_transform.storage);
}
@override
Vector2 projectVector(Vector2 viewportCoordinates) {
return (viewportCoordinates * _scale)..add(_resizeOffset);
}
@override
Vector2 unprojectVector(Vector2 screenCoordinates) {
return (screenCoordinates - _resizeOffset)..scale(1 / _scale);
}
@override
Vector2 scaleVector(Vector2 viewportCoordinates) {
return viewportCoordinates * scale;
}
@override
Vector2 unscaleVector(Vector2 screenCoordinates) {
return screenCoordinates / scale;
}
}
| flame/packages/flame/lib/src/game/camera/viewport.dart/0 | {'file_path': 'flame/packages/flame/lib/src/game/camera/viewport.dart', 'repo_id': 'flame', 'token_count': 2051} |
import 'dart:math';
import 'dart:ui';
import 'package:flame/components.dart';
import 'package:flame/extensions.dart';
import 'package:flame/geometry.dart';
import 'package:flame/src/effects/provider_interfaces.dart';
import 'package:flame/src/utils/solve_quadratic.dart';
class CircleComponent extends ShapeComponent implements SizeProvider {
/// With this constructor you can create your [CircleComponent] from a radius
/// and a position. It will also calculate the bounding rectangle [size] for
/// the [CircleComponent].
CircleComponent({
double? radius,
super.position,
super.angle,
super.anchor,
super.children,
super.priority,
super.paint,
}) : super(
size: Vector2.all((radius ?? 0) * 2),
);
/// With this constructor you define the [CircleComponent] in relation to the
/// [parentSize]. For example having a [relation] of 0.5 would create a circle
/// that fills half of the [parentSize].
CircleComponent.relative(
double relation, {
Vector2? position,
required Vector2 parentSize,
double angle = 0,
Anchor? anchor,
Paint? paint,
}) : this(
radius: relation * (min(parentSize.x, parentSize.y) / 2),
position: position,
angle: angle,
anchor: anchor,
paint: paint,
);
/// Get the radius of the circle before scaling.
double get radius {
return min(size.x, size.y) / 2;
}
/// Set the radius of the circle (and therefore the [size]).
set radius(double value) {
size.setValues(value * 2, value * 2);
}
// Used to not create new Vector2 objects every time radius is called.
final Vector2 _scaledSize = Vector2.zero();
/// Get the radius of the circle after it has been sized and scaled.
double get scaledRadius {
_scaledSize
..setFrom(size)
..multiply(absoluteScale);
return min(_scaledSize.x, _scaledSize.y) / 2;
}
@override
void render(Canvas canvas) {
if (renderShape) {
canvas.drawCircle((size / 2).toOffset(), radius, paint);
}
}
@override
void renderDebugMode(Canvas canvas) {
super.renderDebugMode(canvas);
canvas.drawCircle((size / 2).toOffset(), radius, debugPaint);
}
/// Checks whether the represented circle contains the [point].
@override
bool containsPoint(Vector2 point) {
final scaledRadius = this.scaledRadius;
return absoluteCenter.distanceToSquared(point) <
scaledRadius * scaledRadius;
}
@override
bool containsLocalPoint(Vector2 point) {
final radius = size.x / 2;
final dx = point.x - radius;
final dy = point.y - radius;
return dx * dx + dy * dy <= radius * radius;
}
/// Returns the locus of points in which the provided line segment intersects
/// the circle.
///
/// This can be an empty list (if they don't intersect), one point (if the
/// line is tangent) or two points (if the line is secant).
List<Vector2> lineSegmentIntersections(
LineSegment line, {
double epsilon = double.minPositive,
}) {
// A point on a line is `from + t*(to - from)`. We're trying to solve the
// equation `‖point - center‖² == radius²`. Or, denoting `Δ₂₁ = to - from`
// and `Δ₁₀ = from - center`, the equation is `‖t*Δ₂₁ + Δ₁₀‖² == radius²`.
// Expanding the norm, this becomes a square equation in `t`:
// `t²Δ₂₁² + 2tΔ₂₁Δ₁₀ + Δ₁₀² - radius² == 0`.
_delta21
..setFrom(line.to)
..sub(line.from); // to - from
_delta10
..setFrom(line.from)
..sub(absoluteCenter); // from - absoluteCenter
final a = _delta21.length2;
final b = 2 * _delta21.dot(_delta10);
final c = _delta10.length2 - radius * radius;
return solveQuadratic(a, b, c)
.where((t) => t >= 0 && t <= 1)
.map((t) => line.from.clone()..addScaled(_delta21, t))
.toList();
}
static final Vector2 _delta21 = Vector2.zero();
static final Vector2 _delta10 = Vector2.zero();
}
| flame/packages/flame/lib/src/geometry/circle_component.dart/0 | {'file_path': 'flame/packages/flame/lib/src/geometry/circle_component.dart', 'repo_id': 'flame', 'token_count': 1484} |
import 'dart:ui';
import 'package:flame/src/anchor.dart';
import 'package:flame/src/extensions/vector2.dart';
import 'package:flame/src/particles/particle.dart';
import 'package:flame/src/sprite_animation.dart';
export '../sprite_animation.dart';
export '../sprite_animation.dart';
class SpriteAnimationParticle extends Particle {
final SpriteAnimation animation;
final Vector2? size;
final Paint? overridePaint;
final bool alignAnimationTime;
SpriteAnimationParticle({
required this.animation,
this.size,
this.overridePaint,
super.lifespan,
this.alignAnimationTime = true,
});
@override
void setLifespan(double lifespan) {
super.setLifespan(lifespan);
if (alignAnimationTime) {
animation.stepTime = lifespan / animation.frames.length;
animation.reset();
}
}
@override
void render(Canvas canvas) {
animation.getSprite().render(
canvas,
size: size,
anchor: Anchor.center,
overridePaint: overridePaint,
);
}
@override
void update(double dt) {
super.update(dt);
animation.update(dt);
}
}
| flame/packages/flame/lib/src/particles/animation_particle.dart/0 | {'file_path': 'flame/packages/flame/lib/src/particles/animation_particle.dart', 'repo_id': 'flame', 'token_count': 431} |
import 'dart:collection';
import 'dart:math' show pi;
import 'dart:ui';
import 'package:flame/game.dart';
import 'package:flame/src/cache/images.dart';
import 'package:flame/src/extensions/image.dart';
import 'package:flame/src/extensions/picture_extension.dart';
import 'package:flame/src/flame.dart';
extension SpriteBatchExtension on Game {
/// Utility method to load and cache the image for a [SpriteBatch] based on
/// its options.
Future<SpriteBatch> loadSpriteBatch(
String path, {
Color defaultColor = const Color(0x00000000),
BlendMode defaultBlendMode = BlendMode.srcOver,
RSTransform? defaultTransform,
Images? imageCache,
bool useAtlas = true,
}) {
return SpriteBatch.load(
path,
defaultColor: defaultColor,
defaultBlendMode: defaultBlendMode,
defaultTransform: defaultTransform,
images: imageCache ?? images,
useAtlas: useAtlas,
);
}
}
/// A single item in a SpriteBatch.
///
/// Holds all the important information of a batch item.
class BatchItem {
BatchItem({
required this.source,
required this.transform,
this.flip = false,
required this.color,
}) : paint = Paint()..color = color,
destination = Offset.zero & source.size;
/// The source rectangle on the [SpriteBatch.atlas].
final Rect source;
/// The destination rectangle for the Canvas.
///
/// It will be transformed by [matrix].
final Rect destination;
/// The transform values for this batch item.
final RSTransform transform;
/// The flip value for this batch item.
final bool flip;
/// The background color for this batch item.
final Color color;
/// Fallback matrix for the web.
///
/// Since [Canvas.drawAtlas] is not supported on the web we also
/// build a `Matrix4` based on the [transform] and [flip] values.
late final Matrix4 matrix = Matrix4(
transform.scos, transform.ssin, 0, 0, //
-transform.ssin, transform.scos, 0, 0, //
0, 0, 0, 0, //
transform.tx, transform.ty, 0, 1, //
)
..translate(source.width / 2, source.height / 2)
..rotateY(flip ? pi : 0)
..translate(-source.width / 2, -source.height / 2);
/// Paint object used for the web.
final Paint paint;
}
/// The SpriteBatch API allows for rendering multiple items at once.
///
/// This class allows for optimization when you want to draw many parts of an
/// image onto the canvas. It is more efficient than using multiple calls to
/// [Canvas.drawImageRect] and provides more functionality by allowing each
/// [BatchItem] to have their own transform rotation and color.
///
/// By collecting all the necessary transforms on a single image and sending
/// those transforms in a single batch to the GPU, we can render multiple parts
/// of a single image at once.
///
/// **Note**: If you are experiencing problems with ghost lines, the less
/// performant [Canvas.drawImageRect] can be used instead of [Canvas.drawAtlas].
/// To activate this mode, pass in `useAtlas = false` to the constructor or
/// load method that you are using and each [BatchItem] will be rendered using
/// the [Canvas.drawImageRect] method instead.
class SpriteBatch {
SpriteBatch(
this.atlas, {
this.defaultColor = const Color(0x00000000),
this.defaultBlendMode = BlendMode.srcOver,
this.defaultTransform,
this.useAtlas = true,
Images? imageCache,
String? imageKey,
}) : _imageCache = imageCache,
_imageKey = imageKey;
/// Takes a path of an image, and optional arguments for the SpriteBatch.
///
/// When the [images] is omitted, the global [Flame.images] is used.
static Future<SpriteBatch> load(
String path, {
Color defaultColor = const Color(0x00000000),
BlendMode defaultBlendMode = BlendMode.srcOver,
RSTransform? defaultTransform,
Images? images,
bool useAtlas = true,
}) async {
final _images = images ?? Flame.images;
return SpriteBatch(
await _images.load(path),
defaultColor: defaultColor,
defaultTransform: defaultTransform ?? RSTransform(1, 0, 0, 0),
defaultBlendMode: defaultBlendMode,
useAtlas: useAtlas,
imageCache: _images,
imageKey: path,
);
}
/// List of all the existing batch items.
final _batchItems = <BatchItem>[];
/// The sources to use on the [atlas].
final _sources = <Rect>[];
/// The sources list shouldn't be modified directly, that is why an
/// [UnmodifiableListView] is used. If you want to add sources use the
/// [add] or [addTransform] method.
UnmodifiableListView<Rect> get sources {
return UnmodifiableListView<Rect>(_sources);
}
/// The transforms that should be applied on the [_sources].
final _transforms = <RSTransform>[];
/// The transforms list shouldn't be modified directly, that is why an
/// [UnmodifiableListView] is used. If you want to add transforms use the
/// [add] or [addTransform] method.
UnmodifiableListView<RSTransform> get transforms {
return UnmodifiableListView<RSTransform>(_transforms);
}
/// The background color for the [_sources].
final _colors = <Color>[];
/// The colors list shouldn't be modified directly, that is why an
/// [UnmodifiableListView] is used. If you want to add colors use the
/// [add] or [addTransform] method.
UnmodifiableListView<Color> get colors {
return UnmodifiableListView<Color>(_colors);
}
/// The atlas used by the [SpriteBatch].
Image atlas;
/// The image cache used by the [SpriteBatch] to store image assets.
final Images? _imageCache;
/// When the [_imageCache] isn't specified, the global [Flame.images] is used.
Images get imageCache => _imageCache ?? Flame.images;
/// The root key use by the [SpriteBatch] to store image assets.
final String? _imageKey;
/// When the [_imageKey] isn't specified [imageKey] will return either the key
/// for the [atlas] stored in [imageCache] or a key generated from the
/// identityHashCode.
String get imageKey =>
_imageKey ??
imageCache.findKeyForImage(atlas) ??
'image[${identityHashCode(atlas)}]';
/// Whether any [BatchItem]s needs a flippable atlas.
bool _hasFlips = false;
/// The status of the atlas image loading operations.
bool _atlasReady = true;
/// The default color, used as a background color for a [BatchItem].
final Color defaultColor;
/// The default transform, used when a transform was not supplied for a
/// [BatchItem].
final RSTransform? defaultTransform;
/// The default blend mode, used for blending a batch item.
final BlendMode defaultBlendMode;
/// The width of the [atlas].
int get width => atlas.width;
/// The height of the [atlas].
int get height => atlas.height;
/// The size of the [atlas].
Vector2 get size => atlas.size;
/// Whether to use [Canvas.drawAtlas] or not.
final bool useAtlas;
Future<void> _makeFlippedAtlas() async {
_hasFlips = true;
_atlasReady = false;
final key = '$imageKey#with-flips';
atlas = await imageCache.fetchOrGenerate(
key,
() => _generateFlippedAtlas(atlas),
);
_atlasReady = true;
}
Future<Image> _generateFlippedAtlas(Image image) {
final recorder = PictureRecorder();
final canvas = Canvas(recorder);
final _emptyPaint = Paint();
canvas.drawImage(image, Offset.zero, _emptyPaint);
canvas.scale(-1, 1);
canvas.drawImage(image, Offset(-image.width * 2, 0), _emptyPaint);
final picture = recorder.endRecording();
return picture.toImageSafe(image.width * 2, image.height);
}
/// Add a new batch item using a RSTransform.
///
/// The [source] parameter is the source location on the [atlas].
///
/// You can position, rotate, scale and flip it on the canvas using the
/// [transform] and [flip] parameters.
///
/// The [color] parameter allows you to render a color behind the batch item,
/// as a background color.
///
/// The [add] method may be a simpler way to add a batch item to the batch.
/// However, if there is a way to factor out the computations of the sine and
/// cosine of the rotation so that they can be reused over multiple calls to
/// this constructor, it may be more efficient to directly use this method
/// instead.
void addTransform({
required Rect source,
RSTransform? transform,
bool flip = false,
Color? color,
}) {
final batchItem = BatchItem(
source: source,
transform: transform ??= defaultTransform ?? RSTransform(1, 0, 0, 0),
flip: flip,
color: color ?? defaultColor,
);
if (flip && useAtlas && !_hasFlips) {
_makeFlippedAtlas();
}
_batchItems.add(batchItem);
_sources.add(
flip
? Rect.fromLTWH(
(atlas.width * (!_atlasReady ? 2 : 1)) - source.right,
source.top,
source.width,
source.height,
)
: batchItem.source,
);
_transforms.add(batchItem.transform);
_colors.add(batchItem.color);
}
/// Add a new batch item.
///
/// The [source] parameter is the source location on the [atlas]. You can
/// position it on the canvas using the [offset] parameter.
///
/// You can transform the sprite from its [offset] using [scale], [rotation],
/// [anchor] and [flip].
///
/// The [color] paramater allows you to render a color behind the batch item,
/// as a background color.
///
/// This method creates a new [RSTransform] based on the given transform
/// arguments. If many [RSTransform] objects are being created and there is a
/// way to factor out the computations of the sine and cosine of the rotation
/// (which are computed each time this method is called) and reuse them over
/// multiple [RSTransform] objects,
/// it may be more efficient to directly use the more direct [addTransform]
/// method instead.
void add({
required Rect source,
double scale = 1.0,
Vector2? anchor,
double rotation = 0,
Vector2? offset,
bool flip = false,
Color? color,
}) {
anchor ??= Vector2.zero();
offset ??= Vector2.zero();
RSTransform? transform;
// If any of the transform arguments is different from the defaults,
// then we create one. This is to prevent unnecessary computations
// of the sine and cosine of the rotation.
if (scale != 1.0 ||
anchor != Vector2.zero() ||
rotation != 0 ||
offset != Vector2.zero()) {
transform = RSTransform.fromComponents(
scale: scale,
anchorX: anchor.x,
anchorY: anchor.y,
rotation: rotation,
translateX: offset.x,
translateY: offset.y,
);
}
addTransform(
source: source,
transform: transform,
flip: flip,
color: color,
);
}
/// Clear the SpriteBatch so it can be reused.
void clear() {
_sources.clear();
_transforms.clear();
_colors.clear();
_batchItems.clear();
}
// Used to not create new paint objects in [render] on every tick.
final Paint _emptyPaint = Paint();
void render(
Canvas canvas, {
BlendMode? blendMode,
Rect? cullRect,
Paint? paint,
}) {
paint ??= _emptyPaint;
if (useAtlas && _atlasReady) {
canvas.drawAtlas(
atlas,
_transforms,
_sources,
_colors,
blendMode ?? defaultBlendMode,
cullRect,
paint,
);
} else {
for (final batchItem in _batchItems) {
paint.blendMode = blendMode ?? paint.blendMode;
canvas
..save()
..transform(batchItem.matrix.storage)
..drawRect(batchItem.destination, batchItem.paint)
..drawImageRect(
atlas,
batchItem.source,
batchItem.destination,
paint,
)
..restore();
}
}
}
}
| flame/packages/flame/lib/src/sprite_batch.dart/0 | {'file_path': 'flame/packages/flame/lib/src/sprite_batch.dart', 'repo_id': 'flame', 'token_count': 4120} |
export 'src/anchor.dart';
export 'src/widgets/animation_widget.dart';
export 'src/widgets/nine_tile_box.dart';
export 'src/widgets/sprite_button.dart';
export 'src/widgets/sprite_widget.dart';
| flame/packages/flame/lib/widgets.dart/0 | {'file_path': 'flame/packages/flame/lib/widgets.dart', 'repo_id': 'flame', 'token_count': 76} |
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame_test/flame_test.dart';
import 'package:meta/meta.dart';
class HasCollidablesGame extends FlameGame with HasCollisionDetection {}
@isTest
Future<void> testCollidableGame(
String testName,
Future Function(HasCollidablesGame) testBody,
) {
return testWithGame(testName, HasCollidablesGame.new, testBody);
}
class TestHitbox extends RectangleHitbox {
int startCounter = 0;
int onCollisionCounter = 0;
int endCounter = 0;
TestHitbox() {
onCollisionCallback = (_, __) {
onCollisionCounter++;
};
onCollisionStartCallback = (_, __) {
startCounter++;
};
onCollisionEndCallback = (_) {
endCounter++;
};
}
}
class TestBlock extends PositionComponent with CollisionCallbacks {
String? name;
final hitbox = TestHitbox();
int startCounter = 0;
int onCollisionCounter = 0;
int endCounter = 0;
TestBlock(
Vector2 position,
Vector2 size, {
CollisionType type = CollisionType.active,
bool addTestHitbox = true,
this.name,
}) : super(
position: position,
size: size,
) {
children.register<ShapeHitbox>();
if (addTestHitbox) {
add(hitbox..collisionType = type);
}
}
@override
bool collidingWith(PositionComponent other) {
return activeCollisions.contains(other);
}
bool collidedWithExactly(List<CollisionCallbacks> collidables) {
final otherCollidables = collidables.toSet()..remove(this);
return activeCollisions.containsAll(otherCollidables) &&
otherCollidables.containsAll(activeCollisions);
}
@override
String toString() {
return name == null
? '_TestBlock[${identityHashCode(this)}]'
: '_TestBlock[$name]';
}
Set<Vector2> intersections(TestBlock other) {
final result = <Vector2>{};
for (final hitboxA in children.query<ShapeHitbox>()) {
for (final hitboxB in other.children.query<ShapeHitbox>()) {
result.addAll(hitboxA.intersections(hitboxB));
}
}
return result;
}
@override
void onCollisionStart(
Set<Vector2> intersectionPoints,
PositionComponent other,
) {
super.onCollisionStart(intersectionPoints, other);
startCounter++;
}
@override
void onCollision(Set<Vector2> intersectionPoints, PositionComponent other) {
super.onCollision(intersectionPoints, other);
onCollisionCounter++;
}
@override
void onCollisionEnd(PositionComponent other) {
super.onCollisionEnd(other);
endCounter++;
}
}
| flame/packages/flame/test/collisions/collision_test_helpers.dart/0 | {'file_path': 'flame/packages/flame/test/collisions/collision_test_helpers.dart', 'repo_id': 'flame', 'token_count': 949} |
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('HasAncestor', () {
testWithFlameGame('successfully sets the ancestor link', (game) async {
final ancestor = _AncestorComponent()..addToParent(game);
final inBetween = _InBetweenComponent()..addToParent(ancestor);
final component = _TestComponent()..addToParent(inBetween);
await game.ready();
expect(component.isMounted, true);
expect(component.ancestor, isA<_AncestorComponent>());
});
testWithFlameGame(
'throws assertion error if the wrong ancestor is used',
(game) async {
final ancestor = _DifferentComponent()..addToParent(game);
final inBetween = _InBetweenComponent()..addToParent(ancestor);
await game.ready();
expect(
() {
inBetween.add(_TestComponent());
game.update(0);
},
failsAssert(
'''An ancestor must be of type _AncestorComponent in the component tree''',
),
);
},
);
});
}
class _AncestorComponent extends Component {}
class _InBetweenComponent extends Component {}
class _DifferentComponent extends Component {}
class _TestComponent extends Component with HasAncestor<_AncestorComponent> {}
| flame/packages/flame/test/components/mixins/has_ancestor_test.dart/0 | {'file_path': 'flame/packages/flame/test/components/mixins/has_ancestor_test.dart', 'repo_id': 'flame', 'token_count': 512} |
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
class _MyTimerComponent extends TimerComponent {
int count = 0;
_MyTimerComponent()
: super(
period: 1,
repeat: true,
removeOnFinish: false,
);
@override
void onTick() {
count++;
}
}
class _NonRepeatingTimerComponent extends TimerComponent {
_NonRepeatingTimerComponent()
: super(
period: 1,
repeat: false,
removeOnFinish: true,
);
}
void main() {
group('TimerComponent', () {
final tester = FlameTester(FlameGame.new);
tester.test('runs the tick method', (game) {
final timer = _MyTimerComponent();
game.add(timer);
game.update(0);
game.update(1.2);
game.update(0);
expect(timer.count, equals(1));
});
tester.test('never remove from the game when is repeating', (game) {
game.add(_MyTimerComponent());
game.update(0);
game.update(1.2);
game.update(0);
expect(game.children.length, equals(1));
});
tester.test('is removed from the game when is finished', (game) {
game.add(_NonRepeatingTimerComponent());
game.update(0);
game.update(1.2);
game.update(0);
expect(game.children.length, equals(0));
});
tester.test('calls onTick when provided', (game) {
var called = false;
game.add(
TimerComponent(
period: 1,
onTick: () {
called = true;
},
),
);
game.update(0);
game.update(1.2);
expect(called, isTrue);
});
});
}
| flame/packages/flame/test/components/timer_component_test.dart/0 | {'file_path': 'flame/packages/flame/test/components/timer_component_test.dart', 'repo_id': 'flame', 'token_count': 766} |
import 'package:flame/src/components/component.dart';
import 'package:flame/src/effects/controllers/effect_controller.dart';
import 'package:flame/src/effects/effect.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
class _MyEffect extends Effect {
_MyEffect(super.controller);
double x = -1;
Function()? onStartCallback;
@override
void apply(double progress) {
x = progress;
}
@override
void reset() {
super.reset();
x = -1;
}
@override
void onStart() {
super.onStart();
onStartCallback?.call();
}
}
void main() {
group('Effect', () {
test('pause & resume', () {
final effect = _MyEffect(EffectController(duration: 10));
expect(effect.x, -1);
expect(effect.isPaused, false);
effect.update(0);
expect(effect.x, 0);
effect.update(1);
expect(effect.x, closeTo(0.1, 1e-15));
effect.update(2);
expect(effect.x, closeTo(0.3, 1e-15));
effect.pause();
effect.update(5);
effect.update(2);
expect(effect.x, closeTo(0.3, 1e-15));
effect.resume();
effect.update(1);
expect(effect.x, closeTo(0.4, 1e-15));
effect.pause();
effect.update(1000);
expect(effect.isPaused, true);
effect.reset();
expect(effect.isPaused, false);
expect(effect.x, -1);
effect.update(5);
expect(effect.x, closeTo(0.5, 1e-15));
effect.update(5);
expect(effect.x, closeTo(1, 1e-15));
});
flameGame.test(
'removeOnFinish = true',
(game) async {
final obj = Component();
game.add(obj);
final effect = _MyEffect(EffectController(duration: 1));
obj.add(effect);
await game.ready();
expect(obj.children.length, 1);
expect(effect.removeOnFinish, true);
expect(effect.isMounted, true);
game.update(1);
expect(effect.controller.completed, true);
game.update(0);
expect(effect.isMounted, false);
expect(obj.children.length, 0);
},
);
flameGame.test(
'removeOnFinish = false',
(game) async {
final obj = Component();
game.add(obj);
final effect = _MyEffect(EffectController(duration: 1));
effect.removeOnFinish = false;
obj.add(effect);
await game.ready();
expect(obj.children.length, 1);
expect(effect.removeOnFinish, false);
expect(effect.isMounted, true);
// After the effect completes, it still remains mounted
game.update(1);
expect(effect.x, 1);
expect(effect.controller.completed, true);
game.update(0);
expect(effect.isMounted, true);
expect(obj.children.length, 1);
// Even as more time is passing, the effect remains mounted and in
// the completed state
game.update(10);
expect(effect.x, 1);
expect(effect.isMounted, true);
expect(effect.controller.completed, true);
// However, once the effect is reset, it goes to its initial state
effect.reset();
expect(effect.x, -1);
expect(effect.controller.completed, false);
game.update(0.5);
expect(effect.x, 0.5);
expect(effect.controller.completed, false);
// Now the effect completes once again, but still remains mounted
game.update(0.5);
expect(effect.controller.completed, true);
expect(effect.x, 1);
game.update(0);
expect(effect.isMounted, true);
},
);
test('onStart & onFinish', () {
var nStarted = 0;
var nFinished = 0;
final effect = _MyEffect(EffectController(duration: 1))
..onStartCallback = () {
nStarted++;
}
..onComplete = () {
nFinished++;
};
effect.update(0);
expect(effect.x, 0);
expect(nStarted, 1);
expect(nFinished, 0);
effect.update(0.5);
expect(effect.x, 0.5);
expect(nStarted, 1);
expect(nFinished, 0);
effect.update(0.5);
expect(effect.controller.completed, true);
expect(effect.x, 1);
expect(nStarted, 1);
expect(nFinished, 1);
// As more time passes, `onStart` and `onFinish` are no longer called
effect.update(0.5);
expect(effect.x, 1);
expect(nStarted, 1);
expect(nFinished, 1);
// However, if we reset the effect, the callbacks will be invoked again
effect.reset();
effect.update(0);
expect(nStarted, 2);
expect(nFinished, 1);
effect.update(1);
expect(nStarted, 2);
expect(nFinished, 2);
});
});
}
| flame/packages/flame/test/effects/effect_test.dart/0 | {'file_path': 'flame/packages/flame/test/effects/effect_test.dart', 'repo_id': 'flame', 'token_count': 2068} |
import 'package:flame/components.dart';
import 'package:flame/experimental.dart';
import 'package:flame/src/effects/provider_interfaces.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('FollowBehavior', () {
test('basic properties', () {
final target = PositionComponent();
final owner = PositionComponent();
final behavior = FollowBehavior(target: target, owner: owner);
expect(behavior.target, target);
expect(behavior.owner, owner);
expect(behavior.maxSpeed, double.infinity);
expect(behavior.horizontalOnly, false);
expect(behavior.verticalOnly, false);
});
test('errors', () {
expect(
() => FollowBehavior(target: PositionComponent(), maxSpeed: 0),
failsAssert('maxSpeed must be positive: 0.0'),
);
expect(
() => FollowBehavior(target: PositionComponent(), maxSpeed: -2.45),
failsAssert('maxSpeed must be positive: -2.45'),
);
expect(
() => FollowBehavior(
target: PositionComponent(),
horizontalOnly: true,
verticalOnly: true,
),
failsAssert(
'The behavior cannot be both horizontalOnly and verticalOnly',
),
);
});
testWithFlameGame('parent is not position provider', (game) async {
final target = PositionComponent()..addToParent(game);
final component = Component()..addToParent(game);
await game.ready();
expect(
() async {
component.add(FollowBehavior(target: target));
await game.ready();
},
failsAssert('Can only apply this behavior to a PositionProvider'),
);
});
testWithFlameGame('custom position provider', (game) async {
final target = PositionComponent()
..position = Vector2(3, 100)
..addToParent(game);
final component = Component()..addToParent(game);
await game.ready();
final followTarget = Vector2(3, 1);
component.add(
FollowBehavior(
target: target,
owner: PositionProviderImpl(
getValue: () => followTarget,
setValue: followTarget.setFrom,
),
maxSpeed: 1,
),
);
await game.ready();
const dt = 0.11;
for (var i = 0; i < 20; i++) {
expect(followTarget, closeToVector(3, 1 + i * dt, epsilon: 1e-14));
game.update(dt);
}
});
testWithFlameGame('simple follow', (game) async {
final target = PositionComponent()..addToParent(game);
final pursuer = PositionComponent()
..add(FollowBehavior(target: target))
..addToParent(game);
await game.ready();
for (var i = 0; i < 10; i++) {
target.position = Vector2.random()..scale(1000);
game.update(0.01);
expect(
pursuer.position,
closeToVector(target.position.x, target.position.y, epsilon: 1e-12),
);
}
});
testWithFlameGame('follow with max speed', (game) async {
const dt = 0.013;
const speed = 587.0;
final target = PositionComponent()
..position = Vector2(600, 800)
..addToParent(game);
final pursuer = PositionComponent()
..add(FollowBehavior(target: target, maxSpeed: speed))
..addToParent(game);
await game.ready();
for (var i = 0; i < 100; i++) {
final distance = speed * i * dt;
expect(
pursuer.position,
closeToVector(distance * 0.6, distance * 0.8, epsilon: 1e-12),
);
game.update(dt);
}
});
testWithFlameGame('horizontal-only follow', (game) async {
final target = PositionComponent(position: Vector2(20, 10));
final pursuer = PositionComponent();
pursuer.add(
FollowBehavior(target: target, horizontalOnly: true, maxSpeed: 1),
);
game.addAll([target, pursuer]);
await game.ready();
for (var i = 0; i < 10; i++) {
expect(pursuer.position.x, i);
expect(pursuer.position.y, 0);
game.update(1);
}
});
testWithFlameGame('vertical-only follow', (game) async {
final target = PositionComponent(position: Vector2(20, 100));
final pursuer = PositionComponent();
pursuer.add(
FollowBehavior(target: target, verticalOnly: true, maxSpeed: 1),
);
game.addAll([target, pursuer]);
await game.ready();
for (var i = 0; i < 10; i++) {
expect(pursuer.position.x, 0);
expect(pursuer.position.y, i);
game.update(1);
}
});
});
}
| flame/packages/flame/test/experimental/follow_behavior_test.dart/0 | {'file_path': 'flame/packages/flame/test/experimental/follow_behavior_test.dart', 'repo_id': 'flame', 'token_count': 1973} |
import 'package:collection/collection.dart';
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame/src/game/game_render_box.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'projector_test.dart';
void main() {
group('FlameGame', () {
testWithFlameGame(
'default viewport does not change size',
(game) async {
game.onGameResize(Vector2(100.0, 200.0));
expect(game.canvasSize, Vector2(100.0, 200.00));
expect(game.size, Vector2(100.0, 200.00));
},
);
testWithFlameGame('Game in game', (game) async {
final innerGame = FlameGame();
game.add(innerGame);
await game.ready();
expect(innerGame.canvasSize, closeToVector(800, 600));
expect(innerGame.isLoaded, true);
expect(innerGame.isMounted, true);
});
group('components', () {
testWithFlameGame(
'Add component',
(game) async {
final component = Component();
await game.ensureAdd(component);
expect(component.isMounted, true);
expect(game.children.contains(component), true);
},
);
testWithGame<GameWithTappables>(
'Add component with onLoad function',
GameWithTappables.new,
(game) async {
final component = _MyAsyncComponent();
await game.ensureAdd(component);
expect(game.children.contains(component), true);
expect(component.gameSize, game.size);
expect(component.gameRef, game);
},
);
testWithFlameGame(
'prepare adds gameRef and calls onGameResize',
(game) async {
final component = _MyComponent();
await game.ensureAdd(component);
expect(component.gameSize, game.size);
expect(component.gameRef, game);
},
);
testWithGame<GameWithTappables>(
'component can be tapped',
GameWithTappables.new,
(game) async {
final component = _MyTappableComponent();
await game.ensureAdd(component);
game.onTapDown(1, createTapDownEvent(game));
expect(component.tapped, true);
},
);
testWidgets(
'component render and update is called',
(WidgetTester tester) async {
final game = FlameGame();
late GameRenderBox renderBox;
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
renderBox = GameRenderBox(context, game);
return GameWidget(game: game);
},
),
);
renderBox.attach(PipelineOwner());
final component = _MyComponent()..addToParent(game);
renderBox.gameLoopCallback(1.0);
expect(component.isUpdateCalled, true);
renderBox.paint(
PaintingContext(ContainerLayer(), Rect.zero),
Offset.zero,
);
expect(component.isRenderCalled, true);
renderBox.detach();
},
);
testWithFlameGame(
'onRemove is only called once on component',
(game) async {
final component = _MyComponent();
await game.ensureAdd(component);
// The component is removed both by removing it on the game instance
// and by the function on the component, but the onRemove callback
// should only be called once.
component.removeFromParent();
game.remove(component);
// The component is not removed from the component list until an
// update has been performed.
game.update(0.0);
expect(component.onRemoveCallCounter, 1);
},
);
testWithFlameGame(
'removes PositionComponent when removeFromParent is called',
(game) async {
final component = PositionComponent();
await game.ensureAdd(component);
expect(game.children.length, equals(1));
component.removeFromParent();
game.updateTree(0);
expect(game.children.isEmpty, equals(true));
},
);
testWidgets(
'can add a component to a game without a layout',
(WidgetTester tester) async {
final game = FlameGame();
final component = Component()..addToParent(game);
expect(game.hasLayout, false);
await tester.pumpWidget(GameWidget(game: game));
game.update(0);
expect(game.children.length, 1);
expect(game.children.first, component);
},
);
});
group('projector', () {
testWithFlameGame(
'default viewport+camera should be identity projections',
(game) async {
checkProjectorReversibility(game.projector);
expect(game.projector.projectVector(Vector2(1, 2)), Vector2(1, 2));
expect(game.projector.unprojectVector(Vector2(1, 2)), Vector2(1, 2));
expect(game.projector.scaleVector(Vector2(1, 2)), Vector2(1, 2));
expect(game.projector.unscaleVector(Vector2(1, 2)), Vector2(1, 2));
},
);
testWithFlameGame(
'viewport only with scale projection (no camera)',
(game) async {
final viewport = FixedResolutionViewport(Vector2.all(100));
game.camera.viewport = viewport;
game.onGameResize(Vector2(200, 200));
expect(viewport.scale, 2);
expect(viewport.resizeOffset, Vector2.zero()); // no translation
checkProjectorReversibility(game.projector);
expect(game.projector.projectVector(Vector2(1, 2)), Vector2(2, 4));
expect(game.projector.unprojectVector(Vector2(2, 4)), Vector2(1, 2));
expect(game.projector.scaleVector(Vector2(1, 2)), Vector2(2, 4));
expect(game.projector.unscaleVector(Vector2(2, 4)), Vector2(1, 2));
expect(
game.viewportProjector.projectVector(Vector2(1, 2)),
Vector2(2, 4),
);
expect(
game.viewportProjector.unprojectVector(Vector2(2, 4)),
Vector2(1, 2),
);
expect(
game.viewportProjector.scaleVector(Vector2(1, 2)),
Vector2(2, 4),
);
expect(
game.viewportProjector.unscaleVector(Vector2(2, 4)),
Vector2(1, 2),
);
},
);
testWithFlameGame(
'viewport only with translation projection (no camera)',
(game) async {
final viewport = FixedResolutionViewport(Vector2.all(100));
game.camera.viewport = viewport;
game.onGameResize(Vector2(200, 100));
expect(viewport.scale, 1); // no scale
expect(viewport.resizeOffset, Vector2(50, 0)); // y is unchanged
checkProjectorReversibility(game.projector);
// Click on x=0 means -50 in the game coordinates.
expect(
game.projector.unprojectVector(Vector2.zero()),
Vector2(-50, 0),
);
// Click on x=50 is right on the edge of the viewport.
expect(
game.projector.unprojectVector(Vector2.all(50)),
Vector2(0, 50),
);
// Click on x=150 is on the other edge.
expect(
game.projector.unprojectVector(Vector2.all(150)),
Vector2(100, 150),
);
// 50 past the end.
expect(
game.projector.unprojectVector(Vector2(200, 0)),
Vector2(150, 0),
);
// Translations should not affect projecting deltas.
expect(game.projector.unscaleVector(Vector2.zero()), Vector2.zero());
expect(
game.projector.unscaleVector(Vector2.all(50)),
Vector2.all(50),
);
expect(
game.projector.unscaleVector(Vector2.all(150)),
Vector2.all(150),
);
expect(
game.projector.unscaleVector(Vector2(200, 0)),
Vector2(200, 0),
);
},
);
testWithFlameGame(
'viewport only with both scale and translation (no camera)',
(game) async {
final viewport = FixedResolutionViewport(Vector2.all(100));
game.camera.viewport = viewport;
game.onGameResize(Vector2(200, 400));
expect(viewport.scale, 2);
expect(viewport.resizeOffset, Vector2(0, 100)); // x is unchanged
checkProjectorReversibility(game.projector);
// Click on y=0 means -100 in the game coordinates.
expect(
game.projector.unprojectVector(Vector2.zero()),
Vector2(0, -50),
);
expect(
game.projector.unprojectVector(Vector2(0, 100)),
Vector2.zero(),
);
expect(
game.projector.unprojectVector(Vector2(0, 300)),
Vector2(0, 100),
);
expect(
game.projector.unprojectVector(Vector2(0, 400)),
Vector2(0, 150),
);
},
);
testWithFlameGame(
'camera only with zoom (default viewport)',
(game) async {
game.onGameResize(Vector2.all(1));
game.camera.zoom = 3; // 3x zoom
checkProjectorReversibility(game.projector);
expect(
game.projector.unprojectVector(Vector2.zero()),
Vector2.zero(),
);
expect(game.projector.unprojectVector(Vector2(3, 6)), Vector2(1, 2));
expect(
game.viewportProjector.unprojectVector(Vector2.zero()),
Vector2.zero(),
);
expect(
game.viewportProjector.unprojectVector(Vector2(3, 6)),
Vector2(3, 6),
);
// Delta considers the zoom.
expect(game.projector.unscaleVector(Vector2.zero()), Vector2.zero());
expect(game.projector.unscaleVector(Vector2(3, 6)), Vector2(1, 2));
},
);
testWithFlameGame(
'camera only with translation (default viewport)',
(game) async {
game.onGameResize(Vector2.all(1));
// Top left corner of the screen is (50, 100).
game.camera.snapTo(Vector2(50, 100));
checkProjectorReversibility(game.projector);
expect(
game.projector.unprojectVector(Vector2.zero()),
Vector2(50, 100),
);
expect(
game.projector.unprojectVector(Vector2(-50, 50)),
Vector2(0, 150),
);
// Delta ignores translations.
expect(game.projector.scaleVector(Vector2.zero()), Vector2.zero());
expect(
game.projector.scaleVector(Vector2(-50, 50)),
Vector2(-50, 50),
);
},
);
testWithFlameGame(
'camera only with both zoom and translation (default viewport)',
(game) async {
game.onGameResize(Vector2.all(10));
// No-op because the default is already top left.
game.camera.setRelativeOffset(Anchor.topLeft);
// Top left corner of the screen is (-100, -100).
game.camera.snapTo(Vector2.all(-100));
// Zoom is 2x, meaning every 1 unit you walk away of (-100, -100).
game.camera.zoom = 2;
checkProjectorReversibility(game.projector);
expect(
game.projector.unprojectVector(Vector2.zero()),
Vector2(-100, -100),
);
// Let's "walk" 10 pixels down on the screen;
// that means the world walks 5 units.
expect(
game.projector.unprojectVector(Vector2(0, 10)),
Vector2(-100, -95),
);
// To get to the world 0,0 we need to walk 200 screen units.
expect(
game.projector.unprojectVector(Vector2.all(200)),
Vector2.zero(),
);
// Note: in the current implementation, if we change the relative
// position the zoom is still applied w.r.t. the top left of the
// screen.
game.camera.setRelativeOffset(Anchor.center);
game.camera.snap();
// That means that the center would be -100, -100 if the zoom was 1
// meaning the topLeft will be (-105, -105) (regardless of zoom),
// but since the offset is set to center, topLeft will be
// (-102.5, -102.5)
expect(
game.projector.unprojectVector(Vector2.zero()),
Vector2.all(-102.5),
);
// and with 2x zoom the center will actually be -100, -100 since the
// relative offset is set to center.
expect(
game.projector.unprojectVector(Vector2.all(5)),
Vector2.all(-100),
);
// TODO(luan): we might want to change the behaviour so that the zoom
// is applied w.r.t. the relativeOffset and not topLeft
// For deltas, we consider only the zoom.
expect(game.projector.unscaleVector(Vector2.zero()), Vector2.zero());
expect(game.projector.unscaleVector(Vector2(2, 4)), Vector2(1, 2));
},
);
testWithFlameGame('camera & viewport - two translations', (game) async {
final viewport = FixedResolutionViewport(Vector2.all(100));
game.camera.viewport = viewport; // default camera
game.onGameResize(Vector2(200, 100));
game.camera.snapTo(Vector2(10, 100));
expect(viewport.scale, 1); // no scale
expect(viewport.resizeOffset, Vector2(50, 0)); // y is unchanged
checkProjectorReversibility(game.projector);
// Top left of viewport should be top left of camera.
expect(
game.projector.unprojectVector(Vector2(50, 0)),
Vector2(10, 100),
);
// Viewport only, top left should be the top left of screen.
expect(
game.viewportProjector.unprojectVector(Vector2(50, 0)),
Vector2.zero(),
);
// Top right of viewport is top left of camera + effective screen width.
expect(
game.projector.unprojectVector(Vector2(150, 0)),
Vector2(110, 100),
);
// Vertically, only the camera translation is applied.
expect(
game.projector.unprojectVector(Vector2(40, 123)),
Vector2(0, 223),
);
// Deltas should not be affected by translations at all.
expect(game.projector.unscaleVector(Vector2.zero()), Vector2.zero());
expect(game.projector.unscaleVector(Vector2(1, 2)), Vector2(1, 2));
});
testWithFlameGame('camera zoom & viewport translation', (game) async {
final viewport = FixedResolutionViewport(Vector2.all(100));
game.camera.viewport = viewport;
game.onGameResize(Vector2(200, 100));
game.camera.zoom = 2;
game.camera.snap();
expect(viewport.scale, 1); // no scale
expect(viewport.resizeOffset, Vector2(50, 0)); // y is unchanged
checkProjectorReversibility(game.projector);
// (50, 0) is the top left corner of the camera
expect(game.projector.unprojectVector(Vector2(50, 0)), Vector2.zero());
// the top left of the screen is 50 viewport units to the left,
// but applying the camera zoom on top results in 25 units
// in the game space
expect(game.projector.unprojectVector(Vector2.zero()), Vector2(-25, 0));
// for every two units we walk to right or bottom means one game units
expect(game.projector.unprojectVector(Vector2(52, 20)), Vector2(1, 10));
// the bottom right of the viewport is at (150, 100) on screen
// coordinates for the viewport that is walking (100, 100) in viewport
// units for the camera we need to half that so it means walking
// (50, 50) this is the bottom-right most world pixel that is painted.
expect(
game.projector.unprojectVector(Vector2(150, 100)),
Vector2.all(50),
);
// For deltas, we consider only the 2x zoom of the camera.
expect(game.projector.unscaleVector(Vector2.zero()), Vector2.zero());
expect(game.projector.unscaleVector(Vector2(2, 4)), Vector2(1, 2));
});
testWithFlameGame(
'camera translation & viewport scale+translation',
(game) async {
final viewport = FixedResolutionViewport(Vector2.all(100));
game.camera.viewport = viewport;
game.onGameResize(Vector2(200, 400));
expect(viewport.scale, 2);
expect(viewport.resizeOffset, Vector2(0, 100)); // x is unchanged
// The camera should apply a (10, 10) translation on top of the
// viewport.
game.camera.snapTo(Vector2.all(10));
checkProjectorReversibility(game.projector);
// In the viewport space the top left of the screen would be
// (0, -100), which means 100 viewport units above the top left of the
// camera (10, 10) each viewport unit is twice the camera unit, so
// that is 50 above.
expect(
game.projector.unprojectVector(Vector2.zero()),
Vector2(10, -40),
);
// The top left of the camera should be (10, 10) on game space.
// The top left of the camera should be at (0, 100) on the viewport.
expect(
game.projector.unprojectVector(Vector2(0, 100)),
Vector2(10, 10),
);
// For deltas, we consider only 2x scale of the viewport.
expect(game.projector.unscaleVector(Vector2.zero()), Vector2.zero());
expect(game.projector.unscaleVector(Vector2(2, 4)), Vector2(1, 2));
},
);
testWithFlameGame(
'camera & viewport scale/zoom + translation (cancel out scaling)',
(game) async {
final viewport = FixedResolutionViewport(Vector2.all(100));
game.camera.viewport = viewport;
game.onGameResize(Vector2(200, 400));
expect(viewport.scale, 2);
expect(viewport.resizeOffset, Vector2(0, 100)); // x is unchanged
// The camera should apply a (10, 10) translation + a 0.5x zoom on top
// of the viewport coordinate system.
game.camera.zoom = 0.5;
game.camera.snapTo(Vector2.all(10));
checkProjectorReversibility(game.projector);
// In the viewport space the top left of the screen would be (0, -100)
// that means 100 screen units above the top left of the camera
// (10, 10) each viewport unit is exactly one camera unit, because the
// zoom cancels out the scale.
expect(
game.projector.unprojectVector(Vector2.zero()),
Vector2(10, -90),
);
// The top-left most visible pixel on the viewport would be at
// (0, 100) in screen coordinates. That should be the top left of the
// camera that is snapped to 10,10 by definition.
expect(
game.projector.unprojectVector(Vector2(0, 100)),
Vector2(10, 10),
);
// Now each unit we walk in screen space means only 2 units on the
// viewport space because of the scale. however, since the camera
// applies a 1/2x zoom, each unit step equals to 1 unit on the game
// space.
expect(
game.projector.unprojectVector(Vector2(1, 100)),
Vector2(11, 10),
);
// The last pixel of the viewport is on screen coordinates of
// (200, 300) for the camera, that should be: top left (10,10) +
// effective size (100, 100) * zoom (1/2).
expect(
game.projector.unprojectVector(Vector2(200, 300)),
Vector2.all(210),
);
// For deltas, since the scale and the zoom cancel out, this should
// no-op.
expect(game.projector.unscaleVector(Vector2.zero()), Vector2.zero());
expect(game.projector.unscaleVector(Vector2(1, 2)), Vector2(1, 2));
},
);
testWithFlameGame(
'camera & viewport scale/zoom + translation',
(game) async {
final viewport = FixedResolutionViewport(Vector2.all(100));
game.camera.viewport = viewport;
game.onGameResize(Vector2(200, 400));
expect(viewport.scale, 2);
expect(viewport.resizeOffset, Vector2(0, 100)); // x is unchanged
// The camera should apply a (50, 0) translation + 4x zoom on top of
// the viewport coordinate system.
game.camera.zoom = 4;
game.camera.snapTo(Vector2(50, 0));
checkProjectorReversibility(game.projector);
// In the viewport space the top left of the screen would be (0, -100)
// that means 100 screen units above the top left of the camera
// (50, 0) each screen unit is 1/2 a viewport unit each viewport unit
// is 1/4 of a camera unit so a game unit is 1/8 the screen unit.
expect(
game.projector.unprojectVector(Vector2.zero()),
Vector2(50, -100 / 8),
);
// The top left of the camera (50, 0) should be at screen coordinates
// (0, 100).
expect(
game.projector.unprojectVector(Vector2(0, 100)),
Vector2(50, 0),
);
// now each unit we walk on that 200 unit square on screen equals to
// 1/2 units on the same 100 unit square on the viewport space
// then, given the 4x camera zoom, each viewport unit becomes 4x a
// game unit.
expect(
game.projector.unprojectVector(Vector2(8, 108)),
Vector2(51, 1),
);
expect(
game.projector.unprojectVector(Vector2(16, 104)),
Vector2(52, 0.5),
);
expect(
game.projector.unprojectVector(Vector2(12, 112)),
Vector2(51.5, 1.5),
);
// Deltas only care about the effective scaling factor, which is 8x.
expect(game.projector.unscaleVector(Vector2.zero()), Vector2.zero());
expect(game.projector.unscaleVector(Vector2(8, 16)), Vector2(1, 2));
},
);
testWithGame<FlameGame>(
'children in the constructor',
() {
return FlameGame(
children: [_IndexedComponent(1), _IndexedComponent(2)],
);
},
(game) async {
game.add(_IndexedComponent(3));
game.add(_IndexedComponent(4));
await game.ready();
expect(game.children.length, 4);
expect(
game.children
.whereType<_IndexedComponent>()
.map((c) => c.index)
.isSorted((a, b) => a.compareTo(b)),
isTrue,
);
},
);
testWithGame<FlameGame>(
'children in the constructor and onLoad',
() {
return _ConstructorChildrenGame(
constructorChildren: [_IndexedComponent(1), _IndexedComponent(2)],
onLoadChildren: [_IndexedComponent(3), _IndexedComponent(4)],
);
},
(game) async {
game.add(_IndexedComponent(5));
game.add(_IndexedComponent(6));
await game.ready();
expect(game.children.length, 6);
expect(
game.children
.whereType<_IndexedComponent>()
.map((c) => c.index)
.isSorted((a, b) => a.compareTo(b)),
isTrue,
);
},
);
});
group('Render box attachment', () {
testWidgets('calls on attach', (tester) async {
await tester.runAsync(() async {
var hasAttached = false;
final game = _OnAttachGame(() => hasAttached = true);
await tester.pumpWidget(GameWidget(game: game));
await game.toBeLoaded();
await tester.pump();
expect(hasAttached, isTrue);
});
});
});
});
}
class _IndexedComponent extends Component {
final int index;
_IndexedComponent(this.index);
}
class _ConstructorChildrenGame extends FlameGame {
final Iterable<_IndexedComponent> onLoadChildren;
_ConstructorChildrenGame({
required Iterable<_IndexedComponent> constructorChildren,
required this.onLoadChildren,
}) : super(children: constructorChildren);
@override
Future<void> onLoad() async {
addAll(onLoadChildren);
}
}
class GameWithTappables extends FlameGame with HasTappables {}
class _MyTappableComponent extends _MyComponent with Tappable {
bool tapped = false;
@override
bool onTapDown(_) {
tapped = true;
return true;
}
}
class _MyComponent extends PositionComponent with HasGameRef {
bool isUpdateCalled = false;
bool isRenderCalled = false;
int onRemoveCallCounter = 0;
late Vector2 gameSize;
@override
void update(double dt) {
isUpdateCalled = true;
}
@override
void render(Canvas canvas) {
isRenderCalled = true;
}
@override
void onGameResize(Vector2 gameSize) {
super.onGameResize(gameSize);
this.gameSize = gameSize;
}
@override
bool containsPoint(Vector2 v) => true;
@override
void onRemove() {
super.onRemove();
++onRemoveCallCounter;
}
}
class _MyAsyncComponent extends _MyComponent {
@override
Future<void> onLoad() {
return Future.value();
}
}
class _OnAttachGame extends FlameGame {
final VoidCallback onAttachCallback;
_OnAttachGame(this.onAttachCallback);
@override
void onAttach() {
onAttachCallback();
}
@override
Future<void>? onLoad() {
return Future.delayed(const Duration(seconds: 1));
}
}
| flame/packages/flame/test/game/flame_game_test.dart/0 | {'file_path': 'flame/packages/flame/test/game/flame_game_test.dart', 'repo_id': 'flame', 'token_count': 11637} |
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('MultiTouchDragDetector', () {
testWidgets(
'Game cannot have both MultiTouchDragDetector and PanDetector',
(tester) async {
await tester.pumpWidget(
GameWidget(
game: _MultiDragPanGame(),
),
);
expect(tester.takeException(), isAssertionError);
},
);
});
group('MultiTouchTapDetector', () {
testWidgets(
'Game can have both MultiTouchTapDetector and DoubleTapDetector',
(tester) async {
await tester.pumpWidget(
GameWidget(
game: _MultiTapDoubleTapGame(),
),
);
expect(tester.takeException(), null);
},
);
});
}
class _MultiDragPanGame extends FlameGame
with MultiTouchDragDetector, PanDetector {}
class _MultiTapDoubleTapGame extends FlameGame
with MultiTouchTapDetector, DoubleTapDetector {}
| flame/packages/flame/test/gestures/detectors_test.dart/0 | {'file_path': 'flame/packages/flame/test/gestures/detectors_test.dart', 'repo_id': 'flame', 'token_count': 422} |
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/widgets.dart';
//ignore_for_file: invalid_null_aware_operator
/// {@template _bgm}
/// The looping background music class.
///
/// This class helps with looping background music management that reacts to
/// application lifecycle state changes. On construction, the instance is added
/// as an observer to the [WidgetsBinding] instance. A [dispose] function is
/// provided in case this functionality needs to be unloaded but the app needs
/// to keep running.
/// {@endtemplate}
class Bgm extends WidgetsBindingObserver {
bool _isRegistered = false;
/// The [AudioPlayer] instance that is used to play the audio.
AudioPlayer audioPlayer;
/// Whether [Bgm] is playing or not.
bool isPlaying = false;
/// {@macro _bgm}
Bgm({AudioCache? audioCache})
: audioPlayer = AudioPlayer()
..audioCache = audioCache ?? AudioCache.instance;
/// Registers a [WidgetsBinding] observer.
///
/// This must be called for auto-pause and resume to work properly.
void initialize() {
if (_isRegistered) {
return;
}
_isRegistered = true;
_ambiguate(WidgetsBinding.instance)?.addObserver(this);
}
/// Dispose the [WidgetsBinding] observer.
void dispose() {
audioPlayer.dispose();
if (!_isRegistered) {
return;
}
_ambiguate(WidgetsBinding.instance)?.removeObserver(this);
_isRegistered = false;
}
/// Plays and loops a background music file specified by [fileName].
///
/// The volume can be specified in the optional named parameter [volume]
/// where `0` means off and `1` means max.
///
/// It is safe to call this function even when a current BGM track is
/// playing.
Future<void> play(String fileName, {double volume = 1}) async {
await audioPlayer.dispose();
await audioPlayer.setReleaseMode(ReleaseMode.loop);
await audioPlayer.setVolume(volume);
await audioPlayer.setSource(AssetSource(fileName));
await audioPlayer.resume();
isPlaying = true;
}
/// Stops the currently playing background music track (if any).
Future<void> stop() async {
isPlaying = false;
await audioPlayer.stop();
}
/// Resumes the currently played (but resumed) background music.
Future<void> resume() async {
isPlaying = true;
await audioPlayer.resume();
}
/// Pauses the background music without unloading or resetting the audio
/// player.
Future<void> pause() async {
isPlaying = false;
await audioPlayer.pause();
}
/// Handler for AppLifecycleState changes.
///
/// This function handles the automatic pause and resume when the app
/// lifecycle state changes. There is NO NEED to call this function directly
/// directly.
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
if (isPlaying && audioPlayer.state == PlayerState.paused) {
audioPlayer.resume();
}
} else {
audioPlayer.pause();
}
}
}
/// This allows a value of type T or T?
/// to be treated as a value of type T?.
///
/// We use this so that APIs that have become
/// non-nullable can still be used with `!` and `?`
/// to support older versions of the API as well.
///
/// See more: https://docs.flutter.dev/development/tools/sdk/release-notes/release-notes-3.0.0
T? _ambiguate<T>(T? value) => value;
| flame/packages/flame_audio/lib/bgm.dart/0 | {'file_path': 'flame/packages/flame_audio/lib/bgm.dart', 'repo_id': 'flame', 'token_count': 1078} |
import 'package:flame_bloc_example/src/game_stats/bloc/game_stats_bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class GameStat extends StatelessWidget {
const GameStat({super.key});
@override
Widget build(BuildContext context) {
return BlocConsumer<GameStatsBloc, GameStatsState>(
builder: (context, state) {
return Container(
height: 50,
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text('Score: ${state.score}'),
Text('Lives: ${state.lives}'),
],
),
);
},
listenWhen: (previous, current) =>
previous.status != current.status &&
current.status == GameStatus.gameOver,
listener: (context, state) {
final bloc = context.read<GameStatsBloc>();
showDialog<void>(
context: context,
builder: (context) {
return Dialog(
child: Container(
height: 200,
padding: const EdgeInsets.all(32),
child: Center(
child: Column(
children: [
Text(
'Game Over',
style: Theme.of(context).textTheme.headline2,
),
ElevatedButton(
onPressed: () {
bloc.add(const GameReset());
Navigator.of(context).pop();
},
child: const Text('Reset'),
),
],
),
),
),
);
},
);
},
);
}
}
| flame/packages/flame_bloc/example/lib/src/game_stats/view/game_stat.dart/0 | {'file_path': 'flame/packages/flame_bloc/example/lib/src/game_stats/view/game_stat.dart', 'repo_id': 'flame', 'token_count': 1039} |
import 'package:bloc/bloc.dart';
enum PlayerState { alive, dead, sad }
class PlayerCubit extends Cubit<PlayerState> {
PlayerCubit() : super(PlayerState.alive);
void kill() {
emit(PlayerState.dead);
}
void makeSad() {
emit(PlayerState.sad);
}
void riseFromTheDead() {
emit(PlayerState.alive);
}
}
| flame/packages/flame_bloc/test/player_cubit.dart/0 | {'file_path': 'flame/packages/flame_bloc/test/player_cubit.dart', 'repo_id': 'flame', 'token_count': 123} |
include: package:flame_lint/analysis_options.yaml
| flame/packages/flame_forge2d/example/analysis_options.yaml/0 | {'file_path': 'flame/packages/flame_forge2d/example/analysis_options.yaml', 'repo_id': 'flame', 'token_count': 16} |
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:test/expect.dart';
import 'package:test/scaffolding.dart';
import 'helpers/helpers.dart';
void main() {
group('ContactCallbacks', () {
late Object other;
late Contact contact;
late Manifold manifold;
late ContactImpulse contactImpulse;
setUp(() {
other = Object();
contact = MockContact();
manifold = MockManifold();
contactImpulse = MockContactImpulse();
});
test('beginContact calls onBeginContact', () {
final contactCallbacks = ContactCallbacks();
var called = 0;
contactCallbacks.onBeginContact = (_, __) => called++;
contactCallbacks.beginContact(other, contact);
expect(called, equals(1));
});
test('endContact calls onEndContact', () {
final contactCallbacks = ContactCallbacks();
var called = 0;
contactCallbacks.onEndContact = (_, __) => called++;
contactCallbacks.endContact(other, contact);
expect(called, equals(1));
});
test('preSolve calls onPreSolve', () {
final contactCallbacks = ContactCallbacks();
var called = 0;
contactCallbacks.onPreSolve = (_, __, ___) => called++;
contactCallbacks.preSolve(other, contact, manifold);
expect(called, equals(1));
});
test('postSolve calls on postSolve', () {
final contactCallbacks = ContactCallbacks();
var called = 0;
contactCallbacks.onPostSolve = (_, __, ___) => called++;
contactCallbacks.postSolve(other, contact, contactImpulse);
expect(called, equals(1));
});
});
}
| flame/packages/flame_forge2d/test/contact_callbacks_test.dart/0 | {'file_path': 'flame/packages/flame_forge2d/test/contact_callbacks_test.dart', 'repo_id': 'flame', 'token_count': 592} |
/// The flame_lint package doesn't ship any dart source code.
///
/// To enable `flame_lint`,
/// 1. Add it to your dev_dependencies
/// ```yaml
/// dev_dependencies:
/// flame_lint: VERSION
/// ```
///
/// 2. Include the rules into your `analysis_options.yaml`
/// ```yaml
/// include: package:flame_lint/analysis_options.yaml
/// ```
library flame_lint;
| flame/packages/flame_lint/lib/flame_lint.dart/0 | {'file_path': 'flame/packages/flame_lint/lib/flame_lint.dart', 'repo_id': 'flame', 'token_count': 121} |
import 'package:flame/game.dart';
import 'package:flame_oxygen/flame_oxygen.dart';
import 'package:flutter/material.dart';
class DebugSystem extends BaseSystem {
final debugPaint = Paint()
..color = Colors.green
..style = PaintingStyle.stroke;
final textPainter = TextPaint(
style: const TextStyle(color: Colors.green, fontSize: 10),
);
final statusPainter = TextPaint(
style: const TextStyle(color: Colors.green, fontSize: 16),
);
@override
List<Filter<Component>> get filters => [];
@override
void render(Canvas canvas) {
super.render(canvas);
statusPainter.render(
canvas,
[
'Entities: ${world!.entities.length}',
].join('\n'),
Vector2.zero(),
);
}
@override
void renderEntity(Canvas canvas, Entity entity) {
final size = entity.get<SizeComponent>()!.size;
canvas.drawRect(Vector2.zero() & size, debugPaint);
textPainter.render(
canvas,
[
'position: ${entity.get<PositionComponent>()!.position}',
'size: $size',
'angle: ${entity.get<AngleComponent>()?.radians ?? 0}',
'anchor: ${entity.get<AnchorComponent>()?.anchor ?? Anchor.topLeft}',
].join('\n'),
Vector2(size.x + 2, 0),
);
textPainter.render(
canvas,
entity.name ?? '',
Vector2(size.x / 2, size.y + 2),
anchor: Anchor.topCenter,
);
}
}
| flame/packages/flame_oxygen/example/lib/system/debug_system.dart/0 | {'file_path': 'flame/packages/flame_oxygen/example/lib/system/debug_system.dart', 'repo_id': 'flame', 'token_count': 567} |
import 'package:flame/extensions.dart';
import 'package:oxygen/oxygen.dart';
class PositionComponent extends Component<Vector2> {
late Vector2 _position;
Vector2 get position => _position;
set position(Vector2 position) => _position.setFrom(position);
double get x => _position.x;
set x(double x) => _position.x = x;
double get y => _position.y;
set y(double y) => _position.y = y;
@override
void init([Vector2? position]) {
_position = position?.clone() ?? Vector2.zero();
}
@override
void reset() => _position.setZero();
}
| flame/packages/flame_oxygen/lib/src/component/position_component.dart/0 | {'file_path': 'flame/packages/flame_oxygen/lib/src/component/position_component.dart', 'repo_id': 'flame', 'token_count': 185} |
import 'package:flutter_test/flutter_test.dart';
import 'package:vector_math/vector_math_64.dart';
/// Returns a matcher which checks if the argument is an axis-aligned bounding
/// box sufficiently close (within distance [epsilon]) to [expected]. Example
/// of usage:
/// ```dart
/// expect(
/// component.aabb,
/// closeToAabb(Aabb2.minMax(Vector2.zero(), Vector2.all(1)), 1e-5),
/// );
/// ```
Matcher closeToAabb(Aabb2 expected, [double epsilon = 1e-15]) {
return _IsCloseToAabb(expected, epsilon);
}
class _IsCloseToAabb extends Matcher {
const _IsCloseToAabb(this._expected, this._epsilon);
final Aabb2 _expected;
final double _epsilon;
@override
bool matches(dynamic item, Map matchState) {
return (item is Aabb2) &&
(item.min - _expected.min).length <= _epsilon &&
(item.max - _expected.max).length <= _epsilon;
}
@override
Description describe(Description description) {
return description.add(
'an Aabb2 object within $_epsilon of Aabb2([${_expected.min.x}, '
'${_expected.min.y}]..[${_expected.max.x}, ${_expected.max.y}])',
);
}
@override
Description describeMismatch(
dynamic item,
Description mismatchDescription,
Map matchState,
bool verbose,
) {
if (item is! Aabb2) {
return mismatchDescription.add('is not an instance of Aabb2');
}
final minDiff = (item.min - _expected.min).length;
final maxDiff = (item.max - _expected.max).length;
if (minDiff > _epsilon) {
mismatchDescription.add('min corner is at distance $minDiff\n');
}
if (maxDiff > _epsilon) {
mismatchDescription.add('max corner is at distance $maxDiff\n');
}
return mismatchDescription.add(
'Aabb2([${item.min.x}, ${item.min.y}]..[${item.max.x}, ${item.max.y}])',
);
}
}
| flame/packages/flame_test/lib/src/close_to_aabb.dart/0 | {'file_path': 'flame/packages/flame_test/lib/src/close_to_aabb.dart', 'repo_id': 'flame', 'token_count': 690} |
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('Golden tests', () {
final tester = FlameTester(FlameGame.new);
tester.testGameWidget(
'renders correctly',
setUp: (game, _) async {
await game.ensureAdd(
CircleComponent(
radius: 10,
position: Vector2.all(100),
paint: Paint()..color = Colors.white,
),
);
},
verify: (game, tester) async {
await expectLater(
find.byGame<FlameGame>(),
matchesGoldenFile('golden_test.png'),
);
},
);
testGolden(
'Same test but with testGolden',
(game) async {
final paint = Paint()..color = Colors.white;
game.add(
CircleComponent(radius: 10, position: Vector2.all(100), paint: paint),
);
},
goldenFile: 'golden_test.png',
);
testGolden(
'skipped test',
(game) async {},
goldenFile: 'golden_test.png',
skip: true,
);
});
}
| flame/packages/flame_test/test/golden_test.dart/0 | {'file_path': 'flame/packages/flame_test/test/golden_test.dart', 'repo_id': 'flame', 'token_count': 547} |
import 'package:dashbook/dashbook.dart';
import 'package:flutter/material.dart';
import 'package:tutorials_space_shooter/steps/1_getting_started/getting_started.dart';
void main() {
final dashbook = Dashbook.dualTheme(
light: ThemeData.light(),
dark: ThemeData.dark(),
initWithLight: false,
);
addGettingStarted(dashbook);
runApp(dashbook);
}
| flame/tutorials/space_shooter/lib/main.dart/0 | {'file_path': 'flame/tutorials/space_shooter/lib/main.dart', 'repo_id': 'flame', 'token_count': 131} |
import 'package:flutter/material.dart';
class SwitchButton extends StatefulWidget {
final bool on;
final Function onChange;
final String label;
SwitchButton({this.on, this.onChange, this.label});
@override
State createState() {
return _SwitchButtonState();
}
}
class _SwitchButtonState extends State<SwitchButton> {
bool _status = true;
void handleChange(value) {
setState(() => _status = value);
widget.onChange();
}
@override
void initState() {
super.initState();
_status = widget.on;
}
@override
Widget build(_) {
return Container(
width: 100,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
widget.label,
style: TextStyle(fontFamily: 'Liberation Sans', fontSize: 12),
),
Container(
padding: EdgeInsets.only(top: 6),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(width: 1),
),
),
),
Row(children: [
Text('Off', style: TextStyle(fontFamily: 'Liberation Sans', fontSize: 12)),
Switch(
activeColor: Color(0xff8a3842),
activeTrackColor: Color(0xff86898a),
inactiveThumbColor: Color(0xff8a3842),
value: _status,
onChanged: handleChange,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
Text('On', style: TextStyle(fontFamily: 'Liberation Sans', fontSize: 12)),
]),
],
),
);
}
}
| flame_and_watch/lib/widgets/swtich_button.dart/0 | {'file_path': 'flame_and_watch/lib/widgets/swtich_button.dart', 'repo_id': 'flame_and_watch', 'token_count': 776} |
export 'spawning_behavior.dart';
| flame_behaviors/packages/flame_behaviors/example/lib/behaviors/behaviors.dart/0 | {'file_path': 'flame_behaviors/packages/flame_behaviors/example/lib/behaviors/behaviors.dart', 'repo_id': 'flame_behaviors', 'token_count': 11} |
import 'package:example/entities/entities.dart';
import 'package:flame/extensions.dart';
import 'package:flame_behaviors/flame_behaviors.dart';
import 'package:flutter/material.dart';
class RectangleCollidingBehavior
extends CollisionBehavior<Rectangle, Rectangle> {
final _collisionColor = Colors.yellow.withOpacity(0.8);
@override
void onCollisionStart(Set<Vector2> intersectionPoints, Rectangle other) {
parent.paint.color = _collisionColor;
}
@override
void onCollisionEnd(Rectangle other) {
if (!isColliding) {
parent.paint.color = parent.defaultColor;
}
}
}
| flame_behaviors/packages/flame_behaviors/example/lib/entities/rectangle/behaviors/rectangle_colliding_behavior.dart/0 | {'file_path': 'flame_behaviors/packages/flame_behaviors/example/lib/entities/rectangle/behaviors/rectangle_colliding_behavior.dart', 'repo_id': 'flame_behaviors', 'token_count': 210} |
// ignore_for_file: cascade_invocations, deprecated_member_use_from_same_package
import 'package:flame/components.dart';
import 'package:flame_behaviors/flame_behaviors.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
class _TestEntity extends PositionedEntity {
_TestEntity({super.behaviors}) : super(size: Vector2.all(32));
}
class _TestBehavior extends Behavior<_TestEntity> {}
void main() {
group('Behavior', () {
flameGame.testGameWidget(
'can be added to an Entity',
setUp: (game, tester) async {
final behavior = _TestBehavior();
final entity = _TestEntity(behaviors: [behavior]);
await game.ensureAdd(entity);
},
verify: (game, tester) async {
final entity = game.firstChild<_TestEntity>()!;
expect(game.descendants().whereType<_TestBehavior>().length, equals(1));
expect(entity.children.whereType<_TestBehavior>().length, equals(1));
},
);
flameGame.testGameWidget(
'contains point is relative to parent',
setUp: (game, tester) async {
final behavior = _TestBehavior();
final entity = _TestEntity(behaviors: [behavior]);
await game.ensureAdd(entity);
},
verify: (game, tester) async {
final entity = game.firstChild<_TestEntity>()!;
final behavior = entity.firstChild<_TestBehavior>()!;
expect(behavior.containsPoint(Vector2.zero()), isTrue);
expect(behavior.containsPoint(Vector2(31, 31)), isTrue);
expect(behavior.containsPoint(Vector2(32, 32)), isFalse);
},
);
flameGame.testGameWidget(
'contains local point is relative to parent',
setUp: (game, tester) async {
final behavior = _TestBehavior();
final entity = _TestEntity(behaviors: [behavior]);
await game.ensureAdd(entity);
},
verify: (game, tester) async {
final entity = game.firstChild<_TestEntity>()!;
final behavior = entity.firstChild<_TestBehavior>()!;
expect(behavior.containsLocalPoint(Vector2.zero()), isTrue);
expect(behavior.containsLocalPoint(Vector2(31, 31)), isTrue);
expect(behavior.containsLocalPoint(Vector2(32, 32)), isFalse);
},
);
flameGame.testGameWidget(
'debugMode is provided by the parent',
setUp: (game, tester) async {
final behavior = _TestBehavior();
final entity = _TestEntity(behaviors: [behavior]);
await game.ensureAdd(entity);
},
verify: (game, tester) async {
final entity = game.firstChild<_TestEntity>()!;
final behavior = entity.firstChild<_TestBehavior>()!;
expect(behavior.debugMode, isFalse);
entity.debugMode = true;
expect(behavior.debugMode, isTrue);
},
);
group('children', () {
late _TestBehavior testBehavior;
late _TestEntity testEntity;
setUp(() {
testBehavior = _TestBehavior();
testEntity = _TestEntity(
behaviors: [testBehavior],
);
});
flameGame.testGameWidget(
'can have its own children',
setUp: (game, tester) async {
await game.ensureAdd(testEntity);
},
verify: (game, tester) async {
expect(() => testBehavior.add(Component()), returnsNormally);
},
);
flameGame.testGameWidget(
'can not have behaviors as children',
setUp: (game, tester) async {
await game.ensureAdd(testEntity);
},
verify: (game, tester) async {
expect(
() => testBehavior.add(_TestBehavior()),
failsAssert('Behaviors cannot have behaviors.'),
);
},
);
flameGame.testGameWidget(
'can not have entities as children',
setUp: (game, tester) async {
await game.ensureAdd(testEntity);
},
verify: (game, tester) async {
expect(
() => testBehavior.add(_TestEntity()),
failsAssert('Behaviors cannot have entities.'),
);
},
);
});
});
}
| flame_behaviors/packages/flame_behaviors/test/src/behaviors/behavior_test.dart/0 | {'file_path': 'flame_behaviors/packages/flame_behaviors/test/src/behaviors/behavior_test.dart', 'repo_id': 'flame_behaviors', 'token_count': 1747} |
import 'package:example/src/example_game.dart';
import 'package:flame/game.dart';
import 'package:flutter/material.dart';
void main() {
runApp(GameWidget(game: ExampleGame()));
}
| flame_behaviors/packages/flame_steering_behaviors/example/lib/main.dart/0 | {'file_path': 'flame_behaviors/packages/flame_steering_behaviors/example/lib/main.dart', 'repo_id': 'flame_behaviors', 'token_count': 63} |
import 'package:flame/components.dart';
import 'package:flame_steering_behaviors/flame_steering_behaviors.dart';
/// {@template separation_behavior}
/// Separation steering behavior.
/// {@endtemplate}
class SeparationBehavior<Parent extends Steerable>
extends SteeringBehavior<Parent> {
/// {@macro separation_behavior}
SeparationBehavior(
this.entities, {
required this.maxDistance,
required this.maxAcceleration,
});
/// The maximum distance at which the entity will separate.
final double maxDistance;
/// The maximum acceleration the entity can apply to enable separation.
final double maxAcceleration;
/// The entities to separate from.
final List<PositionComponent> entities;
@override
void update(double dt) {
steer(
Separation(
entities,
maxDistance: maxDistance,
maxAcceleration: maxAcceleration,
),
dt,
);
}
}
| flame_behaviors/packages/flame_steering_behaviors/lib/src/behaviors/separation_behavior.dart/0 | {'file_path': 'flame_behaviors/packages/flame_steering_behaviors/lib/src/behaviors/separation_behavior.dart', 'repo_id': 'flame_behaviors', 'token_count': 302} |
// ignore_for_file: cascade_invocations
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() {
final flameTester = FlameTester(TestGame.new);
group('FleeBehavior', () {
flameTester.testGameWidget(
'only flee if target is within panic distance',
setUp: (game, tester) async {
final target = SteerableEntity();
final parent = SteerableEntity(
behaviors: [
FleeBehavior(
target,
maxAcceleration: 100,
panicDistance: 20,
),
],
position: Vector2.zero(),
size: Vector2.all(32),
);
await game.ensureAddAll([parent, target]);
},
verify: (game, tester) async {
final parent = game.children.whereType<SteerableEntity>().first;
final target = game.children.whereType<SteerableEntity>().last;
// Move target outside panic distance.
target.position.setValues(20, 20);
game.update(1);
expect(parent.velocity, closeToVector(Vector2(0, 0), 0.01));
// Move target inside panic distance.
target.position.setValues(5, 5);
game.update(1);
expect(parent.velocity, closeToVector(Vector2(-70.71, -70.71), 0.01));
},
);
flameTester.testGameWidget(
'render panic distance as a circle in debug mode',
setUp: (game, tester) async {
final entity = SteerableEntity(
behaviors: [
FleeBehavior(
SteerableEntity(),
maxAcceleration: 100,
panicDistance: 64,
),
],
position: game.size / 2,
size: Vector2.all(32),
)..debugMode = true;
await game.ensureAdd(entity);
},
verify: (game, tester) async {
await tester.pump();
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('golden/flee_behavior/render_debug_mode.png'),
);
},
);
});
}
| flame_behaviors/packages/flame_steering_behaviors/test/src/behaviors/flee_behavior_test.dart/0 | {'file_path': 'flame_behaviors/packages/flame_steering_behaviors/test/src/behaviors/flee_behavior_test.dart', 'repo_id': 'flame_behaviors', 'token_count': 1003} |
import 'dart:math';
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'components/components.dart';
class FlameCentipede extends FlameGame
with HasKeyboardHandlerComponents, HasCollisionDetection, PanDetector {
static final resolution = Vector2(256, 240);
FlameCentipede() {
camera.viewport = FixedResolutionViewport(resolution);
}
late Player player;
@override
Future<void> onLoad() async {
await super.onLoad();
add(Background());
_loadGame();
}
void _loadGame() {
add(player = Player());
for (var x = 0; x < 15; x++) {
add(CentipedeBlock.atIndex(x, 0));
}
final random = Random();
final grid = CentipedeBlock.dimensions;
for (var y = grid.y * 2; y < grid.y * 12; y += grid.y * 3) {
for (var x = 0.0; x < grid.x * 14; x += grid.x * 3) {
add(Mushroom.atIndex(x + (random.nextDouble() * grid.x * 2), y));
}
}
}
@override
void onPanStart(_) {
player.beginFiring();
}
@override
void onPanEnd(_) {
player.stopFiring();
}
@override
void onPanCancel() {
player.stopFiring();
}
@override
void onPanUpdate(DragUpdateInfo info) {
player.move(info.delta.game);
}
void gameOver() {
removeWhere((element) => element is! Background);
_loadGame();
}
}
| flame_centipede/lib/src/game/game.dart/0 | {'file_path': 'flame_centipede/lib/src/game/game.dart', 'repo_id': 'flame_centipede', 'token_count': 520} |
import 'dart:ui';
import 'package:flame/game.dart';
import 'package:flame/keyboard.dart';
import 'package:flame/palette.dart';
import 'package:flutter/services.dart' show RawKeyDownEvent, RawKeyEvent;
class KeyboardGame extends Game with KeyboardEvents {
static final Paint _white = BasicPalette.white.paint;
static const int speed = 200;
Rect _rect = const Rect.fromLTWH(0, 100, 100, 100);
final Vector2 velocity = Vector2(0, 0);
@override
void update(double dt) {
final displacement = velocity * (speed * dt);
_rect = _rect.translate(displacement.x, displacement.y);
}
@override
void render(Canvas canvas) {
canvas.drawRect(_rect, _white);
}
@override
void onKeyEvent(RawKeyEvent e) {
final isKeyDown = e is RawKeyDownEvent;
if (e.data.keyLabel == 'a') {
velocity.x = isKeyDown ? -1 : 0;
} else if (e.data.keyLabel == 'd') {
velocity.x = isKeyDown ? 1 : 0;
} else if (e.data.keyLabel == 'w') {
velocity.y = isKeyDown ? -1 : 0;
} else if (e.data.keyLabel == 's') {
velocity.y = isKeyDown ? 1 : 0;
}
}
}
| flame_example/lib/stories/controls/keyboard.dart/0 | {'file_path': 'flame_example/lib/stories/controls/keyboard.dart', 'repo_id': 'flame_example', 'token_count': 422} |
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame/parallax.dart';
class ComponentParallaxGame extends BaseGame {
@override
Future<void> onLoad() async {
add(MyParallaxComponent());
}
}
class MyParallaxComponent extends ParallaxComponent
with HasGameRef<ComponentParallaxGame> {
@override
Future<void> onLoad() async {
parallax = await gameRef.loadParallax(
[
'parallax/bg.png',
'parallax/mountain-far.png',
'parallax/mountains.png',
'parallax/trees.png',
'parallax/foreground-trees.png',
],
size,
baseVelocity: Vector2(20, 0),
velocityMultiplierDelta: Vector2(1.8, 1.0),
);
}
}
| flame_example/lib/stories/parallax/component.dart/0 | {'file_path': 'flame_example/lib/stories/parallax/component.dart', 'repo_id': 'flame_example', 'token_count': 312} |
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flutter/material.dart';
class NineTileBoxGame extends Game {
NineTileBox nineTileBox;
@override
Future<void> onLoad() async {
final sprite = Sprite(await images.load('nine-box.png'));
nineTileBox = NineTileBox(sprite, tileSize: 8, destTileSize: 24);
}
@override
void render(Canvas canvas) {
const length = 300.0;
final boxSize = Vector2.all(length);
final position = (size - boxSize) / 2;
nineTileBox.draw(canvas, position, boxSize);
}
@override
void update(double t) {}
}
| flame_example/lib/stories/utils/nine_tile_box.dart/0 | {'file_path': 'flame_example/lib/stories/utils/nine_tile_box.dart', 'repo_id': 'flame_example', 'token_count': 218} |
import 'dart:math' as math;
import 'package:forge2d/forge2d.dart';
import 'package:flame/palette.dart';
import 'package:flame_forge2d/body_component.dart';
import 'package:flame_forge2d/contact_callbacks.dart';
import 'package:flutter/material.dart';
import 'boundaries.dart';
class Ball extends BodyComponent {
late Paint originalPaint;
bool giveNudge = false;
final double radius;
Vector2 _position;
double _timeSinceNudge = 0.0;
static const double _minNudgeRest = 2.0;
final Paint _blue = BasicPalette.blue.paint();
Ball(this._position, {this.radius = 2}) {
originalPaint = randomPaint();
this.paint = originalPaint;
}
Paint randomPaint() {
final rng = math.Random();
return PaletteEntry(
Color.fromARGB(
100 + rng.nextInt(155),
100 + rng.nextInt(155),
100 + rng.nextInt(155),
255,
),
).paint();
}
@override
Body createBody() {
final CircleShape shape = CircleShape();
shape.radius = radius;
final fixtureDef = FixtureDef(shape)
..restitution = 0.8
..density = 1.0
..friction = 0.4;
final bodyDef = BodyDef()
// To be able to determine object in collision
..userData = this
..angularDamping = 0.8
..position = _position
..type = BodyType.dynamic;
return world.createBody(bodyDef)..createFixture(fixtureDef);
}
@override
void renderCircle(Canvas c, Offset center, double radius) {
super.renderCircle(c, center, radius);
final lineRotation = Offset(0, radius);
c.drawLine(center, center + lineRotation, _blue);
}
@override
void update(double t) {
super.update(t);
_timeSinceNudge += t;
if (giveNudge) {
giveNudge = false;
if (_timeSinceNudge > _minNudgeRest) {
body.applyLinearImpulse(Vector2(0, 1000));
_timeSinceNudge = 0.0;
}
}
}
}
class WhiteBall extends Ball {
WhiteBall(Vector2 position) : super(position) {
originalPaint = BasicPalette.white.paint();
paint = originalPaint;
}
}
class BallContactCallback extends ContactCallback<Ball, Ball> {
@override
void begin(Ball ball1, Ball ball2, Contact contact) {
if (ball1 is WhiteBall || ball2 is WhiteBall) {
return;
}
if (ball1.paint != ball1.originalPaint) {
ball1.paint = ball2.paint;
} else {
ball2.paint = ball1.paint;
}
}
@override
void end(Ball ball1, Ball ball2, Contact contact) {}
}
class WhiteBallContactCallback extends ContactCallback<Ball, WhiteBall> {
@override
void begin(Ball ball, WhiteBall whiteBall, Contact contact) {
ball.giveNudge = true;
}
@override
void end(Ball ball, WhiteBall whiteBall, Contact contact) {}
}
class BallWallContactCallback extends ContactCallback<Ball, Wall> {
@override
void begin(Ball ball, Wall wall, Contact contact) {
wall.paint = ball.paint;
}
@override
void end(Ball ball, Wall wall, Contact contact) {}
}
| flame_forge2d/example/lib/balls.dart/0 | {'file_path': 'flame_forge2d/example/lib/balls.dart', 'repo_id': 'flame_forge2d', 'token_count': 1127} |
name: flame_gamepad
description: A new flutter plugin project.
version: 0.0.2
author: Fireslime <contact@fireslime.xyz>
homepage: https://github.com/fireslime/flame_gamepad
environment:
sdk: ">=2.0.0-dev.68.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# This section identifies this Flutter project as a plugin project.
# The androidPackage and pluginClass identifiers should not ordinarily
# be modified. They are used by the tooling to maintain consistency when
# adding or updating assets for this project.
plugin:
androidPackage: xyz.fireslime.flamegamepad
pluginClass: FlameGamepadPlugin
# To add assets to your plugin package, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
#
# For details regarding assets in packages, see
# https://flutter.io/assets-and-images/#from-packages
#
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.io/assets-and-images/#resolution-aware.
# To add custom fonts to your plugin package, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts in packages, see
# https://flutter.io/custom-fonts/#from-packages
| flame_gamepad/pubspec.yaml/0 | {'file_path': 'flame_gamepad/pubspec.yaml', 'repo_id': 'flame_gamepad', 'token_count': 651} |
import 'package:flutter_test/flutter_test.dart';
import 'package:flame_geom/rectangle.dart';
void main() {
test('basis', () {
final r = Rectangle.fromLTWH(2, 2, 3, 4);
expect(r.x, 2);
expect(r.y, 2);
expect(r.w, 3);
expect(r.h, 4);
expect(r.left, 2);
expect(r.top, 2);
expect(r.right, 5);
expect(r.bottom, 6);
});
}
| flame_geom/test/rectangle_test.dart/0 | {'file_path': 'flame_geom/test/rectangle_test.dart', 'repo_id': 'flame_geom', 'token_count': 173} |
import 'dart:math';
import 'package:collision_detection_performance/components/enemy_component.dart';
import 'package:flame/components.dart';
class EnemyCreator extends TimerComponent with HasGameRef {
final Random random = Random();
final _halfWidth = EnemyComponent.initialSize.x / 2;
EnemyCreator() : super(period: 0.05, repeat: true);
@override
void onTick() {
gameRef.addAll(
List.generate(
5,
(index) => EnemyComponent(
position: Vector2(
_halfWidth + (gameRef.size.x - _halfWidth) * random.nextDouble(),
0,
),
),
),
);
}
}
| flame_perfomance_test_game/collision_detection/lib/components/enemy_creator.dart/0 | {'file_path': 'flame_perfomance_test_game/collision_detection/lib/components/enemy_creator.dart', 'repo_id': 'flame_perfomance_test_game', 'token_count': 263} |
import 'package:flutter/material.dart';
import 'package:flame/game.dart';
import 'package:flame/flame.dart';
import 'package:flame/components/animation_component.dart';
import 'package:flame_scrolling_sprite/flame_scrolling_sprite.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Flame.util.fullScreen();
final size = await Flame.util.initialDimensions();
runApp(MyGame(size).widget);
}
class MyGame extends BaseGame {
final Size size;
MyGame(this.size) {
add(ScrollingSpriteComponent(
scrollingSprite: ScrollingSprite(
spritePath: 'desert/clouds.png',
width: size.width,
spriteDestWidth: 640,
spriteDestHeight: 160,
horizontalSpeed: -50,
),
y: 40,
));
add(ScrollingSpriteComponent(
scrollingSprite: ScrollingSprite(
spritePath: 'desert/mountains.png',
width: size.width,
spriteDestWidth: 640,
spriteDestHeight: 160,
height: size.height,
horizontalSpeed: -100,
),
y: size.height - 180,
));
add(ScrollingSpriteComponent(
scrollingSprite: ScrollingSprite(
spritePath: 'desert/ground.png',
width: size.width,
spriteDestWidth: 320,
spriteDestHeight: 160,
horizontalSpeed: -300,
),
y: size.height - 160,
));
add(AnimationComponent.sequenced(
192.0,
64.0,
'desert/train.png',
8,
textureWidth: 96.0,
textureHeight: 32.0,
)
..y = size.height - 65
..x = size.width / 2 - 96);
add(ScrollingSpriteComponent(
scrollingSprite: ScrollingSprite(
spritePath: 'desert/foreground.png',
width: size.width,
spriteDestWidth: 1280,
spriteDestHeight: 160,
height: size.height,
horizontalSpeed: -1500,
),
y: size.height - 160,
));
}
@override
Color backgroundColor() => const Color(0xFF73acb6);
}
| flame_scrolling_sprite/example/lib/main_desert.dart/0 | {'file_path': 'flame_scrolling_sprite/example/lib/main_desert.dart', 'repo_id': 'flame_scrolling_sprite', 'token_count': 845} |
name: flame_shells
description: Beautiful and easy to use widgets that emulates console shells for your Flame game
version: 0.0.1
homepage: https://github.com/flame-engine/flame_shells
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
meta: ^1.1.8
flame: ^0.18.1
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
| flame_shells/pubspec.yaml/0 | {'file_path': 'flame_shells/pubspec.yaml', 'repo_id': 'flame_shells', 'token_count': 142} |
import 'package:bloc/bloc.dart';
import 'package:example/location_flow/location_flow.dart';
class CountrySelectionCubit extends Cubit<LocationState> {
CountrySelectionCubit(this._locationRepository)
: super(const LocationState.initial());
final LocationRepository _locationRepository;
Future<void> countriesRequested() async {
emit(const LocationState.loading());
try {
final countryList = await _locationRepository.getCountries();
final countries = countryList.map((c) => c.name).toList();
emit(LocationState.success(countries));
} catch (_) {
emit(const LocationState.failure());
}
}
void countrySelected(String? value) {
if (state.status == LocationStatus.success) {
emit(state.copyWith(selectedLocation: value));
}
}
}
| flow_builder/example/lib/location_flow/pages/country_selection/country_selection_cubit.dart/0 | {'file_path': 'flow_builder/example/lib/location_flow/pages/country_selection/country_selection_cubit.dart', 'repo_id': 'flow_builder', 'token_count': 266} |
import 'package:flow_builder/flow_builder.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('FlowBuilder', () {
group('constructor', () {
test('throws when state is null and controller is null', () async {
expect(
() => FlowBuilder(
onGeneratePages: (dynamic _, List<Page<dynamic>> __) => [],
),
throwsAssertionError,
);
});
test('throws when state and controller are both provided', () async {
expect(
() => FlowBuilder(
onGeneratePages: (dynamic _, List<Page<dynamic>> __) => [],
state: '',
controller: FlowController(''),
),
throwsAssertionError,
);
});
test('does not throw when state is null if controller is present',
() async {
expect(
() => FlowBuilder(
onGeneratePages: (dynamic _, List<Page<dynamic>> __) => [],
controller: FlowController(''),
),
isNot(throwsAssertionError),
);
});
test('does not throw when controller is null if state is present',
() async {
expect(
() => FlowBuilder(
state: 0,
onGeneratePages: (dynamic _, List<Page<dynamic>> __) => [],
),
isNot(throwsAssertionError),
);
});
});
testWidgets(
'throws FlutterError when context.flow is called '
'outside of FlowBuilder', (tester) async {
await tester.pumpWidget(
Builder(
builder: (context) {
context.flow<int>();
return const SizedBox();
},
),
);
final exception = await tester.takeException() as FlutterError;
const expectedMessage = '''
context.flow<int>() called with a context that does not contain a FlowBuilder of type int.
This can happen if the context you used comes from a widget above the FlowBuilder.
The context used was: Builder(dirty)
''';
expect(exception.message, expectedMessage);
});
testWidgets('renders correct navigation stack w/one page', (tester) async {
const targetKey = Key('__target__');
var lastPages = <Page<dynamic>>[];
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
lastPages = pages;
return const <Page<dynamic>>[
MaterialPage<void>(child: SizedBox(key: targetKey)),
];
},
),
),
);
expect(find.byKey(targetKey), findsOneWidget);
expect(lastPages, isEmpty);
});
testWidgets('renders correct navigation stack w/multi-page',
(tester) async {
const box1Key = Key('__target1__');
const box2Key = Key('__target2__');
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
return const <Page<dynamic>>[
MaterialPage<void>(child: SizedBox(key: box1Key)),
MaterialPage<void>(child: SizedBox(key: box2Key)),
];
},
),
),
);
expect(find.byKey(box1Key), findsNothing);
expect(find.byKey(box2Key), findsOneWidget);
});
testWidgets('renders correct navigation stack w/multi-page and condition',
(tester) async {
const box1Key = Key('__box1__');
const box2Key = Key('__box2__');
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
return <Page<dynamic>>[
const MaterialPage<void>(child: SizedBox(key: box1Key)),
if (state >= 1)
const MaterialPage<void>(child: SizedBox(key: box2Key)),
];
},
),
),
);
expect(find.byKey(box1Key), findsOneWidget);
expect(find.byKey(box2Key), findsNothing);
});
testWidgets('update triggers a rebuild with correct state', (tester) async {
const buttonKey = Key('__button__');
const boxKey = Key('__box__');
var numBuilds = 0;
var lastPages = <Page<dynamic>>[];
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
numBuilds++;
lastPages = pages;
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) => TextButton(
key: buttonKey,
child: const Text('Button'),
onPressed: () => context.flow<int>().update((s) => s + 1),
),
),
),
if (state == 1)
const MaterialPage<void>(child: SizedBox(key: boxKey)),
];
},
),
),
);
expect(numBuilds, 1);
expect(find.byKey(buttonKey), findsOneWidget);
expect(find.byKey(boxKey), findsNothing);
expect(lastPages, isEmpty);
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle();
expect(numBuilds, 2);
expect(find.byKey(buttonKey), findsNothing);
expect(find.byKey(boxKey), findsOneWidget);
expect(lastPages.length, equals(1));
});
testWidgets('complete terminates the flow', (tester) async {
const startButtonKey = Key('__start_button__');
const completeButtonKey = Key('__complete_button__');
var numBuilds = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (context) {
return TextButton(
key: startButtonKey,
child: const Text('Button'),
onPressed: () async {
final result = await Navigator.of(context).push<int>(
MaterialPageRoute<int>(
builder: (_) => FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
numBuilds++;
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) => TextButton(
key: completeButtonKey,
child: const Text('Button'),
onPressed: () => context
.flow<int>()
.complete((s) => s + 1),
),
),
),
];
},
),
),
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Result: $result')),
);
},
);
},
),
),
),
);
await tester.tap(find.byKey(startButtonKey));
await tester.pumpAndSettle();
expect(numBuilds, 1);
await tester.tap(find.byKey(completeButtonKey));
await tester.pumpAndSettle();
await tester.pump();
expect(numBuilds, 1);
expect(find.text('Result: 1'), findsOneWidget);
});
testWidgets('complete terminates the flow with explicit same state',
(tester) async {
const startButtonKey = Key('__start_button__');
const completeButtonKey = Key('__complete_button__');
var numBuilds = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (context) {
return TextButton(
key: startButtonKey,
child: const Text('Button'),
onPressed: () async {
final result = await Navigator.of(context).push<int>(
MaterialPageRoute<int>(
builder: (_) => FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
numBuilds++;
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) => TextButton(
key: completeButtonKey,
child: const Text('Button'),
onPressed: () =>
context.flow<int>().complete((s) => s),
),
),
),
];
},
),
),
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Result: $result')),
);
},
);
},
),
),
),
);
await tester.tap(find.byKey(startButtonKey));
await tester.pumpAndSettle();
expect(numBuilds, 1);
await tester.tap(find.byKey(completeButtonKey));
await tester.pumpAndSettle();
await tester.pump();
expect(numBuilds, 1);
expect(find.text('Result: 0'), findsOneWidget);
});
testWidgets('complete terminates the flow with implicit same state',
(tester) async {
const startButtonKey = Key('__start_button__');
const completeButtonKey = Key('__complete_button__');
var numBuilds = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (context) {
return TextButton(
key: startButtonKey,
child: const Text('Button'),
onPressed: () async {
final result = await Navigator.of(context).push<int>(
MaterialPageRoute<int>(
builder: (_) => FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
numBuilds++;
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) => TextButton(
key: completeButtonKey,
child: const Text('Button'),
onPressed: () =>
context.flow<int>().complete(),
),
),
),
];
},
),
),
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Result: $result')),
);
},
);
},
),
),
),
);
await tester.tap(find.byKey(startButtonKey));
await tester.pumpAndSettle();
expect(numBuilds, 1);
await tester.tap(find.byKey(completeButtonKey));
await tester.pumpAndSettle();
await tester.pump();
expect(numBuilds, 1);
expect(find.text('Result: 0'), findsOneWidget);
});
testWidgets('complete invokes onComplete', (tester) async {
const startButtonKey = Key('__start_button__');
const completeButtonKey = Key('__complete_button__');
final onCompleteCalls = <int>[];
var numBuilds = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (context) {
return TextButton(
key: startButtonKey,
child: const Text('Button'),
onPressed: () {
Navigator.of(context).push<int>(
MaterialPageRoute<int>(
builder: (_) => FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
numBuilds++;
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) => TextButton(
key: completeButtonKey,
child: const Text('Button'),
onPressed: () => context
.flow<int>()
.complete((s) => s + 1),
),
),
),
];
},
onComplete: onCompleteCalls.add,
),
),
);
},
);
},
),
),
),
);
await tester.tap(find.byKey(startButtonKey));
await tester.pumpAndSettle();
expect(numBuilds, 1);
await tester.tap(find.byKey(completeButtonKey));
await tester.pumpAndSettle();
expect(onCompleteCalls, [1]);
expect(numBuilds, 1);
expect(find.byKey(startButtonKey), findsNothing);
expect(find.byKey(completeButtonKey), findsOneWidget);
});
testWidgets('back button pops parent route', (tester) async {
const buttonKey = Key('__button__');
const scaffoldKey = Key('__scaffold__');
var numBuilds = 0;
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
numBuilds++;
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) => Scaffold(
appBar: AppBar(),
body: TextButton(
key: buttonKey,
child: const Text('Button'),
onPressed: () {
context.flow<int>().update((s) => s + 1);
},
),
),
),
),
if (state == 1)
MaterialPage<void>(
child: Scaffold(
key: scaffoldKey,
appBar: AppBar(),
),
),
];
},
),
),
);
expect(numBuilds, 1);
expect(find.byKey(buttonKey), findsOneWidget);
expect(find.byKey(scaffoldKey), findsNothing);
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle();
expect(numBuilds, 2);
expect(find.byKey(buttonKey), findsNothing);
expect(find.byKey(scaffoldKey), findsOneWidget);
await tester.tap(find.byType(BackButton));
await tester.pumpAndSettle();
expect(numBuilds, 2);
expect(find.byKey(buttonKey), findsOneWidget);
expect(find.byKey(scaffoldKey), findsNothing);
});
testWidgets('system back button pops parent route', (tester) async {
const buttonKey = Key('__button__');
const scaffoldKey = Key('__scaffold__');
var numBuilds = 0;
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
numBuilds++;
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) => Scaffold(
body: TextButton(
key: buttonKey,
child: const Text('Button'),
onPressed: () {
context.flow<int>().update((s) => s + 1);
},
),
),
),
),
if (state == 1)
const MaterialPage<void>(
child: Scaffold(key: scaffoldKey),
),
];
},
),
),
);
expect(numBuilds, 1);
expect(find.byKey(buttonKey), findsOneWidget);
expect(find.byKey(scaffoldKey), findsNothing);
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle();
expect(numBuilds, 2);
expect(find.byKey(buttonKey), findsNothing);
expect(find.byKey(scaffoldKey), findsOneWidget);
await TestSystemNavigationObserver.handleSystemNavigation(
const MethodCall('pushRoute'),
);
await TestSystemNavigationObserver.handleSystemNavigation(
const MethodCall('popRoute'),
);
await tester.pumpAndSettle();
expect(numBuilds, 2);
expect(find.byKey(buttonKey), findsOneWidget);
expect(find.byKey(scaffoldKey), findsNothing);
});
testWidgets('system back button pops entire flow', (tester) async {
var systemPopCallCount = 0;
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) {
if (call.method == 'SystemNavigator.pop') {
systemPopCallCount++;
}
return null;
},
);
const buttonKey = Key('__button__');
const scaffoldKey = Key('__scaffold__');
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) {
return Scaffold(
body: TextButton(
key: buttonKey,
child: const Text('Button'),
onPressed: () {
context.flow<int>().update((s) => s + 1);
},
),
);
},
),
),
];
},
),
),
);
expect(find.byKey(buttonKey), findsOneWidget);
expect(find.byKey(scaffoldKey), findsNothing);
await TestSystemNavigationObserver.handleSystemNavigation(
const MethodCall('popRoute'),
);
await tester.pumpAndSettle();
expect(systemPopCallCount, equals(1));
});
testWidgets('system back button pops routes that have been pushed',
(tester) async {
var systemPopCallCount = 0;
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) {
if (call.method == 'SystemNavigator.pop') {
systemPopCallCount++;
}
return null;
},
);
const buttonKey = Key('__button__');
const scaffoldKey = Key('__scaffold__');
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) {
return Scaffold(
body: TextButton(
key: buttonKey,
child: const Text('Button'),
onPressed: () {
Navigator.of(context).push<void>(
MaterialPageRoute(
builder: (_) => const Scaffold(
key: scaffoldKey,
),
),
);
},
),
);
},
),
),
];
},
),
),
);
expect(find.byKey(buttonKey), findsOneWidget);
expect(find.byKey(scaffoldKey), findsNothing);
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle();
expect(find.byKey(buttonKey), findsNothing);
expect(find.byKey(scaffoldKey), findsOneWidget);
await TestSystemNavigationObserver.handleSystemNavigation(
const MethodCall('popRoute'),
);
await tester.pumpAndSettle();
expect(systemPopCallCount, equals(0));
expect(find.byKey(buttonKey), findsOneWidget);
expect(find.byKey(scaffoldKey), findsNothing);
});
testWidgets('system back button pops typed routes that have been pushed',
(tester) async {
var systemPopCallCount = 0;
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) {
if (call.method == 'SystemNavigator.pop') {
systemPopCallCount++;
}
return null;
},
);
const buttonKey = Key('__button__');
const scaffoldKey = Key('__scaffold__');
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) {
return Scaffold(
body: TextButton(
key: buttonKey,
child: const Text('Button'),
onPressed: () {
Navigator.of(context).push<String>(
MaterialPageRoute(
builder: (context) => const Scaffold(
key: scaffoldKey,
),
),
);
},
),
);
},
),
),
];
},
),
),
);
expect(find.byKey(buttonKey), findsOneWidget);
expect(find.byKey(scaffoldKey), findsNothing);
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle();
expect(find.byKey(buttonKey), findsNothing);
expect(find.byKey(scaffoldKey), findsOneWidget);
await TestSystemNavigationObserver.handleSystemNavigation(
const MethodCall('popRoute'),
);
await tester.pumpAndSettle();
expect(systemPopCallCount, equals(0));
expect(find.byKey(buttonKey), findsOneWidget);
expect(find.byKey(scaffoldKey), findsNothing);
});
testWidgets('Navigator.pop pops parent route', (tester) async {
const button1Key = Key('__button1__');
const button2Key = Key('__button2__');
var numBuilds = 0;
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
numBuilds++;
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) => Scaffold(
appBar: AppBar(),
body: TextButton(
key: button1Key,
child: const Text('Button'),
onPressed: () =>
context.flow<int>().update((s) => s + 1),
),
),
),
),
if (state == 1)
MaterialPage<void>(
child: Scaffold(
appBar: AppBar(),
body: Builder(
builder: (context) => TextButton(
key: button2Key,
child: const Text('Button'),
onPressed: () => Navigator.of(context).pop(),
),
),
),
),
];
},
),
),
);
expect(numBuilds, 1);
expect(find.byKey(button1Key), findsOneWidget);
expect(find.byKey(button2Key), findsNothing);
await tester.tap(find.byKey(button1Key));
await tester.pumpAndSettle();
expect(numBuilds, 2);
expect(find.byKey(button1Key), findsNothing);
expect(find.byKey(button2Key), findsOneWidget);
await tester.tap(find.byKey(button2Key));
await tester.pumpAndSettle();
expect(numBuilds, 2);
expect(find.byKey(button1Key), findsOneWidget);
expect(find.byKey(button2Key), findsNothing);
});
testWidgets(
'navigation stack changes upon back pressed '
'still allows future state changes to work', (tester) async {
const buttonKey = Key('__button__');
const scaffoldKey = Key('__scaffold__');
var numBuilds = 0;
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
numBuilds++;
if (state == 0) {
return [
MaterialPage<void>(
child: Builder(
builder: (context) => Scaffold(
appBar: AppBar(),
body: TextButton(
key: buttonKey,
child: const Text('Button'),
onPressed: () {
context.flow<int>().update((s) => s + 1);
},
),
),
),
),
];
}
if (state == 1) {
return [
MaterialPage<void>(
child: Builder(
builder: (context) => Scaffold(
appBar: AppBar(),
body: TextButton(
key: buttonKey,
child: const Text('Button'),
onPressed: () {
context.flow<int>().update((s) => 1);
},
),
),
),
),
MaterialPage<void>(
child: Scaffold(
key: scaffoldKey,
appBar: AppBar(),
),
),
];
}
return <Page<dynamic>>[];
},
),
),
);
expect(numBuilds, 1);
expect(find.byKey(buttonKey), findsOneWidget);
expect(find.byKey(scaffoldKey), findsNothing);
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle();
expect(numBuilds, 2);
expect(find.byKey(buttonKey), findsNothing);
expect(find.byKey(scaffoldKey), findsOneWidget);
await tester.tap(find.byType(BackButton));
await tester.pumpAndSettle();
expect(numBuilds, 2);
expect(find.byKey(buttonKey), findsOneWidget);
expect(find.byKey(scaffoldKey), findsNothing);
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle();
expect(numBuilds, 3);
expect(find.byKey(buttonKey), findsNothing);
expect(find.byKey(scaffoldKey), findsOneWidget);
});
testWidgets('onComplete callback is only called once', (tester) async {
const pageKey = Key('__page__');
final controller = FlowController(0);
final onCompleteCalls = <int>[];
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
controller: controller,
onComplete: onCompleteCalls.add,
onGeneratePages: (state, pages) {
return <Page<dynamic>>[
MaterialPage<void>(
child: Scaffold(
appBar: AppBar(),
body: const SizedBox(key: pageKey),
),
),
];
},
),
),
);
expect(find.byKey(pageKey), findsOneWidget);
controller.complete();
await tester.pumpAndSettle();
expect(onCompleteCalls, equals([0]));
expect(find.byKey(pageKey), findsOneWidget);
controller.update((state) => state + 1);
await tester.pumpAndSettle();
expect(onCompleteCalls, equals([0]));
expect(find.byKey(pageKey), findsOneWidget);
});
group('pushRoute', () {
testWidgets(
'system pushRoute is passed to WidgetsBinding if contains arguments',
(tester) async {
final widgetsBinding = TestWidgetsFlutterBinding.ensureInitialized();
final observer = _TestPushWidgetsBindingObserver();
const path = '/path';
widgetsBinding.addObserver(observer);
var numBuilds = 0;
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
numBuilds++;
return <Page<dynamic>>[
const MaterialPage<void>(
child: Scaffold(),
),
];
},
),
),
);
expect(numBuilds, 1);
await TestSystemNavigationObserver.handleSystemNavigation(
const MethodCall(
'pushRoute',
path,
),
);
await tester.pumpAndSettle();
expect(observer.lastRoute, path);
expect(observer.pushCount, 1);
widgetsBinding.removeObserver(observer);
});
testWidgets(
'system pushRoute is not passed to WidgetsBinding if empty arguments',
(tester) async {
final widgetsBinding = TestWidgetsFlutterBinding.ensureInitialized();
final observer = _TestPushWidgetsBindingObserver();
widgetsBinding.addObserver(observer);
var numBuilds = 0;
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
numBuilds++;
return <Page<dynamic>>[
const MaterialPage<void>(
child: Scaffold(),
),
];
},
),
),
);
expect(numBuilds, 1);
await TestSystemNavigationObserver.handleSystemNavigation(
const MethodCall('pushRoute'),
);
await tester.pumpAndSettle();
expect(observer.lastRoute, isNull);
expect(observer.pushCount, 0);
widgetsBinding.removeObserver(observer);
});
testWidgets('other system navigation calls are not handled',
(tester) async {
final widgetsBinding = TestWidgetsFlutterBinding.ensureInitialized();
final observer = _TestPushWidgetsBindingObserver();
widgetsBinding.addObserver(observer);
var numBuilds = 0;
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
numBuilds++;
return <Page<dynamic>>[
const MaterialPage<void>(
child: Scaffold(),
),
];
},
),
),
);
expect(numBuilds, 1);
await TestSystemNavigationObserver.handleSystemNavigation(
const MethodCall('randomMethod'),
);
await tester.pumpAndSettle();
expect(observer.lastRoute, isNull);
expect(observer.pushCount, 0);
widgetsBinding.removeObserver(observer);
});
});
testWidgets('system pop does not terminate flow', (tester) async {
const button1Key = Key('__button1__');
const button2Key = Key('__button2__');
var numBuilds = 0;
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
numBuilds++;
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) => Scaffold(
appBar: AppBar(),
body: TextButton(
key: button1Key,
child: const Text('Button'),
onPressed: () =>
context.flow<int>().update((s) => s + 1),
),
),
),
),
if (state == 1)
MaterialPage<void>(
child: Scaffold(
appBar: AppBar(),
body: Builder(
builder: (context) => const TextButton(
key: button2Key,
onPressed: SystemNavigator.pop,
child: Text('Button'),
),
),
),
),
];
},
),
),
);
expect(numBuilds, 1);
expect(find.byKey(button1Key), findsOneWidget);
expect(find.byKey(button2Key), findsNothing);
await tester.tap(find.byKey(button1Key));
await tester.pumpAndSettle();
expect(numBuilds, 2);
expect(find.byKey(button1Key), findsNothing);
expect(find.byKey(button2Key), findsOneWidget);
await tester.tap(find.byKey(button2Key));
await tester.pumpAndSettle();
expect(numBuilds, 2);
expect(find.byKey(button1Key), findsNothing);
expect(find.byKey(button2Key), findsOneWidget);
});
testWidgets('onWillPop pops top page when there are multiple',
(tester) async {
const button1Key = Key('__button1__');
const button2Key = Key('__button2__');
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
return <Page<dynamic>>[
MaterialPage<void>(
child: Scaffold(
body: TextButton(
key: button1Key,
child: const Text('Button'),
onPressed: () {},
),
),
),
MaterialPage<void>(
child: Scaffold(
body: TextButton(
key: button2Key,
child: const Text('Button'),
onPressed: () {},
),
),
),
];
},
),
),
);
expect(find.byKey(button1Key), findsNothing);
expect(find.byKey(button2Key), findsOneWidget);
final willPopScope = tester.widget<WillPopScope>(
find.byType(WillPopScope),
);
final result = await willPopScope.onWillPop!();
expect(result, isFalse);
await tester.pumpAndSettle();
expect(find.byKey(button1Key), findsOneWidget);
expect(find.byKey(button2Key), findsNothing);
});
testWidgets('onWillPop does not exist for only one page', (tester) async {
const button1Key = Key('__button1__');
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
return <Page<dynamic>>[
MaterialPage<void>(
child: Scaffold(
body: TextButton(
key: button1Key,
child: const Text('Button'),
onPressed: () {},
),
),
),
];
},
),
),
);
expect(find.byKey(button1Key), findsOneWidget);
expect(find.byType(WillPopScope), findsNothing);
});
testWidgets('controller change triggers a rebuild with correct state',
(tester) async {
const buttonKey = Key('__button__');
const boxKey = Key('__box__');
var numBuilds = 0;
var controller = FlowController(0);
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (context, setState) {
return FlowBuilder<int>(
controller: controller,
onGeneratePages: (state, pages) {
numBuilds++;
return <Page<dynamic>>[
MaterialPage<void>(
child: TextButton(
key: buttonKey,
child: const Text('Button'),
onPressed: () => setState(
() => controller = FlowController(1),
),
),
),
if (state == 1)
const MaterialPage<void>(child: SizedBox(key: boxKey)),
];
},
);
},
),
),
);
expect(numBuilds, 1);
expect(find.byKey(buttonKey), findsOneWidget);
expect(find.byKey(boxKey), findsNothing);
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle();
expect(numBuilds, 2);
expect(find.byKey(buttonKey), findsNothing);
expect(find.byKey(boxKey), findsOneWidget);
});
testWidgets('state change triggers a rebuild with correct state',
(tester) async {
const buttonKey = Key('__button__');
const boxKey = Key('__box__');
var numBuilds = 0;
var flowState = 0;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (context, setState) {
return FlowBuilder<int>(
state: flowState,
onGeneratePages: (state, pages) {
numBuilds++;
return <Page<dynamic>>[
MaterialPage<void>(
child: TextButton(
key: buttonKey,
child: const Text('Button'),
onPressed: () => setState(() => flowState = 1),
),
),
if (state == 1)
const MaterialPage<void>(child: SizedBox(key: boxKey)),
];
},
);
},
),
),
);
expect(numBuilds, 1);
expect(find.byKey(buttonKey), findsOneWidget);
expect(find.byKey(boxKey), findsNothing);
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle();
expect(numBuilds, 2);
expect(find.byKey(buttonKey), findsNothing);
expect(find.byKey(boxKey), findsOneWidget);
});
testWidgets('can provide a FakeFlowController', (tester) async {
const button1Key = Key('__button1__');
const button2Key = Key('__button2__');
const state = 0;
final controller = FakeFlowController<int>(state);
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
controller: controller,
onGeneratePages: (state, pages) {
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) => Column(
children: [
TextButton(
key: button1Key,
child: const Text('Button'),
onPressed: () {
context.flow<int>().update((s) => s + 1);
},
),
TextButton(
key: button2Key,
child: const Text('Button'),
onPressed: () {
context.flow<int>().complete((s) => s + 1);
},
),
],
),
),
),
];
},
),
),
);
await tester.tap(find.byKey(button1Key));
expect(controller.completed, isFalse);
expect(controller.state, equals(1));
await tester.tap(find.byKey(button2Key));
expect(controller.completed, isTrue);
expect(controller.state, equals(2));
});
testWidgets('FakeFlowController supports complete with null callback',
(tester) async {
const buttonKey = Key('__button__');
const state = 0;
final controller = FakeFlowController<int>(state);
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
controller: controller,
onGeneratePages: (state, pages) {
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) => Column(
children: [
TextButton(
key: buttonKey,
child: const Text('Button'),
onPressed: () => context.flow<int>().complete(),
),
],
),
),
),
];
},
),
),
);
await tester.tap(find.byKey(buttonKey));
expect(controller.completed, isTrue);
expect(controller.state, equals(0));
});
testWidgets('updates when FlowController changes', (tester) async {
const button1Key = Key('__button1__');
const button2Key = Key('__button2__');
const button3Key = Key('__button3__');
var controller = FakeFlowController(0);
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (context, setState) {
return FlowBuilder<int>(
controller: controller,
onGeneratePages: (state, pages) {
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) => Column(
children: [
TextButton(
key: button1Key,
child: const Text('Button'),
onPressed: () {
context.flow<int>().update((s) => s + 1);
},
),
TextButton(
key: button2Key,
child: const Text('Button'),
onPressed: () {
context.flow<int>().complete((s) => s + 1);
},
),
TextButton(
key: button3Key,
child: const Text('Button'),
onPressed: () {
setState(() {
controller = FakeFlowController<int>(0);
});
},
),
],
),
),
),
];
},
);
},
),
),
);
await tester.tap(find.byKey(button3Key));
await tester.pumpAndSettle();
await tester.tap(find.byKey(button1Key));
await tester.tap(find.byKey(button2Key));
expect(controller.completed, isTrue);
expect(controller.state, equals(2));
});
testWidgets('accepts custom navigator observers', (tester) async {
final observers = [NavigatorObserver(), HeroController()];
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
state: 0,
observers: observers,
onGeneratePages: (state, pages) {
return const <Page<dynamic>>[
MaterialPage<void>(child: SizedBox()),
];
},
),
),
);
final navigators = tester.widgetList<Navigator>(find.byType(Navigator));
expect(navigators.last.observers, equals(observers));
});
testWidgets('SystemNavigator.pop respects when WillPopScope returns false',
(tester) async {
const targetKey = Key('__target__');
var onWillPopCallCount = 0;
final flow = FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) => WillPopScope(
onWillPop: () async {
onWillPopCallCount++;
return false;
},
child: TextButton(
key: targetKey,
onPressed: () {
TestSystemNavigationObserver.handleSystemNavigation(
const MethodCall('popRoute'),
);
},
child: const SizedBox(),
),
),
),
),
];
},
);
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => TextButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => flow),
);
},
child: const Text('X'),
),
),
),
);
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
expect(find.byKey(targetKey), findsOneWidget);
await tester.tap(find.byKey(targetKey));
await tester.pumpAndSettle();
expect(onWillPopCallCount, equals(1));
expect(find.byKey(targetKey), findsOneWidget);
});
testWidgets('SystemNavigator.pop respects when WillPopScope returns true',
(tester) async {
const targetKey = Key('__target__');
var onWillPopCallCount = 0;
final flow = FlowBuilder<int>(
state: 0,
onGeneratePages: (state, pages) {
return <Page<dynamic>>[
MaterialPage<void>(
child: Builder(
builder: (context) => WillPopScope(
onWillPop: () async {
onWillPopCallCount++;
return true;
},
child: TextButton(
key: targetKey,
onPressed: () {
TestSystemNavigationObserver.handleSystemNavigation(
const MethodCall('popRoute'),
);
},
child: const SizedBox(),
),
),
),
),
];
},
);
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => TextButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => flow),
);
},
child: const Text('X'),
),
),
),
);
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
expect(find.byKey(targetKey), findsOneWidget);
await tester.tap(find.byKey(targetKey));
await tester.pumpAndSettle();
expect(onWillPopCallCount, equals(1));
expect(find.byKey(targetKey), findsNothing);
});
testWidgets('updates do not trigger rebuilds of existing pages by value',
(tester) async {
const buttonKey = Key('__button__');
const boxKey = Key('__box__');
var numBuildsA = 0;
var numBuildsB = 0;
final pageA = MaterialPage<void>(
child: Builder(
builder: (context) {
numBuildsA++;
return TextButton(
key: buttonKey,
child: const Text('Button'),
onPressed: () => context.flow<int>().update((s) => s + 1),
);
},
),
);
final pageB = MaterialPage<void>(
child: Builder(
builder: (context) {
numBuildsB++;
return const SizedBox(key: boxKey);
},
),
);
await tester.pumpWidget(
MaterialApp(
home: FlowBuilder<int>(
key: const ValueKey('flow'),
state: 0,
onGeneratePages: (state, pages) {
return <Page<dynamic>>[
pageA,
if (state == 1) pageB,
];
},
),
),
);
expect(numBuildsA, 1);
expect(numBuildsB, 0);
expect(find.byKey(buttonKey), findsOneWidget);
expect(find.byKey(boxKey), findsNothing);
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle();
expect(numBuildsA, 1);
expect(numBuildsB, 1);
expect(find.byKey(buttonKey), findsNothing);
expect(find.byKey(boxKey), findsOneWidget);
});
});
}
class _TestPushWidgetsBindingObserver with WidgetsBindingObserver {
int pushCount = 0;
String? lastRoute;
@override
Future<bool> didPushRoute(String route) async {
lastRoute = route;
pushCount++;
return true;
}
}
| flow_builder/test/flow_builder_test.dart/0 | {'file_path': 'flow_builder/test/flow_builder_test.dart', 'repo_id': 'flow_builder', 'token_count': 28684} |
class CounterState {
int counter;
CounterState._();
factory CounterState.initial() {
return CounterState._()..counter = 0;
}
}
| flutter-bloc-library-tutorial/lib/counter_state.dart/0 | {'file_path': 'flutter-bloc-library-tutorial/lib/counter_state.dart', 'repo_id': 'flutter-bloc-library-tutorial', 'token_count': 44} |
export 'factories/cupertino_widgets_factory.dart';
export 'factories/material_widgets_factory.dart';
export 'iwidgets_factory.dart';
export 'widgets/activity_indicators/android_activity_indicator.dart';
export 'widgets/activity_indicators/ios_activity_indicator.dart';
export 'widgets/iactivity_indicator.dart';
export 'widgets/islider.dart';
export 'widgets/iswitch.dart';
export 'widgets/sliders/android_slider.dart';
export 'widgets/sliders/ios_slider.dart';
export 'widgets/switches/android_switch.dart';
export 'widgets/switches/ios_switch.dart';
| flutter-design-patterns/lib/design_patterns/abstract_factory/abstract_factory.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/abstract_factory/abstract_factory.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 196} |
class JsonContactsApi {
static const _contactsJson = '''
{
"contacts": [
{
"fullName": "John Doe (JSON)",
"email": "johndoe@json.com",
"favourite": true
},
{
"fullName": "Emma Doe (JSON)",
"email": "emmadoe@json.com",
"favourite": false
},
{
"fullName": "Michael Roe (JSON)",
"email": "michaelroe@json.com",
"favourite": false
}
]
}
''';
const JsonContactsApi();
String getContactsJson() => _contactsJson;
}
| flutter-design-patterns/lib/design_patterns/adapter/apis/json_contacts_api.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/adapter/apis/json_contacts_api.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 273} |
import 'ingredient.dart';
class Burger {
final List<Ingredient> _ingredients = [];
late double _price;
void addIngredient(Ingredient ingredient) => _ingredients.add(ingredient);
String getFormattedIngredients() =>
_ingredients.map((x) => x.getName()).join(', ');
String getFormattedAllergens() => <String>{
for (final ingredient in _ingredients) ...ingredient.getAllergens()
}.join(', ');
String getFormattedPrice() => '\$${_price.toStringAsFixed(2)}';
// ignore: use_setters_to_change_properties
void setPrice(double price) => _price = price;
}
| flutter-design-patterns/lib/design_patterns/builder/burger.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/builder/burger.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 206} |
import '../../ingredient.dart';
class BigMacSauce extends Ingredient {
BigMacSauce() {
name = 'Big Mac Sauce';
allergens = ['Egg', 'Soy', 'Wheat'];
}
}
| flutter-design-patterns/lib/design_patterns/builder/ingredients/sauces/big_mac_sauce.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/builder/ingredients/sauces/big_mac_sauce.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 70} |
import '../log_bloc.dart';
import '../log_level.dart';
import '../log_message.dart';
class ExternalLoggingService {
const ExternalLoggingService(this.logBloc);
final LogBloc logBloc;
void logMessage(LogLevel logLevel, String message) {
final logMessage = LogMessage(logLevel: logLevel, message: message);
// Send log message to the external logging service
// Log message
logBloc.log(logMessage);
}
}
| flutter-design-patterns/lib/design_patterns/chain_of_responsibility/services/external_logging_service.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/chain_of_responsibility/services/external_logging_service.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 140} |
class PizzaToppingData {
PizzaToppingData(this.label);
final String label;
bool selected = false;
// ignore: use_setters_to_change_properties
void setSelected({required bool isSelected}) => selected = isSelected;
}
| flutter-design-patterns/lib/design_patterns/decorator/pizza_topping_data.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/decorator/pizza_topping_data.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 68} |
export 'apis/apis.dart';
export 'facades/gaming_facade.dart';
export 'facades/smart_home_facade.dart';
export 'smart_home_state.dart';
| flutter-design-patterns/lib/design_patterns/facade/facade.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/facade/facade.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 54} |
class ExpressionContext {
final List<String> _solutionSteps = [];
List<String> getSolutionSteps() => _solutionSteps;
void addSolutionStep(String operatorSymbol, int left, int right, int result) {
final solutionStep =
'${_solutionSteps.length + 1}) $left $operatorSymbol $right = $result';
_solutionSteps.add(solutionStep);
}
}
| flutter-design-patterns/lib/design_patterns/interpreter/expression_context.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/interpreter/expression_context.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 120} |
export 'notification_hub.dart';
export 'notification_hub/team_notification_hub.dart';
export 'team_member.dart';
export 'team_members/team_members.dart';
| flutter-design-patterns/lib/design_patterns/mediator/mediator.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/mediator/mediator.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 53} |
export 'stock.dart';
export 'stock_change_direction.dart';
export 'stock_subscriber.dart';
export 'stock_subscribers/default_stock_subscriber.dart';
export 'stock_subscribers/growing_stock_subscriber.dart';
export 'stock_ticker.dart';
export 'stock_ticker_symbol.dart';
export 'stock_tickers/gamestop_stock_ticker.dart';
export 'stock_tickers/google_stock_ticker.dart';
export 'stock_tickers/tesla_stock_ticker.dart';
| flutter-design-patterns/lib/design_patterns/observer/observer.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/observer/observer.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 154} |
class CustomerDetails {
const CustomerDetails({
required this.customerId,
required this.email,
required this.hobby,
required this.position,
});
final String customerId;
final String email;
final String hobby;
final String position;
}
| flutter-design-patterns/lib/design_patterns/proxy/customer/customer_details.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/proxy/customer/customer_details.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 80} |
import 'package:flutter/material.dart';
import '../fake_api.dart';
import '../istate.dart';
import '../state_context.dart';
import 'error_state.dart';
import 'loaded_state.dart';
import 'no_results_state.dart';
class LoadingState implements IState {
const LoadingState({
this.api = const FakeApi(),
});
final FakeApi api;
@override
Future<void> nextState(StateContext context) async {
try {
final resultList = await api.getNames();
context.setState(
resultList.isEmpty ? const NoResultsState() : LoadedState(resultList),
);
} on Exception {
context.setState(const ErrorState());
}
}
@override
Widget render() {
return const CircularProgressIndicator(
backgroundColor: Colors.transparent,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.black,
),
);
}
}
| flutter-design-patterns/lib/design_patterns/state/states/loading_state.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/state/states/loading_state.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 317} |
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'student.dart';
abstract class StudentsBmiCalculator {
const StudentsBmiCalculator();
List<Student> calculateBmiAndReturnStudentList() {
var studentList = getStudentsData();
studentList = doStudentsFiltering(studentList);
_calculateStudentsBmi(studentList);
return studentList;
}
void _calculateStudentsBmi(List<Student> studentList) {
for (final student in studentList) {
student.bmi = _calculateBmi(student.height, student.weight);
}
}
double _calculateBmi(double height, int weight) {
return weight / math.pow(height, 2);
}
// Hook methods
@protected
List<Student> doStudentsFiltering(List<Student> studentList) {
return studentList;
}
// Abstract methods
@protected
List<Student> getStudentsData();
}
| flutter-design-patterns/lib/design_patterns/template_method/students_bmi_calculator.dart/0 | {'file_path': 'flutter-design-patterns/lib/design_patterns/template_method/students_bmi_calculator.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 286} |
extension FormattingExtension on String {
String indentAndAddNewLine(int nTabs) => '${'\t' * nTabs}$this\n';
}
| flutter-design-patterns/lib/helpers/formatting_extension.dart/0 | {'file_path': 'flutter-design-patterns/lib/helpers/formatting_extension.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 43} |
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../constants/constants.dart';
import '../../data/models/design_pattern_category.dart';
import '../../data/repositories/design_pattern_categories_repository.dart';
import '../../helpers/helpers.dart';
import '../../modules/main_menu/widgets/main_menu_card.dart';
import '../../modules/main_menu/widgets/main_menu_header.dart';
import '../../themes.dart';
class MainMenuPage extends ConsumerWidget {
const MainMenuPage();
@override
Widget build(BuildContext context, WidgetRef ref) {
final designPatternCategories = ref.watch(designPatternCategoriesProvider);
return Scaffold(
body: SafeArea(
child: ScrollConfiguration(
behavior: const ScrollBehavior(),
child: SingleChildScrollView(
padding: const EdgeInsets.all(LayoutConstants.paddingL),
child: Column(
children: <Widget>[
const MainMenuHeader(),
const SizedBox(height: LayoutConstants.spaceXL),
designPatternCategories.when(
data: (categories) => _MainMenuCardsListView(
categories: categories,
),
loading: () => CircularProgressIndicator(
backgroundColor: lightBackgroundColor,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.black.withOpacity(0.65),
),
),
error: (_, __) => const Text('Oops, something went wrong...'),
),
],
),
),
),
),
);
}
}
class _MainMenuCardsListView extends StatelessWidget {
final List<DesignPatternCategory> categories;
const _MainMenuCardsListView({
required this.categories,
});
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
final isDesktop = constraints.maxWidth > LayoutConstants.screenDesktop;
final cardsIterable = categories.map<Widget>(
(category) => MainMenuCard(category: category, isDesktop: isDesktop),
);
if (isDesktop) {
return ConstrainedBox(
constraints: const BoxConstraints(
maxHeight: 500,
maxWidth: 1500,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: cardsIterable
.map<Widget>((card) => Expanded(child: card))
.toList()
.addBetween(const SizedBox(width: LayoutConstants.spaceL)),
),
);
}
return Column(
children: cardsIterable
.toList()
.addBetween(const SizedBox(height: LayoutConstants.spaceL)),
);
},
);
}
}
| flutter-design-patterns/lib/navigation/pages/main_menu_page.dart/0 | {'file_path': 'flutter-design-patterns/lib/navigation/pages/main_menu_page.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 1337} |
import 'package:flutter/material.dart';
class BurgerInformationLabel extends StatelessWidget {
final String label;
const BurgerInformationLabel(this.label);
@override
Widget build(BuildContext context) {
return Text(
label,
style: Theme.of(context)
.textTheme
.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
);
}
}
| flutter-design-patterns/lib/widgets/design_patterns/builder/burger_information/burger_information_label.dart/0 | {'file_path': 'flutter-design-patterns/lib/widgets/design_patterns/builder/burger_information/burger_information_label.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 145} |
import 'package:flutter/material.dart';
import '../../../constants/constants.dart';
import '../../../design_patterns/decorator/decorator.dart';
class PizzaInformation extends StatelessWidget {
final Pizza pizza;
const PizzaInformation({
required this.pizza,
});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'Pizza details:',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: LayoutConstants.spaceL),
Text(
pizza.getDescription(),
textAlign: TextAlign.justify,
),
const SizedBox(height: LayoutConstants.spaceM),
Text('Price: \$${pizza.getPrice().toStringAsFixed(2)}'),
],
);
}
}
| flutter-design-patterns/lib/widgets/design_patterns/decorator/pizza_information.dart/0 | {'file_path': 'flutter-design-patterns/lib/widgets/design_patterns/decorator/pizza_information.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 345} |
import 'package:faker/faker.dart';
import 'package:flutter/material.dart';
import '../../../constants/constants.dart';
import '../../../design_patterns/mediator/mediator.dart';
import '../../platform_specific/platform_button.dart';
import 'notification_list.dart';
class MediatorExample extends StatefulWidget {
const MediatorExample();
@override
_MediatorExampleState createState() => _MediatorExampleState();
}
class _MediatorExampleState extends State<MediatorExample> {
late final NotificationHub _notificationHub;
final _admin = Admin(name: 'God');
@override
void initState() {
super.initState();
final members = [
_admin,
Developer(name: 'Sea Sharp'),
Developer(name: 'Jan Assembler'),
Developer(name: 'Dove Dart'),
Tester(name: 'Cori Debugger'),
Tester(name: 'Tania Mocha'),
];
_notificationHub = TeamNotificationHub(members: members);
}
void _sendToAll() => setState(() => _admin.send('Hello'));
void _sendToQa() => setState(() => _admin.sendTo<Tester>('BUG!'));
void _sendToDevelopers() => setState(
() => _admin.sendTo<Developer>('Hello, World!'),
);
void _addTeamMember() {
final name = '${faker.person.firstName()} ${faker.person.lastName()}';
final teamMember = faker.randomGenerator.boolean()
? Tester(name: name)
: Developer(name: name);
setState(() => _notificationHub.register(teamMember));
}
void _sendFromMember(TeamMember member) => setState(
() => member.send('Hello from ${member.name}'),
);
@override
Widget build(BuildContext context) {
return ScrollConfiguration(
behavior: const ScrollBehavior(),
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(
horizontal: LayoutConstants.paddingL,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
PlatformButton(
text: "Admin: Send 'Hello' to all",
materialColor: Colors.black,
materialTextColor: Colors.white,
onPressed: _sendToAll,
),
PlatformButton(
text: "Admin: Send 'BUG!' to QA",
materialColor: Colors.black,
materialTextColor: Colors.white,
onPressed: _sendToQa,
),
PlatformButton(
text: "Admin: Send 'Hello, World!' to Developers",
materialColor: Colors.black,
materialTextColor: Colors.white,
onPressed: _sendToDevelopers,
),
const Divider(),
PlatformButton(
text: "Add team member",
materialColor: Colors.black,
materialTextColor: Colors.white,
onPressed: _addTeamMember,
),
const SizedBox(height: LayoutConstants.spaceL),
NotificationList(
members: _notificationHub.getTeamMembers(),
onTap: _sendFromMember,
),
],
),
),
);
}
}
| flutter-design-patterns/lib/widgets/design_patterns/mediator/mediator_example.dart/0 | {'file_path': 'flutter-design-patterns/lib/widgets/design_patterns/mediator/mediator_example.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 1343} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.