code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:json_annotation/json_annotation.dart';
import 'package:json_serializable/src/type_helpers/config_types.dart';
final jsonSerializableFields = generatorConfigDefaultJson.keys.toList();
final generatorConfigDefaultJson = Map<String, dynamic>.unmodifiable(
ClassConfig.defaults.toJsonSerializable().toJson(),
);
// #CHANGE WHEN UPDATING json_annotation
final generatorConfigNonDefaultJson =
Map<String, dynamic>.unmodifiable(const JsonSerializable(
anyMap: true,
checked: true,
constructor: 'something',
createFactory: false,
createToJson: false,
createFieldMap: true,
createPerFieldToJson: true,
disallowUnrecognizedKeys: true,
explicitToJson: true,
fieldRename: FieldRename.kebab,
ignoreUnannotated: true,
includeIfNull: false,
genericArgumentFactories: true,
).toJson());
|
json_serializable/json_serializable/test/shared_config.dart/0
|
{'file_path': 'json_serializable/json_serializable/test/shared_config.dart', 'repo_id': 'json_serializable', 'token_count': 322}
|
// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// ignore_for_file: prefer_const_declarations
@TestOn('vm')
library test;
import 'dart:convert';
import 'package:test/test.dart';
import '../test_utils.dart';
import 'input.type_map.dart' show SimpleClassOfStringToStringNullable;
void main() {
for (var input in const <Map<String, Object?>>{
{'value': {}},
{
'value': {'key': 'value'}
},
{
// Regression case for https://github.com/google/json_serializable.dart/issues/864
'value': {'key': null}
},
}) {
test(input, () {
final object = SimpleClassOfStringToStringNullable.fromJson(input);
final encoded = loudEncode(object);
expect(encoded, loudEncode(input));
final object2 = SimpleClassOfStringToStringNullable.fromJson(
jsonDecode(encoded) as Map<String, Object?>,
);
expect(loudEncode(object2), encoded);
});
}
}
|
json_serializable/json_serializable/test/supported_types/extra_map_test.dart/0
|
{'file_path': 'json_serializable/json_serializable/test/supported_types/extra_map_test.dart', 'repo_id': 'json_serializable', 'token_count': 404}
|
import 'dart:convert';
import 'package:stack_trace/stack_trace.dart';
import 'package:test/test.dart';
final throwsTypeError = throwsA(isTypeError);
final isTypeError = isA<TypeError>();
/// Prints out nested causes before throwing `JsonUnsupportedObjectError`.
String loudEncode(Object? object) {
try {
return const JsonEncoder.withIndent(' ').convert(object);
} catch (e) {
if (e is JsonUnsupportedObjectError) {
Object? error = e;
var count = 1;
while (error is JsonUnsupportedObjectError) {
print(
'(${count++}) $error ${error.unsupportedObject} '
'(${error.unsupportedObject.runtimeType}) !!!',
);
print(Trace.from(error.stackTrace!).terse);
error = error.cause;
}
if (error != null) {
print('(${count++}) $error ???');
if (error is Error) {
print(Trace.from(error.stackTrace!).terse);
}
}
}
rethrow;
}
}
T roundTripObject<T>(
T object,
T Function(Map<String, dynamic> json) factory, {
bool skipObjectEquals = false,
}) {
final data = loudEncode(object);
final object2 = factory(json.decode(data) as Map<String, dynamic>);
if (!skipObjectEquals) {
expect(object2, equals(object));
}
final json2 = loudEncode(object2);
expect(json2, equals(data));
return object2;
}
|
json_serializable/shared_test/lib/shared_test.dart/0
|
{'file_path': 'json_serializable/shared_test/lib/shared_test.dart', 'repo_id': 'json_serializable', 'token_count': 544}
|
import 'dart:ui';
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:lightrunners/game/game.dart';
import 'package:lightrunners/ui/ui.dart';
class Bullet extends CircleComponent with HasGameReference<LightRunnersGame> {
final int ownerPlayerNumber;
final Vector2 velocity;
final Color color;
Bullet({
required this.ownerPlayerNumber,
required super.position,
required this.velocity,
required this.color,
}) : super(
radius: velocity.length / 50,
anchor: Anchor.center,
paint: GamePalette.bulletPaints[ownerPlayerNumber],
);
@override
Future<void> onLoad() async {
super.onLoad();
add(CircleHitbox()..collisionType = CollisionType.passive);
}
final _velocityTmp = Vector2.zero();
@override
void update(double dt) {
_velocityTmp
..setFrom(velocity)
..scale(dt);
position.add(_velocityTmp);
if (!game.playArea.contains(position.toOffset())) {
removeFromParent();
}
}
}
|
lightrunners/lib/game/components/bullet.dart/0
|
{'file_path': 'lightrunners/lib/game/components/bullet.dart', 'repo_id': 'lightrunners', 'token_count': 389}
|
export 'view/lobby_page.dart';
|
lightrunners/lib/lobby/lobby.dart/0
|
{'file_path': 'lightrunners/lib/lobby/lobby.dart', 'repo_id': 'lightrunners', 'token_count': 13}
|
import 'package:flame/extensions.dart';
import 'package:flutter/services.dart';
import 'package:gamepads/gamepads.dart';
import 'package:lightrunners/utils/gamepad_map.dart';
class GamepadJoystick {
final String gamepadId;
final GamepadKey xAxisKey;
final GamepadKey yAxisKey;
final Vector2 state = Vector2.zero();
GamepadJoystick({
required this.gamepadId,
required this.xAxisKey,
required this.yAxisKey,
});
void consume(GamepadEvent event) {
if (event.gamepadId != gamepadId) {
return;
}
final intensity = GamepadAnalogAxis.normalizedIntensity(event);
if (xAxisKey.matches(event)) {
state.x = intensity;
} else if (yAxisKey.matches(event)) {
state.y = intensity;
}
}
}
bool readArrowLikeKeysIntoVector2(
RawKeyEvent event,
Set<LogicalKeyboardKey> keysPressed,
Vector2 vector, {
required LogicalKeyboardKey up,
required LogicalKeyboardKey down,
required LogicalKeyboardKey left,
required LogicalKeyboardKey right,
}) {
final isDown = event is RawKeyDownEvent;
if (event.logicalKey == up) {
if (isDown) {
vector.y = -1;
} else if (keysPressed.contains(down)) {
vector.y = 1;
} else {
vector.y = 0;
}
return false;
} else if (event.logicalKey == down) {
if (isDown) {
vector.y = 1;
} else if (keysPressed.contains(up)) {
vector.y = -1;
} else {
vector.y = 0;
}
return false;
} else if (event.logicalKey == left) {
if (isDown) {
vector.x = -1;
} else if (keysPressed.contains(right)) {
vector.x = 1;
} else {
vector.x = 0;
}
return false;
} else if (event.logicalKey == right) {
if (isDown) {
vector.x = 1;
} else if (keysPressed.contains(left)) {
vector.x = -1;
} else {
vector.x = 0;
}
return false;
}
return true;
}
|
lightrunners/lib/utils/input_handler_utils.dart/0
|
{'file_path': 'lightrunners/lib/utils/input_handler_utils.dart', 'repo_id': 'lightrunners', 'token_count': 788}
|
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import '../analyzer.dart';
const _desc = r'Avoid using `as`.';
const _details = r'''
**AVOID** using `as`.
If you know the type is correct, use an assertion or assign to a more
narrowly-typed variable (this avoids the type check in release mode; `as` is not
compiled out in release mode). If you don't know whether the type is
correct, check using `is` (this avoids the exception that `as` raises).
**BAD:**
```dart
(pm as Person).firstName = 'Seth';
```
**GOOD:**
```dart
if (pm is Person)
pm.firstName = 'Seth';
```
but certainly not
**BAD:**
```dart
try {
(pm as Person).firstName = 'Seth';
} on CastError { }
```
Note that an exception is made in the case of `dynamic` since the cast has no
performance impact.
**OK:**
```dart
HasScrollDirection scrollable = renderObject as dynamic;
```
**DEPRECATED:** This advice is no longer recommended.
The rule will be removed in a future Linter release.
''';
class AvoidAs extends LintRule implements NodeLintRule {
AvoidAs()
: super(
name: 'avoid_as',
description: _desc,
details: _details,
group: Group.style,
maturity: Maturity.deprecated,
);
@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor = _Visitor(this);
registry.addAsExpression(this, visitor);
}
}
class _Visitor extends SimpleAstVisitor<void> {
final LintRule rule;
_Visitor(this.rule);
@override
void visitAsExpression(AsExpression node) {
var typeAnnotation = node.type;
if (typeAnnotation is NamedType && typeAnnotation.name.name != 'dynamic') {
rule.reportLint(typeAnnotation);
}
}
}
|
linter/lib/src/rules/avoid_as.dart/0
|
{'file_path': 'linter/lib/src/rules/avoid_as.dart', 'repo_id': 'linter', 'token_count': 708}
|
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import '../analyzer.dart';
import '../util/dart_type_utilities.dart';
const _desc = r"Don't check for null in custom == operators.";
const _details = r'''
**DON'T** check for null in custom == operators.
As null is a special type, no class can be equivalent to it. Thus, it is
redundant to check whether the other instance is null.
**BAD:**
```dart
class Person {
final String name;
@override
operator ==(other) =>
other != null && other is Person && name == other.name;
}
```
**GOOD:**
```dart
class Person {
final String name;
@override
operator ==(other) => other is Person && name == other.name;
}
```
''';
bool _isComparingEquality(TokenType tokenType) =>
tokenType == TokenType.BANG_EQ || tokenType == TokenType.EQ_EQ;
bool _isComparingParameterWithNull(BinaryExpression node, Element? parameter) =>
_isComparingEquality(node.operator.type) &&
((DartTypeUtilities.isNullLiteral(node.leftOperand) &&
_isParameter(node.rightOperand, parameter)) ||
(DartTypeUtilities.isNullLiteral(node.rightOperand) &&
_isParameter(node.leftOperand, parameter)));
bool _isParameter(Expression expression, Element? parameter) =>
DartTypeUtilities.getCanonicalElementFromIdentifier(expression) ==
parameter;
bool _isParameterWithQuestion(AstNode node, Element? parameter) =>
(node is PropertyAccess &&
node.operator.type == TokenType.QUESTION_PERIOD &&
DartTypeUtilities.getCanonicalElementFromIdentifier(node.target) ==
parameter) ||
(node is MethodInvocation &&
node.operator?.type == TokenType.QUESTION_PERIOD &&
DartTypeUtilities.getCanonicalElementFromIdentifier(node.target) ==
parameter);
bool _isParameterWithQuestionQuestion(
BinaryExpression node, Element? parameter) =>
node.operator.type == TokenType.QUESTION_QUESTION &&
_isParameter(node.leftOperand, parameter);
class AvoidNullChecksInEqualityOperators extends LintRule
implements NodeLintRule {
AvoidNullChecksInEqualityOperators()
: super(
name: 'avoid_null_checks_in_equality_operators',
description: _desc,
details: _details,
group: Group.style);
@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor = _Visitor(this);
registry.addMethodDeclaration(this, visitor);
}
}
class _Visitor extends SimpleAstVisitor<void> {
final LintRule rule;
_Visitor(this.rule);
@override
void visitMethodDeclaration(MethodDeclaration node) {
var parameters = node.parameters?.parameters;
if (parameters == null) {
return;
}
if (node.name.token.type == TokenType.EQ_EQ && parameters.length == 1) {
var parameter = DartTypeUtilities.getCanonicalElementFromIdentifier(
parameters.first.identifier);
bool checkIfParameterIsNull(AstNode node) =>
_isParameterWithQuestion(node, parameter) ||
(node is BinaryExpression &&
(_isParameterWithQuestionQuestion(node, parameter) ||
_isComparingParameterWithNull(node, parameter)));
DartTypeUtilities.traverseNodesInDFS(node.body)
.where(checkIfParameterIsNull)
.forEach(rule.reportLint);
}
}
}
|
linter/lib/src/rules/avoid_null_checks_in_equality_operators.dart/0
|
{'file_path': 'linter/lib/src/rules/avoid_null_checks_in_equality_operators.dart', 'repo_id': 'linter', 'token_count': 1352}
|
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import '../analyzer.dart';
const _desc =
r'Avoid <Type>.toString() in production code since results may be minified.';
const _details = r'''
**DO** avoid calls to <Type>.toString() in production code, since it does not
contractually return the user-defined name of the Type (or underlying class).
Development-mode compilers where code size is not a concern use the full name,
but release-mode compilers often choose to minify these symbols.
**BAD:**
```dart
void bar(Object other) {
if (other.runtimeType.toString() == 'Bar') {
doThing();
}
}
Object baz(Thing myThing) {
return getThingFromDatabase(key: myThing.runtimeType.toString());
}
```
**GOOD:**
```dart
void bar(Object other) {
if (other is Bar) {
doThing();
}
}
class Thing {
String get thingTypeKey => ...
}
Object baz(Thing myThing) {
return getThingFromDatabase(key: myThing.thingTypeKey);
}
```
''';
class AvoidTypeToString extends LintRule implements NodeLintRule {
AvoidTypeToString()
: super(
name: 'avoid_type_to_string',
description: _desc,
details: _details,
group: Group.errors);
@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor =
_Visitor(this, context.typeSystem, context.typeProvider.typeType);
// Gathering meta information at these nodes.
// Nodes visited in DFS, so this will be called before
// each visitMethodInvocation.
registry.addClassDeclaration(this, visitor);
registry.addMixinDeclaration(this, visitor);
registry.addExtensionDeclaration(this, visitor);
registry.addArgumentList(this, visitor);
// Actually checking things at these nodes.
// Also delegates to visitArgumentList.
registry.addMethodInvocation(this, visitor);
}
}
class _Visitor extends SimpleAstVisitor {
final LintRule rule;
final TypeSystem typeSystem;
final InterfaceType typeType;
// Null if there is no logical `this` in the given context.
InterfaceType? thisType;
_Visitor(this.rule, this.typeSystem, this.typeType);
@override
void visitClassDeclaration(ClassDeclaration node) {
thisType = node.declaredElement?.thisType;
}
@override
void visitMixinDeclaration(MixinDeclaration node) {
thisType = node.declaredElement?.thisType;
}
@override
void visitExtensionDeclaration(ExtensionDeclaration node) {
var extendedType = node.declaredElement?.extendedType;
// Might not be InterfaceType. Ex: visiting an extension on a dynamic type.
thisType = extendedType is InterfaceType ? extendedType : null;
}
@override
void visitMethodInvocation(MethodInvocation node) {
visitArgumentList(node.argumentList);
var staticType = node.realTarget?.staticType;
var targetType = staticType is InterfaceType ? staticType : thisType;
_reportIfToStringOnCoreTypeClass(targetType, node.methodName);
}
@override
void visitArgumentList(ArgumentList node) {
node.arguments.forEach(_validateArgument);
}
void _validateArgument(Expression expression) {
if (expression is PropertyAccess) {
var expressionType = expression.realTarget.staticType;
var targetType =
(expressionType is InterfaceType) ? expressionType : thisType;
_reportIfToStringOnCoreTypeClass(targetType, expression.propertyName);
} else if (expression is PrefixedIdentifier) {
var prefixType = expression.prefix.staticType;
if (prefixType is InterfaceType) {
_reportIfToStringOnCoreTypeClass(prefixType, expression.identifier);
}
} else if (expression is SimpleIdentifier) {
_reportIfToStringOnCoreTypeClass(thisType, expression);
}
}
void _reportIfToStringOnCoreTypeClass(
InterfaceType? targetType, SimpleIdentifier methodIdentifier) {
if (_isToStringOnCoreTypeClass(targetType, methodIdentifier)) {
rule.reportLint(methodIdentifier);
}
}
bool _isToStringOnCoreTypeClass(
InterfaceType? targetType, SimpleIdentifier methodIdentifier) =>
targetType != null &&
methodIdentifier.name == 'toString' &&
_isSimpleIdDeclByCoreObj(methodIdentifier) &&
typeSystem.isSubtypeOf(targetType, typeType);
bool _isSimpleIdDeclByCoreObj(SimpleIdentifier simpleIdentifier) {
var encloser = simpleIdentifier.staticElement?.enclosingElement;
return encloser is ClassElement && encloser.isDartCoreObject;
}
}
|
linter/lib/src/rules/avoid_type_to_string.dart/0
|
{'file_path': 'linter/lib/src/rules/avoid_type_to_string.dart', 'repo_id': 'linter', 'token_count': 1613}
|
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import '../analyzer.dart';
const _desc = r'Avoid control flow in finally blocks.';
const _details = r'''
**AVOID** control flow leaving finally blocks.
Using control flow in finally blocks will inevitably cause unexpected behavior
that is hard to debug.
**GOOD:**
```dart
class Ok {
double compliantMethod() {
var i = 5;
try {
i = 1 / 0;
} catch (e) {
print(e); // OK
}
return i;
}
}
```
**BAD:**
```dart
class BadReturn {
double nonCompliantMethod() {
try {
return 1 / 0;
} catch (e) {
print(e);
} finally {
return 1.0; // LINT
}
}
}
```
**BAD:**
```dart
class BadContinue {
double nonCompliantMethod() {
for (var o in [1, 2]) {
try {
print(o / 0);
} catch (e) {
print(e);
} finally {
continue; // LINT
}
}
return 1.0;
}
}
```
**BAD:**
```dart
class BadBreak {
double nonCompliantMethod() {
for (var o in [1, 2]) {
try {
print(o / 0);
} catch (e) {
print(e);
} finally {
break; // LINT
}
}
return 1.0;
}
}
```
''';
class ControlFlowInFinally extends LintRule implements NodeLintRule {
ControlFlowInFinally()
: super(
name: 'control_flow_in_finally',
description: _desc,
details: _details,
group: Group.errors);
@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor = _Visitor(this);
registry.addBreakStatement(this, visitor);
registry.addContinueStatement(this, visitor);
registry.addReturnStatement(this, visitor);
}
}
/// Do not extend this class, it is meant to be used from
/// [ControlFlowInFinally] which is in a separate rule to allow a more granular
/// configurability given that reporting throw statements in a finally clause is
/// controversial.
abstract class ControlFlowInFinallyBlockReporterMixin {
LintRule get rule;
void reportIfFinallyAncestorExists(AstNode node, {AstNode? ancestor}) {
var tryStatement = node.thisOrAncestorOfType<TryStatement>();
var finallyBlock = tryStatement?.finallyBlock;
bool finallyBlockAncestorPredicate(AstNode n) => n == finallyBlock;
if (tryStatement == null ||
finallyBlock == null ||
node.thisOrAncestorMatching(finallyBlockAncestorPredicate) == null) {
return;
}
var enablerNode = _findEnablerNode(
ancestor, finallyBlockAncestorPredicate, node, tryStatement);
if (enablerNode == null) {
rule.reportLint(node);
}
}
AstNode? _findEnablerNode(
AstNode? ancestor,
bool Function(AstNode n) finallyBlockAncestorPredicate,
AstNode node,
TryStatement tryStatement) {
AstNode? enablerNode;
if (ancestor == null) {
bool functionBlockPredicate(n) =>
n is FunctionBody &&
n.thisOrAncestorMatching(finallyBlockAncestorPredicate) != null;
enablerNode = node.thisOrAncestorMatching(functionBlockPredicate);
} else {
enablerNode = ancestor.thisOrAncestorMatching((n) => n == tryStatement);
}
return enablerNode;
}
}
class _Visitor extends SimpleAstVisitor<void>
with ControlFlowInFinallyBlockReporterMixin {
@override
final LintRule rule;
_Visitor(this.rule);
@override
void visitBreakStatement(BreakStatement node) {
reportIfFinallyAncestorExists(node, ancestor: node.target);
}
@override
void visitContinueStatement(ContinueStatement node) {
reportIfFinallyAncestorExists(node, ancestor: node.target);
}
@override
void visitReturnStatement(ReturnStatement node) {
reportIfFinallyAncestorExists(node);
}
}
|
linter/lib/src/rules/control_flow_in_finally.dart/0
|
{'file_path': 'linter/lib/src/rules/control_flow_in_finally.dart', 'repo_id': 'linter', 'token_count': 1542}
|
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import '../analyzer.dart';
import '../util/dart_type_utilities.dart';
const _desc = r'Join return statement with assignment when possible.';
const _details = r'''
**DO** join return statement with assignment when possible.
**BAD:**
```dart
class A {
B _lazyInstance;
static B get instance {
_lazyInstance ??= B(); // LINT
return _lazyInstance;
}
}
```
**GOOD:**
```dart
class A {
B _lazyInstance;
static B get instance => _lazyInstance ??= B();
}
```
''';
Expression? _getExpressionFromAssignmentStatement(Statement node) {
var visitor = _AssignmentStatementVisitor();
node.accept(visitor);
return visitor.expression;
}
Expression? _getExpressionFromReturnStatement(Statement node) =>
node is ReturnStatement ? node.expression : null;
class JoinReturnWithAssignment extends LintRule implements NodeLintRule {
JoinReturnWithAssignment()
: super(
name: 'join_return_with_assignment',
description: _desc,
details: _details,
group: Group.style);
@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor = _Visitor(this);
registry.addBlock(this, visitor);
}
}
class _AssignmentStatementVisitor extends SimpleAstVisitor {
Expression? expression;
@override
void visitAssignmentExpression(AssignmentExpression node) {
expression = node.leftHandSide;
}
@override
void visitExpressionStatement(ExpressionStatement statement) {
statement.expression.accept(this);
}
@override
void visitParenthesizedExpression(ParenthesizedExpression node) {
node.unParenthesized.accept(this);
}
@override
void visitPostfixExpression(PostfixExpression node) {
expression = node.operand;
}
@override
void visitPrefixExpression(PrefixExpression node) {
expression = node.operand;
}
}
class _Visitor extends SimpleAstVisitor<void> {
final LintRule rule;
_Visitor(this.rule);
@override
void visitBlock(Block node) {
var statements = node.statements;
var length = statements.length;
if (length < 2) {
return;
}
var secondLastStatement = statements[length - 2];
var lastStatement = statements.last;
var secondLastExpression =
_getExpressionFromAssignmentStatement(secondLastStatement);
var lastExpression = _getExpressionFromReturnStatement(lastStatement);
// In this case, the last statement was not a return statement with a
// simple target.
if (lastExpression == null) {
return;
}
Expression? thirdLastExpression;
if (length >= 3) {
var thirdLastStatement = statements[length - 3];
thirdLastExpression =
_getExpressionFromAssignmentStatement(thirdLastStatement);
}
if (!DartTypeUtilities.canonicalElementsFromIdentifiersAreEqual(
secondLastExpression, thirdLastExpression) &&
DartTypeUtilities.canonicalElementsFromIdentifiersAreEqual(
lastExpression, secondLastExpression)) {
rule.reportLint(secondLastStatement);
}
}
}
|
linter/lib/src/rules/join_return_with_assignment.dart/0
|
{'file_path': 'linter/lib/src/rules/join_return_with_assignment.dart', 'repo_id': 'linter', 'token_count': 1151}
|
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/generated/utilities_general.dart'; // ignore: implementation_imports
import '../analyzer.dart';
import '../util/dart_type_utilities.dart';
const _desc = r'Do not pass `null` as an argument where a closure is expected.';
const _details = r'''
**DO NOT** pass null as an argument where a closure is expected.
Often a closure that is passed to a method will only be called conditionally,
so that tests and "happy path" production calls do not reveal that `null` will
result in an exception being thrown.
This rule only catches null literals being passed where closures are expected
in the following locations:
#### Constructors
* From `dart:async`
* `Future` at the 0th positional parameter
* `Future.microtask` at the 0th positional parameter
* `Future.sync` at the 0th positional parameter
* `Timer` at the 0th positional parameter
* `Timer.periodic` at the 1st positional parameter
* From `dart:core`
* `List.generate` at the 1st positional parameter
#### Static functions
* From `dart:async`
* `scheduleMicrotask` at the 0th positional parameter
* `Future.doWhile` at the 0th positional parameter
* `Future.forEach` at the 0th positional parameter
* `Future.wait` at the named parameter `cleanup`
* `Timer.run` at the 0th positional parameter
#### Instance methods
* From `dart:async`
* `Future.then` at the 0th positional parameter
* `Future.complete` at the 0th positional parameter
* From `dart:collection`
* `Queue.removeWhere` at the 0th positional parameter
* `Queue.retain
* `Iterable.firstWhere` at the 0th positional parameter, and the named
parameter `orElse`
* `Iterable.forEach` at the 0th positional parameter
* `Iterable.fold` at the 1st positional parameter
* `Iterable.lastWhere` at the 0th positional parameter, and the named
parameter `orElse`
* `Iterable.map` at the 0th positional parameter
* `Iterable.reduce` at the 0th positional parameter
* `Iterable.singleWhere` at the 0th positional parameter, and the named
parameter `orElse`
* `Iterable.skipWhile` at the 0th positional parameter
* `Iterable.takeWhile` at the 0th positional parameter
* `Iterable.where` at the 0th positional parameter
* `List.removeWhere` at the 0th positional parameter
* `List.retainWhere` at the 0th positional parameter
* `String.replaceAllMapped` at the 1st positional parameter
* `String.replaceFirstMapped` at the 1st positional parameter
* `String.splitMapJoin` at the named parameters `onMatch` and `onNonMatch`
**BAD:**
```dart
[1, 3, 5].firstWhere((e) => e.isOdd, orElse: null);
```
**GOOD:**
```dart
[1, 3, 5].firstWhere((e) => e.isOdd, orElse: () => null);
```
''';
List<NonNullableFunction> _constructorsWithNonNullableArguments =
<NonNullableFunction>[
NonNullableFunction('dart.async', 'Future', null, positional: [0]),
NonNullableFunction('dart.async', 'Future', 'microtask', positional: [0]),
NonNullableFunction('dart.async', 'Future', 'sync', positional: [0]),
NonNullableFunction('dart.async', 'Timer', null, positional: [1]),
NonNullableFunction('dart.async', 'Timer', 'periodic', positional: [1]),
NonNullableFunction('dart.core', 'List', 'generate', positional: [1]),
];
final Map<String, Set<NonNullableFunction>>
_instanceMethodsWithNonNullableArguments = {
'any': {
NonNullableFunction('dart.core', 'Iterable', 'any', positional: [0]),
},
'complete': {
NonNullableFunction('dart.async', 'Future', 'complete', positional: [0]),
},
'every': {
NonNullableFunction('dart.core', 'Iterable', 'every', positional: [0]),
},
'expand': {
NonNullableFunction('dart.core', 'Iterable', 'expand', positional: [0]),
},
'firstWhere': {
NonNullableFunction('dart.core', 'Iterable', 'firstWhere',
positional: [0], named: ['orElse']),
},
'forEach': {
NonNullableFunction('dart.core', 'Iterable', 'forEach', positional: [0]),
NonNullableFunction('dart.core', 'Map', 'forEach', positional: [0]),
},
'fold': {
NonNullableFunction('dart.core', 'Iterable', 'fold', positional: [1]),
},
'lastWhere': {
NonNullableFunction('dart.core', 'Iterable', 'lastWhere',
positional: [0], named: ['orElse']),
},
'map': {
NonNullableFunction('dart.core', 'Iterable', 'map', positional: [0]),
},
'putIfAbsent': {
NonNullableFunction('dart.core', 'Map', 'putIfAbsent', positional: [1]),
},
'reduce': {
NonNullableFunction('dart.core', 'Iterable', 'reduce', positional: [0]),
},
'removeWhere': {
NonNullableFunction('dart.collection', 'Queue', 'removeWhere',
positional: [0]),
NonNullableFunction('dart.core', 'List', 'removeWhere', positional: [0]),
NonNullableFunction('dart.core', 'Set', 'removeWhere', positional: [0]),
},
'replaceAllMapped': {
NonNullableFunction('dart.core', 'String', 'replaceAllMapped',
positional: [1]),
},
'replaceFirstMapped': {
NonNullableFunction('dart.core', 'String', 'replaceFirstMapped',
positional: [1]),
},
'retainWhere': {
NonNullableFunction('dart.collection', 'Queue', 'retainWhere',
positional: [0]),
NonNullableFunction('dart.core', 'List', 'retainWhere', positional: [0]),
NonNullableFunction('dart.core', 'Set', 'retainWhere', positional: [0]),
},
'singleWhere': {
NonNullableFunction('dart.core', 'Iterable', 'singleWhere',
positional: [0], named: ['orElse']),
},
'skipWhile': {
NonNullableFunction('dart.core', 'Iterable', 'skipWhile', positional: [0]),
},
'splitMapJoin': {
NonNullableFunction('dart.core', 'String', 'splitMapJoin',
named: ['onMatch', 'onNonMatch']),
},
'takeWhile': {
NonNullableFunction('dart.core', 'Iterable', 'takeWhile', positional: [0]),
},
'then': {
NonNullableFunction('dart.async', 'Future', 'then',
positional: [0], named: ['onError']),
},
'where': {
NonNullableFunction('dart.core', 'Iterable', 'where', positional: [0]),
},
};
List<NonNullableFunction> _staticFunctionsWithNonNullableArguments =
<NonNullableFunction>[
NonNullableFunction('dart.async', null, 'scheduleMicrotask', positional: [0]),
NonNullableFunction('dart.async', 'Future', 'doWhile', positional: [0]),
NonNullableFunction('dart.async', 'Future', 'forEach', positional: [1]),
NonNullableFunction('dart.async', 'Future', 'wait', named: ['cleanUp']),
NonNullableFunction('dart.async', 'Timer', 'run', positional: [0]),
];
/// Function with closure parameters that cannot accept null arguments.
class NonNullableFunction {
final String? library;
final String? type;
final String? name;
final List<int> positional;
final List<String> named;
NonNullableFunction(this.library, this.type, this.name,
{this.positional = const <int>[], this.named = const <String>[]});
@override
int get hashCode =>
JenkinsSmiHash.hash3(library.hashCode, type.hashCode, name.hashCode);
/// Two [NonNullableFunction] objects are equal if their [library], [type],
/// and [name] are equal, for the purpose of discovering whether a function
/// invocation is among a collection of non-nullable functions.
@override
bool operator ==(Object other) =>
other is NonNullableFunction && other.hashCode == hashCode;
}
class NullClosures extends LintRule implements NodeLintRule {
NullClosures()
: super(
name: 'null_closures',
description: _desc,
details: _details,
group: Group.style);
@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor = _Visitor(this);
registry.addInstanceCreationExpression(this, visitor);
registry.addMethodInvocation(this, visitor);
}
}
class _Visitor extends SimpleAstVisitor<void> {
final LintRule rule;
_Visitor(this.rule);
@override
void visitInstanceCreationExpression(InstanceCreationExpression node) {
var constructorName = node.constructorName;
var type = node.staticType;
for (var constructor in _constructorsWithNonNullableArguments) {
if (constructorName.name?.name == constructor.name) {
if (DartTypeUtilities.extendsClass(
type, constructor.type, constructor.library)) {
_checkNullArgForClosure(
node.argumentList, constructor.positional, constructor.named);
}
}
}
}
@override
void visitMethodInvocation(MethodInvocation node) {
var target = node.target;
var methodName = node.methodName.name;
var element = target is Identifier ? target.staticElement : null;
if (element is ClassElement) {
// Static function called, "target" is the class.
for (var function in _staticFunctionsWithNonNullableArguments) {
if (methodName == function.name) {
if (element.name == function.type) {
_checkNullArgForClosure(
node.argumentList, function.positional, function.named);
}
}
}
} else {
// Instance method called, "target" is the instance.
var targetType = target?.staticType;
var method = _getInstanceMethod(targetType, methodName);
if (method == null) {
return;
}
_checkNullArgForClosure(
node.argumentList, method.positional, method.named);
}
}
void _checkNullArgForClosure(
ArgumentList node, List<int> positions, List<String> names) {
var args = node.arguments;
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (arg is NamedExpression) {
if (arg.expression is NullLiteral &&
names.contains(arg.name.label.name)) {
rule.reportLint(arg);
}
} else {
if (arg is NullLiteral && positions.contains(i)) {
rule.reportLint(arg);
}
}
}
}
NonNullableFunction? _getInstanceMethod(DartType? type, String methodName) {
var possibleMethods = _instanceMethodsWithNonNullableArguments[methodName];
if (possibleMethods == null) {
return null;
}
if (type is! InterfaceType) {
return null;
}
NonNullableFunction? getMethod(String? library, String? className) =>
possibleMethods
.lookup(NonNullableFunction(library, className, methodName));
var method = getMethod(type.element.library.name, type.element.name);
if (method != null) {
return method;
}
var element = type.element;
if (element.isSynthetic) {
return null;
}
for (var supertype in element.allSupertypes) {
method =
getMethod(supertype.element.library.name, supertype.element.name);
if (method != null) {
return method;
}
}
return null;
}
}
|
linter/lib/src/rules/null_closures.dart/0
|
{'file_path': 'linter/lib/src/rules/null_closures.dart', 'repo_id': 'linter', 'token_count': 3941}
|
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import '../analyzer.dart';
import '../ast.dart';
const _desc = r'Prefer const over final for declarations.';
const _details = r'''
**PREFER** using `const` for const declarations.
Const declarations are more hot-reload friendly and allow to use const
constructors if an instantiation references this declaration.
**GOOD:**
```dart
const o = <int>[];
class A {
static const o = <int>[];
}
```
**BAD:**
```dart
final o = const <int>[];
class A {
static final o = const <int>[];
}
```
''';
class PreferConstDeclarations extends LintRule implements NodeLintRule {
PreferConstDeclarations()
: super(
name: 'prefer_const_declarations',
description: _desc,
details: _details,
group: Group.style);
@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor = _Visitor(this, context);
registry.addFieldDeclaration(this, visitor);
registry.addTopLevelVariableDeclaration(this, visitor);
registry.addVariableDeclarationStatement(this, visitor);
}
}
class _Visitor extends SimpleAstVisitor<void> {
final LintRule rule;
final LinterContext context;
_Visitor(this.rule, this.context);
@override
void visitFieldDeclaration(FieldDeclaration node) {
if (!node.isStatic) return;
_visitVariableDeclarationList(node.fields);
}
@override
void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) =>
_visitVariableDeclarationList(node.variables);
@override
void visitVariableDeclarationStatement(VariableDeclarationStatement node) =>
_visitVariableDeclarationList(node.variables);
void _visitVariableDeclarationList(VariableDeclarationList node) {
if (node.isConst) return;
if (!node.isFinal) return;
if (node.variables.every((declaration) {
var initializer = declaration.initializer;
return initializer != null &&
(initializer is! TypedLiteral ||
(initializer.beginToken.keyword == Keyword.CONST)) &&
!hasConstantError(context, initializer);
})) {
rule.reportLint(node);
}
}
}
|
linter/lib/src/rules/prefer_const_declarations.dart/0
|
{'file_path': 'linter/lib/src/rules/prefer_const_declarations.dart', 'repo_id': 'linter', 'token_count': 863}
|
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import '../analyzer.dart';
import '../util/dart_type_utilities.dart';
const _desc = r'Use initializing formals when possible.';
const _details = r'''
**DO** use initializing formals when possible.
Using initializing formals when possible makes your code more terse.
**BAD:**
```dart
class Point {
num x, y;
Point(num x, num y) {
this.x = x;
this.y = y;
}
}
```
**GOOD:**
```dart
class Point {
num x, y;
Point(this.x, this.y);
}
```
**BAD:**
```dart
class Point {
num x, y;
Point({num x, num y}) {
this.x = x;
this.y = y;
}
}
```
**GOOD:**
```dart
class Point {
num x, y;
Point({this.x, this.y});
}
```
**NOTE**
This rule will not generate a lint for named parameters unless the parameter
name and the field name are the same. The reason for this is that resolving
such a lint would require either renaming the field or renaming the parameter,
and both of those actions would potentially be a breaking change. For example,
the following will not generate a lint:
```darts
class Point {
bool isEnabled;
Point({bool enabled}) {
this.isEnabled = enable; // OK
}
}
```
''';
Iterable<AssignmentExpression> _getAssignmentExpressionsInConstructorBody(
ConstructorDeclaration node) {
var body = node.body;
var statements =
(body is BlockFunctionBody) ? body.block.statements : <Statement>[];
return statements
.whereType<ExpressionStatement>()
.map((e) => e.expression)
.whereType<AssignmentExpression>();
}
Iterable<ConstructorFieldInitializer>
_getConstructorFieldInitializersInInitializers(
ConstructorDeclaration node) =>
node.initializers.whereType<ConstructorFieldInitializer>();
Element? _getLeftElement(AssignmentExpression assignment) =>
DartTypeUtilities.getCanonicalElement(assignment.writeElement);
Iterable<Element?> _getParameters(ConstructorDeclaration node) =>
node.parameters.parameters.map((e) => e.identifier?.staticElement);
Element? _getRightElement(AssignmentExpression assignment) =>
DartTypeUtilities.getCanonicalElementFromIdentifier(
assignment.rightHandSide);
class PreferInitializingFormals extends LintRule implements NodeLintRule {
PreferInitializingFormals()
: super(
name: 'prefer_initializing_formals',
description: _desc,
details: _details,
group: Group.style);
@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor = _Visitor(this);
registry.addConstructorDeclaration(this, visitor);
}
}
class _Visitor extends SimpleAstVisitor<void> {
final LintRule rule;
_Visitor(this.rule);
@override
void visitConstructorDeclaration(ConstructorDeclaration node) {
var parameters = _getParameters(node);
var parametersUsedOnce = <Element?>{};
var parametersUsedMoreThanOnce = <Element?>{};
bool isAssignmentExpressionToLint(AssignmentExpression assignment) {
var leftElement = _getLeftElement(assignment);
var rightElement = _getRightElement(assignment);
return leftElement != null &&
rightElement != null &&
!leftElement.isPrivate &&
leftElement is FieldElement &&
!leftElement.isSynthetic &&
leftElement.enclosingElement ==
node.declaredElement?.enclosingElement &&
parameters.contains(rightElement) &&
(!parametersUsedMoreThanOnce.contains(rightElement) &&
!(rightElement as ParameterElement).isNamed ||
leftElement.name == rightElement.name);
}
bool isConstructorFieldInitializerToLint(
ConstructorFieldInitializer constructorFieldInitializer) {
var expression = constructorFieldInitializer.expression;
if (expression is SimpleIdentifier) {
var staticElement = expression.staticElement;
return staticElement is ParameterElement &&
!(constructorFieldInitializer.fieldName.staticElement?.isPrivate ??
true) &&
parameters.contains(staticElement) &&
(!parametersUsedMoreThanOnce.contains(expression.staticElement) &&
!staticElement.isNamed ||
(constructorFieldInitializer.fieldName.staticElement?.name ==
expression.staticElement?.name));
}
return false;
}
void processElement(Element? element) {
if (!parametersUsedOnce.add(element)) {
parametersUsedMoreThanOnce.add(element);
}
}
node.parameters.parameterElements
.where((p) => p != null && p.isInitializingFormal)
.forEach(processElement);
_getAssignmentExpressionsInConstructorBody(node)
.where(isAssignmentExpressionToLint)
.map(_getRightElement)
.forEach(processElement);
_getConstructorFieldInitializersInInitializers(node)
.where(isConstructorFieldInitializerToLint)
.map((e) => (e.expression as SimpleIdentifier).staticElement)
.forEach(processElement);
_getAssignmentExpressionsInConstructorBody(node)
.where(isAssignmentExpressionToLint)
.forEach(rule.reportLint);
_getConstructorFieldInitializersInInitializers(node)
.where(isConstructorFieldInitializerToLint)
.forEach(rule.reportLint);
}
}
|
linter/lib/src/rules/prefer_initializing_formals.dart/0
|
{'file_path': 'linter/lib/src/rules/prefer_initializing_formals.dart', 'repo_id': 'linter', 'token_count': 2097}
|
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import '../analyzer.dart';
const _desc = r'Provide a deprecation message, via @Deprecated("message").';
const _details = r'''
**DO** specify a deprecation message (with migration instructions and/or a
removal schedule) in the Deprecation constructor.
**BAD:**
```dart
@deprecated
void oldFunction(arg1, arg2) {}
```
**GOOD:**
```dart
@Deprecated("""
[oldFunction] is being deprecated in favor of [newFunction] (with slightly
different parameters; see [newFunction] for more information). [oldFunction]
will be removed on or after the 4.0.0 release.
""")
void oldFunction(arg1, arg2) {}
```
''';
class ProvideDeprecationMessage extends LintRule implements NodeLintRule {
ProvideDeprecationMessage()
: super(
name: 'provide_deprecation_message',
description: _desc,
details: _details,
group: Group.style);
@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor = _Visitor(this);
registry.addAnnotation(this, visitor);
}
}
class _Visitor extends SimpleAstVisitor<void> {
final LintRule rule;
_Visitor(this.rule);
@override
void visitAnnotation(Annotation node) {
var elementAnnotation = node.elementAnnotation;
if (elementAnnotation != null &&
elementAnnotation.isDeprecated &&
node.arguments == null) {
rule.reportLint(node);
}
}
}
|
linter/lib/src/rules/provide_deprecation_message.dart/0
|
{'file_path': 'linter/lib/src/rules/provide_deprecation_message.dart', 'repo_id': 'linter', 'token_count': 596}
|
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import '../analyzer.dart';
const _desc = "Don't type annotate initializing formals.";
const _details = r'''
From the [style guide](https://dart.dev/guides/language/effective-dart/style/):
**DON'T** type annotate initializing formals.
If a constructor parameter is using `this.x` to initialize a field, then the
type of the parameter is understood to be the same type as the field.
**GOOD:**
```dart
class Point {
int x, y;
Point(this.x, this.y);
}
```
**BAD:**
```dart
class Point {
int x, y;
Point(int this.x, int this.y);
}
```
''';
class TypeInitFormals extends LintRule implements NodeLintRule {
TypeInitFormals()
: super(
name: 'type_init_formals',
description: _desc,
details: _details,
group: Group.style);
@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor = _Visitor(this);
registry.addFieldFormalParameter(this, visitor);
}
}
class _Visitor extends SimpleAstVisitor<void> {
final LintRule rule;
_Visitor(this.rule);
@override
void visitFieldFormalParameter(FieldFormalParameter node) {
var nodeType = node.type;
if (nodeType != null) {
var cls = node.thisOrAncestorOfType<ClassDeclaration>()?.declaredElement;
if (cls != null) {
var field = cls.getField(node.identifier.name);
// If no such field exists, the code is invalid; do not report lint.
if (field != null) {
if (nodeType.type == field.type) {
rule.reportLint(nodeType);
}
}
}
}
}
}
|
linter/lib/src/rules/type_init_formals.dart/0
|
{'file_path': 'linter/lib/src/rules/type_init_formals.dart', 'repo_id': 'linter', 'token_count': 736}
|
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import '../analyzer.dart';
const _desc = r'Unnecessary raw string.';
const _details = r'''
Use raw string only when needed.
**BAD:**
```dart
var s1 = r'a';
```
**GOOD:**
```dart
var s1 = 'a';
var s2 = r'$a';
var s3 = r'\a';
```
''';
class UnnecessaryRawStrings extends LintRule implements NodeLintRule {
UnnecessaryRawStrings()
: super(
name: 'unnecessary_raw_strings',
description: _desc,
details: _details,
group: Group.style);
@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor = _Visitor(this);
registry.addSimpleStringLiteral(this, visitor);
}
}
class _Visitor extends SimpleAstVisitor<void> {
final LintRule rule;
_Visitor(this.rule);
@override
void visitSimpleStringLiteral(SimpleStringLiteral node) {
if (node.isRaw && ![r'\', r'$'].any(node.literal.lexeme.contains)) {
rule.reportLint(node);
}
}
}
|
linter/lib/src/rules/unnecessary_raw_strings.dart/0
|
{'file_path': 'linter/lib/src/rules/unnecessary_raw_strings.dart', 'repo_id': 'linter', 'token_count': 498}
|
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import '../analyzer.dart';
import '../util/dart_type_utilities.dart';
const _desc = r'Use rethrow to rethrow a caught exception.';
const _details = r'''
**DO** use rethrow to rethrow a caught exception.
As Dart provides rethrow as a feature, it should be used to improve terseness
and readability.
**BAD:**
```dart
try {
somethingRisky();
} catch(e) {
if (!canHandle(e)) throw e;
handle(e);
}
```
**GOOD:**
```dart
try {
somethingRisky();
} catch(e) {
if (!canHandle(e)) rethrow;
handle(e);
}
```
''';
class UseRethrowWhenPossible extends LintRule implements NodeLintRule {
UseRethrowWhenPossible()
: super(
name: 'use_rethrow_when_possible',
description: _desc,
details: _details,
group: Group.style);
@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor = _Visitor(this);
registry.addThrowExpression(this, visitor);
}
}
class _Visitor extends SimpleAstVisitor<void> {
final LintRule rule;
_Visitor(this.rule);
@override
void visitThrowExpression(ThrowExpression node) {
var element =
DartTypeUtilities.getCanonicalElementFromIdentifier(node.expression);
if (element != null) {
var catchClause = node.thisOrAncestorOfType<CatchClause>();
var exceptionParameter =
DartTypeUtilities.getCanonicalElementFromIdentifier(
catchClause?.exceptionParameter);
if (element == exceptionParameter) {
rule.reportLint(node);
}
}
}
}
|
linter/lib/src/rules/use_rethrow_when_possible.dart/0
|
{'file_path': 'linter/lib/src/rules/use_rethrow_when_possible.dart', 'repo_id': 'linter', 'token_count': 702}
|
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:collection/collection.dart' show IterableExtension;
import '../analyzer.dart';
import '../util/dart_type_utilities.dart';
typedef _InterfaceTypePredicate = bool Function(InterfaceType type);
/// Returns a predicate which returns whether a given [InterfaceTypeDefinition]
/// is equal to [definition].
_InterfaceTypePredicate _buildImplementsDefinitionPredicate(
InterfaceTypeDefinition definition) =>
(InterfaceType interface) =>
interface.element.name == definition.name &&
interface.element.library.name == definition.library;
/// Returns the first type argument on [definition], as implemented by [type].
///
/// In the simplest case, [type] is the same class as [definition]. For
/// example, given the definition `List<E>` and the type `List<int>`,
/// this function returns the DartType for `int`.
///
/// In a more complicated case, we must traverse [type]'s interfaces to find
/// [definition]. For example, given the definition `Set<E>` and the type `A`
/// where `A implements B<List, String>` and `B<E, F> implements Set<F>, C<E>`,
/// this function returns the DartType for `String`.
DartType? _findIterableTypeArgument(
InterfaceTypeDefinition definition, InterfaceType? type,
{List<InterfaceType> accumulator = const []}) {
if (type == null ||
type.isDartCoreObject ||
type.isDynamic ||
accumulator.contains(type)) {
return null;
}
var predicate = _buildImplementsDefinitionPredicate(definition);
if (predicate(type)) {
return type.typeArguments.first;
}
var implementedInterfaces = type.allSupertypes;
var interface = implementedInterfaces.firstWhereOrNull(predicate);
if (interface != null && interface.typeArguments.isNotEmpty) {
return interface.typeArguments.first;
}
return _findIterableTypeArgument(definition, type.superclass,
accumulator: [type, ...accumulator, ...implementedInterfaces]);
}
bool _isParameterizedMethodInvocation(
String methodName, MethodInvocation node) =>
node.methodName.name == methodName &&
node.argumentList.arguments.length == 1;
/// Base class for visitor used in rules where we want to lint about invoking
/// methods on generic classes where the type of the singular argument is
/// unrelated to the singular type argument of the class. Extending this
/// visitor is as simple as knowing the method, class and library that uniquely
/// define the target, i.e. implement only [definition] and [methodName].
abstract class UnrelatedTypesProcessors extends SimpleAstVisitor<void> {
final LintRule rule;
final TypeSystem typeSystem;
UnrelatedTypesProcessors(this.rule, this.typeSystem);
/// The type definition which this [UnrelatedTypesProcessors] is concerned
/// with.
InterfaceTypeDefinition get definition;
/// The name of the method which this [UnrelatedTypesProcessors] is concerned
/// with.
String get methodName;
@override
void visitMethodInvocation(MethodInvocation node) {
if (!_isParameterizedMethodInvocation(methodName, node)) {
return;
}
// At this point, we know that [node] is an invocation of a method which
// has the same name as the method that this UnrelatedTypesProcessors] is
// concerned with, and that the method has a single parameter.
//
// We've completed the "cheap" checks, and must now continue with the
// arduous task of determining whether the method target implements
// [definition].
DartType? targetType;
var target = node.target;
if (target != null) {
targetType = target.staticType;
} else {
var classDeclaration =
node.thisOrAncestorOfType<ClassOrMixinDeclaration>();
if (classDeclaration == null) {
targetType = null;
} else if (classDeclaration is ClassDeclaration) {
targetType = classDeclaration.declaredElement?.thisType;
} else if (classDeclaration is MixinDeclaration) {
targetType = classDeclaration.declaredElement?.thisType;
}
}
var argument = node.argumentList.arguments.first;
// Finally, determine whether the type of the argument is related to the
// type of the method target.
if (targetType is InterfaceType &&
DartTypeUtilities.unrelatedTypes(typeSystem, argument.staticType,
_findIterableTypeArgument(definition, targetType))) {
rule.reportLint(node);
}
}
}
|
linter/lib/src/util/unrelated_types_visitor.dart/0
|
{'file_path': 'linter/lib/src/util/unrelated_types_visitor.dart', 'repo_id': 'linter', 'token_count': 1453}
|
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// test w/ `dart test -N avoid_renaming_method_parameters`
abstract class A {
m1();
m2(a);
m3(String a, int b);
m4([a]);
m5(a);
m6(a, {b});
m7(a, {b});
}
abstract class B extends A {
m1(); // OK
m2(a); // OK
m3(Object a, num b); // OK
m4([a]); // OK
m5(a, [b]); // OK
m6(a, {b}); // OK
m7(a, {b}); // OK
}
abstract class C extends A {
m1(); // OK
m2(aa); // LINT
m3(
Object aa, // LINT
num bb, // LINT
);
m4([aa]); // LINT
m5(aa, [b]); // LINT
m6(aa, {b}); // LINT
m7(a, {c, b}); // OK
}
abstract class D extends A {
/// doc comments
m1(); // OK
/// doc comments
m2(aa); // OK
/// doc comments
m3(
Object aa, // OK
num bb, // OK
);
/// doc comments
m4([aa]); // OK
/// doc comments
m5(aa, [b]); // OK
/// doc comments
m6(aa, {b}); // OK
/// doc comments
m7(a, {c, b}); // OK
}
abstract class _E extends A {
m1(); // OK
m2(aa); // OK
m3(
Object aa, // OK
num bb, // OK
);
m4([aa]); // OK
m5(aa, [b]); // OK
m6(aa, {b}); // OK
m7(a, {c, b}); // OK
}
|
linter/test/_data/avoid_renaming_method_parameters/lib/a.dart/0
|
{'file_path': 'linter/test/_data/avoid_renaming_method_parameters/lib/a.dart', 'repo_id': 'linter', 'token_count': 575}
|
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:math'; // OK
import 'dummy.dart';
import 'dart:html'; // LINT
import 'dart:isolate'; // LINT
export 'dart:math'; // OK
export 'dummy.dart';
export 'dart:html'; // LINT
export 'dart:isolate'; // LINT
|
linter/test/_data/directives_ordering/dart_directives_go_first/bad.dart/0
|
{'file_path': 'linter/test/_data/directives_ordering/dart_directives_go_first/bad.dart', 'repo_id': 'linter', 'token_count': 146}
|
files:
exclude: test/_data/p2/src/ignored/**
|
linter/test/_data/p2/lintconfig.yaml/0
|
{'file_path': 'linter/test/_data/p2/lintconfig.yaml', 'repo_id': 'linter', 'token_count': 18}
|
class A {
A.c1(a) : assert(a != null); // OK
A.c2(a)
: assert(a != null) // OK
{
assert(a != null); // LINT
print('');
assert(a != null); // OK
}
}
|
linter/test/_data/prefer_asserts_in_initializer_lists/lib.dart/0
|
{'file_path': 'linter/test/_data/prefer_asserts_in_initializer_lists/lib.dart', 'repo_id': 'linter', 'token_count': 85}
|
import 'dart:core' as core;
import 'b.dart' deferred as b;
void f() {
[].removeWhere((o) => b.isB(o)); //OK
[].forEach((e) { core.print(e); }); //LINT
}
|
linter/test/_data/unnecessary_lambdas/src/a.dart/0
|
{'file_path': 'linter/test/_data/unnecessary_lambdas/src/a.dart', 'repo_id': 'linter', 'token_count': 71}
|
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:io';
import 'package:analyzer/src/lint/io.dart';
import 'package:linter/src/cli.dart' as cli;
import 'package:test/test.dart';
import '../mocks.dart';
void main() {
group('directives_ordering', () {
var currentOut = outSink;
var collectingOut = CollectingSink();
setUp(() {
exitCode = 0;
outSink = collectingOut;
});
tearDown(() {
collectingOut.buffer.clear();
outSink = currentOut;
exitCode = 0;
});
test('dart_directives_go_first', () async {
var packagesFilePath = File('.packages').absolute.path;
await cli.run([
'--packages',
packagesFilePath,
'test/_data/directives_ordering/dart_directives_go_first',
'--rules=directives_ordering'
]);
expect(
collectingOut.trim(),
stringContainsInOrder([
"Place 'dart:' imports before other imports.",
"import 'dart:html'; // LINT",
"Place 'dart:' imports before other imports.",
"import 'dart:isolate'; // LINT",
"Place 'dart:' exports before other exports.",
"export 'dart:html'; // LINT",
"Place 'dart:' exports before other exports.",
"export 'dart:isolate'; // LINT",
'2 files analyzed, 4 issues found, in'
]));
expect(exitCode, 1);
});
test('package_directives_before_relative', () async {
var packagesFilePath = File('.packages').absolute.path;
await cli.run([
'--packages',
packagesFilePath,
'test/_data/directives_ordering/package_directives_before_relative',
'--rules=directives_ordering'
]);
expect(
collectingOut.trim(),
stringContainsInOrder([
"Place 'package:' imports before relative imports.",
"import 'package:async/src/async_cache.dart'; // LINT",
"Place 'package:' imports before relative imports.",
"import 'package:yaml/yaml.dart'; // LINT",
"Place 'package:' exports before relative exports.",
"export 'package:async/src/async_cache.dart'; // LINT",
"Place 'package:' exports before relative exports.",
"export 'package:yaml/yaml.dart'; // LINT",
'3 files analyzed, 4 issues found, in'
]));
expect(exitCode, 1);
});
test('export_directives_after_import_directives', () async {
var packagesFilePath = File('.packages').absolute.path;
await cli.run([
'--packages',
packagesFilePath,
'test/_data/directives_ordering/export_directives_after_import_directives',
'--rules=directives_ordering'
]);
expect(
collectingOut.trim(),
stringContainsInOrder([
'Specify exports in a separate section after all imports.',
"export 'dummy.dart'; // LINT",
'Specify exports in a separate section after all imports.',
"export 'dummy2.dart'; // LINT",
'5 files analyzed, 2 issues found, in'
]));
expect(exitCode, 1);
});
test('sort_directive_sections_alphabetically', () async {
var packagesFilePath = File('.packages').absolute.path;
await cli.run([
'--packages',
packagesFilePath,
'test/_data/directives_ordering/sort_directive_sections_alphabetically',
'--rules=directives_ordering'
]);
expect(
collectingOut.trim(),
stringContainsInOrder([
'Sort directive sections alphabetically.',
"import 'dart:convert'; // LINT",
'Sort directive sections alphabetically.',
"import 'package:charcode/ascii.dart'; // LINT",
'Sort directive sections alphabetically.',
"import 'package:async/async.dart'; // LINT",
'Sort directive sections alphabetically.',
"import 'package:linter/src/formatter.dart'; // LINT",
'Sort directive sections alphabetically.',
"import 'dummy3.dart'; // LINT",
'Sort directive sections alphabetically.',
"import 'dummy2.dart'; // LINT",
'Sort directive sections alphabetically.',
"import 'dummy1.dart'; // LINT",
'Sort directive sections alphabetically.',
"export 'dart:convert'; // LINT",
'Sort directive sections alphabetically.',
"export 'package:charcode/ascii.dart'; // LINT",
'Sort directive sections alphabetically.',
"export 'package:async/async.dart'; // LINT",
'Sort directive sections alphabetically.',
"export 'package:linter/src/formatter.dart'; // LINT",
'Sort directive sections alphabetically.',
"export 'dummy1.dart'; // LINT",
'5 files analyzed, 12 issues found, in'
]));
expect(exitCode, 1);
});
test('lint_one_node_no_more_than_once', () async {
var packagesFilePath = File('.packages').absolute.path;
await cli.run([
'--packages',
packagesFilePath,
'test/_data/directives_ordering/lint_one_node_no_more_than_once',
'--rules=directives_ordering'
]);
expect(
collectingOut.trim(),
stringContainsInOrder([
"Place 'package:' imports before relative imports.",
"import 'package:async/async.dart'; // LINT",
'2 files analyzed, 1 issue found, in'
]));
expect(exitCode, 1);
});
});
}
|
linter/test/integration/directives_ordering.dart/0
|
{'file_path': 'linter/test/integration/directives_ordering.dart', 'repo_id': 'linter', 'token_count': 2527}
|
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:io';
import 'package:analyzer/src/lint/io.dart';
import 'package:analyzer/src/lint/linter.dart';
import 'package:linter/src/analyzer.dart';
import 'package:linter/src/cli.dart' as cli;
import 'package:linter/src/rules.dart';
import 'package:test/test.dart';
import 'package:yaml/yaml.dart';
import 'integration/always_require_non_null_named_parameters.dart'
as always_require_non_null_named_parameters;
import 'integration/avoid_private_typedef_functions.dart'
as avoid_private_typedef_functions;
import 'integration/avoid_relative_lib_imports.dart'
as avoid_relative_lib_imports;
import 'integration/avoid_renaming_method_parameters.dart'
as avoid_renaming_method_parameters;
import 'integration/avoid_web_libraries_in_flutter.dart'
as avoid_web_libraries_in_flutter;
import 'integration/cancel_subscriptions.dart' as cancel_subscriptions;
import 'integration/close_sinks.dart' as close_sinks;
import 'integration/directives_ordering.dart' as directives_ordering;
import 'integration/exhaustive_cases.dart' as exhaustive_cases;
import 'integration/file_names.dart' as file_names;
import 'integration/flutter_style_todos.dart' as flutter_style_todos;
import 'integration/lines_longer_than_80_chars.dart'
as lines_longer_than_80_chars;
import 'integration/only_throw_errors.dart' as only_throw_errors;
import 'integration/overridden_fields.dart' as overridden_fields;
import 'integration/packages_file_test.dart' as packages_file_test;
import 'integration/prefer_asserts_in_initializer_lists.dart'
as prefer_asserts_in_initializer_lists;
import 'integration/prefer_const_constructors_in_immutables.dart'
as prefer_const_constructors_in_immutables;
import 'integration/prefer_mixin.dart' as prefer_mixin;
import 'integration/prefer_relative_imports.dart' as prefer_relative_imports;
import 'integration/public_member_api_docs.dart' as public_member_api_docs;
import 'integration/sort_pub_dependencies.dart' as sort_pub_dependencies;
import 'integration/unnecessary_lambdas.dart' as unnecessary_lambdas;
import 'integration/unnecessary_string_escapes.dart'
as unnecessary_string_escapes;
import 'mocks.dart';
import 'rules/experiments/experiments.dart';
void main() {
group('integration', () {
ruleTests();
coreTests();
});
}
void coreTests() {
group('core', () {
group('config', () {
var currentOut = outSink;
var collectingOut = CollectingSink();
setUp(() {
exitCode = 0;
outSink = collectingOut;
});
tearDown(() {
collectingOut.buffer.clear();
outSink = currentOut;
exitCode = 0;
});
test('excludes', () async {
await cli.run(['test/_data/p2', '-c', 'test/_data/p2/lintconfig.yaml']);
expect(
collectingOut.trim(),
stringContainsInOrder(
['4 files analyzed, 1 issue found (2 filtered), in']));
expect(exitCode, 1);
});
test('overrides', () async {
await cli
.run(['test/_data/p2', '-c', 'test/_data/p2/lintconfig2.yaml']);
expect(collectingOut.trim(),
stringContainsInOrder(['4 files analyzed, 0 issues found, in']));
expect(exitCode, 0);
});
test('default', () async {
await cli.run(['test/_data/p2']);
expect(collectingOut.trim(),
stringContainsInOrder(['4 files analyzed, 3 issues found, in']));
expect(exitCode, 1);
});
});
group('pubspec', () {
var currentOut = outSink;
var collectingOut = CollectingSink();
setUp(() => outSink = collectingOut);
tearDown(() {
collectingOut.buffer.clear();
outSink = currentOut;
});
test('bad pubspec', () async {
await cli.run(['test/_data/p3', 'test/_data/p3/_pubpspec.yaml']);
expect(collectingOut.trim(),
startsWith('1 file analyzed, 0 issues found, in'));
});
});
group('canonicalization', () {
var currentOut = outSink;
var collectingOut = CollectingSink();
setUp(() => outSink = collectingOut);
tearDown(() {
collectingOut.buffer.clear();
outSink = currentOut;
});
test('no warnings due to bad canonicalization', () async {
var packagesFilePath = File('test/_data/p4/_packages').absolute.path;
await cli.runLinter(['--packages', packagesFilePath, 'test/_data/p4'],
LinterOptions([]));
expect(collectingOut.trim(),
startsWith('3 files analyzed, 0 issues found, in'));
});
});
group('examples', () {
test('all.yaml', () {
var src = readFile('example/all.yaml');
var options = _getOptionsFromString(src);
var configuredLints =
// ignore: cast_nullable_to_non_nullable
(options['linter'] as YamlMap)['rules'] as YamlList;
// rules are sorted
expect(
configuredLints, orderedEquals(configuredLints.toList()..sort()));
registerLintRules();
var registered = Analyzer.facade.registeredRules
.where((r) =>
r.maturity != Maturity.deprecated && !experiments.contains(r))
.map((r) => r.name);
for (var l in configuredLints) {
if (!registered.contains(l)) {
print(l);
}
}
expect(
configuredLints,
unorderedEquals(Analyzer.facade.registeredRules
.where((r) =>
r.maturity != Maturity.deprecated &&
!experiments.contains(r))
.map((r) => r.name)));
});
});
});
}
void ruleTests() {
group('rule', () {
unnecessary_lambdas.main();
exhaustive_cases.main();
avoid_web_libraries_in_flutter.main();
packages_file_test.main();
overridden_fields.main();
close_sinks.main();
cancel_subscriptions.main();
directives_ordering.main();
file_names.main();
flutter_style_todos.main();
lines_longer_than_80_chars.main();
only_throw_errors.main();
always_require_non_null_named_parameters.main();
prefer_asserts_in_initializer_lists.main();
prefer_const_constructors_in_immutables.main();
avoid_relative_lib_imports.main();
prefer_relative_imports.main();
public_member_api_docs.main();
avoid_renaming_method_parameters.main();
avoid_private_typedef_functions.main();
sort_pub_dependencies.main();
unnecessary_string_escapes.main();
prefer_mixin.main();
});
}
/// Provide the options found in [optionsSource].
Map<String, YamlNode> _getOptionsFromString(String? optionsSource) {
var options = <String, YamlNode>{};
if (optionsSource == null) {
return options;
}
var doc = loadYamlNode(optionsSource);
// Empty options.
if (doc is YamlScalar && doc.value == null) {
return options;
}
if (doc is! YamlMap) {
throw Exception(
'Bad options file format (expected map, got ${doc.runtimeType})');
}
if (doc is YamlMap) {
doc.nodes.forEach((k, YamlNode v) {
Object? key;
if (k is YamlScalar) {
key = k.value;
}
if (key is! String) {
throw Exception('Bad options file format (expected String scope key, '
'got ${k.runtimeType})');
}
if (v is! YamlNode) {
throw Exception('Bad options file format (expected Node value, '
'got ${v.runtimeType}: `${v.toString()}`)');
}
options[key] = v;
});
}
return options;
}
|
linter/test/integration_test.dart/0
|
{'file_path': 'linter/test/integration_test.dart', 'repo_id': 'linter', 'token_count': 3215}
|
name: meta
version: 1.1.8
environment:
sdk: '>=2.2.2 <3.0.0'
|
linter/test/mock_packages/meta/pubspec.yaml/0
|
{'file_path': 'linter/test/mock_packages/meta/pubspec.yaml', 'repo_id': 'linter', 'token_count': 35}
|
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// test w/ `dart test -N avoid_double_and_int_checks`
lint_for_double_before_int_check_on_parameter(m) {
if (m is double) {} //
else if (m is int) {} // LINT
}
no_lint_for_only_double_check(m) {
if (m is double) {} // OK
}
no_lint_for_int_before_double_check(m) {
if (m is int) {} //
else if (m is double) {} // OK
}
lint_for_double_before_int_check_on_local() {
var m;
if (m is double) {} //
else if (m is int) {} // LINT
}
get g => null;
lint_for_double_before_int_check_on_getter() {
if (g is double) {} //
else if (g is int) {} // OK
}
|
linter/test/rules/avoid_double_and_int_checks.dart/0
|
{'file_path': 'linter/test/rules/avoid_double_and_int_checks.dart', 'repo_id': 'linter', 'token_count': 300}
|
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// test w/ `dart test -N camel_case_extensions`
extension fooBar // LINT
on Object { }
extension Foo_Bar //LINT
on Object {}
extension FooBar //OK
on Object {}
extension on Object { } //OK
|
linter/test/rules/camel_case_extensions.dart/0
|
{'file_path': 'linter/test/rules/camel_case_extensions.dart', 'repo_id': 'linter', 'token_count': 134}
|
// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// test w/ `dart test test/rule_test.dart -N avoid_dynamic_calls`
import 'dart:core';
import 'dart:core' as core_top_level_prefix_as;
void explicitDynamicType(dynamic object) {
object.foo(); // LINT
object.bar; // LINT
}
void implicitDynamicType(object) {
object.foo(); // LINT
object.bar; // LINT
}
// This would likely not pass at runtime, but we're using it for inference only.
T genericType<T>() => null as T;
void inferredDynamicType() {
var object = genericType();
object.foo(); // LINT
object.bar; // LINT
}
class Wrapper<T> {
final T field;
Wrapper(this.field);
}
void fieldDynamicType(Wrapper<dynamic> wrapper) {
wrapper.field.foo(); // LINT
wrapper.field.bar; // LINT
wrapper.field(); // LINT
(wrapper.field)(); // LINT
}
void cascadeExpressions(dynamic a, Wrapper<dynamic> b) {
a..b; // LINT
b..field; // OK
b
..toString
..field.a() // LINT
..field.b; // LINT
}
class TearOffFunction {
static int staticDoThing() => 0;
int doThing() => 0;
}
void otherPropertyAccessOrCalls(dynamic a) {
a(); // LINT
a?.b; // LINT
a!.b; // LINT
a?.b(); // LINT
a!.b(); // LINT
(a).b; // LINT
}
void tearOffFunctions(TearOffFunction a) {
var p = core_top_level_prefix_as.print; // OK
core_top_level_prefix_as.print('Hello'); // OK
p('Hello'); // OK
var doThing = a.doThing; // OK
doThing(); // OK
var staticDoThing = TearOffFunction.staticDoThing; // OK
staticDoThing(); // OK
identical(true, false); // OK
var alsoIdentical = identical;
alsoIdentical(true, false); // OK
}
typedef F = void Function();
void functionExpressionInvocations(
dynamic a(),
Function b(),
void Function() c,
d(),
F f,
F? fn,
) {
a(); // OK
a()(); // LINT
b(); // OK
b()(); // LINT
c(); // OK
d(); // OK
f.call; // OK
f.call(); // OK
fn?.call; // OK
fn?.call(); // OK
}
void typedFunctionButBasicallyDynamic(Function a, Wrapper<Function> b) {
a(); // LINT
b.field(); // LINT
(b.field)(); // LINT
a.call; // OK
a.call(); // LINT
}
void binaryExpressions(dynamic a, int b, bool c) {
a + a; // LINT
a + b; // LINT
a > b; // LINT
a < b; // LINT
a >= b; // LINT
a <= b; // LINT
a ^ b; // LINT
a | b; // LINT
a & b; // LINT
a % b; // LINT
a / b; // LINT
a ~/ b; // LINT
a >> b; // LINT
a << b; // LINT
a || c; // OK; this is an implicit downcast, not a dynamic call
a && c; // OK; this is an implicit downcast, not a dynamic call
b + a; // OK; this is an implicit downcast, not a dynamic call
a ?? b; // OK; this is a null comparison, not a dynamic call.
a is int; // OK
a is! int; // OK
a as int; // OK
}
void equalityExpressions(dynamic a, dynamic b) {
a == b; // OK, see lint description for details.
a == null; // OK.
a != b; // OK
a != null; // OK.
}
void membersThatExistOnObject(dynamic a, Invocation b) {
a.hashCode; // OK
a.runtimeType; // OK
a.noSuchMethod(); // LINT
a.noSuchMethod(b); // OK
a.noSuchMethod(b, 1); // LINT
a.noSuchMethod(b, name: 1); // LINT
a.toString(); // OK
a.toString(1); // LINT
a.toString(name: 1); // LINT
'$a'; // OK
'${a}'; // OK
}
void memberTearOffsOnObject(dynamic a, Invocation b) {
var tearOffNoSuchMethod = a.noSuchMethod; // OK
tearOffNoSuchMethod(b); // OK
var tearOffToString = a.toString; // OK
tearOffToString(); // OK
}
void assignmentExpressions(dynamic a) {
a += 1; // LINT
a -= 1; // LINT
a *= 1; // LINT
a ^= 1; // LINT
a /= 1; // LINT
a &= 1; // LINT
a |= 1; // LINT
a ??= 1; // OK
}
void prefixExpressions(dynamic a, int b) {
!a; // LINT
-a; // LINT
++a; // LINT
--a; // LINT
++b; // OK
--b; // OK
}
void postfixExpressions(dynamic a, int b) {
a!; // OK; this is not a dynamic call.
a++; // LINT
a--; // LINT
b++; // OK
b--; // OK
}
void indexExpressions(dynamic a) {
a[1]; // LINT
a[1] = 1; // LINT
a = a[1]; // LINT
}
|
linter/test/rules/experiments/nnbd/rules/avoid_dynamic_calls.dart/0
|
{'file_path': 'linter/test/rules/experiments/nnbd/rules/avoid_dynamic_calls.dart', 'repo_id': 'linter', 'token_count': 1638}
|
analyzer:
enable-experiment:
- nonfunction-type-aliases
|
linter/test/rules/experiments/nonfunction-type-aliases/analysis_options.yaml/0
|
{'file_path': 'linter/test/rules/experiments/nonfunction-type-aliases/analysis_options.yaml', 'repo_id': 'linter', 'token_count': 23}
|
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// test w/ `dart test -N no_adjacent_strings_in_list`
void bad() {
List<String> list = <String>[
'a' // LINT
'b',
'c',
];
List<String> list2 = <String>[
'a' // LINT
'b'
'c'
];
}
void good() {
List<String> list = <String>[
'a' + // OK
'b',
'c',
];
}
|
linter/test/rules/no_adjacent_strings_in_list.dart/0
|
{'file_path': 'linter/test/rules/no_adjacent_strings_in_list.dart', 'repo_id': 'linter', 'token_count': 208}
|
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// @dart=2.9
// test w/ `dart test -N prefer_bool_in_asserts`
main() {
assert(true); // OK
assert(true, 'message'); // OK
assert(() => true); // LINT
assert(() => true, 'message'); // LINT
assert((() => true)()); // OK
assert((() => true)(), 'message'); // OK
assert(() { return true; }); // LINT
assert(() { return true; }, 'message'); // LINT
assert(() { return true; }()); // OK
assert(() { return true; }(), 'message'); // OK
assert(() { throw ""; }()); // OK
}
m1(p) {
assert(() { return p; }()); // OK
}
m2(Object p) {
assert(() { return p; }()); // OK
}
m3<T>(T p) {
assert(() { return p; }()); // OK
}
m4<T extends List>(T p) {
assert(() { return p; }()); // LINT
}
m5<S, T extends S>(T p) {
assert(() { return p; }()); // OK
}
m6<S extends List, T extends S>(T p) {
assert(() { return p; }()); // LINT
}
|
linter/test/rules/prefer_bool_in_asserts.dart/0
|
{'file_path': 'linter/test/rules/prefer_bool_in_asserts.dart', 'repo_id': 'linter', 'token_count': 391}
|
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// test w/ `dart test -N prefer_foreach`
void f(Object o) {}
void foo() {
final myList = [];
for (final a in myList) { // LINT
f(a);
}
}
void foo2() {
for (final a in []) { //LINT
(f(a));
}
}
Function func() => null;
void foo3() {
for (final a in <int>[1]) { //LINT
func()(a);
}
}
class WithMethods {
void f(Object o) {}
void foo() {
final myList = [];
for (final a in myList) { // LINT
f(a);
}
}
}
class WithThirdPartyMethods {
WithMethods x;
void foo() {
final myList = [];
for (final a in myList) { // LINT
x.f(a);
}
}
}
class WithElementInTarget {
List<WithMethods> myList;
void good() {
for (final x in myList) { // OK because x is the target
x.f(x);
}
}
void good2() {
for (final x in myList) { // OK because x is in the target
myList[myList.indexOf(x)].f(x);
}
}
}
class WithStaticMethods {
static void f(Object o) {}
void foo() {
final myList = [];
for (final a in myList) { // LINT
WithStaticMethods.f(a);
}
}
}
|
linter/test/rules/prefer_foreach.dart/0
|
{'file_path': 'linter/test/rules/prefer_foreach.dart', 'repo_id': 'linter', 'token_count': 527}
|
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// test w/ `dart test -N prefer_single_quotes`
import "dart:collection"; // LINT
import 'dart:async'; // OK
main() {
String string1 = "no quote"; // LINT
String string2 = 'uses single'; // OK
String string3 = "has quote '"; // OK
String rawString1 = r"no quote"; // LINT
String rawString2 = r'uses single'; // OK
String rawString3 = r"has quote '"; // OK
String multilineString1 = r"""no quote"""; // LINT
String multilineString2 = r'''uses single'''; // OK
String multilineString3 = r"""has quote '"""; // OK
String x = 'x';
String interpString1 = "no quote $x"; // LINT
String interpString2 = 'uses single $x'; // OK
String interpString3 = "has quote ' $x"; // OK
String interpString4 = "no quote $x has quote ' $x no quote"; // OK
String interpString5 = "no quote $x no quote $x no quote"; // LINT
String stringWithinStringDoubleFirst = "foo ${x == 'x'} bar"; // OK
String stringWithinStringSingleFirst = 'foo ${x == "x"} bar'; // OK
}
|
linter/test/rules/prefer_single_quotes.dart/0
|
{'file_path': 'linter/test/rules/prefer_single_quotes.dart', 'repo_id': 'linter', 'token_count': 386}
|
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// test w/ `dart test -N type_annotate_public_apis`
class AA {
final a = AA(); //OK
static final aa = AA(); //OK
final i = 0; //OK
static final ii = 0; //OK
final d = dyn(); //LINT
static final dd = dyn(); //LINT
final n = null; //LINT
static final nn = null; //LINT
}
dynamic dyn() => null;
const X = ''; //OK
f() {} //LINT
void g(x) {} //LINT
void h() {
void i(x) {} // OK
j() {} // OK
}
typedef Foo(x); //LINT
typedef void Bar(int x);
int get xxx => 42; //OK: #151
get xxxx => 42; //LINT
set x(x) {} // LINT
set xx(int x) {} // OK
_f() {}
const _X = '';
class A {
var x; // LINT
static const y = ''; //OK
static final z = 3; //OK
int get xxx => 42; //OK: #151
set xxxxx(x) {} // LINT
set xx(int x) {} // OK
get xxxx => 42; //LINT
var zzz, //LINT
_zzz;
f() {} //LINT
void g(x) {} //LINT
static h() {} //LINT
static void j(x) {} //LINT
static void k(var v) {} //LINT
void l(_) {} // OK!
void ll(__) {} // OK!
var _x;
final _xx = 1;
static const _y = '';
static final _z = 3;
void m() {}
_f() {}
void _g(x) {}
static _h() {}
static _j(x) {}
static _k(var x) {}
}
typedef _PrivateMethod(int value); //OK
typedef void _PrivateMethod2(value); //OK
extension Ext on A {
set x(x) { } // LINT
set _x(x) { } // OK
get x => 0; // LINT
f() {} // LINT
void j(j) { } // LINT
}
|
linter/test/rules/type_annotate_public_apis.dart/0
|
{'file_path': 'linter/test/rules/type_annotate_public_apis.dart', 'repo_id': 'linter', 'token_count': 658}
|
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// test w/ `dart test -N unnecessary_raw_strings`
f(o) {
f(r'a b c d');// LINT
f(r"a b c d");// LINT
f(r'''a b c d''');// LINT
f(r"""a b c d""");// LINT
// with \
f(r'a b c\d');// OK
f(r"a b c\d");// OK
f(r'''a b c\d''');// OK
f(r"""a b c\d""");// OK
// with $
f(r'a b c$d');// OK
f(r"a b c$d");// OK
f(r'''a b c$d''');// OK
f(r"""a b c$d""");// OK
}
|
linter/test/rules/unnecessary_raw_strings.dart/0
|
{'file_path': 'linter/test/rules/unnecessary_raw_strings.dart', 'repo_id': 'linter', 'token_count': 268}
|
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// test w/ `dart test -N use_setters_to_change_properties`
abstract class A {
int _w;
int _x;
void setW(int w) => _w = w; // LINT
void setW1(int w) => this._w = w; // LINT
void setX(int x) { // LINT
_x = x;
}
void setX1(int x) { // LINT
this._x = x;
}
void setY(int y);
void grow1(int value) => _w += value; //OK
}
class B extends A {
int _y;
void setY(int y) { // OK because it is an inherited method.
this._y = y;
}
}
abstract class C {
void setY(int y);
}
class D implements C {
int _y;
int dd;
void setY(int y) { // OK because it is an implementation method.
this._y = y;
}
}
extension E on D {
void setDD(int dd) { // LINT
this.dd = dd;
}
}
|
linter/test/rules/use_setters_to_change_properties.dart/0
|
{'file_path': 'linter/test/rules/use_setters_to_change_properties.dart', 'repo_id': 'linter', 'token_count': 367}
|
import 'package:flutter/cupertino.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:liquid_swipe/Clippers/CircularWave.dart';
import 'package:liquid_swipe/Clippers/WaveLayer.dart';
import 'package:liquid_swipe/Helpers/Helpers.dart';
final clipPathWidget = CircularWave(iconSize, 0.0, 0.0);
final iconSize = Size(50, 50);
void main() {
testWidgets('Circular Test : ', (WidgetTester tester) async {
await tester.pumpWidget(ClipPath(
clipper: clipPathWidget,
));
final findClipPath = find.byType(ClipPath);
expect(findClipPath, findsOneWidget);
});
group("CircularWave Method Tests", () {
test('revealPercent', () {
expect(clipPathWidget.revealPercent, equals(0.0));
});
test('verReveal', () {
expect(clipPathWidget.verReveal, equals(0.0));
});
test('getPAth', () {
expect(clipPathWidget.getClip(iconSize).runtimeType, Path);
});
test('shouldReclip', () {
expect(clipPathWidget.shouldReclip(clipPathWidget), true);
});
});
}
|
liquid_swipe_flutter/test/Clippers/CircularWave_test.dart/0
|
{'file_path': 'liquid_swipe_flutter/test/Clippers/CircularWave_test.dart', 'repo_id': 'liquid_swipe_flutter', 'token_count': 400}
|
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:local_widget_state_approaches/hooks/animated_counter.dart';
import 'package:local_widget_state_approaches/hooks/animation.dart';
import 'package:local_widget_state_approaches/hooks/multiple_animation_controller.dart';
import 'package:local_widget_state_approaches/stateful/animated_counter.dart';
import 'package:local_widget_state_approaches/stateful/multiple_animation_controller.dart';
import 'hooks/counter.dart' show CounterHooks;
// import 'lateProperty/counter.dart' show LatePropertyCounter; // empty
import 'stateful/counter.dart' show StatefulCounter;
import 'stateful/animation.dart' show StatefulAnimation;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(),
);
}
}
enum Approach { hooks, stateful, lateProperty }
enum Examples {
counter,
animation,
animatedCouter,
multipleAnimationController,
}
class HomePage extends HookWidget {
Widget pageFor({Approach approach, Examples example}) {
switch (example) {
case Examples.counter:
switch (approach) {
case Approach.hooks:
return CounterHooks('Hook Counter');
case Approach.stateful:
return StatefulCounter(title: 'Stateful Counter');
case Approach.lateProperty:
return Text('unavailable'); // LatePropertyCounter(title: 'Late Property Counter');
}
break;
case Examples.animatedCouter:
switch (approach) {
case Approach.hooks:
return HookAnimatedCounter();
case Approach.stateful:
return StatefulAnimatedCounter();
case Approach.lateProperty:
return Text('unavailable'); // LatePropertyCounter(title: 'Late Property Counter');
}
break;
case Examples.multipleAnimationController:
switch (approach) {
case Approach.hooks:
return HookMultipleAnimationController();
case Approach.stateful:
return StatefulMultipleAnimationController();
case Approach.lateProperty:
return Text('unavailable'); // LatePropertyCounter(title: 'Late Property Counter');
}
break;
case Examples.animation:
switch (approach) {
case Approach.hooks:
return HookAnimation();
case Approach.stateful:
return StatefulAnimation();
case Approach.lateProperty:
return Text('unavailable'); // LatePropertyCounter(title: 'Late Property Counter');
}
break;
}
return null;
}
@override
Widget build(BuildContext context) {
final approach = useState(Approach.hooks);
final example = useState(Examples.counter);
return Row(
children: [
NavigationRail(
destinations: [
...Examples.values.map(
(a) => NavigationRailDestination(
icon: Container(), label: Text(a.toString().split('.')[1])),
),
],
selectedIndex: Examples.values.indexOf(example.value),
onDestinationSelected: (i) => example.value = Examples.values[i],
labelType: NavigationRailLabelType.all,
),
NavigationRail(
destinations: [
...Approach.values.map(
(a) => NavigationRailDestination(
icon: Container(), label: Text(a.toString().split('.')[1])),
),
],
selectedIndex: Approach.values.indexOf(approach.value),
onDestinationSelected: (i) => approach.value = Approach.values[i],
labelType: NavigationRailLabelType.all,
),
Expanded(child: pageFor(approach: approach.value, example: example.value)),
],
);
}
}
|
local_widget_state_approaches/lib/main.dart/0
|
{'file_path': 'local_widget_state_approaches/lib/main.dart', 'repo_id': 'local_widget_state_approaches', 'token_count': 1648}
|
export 'lumberdash_client.dart';
|
lumberdash/lib/src/client/client.dart/0
|
{'file_path': 'lumberdash/lib/src/client/client.dart', 'repo_id': 'lumberdash', 'token_count': 12}
|
name: favorite_color
description: A new brick created with the Mason CLI.
version: 0.1.0+1
environment:
mason: ">=0.1.0-dev <0.1.0"
vars:
color:
type: enum
description: Your favorite color
default: green
prompt: What is your favorite color?
values:
- red
- green
- blue
|
mason/bricks/favorite_color/brick.yaml/0
|
{'file_path': 'mason/bricks/favorite_color/brick.yaml', 'repo_id': 'mason', 'token_count': 129}
|
# See https://github.com/dart-lang/build/tree/master/build_web_compilers#configuration
targets:
$default:
sources:
exclude:
- test/**
builders:
json_serializable:
options:
any_map: true
disallow_unrecognized_keys: true
field_rename: kebab
include_if_null: false
checked: true
explicit_to_json: true
create_to_json: true
|
mason/packages/mason/build.yaml/0
|
{'file_path': 'mason/packages/mason/build.yaml', 'repo_id': 'mason', 'token_count': 208}
|
import 'package:json_annotation/json_annotation.dart';
import 'package:mason/mason.dart';
part 'mason_lock_json.g.dart';
/// {@template mason_lock_json}
/// Mason lock file which contains locked brick locations.
/// {@endtemplate}
@JsonSerializable()
class MasonLockJson {
/// {@macro mason_lock}
const MasonLockJson({Map<String, BrickLocation>? bricks})
: bricks = bricks ?? const <String, BrickLocation>{};
/// Converts [Map] to [MasonLockJson]
factory MasonLockJson.fromJson(Map<dynamic, dynamic> json) =>
_$MasonLockJsonFromJson(json);
/// Converts [MasonLockJson] to [Map]
Map<dynamic, dynamic> toJson() => _$MasonLockJsonToJson(this);
/// static constant for mason lock file name.
/// `mason-lock.json`
static const file = 'mason-lock.json';
/// static constant for an empty `mason-lock.yaml` file.
static const empty = MasonLockJson();
/// [Map] of [BrickLocation] alias to [BrickLocation] instances.
final Map<String, BrickLocation> bricks;
}
|
mason/packages/mason/lib/src/mason_lock_json.dart/0
|
{'file_path': 'mason/packages/mason/lib/src/mason_lock_json.dart', 'repo_id': 'mason', 'token_count': 345}
|
name: nested_conditional
description: A new brick created with the Mason CLI.
version: 0.1.0+1
environment:
mason: ">=0.1.0-dev <0.1.0"
vars:
name:
type: string
description: Your name
default: Dash
prompt: What is your name?
generate:
type: boolean
description: Whether to generate a file
prompt: Do you want to generate a file?
|
mason/packages/mason/test/bricks/nested_conditional/brick.yaml/0
|
{'file_path': 'mason/packages/mason/test/bricks/nested_conditional/brick.yaml', 'repo_id': 'mason', 'token_count': 134}
|
name: dependency_install_failure_hook
description: A Test Hook
version: 0.1.0+1
|
mason/packages/mason/test/fixtures/dependency_install_failure/brick.yaml/0
|
{'file_path': 'mason/packages/mason/test/fixtures/dependency_install_failure/brick.yaml', 'repo_id': 'mason', 'token_count': 27}
|
import 'package:mason/mason.dart';
import 'package:test/test.dart';
void main() {
const mockText = 'This is-Some_sampleText. YouDig?';
group('StringCaseExtensions', () {
group('snake_case', () {
test('from empty string.', () {
expect(''.snakeCase, equals(''));
});
test('from "$mockText".', () {
expect(mockText.snakeCase, equals('this_is_some_sample_text_you_dig?'));
});
});
group('dot.case', () {
test('from empty string.', () {
expect(''.dotCase, equals(''));
});
test('from "$mockText".', () {
expect(mockText.dotCase, equals('this.is.some.sample.text.you.dig?'));
});
});
group('path/case', () {
test('from empty string.', () {
expect(''.pathCase, equals(''));
});
test('from "$mockText".', () {
expect(mockText.pathCase, equals('this/is/some/sample/text/you/dig?'));
});
});
group('param-case', () {
test('from empty string.', () {
expect(''.paramCase, equals(''));
});
test('from "$mockText".', () {
expect(mockText.paramCase, equals('this-is-some-sample-text-you-dig?'));
});
});
group('PascalCase', () {
test('from empty string.', () {
expect(''.pascalCase, equals(''));
});
test('from "$mockText".', () {
expect(mockText.pascalCase, equals('ThisIsSomeSampleTextYouDig?'));
});
});
group('Pascal.Dot.Case', () {
test('from empty string.', () {
expect(''.pascalDotCase, equals(''));
});
test('from "$mockText".', () {
expect(
mockText.pascalDotCase,
equals('This.Is.Some.Sample.Text.You.Dig?'),
);
});
});
group('Header-Case', () {
test('from empty string.', () {
expect(''.headerCase, equals(''));
});
test('from "$mockText".', () {
expect(
mockText.headerCase,
equals('This-Is-Some-Sample-Text-You-Dig?'),
);
});
});
group('Title Case', () {
test('from empty string.', () {
expect(''.titleCase, equals(''));
});
test('from "$mockText".', () {
expect(mockText.titleCase, equals('This Is Some Sample Text You Dig?'));
});
});
group('camelCase', () {
test('from empty string.', () {
expect(''.camelCase, equals(''));
});
test('from "$mockText".', () {
expect(mockText.camelCase, equals('thisIsSomeSampleTextYouDig?'));
});
});
group('Sentence case', () {
test('from empty string.', () {
expect(''.sentenceCase, equals(''));
});
test('from "$mockText".', () {
expect(
mockText.sentenceCase,
equals('This is some sample text you dig?'),
);
});
});
group('CONSTANT_CASE', () {
test('from empty string.', () {
expect(''.constantCase, equals(''));
});
test('from "$mockText".', () {
expect(
mockText.constantCase,
equals('THIS_IS_SOME_SAMPLE_TEXT_YOU_DIG?'),
);
});
});
});
}
|
mason/packages/mason/test/src/string_case_extensions_test.dart/0
|
{'file_path': 'mason/packages/mason/test/src/string_case_extensions_test.dart', 'repo_id': 'mason', 'token_count': 1446}
|
import 'dart:io';
import 'package:mason/mason.dart' hide packageVersion;
import 'package:mason_cli/src/command_runner.dart';
import 'package:mason_cli/src/version.dart';
import 'package:mocktail/mocktail.dart';
import 'package:path/path.dart' as path;
import 'package:pub_updater/pub_updater.dart';
import 'package:test/test.dart';
import '../helpers/helpers.dart';
class _MockLogger extends Mock implements Logger {}
class _MockPubUpdater extends Mock implements PubUpdater {}
class _MockProgress extends Mock implements Progress {}
void main() {
final cwd = Directory.current;
group('mason init', () {
late Logger logger;
late Progress progress;
late PubUpdater pubUpdater;
late MasonCommandRunner commandRunner;
setUp(() {
logger = _MockLogger();
progress = _MockProgress();
pubUpdater = _MockPubUpdater();
when(() => logger.progress(any())).thenReturn(progress);
when(
() => pubUpdater.getLatestVersion(any()),
).thenAnswer((_) async => packageVersion);
commandRunner = MasonCommandRunner(
logger: logger,
pubUpdater: pubUpdater,
);
setUpTestingEnvironment(cwd, suffix: '.init');
});
tearDown(() {
Directory.current = cwd;
});
test('exits with code 64 when mason.yaml already exists', () async {
final masonYaml = File(path.join(Directory.current.path, 'mason.yaml'));
await masonYaml.create(recursive: true);
final result = await commandRunner.run(['init']);
expect(result, equals(ExitCode.usage.code));
verify(
() => logger.err('''Existing mason.yaml at ${masonYaml.path}'''),
).called(1);
});
test('initializes mason when a mason.yaml does not exist', () async {
final result = await commandRunner.run(['init']);
expect(result, equals(ExitCode.success.code));
final actual = Directory(
path.join(testFixturesPath(cwd, suffix: '.init')),
);
final expected = Directory(
path.join(testFixturesPath(cwd, suffix: 'init')),
);
expect(directoriesDeepEqual(actual, expected), isTrue);
expect(
File(path.join(actual.path, '.mason', 'bricks.json')).existsSync(),
isFalse,
);
verify(() => logger.progress('Initializing')).called(1);
verify(() => progress.complete('Generated 1 file.')).called(1);
});
});
}
|
mason/packages/mason_cli/test/commands/init_test.dart/0
|
{'file_path': 'mason/packages/mason_cli/test/commands/init_test.dart', 'repo_id': 'mason', 'token_count': 933}
|
export 'directories_deep_equal.dart';
export 'override_print.dart';
export 'set_up_testing_environment.dart';
|
mason/packages/mason_cli/test/helpers/helpers.dart/0
|
{'file_path': 'mason/packages/mason_cli/test/helpers/helpers.dart', 'repo_id': 'mason', 'token_count': 38}
|
// coverage:ignore-file
import 'dart:io';
import 'package:mason_logger/src/ffi/unix_terminal.dart';
import 'package:mason_logger/src/ffi/windows_terminal.dart';
/// {@template terminal}
/// Interface for the underlying native terminal.
/// {@endtemplate}
abstract class Terminal {
/// {@macro terminal}
factory Terminal() => Platform.isWindows ? WindowsTerminal() : UnixTerminal();
/// Enables raw mode which allows us to process each keypress as it comes in.
/// https://viewsourcecode.org/snaptoken/kilo/02.enteringRawMode.html
void enableRawMode();
/// Disables raw mode and restores the terminal’s original attributes.
void disableRawMode();
}
|
mason/packages/mason_logger/lib/src/ffi/terminal.dart/0
|
{'file_path': 'mason/packages/mason_logger/lib/src/ffi/terminal.dart', 'repo_id': 'mason', 'token_count': 204}
|
import 'package:mason_logger/src/ffi/terminal.dart';
import 'package:mason_logger/src/io.dart';
import 'package:mason_logger/src/terminal_overrides.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
class _MockTerminal extends Mock implements Terminal {}
void main() {
group(TerminalOverrides, () {
group('runZoned', () {
test('uses default readKey when not specified', () {
TerminalOverrides.runZoned(() {
final overrides = TerminalOverrides.current;
expect(overrides!.readKey, isNotNull);
});
});
test('uses custom readKey when specified', () {
TerminalOverrides.runZoned(
() {
final overrides = TerminalOverrides.current;
expect(
overrides!.readKey(),
isA<KeyStroke>().having((s) => s.char, 'char', 'a'),
);
},
readKey: () => KeyStroke.char('a'),
);
});
test(
'uses current readKey when not specified '
'and zone already contains a readKey', () {
TerminalOverrides.runZoned(
() {
TerminalOverrides.runZoned(() {
final overrides = TerminalOverrides.current;
expect(
overrides!.readKey(),
isA<KeyStroke>().having((s) => s.char, 'char', 'x'),
);
});
},
readKey: () => KeyStroke.char('x'),
);
});
test(
'uses nested readKey when specified '
'and zone already contains a readKey', () {
KeyStroke rootReadKey() => KeyStroke.char('a');
TerminalOverrides.runZoned(
() {
KeyStroke nestedReadKey() => KeyStroke.char('b');
final overrides = TerminalOverrides.current;
expect(
overrides!.readKey(),
isA<KeyStroke>().having((s) => s.char, 'char', 'a'),
);
TerminalOverrides.runZoned(
() {
final overrides = TerminalOverrides.current;
expect(
overrides!.readKey(),
isA<KeyStroke>().having((s) => s.char, 'char', 'b'),
);
},
readKey: nestedReadKey,
);
},
readKey: rootReadKey,
);
});
test('uses default createTerminal when not specified', () {
TerminalOverrides.runZoned(() {
final overrides = TerminalOverrides.current;
expect(overrides!.createTerminal, isNotNull);
});
});
test('uses custom createTerminal when specified', () {
final Terminal terminal = _MockTerminal();
TerminalOverrides.runZoned(
() {
final overrides = TerminalOverrides.current;
expect(
overrides!.createTerminal(),
equals(terminal),
);
},
createTerminal: () => terminal,
);
});
test(
'uses current createTerminal when not specified '
'and zone already contains a createTerminal', () {
final Terminal terminal = _MockTerminal();
TerminalOverrides.runZoned(
() {
TerminalOverrides.runZoned(() {
final overrides = TerminalOverrides.current;
expect(
overrides!.createTerminal(),
equals(terminal),
);
});
},
createTerminal: () => terminal,
);
});
test(
'uses nested readKey when specified '
'and zone already contains a readKey', () {
final Terminal rootTerminal = _MockTerminal();
TerminalOverrides.runZoned(
() {
final Terminal nestedTerminal = _MockTerminal();
final overrides = TerminalOverrides.current;
expect(
overrides!.createTerminal(),
equals(rootTerminal),
);
TerminalOverrides.runZoned(
() {
final overrides = TerminalOverrides.current;
expect(
overrides!.createTerminal(),
equals(nestedTerminal),
);
},
createTerminal: () => nestedTerminal,
);
},
createTerminal: () => rootTerminal,
);
});
test('uses default exit when not specified', () {
TerminalOverrides.runZoned(() {
final overrides = TerminalOverrides.current;
expect(overrides!.exit, isNotNull);
});
});
test('uses custom exit when specified', () {
final exitCalls = <int>[];
try {
TerminalOverrides.runZoned(
() {
final overrides = TerminalOverrides.current;
overrides!.exit(0);
},
exit: (code) {
exitCalls.add(code);
throw Exception('exit');
},
);
} catch (_) {
expect(exitCalls, equals([0]));
}
});
test(
'uses current exit when not specified '
'and zone already contains a exit', () {
final exitCalls = <int>[];
TerminalOverrides.runZoned(
() {
try {
TerminalOverrides.runZoned(() {
final overrides = TerminalOverrides.current;
overrides!.exit(0);
});
} catch (_) {
expect(exitCalls, equals([0]));
}
},
exit: (code) {
exitCalls.add(code);
throw Exception('exit');
},
);
});
test(
'uses nested exit when specified '
'and zone already contains a exit', () {
final rootExitCalls = <int>[];
TerminalOverrides.runZoned(
() {
final nestedExitCalls = <int>[];
try {
TerminalOverrides.runZoned(
() {
final overrides = TerminalOverrides.current;
overrides!.exit(0);
},
exit: (code) {
nestedExitCalls.add(code);
throw Exception('exit');
},
);
} catch (_) {
expect(nestedExitCalls, equals([0]));
expect(rootExitCalls, isEmpty);
}
},
exit: (code) {
rootExitCalls.add(code);
throw Exception('exit');
},
);
});
});
});
}
|
mason/packages/mason_logger/test/src/terminal_overrides_test.dart/0
|
{'file_path': 'mason/packages/mason_logger/test/src/terminal_overrides_test.dart', 'repo_id': 'mason', 'token_count': 3484}
|
import 'package:firebase_auth/firebase_auth.dart';
import 'package:{{name}}/auth/repository/auth_repository.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
final authRepositoryProvider = Provider<AuthRepository>((ref) {
return AuthRepository(FirebaseAuth.instance);
});
final authStateProvider = StreamProvider<User?>((ref) {
return ref.watch(authRepositoryProvider).authStateChange;
});
|
mason_bricks-1/bricks/firebase_auth_riverpod/__brick__/auth/provider/auth_provider.dart/0
|
{'file_path': 'mason_bricks-1/bricks/firebase_auth_riverpod/__brick__/auth/provider/auth_provider.dart', 'repo_id': 'mason_bricks-1', 'token_count': 130}
|
import 'dart:io';
import 'package:mason/mason.dart';
Future<void> run(HookContext context) async {
await _removeFiles(context, '.gitkeep');
await _installDependencies(context);
await _copyGeneratedFilesToLib(context);
}
Future<void> _removeFiles(HookContext context, String name) async {
final removingFilesDone =
context.logger.progress('removing .gitkeep files ...');
var dir = Directory('.');
await dir
.list(recursive: true)
.where((element) => element.toString().contains(name))
.listen(
(element) {
element.delete();
},
onDone: () => removingFilesDone('.gitkeep files removed!'),
);
}
Future<void> _installDependencies(HookContext context) async {
final installDone = context.logger.progress('Installing dependencies...');
var result = await Process.run('flutter', ['pub', 'add', 'get_it'],
workingDirectory: './{{name}}');
if (result.exitCode == 0) {
installDone('Dependencies installed!');
} else {
context.logger.err(result.stderr);
}
}
Future<void> _copyGeneratedFilesToLib(HookContext context) async {
final done = context.logger.progress('Copying files to lib...');
var result = await Process.run('mv', [
'core',
'data',
'domain',
'features',
'di.dart',
'main.dart',
'./{{name}}/lib/',
]);
if (result.exitCode == 0) {
done('Files copied successfully');
} else {
context.logger.err(result.stderr);
}
}
|
mason_bricks/bricks/clean_app/hooks/post_gen.dart/0
|
{'file_path': 'mason_bricks/bricks/clean_app/hooks/post_gen.dart', 'repo_id': 'mason_bricks', 'token_count': 528}
|
bricks:
clean_starter:
path: bricks/clean_starter
cubit_starter:
path: bricks/cubit_starter
|
mason_bricks/mason.yaml/0
|
{'file_path': 'mason_bricks/mason.yaml', 'repo_id': 'mason_bricks', 'token_count': 40}
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:meetup/localization.dart';
import 'package:meetup/one-widget-one-feature/good.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
print('here');
if (const bool.fromEnvironment('PLATFORM_IS_ANDROID')) {
print("there");
}
return MaterialApp(
localizationsDelegates: [
DemoDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
title: 'Flutter Demo',
routes: {
'/one-widget-one-feature': (context) => TodoList(),
},
home: Home(),
);
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
final children = <Widget>[
ListTile(
onTap: () => Navigator.pushNamed(context, '/one-widget-one-feature'),
title: Text('One widget = One feature'),
),
];
return Scaffold(
appBar: AppBar(
title: const Text('Home'),
),
body: ListView.separated(
itemCount: children.length,
itemBuilder: (context, index) => children[index],
separatorBuilder: (context, index) => Divider(),
),
);
}
}
|
meetup-18-10-18/lib/main.dart/0
|
{'file_path': 'meetup-18-10-18/lib/main.dart', 'repo_id': 'meetup-18-10-18', 'token_count': 551}
|
name: mini_hub_client
on:
push:
branches:
- main
paths:
- .github/workflows/mini_hub_client.yaml
- packages/mini_hub_client/**
pull_request:
branches:
- main
paths:
- .github/workflows/mini_hub_client.yaml
- packages/mini_hub_client/**
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2.3.4
- uses: subosito/flutter-action@v2
with:
channel: 'stable'
cache: true
- uses: bluefireteam/melos-action@main
- name: Install Dependencies
run: melos bootstrap
- name: Format
run: melos exec --scope mini_hub_client dart format --set-exit-if-changed lib
- name: Analyze
run: melos exec --scope mini_hub_client dart analyze --fatal-infos --fatal-warnings .
#- name: Run Tests
# run: melos exec --scope mini_hub_client flutter test --coverage
#- name: Check Code Coverage
# uses: VeryGoodOpenSource/very_good_coverage@v1
# with:
# path: packages/mini_hub_client/coverage/lcov.info
# min_coverage: 0
|
mini_sprite/.github/workflows/mini_hub_client.yaml/0
|
{'file_path': 'mini_sprite/.github/workflows/mini_hub_client.yaml', 'repo_id': 'mini_sprite', 'token_count': 498}
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'hub_entry_result.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
HubEntryResult _$HubEntryResultFromJson(Map<String, dynamic> json) =>
HubEntryResult(
name: json['name'] as String,
description: json['description'] as String,
path: json['path'] as String,
);
Map<String, dynamic> _$HubEntryResultToJson(HubEntryResult instance) =>
<String, dynamic>{
'name': instance.name,
'description': instance.description,
'path': instance.path,
};
|
mini_sprite/packages/mini_hub_client/lib/src/hub_entry_result.g.dart/0
|
{'file_path': 'mini_sprite/packages/mini_hub_client/lib/src/hub_entry_result.g.dart', 'repo_id': 'mini_sprite', 'token_count': 208}
|
import 'package:mini_sprite/mini_sprite.dart';
import 'package:test/test.dart';
void main() {
group('MiniMap', () {
group('when using the legacy map format', () {
test('fromDataString returns the correct instance', () {
const data = '[{"x": 0, "y": 0, "data": {"sprite": "player"}}]';
final instance = MiniMap.fromDataString(data);
expect(
instance,
MiniMap(
objects: {
const MapPosition(0, 0): const <String, dynamic>{
'sprite': 'player',
},
},
),
);
});
});
group('when using the new map format', () {
test('fromDataString returns the correct instance', () {
const data =
'{"objects":[{"x": 0, "y": 0, "data": {"sprite": "player"}}]}';
final instance = MiniMap.fromDataString(data);
expect(
instance,
MiniMap(
objects: {
const MapPosition(0, 0): const <String, dynamic>{
'sprite': 'player',
},
},
),
);
});
test(
'fromDataString returns the correct instance with width and height',
() {
const data =
// ignore: lines_longer_than_80_chars
'{"width":2,"height":2,"objects":[{"x": 0, "y": 0, "data": {"sprite": "player"}}]}';
final instance = MiniMap.fromDataString(data);
expect(
instance,
MiniMap(
width: 2,
height: 2,
objects: {
const MapPosition(0, 0): const <String, dynamic>{
'sprite': 'player',
},
},
),
);
},
);
});
test('toDataString returns the correct serialized data', () {
const data = '{"objects":[{"x":0,"y":0,"data":{"sprite":"player"}}]}';
expect(
MiniMap(
objects: {
const MapPosition(0, 0): const <String, dynamic>{
'sprite': 'player',
},
},
).toDataString(),
equals(data),
);
});
group('map size', () {
test('returns informed dimension when present', () {
expect(const MiniMap(objects: {}, width: 10).width, equals(10));
expect(const MiniMap(objects: {}, height: 10).height, equals(10));
});
test('returns the bigger position from objects', () {
final map = MiniMap(
objects: {
const MapPosition(2, 2): const <String, dynamic>{
'sprite': 'player',
},
},
);
expect(map.width, equals(3));
expect(map.height, equals(3));
});
});
});
}
|
mini_sprite/packages/mini_sprite/test/src/mini_map_test.dart/0
|
{'file_path': 'mini_sprite/packages/mini_sprite/test/src/mini_map_test.dart', 'repo_id': 'mini_sprite', 'token_count': 1391}
|
export 'view/app.dart';
|
mini_sprite/packages/mini_sprite_editor/lib/app/app.dart/0
|
{'file_path': 'mini_sprite/packages/mini_sprite_editor/lib/app/app.dart', 'repo_id': 'mini_sprite', 'token_count': 10}
|
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/services.dart';
import 'package:mini_sprite/mini_sprite.dart';
part 'library_state.dart';
class LibraryCubit extends Cubit<LibraryState> {
LibraryCubit({
Future<void> Function(ClipboardData)? setClipboardData,
Future<ClipboardData?> Function(String)? getClipboardData,
}) : _setClipboardData = setClipboardData ?? Clipboard.setData,
_getClipboardData = getClipboardData ?? Clipboard.getData,
super(const LibraryState.initial());
final Future<void> Function(ClipboardData) _setClipboardData;
final Future<ClipboardData?> Function(String) _getClipboardData;
void select(String key) {
emit(state.copyWith(selected: key));
}
void startCollection(List<List<int>> firstSprite) {
emit(
state.copyWith(
sprites: {
'sprite_1': MiniSprite(firstSprite),
},
selected: 'sprite_1',
),
);
}
void updateSelected(List<List<int>> sprite) {
emit(
state.copyWith(
sprites: {
...state.sprites,
state.selected: MiniSprite(sprite),
},
),
);
}
void rename(String key, String newKey) {
final newSprites = {...state.sprites}..remove(key);
emit(
state.copyWith(
sprites: {
...newSprites,
newKey: state.sprites[key]!,
},
selected: state.selected == key ? newKey : state.selected,
),
);
}
String _newSpriteKey() {
var _idx = state.sprites.length + 1;
var _spriteKey = 'sprite_$_idx';
while (state.sprites.containsKey(_spriteKey)) {
_idx++;
_spriteKey = 'sprite_$_idx';
}
return _spriteKey;
}
void addSprite(int width, int height) {
emit(
state.copyWith(
sprites: {
...state.sprites,
_newSpriteKey(): MiniSprite(
List.generate(
height,
(_) => List.generate(
width,
(_) => -1,
),
),
),
},
),
);
}
void removeSprite(String key) {
final newSprites = {...state.sprites}..remove(key);
emit(
state.copyWith(
sprites: newSprites,
selected:
state.selected == key ? state.sprites.keys.last : state.selected,
),
);
}
Future<void> importFromClipboard() async {
final data = await _getClipboardData('text/plain');
final text = data?.text;
if (text != null) {
final library = MiniLibrary.fromDataString(text);
emit(
state.copyWith(
sprites: library.sprites,
selected: library.sprites.isNotEmpty ? library.sprites.keys.last : '',
),
);
}
}
void copyToClipboard() {
final library = MiniLibrary(state.sprites);
final data = library.toDataString();
_setClipboardData(ClipboardData(text: data));
}
}
|
mini_sprite/packages/mini_sprite_editor/lib/library/cubit/library_cubit.dart/0
|
{'file_path': 'mini_sprite/packages/mini_sprite_editor/lib/library/cubit/library_cubit.dart', 'repo_id': 'mini_sprite', 'token_count': 1330}
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mini_sprite_editor/l10n/l10n.dart';
import 'package:mini_sprite_editor/map/map.dart';
class MapSizeDialog extends StatefulWidget {
const MapSizeDialog({super.key});
static Future<Offset?> show(BuildContext context) {
return showDialog<Offset?>(
context: context,
builder: (_) {
return BlocProvider<MapCubit>.value(
value: context.read<MapCubit>(),
child: const MapSizeDialog(),
);
},
);
}
@override
State<MapSizeDialog> createState() => _MapSizeDialogState();
}
class _MapSizeDialogState extends State<MapSizeDialog> {
late TextEditingController _widthController;
late TextEditingController _heightController;
@override
void initState() {
super.initState();
final state = context.read<MapCubit>().state;
_widthController = TextEditingController()
..text = state.mapSize.width.toInt().toString();
_heightController = TextEditingController()
..text = state.mapSize.height.toInt().toString();
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return Dialog(
child: SizedBox(
width: 150,
height: 250,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
l10n.mapSizeTitle,
style: Theme.of(context).textTheme.headlineMedium,
),
const SizedBox(width: 8),
Row(
children: [
const SizedBox(width: 50),
Expanded(
child: TextField(
autofocus: true,
key: const Key('width_text_field_key'),
decoration: InputDecoration(label: Text(l10n.width)),
textAlign: TextAlign.center,
controller: _widthController,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
],
),
),
const SizedBox(width: 50),
Expanded(
child: TextField(
key: const Key('height_text_field_key'),
decoration: InputDecoration(label: Text(l10n.height)),
textAlign: TextAlign.center,
controller: _heightController,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
],
),
),
const SizedBox(width: 50),
],
),
const SizedBox(height: 32),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
Navigator.of(context).pop(null);
},
child: Text(l10n.cancel),
),
const SizedBox(width: 16),
ElevatedButton(
onPressed: () {
Navigator.of(context).pop(
Offset(
double.parse(_widthController.text),
double.parse(_heightController.text),
),
);
},
child: Text(l10n.confirm),
),
],
),
],
),
),
);
}
}
|
mini_sprite/packages/mini_sprite_editor/lib/map/view/map_size_dialog.dart/0
|
{'file_path': 'mini_sprite/packages/mini_sprite_editor/lib/map/view/map_size_dialog.dart', 'repo_id': 'mini_sprite', 'token_count': 1943}
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mini_sprite_editor/l10n/l10n.dart';
import 'package:mini_sprite_editor/sprite/cubit/sprite_cubit.dart';
class SpriteSizeDialog extends StatefulWidget {
const SpriteSizeDialog({super.key});
static Future<Offset?> show(BuildContext context) {
return showDialog<Offset?>(
context: context,
builder: (_) {
return BlocProvider<SpriteCubit>.value(
value: context.read<SpriteCubit>(),
child: const SpriteSizeDialog(),
);
},
);
}
@override
State<SpriteSizeDialog> createState() => _SpriteSizeDialogState();
}
class _SpriteSizeDialogState extends State<SpriteSizeDialog> {
late TextEditingController _widthController;
late TextEditingController _heightController;
@override
void initState() {
super.initState();
final state = context.read<SpriteCubit>().state;
_widthController = TextEditingController()
..text = state.pixels[0].length.toString();
_heightController = TextEditingController()
..text = state.pixels.length.toString();
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return Dialog(
child: SizedBox(
width: 150,
height: 350,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
l10n.spriteSizeTitle,
style: Theme.of(context).textTheme.headlineMedium,
),
const SizedBox(width: 8),
Row(
children: [
const SizedBox(width: 50),
Expanded(
child: TextField(
autofocus: true,
key: const Key('width_text_field_key'),
decoration: InputDecoration(label: Text(l10n.width)),
textAlign: TextAlign.center,
controller: _widthController,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
],
),
),
const SizedBox(width: 50),
Expanded(
child: TextField(
key: const Key('height_text_field_key'),
decoration: InputDecoration(label: Text(l10n.height)),
textAlign: TextAlign.center,
controller: _heightController,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
],
),
),
const SizedBox(width: 50),
],
),
const SizedBox(height: 32),
Column(
children: [
ElevatedButton(
onPressed: () {
Navigator.of(context).pop(null);
},
child: Text(l10n.cancel),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
Navigator.of(context).pop(
Offset(
double.parse(_widthController.text),
double.parse(_heightController.text),
),
);
},
child: Text(l10n.confirm),
),
],
),
],
),
),
);
}
}
|
mini_sprite/packages/mini_sprite_editor/lib/sprite/view/sprite_size_dialog.dart/0
|
{'file_path': 'mini_sprite/packages/mini_sprite_editor/lib/sprite/view/sprite_size_dialog.dart', 'repo_id': 'mini_sprite', 'token_count': 1929}
|
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:mini_sprite/mini_sprite.dart';
import 'package:mini_sprite_editor/library/library.dart';
void main() {
group('LibraryState', () {
test('can be instantiated', () {
expect(
LibraryState(
sprites: const {},
selected: '',
),
isNotNull,
);
});
test('supports equality', () {
expect(
LibraryState(sprites: const {}, selected: ''),
equals(
LibraryState(sprites: const {}, selected: ''),
),
);
expect(
LibraryState(
sprites: const {
'player': MiniSprite([
[1],
[1],
]),
},
selected: '',
),
isNot(
equals(
LibraryState(
sprites: const {
'player': MiniSprite([
[1],
[0],
]),
},
selected: '',
),
),
),
);
expect(
LibraryState(
sprites: const {
'player': MiniSprite([
[1],
[1],
]),
},
selected: '',
),
isNot(
equals(
LibraryState(
sprites: const {
'player': MiniSprite([
[1],
[1],
]),
},
selected: 'player',
),
),
),
);
});
test('copyWith return new instance with the value', () {
expect(
LibraryState.initial().copyWith(
sprites: {
'player': MiniSprite(const [
[1],
[1],
]),
},
),
equals(
LibraryState(
sprites: const {
'player': MiniSprite([
[1],
[1],
]),
},
selected: '',
),
),
);
expect(
LibraryState.initial().copyWith(
selected: 'player',
),
equals(
LibraryState(
sprites: const {},
selected: 'player',
),
),
);
});
});
}
|
mini_sprite/packages/mini_sprite_editor/test/library/cubit/library_state_test.dart/0
|
{'file_path': 'mini_sprite/packages/mini_sprite_editor/test/library/cubit/library_state_test.dart', 'repo_id': 'mini_sprite', 'token_count': 1422}
|
export 'game_view.dart';
export 'win_dialog.dart';
|
mini_sprite/packages/mini_treasure_quest/lib/game/views/view.dart/0
|
{'file_path': 'mini_sprite/packages/mini_treasure_quest/lib/game/views/view.dart', 'repo_id': 'mini_sprite', 'token_count': 21}
|
part of '../observable_collections.dart';
Atom _observableMapAtom<K, V>(ReactiveContext context) {
final ctx = context ?? mainContext;
return Atom(name: ctx.nameFor('ObservableMap<$K, $V>'), context: ctx);
}
class ObservableMap<K, V>
with
// ignore:prefer_mixin
MapMixin<K, V>
implements
Listenable<MapChange<K, V>> {
ObservableMap({ReactiveContext context})
: _context = context ?? mainContext,
_atom = _observableMapAtom<K, V>(context),
_map = <K, V>{};
ObservableMap.of(Map<K, V> other, {ReactiveContext context})
: _context = context ?? mainContext,
_atom = _observableMapAtom<K, V>(context),
_map = Map.of(other);
ObservableMap.linkedHashMapFrom(Map<K, V> other, {ReactiveContext context})
: _context = context ?? mainContext,
_atom = _observableMapAtom<K, V>(context),
_map = LinkedHashMap.from(other);
ObservableMap.splayTreeMapFrom(Map<K, V> other,
{int Function(K, K) compare,
// ignore: avoid_annotating_with_dynamic
bool Function(dynamic) isValidKey,
ReactiveContext context})
: _context = context ?? mainContext,
_atom = _observableMapAtom<K, V>(context),
_map = SplayTreeMap.from(other, compare, isValidKey);
ObservableMap._wrap(this._context, this._map, this._atom);
final ReactiveContext _context;
final Atom _atom;
final Map<K, V> _map;
Listeners<MapChange<K, V>> _listenersField;
Listeners<MapChange<K, V>> get _listeners =>
_listenersField ??= Listeners(_context);
bool get _hasListeners =>
_listenersField != null && _listenersField.hasHandlers;
@override
V operator [](Object key) {
_atom.reportObserved();
return _map[key];
}
@override
void operator []=(K key, V value) {
_context.checkIfStateModificationsAreAllowed(_atom);
if (_hasListeners) {
if (_map.containsKey(key)) {
final oldValue = _map[key];
_map[key] = value;
_reportUpdate(key, value, oldValue);
} else {
_map[key] = value;
_reportAdd(key, value);
}
} else {
_map[key] = value;
}
_atom.reportChanged();
}
@override
void clear() {
_context.checkIfStateModificationsAreAllowed(_atom);
if (isEmpty) {
return;
}
if (_hasListeners) {
final removed = Map<K, V>.from(_map);
_map.clear();
removed.forEach(_reportRemove);
} else {
_map.clear();
}
_atom.reportChanged();
}
@override
Iterable<K> get keys => MapKeysIterable(_map.keys, _atom);
@override
Map<RK, RV> cast<RK, RV>() =>
ObservableMap._wrap(_context, super.cast(), _atom);
@override
V remove(Object key) {
_context.checkIfStateModificationsAreAllowed(_atom);
if (_hasListeners) {
if (_map.containsKey(key)) {
final value = _map.remove(key);
_reportRemove(key, value);
_atom.reportChanged();
return value;
}
return null;
}
final value = _map.remove(key);
_atom.reportChanged();
return value;
}
@override
int get length {
_atom.reportObserved();
return _map.length;
}
@override
bool get isNotEmpty {
_atom.reportObserved();
return _map.isNotEmpty;
}
@override
bool get isEmpty {
_atom.reportObserved();
return _map.isEmpty;
}
@override
bool containsKey(Object key) {
_atom.reportObserved();
return _map.containsKey(key);
}
void _reportUpdate(K key, V newValue, V oldValue) {
_listeners.notifyListeners(MapChange<K, V>(
type: OperationType.update,
key: key,
newValue: newValue,
oldValue: oldValue,
object: this,
));
}
void _reportAdd(K key, V newValue) {
_listeners.notifyListeners(MapChange<K, V>(
type: OperationType.add,
key: key,
newValue: newValue,
object: this,
));
}
void _reportRemove(K key, V oldValue) {
_listeners.notifyListeners(MapChange<K, V>(
type: OperationType.remove,
key: key,
oldValue: oldValue,
object: this,
));
}
@override
Dispose observe(MapChangeListener<K, V> listener, {bool fireImmediately}) {
final dispose = _listeners.add(listener);
if (fireImmediately == true) {
_map.forEach(_reportAdd);
}
return dispose;
}
}
@visibleForTesting
ObservableMap<K, V> wrapInObservableMap<K, V>(Atom atom, Map<K, V> map) =>
ObservableMap._wrap(mainContext, map, atom);
typedef MapChangeListener<K, V> = void Function(MapChange<K, V>);
class MapChange<K, V> {
MapChange({this.type, this.key, this.newValue, this.oldValue, this.object});
final OperationType type;
final K key;
final V newValue;
final V oldValue;
final ObservableMap<K, V> object;
}
// ignore:prefer_mixin
class MapKeysIterable<K> with IterableMixin<K> {
MapKeysIterable(this._iterable, this._atom);
final Iterable<K> _iterable;
final Atom _atom;
@override
int get length {
_atom.reportObserved();
return _iterable.length;
}
@override
bool contains(Object element) {
_atom.reportObserved();
return _iterable.contains(element);
}
@override
Iterator<K> get iterator => MapKeysIterator(_iterable.iterator, _atom);
}
class MapKeysIterator<K> implements Iterator<K> {
MapKeysIterator(this._iterator, this._atom);
final Iterator<K> _iterator;
final Atom _atom;
@override
K get current {
_atom.reportObserved();
return _iterator.current;
}
@override
bool moveNext() {
_atom.reportObserved();
return _iterator.moveNext();
}
}
|
mobx.dart/mobx/lib/src/api/observable_collections/observable_map.dart/0
|
{'file_path': 'mobx.dart/mobx/lib/src/api/observable_collections/observable_map.dart', 'repo_id': 'mobx.dart', 'token_count': 2269}
|
import 'package:mobx/mobx.dart';
part 'generator_example.g.dart';
class User = _User with _$User;
abstract class _User with Store {
_User(this.id);
final int id;
@observable
String firstName = 'Jane';
@observable
String lastName = 'Doe';
@computed
String get fullName => '$firstName $lastName';
@action
void updateNames({String firstName, String lastName}) {
if (firstName != null) this.firstName = firstName;
if (lastName != null) this.lastName = lastName;
}
}
class Admin extends _Admin with _$Admin {
Admin(int id) : super(id);
}
abstract class _Admin extends User with Store {
_Admin(int id) : super(id);
@observable
String userName = 'admin';
@observable
ObservableList<String> accessRights = ObservableList();
@observable
Future<String> loadPrivileges([String foo]) async {
return foo;
}
@observable
Stream<T> loadStuff<T>(String arg1, {T value}) async* {
yield value;
}
@action
@observable
Future<void> loadAccessRights() async {
final items = Stream.fromIterable(['web', 'filesystem'])
.asyncMap((ev) => Future.delayed(Duration(milliseconds: 10), () => ev));
await for (final item in items) {
accessRights.add(item);
}
}
}
class Item<A> = _Item<A> with _$Item<A>;
abstract class _Item<T> with Store {
@observable
T value;
}
|
mobx.dart/mobx_codegen/example/lib/src/generator_example.dart/0
|
{'file_path': 'mobx.dart/mobx_codegen/example/lib/src/generator_example.dart', 'repo_id': 'mobx.dart', 'token_count': 498}
|
import 'package:mobx_codegen/src/template/method_override.dart';
class ObservableStreamTemplate {
MethodOverrideTemplate method;
@override
String toString() => """
@override
ObservableStream${method.returnTypeArgs} ${method.name}${method.typeParams}(${method.params}) {
final _\$stream = super.${method.name}${method.typeArgs}(${method.args});
return ObservableStream${method.returnTypeArgs}(_\$stream);
}""";
}
|
mobx.dart/mobx_codegen/lib/src/template/observable_stream.dart/0
|
{'file_path': 'mobx.dart/mobx_codegen/lib/src/template/observable_stream.dart', 'repo_id': 'mobx.dart', 'token_count': 143}
|
import 'package:flutter/material.dart';
import 'package:mobx_examples/examples.dart';
import 'package:mobx_examples/multi_counter/multi_counter_store.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) => MultiProvider(
providers: [
Provider<MultiCounterStore>(builder: (_) => MultiCounterStore())
],
child: MaterialApp(
initialRoute: '/',
theme: ThemeData(
primarySwatch: Colors.blue,
),
routes: {
'/': (_) => ExampleList(),
}..addEntries(
examples.map((ex) => MapEntry(ex.path, ex.widgetBuilder))),
));
}
class ExampleList extends StatelessWidget {
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Flutter MobX Examples'),
),
body: ListView.builder(
itemCount: examples.length,
itemBuilder: (_, int index) {
final ex = examples[index];
return ListTile(
title: Text(ex.title),
subtitle: Text(ex.description),
trailing: const Icon(Icons.navigate_next),
onTap: () => Navigator.pushNamed(context, ex.path),
);
},
));
}
|
mobx.dart/mobx_examples/lib/main.dart/0
|
{'file_path': 'mobx.dart/mobx_examples/lib/main.dart', 'repo_id': 'mobx.dart', 'token_count': 616}
|
name: ci
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
semantic_pull_request:
uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/semantic_pull_request.yml@v1
build:
uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1
with:
flutter_channel: stable
spell-check:
uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/spell_check.yml@v1
with:
includes: |
**/*.{md,yaml}
!.dart_tool/**/*.yaml
.*/**/*.yml
modified_files_only: false
pana_score:
uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/pana.yml@v1
|
mockingjay/.github/workflows/main.yaml/0
|
{'file_path': 'mockingjay/.github/workflows/main.yaml', 'repo_id': 'mockingjay', 'token_count': 335}
|
import 'dart:async';
import 'package:example/ui/ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockingjay/mockingjay.dart';
import '../helpers.dart';
void main() {
group('PincodeScreen', () {
late MockNavigator navigator;
setUp(() {
navigator = MockNavigator();
when(() => navigator.canPop()).thenReturn(true);
});
testWidgets('.route renders PincodeScreen', (tester) async {
late BuildContext context;
await tester.pumpTest(
builder: (appContext) {
context = appContext;
return const SizedBox();
},
);
unawaited(Navigator.of(context).push(PincodeScreen.route()));
await tester.pumpAndSettle();
expect(find.byType(PincodeScreen), findsOneWidget);
});
testWidgets('renders pincode text input', (tester) async {
await tester.pumpTest(
builder: (context) {
return const PincodeScreen();
},
);
expect(find.byType(TextField), findsOneWidget);
});
testWidgets(
'pops route with entered pincode when 6 digits have been entered',
(tester) async {
await tester.pumpTest(
builder: (context) {
return MockNavigatorProvider(
navigator: navigator,
child: const PincodeScreen(),
);
},
);
await tester.enterText(find.byType(TextField), '1234');
verifyNever(() => navigator.pop('1234'));
await tester.enterText(find.byType(TextField), '12345');
verifyNever(() => navigator.pop('12345'));
await tester.enterText(find.byType(TextField), '123456');
verify(() => navigator.pop('123456')).called(1);
},
);
testWidgets(
'clamps to 6 digits when exact 6 digits have been entered',
(tester) async {
await tester.pumpTest(
builder: (context) {
return MockNavigatorProvider(
navigator: navigator,
child: const PincodeScreen(),
);
},
);
await tester.enterText(find.byType(TextField), '123456');
verify(() => navigator.pop('123456')).called(1);
},
);
testWidgets(
'clamps to 6 digits when more than 6 digits have been entered',
(tester) async {
await tester.pumpTest(
builder: (context) {
return MockNavigatorProvider(
navigator: navigator,
child: const PincodeScreen(),
);
},
);
await tester.enterText(find.byType(TextField), '1234567');
verify(() => navigator.pop('123456')).called(1);
},
);
testWidgets(
'shows error when less than 6 digits have been entered',
(tester) async {
await tester.pumpTest(
builder: (context) {
return MockNavigatorProvider(
navigator: navigator,
child: const PincodeScreen(),
);
},
);
await tester.enterText(find.byType(TextField), '12345');
await tester.testTextInput.receiveAction(TextInputAction.done);
await tester.pump();
expect(find.text('Pincode must be 6 digits long'), findsOneWidget);
},
);
});
}
|
mockingjay/example/test/ui/pincode_screen_test.dart/0
|
{'file_path': 'mockingjay/example/test/ui/pincode_screen_test.dart', 'repo_id': 'mockingjay', 'token_count': 1516}
|
// Copyright 2016 Dart Mockito authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file 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:async';
import 'package:meta/meta.dart';
import 'package:mockito/src/call_pair.dart';
import 'package:mockito/src/invocation_matcher.dart';
import 'package:test_api/fake.dart';
// ignore: deprecated_member_use
import 'package:test_api/test_api.dart';
// TODO(srawlins): Remove this when we no longer need to check for an
// incompatiblity between test_api and test.
// https://github.com/dart-lang/mockito/issues/175
import 'package:test_api/src/backend/invoker.dart';
bool _whenInProgress = false;
bool _untilCalledInProgress = false;
bool _verificationInProgress = false;
_WhenCall _whenCall;
_UntilCall _untilCall;
final List<_VerifyCall> _verifyCalls = <_VerifyCall>[];
final _TimeStampProvider _timer = _TimeStampProvider();
final List<dynamic> _capturedArgs = [];
final List<ArgMatcher> _storedArgs = <ArgMatcher>[];
final Map<String, ArgMatcher> _storedNamedArgs = <String, ArgMatcher>{};
@Deprecated(
'This function is not a supported function, and may be deleted as early as '
'Mockito 5.0.0')
void setDefaultResponse(
Mock mock, CallPair<dynamic> Function() defaultResponse) {
mock._defaultResponse = defaultResponse;
}
/// Opt-into [Mock] throwing [NoSuchMethodError] for unimplemented methods.
///
/// The default behavior when not using this is to always return `null`.
void throwOnMissingStub(
Mock mock, {
void Function(Invocation) exceptionBuilder,
}) {
exceptionBuilder ??= mock._noSuchMethod;
mock._defaultResponse =
() => CallPair<dynamic>.allInvocations(exceptionBuilder);
}
/// Extend or mixin this class to mark the implementation as a [Mock].
///
/// A mocked class implements all fields and methods with a default
/// implementation that does not throw a [NoSuchMethodError], and may be further
/// customized at runtime to define how it may behave using [when].
///
/// __Example use__:
///
/// // Real class.
/// class Cat {
/// String getSound(String suffix) => 'Meow$suffix';
/// }
///
/// // Mock class.
/// class MockCat extends Mock implements Cat {}
///
/// void main() {
/// // Create a new mocked Cat at runtime.
/// var cat = new MockCat();
///
/// // When 'getSound' is called, return 'Woof'
/// when(cat.getSound(any)).thenReturn('Woof');
///
/// // Try making a Cat sound...
/// print(cat.getSound('foo')); // Prints 'Woof'
/// }
///
/// A class which `extends Mock` should not have any directly implemented
/// overridden fields or methods. These fields would not be usable as a [Mock]
/// with [verify] or [when]. To implement a subset of an interface manually use
/// [Fake] instead.
///
/// **WARNING**: [Mock] uses [noSuchMethod](goo.gl/r3IQUH), which is a _form_ of
/// runtime reflection, and causes sub-standard code to be generated. As such,
/// [Mock] should strictly _not_ be used in any production code, especially if
/// used within the context of Dart for Web (dart2js, DDC) and Dart for Mobile
/// (Flutter).
class Mock {
static Null _answerNull(_) => null;
static const _nullResponse = CallPair<Null>.allInvocations(_answerNull);
final StreamController<Invocation> _invocationStreamController =
StreamController.broadcast();
final _realCalls = <RealCall>[];
final _responses = <CallPair<dynamic>>[];
String _givenName;
int _givenHashCode;
_ReturnsCannedResponse _defaultResponse = () => _nullResponse;
void _setExpected(CallPair<dynamic> cannedResponse) {
_responses.add(cannedResponse);
}
/// Handles method stubbing, method call verification, and real method calls.
///
/// If passed, [returnValue] will be returned during method stubbing and
/// method call verification. This is useful in cases where the method
/// invocation which led to `noSuchMethod` being called has a non-nullable
/// return type.
@override
@visibleForTesting
dynamic noSuchMethod(Invocation invocation, [Object /*?*/ returnValue]) {
// noSuchMethod is that 'magic' that allows us to ignore implementing fields
// and methods and instead define them later at compile-time per instance.
invocation = _useMatchedInvocationIfSet(invocation);
if (_whenInProgress) {
_whenCall = _WhenCall(this, invocation);
return returnValue;
} else if (_verificationInProgress) {
_verifyCalls.add(_VerifyCall(this, invocation));
return returnValue;
} else if (_untilCalledInProgress) {
_untilCall = _UntilCall(this, invocation);
return returnValue;
} else {
_realCalls.add(RealCall(this, invocation));
_invocationStreamController.add(invocation);
var cannedResponse = _responses.lastWhere(
(cr) => cr.call.matches(invocation, {}),
orElse: _defaultResponse);
var response = cannedResponse.response(invocation);
return response;
}
}
dynamic _noSuchMethod(Invocation invocation) =>
const Object().noSuchMethod(invocation);
@override
int get hashCode => _givenHashCode ?? 0;
@override
bool operator ==(other) => (_givenHashCode != null && other is Mock)
? _givenHashCode == other._givenHashCode
: identical(this, other);
@override
String toString() => _givenName ?? runtimeType.toString();
String _realCallsToString([Iterable<RealCall> realCalls]) {
var stringRepresentations =
(realCalls ?? _realCalls).map((call) => call.toString());
if (stringRepresentations.any((s) => s.contains('\n'))) {
// As each call contains newlines, put each on its own line, for better
// readability.
return stringRepresentations.join(',\n');
} else {
// A compact String should be perfect.
return stringRepresentations.join(', ');
}
}
String _unverifiedCallsToString() =>
_realCallsToString(_realCalls.where((call) => !call.verified));
}
typedef _ReturnsCannedResponse = CallPair<dynamic> Function();
// When using an [ArgMatcher], we transform our invocation to have knowledge of
// which arguments are wrapped, and which ones are not. Otherwise we just use
// the existing invocation object.
Invocation _useMatchedInvocationIfSet(Invocation invocation) {
if (_storedArgs.isNotEmpty || _storedNamedArgs.isNotEmpty) {
invocation = _InvocationForMatchedArguments(invocation);
}
return invocation;
}
/// An Invocation implementation that takes arguments from [_storedArgs] and
/// [_storedNamedArgs].
class _InvocationForMatchedArguments extends Invocation {
@override
final Symbol memberName;
@override
final Map<Symbol, dynamic> namedArguments;
@override
final List<dynamic> positionalArguments;
@override
final bool isGetter;
@override
final bool isMethod;
@override
final bool isSetter;
factory _InvocationForMatchedArguments(Invocation invocation) {
if (_storedArgs.isEmpty && _storedNamedArgs.isEmpty) {
throw StateError(
'_InvocationForMatchedArguments called when no ArgMatchers have been saved.');
}
// Handle named arguments first, so that we can provide useful errors for
// the various bad states. If all is well with the named arguments, then we
// can process the positional arguments, and resort to more general errors
// if the state is still bad.
var namedArguments = _reconstituteNamedArgs(invocation);
var positionalArguments = _reconstitutePositionalArgs(invocation);
_storedArgs.clear();
_storedNamedArgs.clear();
return _InvocationForMatchedArguments._(
invocation.memberName,
positionalArguments,
namedArguments,
invocation.isGetter,
invocation.isMethod,
invocation.isSetter);
}
// Reconstitutes the named arguments in an invocation from
// [_storedNamedArgs].
//
// The `namedArguments` in [invocation] which are null should be represented
// by a stored value in [_storedNamedArgs].
static Map<Symbol, dynamic> _reconstituteNamedArgs(Invocation invocation) {
final namedArguments = <Symbol, dynamic>{};
final storedNamedArgSymbols =
_storedNamedArgs.keys.map((name) => Symbol(name));
// Iterate through [invocation]'s named args, validate them, and add them
// to the return map.
invocation.namedArguments.forEach((name, arg) {
if (arg == null) {
if (!storedNamedArgSymbols.contains(name)) {
// Either this is a parameter with default value `null`, or a `null`
// argument was passed, or an unnamed ArgMatcher was used. Just use
// `null`.
namedArguments[name] = null;
}
} else {
// Add each real named argument (not wrapped in an ArgMatcher).
namedArguments[name] = arg;
}
});
// Iterate through the stored named args, validate them, and add them to
// the return map.
_storedNamedArgs.forEach((name, arg) {
var nameSymbol = Symbol(name);
if (!invocation.namedArguments.containsKey(nameSymbol)) {
// Clear things out for the next call.
_storedArgs.clear();
_storedNamedArgs.clear();
throw ArgumentError(
'An ArgumentMatcher was declared as named $name, but was not '
'passed as an argument named $name.\n\n'
'BAD: when(obj.fn(anyNamed: "a")))\n'
'GOOD: when(obj.fn(a: anyNamed: "a")))');
}
if (invocation.namedArguments[nameSymbol] != null) {
// Clear things out for the next call.
_storedArgs.clear();
_storedNamedArgs.clear();
throw ArgumentError(
'An ArgumentMatcher was declared as named $name, but a different '
'value (${invocation.namedArguments[nameSymbol]}) was passed as '
'$name.\n\n'
'BAD: when(obj.fn(b: anyNamed("a")))\n'
'GOOD: when(obj.fn(b: anyNamed("b")))');
}
namedArguments[nameSymbol] = arg;
});
return namedArguments;
}
static List<dynamic> _reconstitutePositionalArgs(Invocation invocation) {
final positionalArguments = <dynamic>[];
final nullPositionalArguments =
invocation.positionalArguments.where((arg) => arg == null);
if (_storedArgs.length > nullPositionalArguments.length) {
// More _positional_ ArgMatchers were stored than were actually passed as
// positional arguments. There are three ways this call could have been
// parsed and resolved:
//
// * an ArgMatcher was passed in [invocation] as a named argument, but
// without a name, and thus stored in [_storedArgs], something like
// `when(obj.fn(a: any))`,
// * an ArgMatcher was passed in an expression which was passed in
// [invocation], and thus stored in [_storedArgs], something like
// `when(obj.fn(Foo(any)))`, or
// * a combination of the above.
_storedArgs.clear();
_storedNamedArgs.clear();
throw ArgumentError(
'An argument matcher (like `any`) was either not used as an '
'immediate argument to ${invocation.memberName} (argument matchers '
'can only be used as an argument for the very method being stubbed '
'or verified), or was used as a named argument without the Mockito '
'"named" API (Each argument matcher that is used as a named argument '
'needs to specify the name of the argument it is being used in. For '
'example: `when(obj.fn(x: anyNamed("x")))`).');
}
var storedIndex = 0;
var positionalIndex = 0;
while (storedIndex < _storedArgs.length &&
positionalIndex < invocation.positionalArguments.length) {
var arg = _storedArgs[storedIndex];
if (invocation.positionalArguments[positionalIndex] == null) {
// Add the [ArgMatcher] given to the argument matching helper.
positionalArguments.add(arg);
storedIndex++;
positionalIndex++;
} else {
// An argument matching helper was not used; add the [ArgMatcher] from
// [invocation].
positionalArguments
.add(invocation.positionalArguments[positionalIndex]);
positionalIndex++;
}
}
while (positionalIndex < invocation.positionalArguments.length) {
// Some trailing non-ArgMatcher arguments.
positionalArguments.add(invocation.positionalArguments[positionalIndex]);
positionalIndex++;
}
return positionalArguments;
}
_InvocationForMatchedArguments._(this.memberName, this.positionalArguments,
this.namedArguments, this.isGetter, this.isMethod, this.isSetter);
}
@Deprecated(
'This function does not provide value; hashCode and toString() can be '
'stubbed individually. This function may be deleted as early as Mockito '
'5.0.0')
T named<T extends Mock>(T mock, {String name, int hashCode}) => mock
.._givenName = name
.._givenHashCode = hashCode;
/// Clear stubs of, and collected interactions with [mock].
void reset(var mock) {
mock._realCalls.clear();
mock._responses.clear();
}
/// Clear the collected interactions with [mock].
void clearInteractions(var mock) {
mock._realCalls.clear();
}
class PostExpectation<T> {
/// Store a canned response for this method stub.
///
/// Note: [expected] cannot be a Future or Stream, due to Zone considerations.
/// To return a Future or Stream from a method stub, use [thenAnswer].
void thenReturn(T expected) {
if (expected is Future) {
throw ArgumentError('`thenReturn` should not be used to return a Future. '
'Instead, use `thenAnswer((_) => future)`.');
}
if (expected is Stream) {
throw ArgumentError('`thenReturn` should not be used to return a Stream. '
'Instead, use `thenAnswer((_) => stream)`.');
}
return _completeWhen((_) => expected);
}
/// Store an exception to throw when this method stub is called.
void thenThrow(throwable) {
return _completeWhen((_) {
throw throwable;
});
}
/// Store a function which is called when this method stub is called.
///
/// The function will be called, and the return value will be returned.
void thenAnswer(Answering<T> answer) {
return _completeWhen(answer);
}
void _completeWhen(Answering<T> answer) {
if (_whenCall == null) {
throw StateError(
'No method stub was called from within `when()`. Was a real method '
'called, or perhaps an extension method?');
}
_whenCall._setExpected<T>(answer);
_whenCall = null;
_whenInProgress = false;
}
}
class InvocationMatcher {
final Invocation roleInvocation;
InvocationMatcher(this.roleInvocation);
bool matches(Invocation invocation) {
var isMatching =
_isMethodMatches(invocation) && _isArgumentsMatches(invocation);
if (isMatching) {
_captureArguments(invocation);
}
return isMatching;
}
bool _isMethodMatches(Invocation invocation) {
if (invocation.memberName != roleInvocation.memberName) {
return false;
}
if ((invocation.isGetter != roleInvocation.isGetter) ||
(invocation.isSetter != roleInvocation.isSetter) ||
(invocation.isMethod != roleInvocation.isMethod)) {
return false;
}
return true;
}
void _captureArguments(Invocation invocation) {
var index = 0;
for (var roleArg in roleInvocation.positionalArguments) {
var actArg = invocation.positionalArguments[index];
if (roleArg is ArgMatcher && roleArg._capture) {
_capturedArgs.add(actArg);
}
index++;
}
for (var roleKey in roleInvocation.namedArguments.keys) {
var roleArg = roleInvocation.namedArguments[roleKey];
var actArg = invocation.namedArguments[roleKey];
if (roleArg is ArgMatcher) {
if (roleArg is ArgMatcher && roleArg._capture) {
_capturedArgs.add(actArg);
}
}
}
}
bool _isArgumentsMatches(Invocation invocation) {
if (invocation.positionalArguments.length !=
roleInvocation.positionalArguments.length) {
return false;
}
if (invocation.namedArguments.length !=
roleInvocation.namedArguments.length) {
return false;
}
var index = 0;
for (var roleArg in roleInvocation.positionalArguments) {
var actArg = invocation.positionalArguments[index];
if (!isMatchingArg(roleArg, actArg)) {
return false;
}
index++;
}
Set roleKeys = roleInvocation.namedArguments.keys.toSet();
Set actKeys = invocation.namedArguments.keys.toSet();
if (roleKeys.difference(actKeys).isNotEmpty ||
actKeys.difference(roleKeys).isNotEmpty) {
return false;
}
for (var roleKey in roleInvocation.namedArguments.keys) {
var roleArg = roleInvocation.namedArguments[roleKey];
var actArg = invocation.namedArguments[roleKey];
if (!isMatchingArg(roleArg, actArg)) {
return false;
}
}
return true;
}
bool isMatchingArg(roleArg, actArg) {
if (roleArg is ArgMatcher) {
return roleArg.matcher.matches(actArg, {});
} else {
return equals(roleArg).matches(actArg, {});
}
}
}
class _TimeStampProvider {
int _now = 0;
DateTime now() {
var candidate = DateTime.now();
if (candidate.millisecondsSinceEpoch <= _now) {
candidate = DateTime.fromMillisecondsSinceEpoch(_now + 1);
}
_now = candidate.millisecondsSinceEpoch;
return candidate;
}
}
class RealCall {
final Mock mock;
final Invocation invocation;
final DateTime timeStamp;
bool verified = false;
RealCall(this.mock, this.invocation) : timeStamp = _timer.now();
@override
String toString() {
var argString = '';
var args = invocation.positionalArguments.map((v) => '$v');
if (args.any((arg) => arg.contains('\n'))) {
// As one or more arg contains newlines, put each on its own line, and
// indent each, for better readability.
argString += '\n' +
args
.map((arg) => arg.splitMapJoin('\n', onNonMatch: (m) => ' $m'))
.join(',\n');
} else {
// A compact String should be perfect.
argString += args.join(', ');
}
if (invocation.namedArguments.isNotEmpty) {
if (argString.isNotEmpty) argString += ', ';
var namedArgs = invocation.namedArguments.keys.map((key) =>
'${_symbolToString(key)}: ${invocation.namedArguments[key]}');
if (namedArgs.any((arg) => arg.contains('\n'))) {
// As one or more arg contains newlines, put each on its own line, and
// indent each, for better readability.
namedArgs = namedArgs
.map((arg) => arg.splitMapJoin('\n', onNonMatch: (m) => ' $m'));
argString += '{\n${namedArgs.join(',\n')}}';
} else {
// A compact String should be perfect.
argString += '{${namedArgs.join(', ')}}';
}
}
var method = _symbolToString(invocation.memberName);
if (invocation.isMethod) {
method = '$method($argString)';
} else if (invocation.isGetter) {
method = '$method';
} else if (invocation.isSetter) {
method = '$method=$argString';
} else {
throw StateError('Invocation should be getter, setter or a method call.');
}
var verifiedText = verified ? '[VERIFIED] ' : '';
return '$verifiedText$mock.$method';
}
// This used to use MirrorSystem, which cleans up the Symbol() wrapper.
// Since this toString method is just used in Mockito's own tests, it's not
// a big deal to massage the toString a bit.
//
// Input: Symbol("someMethodName")
static String _symbolToString(Symbol symbol) =>
symbol.toString().split('"')[1];
}
class _WhenCall {
final Mock mock;
final Invocation whenInvocation;
_WhenCall(this.mock, this.whenInvocation);
void _setExpected<T>(Answering<T> answer) {
mock._setExpected(CallPair<T>(isInvocation(whenInvocation), answer));
}
}
class _UntilCall {
final InvocationMatcher _invocationMatcher;
final Mock _mock;
_UntilCall(this._mock, Invocation invocation)
: _invocationMatcher = InvocationMatcher(invocation);
bool _matchesInvocation(RealCall realCall) =>
_invocationMatcher.matches(realCall.invocation);
List<RealCall> get _realCalls => _mock._realCalls;
Future<Invocation> get invocationFuture {
if (_realCalls.any(_matchesInvocation)) {
return Future.value(_realCalls.firstWhere(_matchesInvocation).invocation);
}
return _mock._invocationStreamController.stream
.firstWhere(_invocationMatcher.matches);
}
}
class _VerifyCall {
final Mock mock;
final Invocation verifyInvocation;
List<RealCall> matchingInvocations;
_VerifyCall(this.mock, this.verifyInvocation) {
var expectedMatcher = InvocationMatcher(verifyInvocation);
matchingInvocations = mock._realCalls.where((RealCall recordedInvocation) {
return !recordedInvocation.verified &&
expectedMatcher.matches(recordedInvocation.invocation);
}).toList();
}
RealCall _findAfter(DateTime dt) {
return matchingInvocations
.firstWhere((inv) => !inv.verified && inv.timeStamp.isAfter(dt));
}
void _checkWith(bool never) {
if (!never && matchingInvocations.isEmpty) {
var message;
if (mock._realCalls.isEmpty) {
message = 'No matching calls (actually, no calls at all).';
} else {
var otherCalls = mock._realCallsToString();
message = 'No matching calls. All calls: $otherCalls';
}
fail('$message\n'
'(If you called `verify(...).called(0);`, please instead use '
'`verifyNever(...);`.)');
}
if (never && matchingInvocations.isNotEmpty) {
var calls = mock._unverifiedCallsToString();
fail('Unexpected calls: $calls');
}
matchingInvocations.forEach((inv) {
inv.verified = true;
});
}
@override
String toString() =>
'VerifyCall<mock: $mock, memberName: ${verifyInvocation.memberName}>';
}
// An argument matcher that acts like an argument during stubbing or
// verification, and stores "matching" information.
//
/// Users do not need to construct this manually; users can instead use the
/// built-in values, [any], [anyNamed], [captureAny], [captureAnyNamed], or the
/// functions [argThat] and [captureThat].
class ArgMatcher {
final Matcher matcher;
final bool _capture;
ArgMatcher(this.matcher, this._capture);
@override
String toString() => '$ArgMatcher {$matcher: $_capture}';
}
/// An argument matcher that matches any argument passed in "this" position.
Null get any => _registerMatcher(anything, false, argumentMatcher: 'any');
/// An argument matcher that matches any named argument passed in for the
/// parameter named [named].
Null anyNamed(String named) => _registerMatcher(anything, false,
named: named, argumentMatcher: 'anyNamed');
/// An argument matcher that matches any argument passed in "this" position, and
/// captures the argument for later access with `captured`.
Null get captureAny =>
_registerMatcher(anything, true, argumentMatcher: 'captureAny');
/// An argument matcher that matches any named argument passed in for the
/// parameter named [named], and captures the argument for later access with
/// `captured`.
Null captureAnyNamed(String named) => _registerMatcher(anything, true,
named: named, argumentMatcher: 'captureAnyNamed');
/// An argument matcher that matches an argument that matches [matcher].
Null argThat(Matcher matcher, {String named}) =>
_registerMatcher(matcher, false, named: named, argumentMatcher: 'argThat');
/// An argument matcher that matches an argument that matches [matcher], and
/// captures the argument for later access with `captured`.
Null captureThat(Matcher matcher, {String named}) =>
_registerMatcher(matcher, true,
named: named, argumentMatcher: 'captureThat');
@Deprecated('ArgMatchers no longer need to be wrapped in Mockito 3.0')
Null typed<T>(ArgMatcher matcher, {String named}) => null;
@Deprecated('Replace with `argThat`')
Null typedArgThat(Matcher matcher, {String named}) =>
argThat(matcher, named: named);
@Deprecated('Replace with `captureThat`')
Null typedCaptureThat(Matcher matcher, {String named}) =>
captureThat(matcher, named: named);
/// Registers [matcher] into the stored arguments collections.
///
/// Creates an [ArgMatcher] with [matcher] and [capture], then if [named] is
/// non-null, stores that into the positional stored arguments list; otherwise
/// stores it into the named stored arguments map, keyed on [named].
/// [argumentMatcher] is the name of the public API used to register [matcher],
/// for error messages.
Null _registerMatcher(Matcher matcher, bool capture,
{String named, String argumentMatcher}) {
if (!_whenInProgress && !_untilCalledInProgress && !_verificationInProgress) {
// It is not meaningful to store argument matchers outside of stubbing
// (`when`), or verification (`verify` and `untilCalled`). Such argument
// matchers will be processed later erroneously.
_storedArgs.clear();
_storedNamedArgs.clear();
throw ArgumentError(
'The "$argumentMatcher" argument matcher is used outside of method '
'stubbing (via `when`) or verification (via `verify` or `untilCalled`). '
'This is invalid, and results in bad behavior during the next stubbing '
'or verification.');
}
var argMatcher = ArgMatcher(matcher, capture);
if (named == null) {
_storedArgs.add(argMatcher);
} else {
_storedNamedArgs[named] = argMatcher;
}
return null;
}
/// Information about a stub call verification.
///
/// This class is most useful to users in two ways:
///
/// * verifying call count, via [called],
/// * collecting captured arguments, via [captured].
class VerificationResult {
List<dynamic> _captured;
/// List of all arguments captured in real calls.
///
/// This list will include any captured default arguments and has no
/// structure differentiating the arguments of one call from another. Given
/// the following class:
///
/// ```dart
/// class C {
/// String methodWithPositionalArgs(int x, [int y]) => '';
/// String methodWithTwoNamedArgs(int x, {int y, int z}) => '';
/// }
/// ```
///
/// the following stub calls will result in the following captured arguments:
///
/// ```dart
/// mock.methodWithPositionalArgs(1);
/// mock.methodWithPositionalArgs(2, 3);
/// var captured = verify(
/// mock.methodWithPositionalArgs(captureAny, captureAny)).captured;
/// print(captured); // Prints "[1, null, 2, 3]"
///
/// mock.methodWithTwoNamedArgs(1, y: 42, z: 43);
/// mock.methodWithTwoNamedArgs(1, y: 44, z: 45);
/// var captured = verify(
/// mock.methodWithTwoNamedArgs(any,
/// y: captureAnyNamed('y'), z: captureAnyNamed('z'))).captured;
/// print(captured); // Prints "[42, 43, 44, 45]"
/// ```
///
/// Named arguments are listed in the order they are captured in, not the
/// order in which they were passed.
// TODO(https://github.com/dart-lang/linter/issues/1992): Remove ignore
// comments below when google3 has linter with this bug fixed.
// ignore: unnecessary_getters_setters
List<dynamic> get captured => _captured;
@Deprecated(
'captured should be considered final - assigning this field may be '
'removed as early as Mockito 5.0.0')
// ignore: unnecessary_getters_setters
set captured(List<dynamic> captured) => _captured = captured;
/// The number of calls matched in this verification.
int callCount;
bool _testApiMismatchHasBeenChecked = false;
@Deprecated(
'User-constructed VerificationResult is deprecated; this constructor may '
'be deleted as early as Mockito 5.0.0')
VerificationResult(int callCount) : this._(callCount);
VerificationResult._(this.callCount)
: _captured = List<dynamic>.from(_capturedArgs, growable: false) {
_capturedArgs.clear();
}
/// Check for a version incompatibility between mockito, test, and test_api.
///
/// This incompatibility results in an inscrutible error for users. Catching
/// it here allows us to give some steps to fix.
// TODO(srawlins): Remove this when we don't need to check for an
// incompatiblity between test_api and test any more.
// https://github.com/dart-lang/mockito/issues/175
void _checkTestApiMismatch() {
try {
Invoker.current;
} on CastError catch (e) {
if (!e
.toString()
.contains("type 'Invoker' is not a subtype of type 'Invoker'")) {
// Hmm. This is a different CastError from the one we're trying to
// protect against. Let it go.
return;
}
print('Error: Package incompatibility between mockito, test, and '
'test_api packages:');
print('');
print('* mockito ^4.0.0 is incompatible with test <1.4.0');
print('* mockito <4.0.0 is incompatible with test ^1.4.0');
print('');
print('As mockito does not have a dependency on the test package, '
'nothing stopped you from landing in this situation. :( '
'Apologies.');
print('');
print('To fix: bump your dependency on the test package to something '
'like: ^1.4.0, or downgrade your dependency on mockito to something '
'like: ^3.0.0');
rethrow;
}
}
/// Assert that the number of calls matches [matcher].
///
/// Examples:
///
/// * `verify(mock.m()).called(1)` asserts that `m()` is called exactly once.
/// * `verify(mock.m()).called(greaterThan(2))` asserts that `m()` is called
/// more than two times.
///
/// To assert that a method was called zero times, use [verifyNever].
void called(dynamic matcher) {
if (!_testApiMismatchHasBeenChecked) {
// Only execute the check below once. `Invoker.current` may look like a
// cheap getter, but it involves Zones and casting.
_testApiMismatchHasBeenChecked = true;
_checkTestApiMismatch();
}
expect(callCount, wrapMatcher(matcher),
reason: 'Unexpected number of calls');
}
}
typedef Answering<T> = T Function(Invocation realInvocation);
typedef Verification = VerificationResult Function<T>(T matchingInvocations);
typedef _InOrderVerification = void Function<T>(List<T> recordedInvocations);
/// Verify that a method on a mock object was never called with the given
/// arguments.
///
/// Call a method on a mock object within a `verifyNever` call. For example:
///
/// ```dart
/// cat.eatFood("chicken");
/// verifyNever(cat.eatFood("fish"));
/// ```
///
/// Mockito will pass the current test case, as `cat.eatFood` has not been
/// called with `"chicken"`.
Verification get verifyNever => _makeVerify(true);
/// Verify that a method on a mock object was called with the given arguments.
///
/// Call a method on a mock object within the call to `verify`. For example:
///
/// ```dart
/// cat.eatFood("chicken");
/// verify(cat.eatFood("fish"));
/// ```
///
/// Mockito will fail the current test case if `cat.eatFood` has not been called
/// with `"fish"`. Optionally, call `called` on the result, to verify that the
/// method was called a certain number of times. For example:
///
/// ```dart
/// verify(cat.eatFood("fish")).called(2);
/// verify(cat.eatFood("fish")).called(greaterThan(3));
/// ```
///
/// Note: When mockito verifies a method call, said call is then excluded from
/// further verifications. A single method call cannot be verified from multiple
/// calls to `verify`, or `verifyInOrder`. See more details in the FAQ.
///
/// Note: because of an unintended limitation, `verify(...).called(0);` will
/// not work as expected. Please use `verifyNever(...);` instead.
///
/// See also: [verifyNever], [verifyInOrder], [verifyZeroInteractions], and
/// [verifyNoMoreInteractions].
Verification get verify => _makeVerify(false);
Verification _makeVerify(bool never) {
if (_verifyCalls.isNotEmpty) {
var message = 'Verification appears to be in progress.';
if (_verifyCalls.length == 1) {
message =
'$message One verify call has been stored: ${_verifyCalls.single}';
} else {
message =
'$message ${_verifyCalls.length} verify calls have been stored. '
'[${_verifyCalls.first}, ..., ${_verifyCalls.last}]';
}
throw StateError(message);
}
_verificationInProgress = true;
return <T>(T mock) {
_verificationInProgress = false;
if (_verifyCalls.length == 1) {
var verifyCall = _verifyCalls.removeLast();
var result = VerificationResult._(verifyCall.matchingInvocations.length);
verifyCall._checkWith(never);
return result;
} else {
fail('Used on a non-mockito object');
}
};
}
/// Verify that a list of methods on a mock object have been called with the
/// given arguments. For example:
///
/// ```dart
/// verifyInOrder([cat.eatFood("Milk"), cat.sound(), cat.eatFood(any)]);
/// ```
///
/// This verifies that `eatFood` was called with `"Milk"`, sound` was called
/// with no arguments, and `eatFood` was then called with some argument.
///
/// Note: [verifyInOrder] only verifies that each call was made in the order
/// given, but not that those were the only calls. In the example above, if
/// other calls were made to `eatFood` or `sound` between the three given
/// calls, or before or after them, the verification will still succeed.
_InOrderVerification get verifyInOrder {
if (_verifyCalls.isNotEmpty) {
throw StateError(_verifyCalls.join());
}
_verificationInProgress = true;
return <T>(List<T> _) {
_verificationInProgress = false;
var dt = DateTime.fromMillisecondsSinceEpoch(0);
var tmpVerifyCalls = List<_VerifyCall>.from(_verifyCalls);
_verifyCalls.clear();
var matchedCalls = <RealCall>[];
for (var verifyCall in tmpVerifyCalls) {
try {
var matched = verifyCall._findAfter(dt);
matchedCalls.add(matched);
dt = matched.timeStamp;
} on StateError {
var mocks = tmpVerifyCalls.map((vc) => vc.mock).toSet();
var allInvocations =
mocks.expand((m) => m._realCalls).toList(growable: false);
allInvocations
.sort((inv1, inv2) => inv1.timeStamp.compareTo(inv2.timeStamp));
var otherCalls = '';
if (allInvocations.isNotEmpty) {
otherCalls = " All calls: ${allInvocations.join(", ")}";
}
fail('Matching call #${tmpVerifyCalls.indexOf(verifyCall)} '
'not found.$otherCalls');
}
}
for (var call in matchedCalls) {
call.verified = true;
}
};
}
void _throwMockArgumentError(String method, var nonMockInstance) {
if (nonMockInstance == null) {
throw ArgumentError('$method was called with a null argument');
}
throw ArgumentError('$method must only be given a Mock object');
}
void verifyNoMoreInteractions(var mock) {
if (mock is Mock) {
var unverified = mock._realCalls.where((inv) => !inv.verified).toList();
if (unverified.isNotEmpty) {
fail('No more calls expected, but following found: ' + unverified.join());
}
} else {
_throwMockArgumentError('verifyNoMoreInteractions', mock);
}
}
void verifyZeroInteractions(var mock) {
if (mock is Mock) {
if (mock._realCalls.isNotEmpty) {
fail('No interaction expected, but following found: ' +
mock._realCalls.join());
}
} else {
_throwMockArgumentError('verifyZeroInteractions', mock);
}
}
typedef Expectation = PostExpectation<T> Function<T>(T x);
/// Create a stub method response.
///
/// Call a method on a mock object within the call to `when`, and call a
/// canned response method on the result. For example:
///
/// ```dart
/// when(cat.eatFood("fish")).thenReturn(true);
/// ```
///
/// Mockito will store the fake call to `cat.eatFood`, and pair the exact
/// arguments given with the response. When `cat.eatFood` is called outside a
/// `when` or `verify` context (a call "for real"), Mockito will respond with
/// the stored canned response, if it can match the mock method parameters.
///
/// The response generators include `thenReturn`, `thenAnswer`, and `thenThrow`.
///
/// See the README for more information.
Expectation get when {
if (_whenCall != null) {
throw StateError('Cannot call `when` within a stub response');
}
_whenInProgress = true;
return <T>(T _) {
_whenInProgress = false;
return PostExpectation<T>();
};
}
typedef InvocationLoader = Future<Invocation> Function<T>(T _);
/// Returns a future [Invocation] that will complete upon the first occurrence
/// of the given invocation.
///
/// Usage of this is as follows:
///
/// ```dart
/// cat.eatFood("fish");
/// await untilCalled(cat.chew());
/// ```
///
/// In the above example, the untilCalled(cat.chew()) will complete only when
/// that method is called. If the given invocation has already been called, the
/// future will return immediately.
InvocationLoader get untilCalled {
_untilCalledInProgress = true;
return <T>(T _) {
_untilCalledInProgress = false;
return _untilCall.invocationFuture;
};
}
/// Print all collected invocations of any mock methods of [mocks].
void logInvocations(List<Mock> mocks) {
var allInvocations =
mocks.expand((m) => m._realCalls).toList(growable: false);
allInvocations.sort((inv1, inv2) => inv1.timeStamp.compareTo(inv2.timeStamp));
allInvocations.forEach((inv) {
print(inv.toString());
});
}
/// Reset the state of Mockito, typically for use between tests.
///
/// For example, when using the test package, mock methods may accumulate calls
/// in a `setUp` method, making it hard to verify method calls that were made
/// _during_ an individual test. Or, there may be unverified calls from previous
/// test cases that should not affect later test cases.
///
/// In these cases, [resetMockitoState] might be called at the end of `setUp`,
/// or in `tearDown`.
void resetMockitoState() {
_whenInProgress = false;
_untilCalledInProgress = false;
_verificationInProgress = false;
_whenCall = null;
_untilCall = null;
_verifyCalls.clear();
_capturedArgs.clear();
_storedArgs.clear();
_storedNamedArgs.clear();
}
|
mockito/lib/src/mock.dart/0
|
{'file_path': 'mockito/lib/src/mock.dart', 'repo_id': 'mockito', 'token_count': 13457}
|
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
class Food {}
class Chicken extends Food {}
class Tuna extends Food {}
// A Real Cat class
class Cat {
String sound() => 'meow!';
bool likes(String food, {bool isHungry = false}) => false;
void eat<T extends Food>(T food) {}
final int lives = 9;
}
// A Mock Cat class
class MockCat extends Mock implements Cat {}
void main() {
group('Cat', () {
setUpAll(() {
// Register fallback values when using
// `any` or `captureAny` with custom objects.
registerFallbackValue(Chicken());
registerFallbackValue(Tuna());
});
late Cat cat;
setUp(() {
cat = MockCat();
});
test('example', () {
// Stub a method before interacting with the mock.
when(() => cat.sound()).thenReturn('purr');
// Interact with the mock.
expect(cat.sound(), 'purr');
// Verify the interaction.
verify(() => cat.sound()).called(1);
// Stub a method with parameters
when(
() => cat.likes('fish', isHungry: any(named: 'isHungry')),
).thenReturn(true);
expect(cat.likes('fish', isHungry: true), isTrue);
// Verify the interaction.
verify(() => cat.likes('fish', isHungry: true)).called(1);
// Interact with the mock.
cat
..eat(Chicken())
..eat(Tuna());
// Verify the interaction with specific type arguments.
verify(() => cat.eat<Chicken>(any())).called(1);
verify(() => cat.eat<Tuna>(any())).called(1);
verifyNever(() => cat.eat<Food>(any()));
});
});
}
|
mocktail/packages/mocktail/example/main.dart/0
|
{'file_path': 'mocktail/packages/mocktail/example/main.dart', 'repo_id': 'mocktail', 'token_count': 620}
|
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
class Foo {
String? returnsNullableString() => 'Hello';
String returnsNonNullableString() => 'Hello';
}
class MockFoo extends Mock implements Foo {}
void main() {
late MockFoo mock;
setUp(() {
mock = MockFoo();
});
tearDown(resetMocktailState);
group('Using nSM out of the box,', () {
test('nSM returns the dummy value during method stubbing', () {
// Trigger method stubbing.
final whenCall = when;
final stubbedResponse = mock.returnsNullableString();
expect(stubbedResponse, equals(null));
whenCall(() => stubbedResponse).thenReturn('A');
});
test('nSM returns the dummy value during method call verification', () {
when(() => mock.returnsNullableString()).thenReturn('A');
// Make a real call.
final realResponse = mock.returnsNullableString();
expect(realResponse, equals('A'));
// Trigger method call verification.
final verifyCall = verify;
final verificationResponse = mock.returnsNullableString();
expect(verificationResponse, equals(null));
verifyCall(() => verificationResponse);
});
test(
'nSM returns the dummy value during method call verification, using '
'verifyNever', () {
// Trigger method call verification.
final verifyNeverCall = verifyNever;
final verificationResponse = mock.returnsNullableString();
expect(verificationResponse, equals(null));
verifyNeverCall(() => verificationResponse);
});
});
}
|
mocktail/packages/mocktail/test/mockito_compat/nnbd_support_test.dart/0
|
{'file_path': 'mocktail/packages/mocktail/test/mockito_compat/nnbd_support_test.dart', 'repo_id': 'mocktail', 'token_count': 530}
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'mono_config.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
ConditionalStage _$ConditionalStageFromJson(Map json) {
return $checkedNew('ConditionalStage', json, () {
$checkKeys(json,
allowedKeys: const ['name', 'if'],
requiredKeys: const ['name', 'if'],
disallowNullValues: const ['name', 'if']);
final val = ConditionalStage(
$checkedConvert(json, 'name', (v) => v as String),
$checkedConvert(json, 'if', (v) => v as String));
return val;
}, fieldKeyMap: const {'ifCondition': 'if'});
}
Map<String, dynamic> _$ConditionalStageToJson(ConditionalStage instance) {
final val = <String, dynamic>{};
void writeNotNull(String key, dynamic value) {
if (value != null) {
val[key] = value;
}
}
writeNotNull('name', instance.name);
writeNotNull('if', instance.ifCondition);
return val;
}
|
mono_repo/mono_repo/lib/src/mono_config.g.dart/0
|
{'file_path': 'mono_repo/mono_repo/lib/src/mono_config.g.dart', 'repo_id': 'mono_repo', 'token_count': 353}
|
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:io';
import 'package:test/test.dart';
import 'package:test_process/test_process.dart';
void main() {
test('pub get gets dependencies', () async {
var process = await TestProcess.start('pub', ['run', 'mono_repo']);
var output = await process.stdoutStream().join('\n');
expect(output, _helpOutput);
await process.shouldExit(0);
});
test('readme contains latest task output', () {
var readme = File('README.md');
expect(readme.readAsStringSync(), contains('```\n$_helpOutput\n```'));
});
}
final _helpOutput = '''Manage multiple packages in one source repository.
Usage: mono_repo <command> [arguments]
Global options:
-h, --help Print this usage information.
--version Prints the version of mono_repo.
--[no-]recursive Whether to recursively walk sub-directorys looking for packages.
Available commands:
check Check the state of the repository.
help Display help information for mono_repo.
presubmit Run the travis presubmits locally.
pub Run `pub get` or `pub upgrade` against all packages.
travis Configure Travis-CI for child packages.
Run "mono_repo help <command>" for more information about a command.''';
|
mono_repo/mono_repo/test/mono_repo_test.dart/0
|
{'file_path': 'mono_repo/mono_repo/test/mono_repo_test.dart', 'repo_id': 'mono_repo', 'token_count': 482}
|
import 'dart:convert';
import 'package:clock/clock.dart';
import 'package:dio/dio.dart';
import 'package:movies_app/core/configs/configs.dart';
/// Model for the response returned from HTTP Cache
class CachedResponse {
/// Creates an instance of [CachedResponse]
CachedResponse({
required this.data,
required this.age,
required this.statusCode,
required this.headers,
});
/// Creates an instance of [CachedResponse] parsed raw data
factory CachedResponse.fromJson(Map<String, dynamic> data) {
return CachedResponse(
data: data['data'],
age: DateTime.parse(data['age'] as String),
statusCode: data['statusCode'] as int,
headers: Headers.fromMap(
Map<String, List<dynamic>>.from(
json.decode(json.encode(data['headers'])) as Map<dynamic, dynamic>,
).map(
(k, v) => MapEntry(k, List<String>.from(v)),
),
),
);
}
/// The data inside the cached response
final dynamic data;
/// The age of the cached response
///
/// This is used to determine whether the cache has expired or not
/// based on the [Configs.maxCacheAge] value
///
/// see [isValid]
final DateTime age;
/// The http status code of the cached http response
final int statusCode;
/// The cached http response headers
final Headers headers;
/// Determines if a cached response has expired
///
/// A cached response is expired when its [age] is older
/// than the [Configs.maxCacheAge]
bool get isValid => clock.now().isBefore(age.add(Configs.maxCacheAge));
/// Converts data to json Map
Map<String, dynamic> toJson() {
return <String, dynamic>{
'data': data,
'age': age.toString(),
'statusCode': statusCode,
'headers': headers.map,
};
}
/// Builds a dio response from a [RequestOptions] object
Response<dynamic> buildResponse(RequestOptions options) {
return Response<dynamic>(
data: data,
headers: headers,
requestOptions: options.copyWith(extra: options.extra),
statusCode: statusCode,
);
}
}
|
movies_app/lib/core/models/cache_response.dart/0
|
{'file_path': 'movies_app/lib/core/models/cache_response.dart', 'repo_id': 'movies_app', 'token_count': 731}
|
import 'package:flutter/material.dart';
import 'package:movies_app/core/configs/styles/app_colors.dart';
/// Shimmer widget with simple fade animation
class Shimmer extends StatefulWidget {
/// Creates a new instance of [Shimmer]
const Shimmer({
super.key,
this.width,
this.height,
this.minOpacity = 0.05,
this.maxOpacity = 0.1,
});
/// Shimmer area width
final double? width;
/// Shimmer area height
final double? height;
/// Shimmer fade minimum opacity
final double minOpacity;
/// Shimmer fade maximum opacity
final double maxOpacity;
@override
State<Shimmer> createState() => _ShimmerState();
}
class _ShimmerState extends State<Shimmer> with SingleTickerProviderStateMixin {
late final AnimationController animationController;
@override
void initState() {
animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 1000),
lowerBound: widget.minOpacity,
upperBound: widget.maxOpacity,
);
animationController.repeat(reverse: true);
super.initState();
}
@override
void dispose() {
animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FadeTransition(
opacity: animationController,
child: Container(
width: widget.width,
height: widget.height,
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(10),
),
),
);
}
}
|
movies_app/lib/core/widgets/shimmer.dart/0
|
{'file_path': 'movies_app/lib/core/widgets/shimmer.dart', 'repo_id': 'movies_app', 'token_count': 544}
|
import 'package:flutter/material.dart';
import 'package:movies_app/features/people/views/widgets/popular_people_app_bar.dart';
import 'package:movies_app/features/people/views/widgets/popular_people_list.dart';
/// Widget for the popular people page
class PopularPeoplePage extends StatelessWidget {
/// Creates a new instance of [PopularPeoplePage]
const PopularPeoplePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const PopularPeopleAppBar(),
),
body: const PopularPeopleList(),
);
}
}
|
movies_app/lib/features/people/views/pages/popular_people_page.dart/0
|
{'file_path': 'movies_app/lib/features/people/views/pages/popular_people_page.dart', 'repo_id': 'movies_app', 'token_count': 200}
|
/// Enum for image sizes from The TMDB API configurations
///
/// See: https://developers.themoviedb.org/3/configuration/get-api-configuration
enum ImageSize {
/// Image width of 300px
w300,
/// Image width of 780px
w780,
/// Image width of 1280px
w1280,
/// Image width of 45px
w45,
/// Image width of 92px
w92,
/// Image width of 154px
w154,
/// Image width of 185px
w185,
/// Image width of 500px
w500,
/// Image width of 342px
w342,
/// Image height of 632px
h632,
/// Original image size
original,
}
|
movies_app/lib/features/tmdb-configs/enums/image_size.dart/0
|
{'file_path': 'movies_app/lib/features/tmdb-configs/enums/image_size.dart', 'repo_id': 'movies_app', 'token_count': 192}
|
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:movies_app/features/people/views/pages/person_images_slider_page.dart';
import 'package:movies_app/features/people/views/widgets/person_images_grid.dart';
import '../../../../test-utils/dummy-data/dummy_people.dart';
import '../../../../test-utils/pump_app.dart';
void main() {
testWidgets(
'navigates to PersonImagesSliderPage',
(WidgetTester tester) async {
await tester.pumpApp(
PersonImagesGrid(DummyPeople.personImagesWithoutImages),
);
await tester.pumpAndSettle();
await tester.tap(find.byType(GestureDetector).first);
await tester.pumpAndSettle();
expect(find.byType(PersonImagesSliderPage), findsOneWidget);
},
);
}
|
movies_app/test/features/people/views/widgets/person_images_grid_test.dart/0
|
{'file_path': 'movies_app/test/features/people/views/widgets/person_images_grid_test.dart', 'repo_id': 'movies_app', 'token_count': 306}
|
import 'package:flutter/material.dart';
import 'package:hacker_news_vanilla/src/app.dart';
import 'package:hacker_news_vanilla/src/news_repository.dart';
void main() {
runApp(
HackerNewsApp(newsRepository: NewsRepository()),
);
}
|
new_flutter_template/evaluations/hacker_news_vanilla/lib/main.dart/0
|
{'file_path': 'new_flutter_template/evaluations/hacker_news_vanilla/lib/main.dart', 'repo_id': 'new_flutter_template', 'token_count': 90}
|
import 'package:flutter/cupertino.dart';
import 'package:uuid/uuid.dart';
class JournalEntry {
final String id;
final String title;
final DateTime date;
final String body;
JournalEntry({
@required this.title,
@required this.date,
@required this.body,
String id,
}) : id = id ?? Uuid().v4();
@override
String toString() {
return 'JournalEntry{id: $id, title: $title, date: $date, body: $body}';
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is JournalEntry &&
runtimeType == other.runtimeType &&
id == other.id &&
title == other.title &&
date == other.date &&
body == other.body;
@override
int get hashCode =>
id.hashCode ^ title.hashCode ^ date.hashCode ^ body.hashCode;
}
|
new_flutter_template/evaluations/journal_clean_architecture/lib/domain/entities/journal_entry.dart/0
|
{'file_path': 'new_flutter_template/evaluations/journal_clean_architecture/lib/domain/entities/journal_entry.dart', 'repo_id': 'new_flutter_template', 'token_count': 322}
|
class AppRouteConfiguration {
final String location;
AppRouteConfiguration(this.location);
bool get isHome => this is HomeConfiguration;
bool get isJournalEntry => this is JournalEntryConfiguration;
bool get isUserSettings => this is UserSettingsConfiguration;
bool get isUnknown => this is UnknownConfiguration;
}
class HomeConfiguration extends AppRouteConfiguration {
HomeConfiguration() : super('/');
}
class AddEntryConfiguration extends AppRouteConfiguration {
AddEntryConfiguration() : super('/entry/add');
}
class JournalEntryConfiguration extends AppRouteConfiguration {
final String id;
JournalEntryConfiguration(this.id) : super('/entry/$id');
}
class UserSettingsConfiguration extends AppRouteConfiguration {
UserSettingsConfiguration() : super('/settings');
}
class UnknownConfiguration extends AppRouteConfiguration {
UnknownConfiguration() : super('/404');
}
|
new_flutter_template/evaluations/journal_clean_architecture/lib/ui/navigation/app_route_configuration.dart/0
|
{'file_path': 'new_flutter_template/evaluations/journal_clean_architecture/lib/ui/navigation/app_route_configuration.dart', 'repo_id': 'new_flutter_template', 'token_count': 210}
|
import 'package:flutter/material.dart';
import 'package:list_detail_mvc_cubit/src/users/user_list_controller.dart';
import 'package:list_detail_mvc_cubit/src/users/user_list_view.dart';
class UserListApp extends StatelessWidget {
final UserController controller;
const UserListApp({Key key, @required this.controller}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'List/Detail Demo',
theme: ThemeData.dark(),
home: UserListView(controller: controller),
);
}
}
|
new_flutter_template/evaluations/list_detail_mvc_cubit/lib/src/app.dart/0
|
{'file_path': 'new_flutter_template/evaluations/list_detail_mvc_cubit/lib/src/app.dart', 'repo_id': 'new_flutter_template', 'token_count': 190}
|
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:list_detail_mvc_mobx/src/user.dart';
import 'package:list_detail_mvc_mobx/src/user_details.dart';
import 'package:list_detail_mvc_mobx/src/user_list_controller.dart';
class UserListPage extends StatefulWidget {
final UserController controller;
const UserListPage({Key key, @required this.controller}) : super(key: key);
@override
_UserListPageState createState() => _UserListPageState();
}
class _UserListPageState extends State<UserListPage> {
@override
void initState() {
// Begin loading the users when the User List is first shown.
widget.controller.loadUsers();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('User List'),
),
body: Observer(
builder: (context) {
if (widget.controller.loading) {
return Center(child: CircularProgressIndicator());
} else if (widget.controller.hasError) {
return Center(child: Icon(Icons.error));
}
return ListView.builder(
itemCount: widget.controller.users.length,
itemBuilder: (context, index) {
var user = widget.controller.users[index];
return Dismissible(
key: ObjectKey(user),
onDismissed: (_) => widget.controller.removeUser(user),
background: Container(color: Colors.red),
child: ListTile(
title: Text('User #${user.id}'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => UserDetailsPage(user: user),
),
);
},
),
);
},
);
},
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
widget.controller.addUser(User(Random().nextInt(1000)));
},
),
);
}
}
|
new_flutter_template/evaluations/list_detail_mvc_mobx/lib/src/user_list.dart/0
|
{'file_path': 'new_flutter_template/evaluations/list_detail_mvc_mobx/lib/src/user_list.dart', 'repo_id': 'new_flutter_template', 'token_count': 1035}
|
import 'package:flutter/material.dart';
import 'package:list_detail_mvc_provider/src/app.dart';
import 'package:list_detail_mvc_provider/src/users/user_list_controller.dart';
import 'package:list_detail_mvc_provider/src/users/user_repository.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => UserController(UserRepository()),
child: MyApp(),
),
);
}
|
new_flutter_template/evaluations/list_detail_mvc_provider/lib/main.dart/0
|
{'file_path': 'new_flutter_template/evaluations/list_detail_mvc_provider/lib/main.dart', 'repo_id': 'new_flutter_template', 'token_count': 166}
|
import 'package:flutter/widgets.dart';
class UserAvatar extends StatelessWidget {
final Color color;
final double size;
const UserAvatar({
Key key,
@required this.color,
this.size = 32,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return SizedBox(
width: size,
height: size,
child: Hero(
tag: color,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(100),
color: color,
),
),
),
);
}
}
|
new_flutter_template/evaluations/list_detail_mvc_vn_prettier/lib/src/users/user_avatar.dart/0
|
{'file_path': 'new_flutter_template/evaluations/list_detail_mvc_vn_prettier/lib/src/users/user_avatar.dart', 'repo_id': 'new_flutter_template', 'token_count': 254}
|
import 'package:list_detail_mvc_vn_two_features/src/settings/settings.dart';
class SettingsRepository {
Future<Settings> settings() async => Settings();
Future<void> updateSettings(Settings s) async {}
}
|
new_flutter_template/evaluations/list_detail_mvc_vn_two_features/lib/src/settings/settings_repository.dart/0
|
{'file_path': 'new_flutter_template/evaluations/list_detail_mvc_vn_two_features/lib/src/settings/settings_repository.dart', 'repo_id': 'new_flutter_template', 'token_count': 63}
|
import 'package:list_detail_with_data_layer/src/user_model.dart';
class UserRepository {
Future<User> user(int id) {
return Future.delayed(Duration(seconds: 1), () => User(id));
}
Future<List<User>> users() {
return Future.delayed(
Duration(seconds: 2),
() => List.generate(20, (index) => User(index)),
);
}
}
|
new_flutter_template/evaluations/list_detail_with_data_layer/lib/src/user_repository.dart/0
|
{'file_path': 'new_flutter_template/evaluations/list_detail_with_data_layer/lib/src/user_repository.dart', 'repo_id': 'new_flutter_template', 'token_count': 134}
|
import 'package:login_mvc/src/pantone_colors/pantone_color.dart';
class PantoneColorFeed {
final int page;
final int perPage;
final int total;
final int totalPages;
final List<PantoneColor> colors;
PantoneColorFeed({
this.page,
this.perPage,
this.total,
this.totalPages,
this.colors,
});
PantoneColorFeed.fromJson(Map<String, dynamic> map)
: page = map['page'],
perPage = map['per_page'],
total = map['total'],
totalPages = map['total_pages'],
colors = (map['data'] ?? [])
.cast<Map<String, dynamic>>()
.map<PantoneColor>((json) => PantoneColor.fromJson(json))
.toList();
}
|
new_flutter_template/evaluations/login_mvc/lib/src/pantone_colors/pantone_color_feed.dart/0
|
{'file_path': 'new_flutter_template/evaluations/login_mvc/lib/src/pantone_colors/pantone_color_feed.dart', 'repo_id': 'new_flutter_template', 'token_count': 303}
|
import 'package:flutter/material.dart';
import 'package:newsapp/views/gallery_view.dart';
import 'package:newsapp/authenticate/login_page.dart';
import 'package:newsapp/authenticate/signin.dart';
import 'package:newsapp/authenticate/signup.dart';
class Authenticate extends StatefulWidget {
@override
_AuthenticateState createState() => _AuthenticateState();
}
class _AuthenticateState extends State<Authenticate> {
bool showSignIn = true;
void toggleView(){
setState(() {
showSignIn = !showSignIn;
});
}
@override
Widget build(BuildContext context) {
if (!showSignIn) {
return SignUp(toggleView: toggleView,);
} else {
return SignIn(toggleView: toggleView);
}
}
//// return Container();
// }
}
|
news_app/lib/authenticate/authenticate.dart/0
|
{'file_path': 'news_app/lib/authenticate/authenticate.dart', 'repo_id': 'news_app', 'token_count': 264}
|
name: app_ui
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
pull_request:
paths:
- "flutter_news_example/packages/app_ui/**"
- ".github/workflows/app_ui.yaml"
branches:
- main
jobs:
build:
uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1
with:
flutter_version: 3.10.2
working_directory: flutter_news_example/packages/app_ui
coverage_excludes: "lib/src/generated/*.dart"
|
news_toolkit/.github/workflows/app_ui.yaml/0
|
{'file_path': 'news_toolkit/.github/workflows/app_ui.yaml', 'repo_id': 'news_toolkit', 'token_count': 216}
|
name: notifications_client
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
pull_request:
paths:
- "flutter_news_example/packages/notifications_client/notifications_client/**"
- ".github/workflows/notifications_client.yaml"
branches:
- main
jobs:
build:
uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/dart_package.yml@v1
with:
dart_sdk: 3.0.2
working_directory: flutter_news_example/packages/notifications_client/notifications_client
|
news_toolkit/.github/workflows/notifications_client.yaml/0
|
{'file_path': 'news_toolkit/.github/workflows/notifications_client.yaml', 'repo_id': 'news_toolkit', 'token_count': 207}
|
analyzer:
exclude:
- flutter_news_template/*
|
news_toolkit/analysis_options.yaml/0
|
{'file_path': 'news_toolkit/analysis_options.yaml', 'repo_id': 'news_toolkit', 'token_count': 20}
|
import 'package:equatable/equatable.dart';
import 'package:flutter_news_example_api/client.dart';
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
/// {@template user}
/// A user object which contains user metadata.
/// {@endtemplate}
@JsonSerializable(explicitToJson: true)
class User extends Equatable {
/// {@macro user}
const User({required this.id, required this.subscription});
/// Converts a `Map<String, dynamic>` into a [User] instance.
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
/// The associated user identifier.
final String id;
/// The associated subscription plan.
final SubscriptionPlan subscription;
/// Converts the current instance to a `Map<String, dynamic>`.
Map<String, dynamic> toJson() => _$UserToJson(this);
@override
List<Object> get props => [id, subscription];
}
|
news_toolkit/flutter_news_example/api/lib/src/data/models/user.dart/0
|
{'file_path': 'news_toolkit/flutter_news_example/api/lib/src/data/models/user.dart', 'repo_id': 'news_toolkit', 'token_count': 273}
|
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:news_blocks/news_blocks.dart';
part 'popular_search_response.g.dart';
/// {@template popular_search_response}
/// A search response object which contains popular news content.
/// {@endtemplate}
@JsonSerializable()
class PopularSearchResponse extends Equatable {
/// {@macro popular_search_response}
const PopularSearchResponse({required this.articles, required this.topics});
/// Converts a `Map<String, dynamic>` into a [PopularSearchResponse] instance.
factory PopularSearchResponse.fromJson(Map<String, dynamic> json) =>
_$PopularSearchResponseFromJson(json);
/// The article content blocks.
@NewsBlocksConverter()
final List<NewsBlock> articles;
/// The associated popular topics.
final List<String> topics;
/// Converts the current instance to a `Map<String, dynamic>`.
Map<String, dynamic> toJson() => _$PopularSearchResponseToJson(this);
@override
List<Object> get props => [articles, topics];
}
|
news_toolkit/flutter_news_example/api/lib/src/models/popular_search_response/popular_search_response.dart/0
|
{'file_path': 'news_toolkit/flutter_news_example/api/lib/src/models/popular_search_response/popular_search_response.dart', 'repo_id': 'news_toolkit', 'token_count': 311}
|
/// The supported news post category types.
enum PostCategory {
/// News post relating to business.
business,
/// News post relating to entertainment.
entertainment,
/// News post relating to health.
health,
/// News post relating to science.
science,
/// News post relating to sports.
sports,
/// News post relating to technology.
technology,
}
|
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/post_category.dart/0
|
{'file_path': 'news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/post_category.dart', 'repo_id': 'news_toolkit', 'token_count': 94}
|
import 'package:news_blocks/news_blocks.dart';
import 'package:test/test.dart';
void main() {
group('NewsletterBlock', () {
test('can be (de)serialized', () {
const block = NewsletterBlock();
expect(NewsletterBlock.fromJson(block.toJson()), equals(block));
});
});
}
|
news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/newsletter_block_test.dart/0
|
{'file_path': 'news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/newsletter_block_test.dart', 'repo_id': 'news_toolkit', 'token_count': 107}
|
// ignore_for_file: prefer_const_constructors
import 'package:news_blocks/news_blocks.dart';
import 'package:test/test.dart';
void main() {
group('TrendingStoryBlock', () {
test('can be (de)serialized', () {
final content = PostSmallBlock(
id: 'id',
category: PostCategory.health,
author: 'author',
publishedAt: DateTime(2022, 3, 11),
imageUrl: 'imageUrl',
title: 'title',
);
final block = TrendingStoryBlock(content: content);
expect(TrendingStoryBlock.fromJson(block.toJson()), equals(block));
});
});
}
|
news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/trending_story_block_test.dart/0
|
{'file_path': 'news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/trending_story_block_test.dart', 'repo_id': 'news_toolkit', 'token_count': 242}
|
import 'dart:io';
import 'package:dart_frog/dart_frog.dart';
Response onRequest(RequestContext context) {
return Response(statusCode: HttpStatus.noContent);
}
|
news_toolkit/flutter_news_example/api/routes/index.dart/0
|
{'file_path': 'news_toolkit/flutter_news_example/api/routes/index.dart', 'repo_id': 'news_toolkit', 'token_count': 55}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.