code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
testWidgets('Semantics 8 - Merging with reset', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
MergeSemantics(
child: Semantics(
container: true,
child: Semantics(
container: true,
child: Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
Semantics(
checked: true,
),
Semantics(
label: 'label',
textDirection: TextDirection.ltr,
),
],
),
),
),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index,
label: 'label',
textDirection: TextDirection.ltr,
rect: TestSemantics.fullScreen,
),
],
),
));
// switch the order of the inner Semantics node to trigger a reset
await tester.pumpWidget(
MergeSemantics(
child: Semantics(
container: true,
child: Semantics(
container: true,
child: Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
Semantics(
label: 'label',
textDirection: TextDirection.ltr,
),
Semantics(
checked: true,
),
],
),
),
),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index,
label: 'label',
textDirection: TextDirection.ltr,
rect: TestSemantics.fullScreen,
),
],
),
));
semantics.dispose();
});
}
| flutter/packages/flutter/test/widgets/semantics_8_test.dart/0 | {'file_path': 'flutter/packages/flutter/test/widgets/semantics_8_test.dart', 'repo_id': 'flutter', 'token_count': 1276} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
late ChangerState changer;
class Changer extends StatefulWidget {
const Changer(this.child, { super.key });
final Widget child;
@override
ChangerState createState() => ChangerState();
}
class ChangerState extends State<Changer> {
bool _state = false;
@override
void initState() {
super.initState();
changer = this;
}
void test() { setState(() { _state = true; }); }
@override
Widget build(BuildContext context) => _state ? Wrapper(widget.child) : widget.child;
}
class Wrapper extends StatelessWidget {
const Wrapper(this.child, { super.key });
final Widget child;
@override
Widget build(BuildContext context) => child;
}
class Leaf extends StatefulWidget {
const Leaf({ super.key });
@override
LeafState createState() => LeafState();
}
class LeafState extends State<Leaf> {
@override
Widget build(BuildContext context) => const Text('leaf', textDirection: TextDirection.ltr);
}
void main() {
testWidgets('three-way setState() smoke test', (WidgetTester tester) async {
await tester.pumpWidget(const Changer(Wrapper(Leaf())));
await tester.pumpWidget(const Changer(Wrapper(Leaf())));
changer.test();
await tester.pump();
});
}
| flutter/packages/flutter/test/widgets/set_state_3_test.dart/0 | {'file_path': 'flutter/packages/flutter/test/widgets/set_state_3_test.dart', 'repo_id': 'flutter', 'token_count': 478} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
typedef Logger = void Function(String caller);
class TestBorder extends ShapeBorder {
const TestBorder(this.onLog);
final Logger onLog;
@override
EdgeInsetsGeometry get dimensions => const EdgeInsetsDirectional.only(start: 1.0);
@override
ShapeBorder scale(double t) => TestBorder(onLog);
@override
Path getInnerPath(Rect rect, { TextDirection? textDirection }) {
onLog('getInnerPath $rect $textDirection');
return Path();
}
@override
Path getOuterPath(Rect rect, { TextDirection? textDirection }) {
onLog('getOuterPath $rect $textDirection');
return Path();
}
@override
void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) {
onLog('paint $rect $textDirection');
}
}
| flutter/packages/flutter/test/widgets/test_border.dart/0 | {'file_path': 'flutter/packages/flutter/test/widgets/test_border.dart', 'repo_id': 'flutter', 'token_count': 305} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
class TestUniqueWidget extends UniqueWidget<TestUniqueWidgetState> {
const TestUniqueWidget({ required super.key });
@override
TestUniqueWidgetState createState() => TestUniqueWidgetState();
}
class TestUniqueWidgetState extends State<TestUniqueWidget> {
@override
Widget build(BuildContext context) => Container();
}
void main() {
testWidgets('Unique widget control test', (WidgetTester tester) async {
final TestUniqueWidget widget = TestUniqueWidget(key: GlobalKey<TestUniqueWidgetState>());
await tester.pumpWidget(widget);
final TestUniqueWidgetState state = widget.currentState!;
expect(state, isNotNull);
await tester.pumpWidget(Container(child: widget));
expect(widget.currentState, equals(state));
});
}
| flutter/packages/flutter/test/widgets/unique_widget_test.dart/0 | {'file_path': 'flutter/packages/flutter/test/widgets/unique_widget_test.dart', 'repo_id': 'flutter', 'token_count': 292} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' show FileSystemException, stderr;
/// Standard error thrown by Flutter Driver API.
class DriverError extends Error {
/// Create an error with a [message] and (optionally) the [originalError] and
/// [originalStackTrace] that caused it.
DriverError(this.message, [this.originalError, this.originalStackTrace]);
/// Human-readable error message.
final String message;
/// The error object that was caught and wrapped by this error object, if any.
final Object? originalError;
/// The stack trace that was caught and wrapped by this error object, if any.
final Object? originalStackTrace;
@override
String toString() {
if (originalError == null) {
return 'DriverError: $message\n';
}
return '''
DriverError: $message
Original error: $originalError
Original stack trace:
$originalStackTrace
''';
}
}
/// Signature for [driverLog].
///
/// The first argument is a string representing the source of the message,
/// typically the class name or library name calling the method.
///
/// The second argument is the message being logged.
typedef DriverLogCallback = void Function(String source, String message);
/// Print the given message to the console.
///
/// The first argument is a string representing the source of the message.
///
/// The second argument is the message being logged.
///
/// This can be set to a different callback to override the handling of log
/// messages from the driver subsystem.
///
/// The default implementation prints `"$source: $message"` to stderr.
DriverLogCallback driverLog = _defaultDriverLogger;
void _defaultDriverLogger(String source, String message) {
try {
stderr.writeln('$source: $message');
} on FileSystemException {
// May encounter IO error: https://github.com/flutter/flutter/issues/69314
}
}
| flutter/packages/flutter_driver/lib/src/common/error.dart/0 | {'file_path': 'flutter/packages/flutter_driver/lib/src/common/error.dart', 'repo_id': 'flutter', 'token_count': 537} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' show Platform;
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:file/memory.dart';
/// The file system implementation used by this library.
///
/// See [useMemoryFileSystemForTesting] and [restoreFileSystem].
FileSystem fs = const LocalFileSystem();
/// Overrides the file system so it can be tested without hitting the hard
/// drive.
void useMemoryFileSystemForTesting() {
fs = MemoryFileSystem();
}
/// Restores the file system to the default local file system implementation.
void restoreFileSystem() {
fs = const LocalFileSystem();
}
/// Flutter Driver test output directory.
///
/// Tests should write any output files to this directory. Defaults to the path
/// set in the FLUTTER_TEST_OUTPUTS_DIR environment variable, or `build` if
/// unset.
String get testOutputsDirectory => Platform.environment['FLUTTER_TEST_OUTPUTS_DIR'] ?? 'build';
| flutter/packages/flutter_driver/lib/src/driver/common.dart/0 | {'file_path': 'flutter/packages/flutter_driver/lib/src/driver/common.dart', 'repo_id': 'flutter', 'token_count': 298} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_driver/src/common/error.dart';
import 'package:flutter_driver/src/common/health.dart';
import 'package:flutter_driver/src/driver/web_driver.dart';
import 'package:webdriver/src/common/log.dart';
import '../../common.dart';
void main() {
group('WebDriver', () {
late FakeFlutterWebConnection fakeConnection;
late WebFlutterDriver driver;
setUp(() {
fakeConnection = FakeFlutterWebConnection();
driver = WebFlutterDriver.connectedTo(fakeConnection);
});
test('sendCommand succeeds', () async {
fakeConnection.fakeResponse = '''
{
"isError": false,
"response": {
"test": "hello"
}
}
''';
final Map<String, Object?> response = await driver.sendCommand(const GetHealth());
expect(response['test'], 'hello');
});
test('sendCommand fails on communication error', () async {
fakeConnection.communicationError = Error();
expect(
() => driver.sendCommand(const GetHealth()),
_throwsDriverErrorWithMessage(
'FlutterDriver command GetHealth failed due to a remote error.\n'
'Command sent: {"command":"get_health"}'
),
);
});
test('sendCommand fails on null', () async {
fakeConnection.fakeResponse = null;
expect(
() => driver.sendCommand(const GetHealth()),
_throwsDriverErrorWithDataString('Null', 'null'),
);
});
test('sendCommand fails when response data is not a string', () async {
fakeConnection.fakeResponse = 1234;
expect(
() => driver.sendCommand(const GetHealth()),
_throwsDriverErrorWithDataString('int', '1234'),
);
});
test('sendCommand fails when isError is true', () async {
fakeConnection.fakeResponse = '''
{
"isError": true,
"response": "test error message"
}
''';
expect(
() => driver.sendCommand(const GetHealth()),
_throwsDriverErrorWithMessage(
'Error in Flutter application: test error message'
),
);
});
test('sendCommand fails when isError is not bool', () async {
fakeConnection.fakeResponse = '{ "isError": 5 }';
expect(
() => driver.sendCommand(const GetHealth()),
_throwsDriverErrorWithDataString('String', '{ "isError": 5 }'),
);
});
test('sendCommand fails when "response" field is not a JSON map', () async {
fakeConnection.fakeResponse = '{ "response": 5 }';
expect(
() => driver.sendCommand(const GetHealth()),
_throwsDriverErrorWithDataString('String', '{ "response": 5 }'),
);
});
});
}
Matcher _throwsDriverErrorWithMessage(String expectedMessage) {
return throwsA(allOf(
isA<DriverError>(),
predicate<DriverError>((DriverError error) {
final String actualMessage = error.message;
return actualMessage == expectedMessage;
}, 'contains message: $expectedMessage'),
));
}
Matcher _throwsDriverErrorWithDataString(String dataType, String dataString) {
return _throwsDriverErrorWithMessage(
'Received malformed response from the FlutterDriver extension.\n'
'Expected a JSON map containing a "response" field and, optionally, an '
'"isError" field, but got $dataType: $dataString'
);
}
class FakeFlutterWebConnection implements FlutterWebConnection {
@override
bool supportsTimelineAction = false;
@override
Future<void> close() async {}
@override
Stream<LogEntry> get logs => throw UnimplementedError();
@override
Future<List<int>> screenshot() {
throw UnimplementedError();
}
Object? fakeResponse;
Error? communicationError;
@override
Future<Object?> sendCommand(String script, Duration? duration) async {
if (communicationError != null) {
throw communicationError!;
}
return fakeResponse;
}
}
| flutter/packages/flutter_driver/test/src/web_tests/web_driver_test.dart/0 | {'file_path': 'flutter/packages/flutter_driver/test/src/web_tests/web_driver_test.dart', 'repo_id': 'flutter', 'token_count': 1398} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Text baseline with CJK locale', (WidgetTester tester) async {
// This test in combination with 'Text baseline with EN locale' verify the baselines
// used to align text with ideographic baselines are reasonable. We are currently
// using the alphabetic baseline to lay out as the ideographic baseline is not yet
// properly implemented. When the ideographic baseline is better defined and implemented,
// the values of this test should change very slightly. See the issue this is based off
// of: https://github.com/flutter/flutter/issues/25782.
final Key targetKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
routes: <String, WidgetBuilder>{
'/next': (BuildContext context) {
return const Text('Next');
},
},
localizationsDelegates: GlobalMaterialLocalizations.delegates,
supportedLocales: const <Locale>[
Locale('en', 'US'),
Locale('es', 'ES'),
Locale('zh', 'CN'),
],
locale: const Locale('zh', 'CN'),
home: Material(
child: Center(
child: Builder(
key: targetKey,
builder: (BuildContext context) {
return PopupMenuButton<int>(
onSelected: (int value) {
Navigator.pushNamed(context, '/next');
},
itemBuilder: (BuildContext context) {
return <PopupMenuItem<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text(
'hello, world',
style: TextStyle(color: Colors.blue),
),
),
const PopupMenuItem<int>(
value: 2,
child: Text(
'你好,世界',
style: TextStyle(color: Colors.blue),
),
),
];
},
);
},
),
),
),
),
);
await tester.tap(find.byKey(targetKey));
await tester.pumpAndSettle();
expect(find.text('hello, world'), findsOneWidget);
expect(find.text('你好,世界'), findsOneWidget);
Offset topLeft = tester.getTopLeft(find.text('hello, world'));
Offset topRight = tester.getTopRight(find.text('hello, world'));
Offset bottomLeft = tester.getBottomLeft(find.text('hello, world'));
Offset bottomRight = tester.getBottomRight(find.text('hello, world'));
expect(topLeft, const Offset(392.0, 299.5));
expect(topRight, const Offset(596.0, 299.5));
expect(bottomLeft, const Offset(392.0, 316.5));
expect(bottomRight, const Offset(596.0, 316.5));
topLeft = tester.getTopLeft(find.text('你好,世界'));
topRight = tester.getTopRight(find.text('你好,世界'));
bottomLeft = tester.getBottomLeft(find.text('你好,世界'));
bottomRight = tester.getBottomRight(find.text('你好,世界'));
expect(topLeft, const Offset(392.0, 347.5));
expect(topRight, const Offset(477.0, 347.5));
expect(bottomLeft, const Offset(392.0, 364.5));
expect(bottomRight, const Offset(477.0, 364.5));
});
testWidgets('Text baseline with EN locale', (WidgetTester tester) async {
// This test in combination with 'Text baseline with CJK locale' verify the baselines
// used to align text with ideographic baselines are reasonable. We are currently
// using the alphabetic baseline to lay out as the ideographic baseline is not yet
// properly implemented. When the ideographic baseline is better defined and implemented,
// the values of this test should change very slightly. See the issue this is based off
// of: https://github.com/flutter/flutter/issues/25782.
final Key targetKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
routes: <String, WidgetBuilder>{
'/next': (BuildContext context) {
return const Text('Next');
},
},
localizationsDelegates: GlobalMaterialLocalizations.delegates,
supportedLocales: const <Locale>[
Locale('en', 'US'),
Locale('es', 'ES'),
Locale('zh', 'CN'),
],
locale: const Locale('en', 'US'),
home: Material(
child: Center(
child: Builder(
key: targetKey,
builder: (BuildContext context) {
return PopupMenuButton<int>(
onSelected: (int value) {
Navigator.pushNamed(context, '/next');
},
itemBuilder: (BuildContext context) {
return <PopupMenuItem<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text(
'hello, world',
style: TextStyle(color: Colors.blue),
),
),
const PopupMenuItem<int>(
value: 2,
child: Text(
'你好,世界',
style: TextStyle(color: Colors.blue),
),
),
];
},
);
},
),
),
),
),
);
await tester.tap(find.byKey(targetKey));
await tester.pumpAndSettle();
expect(find.text('hello, world'), findsOneWidget);
expect(find.text('你好,世界'), findsOneWidget);
Offset topLeft = tester.getTopLeft(find.text('hello, world'));
Offset topRight = tester.getTopRight(find.text('hello, world'));
Offset bottomLeft = tester.getBottomLeft(find.text('hello, world'));
Offset bottomRight = tester.getBottomRight(find.text('hello, world'));
expect(topLeft, const Offset(392.0, 300.0));
expect(topRight, const Offset(584.0, 300.0));
expect(bottomLeft, const Offset(392.0, 316));
expect(bottomRight, const Offset(584.0, 316));
topLeft = tester.getTopLeft(find.text('你好,世界'));
topRight = tester.getTopRight(find.text('你好,世界'));
bottomLeft = tester.getBottomLeft(find.text('你好,世界'));
bottomRight = tester.getBottomRight(find.text('你好,世界'));
expect(topLeft, const Offset(392.0, 348.0));
expect(topRight, const Offset(472.0, 348.0));
expect(bottomLeft, const Offset(392.0, 364.0));
expect(bottomRight, const Offset(472.0, 364.0));
});
}
| flutter/packages/flutter_localizations/test/text_test.dart/0 | {'file_path': 'flutter/packages/flutter_localizations/test/text_test.dart', 'repo_id': 'flutter', 'token_count': 3339} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('restartAndRestore', (WidgetTester tester) async {
await tester.pumpWidget(
const RootRestorationScope(
restorationId: 'root-child',
child: _RestorableWidget(
restorationId: 'restorable-widget',
),
),
);
final _RestorableWidgetState state = tester.state(find.byType(_RestorableWidget));
expect(find.text('Hello World 100'), findsOneWidget);
expect(state.doubleValue, 1.0);
state.setValues('Guten Morgen', 200, 33.4);
await tester.pump();
expect(find.text('Guten Morgen 200'), findsOneWidget);
expect(state.doubleValue, 33.4);
await tester.restartAndRestore();
expect(find.text('Guten Morgen 200'), findsOneWidget);
expect(find.text('Hello World 100'), findsNothing);
final _RestorableWidgetState restoredState = tester.state(find.byType(_RestorableWidget));
expect(restoredState, isNot(same(state)));
expect(restoredState.doubleValue, 1.0);
});
testWidgets('restore from previous restoration data', (WidgetTester tester) async {
await tester.pumpWidget(
const RootRestorationScope(
restorationId: 'root-child',
child: _RestorableWidget(
restorationId: 'restorable-widget',
),
),
);
final _RestorableWidgetState state = tester.state(find.byType(_RestorableWidget));
expect(find.text('Hello World 100'), findsOneWidget);
expect(state.doubleValue, 1.0);
state.setValues('Guten Morgen', 200, 33.4);
await tester.pump();
expect(find.text('Guten Morgen 200'), findsOneWidget);
expect(state.doubleValue, 33.4);
final TestRestorationData data = await tester.getRestorationData();
state.setValues('See you later!', 400, 123.5);
await tester.pump();
expect(find.text('See you later! 400'), findsOneWidget);
expect(state.doubleValue, 123.5);
await tester.restoreFrom(data);
expect(tester.state(find.byType(_RestorableWidget)), same(state));
expect(find.text('Guten Morgen 200'), findsOneWidget);
expect(state.doubleValue, 123.5);
});
}
class _RestorableWidget extends StatefulWidget {
const _RestorableWidget({this.restorationId});
final String? restorationId;
@override
State<_RestorableWidget> createState() => _RestorableWidgetState();
}
class _RestorableWidgetState extends State<_RestorableWidget> with RestorationMixin {
final RestorableString stringValue = RestorableString('Hello World');
final RestorableInt intValue = RestorableInt(100);
double doubleValue = 1.0; // Not restorable.
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(stringValue, 'string');
registerForRestoration(intValue, 'int');
}
void setValues(String s, int i, double d) {
setState(() {
stringValue.value = s;
intValue.value = i;
doubleValue = d;
});
}
@override
Widget build(BuildContext context) {
return Text('${stringValue.value} ${intValue.value}', textDirection: TextDirection.ltr);
}
@override
String? get restorationId => widget.restorationId;
}
| flutter/packages/flutter_test/test/restoration_test.dart/0 | {'file_path': 'flutter/packages/flutter_test/test/restoration_test.dart', 'repo_id': 'flutter', 'token_count': 1172} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
import '../dart/analysis.dart';
import 'analyze_base.dart';
class AnalyzeContinuously extends AnalyzeBase {
AnalyzeContinuously(
super.argResults,
List<String> repoRoots,
List<Directory> repoPackages, {
required super.fileSystem,
required super.logger,
required super.terminal,
required super.platform,
required super.processManager,
required super.artifacts,
}) : super(
repoPackages: repoPackages,
repoRoots: repoRoots,
);
String? analysisTarget;
bool firstAnalysis = true;
Set<String> analyzedPaths = <String>{};
Map<String, List<AnalysisError>> analysisErrors = <String, List<AnalysisError>>{};
final Stopwatch analysisTimer = Stopwatch();
int lastErrorCount = 0;
Status? analysisStatus;
@override
Future<void> analyze() async {
List<String> directories;
if (isFlutterRepo) {
final PackageDependencyTracker dependencies = PackageDependencyTracker();
dependencies.checkForConflictingDependencies(repoPackages, dependencies);
directories = repoRoots;
analysisTarget = 'Flutter repository';
logger.printTrace('Analyzing Flutter repository:');
for (final String projectPath in repoRoots) {
logger.printTrace(' ${fileSystem.path.relative(projectPath)}');
}
} else {
directories = <String>[fileSystem.currentDirectory.path];
analysisTarget = fileSystem.currentDirectory.path;
}
final AnalysisServer server = AnalysisServer(
sdkPath,
directories,
fileSystem: fileSystem,
logger: logger,
platform: platform,
processManager: processManager,
terminal: terminal,
protocolTrafficLog: protocolTrafficLog,
);
server.onAnalyzing.listen((bool isAnalyzing) => _handleAnalysisStatus(server, isAnalyzing));
server.onErrors.listen(_handleAnalysisErrors);
await server.start();
final int? exitCode = await server.onExit;
final String message = 'Analysis server exited with code $exitCode.';
if (exitCode != 0) {
throwToolExit(message, exitCode: exitCode);
}
logger.printStatus(message);
if (server.didServerErrorOccur) {
throwToolExit('Server error(s) occurred.');
}
}
void _handleAnalysisStatus(AnalysisServer server, bool isAnalyzing) {
if (isAnalyzing) {
analysisStatus?.cancel();
if (!firstAnalysis) {
logger.printStatus('\n');
}
analysisStatus = logger.startProgress('Analyzing $analysisTarget...');
analyzedPaths.clear();
analysisTimer.start();
} else {
analysisStatus?.stop();
analysisStatus = null;
analysisTimer.stop();
logger.printStatus(terminal.clearScreen(), newline: false);
// Remove errors for deleted files, sort, and print errors.
final List<AnalysisError> sortedErrors = <AnalysisError>[];
final List<String> pathsToRemove = <String>[];
analysisErrors.forEach((String path, List<AnalysisError> errors) {
if (fileSystem.isFileSync(path)) {
sortedErrors.addAll(errors);
} else {
pathsToRemove.add(path);
}
});
analysisErrors.removeWhere((String path, _) => pathsToRemove.contains(path));
sortedErrors.sort();
for (final AnalysisError error in sortedErrors) {
logger.printStatus(error.toString());
logger.printTrace('error code: ${error.code}');
}
dumpErrors(sortedErrors.map<String>((AnalysisError error) => error.toLegacyString()));
final int issueCount = sortedErrors.length;
final int issueDiff = issueCount - lastErrorCount;
lastErrorCount = issueCount;
final String seconds = (analysisTimer.elapsedMilliseconds / 1000.0).toStringAsFixed(2);
final String errorsMessage = AnalyzeBase.generateErrorsMessage(
issueCount: issueCount,
issueDiff: issueDiff,
files: analyzedPaths.length,
seconds: seconds,
);
logger.printStatus(errorsMessage);
if (firstAnalysis && isBenchmarking) {
writeBenchmark(analysisTimer, issueCount);
server.dispose().whenComplete(() { exit(issueCount > 0 ? 1 : 0); });
}
firstAnalysis = false;
}
}
void _handleAnalysisErrors(FileAnalysisErrors fileErrors) {
fileErrors.errors.removeWhere((AnalysisError error) => error.type == 'TODO');
analyzedPaths.add(fileErrors.file);
analysisErrors[fileErrors.file] = fileErrors.errors;
}
}
| flutter/packages/flutter_tools/lib/src/commands/analyze_continuously.dart/0 | {'file_path': 'flutter/packages/flutter_tools/lib/src/commands/analyze_continuously.dart', 'repo_id': 'flutter', 'token_count': 1706} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Hide the original utf8 [Codec] so that we can export our own implementation
// which adds additional error handling.
import 'dart:convert' hide utf8;
import 'dart:convert' as cnv show Utf8Decoder, utf8;
import 'package:meta/meta.dart';
import 'base/common.dart';
export 'dart:convert' hide Utf8Codec, Utf8Decoder, utf8;
/// The original utf8 encoding for testing overrides only.
///
/// Attempting to use the flutter tool utf8 decoder will surface an analyzer
/// warning that overrides cannot change the default value of a named
/// parameter.
@visibleForTesting
const Encoding utf8ForTesting = cnv.utf8;
/// A [Codec] which reports malformed bytes when decoding.
///
/// Occasionally people end up in a situation where we try to decode bytes
/// that aren't UTF-8 and we're not quite sure how this is happening.
/// This tells people to report a bug when they see this.
class Utf8Codec extends Encoding {
const Utf8Codec({this.reportErrors = true});
final bool reportErrors;
@override
Converter<List<int>, String> get decoder => reportErrors
? const Utf8Decoder()
: const Utf8Decoder(reportErrors: false);
@override
Converter<String, List<int>> get encoder => cnv.utf8.encoder;
@override
String get name => cnv.utf8.name;
}
const Encoding utf8 = Utf8Codec();
class Utf8Decoder extends cnv.Utf8Decoder {
const Utf8Decoder({this.reportErrors = true}) : super(allowMalformed: true);
final bool reportErrors;
@override
String convert(List<int> codeUnits, [ int start = 0, int? end ]) {
final String result = super.convert(codeUnits, start, end);
// Finding a unicode replacement character indicates that the input
// was malformed.
if (reportErrors && result.contains('\u{FFFD}')) {
throwToolExit(
'Bad UTF-8 encoding (U+FFFD; REPLACEMENT CHARACTER) found while decoding string: $result. '
'The Flutter team would greatly appreciate if you could file a bug explaining '
'exactly what you were doing when this happened:\n'
'https://github.com/flutter/flutter/issues/new/choose\n'
'The source bytes were:\n$codeUnits\n\n');
}
return result;
}
}
| flutter/packages/flutter_tools/lib/src/convert.dart/0 | {'file_path': 'flutter/packages/flutter_tools/lib/src/convert.dart', 'repo_id': 'flutter', 'token_count': 765} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:process/process.dart';
import 'android/android_device_discovery.dart';
import 'android/android_sdk.dart';
import 'android/android_workflow.dart';
import 'artifacts.dart';
import 'base/file_system.dart';
import 'base/os.dart';
import 'base/platform.dart';
import 'base/user_messages.dart';
import 'custom_devices/custom_device.dart';
import 'custom_devices/custom_devices_config.dart';
import 'device.dart';
import 'features.dart';
import 'fuchsia/fuchsia_device.dart';
import 'fuchsia/fuchsia_sdk.dart';
import 'fuchsia/fuchsia_workflow.dart';
import 'ios/devices.dart';
import 'ios/ios_workflow.dart';
import 'ios/simulators.dart';
import 'linux/linux_device.dart';
import 'macos/macos_device.dart';
import 'macos/macos_ipad_device.dart';
import 'macos/macos_workflow.dart';
import 'macos/xcdevice.dart';
import 'tester/flutter_tester.dart';
import 'version.dart';
import 'web/web_device.dart';
import 'windows/windows_device.dart';
import 'windows/windows_workflow.dart';
/// A provider for all of the device discovery instances.
class FlutterDeviceManager extends DeviceManager {
FlutterDeviceManager({
required super.logger,
required Platform platform,
required ProcessManager processManager,
required FileSystem fileSystem,
required AndroidSdk? androidSdk,
required FeatureFlags featureFlags,
required IOSSimulatorUtils iosSimulatorUtils,
required XCDevice xcDevice,
required AndroidWorkflow androidWorkflow,
required IOSWorkflow iosWorkflow,
required FuchsiaWorkflow fuchsiaWorkflow,
required FlutterVersion flutterVersion,
required Artifacts artifacts,
required MacOSWorkflow macOSWorkflow,
required FuchsiaSdk fuchsiaSdk,
required UserMessages userMessages,
required OperatingSystemUtils operatingSystemUtils,
required WindowsWorkflow windowsWorkflow,
required CustomDevicesConfig customDevicesConfig,
}) : deviceDiscoverers = <DeviceDiscovery>[
AndroidDevices(
logger: logger,
androidSdk: androidSdk,
androidWorkflow: androidWorkflow,
processManager: processManager,
fileSystem: fileSystem,
platform: platform,
userMessages: userMessages,
),
IOSDevices(
platform: platform,
xcdevice: xcDevice,
iosWorkflow: iosWorkflow,
logger: logger,
),
IOSSimulators(
iosSimulatorUtils: iosSimulatorUtils,
),
FuchsiaDevices(
fuchsiaSdk: fuchsiaSdk,
logger: logger,
fuchsiaWorkflow: fuchsiaWorkflow,
platform: platform,
),
FlutterTesterDevices(
fileSystem: fileSystem,
flutterVersion: flutterVersion,
processManager: processManager,
logger: logger,
artifacts: artifacts,
operatingSystemUtils: operatingSystemUtils,
),
MacOSDevices(
processManager: processManager,
macOSWorkflow: macOSWorkflow,
logger: logger,
platform: platform,
fileSystem: fileSystem,
operatingSystemUtils: operatingSystemUtils,
),
MacOSDesignedForIPadDevices(
processManager: processManager,
iosWorkflow: iosWorkflow,
logger: logger,
platform: platform,
fileSystem: fileSystem,
operatingSystemUtils: operatingSystemUtils,
),
LinuxDevices(
platform: platform,
featureFlags: featureFlags,
processManager: processManager,
logger: logger,
fileSystem: fileSystem,
operatingSystemUtils: operatingSystemUtils,
),
WindowsDevices(
processManager: processManager,
operatingSystemUtils: operatingSystemUtils,
logger: logger,
fileSystem: fileSystem,
windowsWorkflow: windowsWorkflow,
),
WebDevices(
featureFlags: featureFlags,
fileSystem: fileSystem,
platform: platform,
processManager: processManager,
logger: logger,
),
CustomDevices(
featureFlags: featureFlags,
processManager: processManager,
logger: logger,
config: customDevicesConfig
),
];
@override
final List<DeviceDiscovery> deviceDiscoverers;
}
| flutter/packages/flutter_tools/lib/src/flutter_device_manager.dart/0 | {'file_path': 'flutter/packages/flutter_tools/lib/src/flutter_device_manager.dart', 'repo_id': 'flutter', 'token_count': 1546} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../base/file_system.dart';
import '../base/logger.dart';
/// The name of the test configuration file that will be discovered by the
/// test harness if it exists in the project directory hierarchy.
const String _kTestConfigFileName = 'flutter_test_config.dart';
/// The name of the file that signals the root of the project and that will
/// cause the test harness to stop scanning for configuration files.
const String _kProjectRootSentinel = 'pubspec.yaml';
/// Find the `flutter_test_config.dart` file for a specific test file.
File? findTestConfigFile(File testFile, Logger logger) {
File? testConfigFile;
Directory directory = testFile.parent;
while (directory.path != directory.parent.path) {
final File configFile = directory.childFile(_kTestConfigFileName);
if (configFile.existsSync()) {
logger.printTrace('Discovered $_kTestConfigFileName in ${directory.path}');
testConfigFile = configFile;
break;
}
if (directory.childFile(_kProjectRootSentinel).existsSync()) {
logger.printTrace('Stopping scan for $_kTestConfigFileName; '
'found project root at ${directory.path}');
break;
}
directory = directory.parent;
}
return testConfigFile;
}
| flutter/packages/flutter_tools/lib/src/test/test_config.dart/0 | {'file_path': 'flutter/packages/flutter_tools/lib/src/test/test_config.dart', 'repo_id': 'flutter', 'token_count': 427} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../base/os.dart';
import '../doctor_validator.dart';
/// Flutter only supports development on Windows host machines version 10 and greater.
const List<String> kUnsupportedVersions = <String>[
'6',
'7',
'8',
];
/// Regex pattern for identifying line from systeminfo stdout with windows version
/// (ie. 10.5.4123)
const String kWindowsOSVersionSemVerPattern = r'([0-9]+)\.([0-9]+)\.([0-9\.]+)';
/// Validator for supported Windows host machine operating system version.
class WindowsVersionValidator extends DoctorValidator {
const WindowsVersionValidator({
required OperatingSystemUtils operatingSystemUtils,
}) : _operatingSystemUtils = operatingSystemUtils,
super('Windows Version');
final OperatingSystemUtils _operatingSystemUtils;
@override
Future<ValidationResult> validate() async {
final RegExp regex =
RegExp(kWindowsOSVersionSemVerPattern, multiLine: true);
final String commandResult = _operatingSystemUtils.name;
final Iterable<RegExpMatch> matches = regex.allMatches(commandResult);
// Use the string split method to extract the major version
// and check against the [kUnsupportedVersions] list
final ValidationType windowsVersionStatus;
final String statusInfo;
if (matches.length == 1 &&
!kUnsupportedVersions.contains(matches.elementAt(0).group(1))) {
windowsVersionStatus = ValidationType.success;
statusInfo = 'Installed version of Windows is version 10 or higher';
} else {
windowsVersionStatus = ValidationType.missing;
statusInfo =
'Unable to determine Windows version (command `ver` returned $commandResult)';
}
return ValidationResult(
windowsVersionStatus,
const <ValidationMessage>[],
statusInfo: statusInfo,
);
}
}
| flutter/packages/flutter_tools/lib/src/windows/windows_version_validator.dart/0 | {'file_path': 'flutter/packages/flutter_tools/lib/src/windows/windows_version_validator.dart', 'repo_id': 'flutter', 'token_count': 610} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/file.dart';
import 'package:flutter_tools/src/convert.dart';
import '../src/common.dart';
import 'test_utils.dart';
/// Checks that all active template files are defined in the template_manifest.json file.
void main() {
testWithoutContext('Check template manifest is up to date', () {
final Map<String, Object?> manifest = json.decode(
fileSystem.file('templates/template_manifest.json').readAsStringSync(),
) as Map<String, Object?>;
final Set<Uri> declaredFileList = Set<Uri>.from(
(manifest['files']! as List<Object?>).cast<String>().map<Uri>(fileSystem.path.toUri));
final Set<Uri> activeTemplateList = fileSystem.directory('templates')
.listSync(recursive: true)
.whereType<File>()
.where((File file) => fileSystem.path.basename(file.path) != 'template_manifest.json' &&
fileSystem.path.basename(file.path) != 'README.md' &&
fileSystem.path.basename(file.path) != '.DS_Store')
.map((File file) => file.uri)
.toSet();
final Set<Uri> difference = activeTemplateList.difference(declaredFileList);
expect(difference, isEmpty, reason: 'manifest and template directory should be in-sync');
});
}
| flutter/packages/flutter_tools/test/integration.shard/template_manifest_test.dart/0 | {'file_path': 'flutter/packages/flutter_tools/test/integration.shard/template_manifest_test.dart', 'repo_id': 'flutter', 'token_count': 475} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Library for logging the remote debug protocol internals.
///
/// Useful for determining connection issues and the like. This is included as a
/// separate library so that it can be imported under a separate namespace in
/// the event that you are using a logging package with similar class names.
library logging;
export 'src/common/logging.dart';
| flutter/packages/fuchsia_remote_debug_protocol/lib/logging.dart/0 | {'file_path': 'flutter/packages/fuchsia_remote_debug_protocol/lib/logging.dart', 'repo_id': 'flutter', 'token_count': 121} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'dart:html' as html;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:integration_test_example/main.dart' as app;
void main() {
final IntegrationTestWidgetsFlutterBinding binding =
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('verify text', (WidgetTester tester) async {
// Build our app and trigger a frame.
app.main();
// Trigger a frame.
await tester.pumpAndSettle();
// Take a screenshot.
await binding.takeScreenshot(
'platform_name',
// The optional parameter 'args' can be used to pass values to the
// [integrationDriver.onScreenshot] handler
// (see test_driver/extended_integration_test.dart). For example, you
// could look up environment variables in this test that were passed to
// the run command via `--dart-define=`, and then pass the values to the
// [integrationDriver.onScreenshot] handler through this 'args' map.
<String, Object?>{
'someArgumentKey': 'someArgumentValue',
},
);
// Verify that platform is retrieved.
expect(
find.byWidgetPredicate(
(Widget widget) =>
widget is Text &&
widget.data!
.startsWith('Platform: ${html.window.navigator.platform}\n'),
),
findsOneWidget,
);
});
testWidgets('verify screenshot', (WidgetTester tester) async {
// Build our app and trigger a frame.
app.main();
// Trigger a frame.
await tester.pumpAndSettle();
// Multiple methods can take screenshots. Screenshots are taken with the
// same order the methods run. We pass an argument that can be looked up
// from the [onScreenshot] handler in
// [test_driver/extended_integration_test.dart].
await binding.takeScreenshot(
'platform_name_2',
// The optional parameter 'args' can be used to pass values to the
// [integrationDriver.onScreenshot] handler
// (see test_driver/extended_integration_test.dart). For example, you
// could look up environment variables in this test that were passed to
// the run command via `--dart-define=`, and then pass the values to the
// [integrationDriver.onScreenshot] handler through this 'args' map.
<String, Object?>{
'someArgumentKey': 'someArgumentValue',
},
);
});
}
| flutter/packages/integration_test/example/integration_test/_extended_test_web.dart/0 | {'file_path': 'flutter/packages/integration_test/example/integration_test/_extended_test_web.dart', 'repo_id': 'flutter', 'token_count': 999} |
import 'package:flutter/material.dart';
class CalculatorConfig {
CalculatorConfig({
required this.calculatorSide,
this.animationCurve = Curves.easeIn,
this.borderRadius = 15,
this.keysHaveShadow = true,
this.baseColor = Colors.blueGrey,
this.startAt3D = true,
});
final double borderRadius;
final bool keysHaveShadow;
final MaterialColor baseColor;
final bool startAt3D;
final Color keysShadowColor = Colors.blueGrey.shade900;
double get keysGap => calculatorSide * 0.04;
final Curve animationCurve;
final int keysPerRow = 4;
double get fontSize => keySideMin * 0.6;
final double calculatorSide;
double get calculatorBodyMaxSidesDistance => calculatorSide * 0.28;
double get calculatorSideWithDistance =>
calculatorTotalSide + calculatorBodyMaxSidesDistance;
double get calculatorTotalSide => calculatorSide + calculatorPadding * 2;
double get calculatorPadding => calculatorSide * 0.04;
double get keyDownDistance => calculatorPadding * 2;
double get calculatorVerticalBodyIndent => calculatorPadding * 2.5;
double get keySideMin =>
(calculatorSide - (keysGap * (keysPerRow - 1))) / keysPerRow;
Size get calculatorSize => Size(calculatorSide, calculatorSide);
}
| flutter_3d_calculator/lib/utils/calculator_config.dart/0 | {'file_path': 'flutter_3d_calculator/lib/utils/calculator_config.dart', 'repo_id': 'flutter_3d_calculator', 'token_count': 378} |
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_airbnb_ui/home_page.dart';
import 'package:flutter_airbnb_ui/widgets/book_flip_demo.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _isInit = true;
@override
void didChangeDependencies() {
if (_isInit) {
for (var i = 1; i <= 6; i++) {
precacheImage(
Image.asset('assets/images/listing-$i.jpg').image,
context,
);
}
for (var i = 1; i <= 3; i++) {
precacheImage(
Image.asset('assets/images/person-$i.jpeg').image,
context,
);
}
}
_isInit = false;
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Airbnb Book Flip Interaction',
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
systemOverlayStyle: SystemUiOverlayStyle.dark,
),
primarySwatch: Colors.blue,
),
home: const HomePage(),
);
}
}
| flutter_airbnb_ui/lib/main.dart/0 | {'file_path': 'flutter_airbnb_ui/lib/main.dart', 'repo_id': 'flutter_airbnb_ui', 'token_count': 585} |
export 'cubit/favorites_cubit.dart';
export 'views/view.dart';
export 'widgets/widgets.dart';
| flutter_and_friends/lib/favorites/favorites.dart/0 | {'file_path': 'flutter_and_friends/lib/favorites/favorites.dart', 'repo_id': 'flutter_and_friends', 'token_count': 40} |
export 'events.dart';
export 'talks.dart';
export 'workshops.dart';
| flutter_and_friends/lib/schedule/data/data.dart/0 | {'file_path': 'flutter_and_friends/lib/schedule/data/data.dart', 'repo_id': 'flutter_and_friends', 'token_count': 26} |
export 'sponsors.dart';
| flutter_and_friends/lib/sponsors/models/models.dart/0 | {'file_path': 'flutter_and_friends/lib/sponsors/models/models.dart', 'repo_id': 'flutter_and_friends', 'token_count': 9} |
export 'twitter_icon_button.dart';
| flutter_and_friends/lib/twitter/widgets/widgets.dart/0 | {'file_path': 'flutter_and_friends/lib/twitter/widgets/widgets.dart', 'repo_id': 'flutter_and_friends', 'token_count': 12} |
import 'package:equatable/equatable.dart';
abstract class StatsState extends Equatable {
const StatsState();
@override
List<Object> get props => [];
}
class StatsLoading extends StatsState {}
class StatsLoaded extends StatsState {
final int numActive;
final int numCompleted;
const StatsLoaded(this.numActive, this.numCompleted);
@override
List<Object> get props => [numActive, numCompleted];
@override
String toString() {
return 'StatsLoaded { numActive: $numActive, numCompleted: $numCompleted }';
}
}
| flutter_architecture_samples/bloc_library/lib/blocs/stats/stats_state.dart/0 | {'file_path': 'flutter_architecture_samples/bloc_library/lib/blocs/stats/stats_state.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 161} |
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.
import 'package:bloc/bloc.dart';
import 'package:bloc_library/blocs/blocs.dart';
import 'package:bloc_library/localization.dart';
import 'package:bloc_library/models/models.dart';
import 'package:bloc_library/screens/screens.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:todos_app_core/todos_app_core.dart';
import 'package:todos_repository_core/todos_repository_core.dart';
void runBlocLibraryApp(TodosRepository repository) {
// BlocSupervisor oversees Blocs and delegates to BlocDelegate.
// We can set the BlocSupervisor's delegate to an instance of `SimpleBlocDelegate`.
// This will allow us to handle all transitions and errors in SimpleBlocDelegate.
BlocSupervisor.delegate = SimpleBlocDelegate();
runApp(
BlocProvider<TodosBloc>(
create: (context) {
return TodosBloc(todosRepository: repository)..add(LoadTodos());
},
child: TodosApp(),
),
);
}
class TodosApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final todosBloc = BlocProvider.of<TodosBloc>(context);
return MaterialApp(
onGenerateTitle: (context) =>
FlutterBlocLocalizations.of(context).appTitle,
theme: ArchSampleTheme.theme,
localizationsDelegates: [
ArchSampleLocalizationsDelegate(),
FlutterBlocLocalizationsDelegate(),
],
routes: {
ArchSampleRoutes.home: (context) {
return MultiBlocProvider(
providers: [
BlocProvider<TabBloc>(
create: (context) => TabBloc(),
),
BlocProvider<FilteredTodosBloc>(
create: (context) => FilteredTodosBloc(todosBloc: todosBloc),
),
BlocProvider<StatsBloc>(
create: (context) => StatsBloc(todosBloc: todosBloc),
),
],
child: HomeScreen(),
);
},
ArchSampleRoutes.addTodo: (context) {
return AddEditScreen(
key: ArchSampleKeys.addTodoScreen,
onSave: (task, note) {
todosBloc.add(AddTodo(Todo(task, note: note)));
},
isEditing: false,
);
},
},
);
}
}
| flutter_architecture_samples/bloc_library/lib/run_app.dart/0 | {'file_path': 'flutter_architecture_samples/bloc_library/lib/run_app.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1078} |
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.
import 'dart:async';
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:bloc_library/blocs/blocs.dart';
import 'package:bloc_library/models/models.dart';
import 'package:todos_repository_local_storage/todos_repository_local_storage.dart';
class MockTodosBloc extends MockBloc<TodosEvent, TodosState>
implements TodosBloc {}
class MockTodosRepository extends Mock implements LocalStorageRepository {}
void main() {
group('FilteredTodosBloc', () {
blocTest<FilteredTodosBloc, FilteredTodosEvent, FilteredTodosState>(
'adds TodosUpdated when TodosBloc.state emits TodosLoaded',
build: () {
final todosBloc = MockTodosBloc();
when(todosBloc.state).thenReturn(
TodosLoaded([Todo('Wash Dishes', id: '0')]),
);
whenListen(
todosBloc,
Stream<TodosState>.fromIterable([
TodosLoaded([Todo('Wash Dishes', id: '0')]),
]),
);
return FilteredTodosBloc(todosBloc: todosBloc);
},
expect: [
FilteredTodosLoaded(
[Todo('Wash Dishes', id: '0')],
VisibilityFilter.all,
),
],
);
blocTest<FilteredTodosBloc, FilteredTodosEvent, FilteredTodosState>(
'should update the VisibilityFilter when filter is active',
build: () {
final todosBloc = MockTodosBloc();
when(todosBloc.state)
.thenReturn(TodosLoaded([Todo('Wash Dishes', id: '0')]));
return FilteredTodosBloc(todosBloc: todosBloc);
},
act: (FilteredTodosBloc bloc) async =>
bloc.add(UpdateFilter(VisibilityFilter.active)),
expect: <FilteredTodosState>[
FilteredTodosLoaded(
[Todo('Wash Dishes', id: '0')],
VisibilityFilter.all,
),
FilteredTodosLoaded(
[Todo('Wash Dishes', id: '0')],
VisibilityFilter.active,
),
],
);
blocTest<FilteredTodosBloc, FilteredTodosEvent, FilteredTodosState>(
'should update the VisibilityFilter when filter is completed',
build: () {
final todosBloc = MockTodosBloc();
when(todosBloc.state)
.thenReturn(TodosLoaded([Todo('Wash Dishes', id: '0')]));
return FilteredTodosBloc(todosBloc: todosBloc);
},
act: (FilteredTodosBloc bloc) async =>
bloc.add(UpdateFilter(VisibilityFilter.completed)),
expect: <FilteredTodosState>[
FilteredTodosLoaded(
[Todo('Wash Dishes', id: '0')],
VisibilityFilter.all,
),
FilteredTodosLoaded([], VisibilityFilter.completed),
],
);
});
}
| flutter_architecture_samples/bloc_library/test/blocs/filtered_todos_bloc_test.dart/0 | {'file_path': 'flutter_architecture_samples/bloc_library/test/blocs/filtered_todos_bloc_test.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1320} |
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.
library filter_selector;
import 'package:built_redux_sample/actions/actions.dart';
import 'package:built_redux_sample/containers/typedefs.dart';
import 'package:built_redux_sample/models/models.dart';
import 'package:built_value/built_value.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_built_redux/flutter_built_redux.dart';
part 'filter_selector.g.dart';
typedef OnFilterSelected = void Function(VisibilityFilter filter);
abstract class FilterSelectorViewModel
implements Built<FilterSelectorViewModel, FilterSelectorViewModelBuilder> {
FilterSelectorViewModel._();
OnFilterSelected get onFilterSelected;
VisibilityFilter get activeFilter;
factory FilterSelectorViewModel(
[void Function(FilterSelectorViewModelBuilder b) updates]) =
_$FilterSelectorViewModel;
factory FilterSelectorViewModel.from(
AppActions actions,
VisibilityFilter activeFilter,
) {
return FilterSelectorViewModel((b) => b
..onFilterSelected = (filter) {
actions.updateFilterAction(filter);
}
..activeFilter = activeFilter);
}
}
class FilterSelector
extends StoreConnector<AppState, AppActions, VisibilityFilter> {
final ViewModelBuilder<FilterSelectorViewModel> builder;
@override
VisibilityFilter connect(AppState state) => state.activeFilter;
FilterSelector({Key key, @required this.builder}) : super(key: key);
@override
Widget build(
BuildContext context,
VisibilityFilter activeFilter,
AppActions actions,
) {
return builder(
context,
FilterSelectorViewModel.from(
actions,
activeFilter,
),
);
}
}
| flutter_architecture_samples/built_redux/lib/containers/filter_selector.dart/0 | {'file_path': 'flutter_architecture_samples/built_redux/lib/containers/filter_selector.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 622} |
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.
library app_tab;
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
part 'app_tab.g.dart';
class AppTab extends EnumClass {
static Serializer<AppTab> get serializer => _$appTabSerializer;
static const AppTab todos = _$todos;
static const AppTab stats = _$stats;
const AppTab._(String name) : super(name);
static BuiltSet<AppTab> get values => _$appTabValues;
static AppTab valueOf(String name) => _$appTabValueOf(name);
static AppTab fromIndex(int index) {
switch (index) {
case 1:
return AppTab.stats;
default:
return AppTab.todos;
}
}
static int toIndex(AppTab tab) {
switch (tab) {
case AppTab.stats:
return 1;
default:
return 0;
}
}
}
| flutter_architecture_samples/built_redux/lib/models/app_tab.dart/0 | {'file_path': 'flutter_architecture_samples/built_redux/lib/models/app_tab.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 368} |
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.
import 'dart:async';
import 'package:flutter/material.dart';
class ProviderLocalizations {
static ProviderLocalizations of(BuildContext context) {
return Localizations.of<ProviderLocalizations>(
context, ProviderLocalizations);
}
String get appTitle => 'Provider Example';
}
class ProviderLocalizationsDelegate
extends LocalizationsDelegate<ProviderLocalizations> {
@override
Future<ProviderLocalizations> load(Locale locale) =>
Future(() => ProviderLocalizations());
@override
bool shouldReload(ProviderLocalizationsDelegate old) => false;
@override
bool isSupported(Locale locale) =>
locale.languageCode.toLowerCase().contains('en');
}
| flutter_architecture_samples/change_notifier_provider/lib/localization.dart/0 | {'file_path': 'flutter_architecture_samples/change_notifier_provider/lib/localization.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 245} |
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:todos_repository_core/todos_repository_core.dart';
class FirestoreReactiveTodosRepository implements ReactiveTodosRepository {
static const String path = 'todo';
final Firestore firestore;
const FirestoreReactiveTodosRepository(this.firestore);
@override
Future<void> addNewTodo(TodoEntity todo) {
return firestore.collection(path).document(todo.id).setData(todo.toJson());
}
@override
Future<void> deleteTodo(List<String> idList) async {
await Future.wait<void>(idList.map((id) {
return firestore.collection(path).document(id).delete();
}));
}
@override
Stream<List<TodoEntity>> todos() {
return firestore.collection(path).snapshots().map((snapshot) {
return snapshot.documents.map((doc) {
return TodoEntity(
doc['task'],
doc.documentID,
doc['note'] ?? '',
doc['complete'] ?? false,
);
}).toList();
});
}
@override
Future<void> updateTodo(TodoEntity todo) {
return firestore
.collection(path)
.document(todo.id)
.updateData(todo.toJson());
}
}
| flutter_architecture_samples/firebase_flutter_repository/lib/reactive_todos_repository.dart/0 | {'file_path': 'flutter_architecture_samples/firebase_flutter_repository/lib/reactive_todos_repository.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 526} |
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.
import 'dart:async';
import 'package:flutter/material.dart';
class FirestoreReduxLocalizations {
static FirestoreReduxLocalizations of(BuildContext context) {
return Localizations.of<FirestoreReduxLocalizations>(
context,
FirestoreReduxLocalizations,
);
}
String get appTitle => 'Firestore Redux Example';
}
class FirestoreReduxLocalizationsDelegate
extends LocalizationsDelegate<FirestoreReduxLocalizations> {
@override
Future<FirestoreReduxLocalizations> load(Locale locale) =>
Future(() => FirestoreReduxLocalizations());
@override
bool shouldReload(FirestoreReduxLocalizationsDelegate old) => false;
@override
bool isSupported(Locale locale) =>
locale.languageCode.toLowerCase().contains('en');
}
| flutter_architecture_samples/firestore_redux/lib/localization.dart/0 | {'file_path': 'flutter_architecture_samples/firestore_redux/lib/localization.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 283} |
import 'package:flutter/material.dart';
import 'package:frideos/frideos.dart';
import 'package:frideos_library/app_state.dart';
import 'package:frideos_library/localization.dart';
import 'package:frideos_library/screens/add_edit_screen.dart';
import 'package:frideos_library/screens/homescreen.dart';
import 'package:todos_app_core/todos_app_core.dart';
void main() {
runApp(FrideosApp());
}
class FrideosApp extends StatelessWidget {
final appState = AppState();
@override
Widget build(BuildContext context) {
return AppStateProvider<AppState>(
appState: appState,
child: MaterialApp(
onGenerateTitle: (context) => FrideosLocalizations.of(context).appTitle,
theme: ArchSampleTheme.theme,
localizationsDelegates: [
ArchSampleLocalizationsDelegate(),
FrideosLocalizationsDelegate(),
],
routes: {
ArchSampleRoutes.home: (context) => HomeScreen(),
ArchSampleRoutes.addTodo: (context) => AddEditScreen(),
},
),
);
}
}
| flutter_architecture_samples/frideos_library/lib/main.dart/0 | {'file_path': 'flutter_architecture_samples/frideos_library/lib/main.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 406} |
// This is a basic Flutter Driver test for the application. A Flutter Driver
// test is an end-to-end test that "drives" your application from another
// process or even from another computer. If you are familiar with
// Selenium/WebDriver for web, Espresso for Android or UI Automation for iOS,
// this is simply Flutter's version of that.
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';
void main() {
group('end-to-end test', () {
FlutterDriver driver;
setUpAll(() async {
// Connect to a running Flutter application instance.
driver = await FlutterDriver.connect();
});
tearDownAll(() async {
if (driver != null) await driver.close();
});
test('tap on the floating action button; verify counter', () async {
// Finds the floating action button (fab) to tap on
final fab = find.byTooltip('Increment');
// Wait for the floating action button to appear
await driver.waitFor(fab);
// Tap on the fab
await driver.tap(fab);
// Wait for text to change to the desired value
await driver.waitFor(find.text('1'));
});
});
}
| flutter_architecture_samples/frideos_library/test_driver/main_test.dart/0 | {'file_path': 'flutter_architecture_samples/frideos_library/test_driver/main_test.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 378} |
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:inherited_widget_sample/app.dart';
import 'package:inherited_widget_sample/state_container.dart';
import 'package:key_value_store_flutter/key_value_store_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:todos_repository_local_storage/todos_repository_local_storage.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(StateContainer(
child: const InheritedWidgetApp(),
repository: LocalStorageRepository(
localStorage: KeyValueStorage(
'inherited_widget_todos',
FlutterKeyValueStore(await SharedPreferences.getInstance()),
),
),
));
}
| flutter_architecture_samples/inherited_widget/lib/main.dart/0 | {'file_path': 'flutter_architecture_samples/inherited_widget/lib/main.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 297} |
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.
import 'dart:async';
import 'package:flutter_driver/flutter_driver.dart';
Future<bool> widgetExists(
FlutterDriver driver,
SerializableFinder finder, {
Duration timeout,
}) async {
try {
await driver.waitFor(finder, timeout: timeout);
return true;
} catch (_) {
return false;
}
}
Future<bool> widgetAbsent(
FlutterDriver driver,
SerializableFinder finder, {
Duration timeout,
}) async {
try {
await driver.waitForAbsent(finder, timeout: timeout);
return true;
} catch (_) {
return false;
}
}
| flutter_architecture_samples/integration_tests/lib/page_objects/utils.dart/0 | {'file_path': 'flutter_architecture_samples/integration_tests/lib/page_objects/utils.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 235} |
import 'package:flutter/material.dart';
import 'package:mobx_sample/models/todo.dart';
import 'package:todos_app_core/todos_app_core.dart';
class EditTodoScreen extends StatefulWidget {
final void Function() onEdit;
final Todo todo;
const EditTodoScreen({
@required this.todo,
@required this.onEdit,
}) : super(key: ArchSampleKeys.editTodoScreen);
@override
_EditTodoScreenState createState() => _EditTodoScreenState();
}
class _EditTodoScreenState extends State<EditTodoScreen> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(ArchSampleLocalizations.of(context).editTodo)),
body: Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
TextFormField(
key: ArchSampleKeys.taskField,
initialValue: widget.todo.task,
style: Theme.of(context).textTheme.headline,
decoration: InputDecoration(
hintText: ArchSampleLocalizations.of(context).newTodoHint,
),
validator: (val) {
return val.trim().isEmpty
? ArchSampleLocalizations.of(context).emptyTodoError
: null;
},
onSaved: (value) => widget.todo.task = value,
),
TextFormField(
key: ArchSampleKeys.noteField,
initialValue: widget.todo.note ?? '',
decoration: InputDecoration(
hintText: ArchSampleLocalizations.of(context).notesHint,
),
maxLines: 10,
onSaved: (value) => widget.todo.note = value,
)
],
),
),
),
floatingActionButton: FloatingActionButton(
key: ArchSampleKeys.saveTodoFab,
tooltip: ArchSampleLocalizations.of(context).saveChanges,
onPressed: () {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
widget.onEdit();
}
},
child: const Icon(Icons.check),
),
);
}
}
| flutter_architecture_samples/mobx/lib/edit_todo_screen.dart/0 | {'file_path': 'flutter_architecture_samples/mobx/lib/edit_todo_screen.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1121} |
part of edit;
Upd<EditTodoModel, EditTodoMessage> init(TodoEntity todo) {
var model = EditTodoModel((b) => b
..id = todo != null ? todo.id : ''
..note = TextEditingController(text: todo != null ? todo.note : '')
..task = TextEditingController(text: todo != null ? todo.task : ''));
return Upd(model);
}
Upd<EditTodoModel, EditTodoMessage> update(
CmdRepository repo, EditTodoMessage msg, EditTodoModel model) {
if (msg is Save && model.task.text.isNotEmpty) {
var updateCmd = model.id.isEmpty
? repo.createCmd((t) => OnSaved(t), model.task.text, model.note.text)
: repo.updateDetailsCmd(
(t) => OnSaved(t), model.id, model.task.text, model.note.text);
return Upd(model, effects: updateCmd);
}
if (msg is OnSaved && msg.todo != null) {
var navCmd = router.goBack<EditTodoMessage>();
return Upd(model, effects: navCmd);
}
return Upd(model);
}
| flutter_architecture_samples/mvu/lib/edit/state.dart/0 | {'file_path': 'flutter_architecture_samples/mvu/lib/edit/state.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 367} |
part of todos;
Upd<TodosModel, TodosMessage> init(VisibilityFilter filter) {
var model = TodosModel((b) => b
..isLoading = false
..filter = filter
..items = BuiltList<TodoModel>().toBuilder());
return Upd(model, effects: Cmd.ofMsg(LoadTodos()));
}
Upd<TodosModel, TodosMessage> update(
CmdRepository repo, TodosMessage msg, TodosModel model) {
if (msg is LoadTodos) {
return _loadTodos(repo, model);
}
if (msg is OnTodosLoaded) {
return _onTodosLoaded(model, msg);
}
if (msg is OnTodosLoadError) {
return _onLoadingError(model, msg);
}
if (msg is UpdateTodo) {
return _toggleTodo(repo, model, msg);
}
if (msg is RemoveTodo) {
var updatedModel = _removeTodo(model, msg.todo.id);
return Upd(updatedModel, effects: repo.removeCmd(msg.todo.toEntity()));
}
if (msg is UndoRemoveItem) {
var updatedModel = model.rebuild((b) => b.items.add(msg.item));
return Upd(updatedModel, effects: _saveTodosCmd(repo, updatedModel));
}
if (msg is FilterChanged) {
var updatedModel = model.rebuild((b) => b..filter = msg.value);
return Upd(updatedModel);
}
if (msg is ToggleAllMessage) {
return _toggleAll(repo, model, msg);
}
if (msg is CleareCompletedMessage) {
var updatedModel = model.rebuild((b) => b.items.where((t) => !t.complete));
return Upd(updatedModel, effects: _saveTodosCmd(repo, updatedModel));
}
if (msg is ShowDetailsMessage) {
var navigateCmd = router.goToDetailsScreen<TodosMessage>(msg.todo);
return Upd(model, effects: navigateCmd);
}
if (msg is OnTodoItemChanged) {
return _onRepoEvent(model, msg);
}
return Upd(model);
}
Upd<TodosModel, TodosMessage> _loadTodos(CmdRepository repo, TodosModel model) {
var loadCmd = repo.loadTodosCmd((items) => OnTodosLoaded(items),
onError: (exc) => OnTodosLoadError(exc));
var updatedModel = model.rebuild((b) => b
..isLoading = true
..loadingError = null);
return Upd(updatedModel, effects: loadCmd);
}
Upd<TodosModel, TodosMessage> _onTodosLoaded(
TodosModel model, OnTodosLoaded msg) {
var updatedModel = model.rebuild((b) => b
..isLoading = false
..loadingError = null
..items.clear()
..items.addAll(msg.items.map(TodoModel.fromEntity)));
return Upd(updatedModel);
}
Upd<TodosModel, TodosMessage> _onLoadingError(
TodosModel model, OnTodosLoadError msg) {
var updatedModel = model.rebuild((b) => b
..isLoading = false
..loadingError = msg.cause.toString());
return Upd(updatedModel);
}
Upd<TodosModel, TodosMessage> _toggleTodo(
CmdRepository repo, TodosModel model, UpdateTodo msg) {
var updatedTodo = msg.todo.rebuild((b) => b..complete = msg.value);
var updatedModel = _updateTodoItem(model, updatedTodo);
return Upd(updatedModel, effects: _saveTodosCmd(repo, updatedModel));
}
Upd<TodosModel, TodosMessage> _toggleAll(
CmdRepository repo, TodosModel model, ToggleAllMessage msg) {
var setComplete = model.items.any((x) => !x.complete);
var updatedModel = model.rebuild(
(b) => b.items.map((t) => t.rebuild((x) => x..complete = setComplete)));
return Upd(updatedModel, effects: _saveTodosCmd(repo, updatedModel));
}
TodosModel _removeTodo(TodosModel model, String id) =>
model.rebuild((b) => b.items.where((x) => x.id != id));
Upd<TodosModel, TodosMessage> _onRepoEvent(
TodosModel model, OnTodoItemChanged msg) {
if (msg.updated != null) {
var updatedTodo = TodoModel.fromEntity(msg.updated);
return Upd(_updateTodoItem(model, updatedTodo));
}
if (msg.created != null) {
var newItem = TodoModel.fromEntity(msg.created);
var updatedModel = model.rebuild((b) => b.items.add(newItem));
return Upd(updatedModel);
}
if (msg.removed != null) {
var updatedModel = _removeTodo(model, msg.removed.id);
return Upd(updatedModel,
effects: snackbar.showUndoCmd<TodosMessage>(msg.removed.task,
() => UndoRemoveItem(TodoModel.fromEntity(msg.removed))));
}
return Upd(model);
}
TodosModel _updateTodoItem(TodosModel model, TodoModel updatedTodo) {
return model.rebuild(
(b) => b.items.map((x) => x.id == updatedTodo.id ? updatedTodo : x));
}
Cmd<TodosMessage> _saveTodosCmd(CmdRepository repo, TodosModel model) =>
repo.saveAllCmd(model.items.map((t) => t.toEntity()).toList());
| flutter_architecture_samples/mvu/lib/todos/state.dart/0 | {'file_path': 'flutter_architecture_samples/mvu/lib/todos/state.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1683} |
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.
import 'package:redux/redux.dart';
import 'package:redux_sample/actions/actions.dart';
import 'package:redux_sample/models/models.dart';
import 'package:redux_sample/selectors/selectors.dart';
import 'package:todos_repository_core/todos_repository_core.dart';
List<Middleware<AppState>> createStoreTodosMiddleware(
TodosRepository repository,
) {
final saveTodos = _createSaveTodos(repository);
final loadTodos = _createLoadTodos(repository);
return [
TypedMiddleware<AppState, LoadTodosAction>(loadTodos),
TypedMiddleware<AppState, AddTodoAction>(saveTodos),
TypedMiddleware<AppState, ClearCompletedAction>(saveTodos),
TypedMiddleware<AppState, ToggleAllAction>(saveTodos),
TypedMiddleware<AppState, UpdateTodoAction>(saveTodos),
TypedMiddleware<AppState, TodosLoadedAction>(saveTodos),
TypedMiddleware<AppState, DeleteTodoAction>(saveTodos),
];
}
Middleware<AppState> _createSaveTodos(TodosRepository repository) {
return (Store<AppState> store, action, NextDispatcher next) {
next(action);
repository.saveTodos(
todosSelector(store.state).map((todo) => todo.toEntity()).toList(),
);
};
}
Middleware<AppState> _createLoadTodos(TodosRepository repository) {
return (Store<AppState> store, action, NextDispatcher next) {
repository.loadTodos().then(
(todos) {
store.dispatch(
TodosLoadedAction(
todos.map(Todo.fromEntity).toList(),
),
);
},
).catchError((_) => store.dispatch(TodosNotLoadedAction()));
next(action);
};
}
| flutter_architecture_samples/redux/lib/middleware/store_todos_middleware.dart/0 | {'file_path': 'flutter_architecture_samples/redux/lib/middleware/store_todos_middleware.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 660} |
name: simple_blocs
description: The Business Logic Components for a Todo App - Simplfied
environment:
sdk: '>=2.0.0-dev.28.0 <3.0.0'
dependencies:
todos_repository_core:
path: ../todos_repository_core
rxdart: ^0.23.1
dev_dependencies:
test:
mockito:
| flutter_architecture_samples/simple_blocs/pubspec.yaml/0 | {'file_path': 'flutter_architecture_samples/simple_blocs/pubspec.yaml', 'repo_id': 'flutter_architecture_samples', 'token_count': 115} |
class ValidationException extends Error {
final String message;
ValidationException(this.message);
}
| flutter_architecture_samples/states_rebuilder/lib/domain/exceptions/validation_exception.dart/0 | {'file_path': 'flutter_architecture_samples/states_rebuilder/lib/domain/exceptions/validation_exception.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 26} |
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:todos_repository_core/todos_repository_core.dart';
/// Loads and saves a List of Todos using a text file stored on the device.
///
/// Note: This class has no direct dependencies on any Flutter dependencies.
/// Instead, the `getDirectory` method should be injected. This allows for
/// testing.
class FileStorage implements TodosRepository {
final String tag;
final Future<Directory> Function() getDirectory;
const FileStorage(
this.tag,
this.getDirectory,
);
@override
Future<List<TodoEntity>> loadTodos() async {
final file = await _getLocalFile();
final string = await file.readAsString();
final json = JsonDecoder().convert(string);
final todos = (json['todos'])
.map<TodoEntity>((todo) => TodoEntity.fromJson(todo))
.toList();
return todos;
}
@override
Future<File> saveTodos(List<TodoEntity> todos) async {
final file = await _getLocalFile();
return file.writeAsString(JsonEncoder().convert({
'todos': todos.map((todo) => todo.toJson()).toList(),
}));
}
Future<File> _getLocalFile() async {
final dir = await getDirectory();
return File('${dir.path}/ArchSampleStorage__$tag.json');
}
Future<FileSystemEntity> clean() async {
final file = await _getLocalFile();
return file.delete();
}
}
| flutter_architecture_samples/todos_repository_local_storage/lib/src/file_storage.dart/0 | {'file_path': 'flutter_architecture_samples/todos_repository_local_storage/lib/src/file_storage.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 535} |
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:todos_app_core/todos_app_core.dart';
import 'package:vanilla/localization.dart';
import 'package:vanilla/models.dart';
import 'package:vanilla/widgets/extra_actions_button.dart';
import 'package:vanilla/widgets/filter_button.dart';
import 'package:vanilla/widgets/stats_counter.dart';
import 'package:vanilla/widgets/todo_list.dart';
import 'package:vanilla/widgets/typedefs.dart';
class HomeScreen extends StatefulWidget {
final AppState appState;
final TodoAdder addTodo;
final TodoRemover removeTodo;
final TodoUpdater updateTodo;
final Function toggleAll;
final Function clearCompleted;
HomeScreen({
@required this.appState,
@required this.addTodo,
@required this.removeTodo,
@required this.updateTodo,
@required this.toggleAll,
@required this.clearCompleted,
Key key,
}) : super(key: ArchSampleKeys.homeScreen);
@override
State<StatefulWidget> createState() {
return HomeScreenState();
}
}
class HomeScreenState extends State<HomeScreen> {
VisibilityFilter activeFilter = VisibilityFilter.all;
AppTab activeTab = AppTab.todos;
void _updateVisibility(VisibilityFilter filter) {
setState(() {
activeFilter = filter;
});
}
void _updateTab(AppTab tab) {
setState(() {
activeTab = tab;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(VanillaLocalizations.of(context).appTitle),
actions: [
FilterButton(
isActive: activeTab == AppTab.todos,
activeFilter: activeFilter,
onSelected: _updateVisibility,
),
ExtraActionsButton(
allComplete: widget.appState.allComplete,
hasCompletedTodos: widget.appState.hasCompletedTodos,
onSelected: (action) {
if (action == ExtraAction.toggleAllComplete) {
widget.toggleAll();
} else if (action == ExtraAction.clearCompleted) {
widget.clearCompleted();
}
},
)
],
),
body: activeTab == AppTab.todos
? TodoList(
filteredTodos: widget.appState.filteredTodos(activeFilter),
loading: widget.appState.isLoading,
removeTodo: widget.removeTodo,
addTodo: widget.addTodo,
updateTodo: widget.updateTodo,
)
: StatsCounter(
numActive: widget.appState.numActive,
numCompleted: widget.appState.numCompleted,
),
floatingActionButton: FloatingActionButton(
key: ArchSampleKeys.addTodoFab,
onPressed: () {
Navigator.pushNamed(context, ArchSampleRoutes.addTodo);
},
child: Icon(Icons.add),
tooltip: ArchSampleLocalizations.of(context).addTodo,
),
bottomNavigationBar: BottomNavigationBar(
key: ArchSampleKeys.tabs,
currentIndex: AppTab.values.indexOf(activeTab),
onTap: (index) {
_updateTab(AppTab.values[index]);
},
items: AppTab.values.map((tab) {
return BottomNavigationBarItem(
icon: Icon(
tab == AppTab.todos ? Icons.list : Icons.show_chart,
key: tab == AppTab.stats
? ArchSampleKeys.statsTab
: ArchSampleKeys.todoTab,
),
title: Text(
tab == AppTab.stats
? ArchSampleLocalizations.of(context).stats
: ArchSampleLocalizations.of(context).todos,
),
);
}).toList(),
),
);
}
}
| flutter_architecture_samples/vanilla/lib/screens/home_screen.dart/0 | {'file_path': 'flutter_architecture_samples/vanilla/lib/screens/home_screen.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1734} |
class HttpResponse<T> {
T data;
bool isOffline;
HttpResponse({
required this.data,
this.isOffline = false,
});
}
| flutter_articles/lib/models/http_response.dart/0 | {'file_path': 'flutter_articles/lib/models/http_response.dart', 'repo_id': 'flutter_articles', 'token_count': 51} |
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_articles/presentation/shared/offline_banner.dart';
typedef HttpPageRequest<T> = Future<T> Function(bool forceRefresh);
class HttpPageWrapper<T> extends StatefulWidget {
final HttpPageRequest<T> dataRequest;
final Function contentBuilder;
final Widget? errorWidget;
final Widget? noDataWidget;
final Widget? loadingWidget;
const HttpPageWrapper({
Key? key,
required this.dataRequest,
required this.contentBuilder,
this.errorWidget,
this.noDataWidget,
this.loadingWidget,
}) : super(key: key);
@override
_HttpPageWrapperState createState() => _HttpPageWrapperState<T>();
}
class _HttpPageWrapperState<T> extends State<HttpPageWrapper> {
final StreamController<T> streamController = StreamController<T>();
Future<void> _getData({bool forceRefresh = false}) async {
try {
T data = await widget.dataRequest(forceRefresh);
streamController.add(data);
} catch (e) {
streamController.addError(e);
rethrow;
}
}
@override
void initState() {
_getData();
super.initState();
}
@override
Widget build(BuildContext context) {
return RefreshIndicator(
onRefresh: () => _getData(forceRefresh: true),
child: StreamBuilder<T>(
stream: streamController.stream,
builder: (BuildContext context, AsyncSnapshot<T> snapshot) {
if (snapshot.hasError) {
return buildErrorWidget();
} else {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return buildLoadingWidget();
case ConnectionState.active:
case ConnectionState.done:
if (!snapshot.hasData ||
(snapshot.data is List &&
(snapshot.data as List).isEmpty)) {
return buildNoDataWidget();
} else {
return Column(
children: [
OfflineBanner(
onRefresh: () => _getData(forceRefresh: true),
),
Expanded(
child: buildContentWidget(context, snapshot.data!)),
],
);
}
case ConnectionState.none:
default:
return buildNoDataWidget();
}
}
},
),
);
}
Widget buildContentWidget(BuildContext context, T data) {
return widget.contentBuilder(context, data);
}
Widget buildErrorWidget() {
return widget.errorWidget ??
const Center(child: Text('An Error Occurred!'));
}
Widget buildNoDataWidget() {
return widget.noDataWidget ?? const Center(child: Text('No Data'));
}
Widget buildLoadingWidget() {
return widget.loadingWidget ??
const Center(child: CircularProgressIndicator());
}
}
| flutter_articles/lib/presentation/shared/http_page_wrapper.dart/0 | {'file_path': 'flutter_articles/lib/presentation/shared/http_page_wrapper.dart', 'repo_id': 'flutter_articles', 'token_count': 1305} |
import 'package:flutter_articles/services/http/http_service.dart';
import 'package:flutter_articles/services/storage/storage_service.dart';
import 'package:get_it/get_it.dart';
import 'http/mock_dio_http_service.dart';
import 'storage/mock_hive_storage_service.dart';
final getMocks = GetIt.instance;
void setUpMockServiceLocator() {
getMocks.registerSingleton<StorageService>(MockHiveStorageService());
final StorageService storageService = getMocks<StorageService>();
getMocks.registerSingleton<HttpService>(MockDioHttpService(storageService));
}
Future resetMockServiceLocator() async {
await getMocks.reset();
}
| flutter_articles/test/services/mock_service_locator.dart/0 | {'file_path': 'flutter_articles/test/services/mock_service_locator.dart', 'repo_id': 'flutter_articles', 'token_count': 203} |
import 'package:cool_tool_bar/constants.dart';
import 'package:cool_tool_bar/models/toolbar_item_data.dart';
import 'package:flutter/material.dart';
class ToolbarItem extends StatelessWidget {
const ToolbarItem(
this.toolbarItem, {
required this.height,
required this.scrollScale,
this.isLongPressed = false,
this.gutter = 10,
Key? key,
}) : super(key: key);
final ToolbarItemData toolbarItem;
final double height;
final double scrollScale;
final bool isLongPressed;
final double gutter;
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.centerLeft,
child: SizedBox(
height: height + gutter,
child: Stack(
children: [
AnimatedScale(
scale: scrollScale,
duration: Constants.scrollScaleAnimationDuration,
curve: Constants.scrollScaleAnimationCurve,
child: AnimatedContainer(
duration: Constants.longPressAnimationDuration,
curve: Constants.longPressAnimationCurve,
height: height + (isLongPressed ? 10 : 0),
width: isLongPressed ? Constants.toolbarWidth * 2 : height,
decoration: BoxDecoration(
color: toolbarItem.color,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
blurRadius: 10,
color: Colors.black.withOpacity(0.1),
),
],
),
alignment: Alignment.center,
margin: EdgeInsets.only(
bottom: gutter,
left: isLongPressed ? Constants.itemsOffset : 0,
),
),
),
Positioned.fill(
child: AnimatedPadding(
duration: Constants.longPressAnimationDuration,
curve: Constants.longPressAnimationCurve,
padding: EdgeInsets.only(
bottom: gutter,
left: 12 + (isLongPressed ? Constants.itemsOffset : 0),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
AnimatedScale(
scale: scrollScale,
duration: Constants.scrollScaleAnimationDuration,
curve: Constants.scrollScaleAnimationCurve,
child: Icon(
toolbarItem.icon,
color: Colors.white,
),
),
const SizedBox(width: 12),
Expanded(
child: AnimatedOpacity(
duration: Constants.longPressAnimationDuration,
curve: Constants.longPressAnimationCurve,
opacity: isLongPressed ? 1 : 0,
child: Text(
toolbarItem.title,
style: const TextStyle(
fontSize: 18,
color: Colors.white,
),
maxLines: 1,
),
),
),
],
),
),
),
],
),
),
);
}
}
| flutter_cool_toolbar/lib/widgets/toolbar_item.dart/0 | {'file_path': 'flutter_cool_toolbar/lib/widgets/toolbar_item.dart', 'repo_id': 'flutter_cool_toolbar', 'token_count': 1961} |
name: flutter_flows
description: A sample Flutter project which demonstrates how to use flow_builder.
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
flow_builder: ^0.0.1-dev.13
flutter:
uses-material-design: true
| flutter_flows/pubspec.yaml/0 | {'file_path': 'flutter_flows/pubspec.yaml', 'repo_id': 'flutter_flows', 'token_count': 114} |
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter/services.dart';
class GaplessAudioLoop {
static const MethodChannel _channel =
const MethodChannel('gapless_audio_loop');
/// A reference to the loaded file.
String _loadedFile;
int _id;
double _volume = 1.0;
double get volume => _volume;
void setVolume(double volume) async {
_volume = volume;
if (_id != null) {
await _channel
.invokeMethod("setVolume", {'playerId': _id, "volume": _volume});
}
}
Future<ByteData> _fetchAsset(String fileName) async {
return await rootBundle.load('assets/$fileName');
}
Future<File> _fetchToMemory(String fileName) async {
final file = File('${(await getTemporaryDirectory()).path}/$fileName');
await file.create(recursive: true);
return await file
.writeAsBytes((await _fetchAsset(fileName)).buffer.asUint8List());
}
/// Load the [fileName] for playing
///
Future<void> loadAsset(String fileName) async {
if (_loadedFile != null) {
return _loadedFile;
}
final result = await _fetchToMemory(fileName);
_loadedFile = result.path;
}
void loadFile(String path) {
_loadedFile = path;
}
Future<void> play() async {
assert(_loadedFile != null, 'File is not loaded');
// Do nothing when it is already playing
if (_id == null) {
_id = await _channel
.invokeMethod("play", {'url': _loadedFile, 'volume': _volume});
}
}
Future<void> pause() async {
assert(_id != null, 'Loop is not playing');
await _channel.invokeMethod("pause", {'playerId': _id});
}
Future<void> resume() async {
assert(_loadedFile != null, 'File is not loaded');
assert(_id != null, 'Loop is not playing');
await _channel.invokeMethod("resume", {'playerId': _id});
}
Future<void> stop() async {
assert(_loadedFile != null, 'File is not loaded');
assert(_id != null, 'Loop is not playing');
await _channel.invokeMethod("stop", {'playerId': _id});
}
Future<void> seek(Duration duration) async {
assert(_loadedFile != null, 'File is not loaded');
assert(_id != null, 'Loop is not playing');
await _channel.invokeMethod(
"seek", {'playerId': _id, "position": duration.inMilliseconds});
}
bool isAssetLoaded() {
return _loadedFile != null;
}
}
| flutter_gapless_audio_loop/lib/gapless_audio_loop.dart/0 | {'file_path': 'flutter_gapless_audio_loop/lib/gapless_audio_loop.dart', 'repo_id': 'flutter_gapless_audio_loop', 'token_count': 873} |
import 'package:flutter/material.dart';
class MondrianCompositionData {
const MondrianCompositionData({
this.rectangles = const [],
this.lines = const [],
});
final List<List<Offset>> rectangles;
final List<List<Offset>> lines;
}
| flutter_generative_art/lib/models/mondrian_composition_data.dart/0 | {'file_path': 'flutter_generative_art/lib/models/mondrian_composition_data.dart', 'repo_id': 'flutter_generative_art', 'token_count': 82} |
import 'package:flutter/material.dart';
class RawRecursiveSquaresGrid extends StatelessWidget {
const RawRecursiveSquaresGrid({
super.key,
this.side = 80,
this.strokeWidth = 1.5,
this.gap = 10,
this.minSquareSideFraction = 0.2,
});
final double side;
final double strokeWidth;
final double gap;
final double minSquareSideFraction;
@override
Widget build(BuildContext context) {
return ColoredBox(
color: Colors.white,
child: SizedBox.expand(
child: CustomPaint(
painter: _RecursiveSquaresCustomPainter(
sideLength: side,
strokeWidth: strokeWidth,
minSquareSideFraction: minSquareSideFraction,
gap: gap,
),
),
),
);
}
}
class _RecursiveSquaresCustomPainter extends CustomPainter {
_RecursiveSquaresCustomPainter({
this.sideLength = 80,
this.strokeWidth = 2,
this.gap = 10,
this.minSquareSideFraction = 0.2,
}) : minSideLength = sideLength * minSquareSideFraction;
final double sideLength;
final double strokeWidth;
final double gap;
final double minSideLength;
final double minSquareSideFraction;
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..style = PaintingStyle.stroke
..strokeWidth = strokeWidth;
// Calculate the number of squares that can fit on the horizontal axis
final xCount = ((size.width + gap) / (sideLength + gap)).floor();
// Calculate the number of squares that can fit on the vertical axis
final yCount = ((size.height + gap) / (sideLength + gap)).floor();
// Calculate the size of the grid of squares
final contentSize = Size(
(xCount * sideLength) + ((xCount - 1) * gap),
(yCount * sideLength) + ((yCount - 1) * gap),
);
// Calculate the offset from which we should start painting
// the grid so that it is eventually centered
final offset = Offset(
(size.width - contentSize.width) / 2,
(size.height - contentSize.height) / 2,
);
final totalCount = xCount * yCount;
canvas.save();
canvas.translate(offset.dx, offset.dy);
for (int index = 0; index < totalCount; index++) {
int i = index ~/ yCount;
int j = index % yCount;
// Recursively draw squares
drawNestedSquares(
canvas,
Offset(
(i * (sideLength + gap)),
(j * (sideLength + gap)),
),
sideLength,
paint,
);
}
canvas.restore();
}
void drawNestedSquares(
Canvas canvas,
Offset start,
double sideLength,
Paint paint,
) {
// Recursively draw squares until the side of the square
// reaches the minimum defined by the `minSideLength` input
if (sideLength < minSideLength) return;
canvas.drawRect(
Rect.fromLTWH(
start.dx,
start.dy,
sideLength,
sideLength,
),
paint,
);
// calculate the side length for the next square
final nextSideLength = sideLength * 0.8;
final nextStart = Offset(
start.dx + sideLength / 2 - nextSideLength / 2,
start.dy + sideLength / 2 - nextSideLength / 2,
);
// recursive call with the next side length and starting point
drawNestedSquares(canvas, nextStart, nextSideLength, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
| flutter_generative_art/lib/vera_molnar/raw_recursive_squares_grid.dart/0 | {'file_path': 'flutter_generative_art/lib/vera_molnar/raw_recursive_squares_grid.dart', 'repo_id': 'flutter_generative_art', 'token_count': 1313} |
// ignore_for_file: omit_local_variable_types
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// This example demonstrates how to create a custom Hook.
class CustomHookExample extends HookWidget {
@override
Widget build(BuildContext context) {
// Consume the custom hook. It returns a StreamController that we can use
// within this Widget.
//
// To update the stored value, `add` data to the StreamController. To get
// the latest value from the StreamController, listen to the Stream with
// the useStream hook.
// ignore: close_sinks
final StreamController<int> countController =
_useLocalStorageInt('counter');
return Scaffold(
appBar: AppBar(
title: const Text('Custom Hook example'),
),
body: Center(
// Use a HookBuilder Widget to listen to the Stream. This ensures a
// smaller portion of the Widget tree is rebuilt when the stream emits a
// new value
child: HookBuilder(
builder: (context) {
final AsyncSnapshot<int> count =
useStream(countController.stream, initialData: 0);
return !count.hasData
? const CircularProgressIndicator()
: GestureDetector(
onTap: () => countController.add(count.requireData + 1),
child: Text('You tapped me ${count.data} times.'),
);
},
),
),
);
}
}
// A custom hook that will read and write values to local storage using the
// SharedPreferences package.
StreamController<int> _useLocalStorageInt(
String key, {
int defaultValue = 0,
}) {
// Custom hooks can use additional hooks internally!
final controller = useStreamController<int>(keys: [key]);
// Pass a callback to the useEffect hook. This function should be called on
// first build and every time the controller or key changes
useEffect(
() {
// Listen to the StreamController, and when a value is added, store it
// using SharedPrefs.
final sub = controller.stream.listen((data) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt(key, data);
});
// Unsubscribe when the widget is disposed
// or on controller/key change
return sub.cancel;
},
// Pass the controller and key to the useEffect hook. This will ensure the
// useEffect hook is only called the first build or when one of the the
// values changes.
[controller, key],
);
// Load the initial value from local storage and add it as the initial value
// to the controller
useEffect(
() {
SharedPreferences.getInstance().then<void>((prefs) async {
final int? valueFromStorage = prefs.getInt(key);
controller.add(valueFromStorage ?? defaultValue);
}).catchError(controller.addError);
return null;
},
// Pass the controller and key to the useEffect hook. This will ensure the
// useEffect hook is only called the first build or when one of the the
// values changes.
[controller, key],
);
// Finally, return the StreamController. This allows users to add values from
// the Widget layer and listen to the stream for changes.
return controller;
}
| flutter_hooks/packages/flutter_hooks/example/lib/use_effect.dart/0 | {'file_path': 'flutter_hooks/packages/flutter_hooks/example/lib/use_effect.dart', 'repo_id': 'flutter_hooks', 'token_count': 1182} |
part of 'hooks.dart';
/// Subscribes to a [ValueListenable] and returns its value.
///
/// See also:
/// * [ValueListenable], the created object
/// * [useListenable]
T useValueListenable<T>(ValueListenable<T> valueListenable) {
use(_UseValueListenableHook(valueListenable));
return valueListenable.value;
}
class _UseValueListenableHook extends _ListenableHook {
const _UseValueListenableHook(ValueListenable<Object?> animation)
: super(animation);
@override
_UseValueListenableStateHook createState() {
return _UseValueListenableStateHook();
}
}
class _UseValueListenableStateHook extends _ListenableStateHook {
@override
String get debugLabel => 'useValueListenable';
@override
Object? get debugValue => (hook.listenable as ValueListenable?)?.value;
}
/// Subscribes to a [Listenable] and marks the widget as needing build
/// whenever the listener is called.
///
/// See also:
/// * [Listenable]
/// * [useValueListenable], [useAnimation]
T useListenable<T extends Listenable?>(T listenable) {
use(_ListenableHook(listenable));
return listenable;
}
class _ListenableHook extends Hook<void> {
const _ListenableHook(this.listenable);
final Listenable? listenable;
@override
_ListenableStateHook createState() => _ListenableStateHook();
}
class _ListenableStateHook extends HookState<void, _ListenableHook> {
@override
void initHook() {
super.initHook();
hook.listenable?.addListener(_listener);
}
@override
void didUpdateHook(_ListenableHook oldHook) {
super.didUpdateHook(oldHook);
if (hook.listenable != oldHook.listenable) {
oldHook.listenable?.removeListener(_listener);
hook.listenable?.addListener(_listener);
}
}
@override
void build(BuildContext context) {}
void _listener() {
setState(() {});
}
@override
void dispose() {
hook.listenable?.removeListener(_listener);
}
@override
String get debugLabel => 'useListenable';
@override
Object? get debugValue => hook.listenable;
}
/// Creates a [ValueNotifier] that is automatically disposed.
///
/// As opposed to `useState`, this hook does not subscribe to [ValueNotifier].
/// This allows a more granular rebuild.
///
/// See also:
/// * [ValueNotifier]
/// * [useValueListenable]
ValueNotifier<T> useValueNotifier<T>(T initialData, [List<Object?>? keys]) {
return use(
_ValueNotifierHook(
initialData: initialData,
keys: keys,
),
);
}
class _ValueNotifierHook<T> extends Hook<ValueNotifier<T>> {
const _ValueNotifierHook({List<Object?>? keys, required this.initialData})
: super(keys: keys);
final T initialData;
@override
_UseValueNotifierHookState<T> createState() =>
_UseValueNotifierHookState<T>();
}
class _UseValueNotifierHookState<T>
extends HookState<ValueNotifier<T>, _ValueNotifierHook<T>> {
late final notifier = ValueNotifier<T>(hook.initialData);
@override
ValueNotifier<T> build(BuildContext context) {
return notifier;
}
@override
void dispose() {
notifier.dispose();
}
@override
String get debugLabel => 'useValueNotifier';
}
| flutter_hooks/packages/flutter_hooks/lib/src/listenable.dart/0 | {'file_path': 'flutter_hooks/packages/flutter_hooks/lib/src/listenable.dart', 'repo_id': 'flutter_hooks', 'token_count': 1075} |
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'mock.dart';
void main() {
testWidgets('creates a focus scope node and disposes it', (tester) async {
late FocusScopeNode focusScopeNode;
await tester.pumpWidget(
HookBuilder(builder: (_) {
focusScopeNode = useFocusScopeNode();
return Container();
}),
);
expect(focusScopeNode, isA<FocusScopeNode>());
// ignore: invalid_use_of_protected_member
expect(focusScopeNode.hasListeners, isFalse);
final previousValue = focusScopeNode;
await tester.pumpWidget(
HookBuilder(builder: (_) {
focusScopeNode = useFocusScopeNode();
return Container();
}),
);
expect(previousValue, focusScopeNode);
// ignore: invalid_use_of_protected_member
expect(focusScopeNode.hasListeners, isFalse);
await tester.pumpWidget(Container());
expect(
() => focusScopeNode.dispose(),
throwsAssertionError,
);
});
testWidgets('debugFillProperties', (tester) async {
await tester.pumpWidget(
HookBuilder(builder: (context) {
useFocusScopeNode();
return const SizedBox();
}),
);
final element = tester.element(find.byType(HookBuilder));
expect(
element
.toDiagnosticsNode(style: DiagnosticsTreeStyle.offstage)
.toStringDeep(),
equalsIgnoringHashCodes(
'HookBuilder\n'
' │ useFocusScopeNode: FocusScopeNode#00000\n'
' └SizedBox(renderObject: RenderConstrainedBox#00000)\n',
),
);
});
testWidgets('default values matches with FocusScopeNode', (tester) async {
final official = FocusScopeNode();
late FocusScopeNode focusScopeNode;
await tester.pumpWidget(
HookBuilder(builder: (_) {
focusScopeNode = useFocusScopeNode();
return Container();
}),
);
expect(focusScopeNode.debugLabel, official.debugLabel);
expect(focusScopeNode.onKey, official.onKey);
expect(focusScopeNode.skipTraversal, official.skipTraversal);
expect(focusScopeNode.canRequestFocus, official.canRequestFocus);
});
testWidgets('has all the FocusScopeNode parameters', (tester) async {
KeyEventResult onKey(FocusNode node, RawKeyEvent event) =>
KeyEventResult.ignored;
KeyEventResult onKeyEvent(FocusNode node, KeyEvent event) =>
KeyEventResult.ignored;
late FocusScopeNode focusScopeNode;
await tester.pumpWidget(
HookBuilder(builder: (_) {
focusScopeNode = useFocusScopeNode(
debugLabel: 'Foo',
onKey: onKey,
onKeyEvent: onKeyEvent,
skipTraversal: true,
canRequestFocus: false,
);
return Container();
}),
);
expect(focusScopeNode.debugLabel, 'Foo');
expect(focusScopeNode.onKey, onKey);
expect(focusScopeNode.onKeyEvent, onKeyEvent);
expect(focusScopeNode.skipTraversal, true);
expect(focusScopeNode.canRequestFocus, false);
});
testWidgets('handles parameter change', (tester) async {
KeyEventResult onKey(FocusNode node, RawKeyEvent event) =>
KeyEventResult.ignored;
KeyEventResult onKey2(FocusNode node, RawKeyEvent event) =>
KeyEventResult.ignored;
KeyEventResult onKeyEvent(FocusNode node, KeyEvent event) =>
KeyEventResult.ignored;
KeyEventResult onKeyEvent2(FocusNode node, KeyEvent event) =>
KeyEventResult.ignored;
late FocusScopeNode focusScopeNode;
await tester.pumpWidget(
HookBuilder(builder: (_) {
focusScopeNode = useFocusScopeNode(
debugLabel: 'Foo',
onKey: onKey,
onKeyEvent: onKeyEvent,
skipTraversal: true,
canRequestFocus: false,
);
return Container();
}),
);
await tester.pumpWidget(
HookBuilder(builder: (_) {
focusScopeNode = useFocusScopeNode(
debugLabel: 'Bar',
onKey: onKey2,
onKeyEvent: onKeyEvent2,
);
return Container();
}),
);
expect(focusScopeNode.onKey, onKey2);
expect(focusScopeNode.onKeyEvent, onKeyEvent2);
expect(focusScopeNode.debugLabel, 'Bar');
expect(focusScopeNode.skipTraversal, false);
expect(focusScopeNode.canRequestFocus, true);
});
}
| flutter_hooks/packages/flutter_hooks/test/use_focus_scope_node_test.dart/0 | {'file_path': 'flutter_hooks/packages/flutter_hooks/test/use_focus_scope_node_test.dart', 'repo_id': 'flutter_hooks', 'token_count': 1745} |
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_hooks/src/framework.dart';
import 'package:flutter_hooks/src/hooks.dart';
import 'mock.dart';
void main() {
testWidgets('debugFillProperties', (tester) async {
await tester.pumpWidget(
HookBuilder(builder: (context) {
useTabController(initialLength: 4);
return const SizedBox();
}),
);
await tester.pump();
final element = tester.element(find.byType(HookBuilder));
expect(
element
.toDiagnosticsNode(style: DiagnosticsTreeStyle.offstage)
.toStringDeep(),
equalsIgnoringHashCodes(
'HookBuilder\n'
' │ useSingleTickerProvider\n'
" │ useTabController: Instance of 'TabController'\n"
' └SizedBox(renderObject: RenderConstrainedBox#00000)\n',
),
);
});
group('useTabController', () {
testWidgets('initial values matches with real constructor', (tester) async {
late TabController controller;
late TabController controller2;
await tester.pumpWidget(
HookBuilder(builder: (context) {
final vsync = useSingleTickerProvider();
controller2 = TabController(length: 4, vsync: vsync);
controller = useTabController(initialLength: 4);
return Container();
}),
);
expect(controller.index, controller2.index);
});
testWidgets("returns a TabController that doesn't change", (tester) async {
late TabController controller;
late TabController controller2;
await tester.pumpWidget(
HookBuilder(builder: (context) {
controller = useTabController(initialLength: 1);
return Container();
}),
);
expect(controller, isA<TabController>());
await tester.pumpWidget(
HookBuilder(builder: (context) {
controller2 = useTabController(initialLength: 1);
return Container();
}),
);
expect(identical(controller, controller2), isTrue);
});
testWidgets('changing length is no-op', (tester) async {
late TabController controller;
await tester.pumpWidget(
HookBuilder(builder: (context) {
controller = useTabController(initialLength: 1);
return Container();
}),
);
expect(controller.length, 1);
await tester.pumpWidget(
HookBuilder(builder: (context) {
controller = useTabController(initialLength: 2);
return Container();
}),
);
expect(controller.length, 1);
});
testWidgets('passes hook parameters to the TabController', (tester) async {
late TabController controller;
await tester.pumpWidget(
HookBuilder(
builder: (context) {
controller = useTabController(initialIndex: 2, initialLength: 4);
return Container();
},
),
);
expect(controller.index, 2);
expect(controller.length, 4);
});
testWidgets('allows passing custom vsync', (tester) async {
final vsync = TickerProviderMock();
final ticker = Ticker((_) {});
when(vsync.createTicker((_) {})).thenReturn(ticker);
await tester.pumpWidget(
HookBuilder(
builder: (context) {
useTabController(initialLength: 1, vsync: vsync);
return Container();
},
),
);
verify(vsync.createTicker((_) {})).called(1);
verifyNoMoreInteractions(vsync);
await tester.pumpWidget(
HookBuilder(
builder: (context) {
useTabController(initialLength: 1, vsync: vsync);
return Container();
},
),
);
verifyNoMoreInteractions(vsync);
ticker.dispose();
});
});
}
class TickerProviderMock extends Mock implements TickerProvider {
@override
Ticker createTicker(TickerCallback onTick) => super.noSuchMethod(
Invocation.getter(#createTicker),
returnValue: Ticker(onTick),
) as Ticker;
}
| flutter_hooks/packages/flutter_hooks/test/use_tab_controller_test.dart/0 | {'file_path': 'flutter_hooks/packages/flutter_hooks/test/use_tab_controller_test.dart', 'repo_id': 'flutter_hooks', 'token_count': 1717} |
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:github_repository/github_repository.dart';
import 'package:flutter_hub/github_search_bloc/bloc.dart';
import 'package:flutter_hub/components/components.dart';
class ProfileSearch extends StatefulWidget {
@override
_ProfileSearchState createState() => _ProfileSearchState();
}
class _ProfileSearchState extends State<ProfileSearch>
with AutomaticKeepAliveClientMixin {
GithubSearchBloc _searchBloc;
@override
void initState() {
super.initState();
_searchBloc = BlocProvider.of<GithubSearchBloc>(context);
_searchBloc.dispatch(FetchInitialProfiles());
}
@override
Widget build(BuildContext context) {
super.build(context);
return Column(
children: <Widget>[
SearchBar(
hintText: 'Search for Flutter developer profiles',
onChanged: (text) {
_searchBloc.dispatch(
ProfileTextChanged(
text: text,
),
);
},
onClear: () {
_searchBloc.dispatch(ProfileTextChanged(text: ''));
},
),
_SearchBody()
],
);
}
@override
bool get wantKeepAlive => true;
}
class _SearchBody extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocBuilder<GithubSearchEvent, GithubSearchState>(
bloc: BlocProvider.of<GithubSearchBloc>(context),
builder: (BuildContext context, GithubSearchState state) {
if (state is SearchStateLoading) {
return CircularProgressIndicator();
}
if (state is SearchStateError) {
return Text(state.error);
}
if (state is SearchStateSuccess) {
return state.items.isEmpty
? Text('No Results')
: Expanded(child: _SearchResults(items: state.items));
}
},
);
}
}
class _SearchResults extends StatelessWidget {
final List<SearchResultItem> items;
const _SearchResults({Key key, this.items}) : super(key: key);
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return _SearchResultItem(item: items[index]);
},
);
}
}
class _SearchResultItem extends StatelessWidget {
final SearchResultItem item;
const _SearchResultItem({Key key, @required this.item}) : super(key: key);
@override
Widget build(BuildContext context) {
return ListTile(
leading: CircleAvatar(
child: Image.network(item.owner.avatarUrl),
),
title: Text(
item.owner.login,
style: TextStyle(
fontWeight: FontWeight.bold,
color: Theme.of(context).primaryColor,
),
),
onTap: () async {
if (await canLaunch(item.owner.htmlUrl)) {
await launch(item.owner.htmlUrl);
}
},
);
}
}
| flutter_hub/lib/profile_search/profile_search_screen.dart/0 | {'file_path': 'flutter_hub/lib/profile_search/profile_search_screen.dart', 'repo_id': 'flutter_hub', 'token_count': 1260} |
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:reddit_repository/reddit_repository.dart';
class RedditClient {
final String baseUrl;
final http.Client httpClient;
RedditClient({
http.Client httpClient,
this.baseUrl = "https://www.reddit.com/r/flutterdev/hot/.json",
}) : this.httpClient = httpClient ?? http.Client();
Future<SearchResult> getArticles(int count) async {
print('GET $baseUrl?count=$count');
final response = await httpClient.get(Uri.parse("$baseUrl?count=$count"));
final results = json.decode(response.body);
if (response.statusCode == 200) {
return SearchResult.fromJson(results);
} else {
throw SearchResultError();
}
}
}
| flutter_hub/reddit_repository/lib/src/reddit_client.dart/0 | {'file_path': 'flutter_hub/reddit_repository/lib/src/reddit_client.dart', 'repo_id': 'flutter_hub', 'token_count': 267} |
import 'package:example/content.dart';
import 'package:flutter/material.dart';
import 'sample.dart';
import 'sample2.dart';
import 'sample3.dart';
import 'sample4.dart';
import 'sample5.dart';
// Application entry-point
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);
_openWidget(BuildContext context, Widget widget) =>
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => widget),
);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
backgroundColor: Colors.amber,
body: Builder(
builder: (myContext) => Center(
child: Padding(
padding: const EdgeInsets.all(18.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ElevatedButton(
child: Text("Full Screen form"),
onPressed: () => _openWidget(
myContext,
ScaffoldTest(),
),
),
const SizedBox(
height: 25,
),
ElevatedButton(
child: Text("Dialog form"),
onPressed: () => _openWidget(
myContext,
DialogTest(),
),
),
const SizedBox(
height: 25,
),
ElevatedButton(
child: Text("Custom Sample 1"),
onPressed: () => _openWidget(
myContext,
Sample(),
),
),
const SizedBox(
height: 25,
),
ElevatedButton(
child: Text("Custom Sample 2"),
onPressed: () => _openWidget(
myContext,
Sample2(),
),
),
const SizedBox(
height: 25,
),
ElevatedButton(
child: Text("Custom Sample 3"),
onPressed: () => _openWidget(
myContext,
Sample3(),
),
),
const SizedBox(
height: 25,
),
ElevatedButton(
child: Text("Custom Sample 4"),
onPressed: () => _openWidget(
myContext,
Sample4(),
),
),
const SizedBox(
height: 25,
),
ElevatedButton(
child: Text("Custom Sample 5"),
onPressed: () => _openWidget(
myContext,
Sample5(),
),
),
],
),
),
),
),
),
);
}
}
/// Displays our [TextField]s in a [Scaffold] with a [FormKeyboardActions].
class ScaffoldTest extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Keyboard Actions Sample"),
),
body: Content(),
);
}
}
/// Displays our [FormKeyboardActions] nested in a [AlertDialog].
class DialogTest extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Keyboard Actions Sample"),
),
body: Center(
child: TextButton(
child: Text('Launch dialog'),
onPressed: () => _launchInDialog(context),
),
),
);
}
void _launchInDialog(BuildContext context) async {
final height = MediaQuery.of(context).size.height / 3;
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Dialog test'),
content: SizedBox(
height: height,
child: Content(
isDialog: true,
),
),
actions: [
TextButton(
child: Text('Ok'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
| flutter_keyboard_actions/example/lib/main.dart/0 | {'file_path': 'flutter_keyboard_actions/example/lib/main.dart', 'repo_id': 'flutter_keyboard_actions', 'token_count': 2736} |
import 'package:flutter/material.dart';
import 'dart:math' as math;
class CustomTween extends Tween<double> {
CustomTween({
double? begin,
double? end,
required this.delay,
}) : super(begin: begin, end: end);
final double delay;
@override
double lerp(double t) => super.lerp(math.sqrt(t - delay) * math.pi) / 2;
@override
double evaluate(Animation<double> animation) => lerp(animation.value);
}
| flutter_loadkit/lib/src/custom_tweens/custom_tween.dart/0 | {'file_path': 'flutter_loadkit/lib/src/custom_tweens/custom_tween.dart', 'repo_id': 'flutter_loadkit', 'token_count': 154} |
import 'package:flutter/material.dart';
import 'package:flutter_playlist_animation/not-animated/utils/library_data.dart';
import 'package:flutter_playlist_animation/not-animated/widgets/image_wrapper.dart';
import 'package:flutter_playlist_animation/not-animated/widgets/song_action_buttons.dart';
import 'package:flutter_playlist_animation/not-animated/widgets/song_list_item.dart';
class PlaylistPage extends StatefulWidget {
const PlaylistPage({
super.key,
required this.image,
});
final String image;
@override
State<PlaylistPage> createState() => _PlaylistPageState();
}
class _PlaylistPageState extends State<PlaylistPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
AppBar(),
Expanded(
child: CustomScrollView(
slivers: [
SliverAppBar(
expandedHeight: 240,
automaticallyImplyLeading: false,
floating: true,
pinned: true,
flexibleSpace: Container(
margin: const EdgeInsets.only(bottom: 20),
child: Center(
child: ImageWrapper(image: widget.image),
),
),
),
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 20),
sliver: SliverToBoxAdapter(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Center(
child: Text(
'Acoustic',
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w700,
),
),
),
const SizedBox(height: 20),
const SongActionButtons(),
const SizedBox(height: 20),
const Text(
'Upcoming songs',
style: TextStyle(fontSize: 22),
),
ListView.builder(
shrinkWrap: true,
padding: EdgeInsets.only(
top: 10,
bottom: MediaQuery.of(context).padding.bottom + 20,
),
physics: const NeverScrollableScrollPhysics(),
itemCount: LibraryData.playlistImages.length,
itemBuilder: (context, index) => SongListItem(
image: LibraryData.playlistImages[index],
),
),
],
),
),
),
],
),
)
],
),
);
}
}
| flutter_playlist_animation/lib/not-animated/pages/playlist_page.dart/0 | {'file_path': 'flutter_playlist_animation/lib/not-animated/pages/playlist_page.dart', 'repo_id': 'flutter_playlist_animation', 'token_count': 1816} |
library flutter_ravepay;
import 'dart:async' show Future;
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_ravepay/src/config.dart';
import 'package:flutter_ravepay/src/result.dart';
export 'src/card.dart';
export 'src/config.dart';
export 'src/meta.dart';
export 'src/result.dart';
class Ravepay {
BuildContext context;
final String _channelName = 'ng.i.handikraft/flutter_ravepay';
Ravepay(this.context);
Future<RavepayResult> chargeCard(RavepayConfig config) async {
final bool isIos = Theme.of(context).platform == TargetPlatform.iOS;
final MethodChannel _channel = new MethodChannel(_channelName);
Map result;
try {
result = await _channel.invokeMethod('chargeCard', config.toMap());
// print(result);
} on PlatformException {
result = <String, String>{"status": "CANCELLED"};
}
return new RavepayResult(
result["status"],
result["payload"] != null
? (isIos ? result["payload"] : json.decode(result["payload"]))
: null,
);
}
static Ravepay of(BuildContext context) {
return new Ravepay(context);
}
}
| flutter_ravepay/lib/flutter_ravepay.dart/0 | {'file_path': 'flutter_ravepay/lib/flutter_ravepay.dart', 'repo_id': 'flutter_ravepay', 'token_count': 455} |
import 'dart:math' as math;
import 'package:flutter/widgets.dart';
class SpinKitDualRing extends StatefulWidget {
const SpinKitDualRing({
Key? key,
required this.color,
this.lineWidth = 7.0,
this.size = 50.0,
this.duration = const Duration(milliseconds: 1200),
this.controller,
}) : super(key: key);
final Color color;
final double lineWidth;
final double size;
final Duration duration;
final AnimationController? controller;
@override
State<SpinKitDualRing> createState() => _SpinKitDualRingState();
}
class _SpinKitDualRingState extends State<SpinKitDualRing> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = (widget.controller ?? AnimationController(vsync: this, duration: widget.duration))
..addListener(() {
if (mounted) {
setState(() {});
}
})
..repeat();
_animation = Tween(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: _controller,
curve: const Interval(0.0, 1.0, curve: Curves.linear),
),
);
}
@override
void dispose() {
if (widget.controller == null) {
_controller.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Transform(
transform: Matrix4.identity()..rotateZ((_animation.value) * math.pi * 2),
alignment: FractionalOffset.center,
child: CustomPaint(
painter: _DualRingPainter(
angle: 90,
paintWidth: widget.lineWidth,
color: widget.color,
),
child: SizedBox.fromSize(size: Size.square(widget.size)),
),
),
);
}
}
class _DualRingPainter extends CustomPainter {
_DualRingPainter({
required this.angle,
required double paintWidth,
required Color color,
}) : ringPaint = Paint()
..color = color
..strokeWidth = paintWidth
..style = PaintingStyle.stroke;
final Paint ringPaint;
final double angle;
@override
void paint(Canvas canvas, Size size) {
final rect = Rect.fromPoints(Offset.zero, Offset(size.width, size.height));
canvas.drawArc(rect, 0.0, getRadian(angle), false, ringPaint);
canvas.drawArc(rect, getRadian(180.0), getRadian(angle), false, ringPaint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => true;
double getRadian(double angle) => math.pi / 180 * angle;
}
| flutter_spinkit/lib/src/dual_ring.dart/0 | {'file_path': 'flutter_spinkit/lib/src/dual_ring.dart', 'repo_id': 'flutter_spinkit', 'token_count': 994} |
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_test/flutter_test.dart';
import 'helpers.dart';
void main() {
group('Circle', () {
testWidgets(
'needs either color or itemBuilder',
(WidgetTester tester) async {
expect(() => SpinKitCircle(), throwsAssertionError);
expect(
() => SpinKitCircle(color: Colors.white, itemBuilder: fakeBoxBuilder),
throwsAssertionError,
);
},
);
testWidgets('needs color to be non-null', (WidgetTester tester) async {
expect(() => SpinKitCircle(color: null), throwsAssertionError);
});
testWidgets(
'needs itemBuilder to be non-null',
(WidgetTester tester) async {
expect(() => SpinKitCircle(itemBuilder: null), throwsAssertionError);
},
);
testWidgets('works with color', (WidgetTester tester) async {
await tester.pumpWidget(
createMaterialApp(const SpinKitCircle(color: Colors.white)),
);
expect(find.byType(SpinKitCircle), findsOneWidget);
expect(find.byType(DecoratedBox), findsWidgets);
tester.verifyTickersWereDisposed();
});
testWidgets('works with itemBuilder', (WidgetTester tester) async {
await tester.pumpWidget(
createMaterialApp(const SpinKitCircle(itemBuilder: fakeBoxBuilder)),
);
expect(find.byType(SpinKitCircle), findsOneWidget);
expect(find.byType(FakeBox), findsWidgets);
tester.verifyTickersWereDisposed();
});
testWidgets('works without Material', (WidgetTester tester) async {
await tester.pumpWidget(
createWidgetsApp(const SpinKitCircle(color: Colors.white)),
);
expect(find.byType(SpinKitCircle), findsOneWidget);
expect(find.byType(DecoratedBox), findsWidgets);
tester.verifyTickersWereDisposed();
});
});
}
| flutter_spinkit/test/circle_test.dart/0 | {'file_path': 'flutter_spinkit/test/circle_test.dart', 'repo_id': 'flutter_spinkit', 'token_count': 764} |
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_test/flutter_test.dart';
import 'helpers.dart';
void main() {
group('PulsingGrid', () {
testWidgets(
'needs either color or itemBuilder',
(WidgetTester tester) async {
expect(() => SpinKitPulsingGrid(), throwsAssertionError);
expect(
() => SpinKitPulsingGrid(
color: Colors.white,
itemBuilder: fakeBoxBuilder,
),
throwsAssertionError,
);
},
);
testWidgets('needs color to be non-null', (WidgetTester tester) async {
expect(() => SpinKitPulsingGrid(color: null), throwsAssertionError);
});
testWidgets(
'needs itemBuilder to be non-null',
(WidgetTester tester) async {
expect(
() => SpinKitPulsingGrid(itemBuilder: null),
throwsAssertionError,
);
},
);
testWidgets('works with color', (WidgetTester tester) async {
await tester.pumpWidget(
createMaterialApp(const SpinKitPulsingGrid(color: Colors.white)),
);
expect(find.byType(SpinKitPulsingGrid), findsOneWidget);
expect(find.byType(DecoratedBox), findsWidgets);
tester.verifyTickersWereDisposed();
});
testWidgets('works with itemBuilder', (WidgetTester tester) async {
await tester.pumpWidget(
createMaterialApp(
const SpinKitPulsingGrid(itemBuilder: fakeBoxBuilder),
),
);
expect(find.byType(SpinKitPulsingGrid), findsOneWidget);
expect(find.byType(FakeBox), findsWidgets);
tester.verifyTickersWereDisposed();
});
testWidgets('works without Material', (WidgetTester tester) async {
await tester.pumpWidget(
createWidgetsApp(const SpinKitPulsingGrid(color: Colors.white)),
);
expect(find.byType(SpinKitPulsingGrid), findsOneWidget);
expect(find.byType(DecoratedBox), findsWidgets);
tester.verifyTickersWereDisposed();
});
});
}
| flutter_spinkit/test/pulsing_grid_test.dart/0 | {'file_path': 'flutter_spinkit/test/pulsing_grid_test.dart', 'repo_id': 'flutter_spinkit', 'token_count': 869} |
part of 'rx.dart';
/// {@template rx_notifier}
/// An abstract base class for creating reactive notifiers that manage
/// a state of type `T`.
///
/// The `RxNotifier` class provides a foundation for creating reactive notifiers
/// that encapsulate a piece of immutable state and notify their listeners
/// when the state changes. Subclasses of `RxNotifier` must override the
/// `watch` method to provide the initial state and implement the logic
/// for updating the state.
///
/// Example usage:
///
/// ```dart
/// class CounterNotifier extends RxNotifier<int> {
/// @override
/// int watch() {
/// return 0; // Initial state
/// }
///
/// void increment() {
/// state++; // Update the state
/// }
/// }
///
/// final counter = CounterNotifier();
///
/// // Adding a listener to the notifier
/// counter.addListener(() {
/// print('Counter changed: ${counter.state}');
/// });
///
/// // Updating the state
/// counter.increment(); // This will trigger the listener and print the updated state.
/// ```
///
/// It is best used for global state i.e state used in multiple controllers
/// but it could also be used for a single controller to abstract a
/// state and its events e.g if a state has a lot events, rather than
/// complicating your controller, you could use an RxNotifier for that singular
/// state instead.
///
/// **Note:** When using the RxNotifier class, it is important to call the
/// `dispose()` method on the object when it is no longer needed to
/// prevent memory leaks.
/// This can be done using the onDisable method of your controller.
/// {@endtemplate}
abstract class RxNotifier<T> extends Rx {
/// {@macro rx_notifier}
RxNotifier() {
if (kFlutterMemoryAllocationsEnabled && !_creationDispatched) {
MemoryAllocations.instance.dispatchObjectCreated(
library: 'package:flutter/foundation.dart',
className: '$RxNotifier',
object: this,
);
_creationDispatched = true;
}
_state = watch();
}
late T _state;
/// Retrieves the initial state for the notifier.
///
/// Subclasses must override this method to provide the initial state for
/// the notifier. The initial state is returned and used as the current state
/// when the notifier is created.
///
/// Example:
///
/// ```dart
/// @override
/// int watch() {
/// return 0; // Initial state
/// }
/// ```
@protected
T watch();
/// The current state of the notifier.
T get state {
RxListener._read(this);
return _state;
}
/// Sets the new state for the notifier.
///
/// The `state` argument represents the new state value for the notifier.
/// If the new state is different from the current state, the notifier will
/// update its state and notify its listeners.
///
/// Example:
///
/// ```dart
/// void increment() {
/// state++; // Update the state
/// }
/// ```
@protected
@visibleForTesting
set state(T state) {
if ('$_state' == '$state') return;
_state = state;
_notifyListeners();
}
@override
String toString() => '$runtimeType($state)';
}
| flutter_super/lib/src/rx/rx_notifier.dart/0 | {'file_path': 'flutter_super/lib/src/rx/rx_notifier.dart', 'repo_id': 'flutter_super', 'token_count': 948} |
// ignore_for_file: invalid_override_of_non_virtual_member
import 'package:flutter/material.dart';
import 'package:flutter_super/flutter_super.dart';
import 'package:flutter_super/src/instance.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('InstanceManager', () {
setUp(() {
InstanceManager.activate(
testMode: true,
autoDispose: true,
mocks: [],
);
TestWidgetsFlutterBinding.ensureInitialized();
});
tearDown(() {
InstanceManager.deactivate('super');
});
test('create() should register a singleton instance', () {
final instance = MockRx();
final lazyInstance = MockController();
InstanceManager.create<MockRx>(instance);
expect(InstanceManager.of<MockRx>(), instance);
InstanceManager.create<MockController>(lazyInstance, lazy: true);
expect(InstanceManager.of<MockController>(), lazyInstance);
});
test('create() should throw an error if SuperApp is not found', () {
InstanceManager.deactivate('super');
expect(
() => InstanceManager.create<String>('example'),
throwsA(isA<FlutterError>()),
);
});
test('of() should retrieve an instance from the manager', () {
const instance = 'example';
InstanceManager.create<String>(instance);
expect(InstanceManager.of<String>(), instance);
});
test('of() should invoke start() on SuperController instances', () {
final instance = MockController();
InstanceManager.create<MockController>(instance);
expect(instance.startCalled, false);
InstanceManager.of<MockController>();
expect(instance.startCalled, true);
});
test('of() should register and retrieve lazy instances', () {
const lazyInstance = 10;
InstanceManager.create<int>(lazyInstance, lazy: true);
expect(InstanceManager.of<int>(), lazyInstance);
});
test('of() should recursively register and retrieve instances', () {
final instance = MockController();
InstanceManager.create<MockController>(instance);
final mockInstance = InstanceManager.of<MockController>();
expect(mockInstance, instance);
});
test('of() should throw an error if type T is not found', () {
expect(
() => InstanceManager.of<String>(),
throwsA(isA<FlutterError>()),
);
});
test('init() should retrieve an instance or create a new one', () {
const instance = 'example';
InstanceManager.create<String>(instance);
// String key already exists
expect(InstanceManager.init<String>('other'), instance);
expect(InstanceManager.init<int>(10), 10);
});
test('init() should create a new instance if it does not exist', () {
const instance = 'example';
expect(InstanceManager.init<String>(instance), instance);
expect(InstanceManager.of<String>(), instance);
});
test('delete() should delete an instance from the manager', () {
const instance = 'example';
InstanceManager.create<String>(instance);
expect(InstanceManager.of<String>(), instance);
InstanceManager.delete<String>();
expect(() => InstanceManager.of<String>(), throwsA(isA<FlutterError>()));
});
test('delete() should stop SuperController instances', () {
final controller = MockController();
InstanceManager.create<MockController>(controller);
expect(controller.stopCalled, false);
InstanceManager.delete<MockController>();
expect(controller.stopCalled, true);
});
test('delete() should dispose Rx instances', () {
final rxInstance = MockRx();
InstanceManager.create<Rx>(rxInstance);
expect(rxInstance.disposeCalled, false);
InstanceManager.delete<Rx>();
expect(rxInstance.disposeCalled, true);
});
test('deleteAll() should delete all instances from the manager', () {
InstanceManager.create<String>('example');
InstanceManager.create<int>(42);
InstanceManager.create<Rx>(MockRx());
expect(InstanceManager.of<String>(), 'example');
expect(InstanceManager.of<int>(), 42);
expect(InstanceManager.of<Rx>(), isA<MockRx>());
InstanceManager.deleteAll();
expect(
() => InstanceManager.of<String>(),
throwsA(isA<FlutterError>()),
);
expect(
() => InstanceManager.of<int>(),
throwsA(isA<FlutterError>()),
);
expect(
() => InstanceManager.of<Rx>(),
throwsA(isA<FlutterError>()),
);
});
test('deleteAll() should stop SuperController instances', () {
final controller1 = MockController();
final controller2 = MockController();
InstanceManager.create<MockController>(controller1);
InstanceManager.create<SuperController>(controller2);
expect(controller1.stopCalled, false);
expect(controller2.stopCalled, false);
InstanceManager.deleteAll();
expect(controller1.stopCalled, true);
expect(controller2.stopCalled, true);
});
test('deleteAll() should dispose Rx instances', () {
final rxInstance1 = MockRx();
final rxInstance2 = MockRx();
InstanceManager.create<MockRx>(rxInstance1);
InstanceManager.create<Rx>(rxInstance2);
expect(rxInstance1.disposeCalled, false);
expect(rxInstance2.disposeCalled, false);
InstanceManager.deleteAll();
expect(rxInstance1.disposeCalled, true);
expect(rxInstance2.disposeCalled, true);
});
test('activate() should set the scoped state', () {
expect(InstanceManager.scoped, true);
});
test('deactivate() should reset the scoped state', () {
InstanceManager.deactivate('super');
expect(InstanceManager.scoped, false);
});
});
}
class MockController extends SuperController {
bool startCalled = false;
bool stopCalled = false;
@override
void start() {
super.start();
startCalled = true;
}
@override
void stop() {
stopCalled = true;
super.stop();
}
}
class MockRx extends Rx {
bool disposeCalled = false;
@override
void dispose() {
disposeCalled = true;
super.dispose();
}
}
| flutter_super/test/src/instance_test.dart/0 | {'file_path': 'flutter_super/test/src/instance_test.dart', 'repo_id': 'flutter_super', 'token_count': 2274} |
import 'package:flutter/material.dart';
import 'package:flutter_super/flutter_super.dart';
import 'package:flutter_test/flutter_test.dart';
class MyController extends SuperController {
bool initContextCalled = false;
bool stopCalled = false;
@override
void initContext(BuildContext? context) {
initContextCalled = true;
}
@override
// ignore: invalid_override_of_non_virtual_member
void stop() {
stopCalled = true;
super.stop();
}
}
class MySuperWidget extends SuperWidget<MyController> {
const MySuperWidget({super.key});
@override
MyController initController() => MyController();
@override
Widget build(BuildContext context) => Container();
}
void main() {
group('SuperWidget', () {
testWidgets('Initializes the controller', (WidgetTester tester) async {
const widget = MySuperWidget();
await tester.pumpWidget(const SuperApp(child: widget));
final controller = widget.controller;
expect(controller, isNotNull);
expect(controller.initContextCalled, isTrue);
});
testWidgets('Builds the widget', (WidgetTester tester) async {
const widget = MySuperWidget();
await tester.pumpWidget(const SuperApp(child: widget));
expect(find.byType(Container), findsOneWidget);
});
testWidgets('Disposes the controller', (WidgetTester tester) async {
const widget = MySuperWidget();
await tester.pumpWidget(const SuperApp(child: widget));
final controller = widget.controller;
await tester.pumpWidget(Container());
expect(controller.stopCalled, isTrue);
});
});
}
| flutter_super/test/src/widgets/super_widget_test.dart/0 | {'file_path': 'flutter_super/test/src/widgets/super_widget_test.dart', 'repo_id': 'flutter_super', 'token_count': 539} |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
void main() {
testWidgets('Default Swiper', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MaterialApp(
home: Swiper(
itemBuilder: (context, index) {
return Text("0");
},
itemCount: 10)));
expect(find.text("0", skipOffstage: false), findsOneWidget);
});
testWidgets('Default Swiper loop:false', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MaterialApp(
home: Swiper(
onTap: (int inde) {},
itemBuilder: (context, index) {
return Text("0");
},
itemCount: 10,
loop: false,
)));
expect(find.text("0", skipOffstage: true), findsOneWidget);
});
testWidgets('Create Swiper with children', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MaterialApp(
home: Swiper.children(
children: <Widget>[Text("0"), Text("1")],
)));
expect(find.text("0", skipOffstage: false), findsOneWidget);
});
testWidgets('Create Swiper with list', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MaterialApp(
home: Swiper.list(
list: ["0", "1"],
builder: (BuildContext context, dynamic data, int index) {
return Text(data);
},
)));
expect(find.text("0", skipOffstage: false), findsOneWidget);
});
testWidgets('Swiper with default plugins', (WidgetTester tester) async {
// Build our app and trigger a frame.
SwiperController controller = SwiperController();
await tester.pumpWidget(MaterialApp(
home: Swiper(
controller: controller,
itemBuilder: (context, index) {
return Text("0");
},
itemCount: 10,
pagination: SwiperPagination(),
control: SwiperControl(),
)));
expect(find.text("0", skipOffstage: false), findsOneWidget);
});
const List<String> titles = [
"Flutter Swiper is awosome",
"Really nice",
"Yeap"
];
testWidgets('Customize pagination', (WidgetTester tester) async {
// Build our app and trigger a frame.
SwiperController controller = SwiperController();
await tester.pumpWidget(MaterialApp(
home: Swiper(
controller: controller,
itemBuilder: (context, index) {
return Text("0");
},
itemCount: 10,
pagination: SwiperCustomPagination(
builder: (BuildContext context, SwiperPluginConfig config) {
return ConstrainedBox(
child: Row(
children: <Widget>[
Text(
"${titles[config.activeIndex]} ${config.activeIndex+1}/${config.itemCount}",
style: TextStyle(fontSize: 20.0),
),
Expanded(
child: Align(
alignment: Alignment.centerRight,
child: DotSwiperPaginationBuilder(
color: Colors.black12,
activeColor: Colors.black,
size: 10.0,
activeSize: 20.0)
.build(context, config),
),
)
],
),
constraints: BoxConstraints.expand(height: 50.0),
);
}),
control: SwiperControl(),
)));
controller.startAutoplay();
controller.stopAutoplay();
controller.move(0, animation: true);
controller.move(0, animation: false);
controller.next(animation: false);
controller.previous(animation: true);
expect(find.text("0", skipOffstage: false), findsOneWidget);
});
testWidgets('Swiper fraction', (WidgetTester tester) async {
// Build our app and trigger a frame.
SwiperController controller = SwiperController();
await tester.pumpWidget(MaterialApp(
home: Swiper(
controller: controller,
itemBuilder: (context, index) {
return Text("0");
},
itemCount: 10,
pagination: SwiperPagination(builder: SwiperPagination.fraction),
control: SwiperControl(),
)));
expect(find.text("0", skipOffstage: false), findsOneWidget);
});
}
| flutter_swiper/test/flutter_swiper_test.dart/0 | {'file_path': 'flutter_swiper/test/flutter_swiper_test.dart', 'repo_id': 'flutter_swiper', 'token_count': 1869} |
import 'package:bloc/bloc.dart';
// We can extend `BlocDelegate` and override `onTransition` and `onError`
// in order to handle transitions and errors from all Blocs.
class SimpleBlocDelegate extends BlocDelegate {
@override
void onEvent(Bloc bloc, Object event) {
super.onEvent(bloc, event);
print(event);
}
@override
void onTransition(Bloc bloc, Transition transition) {
super.onTransition(bloc, transition);
print(transition);
}
@override
void onError(Bloc bloc, Object error, StackTrace stacktrace) {
super.onError(bloc, error, stacktrace);
print(error);
}
}
| flutter_todos/lib/blocs/simple_bloc_delegate.dart/0 | {'file_path': 'flutter_todos/lib/blocs/simple_bloc_delegate.dart', 'repo_id': 'flutter_todos', 'token_count': 212} |
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
import 'package:flutter_todos/blocs/todos/todos.dart';
import 'package:flutter_todos/models/models.dart';
import 'package:todos_repository_simple/todos_repository_simple.dart';
class TodosBloc extends Bloc<TodosEvent, TodosState> {
final TodosRepositoryFlutter todosRepository;
TodosBloc({@required this.todosRepository});
@override
TodosState get initialState => TodosLoadInProgress();
@override
Stream<TodosState> mapEventToState(TodosEvent event) async* {
if (event is TodosLoaded) {
yield* _mapTodosLoadedToState();
} else if (event is TodoAdded) {
yield* _mapTodoAddedToState(event);
} else if (event is TodoUpdated) {
yield* _mapTodoUpdatedToState(event);
} else if (event is TodoDeleted) {
yield* _mapTodoDeletedToState(event);
} else if (event is ToggleAll) {
yield* _mapToggleAllToState();
} else if (event is ClearCompleted) {
yield* _mapClearCompletedToState();
}
}
Stream<TodosState> _mapTodosLoadedToState() async* {
try {
final todos = await this.todosRepository.loadTodos();
yield TodosLoadSuccess(
todos.map(Todo.fromEntity).toList(),
);
} catch (_) {
yield TodosLoadFailure();
}
}
Stream<TodosState> _mapTodoAddedToState(TodoAdded event) async* {
if (state is TodosLoadSuccess) {
final List<Todo> updatedTodos =
List.from((state as TodosLoadSuccess).todos)..add(event.todo);
yield TodosLoadSuccess(updatedTodos);
_saveTodos(updatedTodos);
}
}
Stream<TodosState> _mapTodoUpdatedToState(TodoUpdated event) async* {
if (state is TodosLoadSuccess) {
final List<Todo> updatedTodos =
(state as TodosLoadSuccess).todos.map((todo) {
return todo.id == event.todo.id ? event.todo : todo;
}).toList();
yield TodosLoadSuccess(updatedTodos);
_saveTodos(updatedTodos);
}
}
Stream<TodosState> _mapTodoDeletedToState(TodoDeleted event) async* {
if (state is TodosLoadSuccess) {
final updatedTodos = (state as TodosLoadSuccess)
.todos
.where((todo) => todo.id != event.todo.id)
.toList();
yield TodosLoadSuccess(updatedTodos);
_saveTodos(updatedTodos);
}
}
Stream<TodosState> _mapToggleAllToState() async* {
if (state is TodosLoadSuccess) {
final allComplete =
(state as TodosLoadSuccess).todos.every((todo) => todo.complete);
final List<Todo> updatedTodos = (state as TodosLoadSuccess)
.todos
.map((todo) => todo.copyWith(complete: !allComplete))
.toList();
yield TodosLoadSuccess(updatedTodos);
_saveTodos(updatedTodos);
}
}
Stream<TodosState> _mapClearCompletedToState() async* {
if (state is TodosLoadSuccess) {
final List<Todo> updatedTodos = (state as TodosLoadSuccess)
.todos
.where((todo) => !todo.complete)
.toList();
yield TodosLoadSuccess(updatedTodos);
_saveTodos(updatedTodos);
}
}
Future _saveTodos(List<Todo> todos) {
return todosRepository.saveTodos(
todos.map((todo) => todo.toEntity()).toList(),
);
}
}
| flutter_todos/lib/blocs/todos/todos_bloc.dart/0 | {'file_path': 'flutter_todos/lib/blocs/todos/todos_bloc.dart', 'repo_id': 'flutter_todos', 'token_count': 1433} |
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:todos_app_core/todos_app_core.dart';
import 'package:flutter_todos/blocs/todos/todos.dart';
import 'package:flutter_todos/models/models.dart';
import 'package:flutter_todos/flutter_todos_keys.dart';
class ExtraActions extends StatelessWidget {
ExtraActions({Key key}) : super(key: ArchSampleKeys.extraActionsButton);
@override
Widget build(BuildContext context) {
return BlocBuilder<TodosBloc, TodosState>(
builder: (context, state) {
if (state is TodosLoadSuccess) {
bool allComplete =
(BlocProvider.of<TodosBloc>(context).state as TodosLoadSuccess)
.todos
.every((todo) => todo.complete);
return PopupMenuButton<ExtraAction>(
key: FlutterTodosKeys.extraActionsPopupMenuButton,
onSelected: (action) {
switch (action) {
case ExtraAction.clearCompleted:
BlocProvider.of<TodosBloc>(context).add(ClearCompleted());
break;
case ExtraAction.toggleAllComplete:
BlocProvider.of<TodosBloc>(context).add(ToggleAll());
break;
}
},
itemBuilder: (BuildContext context) => <PopupMenuItem<ExtraAction>>[
PopupMenuItem<ExtraAction>(
key: ArchSampleKeys.toggleAll,
value: ExtraAction.toggleAllComplete,
child: Text(
allComplete
? ArchSampleLocalizations.of(context).markAllIncomplete
: ArchSampleLocalizations.of(context).markAllComplete,
),
),
PopupMenuItem<ExtraAction>(
key: ArchSampleKeys.clearCompleted,
value: ExtraAction.clearCompleted,
child: Text(
ArchSampleLocalizations.of(context).clearCompleted,
),
),
],
);
}
return Container(key: FlutterTodosKeys.extraActionsEmptyContainer);
},
);
}
}
| flutter_todos/lib/widgets/extra_actions.dart/0 | {'file_path': 'flutter_todos/lib/widgets/extra_actions.dart', 'repo_id': 'flutter_todos', 'token_count': 1113} |
// ignore_for_file: avoid_print
/*
* Copyright (c) 2020-present Invertase Limited & Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this library except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import 'dart:io';
import 'package:flutterfire_cli/src/command_runner.dart';
import 'package:flutterfire_cli/src/common/strings.dart';
import 'package:flutterfire_cli/src/common/utils.dart' as utils;
import 'package:flutterfire_cli/src/flutter_app.dart';
import 'package:flutterfire_cli/version.g.dart';
import 'package:pub_updater/pub_updater.dart';
Future<void> main(List<String> arguments) async {
if (arguments.contains('--version') || arguments.contains('-v')) {
print(cliVersion);
// No version checks on CIs.
if (utils.isCI) return;
// Check for updates.
final pubUpdater = PubUpdater();
const packageName = 'flutterfire_cli';
final isUpToDate = await pubUpdater.isUpToDate(
packageName: packageName,
currentVersion: cliVersion,
);
if (!isUpToDate) {
final latestVersion = await pubUpdater.getLatestVersion(packageName);
final shouldUpdate = utils.promptBool(
logPromptNewCliVersionAvailable(packageName, latestVersion),
);
if (shouldUpdate) {
await pubUpdater.update(packageName: packageName);
print(logCliUpdated(packageName, latestVersion));
}
}
return;
}
try {
final flutterApp = await FlutterApp.load(Directory.current);
await FlutterFireCommandRunner(flutterApp).run(arguments);
} on FlutterFireException catch (err) {
if (utils.activeSpinnerState != null) {
try {
utils.activeSpinnerState!.done();
} catch (_) {}
}
stderr.writeln(err.toString());
exitCode = 1;
} catch (err) {
exitCode = 1;
rethrow;
}
}
| flutterfire_cli/packages/flutterfire_cli/bin/flutterfire.dart/0 | {'file_path': 'flutterfire_cli/packages/flutterfire_cli/bin/flutterfire.dart', 'repo_id': 'flutterfire_cli', 'token_count': 798} |
import 'package:flutter/material.dart';
/// Displays detailed information about a SampleItem.
class SampleItemDetailsView extends StatelessWidget {
const SampleItemDetailsView({Key? key}) : super(key: key);
static const routeName = '/sample_item';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Item Details'),
),
body: const Center(
child: Text('More Information Here'),
),
);
}
}
| flutterfire_cli/packages/flutterfire_starter/__brick__/lib/src/sample_feature/sample_item_details_view.dart/0 | {'file_path': 'flutterfire_cli/packages/flutterfire_starter/__brick__/lib/src/sample_feature/sample_item_details_view.dart', 'repo_id': 'flutterfire_cli', 'token_count': 171} |
import 'package:flutter/material.dart' hide SearchBar;
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttersaurus/search/search.dart';
import 'package:fluttersaurus/synonyms/synonyms.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:shimmer/shimmer.dart';
class SearchForm extends StatelessWidget {
const SearchForm({super.key});
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
SearchBar(
onChanged: (term) {
context.read<SearchBloc>().add(SearchTermChanged(term));
},
),
const SizedBox(height: 16),
_SearchContent(),
],
);
}
}
class _SearchContent extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Flexible(
child: BlocConsumer<SearchBloc, SearchState>(
listenWhen: (previous, current) => previous.status != current.status,
listener: (context, state) {
if (state.status == SearchStatus.failure) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
const SnackBar(content: Text('oops try again!')),
);
}
},
builder: (context, state) {
switch (state.status) {
case SearchStatus.initial:
case SearchStatus.failure:
return const _SearchInitial();
case SearchStatus.loading:
return const _SearchLoading();
case SearchStatus.success:
return _SearchSuccess(suggestions: state.suggestions);
}
},
),
);
}
}
class _SearchLoading extends StatelessWidget {
const _SearchLoading();
@override
Widget build(BuildContext context) {
return Shimmer.fromColors(
key: const Key('search_loading_shimmer'),
baseColor: Colors.grey.shade300,
highlightColor: Colors.grey.shade100,
child: ListView.separated(
itemBuilder: (context, index) => Container(
height: 48,
color: Colors.white,
),
itemCount: 10,
separatorBuilder: (context, index) => const SizedBox(height: 16),
),
);
}
}
class _SearchSuccess extends StatelessWidget {
const _SearchSuccess({required this.suggestions});
final List<Suggestion> suggestions;
@override
Widget build(BuildContext context) {
return SearchResults(
suggestions: suggestions,
onTap: (suggestion) {
Navigator.of(context).push<void>(
SynonymsPage.route(word: suggestion.value),
);
},
);
}
}
class _SearchInitial extends StatelessWidget {
const _SearchInitial();
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Text(
'Find some fancy words ✨',
key: const Key('search_initial_text'),
style: GoogleFonts.roboto(
textStyle: textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w300),
),
);
}
}
| fluttersaurus/lib/search/view/search_form.dart/0 | {'file_path': 'fluttersaurus/lib/search/view/search_form.dart', 'repo_id': 'fluttersaurus', 'token_count': 1281} |
import 'package:datamuse_api/datamuse_api.dart';
/// {@template thesaurus_exception}
/// Generic exception thrown by the [ThesaurusRepository].
/// {@endtemplate}
class ThesaurusException implements Exception {
/// {@macro thesaurus_exception}
const ThesaurusException(this.exception, this.stackTrace);
/// The exception that occured.
final dynamic exception;
/// The [StackTrace] for the exception.
final StackTrace stackTrace;
}
/// {@template search_http_request_failure}
/// Thrown when an error occurs while performing a search.
/// {@endtemplate}
class SearchHttpRequestFailure extends ThesaurusException {
/// {@macro search_http_request_failure}
SearchHttpRequestFailure(super.failure, super.stackTrace);
}
/// {@template synonyms_exception}
/// Thrown when an error occurs while looking up synonyms.
/// {@endtemplate}
class SynonymsException extends ThesaurusException {
/// {@macro synonyms_exception}
SynonymsException(super.exception, super.stackTrace);
}
/// {@template thesaurus_repository}
/// A Dart class which exposes methods to implement thesaurus functionality.
/// {@endtemplate}
class ThesaurusRepository {
/// {@macro thesaurus_repository}
ThesaurusRepository({DatamuseApiClient? datamuseApiClient})
: _datamuseApiClient = datamuseApiClient ?? DatamuseApiClient();
final DatamuseApiClient _datamuseApiClient;
/// Returns a list of suggestions for the provided [term].
/// A [limit] can optionally be provided to control the number of suggestions.
///
/// Throws a [SearchHttpRequestFailure] if an error occurs.
Future<List<String>> search({required String term, int? limit}) async {
assert(term.isNotEmpty, 'term must not be empty');
try {
final words = await _datamuseApiClient.suggestions(term, max: limit);
return words.map((word) => word.word).toList();
} on HttpRequestFailure catch (e, stackTrace) {
throw SearchHttpRequestFailure(e, stackTrace);
}
}
/// Returns a list of synonyms for the given [word].
/// A [limit] can optionally be provided to control the number of results.
///
/// Throws a [SynonymsException] if an error occurs.
Future<List<String>> synonyms({required String word, int? limit}) async {
assert(word.isNotEmpty, 'word must not be empty');
List<Word> words;
try {
words = await _datamuseApiClient.words(meansLike: word, max: limit);
} on Exception catch (error, stackTrace) {
throw SynonymsException(error, stackTrace);
}
return words
.where((word) => word.tags.contains(Tag.synonym))
.map((word) => word.word)
.toList();
}
}
| fluttersaurus/packages/thesaurus_repository/lib/src/thesaurus_repository.dart/0 | {'file_path': 'fluttersaurus/packages/thesaurus_repository/lib/src/thesaurus_repository.dart', 'repo_id': 'fluttersaurus', 'token_count': 854} |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:fluttersaurus/search/search.dart';
import 'package:fluttersaurus/synonyms/synonyms.dart';
import 'package:mocktail/mocktail.dart';
import 'package:thesaurus_repository/thesaurus_repository.dart';
class MockThesaurusRepository extends Mock implements ThesaurusRepository {}
class MockSearchBloc extends MockBloc<SearchEvent, SearchState>
implements SearchBloc {}
void main() {
group('SearchForm', () {
late SearchBloc searchBloc;
setUpAll(() {
registerFallbackValue(const SearchTermChanged(''));
registerFallbackValue(const SearchState.initial());
});
setUp(() {
searchBloc = MockSearchBloc();
when(() => searchBloc.state).thenReturn(const SearchState.initial());
});
testWidgets('adds SearchTermChanged when text is entered', (tester) async {
const term = 'cats';
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: BlocProvider.value(
value: searchBloc,
child: const SearchForm(),
),
),
),
);
await tester.enterText(
find.byKey(const Key('searchBar_textField')),
term,
);
verify(() => searchBloc.add(const SearchTermChanged(term))).called(1);
});
testWidgets('renders initial text when state is initial', (tester) async {
when(() => searchBloc.state).thenReturn(const SearchState.initial());
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: BlocProvider.value(
value: searchBloc,
child: const SearchForm(),
),
),
),
);
expect(find.byKey(const Key('search_initial_text')), findsOneWidget);
});
testWidgets('renders loading shimmer when state is loading',
(tester) async {
when(() => searchBloc.state).thenReturn(const SearchState.loading());
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: BlocProvider.value(
value: searchBloc,
child: const SearchForm(),
),
),
),
);
expect(find.byKey(const Key('search_loading_shimmer')), findsOneWidget);
});
testWidgets('renders SearchResults when state is success', (tester) async {
when(() => searchBloc.state).thenReturn(const SearchState.success([]));
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: BlocProvider.value(
value: searchBloc,
child: const SearchForm(),
),
),
),
);
expect(find.byType(SearchResults), findsOneWidget);
});
testWidgets('renders SnackBar when state is failure', (tester) async {
when(() => searchBloc.state).thenReturn(const SearchState.failure());
whenListen(
searchBloc,
Stream.fromIterable(
const <SearchState>[SearchState.loading(), SearchState.failure()],
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: BlocProvider.value(
value: searchBloc,
child: const SearchForm(),
),
),
),
);
await tester.pump();
expect(find.byType(SnackBar), findsOneWidget);
});
testWidgets('navigates to SynonymsPage when suggestion is tapped',
(tester) async {
const word = 'kitty';
final thesaurusRepository = MockThesaurusRepository();
when(() => thesaurusRepository.synonyms(word: any(named: 'word')))
.thenAnswer((_) async => []);
when(() => searchBloc.state).thenReturn(
const SearchState.success([Suggestion(word)]),
);
await tester.pumpWidget(
RepositoryProvider<ThesaurusRepository>.value(
value: thesaurusRepository,
child: MaterialApp(
home: Scaffold(
body: BlocProvider.value(
value: searchBloc,
child: const SearchForm(),
),
),
),
),
);
await tester.tap(find.text(word));
await tester.pumpAndSettle();
expect(find.byType(SynonymsPage), findsOneWidget);
});
});
}
| fluttersaurus/test/search/view/search_form_test.dart/0 | {'file_path': 'fluttersaurus/test/search/view/search_form_test.dart', 'repo_id': 'fluttersaurus', 'token_count': 1996} |
import 'dart:html' hide Body;
import 'dart:math';
import 'package:forge2d/forge2d_browser.dart';
import 'demo.dart';
import 'racer/car.dart';
import 'racer/control_state.dart';
import 'racer/ground_area.dart';
import 'racer/tire.dart';
class Racer extends Demo implements ContactListener {
static void main() {
final racer = Racer();
racer.initialize();
racer.initializeAnimation();
final paragraph = ParagraphElement()
..innerText = 'Use the arrow keys to drive the car';
document.body?.nodes.add(paragraph);
racer.runAnimation();
}
Racer() : super('Racer', Vector2.zero(), 2.5);
late int _controlState;
late Body _groundBody;
late final Car _car;
num _lastTime = 0;
@override
void initialize() {
_createGround();
_createBoundary();
_car = Car(world);
_controlState = 0;
// Bind to keyboard events.
document.onKeyDown.listen(_handleKeyDown);
document.onKeyUp.listen(_handleKeyUp);
// Add ourselves as a collision listener.
world.setContactListener(this);
}
@override
void step(num time) {
_car.update(time - _lastTime, _controlState);
_lastTime = time;
super.step(time);
}
// ContactListener overrides.
@override
void beginContact(Contact contact) {
_handleContact(contact, true);
}
@override
void endContact(Contact contact) {
_handleContact(contact, false);
}
@override
void preSolve(Contact contact, Manifold oldManifold) {}
@override
void postSolve(Contact contact, ContactImpulse impulse) {}
double radians(double deg) => deg * (pi / 180.0);
void _createGround() {
final def = BodyDef();
_groundBody = world.createBody(def);
_groundBody.userData = 'Ground';
final shape = PolygonShape()
..setAsBox(27.0, 21.0, Vector2(-30.0, 30.0), radians(20.0));
final fixtureDef = FixtureDef(shape)
..isSensor = true
..userData = GroundArea(0.001, outOfCourse: false);
_groundBody.createFixture(fixtureDef);
fixtureDef.userData = GroundArea(0.2, outOfCourse: false);
shape.setAsBox(27.0, 15.0, Vector2(20.0, 40.0), radians(-40.0));
_groundBody.createFixture(fixtureDef);
}
void _createBoundary() {
final def = BodyDef();
final boundaryBody = world.createBody(def);
boundaryBody.userData = 'Boundary';
final shape = PolygonShape();
final fixtureDef = FixtureDef(shape);
const boundaryX = 150.0;
const boundaryY = 100.0;
shape.setAsEdge(
Vector2(-boundaryX, -boundaryY),
Vector2(boundaryX, -boundaryY),
);
boundaryBody.createFixture(fixtureDef);
shape.setAsEdge(
Vector2(boundaryX, -boundaryY),
Vector2(boundaryX, boundaryY),
);
boundaryBody.createFixture(fixtureDef);
shape.setAsEdge(
Vector2(boundaryX, boundaryY),
Vector2(-boundaryX, boundaryY),
);
boundaryBody.createFixture(fixtureDef);
shape.setAsEdge(
Vector2(-boundaryX, boundaryY),
Vector2(-boundaryX, -boundaryY),
);
boundaryBody.createFixture(fixtureDef);
}
void _handleKeyDown(KeyboardEvent event) {
switch (event.keyCode) {
case 37:
_controlState |= ControlState.left;
break;
case 38:
_controlState |= ControlState.up;
break;
case 39:
_controlState |= ControlState.right;
break;
case 40:
_controlState |= ControlState.down;
break;
}
}
void _handleKeyUp(KeyboardEvent event) {
switch (event.keyCode) {
case 37:
_controlState &= ~ControlState.left;
break;
case 38:
_controlState &= ~ControlState.up;
break;
case 39:
_controlState &= ~ControlState.right;
break;
case 40:
_controlState &= ~ControlState.down;
break;
}
}
// TODO(any): collision filtering.
// Tire with Boundary
// Tire with GroundArea
void _handleContact(Contact contact, bool began) {
final fudA = contact.fixtureA.userData;
final fudB = contact.fixtureB.userData;
// Check for ground area collision.
// TODO(any): named parameters instead of swapping order?
if (fudA is Tire && fudB is GroundArea) {
_tireVsGroundArea(fudA, fudB, began);
} else if (fudA is GroundArea && fudB is Tire) {
_tireVsGroundArea(fudB, fudA, began);
}
}
void _tireVsGroundArea(Tire tire, GroundArea groundArea, bool began) {
if (began) {
tire.addGroundArea(groundArea);
} else {
tire.removeGroundArea(groundArea);
}
}
}
void main() {
Racer.main();
}
| forge2d/packages/forge2d/example/web/racer.dart/0 | {'file_path': 'forge2d/packages/forge2d/example/web/racer.dart', 'repo_id': 'forge2d', 'token_count': 1819} |
import 'package:forge2d/forge2d.dart';
abstract class ParticleRaycastCallback {
/// Called for each particle found in the query.
/// See [RayCastCallback.reportFixture] for more info.
double reportParticle(
int index,
Vector2 point,
Vector2 normal,
double fraction,
);
}
| forge2d/packages/forge2d/lib/src/callbacks/particle_raycast_callback.dart/0 | {'file_path': 'forge2d/packages/forge2d/lib/src/callbacks/particle_raycast_callback.dart', 'repo_id': 'forge2d', 'token_count': 98} |
import 'package:forge2d/forge2d.dart';
/// Output for Distance.
class DistanceOutput {
/// Closest point on shapeA
final Vector2 pointA = Vector2.zero();
/// Closest point on shapeB
final Vector2 pointB = Vector2.zero();
double distance = 0.0;
/// number of gjk iterations used
int iterations = 0;
}
| forge2d/packages/forge2d/lib/src/collision/distance_output.dart/0 | {'file_path': 'forge2d/packages/forge2d/lib/src/collision/distance_output.dart', 'repo_id': 'forge2d', 'token_count': 102} |
class Color3i {
Color3i(this.r, this.g, this.b, {this.a = 1.0});
Color3i.white() : this(255, 255, 255);
Color3i.black() : this(0, 0, 0);
Color3i.blue() : this(0, 0, 255);
Color3i.green() : this(0, 255, 0);
Color3i.red() : this(255, 0, 0);
int r = 0;
int g = 0;
int b = 0;
double a = 1.0;
Color3i.zero();
Color3i.fromRGBd(double red, double green, double blue, {double alpha = 1.0})
: r = (red * 255).floor(),
g = (green * 255).floor(),
b = (blue * 255).floor(),
a = alpha;
void setRGB(int red, int green, int blue, {double? alpha}) {
r = red;
g = green;
b = blue;
a = alpha ?? a;
}
void setFromRGBd(double red, double green, double blue, {double? alpha}) {
r = (red * 255).floor();
g = (green * 255).floor();
b = (blue * 255).floor();
a = alpha ?? a;
}
void setFromColor3i(Color3i argColor) {
r = argColor.r;
g = argColor.b;
b = argColor.g;
a = argColor.a;
}
Color3i clone() => Color3i(r, g, b, a: a);
@override
String toString() => 'Color3i($r, $g, $b, $a)';
}
| forge2d/packages/forge2d/lib/src/common/color3i.dart/0 | {'file_path': 'forge2d/packages/forge2d/lib/src/common/color3i.dart', 'repo_id': 'forge2d', 'token_count': 494} |
import 'dart:math';
import 'package:forge2d/forge2d.dart';
import 'package:forge2d/src/settings.dart' as settings;
class ContactSolverDef {
late TimeStep step;
late List<Contact> contacts;
late List<Position> positions;
late List<Velocity> velocities;
}
class ContactSolver {
static const bool debugSolver = false;
static const double errorTol = 1e-3;
/// Ensure a reasonable condition number. for the block solver
static const double maxConditionNumber = 100.0;
late TimeStep _step;
late List<Position> _positions;
late List<Velocity> _velocities;
late List<Contact> _contacts;
void init(ContactSolverDef def) {
_step = def.step;
_positions = def.positions;
_velocities = def.velocities;
_contacts = def.contacts;
for (final contact in _contacts) {
final fixtureA = contact.fixtureA;
final fixtureB = contact.fixtureB;
final shapeA = fixtureA.shape;
final shapeB = fixtureB.shape;
final radiusA = shapeA.radius;
final radiusB = shapeB.radius;
final bodyA = fixtureA.body;
final bodyB = fixtureB.body;
final manifold = contact.manifold;
final pointCount = manifold.pointCount;
assert(pointCount > 0);
final velocityConstraint = contact.velocityConstraint
..friction = contact.friction
..restitution = contact.restitution
..tangentSpeed = contact.tangentSpeed
..indexA = bodyA.islandIndex
..indexB = bodyB.islandIndex
..invMassA = bodyA.inverseMass
..invMassB = bodyB.inverseMass
..invIA = bodyA.inverseInertia
..invIB = bodyB.inverseInertia
..contactIndex = _contacts.indexOf(contact)
..pointCount = pointCount
..K.setZero()
..normalMass.setZero();
final positionConstraint = contact.positionConstraint
..indexA = bodyA.islandIndex
..indexB = bodyB.islandIndex
..invMassA = bodyA.inverseMass
..invMassB = bodyB.inverseMass
..localCenterA.setFrom(bodyA.sweep.localCenter)
..localCenterB.setFrom(bodyB.sweep.localCenter)
..invIA = bodyA.inverseInertia
..invIB = bodyB.inverseInertia
..localNormal.setFrom(manifold.localNormal)
..localPoint.setFrom(manifold.localPoint)
..pointCount = pointCount
..radiusA = radiusA
..radiusB = radiusB
..type = manifold.type;
for (var j = 0; j < pointCount; j++) {
final cp = manifold.points[j];
final vcp = velocityConstraint.points[j];
if (_step.warmStarting) {
vcp.normalImpulse = _step.dtRatio * cp.normalImpulse;
vcp.tangentImpulse = _step.dtRatio * cp.tangentImpulse;
} else {
vcp.normalImpulse = 0.0;
vcp.tangentImpulse = 0.0;
}
vcp.rA.setZero();
vcp.rB.setZero();
vcp.normalMass = 0.0;
vcp.tangentMass = 0.0;
vcp.velocityBias = 0.0;
positionConstraint.localPoints[j].x = cp.localPoint.x;
positionConstraint.localPoints[j].y = cp.localPoint.y;
}
}
}
void warmStart() {
// Warm start.
for (final contact in _contacts) {
final velocityConstraint = contact.velocityConstraint;
final indexA = velocityConstraint.indexA;
final indexB = velocityConstraint.indexB;
final mA = velocityConstraint.invMassA;
final iA = velocityConstraint.invIA;
final mB = velocityConstraint.invMassB;
final iB = velocityConstraint.invIB;
final pointCount = velocityConstraint.pointCount;
final vA = _velocities[indexA].v;
var wA = _velocities[indexA].w;
final vB = _velocities[indexB].v;
var wB = _velocities[indexB].w;
final normal = velocityConstraint.normal;
final tangentX = 1.0 * normal.y;
final tangentY = -1.0 * normal.x;
for (var j = 0; j < pointCount; ++j) {
final vcp = velocityConstraint.points[j];
final pX = tangentX * vcp.tangentImpulse + normal.x * vcp.normalImpulse;
final pY = tangentY * vcp.tangentImpulse + normal.y * vcp.normalImpulse;
wA -= iA * (vcp.rA.x * pY - vcp.rA.y * pX);
vA.x -= pX * mA;
vA.y -= pY * mA;
wB += iB * (vcp.rB.x * pY - vcp.rB.y * pX);
vB.x += pX * mB;
vB.y += pY * mB;
}
_velocities[indexA].w = wA;
_velocities[indexB].w = wB;
}
}
final Transform _xfA = Transform.zero();
final Transform _xfB = Transform.zero();
final WorldManifold _worldManifold = WorldManifold();
void initializeVelocityConstraints() {
// Warm start.
for (final contact in _contacts) {
final velocityConstraint = contact.velocityConstraint;
final positionConstraint = contact.positionConstraint;
final radiusA = positionConstraint.radiusA;
final radiusB = positionConstraint.radiusB;
final manifold = _contacts[velocityConstraint.contactIndex].manifold;
final indexA = velocityConstraint.indexA;
final indexB = velocityConstraint.indexB;
final mA = velocityConstraint.invMassA;
final mB = velocityConstraint.invMassB;
final iA = velocityConstraint.invIA;
final iB = velocityConstraint.invIB;
final localCenterA = positionConstraint.localCenterA;
final localCenterB = positionConstraint.localCenterB;
final cA = _positions[indexA].c;
final aA = _positions[indexA].a;
final vA = _velocities[indexA].v;
final wA = _velocities[indexA].w;
final cB = _positions[indexB].c;
final aB = _positions[indexB].a;
final vB = _velocities[indexB].v;
final wB = _velocities[indexB].w;
assert(manifold.pointCount > 0);
final xfAq = _xfA.q;
final xfBq = _xfB.q;
xfAq.setAngle(aA);
xfBq.setAngle(aB);
_xfA.p.x = cA.x - (xfAq.cos * localCenterA.x - xfAq.sin * localCenterA.y);
_xfA.p.y = cA.y - (xfAq.sin * localCenterA.x + xfAq.cos * localCenterA.y);
_xfB.p.x = cB.x - (xfBq.cos * localCenterB.x - xfBq.sin * localCenterB.y);
_xfB.p.y = cB.y - (xfBq.sin * localCenterB.x + xfBq.cos * localCenterB.y);
_worldManifold.initialize(manifold, _xfA, radiusA, _xfB, radiusB);
final vcNormal = velocityConstraint.normal;
vcNormal.x = _worldManifold.normal.x;
vcNormal.y = _worldManifold.normal.y;
final pointCount = velocityConstraint.pointCount;
for (var j = 0; j < pointCount; ++j) {
final vcp = velocityConstraint.points[j];
final wmPj = _worldManifold.points[j];
final vcprA = vcp.rA;
final vcprB = vcp.rB;
vcprA.x = wmPj.x - cA.x;
vcprA.y = wmPj.y - cA.y;
vcprB.x = wmPj.x - cB.x;
vcprB.y = wmPj.y - cB.y;
final rnA = vcprA.x * vcNormal.y - vcprA.y * vcNormal.x;
final rnB = vcprB.x * vcNormal.y - vcprB.y * vcNormal.x;
final kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
vcp.normalMass = kNormal > 0.0 ? 1.0 / kNormal : 0.0;
final tangentX = 1.0 * vcNormal.y;
final tangentY = -1.0 * vcNormal.x;
final rtA = vcprA.x * tangentY - vcprA.y * tangentX;
final rtB = vcprB.x * tangentY - vcprB.y * tangentX;
final kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB;
vcp.tangentMass = kTangent > 0.0 ? 1.0 / kTangent : 0.0;
// Setup a velocity bias for restitution.
vcp.velocityBias = 0.0;
final tempX = vB.x + -wB * vcprB.y - vA.x - (-wA * vcprA.y);
final tempY = vB.y + wB * vcprB.x - vA.y - (wA * vcprA.x);
final vRel = vcNormal.x * tempX + vcNormal.y * tempY;
if (vRel < -settings.velocityThreshold) {
vcp.velocityBias = -velocityConstraint.restitution * vRel;
}
}
// If we have two points, then prepare the block solver.
if (velocityConstraint.pointCount == 2) {
final vcp1 = velocityConstraint.points[0];
final vcp2 = velocityConstraint.points[1];
final rn1A = vcp1.rA.x * vcNormal.y - vcp1.rA.y * vcNormal.x;
final rn1B = vcp1.rB.x * vcNormal.y - vcp1.rB.y * vcNormal.x;
final rn2A = vcp2.rA.x * vcNormal.y - vcp2.rA.y * vcNormal.x;
final rn2B = vcp2.rB.x * vcNormal.y - vcp2.rB.y * vcNormal.x;
final k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B;
final k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B;
final k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B;
if (k11 * k11 < maxConditionNumber * (k11 * k22 - k12 * k12)) {
// K is safe to invert.
velocityConstraint.K.setValues(k11, k12, k12, k22);
velocityConstraint.normalMass.setFrom(velocityConstraint.K);
velocityConstraint.normalMass.invert();
} else {
// The constraints are redundant, just use one.
// TODO_ERIN use deepest?
velocityConstraint.pointCount = 1;
}
}
}
}
void solveVelocityConstraints() {
for (final contact in _contacts) {
final vc = contact.velocityConstraint;
final indexA = vc.indexA;
final indexB = vc.indexB;
final mA = vc.invMassA;
final mB = vc.invMassB;
final iA = vc.invIA;
final iB = vc.invIB;
final pointCount = vc.pointCount;
final vA = _velocities[indexA].v;
var wA = _velocities[indexA].w;
final vB = _velocities[indexB].v;
var wB = _velocities[indexB].w;
final normal = vc.normal;
final normalX = normal.x;
final normalY = normal.y;
final tangentX = 1.0 * vc.normal.y;
final tangentY = -1.0 * vc.normal.x;
final friction = vc.friction;
assert(pointCount == 1 || pointCount == 2);
// Solve tangent constraints
for (var j = 0; j < pointCount; ++j) {
final vcp = vc.points[j];
final a = vcp.rA;
final dvx = -wB * vcp.rB.y + vB.x - vA.x + wA * a.y;
final dvy = wB * vcp.rB.x + vB.y - vA.y - wA * a.x;
// Compute tangent force
final vt = dvx * tangentX + dvy * tangentY - vc.tangentSpeed;
var lambda = vcp.tangentMass * (-vt);
// Clamp the accumulated force
final maxFriction = (friction * vcp.normalImpulse).abs();
final newImpulse =
(vcp.tangentImpulse + lambda).clamp(-maxFriction, maxFriction);
lambda = newImpulse - vcp.tangentImpulse;
vcp.tangentImpulse = newImpulse;
// Apply contact impulse
// Vec2 P = lambda * tangent;
final pX = tangentX * lambda;
final pY = tangentY * lambda;
// vA -= invMassA * P;
vA.x -= pX * mA;
vA.y -= pY * mA;
wA -= iA * (vcp.rA.x * pY - vcp.rA.y * pX);
// vB += invMassB * P;
vB.x += pX * mB;
vB.y += pY * mB;
wB += iB * (vcp.rB.x * pY - vcp.rB.y * pX);
}
// Solve normal constraints
if (vc.pointCount == 1) {
final vcp = vc.points[0];
// Relative velocity at contact
// Vec2 dv = vB + Cross(wB, vcp.rB) - vA - Cross(wA, vcp.rA);
final dvx = -wB * vcp.rB.y + vB.x - vA.x + wA * vcp.rA.y;
final dvy = wB * vcp.rB.x + vB.y - vA.y - wA * vcp.rA.x;
// Compute normal impulse
final vn = dvx * normalX + dvy * normalY;
var lambda = -vcp.normalMass * (vn - vcp.velocityBias);
// Clamp the accumulated impulse
final a = vcp.normalImpulse + lambda;
final newImpulse = a > 0.0 ? a : 0.0;
lambda = newImpulse - vcp.normalImpulse;
vcp.normalImpulse = newImpulse;
// Apply contact impulse
final pX = normalX * lambda;
final pY = normalY * lambda;
vA.x -= pX * mA;
vA.y -= pY * mA;
wA -= iA * (vcp.rA.x * pY - vcp.rA.y * pX);
// vB += invMassB * P;
vB.x += pX * mB;
vB.y += pY * mB;
wB += iB * (vcp.rB.x * pY - vcp.rB.y * pX);
} else {
// Block solver developed in collaboration with Dirk Gregorius
// (back in 01/07 on Box2D_Lite).
// Build the mini LCP for this contact patch
//
// vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0
// with i = 1..2
//
// A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n )
// b = vn_0 - velocityBias
//
// The system is solved using the "Total enumeration method" (s. Murty).
// The complementary constraint vn_i * x_i
// implies that we must have in any solution either vn_i = 0 or x_i = 0.
// So for the 2D contact problem the cases
// vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0
// and vn1 = 0 need to be tested.
// The first valid solution that satisfies the problem is chosen.
//
// In order to account of the accumulated impulse 'a'
// (because of the iterative nature of the solver which only requires
// that the accumulated impulse is clamped and not the incremental
// impulse) we change the impulse variable (x_i).
//
// Substitute:
//
// x = a + d
//
// a := old total impulse
// x := new total impulse
// d := incremental impulse
//
// For the current iteration we extend the formula for the incremental
// impulse to compute the new total impulse:
//
// vn = A * d + b
// = A * (x - a) + b
// = A * x + b - A * a
// = A * x + b'
// b' = b - A * a;
final cp1 = vc.points[0];
final cp2 = vc.points[1];
final cp1rA = cp1.rA;
final cp1rB = cp1.rB;
final cp2rA = cp2.rA;
final cp2rB = cp2.rB;
final ax = cp1.normalImpulse;
final ay = cp2.normalImpulse;
assert(ax >= 0.0 && ay >= 0.0);
// Relative velocity at contact
// Vec2 dv1 = vB + Cross(wB, cp1.rB) - vA - Cross(wA, cp1.rA);
final dv1x = -wB * cp1rB.y + vB.x - vA.x + wA * cp1rA.y;
final dv1y = wB * cp1rB.x + vB.y - vA.y - wA * cp1rA.x;
// Vec2 dv2 = vB + Cross(wB, cp2.rB) - vA - Cross(wA, cp2.rA);
final dv2x = -wB * cp2rB.y + vB.x - vA.x + wA * cp2rA.y;
final dv2y = wB * cp2rB.x + vB.y - vA.y - wA * cp2rA.x;
// Compute normal velocity
var vn1 = dv1x * normalX + dv1y * normalY;
var vn2 = dv2x * normalX + dv2y * normalY;
var bx = vn1 - cp1.velocityBias;
var by = vn2 - cp2.velocityBias;
// Compute b'
final r = vc.K;
bx -= r.entry(0, 0) * ax + r.entry(0, 1) * ay;
by -= r.entry(1, 0) * ax + r.entry(1, 1) * ay;
// final double k_errorTol = 1e-3f;
// B2_NOT_USED(k_errorTol);
for (;;) {
//
// Case 1: vn = 0
//
// 0 = A * x' + b'
//
// Solve for x':
//
// x' = - inv(A) * b'
//
// Vec2 x = - Mul(c.normalMass, b);
final r1 = vc.normalMass;
var xx = r1.entry(0, 0) * bx + r1.entry(0, 1) * by;
var xy = r1.entry(1, 0) * bx + r1.entry(1, 1) * by;
xx *= -1;
xy *= -1;
if (xx >= 0.0 && xy >= 0.0) {
// Get the incremental impulse
final dx = xx - ax;
final dy = xy - ay;
// Apply incremental impulse
final p1x = dx * normalX;
final p1y = dx * normalY;
final p2x = dy * normalX;
final p2y = dy * normalY;
/*
* vA -= invMassA * (P1 + P2); wA -= invIA * (Cross(cp1.rA, P1) +
* Cross(cp2.rA, P2));
*
* vB += invMassB * (P1 + P2); wB += invIB * (Cross(cp1.rB, P1) +
* Cross(cp2.rB, P2));
*/
vA.x -= mA * (p1x + p2x);
vA.y -= mA * (p1y + p2y);
vB.x += mB * (p1x + p2x);
vB.y += mB * (p1y + p2y);
wA -= iA *
(cp1rA.x * p1y -
cp1rA.y * p1x +
(cp2rA.x * p2y - cp2rA.y * p2x));
wB += iB *
(cp1rB.x * p1y -
cp1rB.y * p1x +
(cp2rB.x * p2y - cp2rB.y * p2x));
// Accumulate
cp1.normalImpulse = xx;
cp2.normalImpulse = xy;
// Postconditions
// dv1 = vB + Cross(wB, cp1.rB) - vA - Cross(wA, cp1.rA);
// dv2 = vB + Cross(wB, cp2.rB) - vA - Cross(wA, cp2.rA);
//
// Compute normal velocity
// vn1 = Dot(dv1, normal); vn2 = Dot(dv2, normal);
if (debugSolver) {
// Postconditions
final dv1 = vB + _crossDoubleVector2(wB, cp1rB)
..sub(vA)
..sub(_crossDoubleVector2(wA, cp1rA));
final dv2 = vB + _crossDoubleVector2(wB, cp2rB)
..sub(vA)
..sub(_crossDoubleVector2(wA, cp2rA));
// Compute normal velocity
vn1 = dv1.dot(normal);
vn2 = dv2.dot(normal);
assert((vn1 - cp1.velocityBias).abs() < errorTol);
assert((vn2 - cp2.velocityBias).abs() < errorTol);
}
break;
}
//
// Case 2: vn1 = 0 and x2 = 0
//
// 0 = a11 * x1' + a12 * 0 + b1'
// vn2 = a21 * x1' + a22 * 0 + '
//
xx = -cp1.normalMass * bx;
xy = 0.0;
vn1 = 0.0;
vn2 = vc.K.entry(1, 0) * xx + by;
if (xx >= 0.0 && vn2 >= 0.0) {
// Get the incremental impulse
final dx = xx - ax;
final dy = xy - ay;
// Apply incremental impulse
final p1x = normalX * dx;
final p1y = normalY * dx;
final p2x = normalX * dy;
final p2y = normalY * dy;
// Vec2 P1 = d.x * normal;
// Vec2 P2 = d.y * normal;
// vA -= invMassA * (P1 + P2); wA -=
// invIA * (Cross(cp1.rA, P1) + Cross(cp2.rA, P2));
//
// vB += invMassB * (P1 + P2);
// wB += invIB * (Cross(cp1.rB, P1) + Cross(cp2.rB, P2));
vA.x -= mA * (p1x + p2x);
vA.y -= mA * (p1y + p2y);
vB.x += mB * (p1x + p2x);
vB.y += mB * (p1y + p2y);
wA -= iA *
(cp1rA.x * p1y -
cp1rA.y * p1x +
(cp2rA.x * p2y - cp2rA.y * p2x));
wB += iB *
(cp1rB.x * p1y -
cp1rB.y * p1x +
(cp2rB.x * p2y - cp2rB.y * p2x));
// Accumulate
cp1.normalImpulse = xx;
cp2.normalImpulse = xy;
/*
* #if B2_DEBUG_SOLVER == 1 // Postconditions dv1 = vB + Cross(wB, cp1.rB) - vA -
* Cross(wA, cp1.rA);
*
* // Compute normal velocity vn1 = Dot(dv1, normal);
*
* assert(Abs(vn1 - cp1.velocityBias) < k_errorTol); #endif
*/
if (debugSolver) {
// Postconditions
final dv1 = vB + _crossDoubleVector2(wB, cp1rB)
..sub(vA)
..sub(_crossDoubleVector2(wA, cp1rA));
// Compute normal velocity
vn1 = dv1.dot(normal);
assert((vn1 - cp1.velocityBias).abs() < errorTol);
}
break;
}
//
// Case 3: wB = 0 and x1 = 0
//
// vn1 = a11 * 0 + a12 * x2' + b1'
// 0 = a21 * 0 + a22 * x2' + '
//
xx = 0.0;
xy = -cp2.normalMass * by;
vn1 = vc.K.entry(0, 1) * xy + bx;
vn2 = 0.0;
if (xy >= 0.0 && vn1 >= 0.0) {
// Resubstitute for the incremental impulse
final dx = xx - ax;
final dy = xy - ay;
// Apply incremental impulse
//
// Vec2 P1 = d.x * normal;
// Vec2 P2 = d.y * normal;
// vA -= invMassA * (P1 + P2); wA -=
// invIA * (Cross(cp1.rA, P1) + Cross(cp2.rA, P2));
//
// vB += invMassB * (P1 + P2);
// wB += invIB * (Cross(cp1.rB, P1) + Cross(cp2.rB, P2));
final p1x = normalX * dx;
final p1y = normalY * dx;
final p2x = normalX * dy;
final p2y = normalY * dy;
vA.x -= mA * (p1x + p2x);
vA.y -= mA * (p1y + p2y);
vB.x += mB * (p1x + p2x);
vB.y += mB * (p1y + p2y);
wA -= iA *
(cp1rA.x * p1y -
cp1rA.y * p1x +
(cp2rA.x * p2y - cp2rA.y * p2x));
wB += iB *
(cp1rB.x * p1y -
cp1rB.y * p1x +
(cp2rB.x * p2y - cp2rB.y * p2x));
// Accumulate
cp1.normalImpulse = xx;
cp2.normalImpulse = xy;
/*
* #if B2_DEBUG_SOLVER == 1 // Postconditions dv2 = vB + Cross(wB, cp2.rB) - vA -
* Cross(wA, cp2.rA);
*
* // Compute normal velocity vn2 = Dot(dv2, normal);
*
* assert(Abs(vn2 - cp2.velocityBias) < k_errorTol); #endif
*/
if (debugSolver) {
// Postconditions
final dv2 = vB + _crossDoubleVector2(wB, cp2rB)
..sub(vA)
..sub(_crossDoubleVector2(wA, cp2rA));
// Compute normal velocity
vn2 = dv2.dot(normal);
assert((vn2 - cp2.velocityBias).abs() < errorTol);
}
break;
}
//
// Case 4: x1 = 0 and x2 = 0
//
// vn1 = b1
// vn2 = ;
xx = 0.0;
xy = 0.0;
vn1 = bx;
vn2 = by;
if (vn1 >= 0.0 && vn2 >= 0.0) {
// Resubstitute for the incremental impulse
final dx = xx - ax;
final dy = xy - ay;
// Apply incremental impulse
// Vec2 P1 = d.x * normal;
// Vec2 P2 = d.y * normal;
// vA -= invMassA * (P1 + P2); wA -=
// invIA * (Cross(cp1.rA, P1) + Cross(cp2.rA, P2));
//
// vB += invMassB * (P1 + P2);
// wB += invIB * (Cross(cp1.rB, P1) + Cross(cp2.rB, P2));
final p1x = normalX * dx;
final p1y = normalY * dx;
final p2x = normalX * dy;
final p2y = normalY * dy;
vA.x -= mA * (p1x + p2x);
vA.y -= mA * (p1y + p2y);
vB.x += mB * (p1x + p2x);
vB.y += mB * (p1y + p2y);
wA -= iA *
(cp1rA.x * p1y -
cp1rA.y * p1x +
(cp2rA.x * p2y - cp2rA.y * p2x));
wB += iB *
(cp1rB.x * p1y -
cp1rB.y * p1x +
(cp2rB.x * p2y - cp2rB.y * p2x));
// Accumulate
cp1.normalImpulse = xx;
cp2.normalImpulse = xy;
break;
}
// No solution, give up.
// This is hit sometimes, but it doesn't seem to matter.
break;
}
}
_velocities[indexA].w = wA;
_velocities[indexB].w = wB;
}
}
void storeImpulses() {
for (final contact in _contacts) {
final vc = contact.velocityConstraint;
final manifold = _contacts[vc.contactIndex].manifold;
for (var j = 0; j < vc.pointCount; j++) {
manifold.points[j].normalImpulse = vc.points[j].normalImpulse;
manifold.points[j].tangentImpulse = vc.points[j].tangentImpulse;
}
}
}
final PositionSolverManifold _pSolver = PositionSolverManifold();
/// Sequential solver.
bool solvePositionConstraints() {
var minSeparation = 0.0;
for (final contact in _contacts) {
final pc = contact.positionConstraint;
final indexA = pc.indexA;
final indexB = pc.indexB;
final mA = pc.invMassA;
final iA = pc.invIA;
final localCenterA = pc.localCenterA;
final localCenterAx = localCenterA.x;
final localCenterAy = localCenterA.y;
final mB = pc.invMassB;
final iB = pc.invIB;
final localCenterB = pc.localCenterB;
final localCenterBx = localCenterB.x;
final localCenterBy = localCenterB.y;
final pointCount = pc.pointCount;
final cA = _positions[indexA].c;
var aA = _positions[indexA].a;
final cB = _positions[indexB].c;
var aB = _positions[indexB].a;
// Solve normal constraints
for (var j = 0; j < pointCount; ++j) {
final xfAq = _xfA.q;
final xfBq = _xfB.q;
xfAq.setAngle(aA);
xfBq.setAngle(aB);
_xfA.p.x = cA.x - xfAq.cos * localCenterAx + xfAq.sin * localCenterAy;
_xfA.p.y = cA.y - xfAq.sin * localCenterAx - xfAq.cos * localCenterAy;
_xfB.p.x = cB.x - xfBq.cos * localCenterBx + xfBq.sin * localCenterBy;
_xfB.p.y = cB.y - xfBq.sin * localCenterBx - xfBq.cos * localCenterBy;
final psm = _pSolver;
psm.initialize(pc, _xfA, _xfB, j);
final normal = psm.normal;
final point = psm.point;
final separation = psm.separation;
final rAx = point.x - cA.x;
final rAy = point.y - cA.y;
final rBx = point.x - cB.x;
final rBy = point.y - cB.y;
// Track max constraint error.
minSeparation = min(minSeparation, separation);
// Prevent large corrections and allow slop.
final C = (settings.baumgarte * (separation + settings.linearSlop))
.clamp(-settings.maxLinearCorrection, 0.0);
// Compute the effective mass.
final rnA = rAx * normal.y - rAy * normal.x;
final rnB = rBx * normal.y - rBy * normal.x;
final K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
// Compute normal impulse
final impulse = K > 0.0 ? -C / K : 0.0;
final pX = normal.x * impulse;
final pY = normal.y * impulse;
cA.x -= pX * mA;
cA.y -= pY * mA;
aA -= iA * (rAx * pY - rAy * pX);
cB.x += pX * mB;
cB.y += pY * mB;
aB += iB * (rBx * pY - rBy * pX);
}
_positions[indexA].a = aA;
_positions[indexB].a = aB;
}
// We can't expect minSeparation >= -linearSlop because we don't
// push the separation above -linearSlop.
return minSeparation >= -3.0 * settings.linearSlop;
}
// Sequential position solver for position constraints.
bool solveTOIPositionConstraints(int toiIndexA, int toiIndexB) {
var minSeparation = 0.0;
for (final contact in _contacts) {
final pc = contact.positionConstraint;
final indexA = pc.indexA;
final indexB = pc.indexB;
final localCenterA = pc.localCenterA;
final localCenterB = pc.localCenterB;
final localCenterAx = localCenterA.x;
final localCenterAy = localCenterA.y;
final localCenterBx = localCenterB.x;
final localCenterBy = localCenterB.y;
final pointCount = pc.pointCount;
var mA = 0.0;
var iA = 0.0;
if (indexA == toiIndexA || indexA == toiIndexB) {
mA = pc.invMassA;
iA = pc.invIA;
}
var mB = 0.0;
var iB = 0.0;
if (indexB == toiIndexA || indexB == toiIndexB) {
mB = pc.invMassB;
iB = pc.invIB;
}
final cA = _positions[indexA].c;
var aA = _positions[indexA].a;
final cB = _positions[indexB].c;
var aB = _positions[indexB].a;
// Solve normal constraints
for (var j = 0; j < pointCount; ++j) {
final xfAq = _xfA.q;
final xfBq = _xfB.q;
xfAq.setAngle(aA);
xfBq.setAngle(aB);
_xfA.p.x = cA.x - xfAq.cos * localCenterAx + xfAq.sin * localCenterAy;
_xfA.p.y = cA.y - xfAq.sin * localCenterAx - xfAq.cos * localCenterAy;
_xfB.p.x = cB.x - xfBq.cos * localCenterBx + xfBq.sin * localCenterBy;
_xfB.p.y = cB.y - xfBq.sin * localCenterBx - xfBq.cos * localCenterBy;
final psm = _pSolver;
psm.initialize(pc, _xfA, _xfB, j);
final normal = psm.normal;
final point = psm.point;
final separation = psm.separation;
final rAx = point.x - cA.x;
final rAy = point.y - cA.y;
final rBx = point.x - cB.x;
final rBy = point.y - cB.y;
// Track max constraint error.
minSeparation = min(minSeparation, separation);
// Prevent large corrections and allow slop.
final C = (settings.baumgarte * (separation + settings.linearSlop))
.clamp(-settings.maxLinearCorrection, 0.0);
// Compute the effective mass.
final rnA = rAx * normal.y - rAy * normal.x;
final rnB = rBx * normal.y - rBy * normal.x;
final k = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
// Compute normal impulse
final impulse = k > 0.0 ? -C / k : 0.0;
final pX = normal.x * impulse;
final pY = normal.y * impulse;
cA.x -= pX * mA;
cA.y -= pY * mA;
aA -= iA * (rAx * pY - rAy * pX);
cB.x += pX * mB;
cB.y += pY * mB;
aB += iB * (rBx * pY - rBy * pX);
}
_positions[indexA].a = aA;
_positions[indexB].a = aB;
}
// We can't expect minSeparation >= -_linearSlop because we don't
// push the separation above -_linearSlop.
return minSeparation >= -1.5 * settings.linearSlop;
}
Vector2 _crossDoubleVector2(double s, Vector2 a) {
return Vector2(-s * a.y, s * a.x);
}
}
class PositionSolverManifold {
final Vector2 normal = Vector2.zero();
final Vector2 point = Vector2.zero();
double separation = 0.0;
void initialize(
ContactPositionConstraint pc,
Transform xfA,
Transform xfB,
int index,
) {
assert(pc.pointCount > 0);
final xfAq = xfA.q;
final xfBq = xfB.q;
final pcLocalPointsI = pc.localPoints[index];
switch (pc.type) {
case ManifoldType.circles:
final pLocalPoint = pc.localPoint;
final pLocalPoints0 = pc.localPoints[0];
final pointAx =
(xfAq.cos * pLocalPoint.x - xfAq.sin * pLocalPoint.y) + xfA.p.x;
final pointAy =
(xfAq.sin * pLocalPoint.x + xfAq.cos * pLocalPoint.y) + xfA.p.y;
final pointBx =
(xfBq.cos * pLocalPoints0.x - xfBq.sin * pLocalPoints0.y) + xfB.p.x;
final pointBy =
(xfBq.sin * pLocalPoints0.x + xfBq.cos * pLocalPoints0.y) + xfB.p.y;
normal.x = pointBx - pointAx;
normal.y = pointBy - pointAy;
normal.normalize();
point.x = (pointAx + pointBx) * .5;
point.y = (pointAy + pointBy) * .5;
final tempX = pointBx - pointAx;
final tempY = pointBy - pointAy;
separation =
tempX * normal.x + tempY * normal.y - pc.radiusA - pc.radiusB;
break;
case ManifoldType.faceA:
final pcLocalNormal = pc.localNormal;
final pcLocalPoint = pc.localPoint;
normal.x = xfAq.cos * pcLocalNormal.x - xfAq.sin * pcLocalNormal.y;
normal.y = xfAq.sin * pcLocalNormal.x + xfAq.cos * pcLocalNormal.y;
final planePointX =
(xfAq.cos * pcLocalPoint.x - xfAq.sin * pcLocalPoint.y) + xfA.p.x;
final planePointY =
(xfAq.sin * pcLocalPoint.x + xfAq.cos * pcLocalPoint.y) + xfA.p.y;
final clipPointX =
(xfBq.cos * pcLocalPointsI.x - xfBq.sin * pcLocalPointsI.y) +
xfB.p.x;
final clipPointY =
(xfBq.sin * pcLocalPointsI.x + xfBq.cos * pcLocalPointsI.y) +
xfB.p.y;
final tempX = clipPointX - planePointX;
final tempY = clipPointY - planePointY;
separation =
tempX * normal.x + tempY * normal.y - pc.radiusA - pc.radiusB;
point.x = clipPointX;
point.y = clipPointY;
break;
case ManifoldType.faceB:
final pcLocalNormal = pc.localNormal;
final pcLocalPoint = pc.localPoint;
normal.x = xfBq.cos * pcLocalNormal.x - xfBq.sin * pcLocalNormal.y;
normal.y = xfBq.sin * pcLocalNormal.x + xfBq.cos * pcLocalNormal.y;
final planePointX =
(xfBq.cos * pcLocalPoint.x - xfBq.sin * pcLocalPoint.y) + xfB.p.x;
final planePointY =
(xfBq.sin * pcLocalPoint.x + xfBq.cos * pcLocalPoint.y) + xfB.p.y;
final clipPointX =
(xfAq.cos * pcLocalPointsI.x - xfAq.sin * pcLocalPointsI.y) +
xfA.p.x;
final clipPointY =
(xfAq.sin * pcLocalPointsI.x + xfAq.cos * pcLocalPointsI.y) +
xfA.p.y;
final tempX = clipPointX - planePointX;
final tempY = clipPointY - planePointY;
separation =
tempX * normal.x + tempY * normal.y - pc.radiusA - pc.radiusB;
point.x = clipPointX;
point.y = clipPointY;
normal.x *= -1;
normal.y *= -1;
break;
}
}
}
| forge2d/packages/forge2d/lib/src/dynamics/contacts/contact_solver.dart/0 | {'file_path': 'forge2d/packages/forge2d/lib/src/dynamics/contacts/contact_solver.dart', 'repo_id': 'forge2d', 'token_count': 17689} |
import 'package:forge2d/forge2d.dart';
/// Distance joint definition. This requires defining an anchor point on both
/// bodies and the non-zero length of the distance joint. The definition uses
/// local anchor points so that the initial configuration can violate the
/// constraint slightly. This helps when saving and loading a game.
///
/// Warning: Do not use a zero or short length.
class DistanceJointDef<A extends Body, B extends Body> extends JointDef<A, B> {
/// The equilibrium length between the anchor points.
double length = 1.0;
/// The mass-spring-damper frequency in Hertz.
double frequencyHz = 0.0;
/// The damping ratio. 0 = no damping, 1 = critical damping.
double dampingRatio = 0.0;
/// Initialize the bodies, anchors, and length using the world anchors.
void initialize(A body1, B body2, Vector2 anchor1, Vector2 anchor2) {
bodyA = body1;
bodyB = body2;
localAnchorA.setFrom(bodyA.localPoint(anchor1));
localAnchorB.setFrom(bodyB.localPoint(anchor2));
final d = anchor2 - anchor1;
length = d.length;
}
}
| forge2d/packages/forge2d/lib/src/dynamics/joints/distance_joint_def.dart/0 | {'file_path': 'forge2d/packages/forge2d/lib/src/dynamics/joints/distance_joint_def.dart', 'repo_id': 'forge2d', 'token_count': 326} |
import 'package:forge2d/forge2d.dart';
import 'package:forge2d/src/settings.dart' as settings;
/// Pulley joint definition. This requires two ground anchors, two dynamic body
/// anchor points, and a pulley ratio.
class PulleyJointDef<A extends Body, B extends Body> extends JointDef<A, B> {
/// The first ground anchor in world coordinates. This point never moves.
Vector2 groundAnchorA = Vector2(-1.0, 1.0);
/// The second ground anchor in world coordinates. This point never moves.
Vector2 groundAnchorB = Vector2(1.0, 1.0);
/// The a reference length for the segment attached to bodyA.
double lengthA = 0.0;
/// The a reference length for the segment attached to bodyB.
double lengthB = 0.0;
/// The pulley ratio, used to simulate a block-and-tackle.
double ratio = 1.0;
PulleyJointDef() : super(collideConnected: true);
/// Initialize the bodies, anchors, lengths, max lengths, and ratio using the
/// world anchors.
void initialize(
A b1,
B b2,
Vector2 ga1,
Vector2 ga2,
Vector2 anchor1,
Vector2 anchor2,
double r,
) {
bodyA = b1;
bodyB = b2;
groundAnchorA = ga1;
groundAnchorB = ga2;
localAnchorA.setFrom(bodyA.localPoint(anchor1));
localAnchorB.setFrom(bodyB.localPoint(anchor2));
final d1 = anchor1 - ga1;
lengthA = d1.length;
final d2 = anchor2 - ga2;
lengthB = d2.length;
ratio = r;
assert(ratio > settings.epsilon);
}
}
| forge2d/packages/forge2d/lib/src/dynamics/joints/pulley_joint_def.dart/0 | {'file_path': 'forge2d/packages/forge2d/lib/src/dynamics/joints/pulley_joint_def.dart', 'repo_id': 'forge2d', 'token_count': 522} |
import 'package:forge2d/forge2d.dart';
class ParticleContact {
/// The respective particles making contact.
Particle particleA;
Particle particleB;
ParticleContact(this.particleA, this.particleB);
/// The logical sum of the particle behaviors that have been set.
int flags = 0;
/// Weight of the contact. A value between 0.0f and 1.0f.
double weight = 0.0;
/// The normalized direction from A to B.
final Vector2 normal = Vector2.zero();
}
| forge2d/packages/forge2d/lib/src/particle/particle_contact.dart/0 | {'file_path': 'forge2d/packages/forge2d/lib/src/particle/particle_contact.dart', 'repo_id': 'forge2d', 'token_count': 141} |
import 'package:forge2d/forge2d.dart';
import 'package:test/test.dart';
void main() {
group('DistanceJointDef', () {
test('can be instantiated', () {
expect(DistanceJointDef(), isA<DistanceJointDef>());
});
});
}
| forge2d/packages/forge2d/test/dynamics/joints/distance_joint_def_test.dart/0 | {'file_path': 'forge2d/packages/forge2d/test/dynamics/joints/distance_joint_def_test.dart', 'repo_id': 'forge2d', 'token_count': 90} |
import 'package:forge2d/forge2d.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
class _MockBody extends Mock implements Body {}
class _MockDebugDraw extends Mock implements DebugDraw {}
void main() {
group('RevoluteJoint', () {
late RevoluteJointDef jointDef;
setUp(() {
jointDef = RevoluteJointDef()
..bodyA = _MockBody()
..bodyB = _MockBody();
});
test('can be instantiated', () {
expect(RevoluteJoint(jointDef), isA<RevoluteJoint>());
});
group('motorSpeed', () {
test('can change motor speed', () {
final joint = RevoluteJoint(jointDef);
final oldMotorSpeed = joint.motorSpeed;
final newMotorSpeed = oldMotorSpeed + 1;
joint.motorSpeed = newMotorSpeed;
expect(joint.motorSpeed, equals(newMotorSpeed));
});
test('wakes up both bodies', () {
final joint = RevoluteJoint(jointDef);
joint.motorSpeed = 1;
verify(() => joint.bodyA.setAwake(true)).called(1);
verify(() => joint.bodyB.setAwake(true)).called(1);
});
});
group('render', () {
late DebugDraw debugDraw;
setUp(() {
debugDraw = _MockDebugDraw();
registerFallbackValue(Vector2.zero());
registerFallbackValue(Color3i.black());
});
test('draws three segments', () {
final joint = RevoluteJoint(jointDef);
when(() => joint.bodyA.transform).thenReturn(Transform.zero());
when(() => joint.bodyB.transform).thenReturn(Transform.zero());
when(() => joint.bodyA.worldPoint(any())).thenReturn(Vector2.zero());
when(() => joint.bodyB.worldPoint(any())).thenReturn(Vector2.zero());
joint.render(debugDraw);
verify(() => debugDraw.drawSegment(any(), any(), any())).called(3);
});
});
});
}
| forge2d/packages/forge2d/test/dynamics/joints/revolute_joint_test.dart/0 | {'file_path': 'forge2d/packages/forge2d/test/dynamics/joints/revolute_joint_test.dart', 'repo_id': 'forge2d', 'token_count': 763} |
analyzer:
exclude:
- "**/*.g.dart"
language:
strict-casts: true
strict-inference: true
strict-raw-types: true
errors:
invalid_annotation_target: ignore
linter:
rules:
# - public_member_api_docs
- annotate_overrides
- avoid_empty_else
- avoid_function_literals_in_foreach_calls
- avoid_init_to_null
- avoid_null_checks_in_equality_operators
- avoid_relative_lib_imports
# - avoid_renaming_method_parameters
- use_function_type_syntax_for_parameters
- avoid_return_types_on_setters
- avoid_returning_null
- avoid_types_as_parameter_names
- avoid_unused_constructor_parameters
- await_only_futures
- camel_case_types
- cancel_subscriptions
- cascade_invocations
- comment_references
- constant_identifier_names
- control_flow_in_finally
- directives_ordering
- empty_catches
- empty_constructor_bodies
- empty_statements
- hash_and_equals
- implementation_imports
# Deprecated rule
# - invariant_booleans
- collection_methods_unrelated_type
- library_names
- library_prefixes
# - lines_longer_than_80_chars
- no_adjacent_strings_in_list
- no_duplicate_case_values
- non_constant_identifier_names
- null_closures
- omit_local_variable_types
- only_throw_errors
- overridden_fields
- package_api_docs
- package_names
- package_prefixed_library_names
- prefer_adjacent_string_concatenation
- prefer_collection_literals
- prefer_conditional_assignment
- prefer_const_constructors
- prefer_contains
- prefer_equal_for_default_values
- prefer_final_fields
- prefer_initializing_formals
- prefer_interpolation_to_compose_strings
- prefer_is_empty
- prefer_is_not_empty
- prefer_single_quotes
- prefer_typing_uninitialized_variables
- recursive_getters
- slash_for_doc_comments
- test_types_in_equals
- throw_in_finally
- type_init_formals
- unawaited_futures
- unnecessary_brace_in_string_interps
- unnecessary_const
- unnecessary_getters_setters
- unnecessary_lambdas
- unnecessary_new
- unnecessary_null_aware_assignments
- unnecessary_statements
- unnecessary_this
- unrelated_type_equality_checks
- use_rethrow_when_possible
- valid_regexps
- cast_nullable_to_non_nullable
| freezed/packages/freezed/analysis_options.yaml/0 | {'file_path': 'freezed/packages/freezed/analysis_options.yaml', 'repo_id': 'freezed', 'token_count': 942} |
import 'package:analyzer/dart/analysis/results.dart';
import 'package:build_test/build_test.dart';
import 'package:test/test.dart';
import 'integration/bidirectional.dart';
void main() {
test('has no issue', () async {
final main = await resolveSources(
{
'freezed|test/integration/bidirectional.dart': useAssetReader,
},
(r) => r.libraries.firstWhere(
(element) => element.source.toString().contains('bidirectional')),
);
final errorResult = await main.session
.getErrors('/freezed/test/integration/bidirectional.freezed.dart')
as ErrorsResult;
expect(errorResult.errors, isEmpty);
});
test('bidirectional deep_copy', () {
final person = Person(
name: 'Adam',
age: 36,
appointment: Appointment(
title: 'Some Appointment',
creator: Person(
name: 'Bob',
age: 24,
appointment: Appointment(
title: 'Other Appointment',
),
),
),
);
expect(
person.copyWith.appointment!.creator!(name: 'Steve'),
Person(
name: 'Adam',
age: 36,
appointment: Appointment(
title: 'Some Appointment',
creator: Person(
name: 'Steve',
age: 24,
appointment: Appointment(
title: 'Other Appointment',
),
),
),
),
);
expect(
person.copyWith.appointment!.creator!.appointment!(
title: 'Some New Appointment',
),
Person(
name: 'Adam',
age: 36,
appointment: Appointment(
title: 'Some Appointment',
creator: Person(
name: 'Bob',
age: 24,
appointment: Appointment(
title: 'Some New Appointment',
),
),
),
),
);
});
}
| freezed/packages/freezed/test/bidirectional_test.dart/0 | {'file_path': 'freezed/packages/freezed/test/bidirectional_test.dart', 'repo_id': 'freezed', 'token_count': 904} |
import 'package:freezed_annotation/freezed_annotation.dart';
part 'common_types.freezed.dart';
@freezed
class Union with _$Union {
factory Union.foo({int? arg}) = _UnionFoo;
factory Union.bar({required int arg}) = _UnionBar;
}
@freezed
class Union2 with _$Union2 {
factory Union2.foo({required int arg}) = _Union2Foo;
factory Union2.bar({double? arg}) = _Union2Bar;
}
@freezed
class Union3 with _$Union3 {
factory Union3.bar({double? arg}) = _Union3Bar;
factory Union3.foo({required int arg}) = _Union3Foo;
}
@freezed
class Union4 with _$Union4 {
factory Union4.eventOne({
required int count,
required String? id,
required String? name,
}) = Union4One;
factory Union4.eventTwo({
required int? count,
required String id,
required String name,
}) = Union4Two;
}
@freezed
class Union5 with _$Union5 {
factory Union5.first(int value) = _Union5First;
factory Union5.second(double? value) = _Union5Second;
factory Union5.third(String value) = _Union5Third;
}
@freezed
class UnionDeepCopy with _$UnionDeepCopy {
factory UnionDeepCopy.first(CommonSuperSubtype value42) = _UnionWrapperFirst;
factory UnionDeepCopy.second(CommonSuperSubtype? value42) =
_UnionWrapperSecond;
}
@freezed
class Check with _$Check {
factory Check.first({required dynamic value}) = _CheckFirst; // NOT OK
factory Check.second({required int value}) = _CheckSecond; // OK
factory Check.third({required double value}) = _CheckThird; // OK
factory Check.fourth({required dynamic value}) = _CheckFourth; // OK
}
@freezed
class CommonSuperSubtype with _$CommonSuperSubtype {
const factory CommonSuperSubtype({
required int nullabilityDifference,
required int typeDifference,
String? unknown,
}) = CommonSuperSubtype0;
const factory CommonSuperSubtype.named({
required int? nullabilityDifference,
required double typeDifference,
}) = CommonSuperSubtype1;
}
@freezed
class DeepCopySharedProperties with _$DeepCopySharedProperties {
const factory DeepCopySharedProperties(CommonSuperSubtype value) =
_DeepCopySharedProperties;
}
@unfreezed
class CommonUnfreezed with _$CommonUnfreezed {
factory CommonUnfreezed.one({required int a, required double b}) =
CommonUnfreezedOne;
factory CommonUnfreezed.two({required num a, required double b}) =
CommonUnfreezedTwo;
}
// Checking that the constructor order does not matter
@unfreezed
class CommonUnfreezed2 with _$CommonUnfreezed2 {
factory CommonUnfreezed2.two({required num a, required double b}) =
CommonUnfreezedTwo2;
factory CommonUnfreezed2.one({required int a, required double b}) =
CommonUnfreezedOne2;
}
| freezed/packages/freezed/test/integration/common_types.dart/0 | {'file_path': 'freezed/packages/freezed/test/integration/common_types.dart', 'repo_id': 'freezed', 'token_count': 874} |
import 'package:freezed_annotation/freezed_annotation.dart';
part 'json.freezed.dart';
part 'json.g.dart';
@freezed
class NoWhen with _$NoWhen {
factory NoWhen({int? first}) = _NoWhen;
factory NoWhen.fromJson(Map<String, dynamic> json) => _$NoWhenFromJson(json);
}
abstract class Base {}
const unionMixin = _$UnionJsonWithExtends;
const unionFirstBase = _$UnionJsonFirstWithExtendsImpl;
const unionSecondBase = _$UnionJsonSecondWithExtendsImpl;
const unionJson = _$UnionJsonWithExtendsFromJson;
@freezed
class UnionJsonWithExtends extends Base with _$UnionJsonWithExtends {
UnionJsonWithExtends._();
factory UnionJsonWithExtends.first({int? first}) = _UnionJsonFirstWithExtends;
factory UnionJsonWithExtends.second({int? second}) =
_UnionJsonSecondWithExtends;
factory UnionJsonWithExtends.fromJson(Map<String, dynamic> json) =>
_$UnionJsonWithExtendsFromJson(json);
}
const pUnionMixin = _$PUnionJsonWithExtends;
const pUnionFirstBase = _$PUnionJsonFirstWithExtendsImpl;
const pUnionSecondBase = _$PUnionJsonSecondWithExtendsImpl;
const pUnionJson = _$PUnionJsonWithExtendsFromJson;
@freezed
class _PUnionJsonWithExtends extends Base with _$PUnionJsonWithExtends {
_PUnionJsonWithExtends._();
// ignore: unused_element
factory _PUnionJsonWithExtends.first({int? first}) =
_PUnionJsonFirstWithExtends;
// ignore: unused_element
factory _PUnionJsonWithExtends.second({int? second}) =
_PUnionJsonSecondWithExtends;
// ignore: unused_element
factory _PUnionJsonWithExtends.fromJson(Map<String, dynamic> json) =>
_$PUnionJsonWithExtendsFromJson(json);
}
// regression test for https://github.com/rrousselGit/freezed/issues/409
@freezed
class Regression409 with _$Regression409 {
factory Regression409({
dynamic totalResults,
}) = _Regression409;
factory Regression409.fromJson(Map<String, dynamic> json) =>
_$Regression409FromJson(json);
}
// regression test for https://github.com/rrousselGit/freezed/issues/351
@freezed
class Regression351 with _$Regression351 {
factory Regression351({
@JsonKey(name: 'total_results') required int totalResults,
}) = _Regression351;
factory Regression351.fromJson(Map<String, dynamic> json) =>
_$Regression351FromJson(json);
}
// regression test for https://github.com/rrousselGit/freezed/issues/323
@freezed
class Regression323 with _$Regression323 {
const factory Regression323({
required String id,
required num amount,
}) = _Regression323;
factory Regression323.fromJson(Map<String, dynamic> json) =>
_$Regression323FromJson(json);
factory Regression323.unknown(num amount) => Regression323(
id: '',
amount: amount,
);
}
// regression test for https://github.com/rrousselGit/freezed/issues/280
@freezed
class Regression280 with _$Regression280 {
const factory Regression280(String label) = _Regression280;
factory Regression280.fromJson(Map<String, dynamic> val) {
return Regression280(val['foo'] as String);
}
}
@freezed
class Regression280n2 with _$Regression280n2 {
const factory Regression280n2(String label) = _Regression280n2;
factory Regression280n2.fromJson(String val) {
return Regression280n2(val);
}
}
CustomJson _fromJson(Map<String, dynamic> json) {
return _$CustomJsonFromJson(<String, dynamic>{
'label': json['key'],
});
}
@freezed
class CustomJson with _$CustomJson {
const factory CustomJson(String label) = _CustomJson;
factory CustomJson.fromJson(Map<String, dynamic> json) => _fromJson(json);
}
@Freezed(unionKey: 'ty"\'pe')
class FancyCustomKey with _$FancyCustomKey {
const factory FancyCustomKey.first(int a) = _FancyCustomKeyFirst;
const factory FancyCustomKey.second(int a) = _FancyCustomKeySecond;
factory FancyCustomKey.fromJson(Map<String, dynamic> json) =>
_$FancyCustomKeyFromJson(json);
}
@freezed
class PositonalOptional with _$PositonalOptional {
const factory PositonalOptional.first([int? a]) = _PositonalOptionalFirst;
const factory PositonalOptional.second([int? a]) = _PositonalOptionalSecond;
factory PositonalOptional.fromJson(Map<String, dynamic> json) =>
_$PositonalOptionalFromJson(json);
}
@Freezed(unionKey: r'$type')
class RawCustomKey with _$RawCustomKey {
const factory RawCustomKey.first(int a) = _RawCustomKeyFirst;
const factory RawCustomKey.second(int a) = _RawCustomKeySecond;
factory RawCustomKey.fromJson(Map<String, dynamic> json) =>
_$RawCustomKeyFromJson(json);
}
@Freezed(unionKey: 'type')
class CustomKey with _$CustomKey {
const factory CustomKey.first(int a) = _CustomKeyFirst;
const factory CustomKey.second(int a) = _CustomKeySecond;
factory CustomKey.fromJson(Map<String, dynamic> json) =>
_$CustomKeyFromJson(json);
}
@freezed
class CustomUnionValue with _$CustomUnionValue {
const factory CustomUnionValue.first(int a) = _CustomUnionValueFirst;
@FreezedUnionValue('SECOND')
const factory CustomUnionValue.second(int a) = _CustomUnionValueSecond;
factory CustomUnionValue.fromJson(Map<String, dynamic> json) =>
_$CustomUnionValueFromJson(json);
}
@Freezed(fallbackUnion: 'fallback')
class UnionFallback with _$UnionFallback {
const factory UnionFallback.first(int a) = _UnionFallbackFirst;
const factory UnionFallback.second(int a) = _UnionFallbackSecond;
const factory UnionFallback.fallback(int a) = _UnionFallbackFallback;
factory UnionFallback.fromJson(Map<String, dynamic> json) =>
_$UnionFallbackFromJson(json);
}
@Freezed(fallbackUnion: 'default')
class UnionDefaultFallback with _$UnionDefaultFallback {
const factory UnionDefaultFallback(int a) = _UnionDefaultFallback;
const factory UnionDefaultFallback.first(int a) = _UnionDefaultFallbackFirst;
const factory UnionDefaultFallback.second(int a) =
_UnionDefaultFallbackSecond;
factory UnionDefaultFallback.fromJson(Map<String, dynamic> json) =>
_$UnionDefaultFallbackFromJson(json);
}
@Freezed(unionKey: 'key', fallbackUnion: 'default')
class UnionKeyDefaultFallback with _$UnionKeyDefaultFallback {
const factory UnionKeyDefaultFallback(String key) = _UnionKeyDefaultFallback;
const factory UnionKeyDefaultFallback.first(String key) =
_UnionKeyDefaultFallbackFirst;
factory UnionKeyDefaultFallback.fromJson(Map<String, dynamic> json) =>
_$UnionKeyDefaultFallbackFromJson(json);
}
@Freezed(unionValueCase: FreezedUnionCase.pascal)
class UnionValueCasePascal with _$UnionValueCasePascal {
const factory UnionValueCasePascal.first(int a) = _UnionValueCasePascalFirst;
const factory UnionValueCasePascal.secondValue(int a) =
_UnionValueCasePascalSecondValue;
factory UnionValueCasePascal.fromJson(Map<String, dynamic> json) =>
_$UnionValueCasePascalFromJson(json);
}
@Freezed(unionValueCase: FreezedUnionCase.kebab)
class UnionValueCaseKebab with _$UnionValueCaseKebab {
const factory UnionValueCaseKebab.first(int a) = _UnionValueCaseKebabFirst;
const factory UnionValueCaseKebab.secondValue(int a) =
_UnionValueCaseKebabSecondValue;
factory UnionValueCaseKebab.fromJson(Map<String, dynamic> json) =>
_$UnionValueCaseKebabFromJson(json);
}
@Freezed(unionValueCase: FreezedUnionCase.snake)
class UnionValueCaseSnake with _$UnionValueCaseSnake {
const factory UnionValueCaseSnake.first(int a) = _UnionValueCaseSnakeFirst;
const factory UnionValueCaseSnake.secondValue(int a) =
_UnionValueCaseSnakeSecondValue;
factory UnionValueCaseSnake.fromJson(Map<String, dynamic> json) =>
_$UnionValueCaseSnakeFromJson(json);
}
@Freezed(unionValueCase: FreezedUnionCase.screamingSnake)
class UnionValueCaseScreamingSnake with _$UnionValueCaseScreamingSnake {
const factory UnionValueCaseScreamingSnake.first(int a) =
_UnionValueCaseScreamingSnakeFirst;
const factory UnionValueCaseScreamingSnake.secondValue(int a) =
_UnionValueCaseScreamingSnakeSecondValue;
factory UnionValueCaseScreamingSnake.fromJson(Map<String, dynamic> json) =>
_$UnionValueCaseScreamingSnakeFromJson(json);
}
@Freezed(unionKey: 'runtimeType')
class RuntimeTypeKey with _$RuntimeTypeKey {
const factory RuntimeTypeKey.first(int a) = _RuntimeTypeKeyFirst;
const factory RuntimeTypeKey.second(int a) = _RuntimeTypeKeySecond;
factory RuntimeTypeKey.fromJson(Map<String, dynamic> json) =>
_$RuntimeTypeKeyFromJson(json);
}
@Freezed(unionKey: r'$runtimeType')
class RawRuntimeTypeKey with _$RawRuntimeTypeKey {
const factory RawRuntimeTypeKey.first(int a) = _RawRuntimeTypeKeyFirst;
const factory RawRuntimeTypeKey.second(int a) = _RawRuntimeTypeKeySecond;
factory RawRuntimeTypeKey.fromJson(Map<String, dynamic> json) =>
_$RawRuntimeTypeKeyFromJson(json);
}
@Freezed(unionKey: 'run"\'timeType')
class FancyRuntimeTypeKey with _$FancyRuntimeTypeKey {
const factory FancyRuntimeTypeKey.first(int a) = _FancyRuntimeTypeKeyFirst;
const factory FancyRuntimeTypeKey.second(int a) = _FancyRuntimeTypeKeySecond;
factory FancyRuntimeTypeKey.fromJson(Map<String, dynamic> json) =>
_$FancyRuntimeTypeKeyFromJson(json);
}
@Freezed(unionKey: 'runtimeType')
class RuntimeTypeUnrecognizedKeys with _$RuntimeTypeUnrecognizedKeys {
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory RuntimeTypeUnrecognizedKeys.first(int a) =
_RuntimeTypeUnrecognizedKeysFirst;
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory RuntimeTypeUnrecognizedKeys.second(int a) =
_RuntimeTypeUnrecognizedKeysSecond;
factory RuntimeTypeUnrecognizedKeys.fromJson(Map<String, dynamic> json) =>
_$RuntimeTypeUnrecognizedKeysFromJson(json);
}
@Freezed(unionKey: r'$runtimeType')
class RuntimeTypeRawCustomKey with _$RuntimeTypeRawCustomKey {
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory RuntimeTypeRawCustomKey.first(int a) =
_RuntimeTypeRawCustomKeyFirst;
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory RuntimeTypeRawCustomKey.second(int a) =
_RuntimeTypeRawCustomKeySecond;
factory RuntimeTypeRawCustomKey.fromJson(Map<String, dynamic> json) =>
_$RuntimeTypeRawCustomKeyFromJson(json);
}
@Freezed(unionKey: 'ty"\'pe')
class UnrecognizedKeysFancyCustomKey with _$UnrecognizedKeysFancyCustomKey {
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysFancyCustomKey.first(int a) =
_UnrecognizedKeysFancyCustomKeyFirst;
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysFancyCustomKey.second(int a) =
_UnrecognizedKeysFancyCustomKeySecond;
factory UnrecognizedKeysFancyCustomKey.fromJson(Map<String, dynamic> json) =>
_$UnrecognizedKeysFancyCustomKeyFromJson(json);
}
@Freezed(unionKey: r'$type')
class UnrecognizedKeysRawCustomKey with _$UnrecognizedKeysRawCustomKey {
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysRawCustomKey.first(int a) =
_UnrecognizedKeysRawCustomKeyFirst;
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysRawCustomKey.second(int a) =
_UnrecognizedKeysRawCustomKeySecond;
factory UnrecognizedKeysRawCustomKey.fromJson(Map<String, dynamic> json) =>
_$UnrecognizedKeysRawCustomKeyFromJson(json);
}
@Freezed(unionKey: 'type')
class UnrecognizedKeysCustomKey with _$UnrecognizedKeysCustomKey {
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysCustomKey.first(int a) =
_UnrecognizedKeysCustomKeyFirst;
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysCustomKey.second(int a) =
_UnrecognizedKeysCustomKeySecond;
factory UnrecognizedKeysCustomKey.fromJson(Map<String, dynamic> json) =>
_$UnrecognizedKeysCustomKeyFromJson(json);
}
@freezed
class UnrecognizedKeysCustomUnionValue with _$UnrecognizedKeysCustomUnionValue {
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysCustomUnionValue.first(int a) =
_UnrecognizedKeysCustomUnionValueFirst;
@JsonSerializable(disallowUnrecognizedKeys: true)
@FreezedUnionValue('SECOND')
const factory UnrecognizedKeysCustomUnionValue.second(int a) =
UnrecognizedKeys_CustomUnionValueSecond;
factory UnrecognizedKeysCustomUnionValue.fromJson(
Map<String, dynamic> json) =>
_$UnrecognizedKeysCustomUnionValueFromJson(json);
}
@Freezed(fallbackUnion: 'fallback')
class UnrecognizedKeysUnionFallback with _$UnrecognizedKeysUnionFallback {
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysUnionFallback.first(int a) =
_UnrecognizedKeysUnionFallbackFirst;
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysUnionFallback.second(int a) =
_UnrecognizedKeysUnionFallbackSecond;
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysUnionFallback.fallback(int a) =
_UnrecognizedKeysUnionFallbackFallback;
factory UnrecognizedKeysUnionFallback.fromJson(Map<String, dynamic> json) =>
_$UnrecognizedKeysUnionFallbackFromJson(json);
}
@Freezed(fallbackUnion: 'default')
class UnrecognizedKeysUnionDefaultFallback
with _$UnrecognizedKeysUnionDefaultFallback {
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysUnionDefaultFallback(int a) =
_UnrecognizedKeysUnionDefaultFallback;
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysUnionDefaultFallback.first(int a) =
_UnrecognizedKeysUnionDefaultFallbackFirst;
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysUnionDefaultFallback.second(int a) =
_UnrecognizedKeysUnionDefaultFallbackSecond;
factory UnrecognizedKeysUnionDefaultFallback.fromJson(
Map<String, dynamic> json) =>
_$UnrecognizedKeysUnionDefaultFallbackFromJson(json);
}
@Freezed(unionValueCase: FreezedUnionCase.pascal)
class UnrecognizedKeysUnionValueCasePascal
with _$UnrecognizedKeysUnionValueCasePascal {
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysUnionValueCasePascal.first(int a) =
_UnrecognizedKeysUnionValueCasePascalFirst;
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysUnionValueCasePascal.secondValue(int a) =
_UnrecognizedKeysUnionValueCasePascalSecondValue;
factory UnrecognizedKeysUnionValueCasePascal.fromJson(
Map<String, dynamic> json) =>
_$UnrecognizedKeysUnionValueCasePascalFromJson(json);
}
@Freezed(unionValueCase: FreezedUnionCase.kebab)
class UnrecognizedKeysUnionValueCaseKebab
with _$UnrecognizedKeysUnionValueCaseKebab {
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysUnionValueCaseKebab.first(int a) =
_UnrecognizedKeysUnionValueCaseKebabFirst;
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysUnionValueCaseKebab.secondValue(int a) =
_UnrecognizedKeysUnionValueCaseKebabSecondValue;
factory UnrecognizedKeysUnionValueCaseKebab.fromJson(
Map<String, dynamic> json) =>
_$UnrecognizedKeysUnionValueCaseKebabFromJson(json);
}
@Freezed(unionValueCase: FreezedUnionCase.snake)
class UnrecognizedKeysUnionValueCaseSnake
with _$UnrecognizedKeysUnionValueCaseSnake {
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysUnionValueCaseSnake.first(int a) =
_UnrecognizedKeysUnionValueCaseSnakeFirst;
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysUnionValueCaseSnake.secondValue(int a) =
_UnrecognizedKeysUnionValueCaseSnakeSecondValue;
factory UnrecognizedKeysUnionValueCaseSnake.fromJson(
Map<String, dynamic> json) =>
_$UnrecognizedKeysUnionValueCaseSnakeFromJson(json);
}
@Freezed(unionValueCase: FreezedUnionCase.screamingSnake)
class UnrecognizedKeysUnionValueCaseScreamingSnake
with _$UnrecognizedKeysUnionValueCaseScreamingSnake {
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysUnionValueCaseScreamingSnake.first(int a) =
_UnrecognizedKeysUnionValueCaseScreamingSnakeFirst;
@JsonSerializable(disallowUnrecognizedKeys: true)
const factory UnrecognizedKeysUnionValueCaseScreamingSnake.secondValue(
int a) = _UnrecognizedKeysUnionValueCaseScreamingSnakeSecondValue;
factory UnrecognizedKeysUnionValueCaseScreamingSnake.fromJson(
Map<String, dynamic> json) =>
_$UnrecognizedKeysUnionValueCaseScreamingSnakeFromJson(json);
}
@freezed
class Single with _$Single {
const factory Single(int a) = _Single;
factory Single.fromJson(Map<String, dynamic> json) => _$SingleFromJson(json);
}
@freezed
class Json with _$Json {
const factory Json() = JsonDefault;
const factory Json.first(String a) = First;
const factory Json.second(int b) = Second;
factory Json.fromJson(Map<String, dynamic> json) => _$JsonFromJson(json);
}
@freezed
class NoJson with _$NoJson {
const factory NoJson() = NoDefault;
const factory NoJson.first(String a) = NoFirst;
const factory NoJson.second(int b) = NoSecond;
}
@freezed
class Decorator with _$Decorator {
factory Decorator(@JsonKey(name: 'what') String a) = _Decorator;
factory Decorator.fromJson(Map<String, dynamic> json) =>
_$DecoratorFromJson(json);
}
@freezed
class Generic<T> with _$Generic<T> {
factory Generic(@DataConverter() T a) = _Generic<T>;
factory Generic.fromJson(Map<String, dynamic> json) =>
_$GenericFromJson<T>(json);
}
class DataConverter<T extends Object?> implements JsonConverter<T, Object?> {
const DataConverter();
@override
T fromJson(Object? json) {
return json as T;
}
@override
Object? toJson(T object) {
return object;
}
}
@freezed
class DefaultValue with _$DefaultValue {
factory DefaultValue([@Default(42) int value]) = _DefaultValue;
factory DefaultValue.fromJson(Map<String, dynamic> json) =>
_$DefaultValueFromJson(json);
}
@freezed
class DefaultValueJsonKey with _$DefaultValueJsonKey {
factory DefaultValueJsonKey([
@Default(42) @JsonKey(defaultValue: 21) int value,
]) = _DefaultValueJsonKey;
factory DefaultValueJsonKey.fromJson(Map<String, dynamic> json) =>
_$DefaultValueJsonKeyFromJson(json);
}
@freezed
class ClassDecorator with _$ClassDecorator {
@JsonSerializable(fieldRename: FieldRename.snake)
const factory ClassDecorator(String complexName) = ClassDecoratorDefault;
factory ClassDecorator.fromJson(Map<String, dynamic> json) =>
_$ClassDecoratorFromJson(json);
}
@freezed
class DurationValue with _$DurationValue {
const factory DurationValue(Duration complexName) = DurationValueDefault;
factory DurationValue.fromJson(Map<String, dynamic> json) =>
_$DurationValueFromJson(json);
}
@JsonEnum(alwaysCreate: true, fieldRename: FieldRename.kebab)
enum StandAloneEnum {
expected,
specialResult,
@JsonValue('unknown')
unknownResult,
}
Iterable<String> get standAloneEnumValues => _$StandAloneEnumEnumMap.values;
@JsonEnum()
enum Enum {
alpha,
beta,
gamma,
}
@freezed
class EnumJson with _$EnumJson {
factory EnumJson({
@JsonKey(
disallowNullValue: true,
required: true,
unknownEnumValue: JsonKey.nullForUndefinedEnumValue,
)
Enum? status,
}) = _EnumJson;
factory EnumJson.fromJson(Map<String, dynamic> json) =>
_$EnumJsonFromJson(json);
}
@Freezed(genericArgumentFactories: true)
class GenericWithArgumentFactories<T> with _$GenericWithArgumentFactories<T> {
factory GenericWithArgumentFactories(T value, String value2) =
_GenericWithArgumentFactories<T>;
factory GenericWithArgumentFactories.fromJson(
Map<String, dynamic> json,
T Function(Object? json) fromJsonT,
) =>
_$GenericWithArgumentFactoriesFromJson<T>(json, fromJsonT);
}
@Freezed(genericArgumentFactories: true)
class GenericTupleWithArgumentFactories<T, S>
with _$GenericTupleWithArgumentFactories<T, S> {
factory GenericTupleWithArgumentFactories(
T value1,
S value2,
String value3,
) = _GenericTupleWithArgumentFactories<T, S>;
factory GenericTupleWithArgumentFactories.fromJson(
Map<String, dynamic> json,
T Function(Object? json) fromJsonT,
S Function(Object? json) fromJsonS,
) =>
_$GenericTupleWithArgumentFactoriesFromJson(json, fromJsonT, fromJsonS);
}
@Freezed(genericArgumentFactories: true)
class GenericMultiCtorWithArgumentFactories<T, S>
with _$GenericMultiCtorWithArgumentFactories<T, S> {
factory GenericMultiCtorWithArgumentFactories(
T first,
S second,
String another,
) = _GenericMultiCtorWithArgumentFactories<T, S>;
factory GenericMultiCtorWithArgumentFactories.first(T first, String another) =
_GenericMultiCtorWithArgumentFactoriesVal<T, S>;
factory GenericMultiCtorWithArgumentFactories.second(
S second,
String another,
) = _GenericMultiCtorWithArgumentFactoriesSec<T, S>;
factory GenericMultiCtorWithArgumentFactories.both(
T first,
S second,
String another,
) = _GenericMultiCtorWithArgumentFactoriesBoth<T, S>;
factory GenericMultiCtorWithArgumentFactories.none(String another) =
_GenericMultiCtorWithArgumentFactoriesNone<T, S>;
factory GenericMultiCtorWithArgumentFactories.fromJson(
Map<String, dynamic> json,
T Function(Object? json) fromJsonT,
S Function(Object? json) fromJsonS,
) =>
_$GenericMultiCtorWithArgumentFactoriesFromJson<T, S>(
json,
fromJsonT,
fromJsonS,
);
}
| freezed/packages/freezed/test/integration/json.dart/0 | {'file_path': 'freezed/packages/freezed/test/integration/json.dart', 'repo_id': 'freezed', 'token_count': 7374} |
// ignore_for_file: prefer_const_constructors, omit_local_variable_types
import 'package:analyzer/dart/analysis/results.dart';
import 'package:build_test/build_test.dart';
import 'package:test/test.dart';
import 'common.dart';
import 'integration/multiple_constructors.dart';
void main() {
group('map', () {
test('works with no default ctr', () {
var value = NoDefault.first('a');
expect(
value.map(
first: (NoDefault1 value) => '${value.a} first',
second: (NoDefault2 value) => throw Error(),
),
'a first',
);
value = NoDefault.second('a');
expect(
value.map(
first: (NoDefault1 value) => throw Error(),
second: (NoDefault2 value) => '${value.a} second',
),
'a second',
);
});
group('default ctor', () {
test("assert callbacks can't be null", () async {
await expectLater(compile(r'''
import 'multiple_constructors.dart';
void main() {
final value = SwitchTest('a');
value.map(
(SwitchTest0 a) {},
first: (SwitchTest1 b) {},
second: (SwitchTest2 c) {},
);
}
'''), completes);
await expectLater(compile(r'''
import 'multiple_constructors.dart';
void main() {
final value = SwitchTest('a');
value.map(
(SwitchTest0 a) {},
first: null,
second: (SwitchTest2 value) {},
);
}
'''), throwsCompileError);
await expectLater(compile(r'''
import 'multiple_constructors.dart';
void main() {
final value = SwitchTest('a');
value.map(
null,
first: (SwitchTest1 value) {},
second: (SwitchTest2 value) {},
);
}
'''), throwsCompileError);
await expectLater(compile(r'''
import 'multiple_constructors.dart';
void main() {
final value = SwitchTest('a');
value.map(
(SwitchTest0 a) {},
first: (SwitchTest1 value) {},
second: null,
);
}
'''), throwsCompileError);
});
test('calls default callback', () {
final value = SwitchTest('a');
expect(
value.map(
(SwitchTest0 value) => '${value.a} 42',
first: (SwitchTest1 value) => throw Error(),
second: (SwitchTest2 value) => throw Error(),
),
'a 42',
);
});
});
group('first ctor', () {
test("assert callbacks can't be null", () async {
await expectLater(compile(r'''
import 'multiple_constructors.dart';
void main() {
final value = SwitchTest.first('a');
value.map(
(SwitchTest0 a) {},
first: (SwitchTest1 b) {},
second: (SwitchTest2 c) {},
);
}
'''), completes);
await expectLater(compile(r'''
import 'multiple_constructors.dart';
void main() {
final value = SwitchTest.first('a');
value.map(
(SwitchTest0 a) {},
first: null,
second: (SwitchTest2 value) {},
);
}
'''), throwsCompileError);
await expectLater(compile(r'''
import 'multiple_constructors.dart';
void main() {
final value = SwitchTest.first('a');
value.map(
null,
first: (SwitchTest1 value) {},
second: (SwitchTest2 value) {},
);
}
'''), throwsCompileError);
await expectLater(compile(r'''
import 'multiple_constructors.dart';
void main() {
final value = SwitchTest.first('a');
value.map(
(SwitchTest0 a) {},
first: (SwitchTest1 value) {},
second: null,
);
}
'''), throwsCompileError);
});
test('calls first callback', () {
final value = SwitchTest.first('a', b: false, d: .42);
expect(
value.map(
(SwitchTest0 a) => throw Error(),
first: (SwitchTest1 value) => '${value.a} ${value.b} ${value.d}',
second: (SwitchTest2 value) => throw Error(),
),
'a false 0.42',
);
});
});
group('second ctor', () {
test("assert callbacks can't be null", () async {
await expectLater(compile(r'''
import 'multiple_constructors.dart';
void main() {
final value = SwitchTest.second('a');
value.map(
(SwitchTest0 a) {},
first: (SwitchTest1 b) {},
second: (SwitchTest2 c) {},
);
}
'''), completes);
await expectLater(compile(r'''
import 'multiple_constructors.dart';
void main() {
final value = SwitchTest.second('a');
value.map(
(SwitchTest0 a) {},
first: null,
second: (SwitchTest2 value) {},
);
}
'''), throwsCompileError);
await expectLater(compile(r'''
import 'multiple_constructors.dart';
void main() {
final value = SwitchTest.second('a');
value.map(
null,
first: (SwitchTest1 value) {},
second: (SwitchTest2 value) {},
);
}
'''), throwsCompileError);
await expectLater(compile(r'''
import 'multiple_constructors.dart';
void main() {
final value = SwitchTest.second('a');
value.map(
(SwitchTest0 a) {},
first: (SwitchTest1 value) {},
second: null,
);
}
'''), throwsCompileError);
});
test('calls second callback', () {
final value = SwitchTest.second('a', 21, .42);
expect(
value.map(
(SwitchTest0 a) => throw Error(),
first: (SwitchTest1 value) => throw Error(),
second: (SwitchTest2 value) => '${value.a} ${value.c} ${value.d}',
),
'a 21 0.42',
);
});
});
test('named parameters are marked as required', () async {
final main = await resolveSources(
{
'freezed|test/integration/main.dart': r'''
library main;
import 'multiple_constructors.dart';
void main() {
final value = SwitchTest.first('a', b: false, d: .42);
value.map(
(a) => 42,
);
}
''',
},
(r) => r.findLibraryByName('main'),
);
final errorResult = await main!.session
.getErrors('/freezed/test/integration/main.dart') as ErrorsResult;
expect(errorResult.errors, isNotEmpty);
});
});
group('maybeMap', () {
test('returns callback result if has callback', () {
var value = SwitchTest('a');
expect(
value.maybeMap(
(value) => '${value.a} default',
orElse: () => throw Error(),
),
'a default',
);
value = SwitchTest.first('a', b: false, d: .42);
expect(
value.maybeMap(
null,
first: (SwitchTest1 value) => '${value.a} ${value.b} ${value.d}',
orElse: () => throw Error(),
),
'a false 0.42',
);
value = SwitchTest.second('a', 21, 0.42);
expect(
value.maybeMap(
null,
second: (SwitchTest2 value) => '${value.a} ${value.c} ${value.d}',
orElse: () => throw Error(),
),
'a 21 0.42',
);
});
test('assert orElse is passed', () async {
await expectLater(compile(r'''
import 'multiple_constructors.dart';
void main() {
var value = SwitchTest('a');
value.maybeMap(
(SwitchTest0 a) {},
orElse: () {},
);
}
'''), completes);
await expectLater(compile(r'''
import 'multiple_constructors.dart';
void main() {
var value = SwitchTest('a');
value.maybeMap(
(SwitchTest0 a) => '$a default',
orElse: null,
);
}
'''), throwsCompileError);
await expectLater(compile(r'''
import 'multiple_constructors.dart';
void main() {
var value = SwitchTest('a');
value.maybeMap(
(SwitchTest0 a) => '$a default',
orElse: null,
);
}
'''), throwsCompileError);
});
test('orElse is called', () {
var value = SwitchTest('a');
expect(value.maybeMap(null, orElse: () => 42), 42);
value = SwitchTest.first('a', b: false, d: .42);
expect(value.maybeMap(null, orElse: () => 42), 42);
value = SwitchTest.second('a', 21, 0.42);
expect(value.maybeMap(null, orElse: () => 42), 42);
});
test('named parameters are not required', () async {
final main = await resolveSources(
{
'freezed|test/integration/main.dart': r'''
library main;
import 'multiple_constructors.dart';
void main() {
final value = SwitchTest('a');
value.maybeMap(null, orElse: () => 42);
}
''',
},
(r) => r.findLibraryByName('main'),
);
final errorResult = await main!.session
.getErrors('/freezed/test/integration/main.dart') as ErrorsResult;
expect(errorResult.errors, isEmpty);
});
test('orElse is required', () async {
final main = await resolveSources(
{
'freezed|test/integration/main.dart': r'''
library main;
import 'multiple_constructors.dart';
void main() {
final value = SwitchTest('a');
value.maybeMap(null);
}
''',
},
(r) => r.findLibraryByName('main'),
);
final errorResult = await main!.session
.getErrors('/freezed/test/integration/main.dart') as ErrorsResult;
expect(errorResult.errors, isNotEmpty);
});
});
group('mapOrNull', () {
test('has all parameters as optional', () {
expect(NoDefault.first('a').mapOrNull(), null);
expect(NoDefault.second('a').mapOrNull(), null);
});
test('can map to nullable return type without type cast', () {
String? res = NoDefault.first('a').mapOrNull(
first: (value) => value.a.isEmpty ? null : value.a,
);
expect(res, 'a');
});
test('calls callback on matching constructor', () {
expect(
NoDefault.first('a').mapOrNull(first: (v) => v),
NoDefault.first('a'),
);
expect(
NoDefault.second('a').mapOrNull(second: (v) => v),
NoDefault.second('a'),
);
});
});
}
| freezed/packages/freezed/test/map_test.dart/0 | {'file_path': 'freezed/packages/freezed/test/map_test.dart', 'repo_id': 'freezed', 'token_count': 4057} |
import 'package:freezed_annotation/freezed_annotation.dart';
part 'missing_private_empty_ctor.freezed.dart';
@freezed
// expect_lint: freezed_missing_private_empty_constructor
class RequiresPrivateCtor with _$RequiresPrivateCtor {
// const RequiresPrivateCtor._();
const factory RequiresPrivateCtor() = _RequiresPrivateCtor;
void method() {
print('hello world');
}
}
@freezed
class HasPrivateCtor with _$HasPrivateCtor {
const HasPrivateCtor._();
const factory HasPrivateCtor() = _HasPrivateCtor;
void method() {
print('hello world');
}
}
@freezed
// expect_lint: freezed_missing_private_empty_constructor
class HasAccessor with _$HasAccessor {
// const HasAccessor._();
const factory HasAccessor(int id) = _HasAccessor;
String get idString => id.toString();
}
abstract class IdClass {
int get id;
}
mixin IdMixin {
int get id;
}
@freezed
class WithIdMixin with _$WithIdMixin, IdMixin {
// const WithIdMixin._();
const factory WithIdMixin(int id) = _WithIdMixin;
}
@freezed
// expect_lint: freezed_missing_private_empty_constructor
class ExtendsIdClass extends IdClass with _$ExtendsIdClass {
// ExtendsIdClass._();
const factory ExtendsIdClass(int id) = _ExtendsIdClass;
@override
int get id => id;
}
| freezed/packages/freezed_lint/example/lib/missing_private_empty_ctor.dart/0 | {'file_path': 'freezed/packages/freezed_lint/example/lib/missing_private_empty_ctor.dart', 'repo_id': 'freezed', 'token_count': 429} |
name: ci
on:
pull_request:
paths:
- "!packages/fresh_dio/lib/**"
- "!packages/fresh_dio/test/**"
- "!packages/fresh_dio/example/**"
- "!packages/fresh/lib/**"
- "!packages/fresh/test/**"
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: noop
run: echo 'noop'
| fresh/.github/workflows/ci.yaml/0 | {'file_path': 'fresh/.github/workflows/ci.yaml', 'repo_id': 'fresh', 'token_count': 176} |
export 'src/fresh.dart';
| fresh/packages/fresh/lib/fresh.dart/0 | {'file_path': 'fresh/packages/fresh/lib/fresh.dart', 'repo_id': 'fresh', 'token_count': 10} |
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:photos_repository/photos_repository.dart';
part 'photos_event.dart';
part 'photos_state.dart';
class PhotosBloc extends Bloc<PhotosEvent, PhotosState> {
PhotosBloc(PhotosRepository photosRepository)
: _photosRepository = photosRepository,
super(PhotosLoadInProgress()) {
on<PhotosRequested>(_onPhotosRequested);
}
final PhotosRepository _photosRepository;
Future<void> _onPhotosRequested(
PhotosRequested event,
Emitter<PhotosState> emit,
) async {
emit(PhotosLoadInProgress());
try {
final photos = await _photosRepository.getPhotos();
emit(PhotosLoadSuccess(photos));
} catch (_) {
emit(PhotosLoadFailure());
}
}
}
| fresh/packages/fresh_dio/example/lib/photos/bloc/photos_bloc.dart/0 | {'file_path': 'fresh/packages/fresh_dio/example/lib/photos/bloc/photos_bloc.dart', 'repo_id': 'fresh', 'token_count': 289} |
name: photos_repository
description: A Photos Dart Repository
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
jsonplaceholder_client:
path: ../jsonplaceholder_client
| fresh/packages/fresh_dio/example/packages/photos_repository/pubspec.yaml/0 | {'file_path': 'fresh/packages/fresh_dio/example/packages/photos_repository/pubspec.yaml', 'repo_id': 'fresh', 'token_count': 83} |
name: my_project
packages:
- packages/**
| functional_widget/melos.yaml/0 | {'file_path': 'functional_widget/melos.yaml', 'repo_id': 'functional_widget', 'token_count': 15} |
import 'package:build/build.dart';
import 'package:functional_widget/function_to_widget_class.dart';
import 'package:functional_widget/src/utils.dart';
import 'package:source_gen/source_gen.dart';
/// Builds generators for `build_runner` to run
Builder functionalWidget(BuilderOptions options) {
final parse = parseBuilderOptions(options);
return SharedPartBuilder(
[FunctionalWidgetGenerator(parse)],
'functional_widget',
);
}
| functional_widget/packages/functional_widget/lib/builder.dart/0 | {'file_path': 'functional_widget/packages/functional_widget/lib/builder.dart', 'repo_id': 'functional_widget', 'token_count': 134} |
blank_issues_enabled: false
contact_links:
- name: Flutter issue
url: https://github.com/flutter/flutter/issues/new/choose
about: I'm having an issue with Flutter itself.
- name: Question
url: https://stackoverflow.com/questions/tagged/flutter?tab=Frequent
about: I have a question about Flutter.
| gallery/.github/ISSUE_TEMPLATE/config.yml/0 | {'file_path': 'gallery/.github/ISSUE_TEMPLATE/config.yml', 'repo_id': 'gallery', 'token_count': 108} |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/gallery_localizations.dart';
// BEGIN cupertinoContextMenuDemo
class CupertinoContextMenuDemo extends StatelessWidget {
const CupertinoContextMenuDemo({super.key});
@override
Widget build(BuildContext context) {
final galleryLocalizations = GalleryLocalizations.of(context)!;
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
automaticallyImplyLeading: false,
middle: Text(
galleryLocalizations.demoCupertinoContextMenuTitle,
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: SizedBox(
width: 100,
height: 100,
child: CupertinoContextMenu(
actions: [
CupertinoContextMenuAction(
onPressed: () {
Navigator.pop(context);
},
child: Text(
galleryLocalizations.demoCupertinoContextMenuActionOne,
),
),
CupertinoContextMenuAction(
onPressed: () {
Navigator.pop(context);
},
child: Text(
galleryLocalizations.demoCupertinoContextMenuActionTwo,
),
),
],
child: const FlutterLogo(size: 250),
),
),
),
const SizedBox(height: 20),
Padding(
padding: const EdgeInsets.all(30),
child: Text(
galleryLocalizations.demoCupertinoContextMenuActionText,
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.black,
),
),
),
],
),
);
}
}
// END
| gallery/lib/demos/cupertino/cupertino_context_menu_demo.dart/0 | {'file_path': 'gallery/lib/demos/cupertino/cupertino_context_menu_demo.dart', 'repo_id': 'gallery', 'token_count': 1136} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.