code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
/// Any line that starts with `var` or `void` should be coloured.
/// Every other line should be a comment.
// ignore_for_file: unused_element
/* test /* test */ */
var a = 1;
/** test /** test */ */
var b = 1;
/** test /* test */ */
var c = 1;
/* test /** test */ */
var d = 1;
// test
var e = 1;
/**
* test
* test
* test
*/
/*
/**
* test
* test
* test
*/
*/
// /**
// * test
// * test
// * test
// */
/// /*
/// /**
/// * test
/// * test
/// * test
/// */
/// */
/**
* /**
* * bbb
* */
*/
/// test
var f = 1;
/// test
/// test
var g = 1; /// test
var h = 1; /// test
/// test
// test
var i = 1;
// test
// test
var j = 1; // test
var k = 1; // test
// test
/* // */
var l = 1;
/* /// */
var m = 1;
/*
* // Test
*/
var n = 1;
/** // */
var o = 1;
/** /// */
var p = 1;
/**
* // Test
*/
var q = 1;
/// This is a long comment with some nested code.
///
/// ```dart
/// test
/// ```
var r = 1;
void foo() {
/**
* Nested function.
*/
bool bar() => true;
}
class ClassToAddIndenting {
/* test /* test */ */
var a = 1;
/** test /** test */ */
var b = 1;
/** test /* test */ */
var c = 1;
/* test /** test */ */
var d = 1;
// test
var e = 1;
/**
* test
* test
* test
*/
/*
/**
* test
* test
* test
*/
*/
// /**
// * test
// * test
// * test
// */
/// /*
/// /**
/// * test
/// * test
/// * test
/// */
/// */
/// test
var f = 1;
/// test
/// test
var g = 1; /// test
var h = 1; /// test
/// test
// test
var i = 1;
// test
// test
var j = 1; // test
var k = 1; // test
// test
/* // */
var l = 1;
/* /// */
var m = 1;
/*
* // Test
*/
var n = 1;
/** // */
var o = 1;
/** /// */
var p = 1;
/**
* // Test
*/
var q = 1;
/// This is a long comment with some nested code.
///
/// ```dart
/// test
/// ```
var r = 1;
void foo() {
/**
* Nested function.
*/
void bar() {}
}
}
|
Dart-Code/src/test/test_projects/grammar_testing/lib/comments.dart/0
|
{'file_path': 'Dart-Code/src/test/test_projects/grammar_testing/lib/comments.dart', 'repo_id': 'Dart-Code', 'token_count': 899}
|
import 'dart:async';
Future<void> main() async {
await func1();
}
Future func1() async => await func2();
Future func2() async => await func3();
Future func3() async => await func4();
Future func4() async => await func5();
Future func5() async => await func6();
Future func6() async => await func7();
Future func7() async => await func8();
Future func8() async => await func9();
Future func9() async => await func10();
Future func10() async => await func11();
Future func11() async => await func12();
Future func12() async => await func13();
Future func13() async => await func14();
Future func14() async => await func15();
Future func15() async => await func16();
Future func16() async => await func17();
Future func17() async => await func18();
Future func18() async => await func19();
Future func19() async => await func20();
Future func20() async => await func21();
Future func21() async => await func22();
Future func22() async => await func23();
Future func23() async => await func24();
Future func24() async => await func25();
Future func25() async => await func26();
Future func26() async => await func27();
Future func27() async => await func28();
Future func28() async => await func29();
Future func29() async => await func30();
Future func30() async => await func31();
Future func31() async => await func32();
Future func32() async => await func33();
Future func33() async => await func34();
Future func34() async => await func35();
Future func35() async => await func36();
Future func36() async => await func37();
Future func37() async => await func38();
Future func38() async => await func39();
Future func39() async => await func40();
Future func40() async => await func41();
Future func41() async => await func42();
Future func42() async => await func43();
Future func43() async => await func44();
Future func44() async => await func45();
Future func45() async => await func46();
Future func46() async => await func47();
Future func47() async => await func48();
Future func48() async => await func49();
Future func49() async => await func50();
Future func50() async => await func51();
Future func51() async => await func52();
Future func52() async => await func53();
Future func53() async => await func54();
Future func54() async => await func55();
Future func55() async => await func56();
Future func56() async => await func57();
Future func57() async => await func58();
Future func58() async => await func59();
Future func59() async => await func60();
Future func60() async {
print("Hello, world!"); // BREAKPOINT1
}
|
Dart-Code/src/test/test_projects/hello_world/bin/stack60.dart/0
|
{'file_path': 'Dart-Code/src/test/test_projects/hello_world/bin/stack60.dart', 'repo_id': 'Dart-Code', 'token_count': 701}
|
import "package:test/test.dart";
void main() {
group("String", () {
test(".split() splits the string on the delimiter", () {
var string = "foo,bar,baz"; // BREAKPOINT1
expect(string.split(","), equals(["foo", "bar", "baz"]));
});
test(".split() splits the string on the delimiter 2", () {
expect("foo,bar,baz",
allOf([contains("foo"), isNot(startsWith("bar")), endsWith("baz")]));
});
test(".trim() removes surrounding whitespace", () {
var string = " foo ";
expect(string.trim(), equals("foo"));
});
});
group("int", () {
test(".remainder() returns the remainder of division", () {
expect(11.remainder(3), equals(2));
});
test(".toRadixString() returns a hex string", () {
expect(11.toRadixString(16), equals("b"));
});
});
group("greater than", () {
test("without quotes List<String>", () {
expect(1, 1);
});
test('with quotes ">= foo"', () {
expect(1, 1);
});
});
}
|
Dart-Code/src/test/test_projects/hello_world/test/basic_test.dart/0
|
{'file_path': 'Dart-Code/src/test/test_projects/hello_world/test/basic_test.dart', 'repo_id': 'Dart-Code', 'token_count': 414}
|
name: my_package
environment:
sdk: '>=2.12.0 <3.0.0'
|
Dart-Code/src/test/test_projects/my_package/pubspec.yaml/0
|
{'file_path': 'Dart-Code/src/test/test_projects/my_package/pubspec.yaml', 'repo_id': 'Dart-Code', 'token_count': 30}
|
import 'package:flare_flutter/flare_actor.dart';
import 'package:flutter/material.dart';
import 'package:init_dsktp_plugin/init_dsktp_plugin.dart';
class BgWidget extends StatelessWidget {
const BgWidget({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
//
return Stack(
alignment: AlignmentDirectional.center,
children: <Widget>[
const FlareActor(
'assets/animations/spaceman.flr',
alignment: Alignment.centerLeft,
fit: BoxFit.cover,
animation: 'Untitled',
),
Positioned(
bottom: 10.0,
child: FutureBuilder<String>(
future: InitDsktpPlugin.platformVersion,
builder: (context, snapshot) {
if (snapshot.hasData) {
return _CustomText(data: snapshot.data);
}
return const Text('');
},
),
),
],
);
}
}
class _CustomText extends StatelessWidget {
const _CustomText({Key key, this.data}) : super(key: key);
final String data;
@override
Widget build(BuildContext context) {
//
return Text(
data,
style: const TextStyle(
color: Colors.white,
fontSize: 24.0,
),
);
}
}
|
Experiments_with_Desktop/first_desktop_application/lib/app-level/widgets/bg_widget.dart/0
|
{'file_path': 'Experiments_with_Desktop/first_desktop_application/lib/app-level/widgets/bg_widget.dart', 'repo_id': 'Experiments_with_Desktop', 'token_count': 588}
|
// To parse this JSON data, do
//
// final cryptoModel = cryptoModelFromJson(jsonString);
import 'dart:convert';
CryptoModel cryptoModelFromJson(String str) =>
CryptoModel.fromJson(json.decode(str) as Map<String, dynamic>);
String cryptoModelToJson(CryptoModel data) => json.encode(data.toJson());
class CryptoModel {
CryptoModel({
this.time,
this.disclaimer,
this.chartName,
this.bpi,
});
Time time;
String disclaimer;
String chartName;
Bpi bpi;
factory CryptoModel.fromJson(Map<String, dynamic> json) => CryptoModel(
time: Time.fromJson(json["time"] as Map<String, dynamic>),
disclaimer: json["disclaimer"] as String,
chartName: json["chartName"] as String,
bpi: Bpi.fromJson(json["bpi"] as Map<String, dynamic>),
);
Map<String, dynamic> toJson() => <String, dynamic>{
"time": time.toJson(),
"disclaimer": disclaimer,
"chartName": chartName,
"bpi": bpi.toJson(),
};
}
class Bpi {
Bpi({
this.usd,
this.gbp,
this.eur,
});
Eur usd;
Eur gbp;
Eur eur;
factory Bpi.fromJson(Map<String, dynamic> json) => Bpi(
usd: Eur.fromJson(json["USD"] as Map<String, dynamic>),
gbp: Eur.fromJson(json["GBP"] as Map<String, dynamic>),
eur: Eur.fromJson(json["EUR"] as Map<String, dynamic>),
);
Map<String, dynamic> toJson() => <String, dynamic>{
"USD": usd.toJson(),
"GBP": gbp.toJson(),
"EUR": eur.toJson(),
};
}
class Eur {
Eur({
this.code,
this.symbol,
this.rate,
this.description,
this.rateFloat,
});
String code;
String symbol;
String rate;
String description;
double rateFloat;
factory Eur.fromJson(Map<String, dynamic> json) => Eur(
code: json["code"] as String,
symbol: json["symbol"] as String,
rate: json["rate"] as String,
description: json["description"] as String,
rateFloat: json["rate_float"].toDouble() as double,
);
Map<String, dynamic> toJson() => <String, dynamic>{
"code": code,
"symbol": symbol,
"rate": rate,
"description": description,
"rate_float": rateFloat,
};
}
class Time {
Time({
this.updated,
this.updatedIso,
this.updateduk,
});
String updated;
DateTime updatedIso;
String updateduk;
factory Time.fromJson(Map<String, dynamic> json) => Time(
updated: json["updated"] as String,
updatedIso: DateTime.parse(json["updatedISO"] as String),
updateduk: json["updateduk"] as String,
);
Map<String, dynamic> toJson() => <String, dynamic>{
"updated": updated,
"updatedISO": updatedIso.toIso8601String(),
"updateduk": updateduk,
};
}
|
Experiments_with_Desktop/first_desktop_application/lib/crypto/model/crypto.model.dart/0
|
{'file_path': 'Experiments_with_Desktop/first_desktop_application/lib/crypto/model/crypto.model.dart', 'repo_id': 'Experiments_with_Desktop', 'token_count': 1179}
|
import 'package:first_desktop_application/flipping/data/demo_data.dart';
import 'package:first_desktop_application/flipping/widgets/flight_barcode.dart';
import 'package:first_desktop_application/flipping/widgets/flight_details.dart';
import 'package:first_desktop_application/flipping/widgets/flight_summary.dart';
import 'package:first_desktop_application/flipping/widgets/folding_ticket.dart';
import 'package:flutter/material.dart';
class Ticket extends StatefulWidget {
static const double nominalOpenHeight = 400; // 160 +160 +80 (_getEntries)
static const double nominalClosedHeight = 160; // 160
final BoardingPassData boardingPass;
final Function onClick;
const Ticket({
Key key,
@required this.boardingPass,
@required this.onClick,
}) : super(key: key);
@override
_TicketState createState() => _TicketState();
}
class _TicketState extends State<Ticket> {
FlightSummary frontCard;
FlightSummary topCard;
FlightDetails middleCard;
FlightBarcode bottomCard;
bool _isOpen;
Widget get backCard => Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4.0),
color: const Color(0xffdce6ef)),
);
@override
void initState() {
super.initState();
_isOpen = false;
frontCard = FlightSummary(boardingPass: widget.boardingPass);
middleCard = FlightDetails(boardingPass: widget.boardingPass);
bottomCard = const FlightBarcode();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _handleOnTap,
child: FoldingTicket(
entries: _getEntries(),
isOpen: _isOpen,
),
);
}
List<FoldEntry> _getEntries() {
return [
FoldEntry(height: 160.0, front: topCard),
FoldEntry(height: 160.0, front: middleCard, back: frontCard),
FoldEntry(height: 80.0, front: bottomCard, back: backCard)
];
}
void _handleOnTap() {
widget.onClick();
setState(() {
_isOpen = !_isOpen;
topCard = FlightSummary(
boardingPass: widget.boardingPass,
theme: SummaryTheme.dark,
isOpen: _isOpen,
);
});
}
}
|
Experiments_with_Desktop/first_desktop_application/lib/flipping/widgets/ticket.dart/0
|
{'file_path': 'Experiments_with_Desktop/first_desktop_application/lib/flipping/widgets/ticket.dart', 'repo_id': 'Experiments_with_Desktop', 'token_count': 793}
|
import 'package:url_launcher/url_launcher.dart';
class LinkerService {
LinkerService();
Future<void> openLink(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
}
|
Experiments_with_Desktop/first_desktop_application/lib/shared/services/linker_service.dart/0
|
{'file_path': 'Experiments_with_Desktop/first_desktop_application/lib/shared/services/linker_service.dart', 'repo_id': 'Experiments_with_Desktop', 'token_count': 101}
|
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
class AdvancedShare {
static const MethodChannel _channel =
const MethodChannel('github.com/mrtcndnlr/advanced_share');
/// Required String msg or String url
/// Default title: "Share"
static Future<int> generic(
{String msg,
String url,
String title,
String subject,
String type}) async {
final Map<String, dynamic> params = <String, dynamic>{
'msg': msg,
'url': url,
'title': title,
'subject': subject,
'type': type,
};
return await exec(params);
}
static Future<int> whatsapp({String msg, String url}) async {
final Map<String, dynamic> params = <String, dynamic>{
'msg': msg,
'url': url,
'direct': 'whatsapp'
};
return await exec(params);
}
static Future<int> gmail({String subject, String msg, String url}) async {
final Map<String, dynamic> params = <String, dynamic>{
'msg': msg,
'url': url,
'subject': subject,
'direct': 'gmail'
};
return await exec(params);
}
@protected
static Future<int> exec(params) async {
try {
return await _channel.invokeMethod('share', params);
} catch (e) {
return await Future<int>.value(0);
}
}
}
|
Flutter-Advanced-Share/lib/advanced_share.dart/0
|
{'file_path': 'Flutter-Advanced-Share/lib/advanced_share.dart', 'repo_id': 'Flutter-Advanced-Share', 'token_count': 515}
|
import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:stacked/stacked.dart';
import 'package:xafe/app/authentication/data/models/user_model.dart';
import 'package:xafe/app/authentication/domain/params/post_params/post_params.dart';
import 'package:xafe/app/authentication/domain/usecases/create_user.dart';
import 'package:xafe/app/authentication/domain/usecases/register_user.dart';
import 'package:xafe/core/error/helpers/helpers.dart';
import 'package:xafe/main_screen.dart';
import 'package:xafe/src/utils/navigation/navigation.dart';
class SignUpViewmodel extends BaseViewModel {
SignUpViewmodel(
this._registerUser,
this._createUser,
);
final RegisterUser _registerUser;
final CreateUser _createUser;
Future registerUser({
UserModel params,
EmailPasswordParams emailPasswordParams,
BuildContext context,
}) {
setBusy(true);
return _registerUser(emailPasswordParams)
..then(
(result) {
result.fold(
(failure) {
setBusy(false);
Fluttertoast.showToast(
msg: mapFailureMessage(failure),
);
},
(data) {
setBusy(false);
return createUser(
params: UserModel(
name: params.name,
id: data.uid,
email: data.email,
),
context: context,
);
},
).then(
(value) => setBusy(false),
);
},
);
}
Future createUser({
UserModel params,
BuildContext context,
}) {
setBusy(true);
return _createUser(params)
..then(
(result) {
result.fold(
(failure) {},
(data) {
return pushAndRemoveUntil(
context,
MainScreen(),
);
},
).then(
(value) => setBusy(false),
);
},
);
}
}
|
Xafe/lib/app/authentication/presentation/logic/viewmodels/signup_viewmodel.dart/0
|
{'file_path': 'Xafe/lib/app/authentication/presentation/logic/viewmodels/signup_viewmodel.dart', 'repo_id': 'Xafe', 'token_count': 1020}
|
import 'package:dartz/dartz.dart';
import 'package:xafe/app/budget/data/models/budget_model.dart';
import 'package:xafe/app/budget/domain/repository/budget_repo.dart';
import 'package:xafe/core/error/failures.dart';
class EditBudget {
EditBudget(this._repository);
final BudgetRepo _repository;
Future<Either<Failure, void>> call(BudgetModel params) async =>
await _repository.editBudget(params);
}
|
Xafe/lib/app/budget/domain/usecases/edit_budget.dart/0
|
{'file_path': 'Xafe/lib/app/budget/domain/usecases/edit_budget.dart', 'repo_id': 'Xafe', 'token_count': 150}
|
import 'package:dartz/dartz.dart';
import 'package:xafe/app/categories/data/datasource/categories_datasource.dart';
import 'package:xafe/app/categories/data/model/category_model.dart';
import 'package:xafe/app/categories/domain/repository/categories_repo.dart';
import 'package:xafe/core/error/failures.dart';
import 'package:xafe/core/error/helpers/helpers.dart';
class CategoriesRepoImpl implements CategoriesRepo {
CategoriesRepoImpl(this._categoriesDataSource);
final CategoriesDataSource _categoriesDataSource;
@override
Future<Either<Failure, void>> createCategory(CategoryModel params) {
return successFailureInterceptor(
() => _categoriesDataSource.createCategory(params),
);
}
@override
Stream<List<CategoryModel>> listenToCategories({String uid}) {
return _categoriesDataSource.listenToCategories(uid);
}
@override
Future<Either<Failure, void>> deleteCategory(String categoryId) {
return successFailureInterceptor(
() => _categoriesDataSource.deleteCategory(categoryId),
);
}
}
|
Xafe/lib/app/categories/data/repository/categories_repo_impl.dart/0
|
{'file_path': 'Xafe/lib/app/categories/data/repository/categories_repo_impl.dart', 'repo_id': 'Xafe', 'token_count': 340}
|
import 'package:xafe/app/home/data/datasource/home_datasource.dart';
import 'package:xafe/app/home/data/datasource/impl/home_datasource_impl.dart';
import 'package:xafe/app/home/data/repository/home_repo_impl.dart';
import 'package:xafe/app/home/domain/repository/home_repo.dart';
import 'package:xafe/app/home/domain/usecases/add_an_expense.dart';
import 'package:xafe/app/home/domain/usecases/listen_to_expenses.dart';
import 'package:xafe/core/config/di_config.dart';
void registerHomeDIs() {
//Use cases
locator.registerLazySingleton(() => AddAnExpense(locator()));
locator.registerLazySingleton(() => ListenToExpenses(locator()));
//Repository
locator.registerLazySingleton<HomeRepo>(
() => HomeRepoImpl(
locator(),
),
);
// Data sources
locator.registerLazySingleton<HomeDataSource>(
() => HomeDataSourceImpl(
locator(),
),
);
}
|
Xafe/lib/app/home/home_dependencies.dart/0
|
{'file_path': 'Xafe/lib/app/home/home_dependencies.dart', 'repo_id': 'Xafe', 'token_count': 342}
|
String _errorMessage;
String get getErrorMessage => _errorMessage;
String setErrorMessage(String errorMessage) => _errorMessage = errorMessage;
class Error {
Error({this.message});
//Map error coming from the [API].
Error.map(Map<String, dynamic> map) {
message = map['message'].toString() ?? ''.toString();
}
String message;
}
|
Xafe/lib/core/error/error.dart/0
|
{'file_path': 'Xafe/lib/core/error/error.dart', 'repo_id': 'Xafe', 'token_count': 104}
|
export 'colors/colors.dart';
|
Xafe/lib/src/res/values/values.dart/0
|
{'file_path': 'Xafe/lib/src/res/values/values.dart', 'repo_id': 'Xafe', 'token_count': 11}
|
import 'package:equatable/equatable.dart';
import 'package:{{project_name.snakeCase()}}/models/Todo.dart';
abstract class AddTodoPageEvents extends Equatable {
const AddTodoPageEvents();
@override
List<Object> get props => [];
}
class TodoAdded extends AddTodoPageEvents {
const TodoAdded(this.todo);
final Todo todo;
@override
List<Object> get props => [todo];
}
|
amplify_starter/__brick__/{{project_name}}/lib/todos/add_todo/bloc/add_todo_page_events.dart/0
|
{'file_path': 'amplify_starter/__brick__/{{project_name}}/lib/todos/add_todo/bloc/add_todo_page_events.dart', 'repo_id': 'amplify_starter', 'token_count': 130}
|
import 'dart:convert';
import 'dart:io';
import 'dart:mirrors';
import 'package:cli_util/cli_logging.dart';
import 'package:pubspec_parse/pubspec_parse.dart';
abstract class Socket {}
final _log = Logger.standard();
Future<void> startPlugin({
required List<String> args,
required String pluginName,
required String pluginInterfaceName,
required String mainSource,
}) async {
final ownerDetails = await _findOwnerPubspec();
final pubspecFile = File('./pubspec.yaml');
if (!pubspecFile.existsSync()) {
_log.stderr(
'The current folder (${Directory.current.absolute.path}) does not contains a `pubspec.yaml`',
);
exit(-1);
}
final analyzedPubspec = Pubspec.parse(await pubspecFile.readAsString());
final progress = _log.progress('Searching for plugins');
final plugins = await _findPluginsThatDependsOnPackage(
analyzedPubspec: analyzedPubspec,
packageName: 'analyzer_plugin',
).toList();
progress.finish(showTiming: true);
final pluginsBuffer = StringBuffer('Found ${plugins.length} plugins\n');
for (final plugin in plugins) {
pluginsBuffer.writeln('- ${plugin.name}');
}
_log.stdout(pluginsBuffer.toString());
await _generateTemporaryProject(
plugins,
pluginName: pluginName,
analyzedPubspec: analyzedPubspec,
ownerDetails: ownerDetails,
entrypointSource: mainSource,
pluginInterfaceName: pluginInterfaceName,
);
final process = await Process.start(
'dart',
['run', './.dart_tool/plugin/generated/bin/generated_project.dart'],
);
stdout.addStream(process.stdout);
stderr.addStream(process.stderr);
await process.exitCode;
}
Future<_PackageDetails> _findOwnerPubspec() async {
final mirror = currentMirrorSystem();
var dir = Directory(
FileSystemEntity.parentOf(
mirror.isolate.rootLibrary.uri.toFilePath(),
),
);
while (!await File('${dir.path}/pubspec.yaml').exists()) {
dir = dir.parent;
}
final pubspecFile = await File('${dir.path}/pubspec.yaml').readAsString();
final pubspec = Pubspec.parse(pubspecFile);
return _PackageDetails(name: pubspec.name, path: dir.path, pubspec: pubspec);
}
Future<void> _generateTemporaryProject(
List<_PackageDetails> plugins, {
required String pluginName,
required _PackageDetails ownerDetails,
required Pubspec analyzedPubspec,
required String entrypointSource,
required String pluginInterfaceName,
}) async {
await _generateTemporaryPubspec(plugins, ownerDetails: ownerDetails);
final entrypointFile =
File('./.dart_tool/plugin/generated/bin/entrypoint.dart');
await entrypointFile.create(recursive: true);
await entrypointFile.writeAsString(entrypointSource);
final generatedMainFile =
File('./.dart_tool/plugin/generated/bin/generated_project.dart');
await generatedMainFile.create(recursive: true);
final pluginsImports = [
for (final plugin in plugins)
"import 'package:${plugin.name}/${plugin.name}.dart' as ${plugin.name};"
].join('\n');
final pluginDetails = [
for (final plugin in plugins) " ${plugin.name}.createPlugin(),"
];
generatedMainFile.writeAsString('''
import './entrypoint.dart' as entrypoint;
import 'package:$pluginName/$pluginName.dart' as $pluginName;
$pluginsImports
void main(List<String> args) {
final List<$pluginName.${pluginInterfaceName}> plugins = [
${pluginDetails.join('\n')}
];
entrypoint.main(args, plugins);
}
''');
}
Future<void> _generateTemporaryPubspec(
List<_PackageDetails> plugins, {
required _PackageDetails ownerDetails,
}) async {
final generatedPubspecFile =
File('./.dart_tool/plugin/generated/pubspec.yaml');
await generatedPubspecFile.create(recursive: true);
final generatedPubspecBuffer = StringBuffer();
// TODO: reuse environment from pubspec
generatedPubspecBuffer.write('''
name: generated_project
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
${ownerDetails.name}:
path: ${ownerDetails.path}
''');
for (final plugin in plugins) {
generatedPubspecBuffer.write('''
${plugin.name}:
path: ${plugin.path}
''');
}
await generatedPubspecFile.writeAsString(generatedPubspecBuffer.toString());
final progress =
_log.progress('Running `dart pub get` in the generated project');
await Process.run(
'dart',
['pub', 'get'],
workingDirectory: './.dart_tool/plugin/generated',
);
progress.finish(showTiming: true);
}
class _PackageDetails {
_PackageDetails({
required this.name,
required this.path,
required this.pubspec,
});
final String name;
final String path;
final Pubspec pubspec;
}
Stream<_PackageDetails> _findPluginsThatDependsOnPackage({
required String packageName,
required Pubspec analyzedPubspec,
}) async* {
final packageConfigFile = File('./.dart_tool/package_config.json');
if (!packageConfigFile.existsSync()) {
_log.stderr("""
Dependencies not found.
Make sure to run `dart pub get` first""");
exit(-1);
}
final packageConfig = json.decode(await packageConfigFile.readAsString())
as Map<String, Object?>;
final packages =
(packageConfig['packages'] as List).cast<Map<String, Object?>>();
final allDirectDependencies = {
...analyzedPubspec.dependencies,
...analyzedPubspec.devDependencies,
}.entries;
for (final dep in allDirectDependencies) {
final dependencyConfig = packages.firstWhere(
(e) => e['name'] == dep.key,
orElse: () {
_log.stderr("""
Dependencies not found.
Make sure to run `dart pub get` first""");
exit(-1);
},
);
var uri = dependencyConfig['rootUri'] as String;
if (uri.startsWith('../')) uri = uri.replaceFirst('../', '');
final packagePath = Directory.fromUri(Uri.parse(uri)).absolute.path;
final packagePubspecFile = File('${packagePath}/pubspec.yaml');
if (!packagePubspecFile.existsSync()) {
_log.stderr(
'No pubspec.yaml for package ${dep.key} at ${packagePubspecFile.path}',
);
exit(-1);
}
final packagePubspec =
Pubspec.parse(await packagePubspecFile.readAsString());
if (packagePubspec.dependencies.containsKey(packageName) ||
packagePubspec.devDependencies.containsKey(packageName))
yield _PackageDetails(
name: dep.key,
path: packagePath,
pubspec: packagePubspec,
);
}
}
|
analyzer_plugins/packages/plugin/lib/plugin.dart/0
|
{'file_path': 'analyzer_plugins/packages/plugin/lib/plugin.dart', 'repo_id': 'analyzer_plugins', 'token_count': 2197}
|
name: sample
description: An new Dart Frog application
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.18.0 <3.0.0"
dependencies:
dart_frog: ^0.3.0
dev_dependencies:
mocktail: ^0.3.0
test: ^1.19.2
very_good_analysis: ^3.1.0
|
article-hub/dart-frog/sample/pubspec.yaml/0
|
{'file_path': 'article-hub/dart-frog/sample/pubspec.yaml', 'repo_id': 'article-hub', 'token_count': 112}
|
name: sample
on: [pull_request, push]
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
flutter_version: 3.3.3
|
article-hub/flame-game/sample/.github/workflows/main.yaml/0
|
{'file_path': 'article-hub/flame-game/sample/.github/workflows/main.yaml', 'repo_id': 'article-hub', 'token_count': 133}
|
export 'tapping_behavior.dart';
|
article-hub/flame-game/sample/lib/game/entities/unicorn/behaviors/behaviors.dart/0
|
{'file_path': 'article-hub/flame-game/sample/lib/game/entities/unicorn/behaviors/behaviors.dart', 'repo_id': 'article-hub', 'token_count': 11}
|
import 'package:flutter/material.dart';
/// {@template animated_progress_bar}
/// A [Widget] that renders a intrinsically animated progress bar.
///
/// [progress] should be between 0 and 1;
/// {@endtemplate}
class AnimatedProgressBar extends StatelessWidget {
/// {@macro animated_progress_bar}
const AnimatedProgressBar({
super.key,
required this.progress,
required this.backgroundColor,
required this.foregroundColor,
}) : assert(
progress >= 0.0 && progress <= 1.0,
'Progress should be set between 0.0 and 1.0',
);
/// The background color of the progress bar.
final Color backgroundColor;
/// The foreground color of the progress bar.
final Color foregroundColor;
/// The current progress for the bar.
final double progress;
/// The duration of the animation on [AnimatedProgressBar]
static const Duration intrinsicAnimationDuration =
Duration(milliseconds: 300);
@override
Widget build(BuildContext context) {
// Outer bar
return ClipRRect(
borderRadius: BorderRadius.circular(2),
child: SizedBox(
height: 16,
width: 200,
child: ColoredBox(
color: backgroundColor,
child: Padding(
padding: const EdgeInsets.all(2),
// Animate the progress bar
child: TweenAnimationBuilder(
tween: Tween<double>(begin: 0, end: progress),
duration: intrinsicAnimationDuration,
builder: (BuildContext context, double progress, _) {
// Inner bar
return FractionallySizedBox(
alignment: Alignment.centerLeft,
widthFactor: progress,
child: ClipRRect(
borderRadius: BorderRadius.circular(1),
child: ColoredBox(
color: foregroundColor,
),
),
);
},
),
),
),
),
);
}
}
|
article-hub/flame-game/sample/lib/loading/widgets/animated_progress_bar.dart/0
|
{'file_path': 'article-hub/flame-game/sample/lib/loading/widgets/animated_progress_bar.dart', 'repo_id': 'article-hub', 'token_count': 871}
|
export 'mocks.dart';
export 'pump_app.dart';
export 'test_game.dart';
|
article-hub/flame-game/sample/test/helpers/helpers.dart/0
|
{'file_path': 'article-hub/flame-game/sample/test/helpers/helpers.dart', 'repo_id': 'article-hub', 'token_count': 30}
|
import 'package:flutter/material.dart';
import 'app.dart';
void main() {
runApp(const App());
}
|
article-hub/flutter/hack_proof_app/lib/main.dart/0
|
{'file_path': 'article-hub/flutter/hack_proof_app/lib/main.dart', 'repo_id': 'article-hub', 'token_count': 38}
|
// 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:async';
import 'package:async/async.dart';
/// Runs asynchronous functions and caches the result for a period of time.
///
/// This class exists to cover the pattern of having potentially expensive code
/// such as file I/O, network access, or isolate computation that's unlikely to
/// change quickly run fewer times. For example:
///
/// ```dart
/// final _usersCache = new AsyncCache<List<String>>(const Duration(hours: 1));
///
/// /// Uses the cache if it exists, otherwise calls the closure:
/// Future<List<String>> get onlineUsers => _usersCache.fetch(() {
/// // Actually fetch online users here.
/// });
/// ```
///
/// This class's timing can be mocked using [`fake_async`][fake_async].
///
/// [fake_async]: https://pub.dev/packages/fake_async
class AsyncCache<T> {
/// How long cached values stay fresh.
final Duration _duration;
/// Cached results of a previous [fetchStream] call.
StreamSplitter<T> _cachedStreamSplitter;
/// Cached results of a previous [fetch] call.
Future<T> _cachedValueFuture;
/// Fires when the cache should be considered stale.
Timer _stale;
/// Creates a cache that invalidates its contents after [duration] has passed.
///
/// The [duration] starts counting after the Future returned by [fetch]
/// completes, or after the Stream returned by [fetchStream] emits a done
/// event.
AsyncCache(this._duration);
/// Creates a cache that invalidates after an in-flight request is complete.
///
/// An ephemeral cache guarantees that a callback function will only be
/// executed at most once concurrently. This is useful for requests for which
/// data is updated frequently but stale data is acceptable.
factory AsyncCache.ephemeral() => AsyncCache(Duration.zero);
/// Returns a cached value from a previous call to [fetch], or runs [callback]
/// to compute a new one.
///
/// If [fetch] has been called recently enough, returns its previous return
/// value. Otherwise, runs [callback] and returns its new return value.
Future<T> fetch(Future<T> Function() callback) async {
if (_cachedStreamSplitter != null) {
throw StateError('Previously used to cache via `fetchStream`');
}
if (_cachedValueFuture == null) {
_cachedValueFuture = callback();
await _cachedValueFuture;
_startStaleTimer();
}
return _cachedValueFuture;
}
/// Returns a cached stream from a previous call to [fetchStream], or runs
/// [callback] to compute a new stream.
///
/// If [fetchStream] has been called recently enough, returns a copy of its
/// previous return value. Otherwise, runs [callback] and returns its new
/// return value.
Stream<T> fetchStream(Stream<T> Function() callback) {
if (_cachedValueFuture != null) {
throw StateError('Previously used to cache via `fetch`');
}
_cachedStreamSplitter ??= StreamSplitter(
callback().transform(StreamTransformer.fromHandlers(handleDone: (sink) {
_startStaleTimer();
sink.close();
})));
return _cachedStreamSplitter.split();
}
/// Removes any cached value.
void invalidate() {
// TODO: This does not return a future, but probably should.
_cachedValueFuture = null;
// TODO: This does not await, but probably should.
_cachedStreamSplitter?.close();
_cachedStreamSplitter = null;
_stale?.cancel();
_stale = null;
}
void _startStaleTimer() {
_stale = Timer(_duration, invalidate);
}
}
|
async/lib/src/async_cache.dart/0
|
{'file_path': 'async/lib/src/async_cache.dart', 'repo_id': 'async', 'token_count': 1113}
|
// 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 'dart:async';
import 'result.dart';
import 'capture_sink.dart';
/// A stream transformer that captures a stream of events into [Result]s.
///
/// The result of the transformation is a stream of [Result] values and no
/// error events. Exposed by [Result.captureStream].
class CaptureStreamTransformer<T> extends StreamTransformerBase<T, Result<T>> {
const CaptureStreamTransformer();
@override
Stream<Result<T>> bind(Stream<T> source) =>
Stream<Result<T>>.eventTransformed(
source, (sink) => CaptureSink<T>(sink));
}
|
async/lib/src/result/capture_transformer.dart/0
|
{'file_path': 'async/lib/src/result/capture_transformer.dart', 'repo_id': 'async', 'token_count': 235}
|
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'future_group.dart';
import 'result/result.dart';
/// A class that splits a single source stream into an arbitrary number of
/// (single-subscription) streams (called "branch") that emit the same events.
///
/// Each branch will emit all the same values and errors as the source stream,
/// regardless of which values have been emitted on other branches. This means
/// that the splitter stores every event that has been emitted so far, which may
/// consume a lot of memory. The user can call [close] to indicate that no more
/// branches will be created, and this memory will be released.
///
/// The source stream is only listened to once a branch is created *and listened
/// to*. It's paused when all branches are paused *or when all branches are
/// canceled*, and resumed once there's at least one branch that's listening and
/// unpaused. It's not canceled unless no branches are listening and [close] has
/// been called.
class StreamSplitter<T> {
/// The wrapped stream.
final Stream<T> _stream;
/// The subscription to [_stream].
///
/// This will be `null` until a branch has a listener.
StreamSubscription<T> _subscription;
/// The buffer of events or errors that have already been emitted by
/// [_stream].
final _buffer = <Result<T>>[];
/// The controllers for branches that are listening for future events from
/// [_stream].
///
/// Once a branch is canceled, it's removed from this list. When [_stream] is
/// done, all branches are removed.
final _controllers = <StreamController<T>>{};
/// A group of futures returned by [close].
///
/// This is used to ensure that [close] doesn't complete until all
/// [StreamController.close] and [StreamSubscription.cancel] calls complete.
final _closeGroup = FutureGroup();
/// Whether [_stream] is done emitting events.
var _isDone = false;
/// Whether [close] has been called.
var _isClosed = false;
/// Splits [stream] into [count] identical streams.
///
/// [count] defaults to 2. This is the same as creating [count] branches and
/// then closing the [StreamSplitter].
static List<Stream<T>> splitFrom<T>(Stream<T> stream, [int count]) {
count ??= 2;
var splitter = StreamSplitter<T>(stream);
var streams = List<Stream<T>>.generate(count, (_) => splitter.split());
splitter.close();
return streams;
}
StreamSplitter(this._stream);
/// Returns a single-subscription stream that's a copy of the input stream.
///
/// This will throw a [StateError] if [close] has been called.
Stream<T> split() {
if (_isClosed) {
throw StateError("Can't call split() on a closed StreamSplitter.");
}
var controller = StreamController<T>(
onListen: _onListen, onPause: _onPause, onResume: _onResume);
controller.onCancel = () => _onCancel(controller);
for (var result in _buffer) {
result.addTo(controller);
}
if (_isDone) {
_closeGroup.add(controller.close());
} else {
_controllers.add(controller);
}
return controller.stream;
}
/// Indicates that no more branches will be requested via [split].
///
/// This clears the internal buffer of events. If there are no branches or all
/// branches have been canceled, this cancels the subscription to the input
/// stream.
///
/// Returns a [Future] that completes once all events have been processed by
/// all branches and (if applicable) the subscription to the input stream has
/// been canceled.
Future close() {
if (_isClosed) return _closeGroup.future;
_isClosed = true;
_buffer.clear();
if (_controllers.isEmpty) _cancelSubscription();
return _closeGroup.future;
}
/// Cancel [_subscription] and close [_closeGroup].
///
/// This should be called after all the branches' subscriptions have been
/// canceled and the splitter has been closed. In that case, we won't use the
/// events from [_subscription] any more, since there's nothing to pipe them
/// to and no more branches will be created. If [_subscription] is done,
/// canceling it will be a no-op.
///
/// This may also be called before any branches have been created, in which
/// case [_subscription] will be `null`.
void _cancelSubscription() {
assert(_controllers.isEmpty);
assert(_isClosed);
Future future;
if (_subscription != null) future = _subscription.cancel();
if (future != null) _closeGroup.add(future);
_closeGroup.close();
}
// StreamController events
/// Subscribe to [_stream] if we haven't yet done so, and resume the
/// subscription if we have.
void _onListen() {
if (_isDone) return;
if (_subscription != null) {
// Resume the subscription in case it was paused, either because all the
// controllers were paused or because the last one was canceled. If it
// wasn't paused, this will be a no-op.
_subscription.resume();
} else {
_subscription =
_stream.listen(_onData, onError: _onError, onDone: _onDone);
}
}
/// Pauses [_subscription] if every controller is paused.
void _onPause() {
if (!_controllers.every((controller) => controller.isPaused)) return;
_subscription.pause();
}
/// Resumes [_subscription].
///
/// If [_subscription] wasn't paused, this is a no-op.
void _onResume() {
_subscription.resume();
}
/// Removes [controller] from [_controllers] and cancels or pauses
/// [_subscription] as appropriate.
///
/// Since the controller emitting a done event will cause it to register as
/// canceled, this is the only way that a controller is ever removed from
/// [_controllers].
void _onCancel(StreamController controller) {
_controllers.remove(controller);
if (_controllers.isNotEmpty) return;
if (_isClosed) {
_cancelSubscription();
} else {
_subscription.pause();
}
}
// Stream events
/// Buffers [data] and passes it to [_controllers].
void _onData(T data) {
if (!_isClosed) _buffer.add(Result.value(data));
for (var controller in _controllers) {
controller.add(data);
}
}
/// Buffers [error] and passes it to [_controllers].
void _onError(Object error, StackTrace stackTrace) {
if (!_isClosed) _buffer.add(Result.error(error, stackTrace));
for (var controller in _controllers) {
controller.addError(error, stackTrace);
}
}
/// Marks [_controllers] as done.
void _onDone() {
_isDone = true;
for (var controller in _controllers) {
_closeGroup.add(controller.close());
}
}
}
|
async/lib/src/stream_splitter.dart/0
|
{'file_path': 'async/lib/src/stream_splitter.dart', 'repo_id': 'async', 'token_count': 2113}
|
// 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:async';
import 'dart:math' show Random;
import 'package:async/async.dart';
import 'package:test/test.dart';
final someStack = StackTrace.current;
Result<int> res(int n) => Result<int>.value(n);
Result err(n) => ErrorResult('$n', someStack);
/// Helper function creating an iterable of futures.
Iterable<Future<int>> futures(int count,
{bool Function(int index) throwWhen}) sync* {
for (var i = 0; i < count; i++) {
if (throwWhen != null && throwWhen(i)) {
yield Future<int>.error('$i', someStack);
} else {
yield Future<int>.value(i);
}
}
}
void main() {
test('empty', () async {
var all = await Result.captureAll<int>(futures(0));
expect(all, []);
});
group('futures only,', () {
test('single', () async {
var all = await Result.captureAll<int>(futures(1));
expect(all, [res(0)]);
});
test('multiple', () async {
var all = await Result.captureAll<int>(futures(3));
expect(all, [res(0), res(1), res(2)]);
});
test('error only', () async {
var all =
await Result.captureAll<int>(futures(1, throwWhen: (_) => true));
expect(all, [err(0)]);
});
test('multiple error only', () async {
var all =
await Result.captureAll<int>(futures(3, throwWhen: (_) => true));
expect(all, [err(0), err(1), err(2)]);
});
test('mixed error and value', () async {
var all =
await Result.captureAll<int>(futures(4, throwWhen: (x) => x.isOdd));
expect(all, [res(0), err(1), res(2), err(3)]);
});
test('completion permutation 1-2-3', () async {
var cs = List.generate(3, (_) => Completer<int>());
var all = Result.captureAll<int>(cs.map((c) => c.future));
expect(all, completion([res(1), res(2), err(3)]));
await 0;
cs[0].complete(1);
await 0;
cs[1].complete(2);
await 0;
cs[2].completeError('3', someStack);
});
test('completion permutation 1-3-2', () async {
var cs = List.generate(3, (_) => Completer<int>());
var all = Result.captureAll<int>(cs.map((c) => c.future));
expect(all, completion([res(1), res(2), err(3)]));
await 0;
cs[0].complete(1);
await 0;
cs[2].completeError('3', someStack);
await 0;
cs[1].complete(2);
});
test('completion permutation 2-1-3', () async {
var cs = List.generate(3, (_) => Completer<int>());
var all = Result.captureAll<int>(cs.map((c) => c.future));
expect(all, completion([res(1), res(2), err(3)]));
await 0;
cs[1].complete(2);
await 0;
cs[0].complete(1);
await 0;
cs[2].completeError('3', someStack);
});
test('completion permutation 2-3-1', () async {
var cs = List.generate(3, (_) => Completer<int>());
var all = Result.captureAll<int>(cs.map((c) => c.future));
expect(all, completion([res(1), res(2), err(3)]));
await 0;
cs[1].complete(2);
await 0;
cs[2].completeError('3', someStack);
await 0;
cs[0].complete(1);
});
test('completion permutation 3-1-2', () async {
var cs = List.generate(3, (_) => Completer<int>());
var all = Result.captureAll<int>(cs.map((c) => c.future));
expect(all, completion([res(1), res(2), err(3)]));
await 0;
cs[2].completeError('3', someStack);
await 0;
cs[0].complete(1);
await 0;
cs[1].complete(2);
});
test('completion permutation 3-2-1', () async {
var cs = List.generate(3, (_) => Completer<int>());
var all = Result.captureAll<int>(cs.map((c) => c.future));
expect(all, completion([res(1), res(2), err(3)]));
await 0;
cs[2].completeError('3', someStack);
await 0;
cs[1].complete(2);
await 0;
cs[0].complete(1);
});
var seed = Random().nextInt(0x100000000);
var n = 25; // max 32, otherwise rnd.nextInt(1<<n) won't work.
test('randomized #$n seed:${seed.toRadixString(16)}', () async {
var cs = List.generate(n, (_) => Completer<int>());
var all = Result.captureAll<int>(cs.map((c) => c.future));
var rnd = Random(seed);
var throwFlags = rnd.nextInt(1 << n); // Bit-flag for throwing.
bool throws(index) => (throwFlags & (1 << index)) != 0;
var expected = List.generate(n, (x) => throws(x) ? err(x) : res(x));
expect(all, completion(expected));
var completeFunctions = List<Function()>.generate(n, (i) {
var c = cs[i];
return () =>
throws(i) ? c.completeError('$i', someStack) : c.complete(i);
});
completeFunctions.shuffle(rnd);
for (var i = 0; i < n; i++) {
await 0;
completeFunctions[i]();
}
});
});
group('values only,', () {
test('single', () async {
var all = await Result.captureAll<int>(<int>[1]);
expect(all, [res(1)]);
});
test('multiple', () async {
var all = await Result.captureAll<int>(<int>[1, 2, 3]);
expect(all, [res(1), res(2), res(3)]);
});
});
group('mixed futures and values,', () {
test('no error', () async {
var all = await Result.captureAll<int>(<FutureOr<int>>[
1,
Future<int>(() => 2),
3,
Future<int>.value(4),
]);
expect(all, [res(1), res(2), res(3), res(4)]);
});
test('error', () async {
var all = await Result.captureAll<int>(<FutureOr<int>>[
1,
Future<int>(() => 2),
3,
Future<int>(() async => await Future.error('4', someStack)),
Future<int>.value(5)
]);
expect(all, [res(1), res(2), res(3), err(4), res(5)]);
});
});
}
|
async/test/result/result_captureAll_test.dart/0
|
{'file_path': 'async/test/result/result_captureAll_test.dart', 'repo_id': 'async', 'token_count': 2625}
|
// 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.
/// Helper utilities for testing.
import 'dart:async';
import 'package:async/async.dart';
import 'package:test/test.dart';
/// A zero-millisecond timer should wait until after all microtasks.
Future flushMicrotasks() => Future.delayed(Duration.zero);
typedef OptionalArgAction = void Function([dynamic a, dynamic b]);
/// A generic unreachable callback function.
///
/// Returns a function that fails the test if it is ever called.
OptionalArgAction unreachable(String name) =>
([a, b]) => fail('Unreachable: $name');
// TODO(nweiz): Use the version of this in test when test#418 is fixed.
/// A matcher that runs a callback in its own zone and asserts that that zone
/// emits an error that matches [matcher].
Matcher throwsZoned(matcher) => predicate((callback) {
var firstError = true;
runZoned(callback,
onError: expectAsync2((error, stackTrace) {
if (firstError) {
expect(error, matcher);
firstError = false;
} else {
registerException(error, stackTrace);
}
}, max: -1));
return true;
});
/// A matcher that runs a callback in its own zone and asserts that that zone
/// emits a [CastError].
final throwsZonedCastError = throwsZoned(TypeMatcher<CastError>());
/// A matcher that matches a callback or future that throws a [CastError].
final throwsCastError = throwsA(TypeMatcher<CastError>());
/// A badly behaved stream which throws if it's ever listened to.
///
/// Can be used to test cases where a stream should not be used.
class UnusableStream<T> extends Stream<T> {
@override
StreamSubscription<T> listen(onData, {onError, onDone, cancelOnError}) {
throw UnimplementedError('Gotcha!');
}
}
/// A dummy [StreamSink] for testing the routing of the [done] and [close]
/// futures.
///
/// The [completer] field allows the user to control the future returned by
/// [done] and [close].
class CompleterStreamSink<T> implements StreamSink<T> {
final completer = Completer();
@override
Future get done => completer.future;
@override
void add(T event) {}
@override
void addError(error, [StackTrace stackTrace]) {}
@override
Future addStream(Stream<T> stream) async {}
@override
Future close() => completer.future;
}
/// A [StreamSink] that collects all events added to it as results.
///
/// This is used for testing code that interacts with sinks.
class TestSink<T> implements StreamSink<T> {
/// The results corresponding to events that have been added to the sink.
final results = <Result<T>>[];
/// Whether [close] has been called.
bool get isClosed => _isClosed;
var _isClosed = false;
@override
Future get done => _doneCompleter.future;
final _doneCompleter = Completer();
final Function _onDone;
/// Creates a new sink.
///
/// If [onDone] is passed, it's called when the user calls [close]. Its result
/// is piped to the [done] future.
TestSink({void Function() onDone}) : _onDone = onDone ?? (() {});
@override
void add(T event) {
results.add(Result<T>.value(event));
}
@override
void addError(error, [StackTrace stackTrace]) {
results.add(Result<T>.error(error, stackTrace));
}
@override
Future addStream(Stream<T> stream) {
var completer = Completer.sync();
stream.listen(add, onError: addError, onDone: completer.complete);
return completer.future;
}
@override
Future close() {
_isClosed = true;
_doneCompleter.complete(Future.microtask(_onDone));
return done;
}
}
|
async/test/utils.dart/0
|
{'file_path': 'async/test/utils.dart', 'repo_id': 'async', 'token_count': 1249}
|
/// {@template async_toolkit}
/// A Very Good Project created by Very Good CLI.
/// {@endtemplate}
class AsyncToolkit {
/// {@macro async_toolkit}
const AsyncToolkit();
}
|
async_toolkit/lib/src/async_toolkit.dart/0
|
{'file_path': 'async_toolkit/lib/src/async_toolkit.dart', 'repo_id': 'async_toolkit', 'token_count': 58}
|
import 'package:flutter/foundation.dart';
/// A pair of latitude and longitude coordinates.
/// The `latitude` and `longitude` are stored as degrees.
class LatLng {
/// The latitude in degrees between -90.0 and 90.0, both inclusive.
final double latitude;
/// The longitude in degrees between -180.0 (inclusive) and 180.0 (exclusive).
final double longitude;
const LatLng({
@required double latitude,
@required double longitude,
}) : assert(latitude != null),
assert(longitude != null),
latitude =
(latitude < -90.0 ? -90.0 : (90.0 < latitude ? 90.0 : latitude)),
longitude = (longitude + 180.0) % 360.0 - 180.0;
@override
bool operator ==(Object o) {
return o is LatLng && o.latitude == latitude && o.longitude == longitude;
}
@override
int get hashCode =>
runtimeType.hashCode ^ latitude.hashCode ^ longitude.hashCode;
}
|
atlas/packages/atlas/lib/src/lat_lng.dart/0
|
{'file_path': 'atlas/packages/atlas/lib/src/lat_lng.dart', 'repo_id': 'atlas', 'token_count': 316}
|
import 'package:flutter_test/flutter_test.dart';
import 'package:atlas/atlas.dart';
main() {
group('Marker Icon', () {
test('should throw assertion error if assetName is null', () {
try {
MarkerIcon(
assetName: null,
);
fail('should throw assertion error');
} catch (error) {
expect(error, isAssertionError);
}
});
test('should override == properly', () {
expect(
MarkerIcon(
assetName: 'my-asset',
),
MarkerIcon(
assetName: 'my-asset',
),
);
});
test('should override hashCode properly', () {
final markerIcon = MarkerIcon(
assetName: 'my-asset',
);
expect(
markerIcon.hashCode,
markerIcon.runtimeType.hashCode ^ markerIcon.assetName.hashCode,
);
});
});
}
|
atlas/packages/atlas/test/marker_icon_test.dart/0
|
{'file_path': 'atlas/packages/atlas/test/marker_icon_test.dart', 'repo_id': 'atlas', 'token_count': 397}
|
import 'package:atlas/atlas.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart' as GoogleMaps;
class CameraUtils {
/// Converts an `Atlas.LatLng` to a `GoogleMaps.CameraPosition`
static GoogleMaps.CameraPosition toGoogleCameraPosition(
CameraPosition position,
) {
return GoogleMaps.CameraPosition(
target: GoogleMaps.LatLng(
position.target.latitude,
position.target.longitude,
),
zoom: position.zoom,
);
}
}
|
atlas/packages/google_atlas/lib/src/utils/camera_utils.dart/0
|
{'file_path': 'atlas/packages/google_atlas/lib/src/utils/camera_utils.dart', 'repo_id': 'atlas', 'token_count': 181}
|
import 'package:audioplayers/audioplayers.dart';
import 'package:audioplayers_example/tabs/sources.dart';
import '../platform_features.dart';
import '../source_test_data.dart';
/// Data of a library test source.
class LibSourceTestData extends SourceTestData {
Source source;
LibSourceTestData({
required this.source,
required super.duration,
super.isVBR,
});
@override
String toString() {
return 'LibSourceTestData('
'source: $source, '
'duration: $duration, '
'isVBR: $isVBR'
')';
}
}
final _features = PlatformFeatures.instance();
final wavUrl1TestData = LibSourceTestData(
source: UrlSource(wavUrl1),
duration: const Duration(milliseconds: 451),
);
final specialCharUrlTestData = LibSourceTestData(
source: UrlSource(wavUrl3),
duration: const Duration(milliseconds: 451),
);
final mp3Url1TestData = LibSourceTestData(
source: UrlSource(mp3Url1),
duration: const Duration(minutes: 3, seconds: 30, milliseconds: 77),
isVBR: true,
);
final m3u8UrlTestData = LibSourceTestData(
source: UrlSource(m3u8StreamUrl),
duration: null,
);
final mpgaUrlTestData = LibSourceTestData(
source: UrlSource(mpgaStreamUrl),
duration: null,
);
final wavAsset1TestData = LibSourceTestData(
source: AssetSource(wavAsset1),
duration: const Duration(milliseconds: 451),
);
final wavAsset2TestData = LibSourceTestData(
source: AssetSource(wavAsset2),
duration: const Duration(seconds: 1, milliseconds: 068),
);
final invalidAssetTestData = LibSourceTestData(
source: AssetSource(invalidAsset),
duration: null,
);
final specialCharAssetTestData = LibSourceTestData(
source: AssetSource(specialCharAsset),
duration: const Duration(milliseconds: 451),
);
final noExtensionAssetTestData = LibSourceTestData(
source: AssetSource(noExtensionAsset),
duration: const Duration(milliseconds: 451),
);
final nonExistentUrlTestData = LibSourceTestData(
source: UrlSource('non_existent.txt'),
duration: null,
);
// Some sources are commented which are considered redundant
Future<List<LibSourceTestData>> getAudioTestDataList() async {
return [
if (_features.hasUrlSource) wavUrl1TestData,
/*if (_features.hasUrlSource)
LibSourceTestData(
source: UrlSource(wavUrl2),
duration: const Duration(seconds: 1, milliseconds: 068),
),*/
if (_features.hasUrlSource) mp3Url1TestData,
/*if (_features.hasUrlSource)
LibSourceTestData(
source: UrlSource(mp3Url2),
duration: const Duration(minutes: 1, seconds: 34, milliseconds: 119),
),*/
if (_features.hasUrlSource && _features.hasPlaylistSourceType)
m3u8UrlTestData,
if (_features.hasUrlSource) mpgaUrlTestData,
if (_features.hasAssetSource) wavAsset2TestData,
/*if (_features.hasAssetSource)
LibSourceTestData(
source: AssetSource(mp3Asset),
duration: const Duration(minutes: 1, seconds: 34, milliseconds: 119),
),*/
if (_features.hasBytesSource)
LibSourceTestData(
source: BytesSource(await AudioCache.instance.loadAsBytes(wavAsset2)),
duration: const Duration(seconds: 1, milliseconds: 068),
),
/*if (_features.hasBytesSource)
LibSourceTestData(
source: BytesSource(await readBytes(Uri.parse(mp3Url1))),
duration: const Duration(minutes: 3, seconds: 30, milliseconds: 76),
),*/
];
}
|
audioplayers/packages/audioplayers/example/integration_test/lib/lib_source_test_data.dart/0
|
{'file_path': 'audioplayers/packages/audioplayers/example/integration_test/lib/lib_source_test_data.dart', 'repo_id': 'audioplayers', 'token_count': 1218}
|
import 'package:flutter/material.dart';
class Tabs extends StatelessWidget {
final List<TabData> tabs;
const Tabs({
required this.tabs,
super.key,
});
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: tabs.length,
child: Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TabBar(
labelColor: Colors.black,
tabs: tabs
.map(
(tData) => Tab(
key: tData.key != null ? Key(tData.key!) : null,
text: tData.label,
),
)
.toList(),
),
Expanded(
child: TabBarView(
children: tabs.map((tab) => tab.content).toList(),
),
),
],
),
),
);
}
}
class TabData {
final String? key;
final String label;
final Widget content;
TabData({
required this.label,
required this.content,
this.key,
});
}
|
audioplayers/packages/audioplayers/example/lib/components/tabs.dart/0
|
{'file_path': 'audioplayers/packages/audioplayers/example/lib/components/tabs.dart', 'repo_id': 'audioplayers', 'token_count': 599}
|
import 'package:audioplayers/audioplayers.dart';
import 'package:audioplayers_platform_interface/audioplayers_platform_interface.dart';
import 'package:flutter_test/flutter_test.dart';
import 'fake_audioplayers_platform.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late FakeAudioplayersPlatform platform;
setUp(() {
platform = FakeAudioplayersPlatform();
AudioplayersPlatformInterface.instance = platform;
});
Future<AudioPlayer> createPlayer({
required String playerId,
}) async {
final player = AudioPlayer(playerId: playerId);
// Avoid unpredictable position updates
player.positionUpdater = null;
expect(player.source, null);
await player.creatingCompleter.future;
expect(platform.popCall().method, 'create');
expect(platform.popLastCall().method, 'getEventStream');
return player;
}
group('AudioPlayer Methods', () {
late AudioPlayer player;
setUp(() async {
player = await createPlayer(playerId: 'p1');
expect(player.source, null);
});
test('#setSource and #dispose', () async {
await player.setSource(UrlSource('internet.com/file.mp3'));
expect(platform.popLastCall().method, 'setSourceUrl');
expect(player.source, isInstanceOf<UrlSource>());
final urlSource = player.source as UrlSource?;
expect(urlSource?.url, 'internet.com/file.mp3');
await player.dispose();
expect(platform.popCall().method, 'stop');
expect(platform.popCall().method, 'release');
expect(platform.popLastCall().method, 'dispose');
expect(player.source, null);
});
test('#play', () async {
await player.play(UrlSource('internet.com/file.mp3'));
final call1 = platform.popCall();
expect(call1.method, 'setSourceUrl');
expect(call1.value, 'internet.com/file.mp3');
expect(platform.popLastCall().method, 'resume');
});
test('multiple players', () async {
final player2 = await createPlayer(playerId: 'p2');
await player.play(UrlSource('internet.com/file.mp3'));
final call1 = platform.popCall();
expect(call1.id, 'p1');
expect(call1.method, 'setSourceUrl');
expect(call1.value, 'internet.com/file.mp3');
expect(platform.popLastCall().method, 'resume');
platform.clear();
await player.play(UrlSource('internet.com/file.mp3'));
expect(platform.popCall().id, 'p1');
platform.clear();
await player2.play(UrlSource('internet.com/file.mp3'));
expect(platform.popCall().id, 'p2');
platform.clear();
await player.play(UrlSource('internet.com/file.mp3'));
expect(platform.popCall().id, 'p1');
});
test('#resume, #pause and #duration', () async {
await player.setSourceUrl('assets/audio.mp3');
expect(platform.popLastCall().method, 'setSourceUrl');
await player.resume();
expect(platform.popLastCall().method, 'resume');
await player.getDuration();
expect(platform.popLastCall().method, 'getDuration');
await player.pause();
expect(platform.popLastCall().method, 'pause');
});
test('set #volume, #balance, #playbackRate, #playerMode, #releaseMode',
() async {
await player.setVolume(0.1);
expect(player.volume, 0.1);
expect(platform.popLastCall().method, 'setVolume');
await player.setBalance(0.2);
expect(player.balance, 0.2);
expect(platform.popLastCall().method, 'setBalance');
await player.setPlaybackRate(0.3);
expect(player.playbackRate, 0.3);
expect(platform.popLastCall().method, 'setPlaybackRate');
await player.setPlayerMode(PlayerMode.lowLatency);
expect(player.mode, PlayerMode.lowLatency);
expect(platform.popLastCall().method, 'setPlayerMode');
await player.setReleaseMode(ReleaseMode.loop);
expect(player.releaseMode, ReleaseMode.loop);
expect(platform.popLastCall().method, 'setReleaseMode');
});
});
group('AudioPlayers Events', () {
late AudioPlayer player;
setUp(() async {
player = await createPlayer(playerId: 'p1');
expect(player.source, null);
});
test('event stream', () async {
final audioEvents = <AudioEvent>[
const AudioEvent(
eventType: AudioEventType.duration,
duration: Duration(milliseconds: 98765),
),
const AudioEvent(
eventType: AudioEventType.log,
logMessage: 'someLogMessage',
),
const AudioEvent(
eventType: AudioEventType.complete,
),
const AudioEvent(
eventType: AudioEventType.seekComplete,
),
];
expect(
player.eventStream,
emitsInOrder(audioEvents),
);
audioEvents.forEach(platform.eventStreamControllers['p1']!.add);
await platform.eventStreamControllers['p1']!.close();
});
});
}
|
audioplayers/packages/audioplayers/test/audioplayers_test.dart/0
|
{'file_path': 'audioplayers/packages/audioplayers/test/audioplayers_test.dart', 'repo_id': 'audioplayers', 'token_count': 1876}
|
include: package:flame_lint/analysis_options.yaml
|
audioplayers/packages/audioplayers_linux/analysis_options.yaml/0
|
{'file_path': 'audioplayers/packages/audioplayers_linux/analysis_options.yaml', 'repo_id': 'audioplayers', 'token_count': 16}
|
import 'package:flutter/foundation.dart';
enum AudioEventType {
log,
duration,
seekComplete,
complete,
prepared,
}
/// Event emitted from the platform implementation.
@immutable
class AudioEvent {
/// Creates an instance of [AudioEvent].
///
/// The [eventType] argument is required.
const AudioEvent({
required this.eventType,
this.duration,
this.logMessage,
this.isPrepared,
});
/// The type of the event.
final AudioEventType eventType;
/// Duration of the audio.
final Duration? duration;
/// Log message in the player scope.
final String? logMessage;
/// Whether the source is prepared to be played.
final bool? isPrepared;
@override
bool operator ==(Object other) {
return identical(this, other) ||
other is AudioEvent &&
runtimeType == other.runtimeType &&
eventType == other.eventType &&
duration == other.duration &&
logMessage == other.logMessage &&
isPrepared == other.isPrepared;
}
@override
int get hashCode => Object.hash(
eventType,
duration,
logMessage,
isPrepared,
);
@override
String toString() {
return 'AudioEvent('
'eventType: $eventType, '
'duration: $duration, '
'logMessage: $logMessage, '
'isPrepared: $isPrepared'
')';
}
}
|
audioplayers/packages/audioplayers_platform_interface/lib/src/api/audio_event.dart/0
|
{'file_path': 'audioplayers/packages/audioplayers_platform_interface/lib/src/api/audio_event.dart', 'repo_id': 'audioplayers', 'token_count': 521}
|
name: audioplayers_workspace
environment:
sdk: '>=3.0.0 <4.0.0'
dev_dependencies:
melos: ^3.0.0
|
audioplayers/pubspec.yaml/0
|
{'file_path': 'audioplayers/pubspec.yaml', 'repo_id': 'audioplayers', 'token_count': 52}
|
import 'package:benckmark/_bloc_lib/_shared/entitity.dart';
import 'package:benckmark/_bloc_lib/_shared/item.entity.dart';
class ItemsState extends EntityState<Item> {
ItemsState([List<Item> items = const []]) : super(items);
}
|
benchmarks/state_managers/lib/_bloc_lib/_blocs/items/items.state.dart/0
|
{'file_path': 'benchmarks/state_managers/lib/_bloc_lib/_blocs/items/items.state.dart', 'repo_id': 'benchmarks', 'token_count': 80}
|
import 'package:benckmark/item.dart';
import 'package:meta/meta.dart';
@immutable
class AppState {
final List<Item> items;
AppState({
this.items,
});
AppState.initialState() : items = sampleItems;
}
class AddItemAction {
Item payload;
AddItemAction({
this.payload,
});
}
AppState appReducer(AppState state, dynamic action) {
return AppState(items: itemsReducer(state.items, action));
}
List<Item> itemsReducer(List<Item> state, dynamic action) {
if (action is AddItemAction) {
return [...state, action.payload];
}
return state;
}
|
benchmarks/state_managers/lib/_redux/_store.dart/0
|
{'file_path': 'benchmarks/state_managers/lib/_redux/_store.dart', 'repo_id': 'benchmarks', 'token_count': 200}
|
import 'package:flame/animation.dart';
import 'package:flame/flame.dart';
import 'package:flame/position.dart';
import 'package:flutter/widgets.dart' hide Animation;
import '../data.dart';
import 'gui_commons.dart';
class CoinWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _CoinWidgetState();
}
}
class _CoinWidgetState extends State<CoinWidget> {
@override
Widget build(BuildContext context) {
final animation = Animation.sequenced('coin.png', 10, textureWidth: 16.0, textureHeight: 16.0);
final coinCounter = Data.hasData ? Data.buy.coins.toString() : '';
return Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(coinCounter, style: text),
Flame.util.animationAsWidget(Position(32.0, 32.0), animation),
],
),
constraints: const BoxConstraints(maxWidth: 100.0, maxHeight: 32.0),
);
}
}
|
bgug/lib/screens/coin_widget.dart/0
|
{'file_path': 'bgug/lib/screens/coin_widget.dart', 'repo_id': 'bgug', 'token_count': 358}
|
import 'dart:io';
import 'package:flame_gamepad/flame_gamepad.dart';
enum TutorialStatus { NOT_SHOWING, PAGE_0_REGULAR, PAGE_0_GAMEPAD, PAGE_1 }
Future<TutorialStatus> getFirstTutorialStatus() async {
final gamepad = Platform.isAndroid && await FlameGamepad.isGamepadConnected;
return gamepad ? TutorialStatus.PAGE_0_GAMEPAD : TutorialStatus.PAGE_0_REGULAR;
}
TutorialStatus getNextStatus(TutorialStatus current) {
if (current == TutorialStatus.PAGE_0_GAMEPAD || current == TutorialStatus.PAGE_0_REGULAR) {
return TutorialStatus.PAGE_1;
} else {
return TutorialStatus.NOT_SHOWING;
}
}
|
bgug/lib/tutorial_status.dart/0
|
{'file_path': 'bgug/lib/tutorial_status.dart', 'repo_id': 'bgug', 'token_count': 213}
|
import 'dart:ffi' as ffi;
import 'dart:typed_data';
import '../bitmap.dart';
import '../ffi.dart';
import 'operation.dart';
// *** FFi C++ bindings ***
const _nativeFunctionName = "brightness";
typedef _NativeSideFunction = ffi.Void Function(
ffi.Pointer<ffi.Uint8>,
ffi.Int32,
ffi.Int32,
);
typedef _DartSideFunction = void Function(
ffi.Pointer<ffi.Uint8> startingPointer,
int bitmapLength,
int brightnessAmount,
);
_DartSideFunction _brightnessFFIImpl = bitmapFFILib
.lookup<ffi.NativeFunction<_NativeSideFunction>>(_nativeFunctionName)
.asFunction();
/// Changes brightness of [sourceBmp] accordingly to [brightnessRate] .
///
/// [brightnessRate] Can be between -1.0 and 1.0. 0.0 does nothing;
class BitmapBrightness implements BitmapOperation {
BitmapBrightness(double brightnessFactor)
: brightnessFactor = brightnessFactor.clamp(-1.0, 1.0);
final double brightnessFactor;
@override
Bitmap applyTo(Bitmap bitmap) {
final Bitmap copy = bitmap.cloneHeadless();
_brightnessCore(copy.content, brightnessFactor);
return copy;
}
void _brightnessCore(Uint8List sourceBmp, double brightnessRate) {
assert(brightnessRate >= -1.0 && brightnessRate <= 1.0);
if (brightnessRate == 0.0) {
return;
}
final brightnessAmount = (brightnessRate * 255).floor();
final size = sourceBmp.length;
// start native execution
FFIImpl((startingPointer, pointerList) {
_brightnessFFIImpl(startingPointer, size, brightnessAmount);
}).execute(sourceBmp);
}
}
|
bitmap/lib/src/operation/brightness.dart/0
|
{'file_path': 'bitmap/lib/src/operation/brightness.dart', 'repo_id': 'bitmap', 'token_count': 546}
|
name: angular_bloc
on:
push:
paths:
- "packages/angular_bloc/**"
- ".github/workflows/angular_bloc.yaml"
pull_request:
paths:
- "packages/angular_bloc/**"
- ".github/workflows/angular_bloc.yaml"
jobs:
build:
defaults:
run:
working-directory: packages/angular_bloc
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: dart-lang/setup-dart@v1
with:
sdk: 2.19.0
- name: Install Dependencies
run: dart pub get
- name: Format
run: dart format --set-exit-if-changed .
- name: Analyze
run: dart analyze --fatal-infos --fatal-warnings .
- name: Run tests
run: dart run build_runner test --fail-on-severe
pana:
defaults:
run:
working-directory: packages/angular_bloc
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: subosito/flutter-action@v2.8.0
- name: Install Dependencies
run: |
flutter packages get
flutter pub global activate pana
sudo apt-get install webp
- name: Verify Pub Score
run: ../../tool/verify_pub_score.sh 110
|
bloc/.github/workflows/angular_bloc.yaml/0
|
{'file_path': 'bloc/.github/workflows/angular_bloc.yaml', 'repo_id': 'bloc', 'token_count': 556}
|
name: cubit
description: Generate a new Cubit in Dart. Built for the bloc state management library.
version: 0.2.0
repository: https://github.com/felangel/bloc/tree/master/bricks/cubit
environment:
mason: ">=0.1.0-dev.32 <0.1.0"
vars:
name:
type: string
description: The name of the cubit class.
default: counter
prompt: Please enter the cubit name.
style:
type: enum
description: The style of cubit generated.
default: basic
prompt: What is the cubit style?
values:
- basic
- equatable
- freezed
|
bloc/bricks/cubit/brick.yaml/0
|
{'file_path': 'bloc/bricks/cubit/brick.yaml', 'repo_id': 'bloc', 'token_count': 215}
|
import 'dart:io';
import 'package:mason/mason.dart';
import 'package:path/path.dart' as path;
enum BlocType {
bloc,
cubit,
hydrated_bloc,
hydrated_cubit,
replay_bloc,
replay_cubit,
}
Future<void> run(HookContext context) async {
final blocType = _blocTypeFromContext(context);
final progress = context.logger.progress('Making brick ${blocType.name}');
final name = context.vars['name'] as String;
final style = context.vars['style'] as String;
final brick = Brick.version(name: blocType.name, version: '^0.2.0');
final generator = await MasonGenerator.fromBrick(brick);
final blocDirectoryName = blocType.toDirectoryName();
final directory = Directory(
path.join(Directory.current.path, name.snakeCase, blocDirectoryName),
);
final target = DirectoryGeneratorTarget(directory);
var vars = <String, dynamic>{'name': name, 'style': style};
await generator.hooks.preGen(vars: vars, onVarsChanged: (v) => vars = v);
final files = await generator.generate(
target,
vars: vars,
logger: context.logger,
fileConflictResolution: FileConflictResolution.overwrite,
);
await generator.hooks.postGen(vars: vars);
final blocExport =
'./${blocDirectoryName}/${name.snakeCase}_${blocDirectoryName}.dart';
progress.complete('Made brick ${blocType.name}');
context.logger.logFilesGenerated(files.length);
context.vars = {
...context.vars,
'bloc_export': blocExport,
'is_bloc': blocDirectoryName == 'bloc',
};
}
BlocType _blocTypeFromContext(HookContext context) {
final type = context.vars['type'] as String;
switch (type) {
case 'cubit':
return BlocType.cubit;
case 'hydrated_bloc':
return BlocType.hydrated_bloc;
case 'hydrated_cubit':
return BlocType.hydrated_cubit;
case 'replay_bloc':
return BlocType.replay_bloc;
case 'replay_cubit':
return BlocType.replay_cubit;
case 'bloc':
default:
return BlocType.bloc;
}
}
extension on BlocType {
String toDirectoryName() {
switch (this) {
case BlocType.bloc:
case BlocType.hydrated_bloc:
case BlocType.replay_bloc:
return 'bloc';
case BlocType.cubit:
case BlocType.hydrated_cubit:
case BlocType.replay_cubit:
return 'cubit';
}
}
}
extension on Logger {
void logFilesGenerated(int fileCount) {
if (fileCount == 1) {
this
..info(
'${lightGreen.wrap('\u2713')} '
'Generated $fileCount file:',
)
..flush((message) => info(darkGray.wrap(message)));
} else {
this
..info(
'${lightGreen.wrap('\u2713')} '
'Generated $fileCount file(s):',
)
..flush((message) => info(darkGray.wrap(message)));
}
}
}
|
bloc/bricks/flutter_bloc_feature/hooks/pre_gen.dart/0
|
{'file_path': 'bloc/bricks/flutter_bloc_feature/hooks/pre_gen.dart', 'repo_id': 'bloc', 'token_count': 1148}
|
import 'package:mason/mason.dart';
Future<void> run(HookContext context) async {
final style = context.vars['style'];
context.vars = {
...context.vars,
'use_basic': style == 'basic',
'use_equatable': style == 'equatable',
'use_freezed': style == 'freezed',
};
}
|
bloc/bricks/hydrated_cubit/hooks/pre_gen.dart/0
|
{'file_path': 'bloc/bricks/hydrated_cubit/hooks/pre_gen.dart', 'repo_id': 'bloc', 'token_count': 111}
|
name: replay_cubit
description: Generate a new ReplayCubit in Dart. Built for the bloc state management library.
version: 0.2.0
repository: https://github.com/felangel/bloc/tree/master/bricks/replay_cubit
environment:
mason: ">=0.1.0-dev.32 <0.1.0"
vars:
name:
type: string
description: The name of the cubit class.
default: counter
prompt: Please enter the cubit name.
style:
type: enum
description: The style of cubit generated.
default: basic
prompt: What is the cubit style?
values:
- basic
- equatable
- freezed
|
bloc/bricks/replay_cubit/brick.yaml/0
|
{'file_path': 'bloc/bricks/replay_cubit/brick.yaml', 'repo_id': 'bloc', 'token_count': 222}
|
import 'package:bloc/bloc.dart';
import 'package:ngdart/angular.dart';
import 'package:angular_counter/app_component.template.dart' as ng;
class SimpleBlocObserver extends BlocObserver {
const SimpleBlocObserver();
@override
void onEvent(Bloc bloc, Object? event) {
print(event);
super.onEvent(bloc, event);
}
@override
void onTransition(Bloc bloc, Transition transition) {
print(transition);
super.onTransition(bloc, transition);
}
@override
void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
print(error);
super.onError(bloc, error, stackTrace);
}
}
void main() {
Bloc.observer = const SimpleBlocObserver();
runApp(ng.AppComponentNgFactory);
}
|
bloc/examples/angular_counter/web/main.dart/0
|
{'file_path': 'bloc/examples/angular_counter/web/main.dart', 'repo_id': 'bloc', 'token_count': 259}
|
part of 'ticker_bloc.dart';
/// {@template ticker_event}
/// Base class for all [TickerEvent]s which are
/// handled by the [TickerBloc].
/// {@endtemplate}
abstract class TickerEvent extends Equatable {
/// {@macro ticker_event}
const TickerEvent();
@override
List<Object> get props => [];
}
/// {@template ticker_started}
/// Signifies to the [TickerBloc] that the user
/// has requested to start the [Ticker].
/// {@endtemplate}
class TickerStarted extends TickerEvent {
/// {@macro ticker_started}
const TickerStarted();
}
class _TickerTicked extends TickerEvent {
const _TickerTicked(this.tick);
/// The current tick count.
final int tick;
@override
List<Object> get props => [tick];
}
|
bloc/examples/flutter_bloc_with_stream/lib/bloc/ticker_event.dart/0
|
{'file_path': 'bloc/examples/flutter_bloc_with_stream/lib/bloc/ticker_event.dart', 'repo_id': 'bloc', 'token_count': 239}
|
import 'dart:async';
import 'dart:math';
import 'package:flutter_complex_list/complex_list/complex_list.dart';
class Repository {
final _random = Random();
int _randomRange(int min, int max) => min + _random.nextInt(max - min);
Future<List<Item>> fetchItems() async {
await Future<void>.delayed(Duration(seconds: _randomRange(1, 5)));
return List.of(_generateItemsList(10));
}
List<Item> _generateItemsList(int length) {
return List.generate(
length,
(index) => Item(id: '$index', value: 'Item $index'),
);
}
Future<void> deleteItem(String id) async {
await Future<void>.delayed(Duration(seconds: _randomRange(1, 5)));
}
}
|
bloc/examples/flutter_complex_list/lib/repository.dart/0
|
{'file_path': 'bloc/examples/flutter_complex_list/lib/repository.dart', 'repo_id': 'bloc', 'token_count': 249}
|
import 'package:flutter/material.dart';
import 'package:flutter_counter/main.dart' as app;
import 'package:flutter_test/flutter_test.dart';
void main() {
group('CounterApp', () {
testWidgets('renders correct AppBar text', (tester) async {
await tester.pumpApp();
expect(find.text('Counter'), findsOneWidget);
});
testWidgets('renders correct initial count', (tester) async {
await tester.pumpApp();
expect(find.text('0'), findsOneWidget);
});
testWidgets('tapping increment button updates the count', (tester) async {
await tester.pumpApp();
await tester.incrementCounter();
expect(find.text('1'), findsOneWidget);
await tester.incrementCounter();
expect(find.text('2'), findsOneWidget);
await tester.incrementCounter();
expect(find.text('3'), findsOneWidget);
});
testWidgets('tapping decrement button updates the count', (tester) async {
await tester.pumpApp();
await tester.decrementCounter();
expect(find.text('-1'), findsOneWidget);
await tester.decrementCounter();
expect(find.text('-2'), findsOneWidget);
await tester.decrementCounter();
expect(find.text('-3'), findsOneWidget);
});
});
}
extension on WidgetTester {
Future<void> pumpApp() async {
app.main();
await pumpAndSettle();
}
Future<void> incrementCounter() async {
await tap(
find.byKey(const Key('counterView_increment_floatingActionButton')),
);
await pump();
}
Future<void> decrementCounter() async {
await tap(
find.byKey(const Key('counterView_decrement_floatingActionButton')),
);
await pump();
}
}
|
bloc/examples/flutter_counter/integration_test/app_test.dart/0
|
{'file_path': 'bloc/examples/flutter_counter/integration_test/app_test.dart', 'repo_id': 'bloc', 'token_count': 633}
|
part of 'login_cubit.dart';
class LoginState extends Equatable {
const LoginState({
this.email = const Email.pure(),
this.password = const Password.pure(),
this.status = FormzStatus.pure,
this.errorMessage,
});
final Email email;
final Password password;
final FormzStatus status;
final String? errorMessage;
@override
List<Object> get props => [email, password, status];
LoginState copyWith({
Email? email,
Password? password,
FormzStatus? status,
String? errorMessage,
}) {
return LoginState(
email: email ?? this.email,
password: password ?? this.password,
status: status ?? this.status,
errorMessage: errorMessage ?? this.errorMessage,
);
}
}
|
bloc/examples/flutter_firebase_login/lib/login/cubit/login_state.dart/0
|
{'file_path': 'bloc/examples/flutter_firebase_login/lib/login/cubit/login_state.dart', 'repo_id': 'bloc', 'token_count': 252}
|
export 'user.dart';
|
bloc/examples/flutter_firebase_login/packages/authentication_repository/lib/src/models/models.dart/0
|
{'file_path': 'bloc/examples/flutter_firebase_login/packages/authentication_repository/lib/src/models/models.dart', 'repo_id': 'bloc', 'token_count': 8}
|
// ignore_for_file: prefer_const_constructors, must_be_immutable
import 'package:authentication_repository/authentication_repository.dart';
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_firebase_login/app/app.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class MockAuthenticationRepository extends Mock
implements AuthenticationRepository {}
class MockUser extends Mock implements User {}
void main() {
group('AppBloc', () {
final user = MockUser();
late AuthenticationRepository authenticationRepository;
setUp(() {
authenticationRepository = MockAuthenticationRepository();
when(() => authenticationRepository.user).thenAnswer(
(_) => Stream.empty(),
);
when(
() => authenticationRepository.currentUser,
).thenReturn(User.empty);
});
test('initial state is unauthenticated when user is empty', () {
expect(
AppBloc(authenticationRepository: authenticationRepository).state,
AppState.unauthenticated(),
);
});
group('UserChanged', () {
blocTest<AppBloc, AppState>(
'emits authenticated when user is not empty',
setUp: () {
when(() => user.isNotEmpty).thenReturn(true);
when(() => authenticationRepository.user).thenAnswer(
(_) => Stream.value(user),
);
},
build: () => AppBloc(
authenticationRepository: authenticationRepository,
),
seed: AppState.unauthenticated,
expect: () => [AppState.authenticated(user)],
);
blocTest<AppBloc, AppState>(
'emits unauthenticated when user is empty',
setUp: () {
when(() => authenticationRepository.user).thenAnswer(
(_) => Stream.value(User.empty),
);
},
build: () => AppBloc(
authenticationRepository: authenticationRepository,
),
expect: () => [AppState.unauthenticated()],
);
});
group('LogoutRequested', () {
blocTest<AppBloc, AppState>(
'invokes logOut',
setUp: () {
when(
() => authenticationRepository.logOut(),
).thenAnswer((_) async {});
},
build: () => AppBloc(
authenticationRepository: authenticationRepository,
),
act: (bloc) => bloc.add(AppLogoutRequested()),
verify: (_) {
verify(() => authenticationRepository.logOut()).called(1);
},
);
});
});
}
|
bloc/examples/flutter_firebase_login/test/app/bloc/app_bloc_test.dart/0
|
{'file_path': 'bloc/examples/flutter_firebase_login/test/app/bloc/app_bloc_test.dart', 'repo_id': 'bloc', 'token_count': 1046}
|
const getJobs = '''
query GetJobs() {
jobs {
id,
title,
locationNames,
isFeatured
}
}
''';
|
bloc/examples/flutter_graphql_jobs/lib/api/queries/get_jobs.dart/0
|
{'file_path': 'bloc/examples/flutter_graphql_jobs/lib/api/queries/get_jobs.dart', 'repo_id': 'bloc', 'token_count': 66}
|
import 'package:flutter/material.dart';
import 'package:flutter_infinite_list/posts/posts.dart';
class PostListItem extends StatelessWidget {
const PostListItem({super.key, required this.post});
final Post post;
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Material(
child: ListTile(
leading: Text('${post.id}', style: textTheme.bodySmall),
title: Text(post.title),
isThreeLine: true,
subtitle: Text(post.body),
dense: true,
),
);
}
}
|
bloc/examples/flutter_infinite_list/lib/posts/widgets/post_list_item.dart/0
|
{'file_path': 'bloc/examples/flutter_infinite_list/lib/posts/widgets/post_list_item.dart', 'repo_id': 'bloc', 'token_count': 218}
|
part of 'login_bloc.dart';
abstract class LoginEvent extends Equatable {
const LoginEvent();
@override
List<Object> get props => [];
}
class LoginUsernameChanged extends LoginEvent {
const LoginUsernameChanged(this.username);
final String username;
@override
List<Object> get props => [username];
}
class LoginPasswordChanged extends LoginEvent {
const LoginPasswordChanged(this.password);
final String password;
@override
List<Object> get props => [password];
}
class LoginSubmitted extends LoginEvent {
const LoginSubmitted();
}
|
bloc/examples/flutter_login/lib/login/bloc/login_event.dart/0
|
{'file_path': 'bloc/examples/flutter_login/lib/login/bloc/login_event.dart', 'repo_id': 'bloc', 'token_count': 159}
|
include: package:very_good_analysis/analysis_options.3.1.0.yaml
linter:
rules:
public_member_api_docs: false
|
bloc/examples/flutter_login/packages/authentication_repository/analysis_options.yaml/0
|
{'file_path': 'bloc/examples/flutter_login/packages/authentication_repository/analysis_options.yaml', 'repo_id': 'bloc', 'token_count': 44}
|
// ignore_for_file: prefer_const_constructors
import 'package:flutter_login/login/login.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
const passwordString = 'mock-password';
group('Password', () {
group('constructors', () {
test('pure creates correct instance', () {
final password = Password.pure();
expect(password.value, '');
expect(password.pure, true);
});
test('dirty creates correct instance', () {
final password = Password.dirty(passwordString);
expect(password.value, passwordString);
expect(password.pure, false);
});
});
group('validator', () {
test('returns empty error when password is empty', () {
expect(
Password.dirty().error,
PasswordValidationError.empty,
);
});
test('is valid when password is not empty', () {
expect(
Password.dirty(passwordString).error,
isNull,
);
});
});
});
}
|
bloc/examples/flutter_login/test/login/models/password_test.dart/0
|
{'file_path': 'bloc/examples/flutter_login/test/login/models/password_test.dart', 'repo_id': 'bloc', 'token_count': 408}
|
export 'cart.dart';
|
bloc/examples/flutter_shopping_cart/lib/cart/models/models.dart/0
|
{'file_path': 'bloc/examples/flutter_shopping_cart/lib/cart/models/models.dart', 'repo_id': 'bloc', 'token_count': 8}
|
import 'dart:developer';
import 'package:bloc/bloc.dart';
class AppBlocObserver extends BlocObserver {
const AppBlocObserver();
@override
void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) {
super.onChange(bloc, change);
log('onChange(${bloc.runtimeType}, $change)');
}
@override
void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) {
log('onError(${bloc.runtimeType}, $error, $stackTrace)');
super.onError(bloc, error, stackTrace);
}
}
|
bloc/examples/flutter_todos/lib/app/app_bloc_observer.dart/0
|
{'file_path': 'bloc/examples/flutter_todos/lib/app/app_bloc_observer.dart', 'repo_id': 'bloc', 'token_count': 191}
|
import 'package:flutter/widgets.dart';
import 'package:flutter_todos/bootstrap.dart';
import 'package:local_storage_todos_api/local_storage_todos_api.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final todosApi = LocalStorageTodosApi(
plugin: await SharedPreferences.getInstance(),
);
bootstrap(todosApi: todosApi);
}
|
bloc/examples/flutter_todos/lib/main_development.dart/0
|
{'file_path': 'bloc/examples/flutter_todos/lib/main_development.dart', 'repo_id': 'bloc', 'token_count': 134}
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_todos/edit_todo/view/edit_todo_page.dart';
import 'package:flutter_todos/l10n/l10n.dart';
import 'package:flutter_todos/todos_overview/todos_overview.dart';
import 'package:todos_repository/todos_repository.dart';
class TodosOverviewPage extends StatelessWidget {
const TodosOverviewPage({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => TodosOverviewBloc(
todosRepository: context.read<TodosRepository>(),
)..add(const TodosOverviewSubscriptionRequested()),
child: const TodosOverviewView(),
);
}
}
class TodosOverviewView extends StatelessWidget {
const TodosOverviewView({super.key});
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return Scaffold(
appBar: AppBar(
title: Text(l10n.todosOverviewAppBarTitle),
actions: const [
TodosOverviewFilterButton(),
TodosOverviewOptionsButton(),
],
),
body: MultiBlocListener(
listeners: [
BlocListener<TodosOverviewBloc, TodosOverviewState>(
listenWhen: (previous, current) =>
previous.status != current.status,
listener: (context, state) {
if (state.status == TodosOverviewStatus.failure) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(
content: Text(l10n.todosOverviewErrorSnackbarText),
),
);
}
},
),
BlocListener<TodosOverviewBloc, TodosOverviewState>(
listenWhen: (previous, current) =>
previous.lastDeletedTodo != current.lastDeletedTodo &&
current.lastDeletedTodo != null,
listener: (context, state) {
final deletedTodo = state.lastDeletedTodo!;
final messenger = ScaffoldMessenger.of(context);
messenger
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(
content: Text(
l10n.todosOverviewTodoDeletedSnackbarText(
deletedTodo.title,
),
),
action: SnackBarAction(
label: l10n.todosOverviewUndoDeletionButtonText,
onPressed: () {
messenger.hideCurrentSnackBar();
context
.read<TodosOverviewBloc>()
.add(const TodosOverviewUndoDeletionRequested());
},
),
),
);
},
),
],
child: BlocBuilder<TodosOverviewBloc, TodosOverviewState>(
builder: (context, state) {
if (state.todos.isEmpty) {
if (state.status == TodosOverviewStatus.loading) {
return const Center(child: CupertinoActivityIndicator());
} else if (state.status != TodosOverviewStatus.success) {
return const SizedBox();
} else {
return Center(
child: Text(
l10n.todosOverviewEmptyText,
style: Theme.of(context).textTheme.bodySmall,
),
);
}
}
return CupertinoScrollbar(
child: ListView(
children: [
for (final todo in state.filteredTodos)
TodoListTile(
todo: todo,
onToggleCompleted: (isCompleted) {
context.read<TodosOverviewBloc>().add(
TodosOverviewTodoCompletionToggled(
todo: todo,
isCompleted: isCompleted,
),
);
},
onDismissed: (_) {
context
.read<TodosOverviewBloc>()
.add(TodosOverviewTodoDeleted(todo));
},
onTap: () {
Navigator.of(context).push(
EditTodoPage.route(initialTodo: todo),
);
},
),
],
),
);
},
),
),
);
}
}
|
bloc/examples/flutter_todos/lib/todos_overview/view/todos_overview_page.dart/0
|
{'file_path': 'bloc/examples/flutter_todos/lib/todos_overview/view/todos_overview_page.dart', 'repo_id': 'bloc', 'token_count': 2763}
|
/// The type definition for a JSON-serializable [Map].
typedef JsonMap = Map<String, dynamic>;
|
bloc/examples/flutter_todos/packages/todos_api/lib/src/models/json_map.dart/0
|
{'file_path': 'bloc/examples/flutter_todos/packages/todos_api/lib/src/models/json_map.dart', 'repo_id': 'bloc', 'token_count': 29}
|
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_todos/stats/stats.dart';
import 'package:mockingjay/mockingjay.dart';
import 'package:todos_repository/todos_repository.dart';
import '../../helpers/helpers.dart';
class MockStatsBloc extends MockBloc<StatsEvent, StatsState>
implements StatsBloc {}
void main() {
group('StatsPage', () {
late TodosRepository todosRepository;
setUp(() {
todosRepository = MockTodosRepository();
when(todosRepository.getTodos).thenAnswer((_) => const Stream.empty());
});
testWidgets('renders StatsView', (tester) async {
await tester.pumpApp(
const StatsPage(),
todosRepository: todosRepository,
);
expect(find.byType(StatsView), findsOneWidget);
});
testWidgets(
'subscribes to todos from repository on initialization',
(tester) async {
await tester.pumpApp(
const StatsPage(),
todosRepository: todosRepository,
);
verify(() => todosRepository.getTodos()).called(1);
},
);
});
group('StatsView', () {
const completedTodosListTileKey = Key('statsView_completedTodos_listTile');
const activeTodosListTileKey = Key('statsView_activeTodos_listTile');
late MockNavigator navigator;
late StatsBloc statsBloc;
setUp(() {
navigator = MockNavigator();
when(() => navigator.push(any())).thenAnswer((_) async => null);
statsBloc = MockStatsBloc();
when(() => statsBloc.state).thenReturn(
const StatsState(status: StatsStatus.success),
);
});
Widget buildSubject() {
return MockNavigatorProvider(
navigator: navigator,
child: BlocProvider.value(
value: statsBloc,
child: const StatsView(),
),
);
}
testWidgets(
'renders AppBar with title text',
(tester) async {
await tester.pumpApp(buildSubject());
expect(find.byType(AppBar), findsOneWidget);
expect(
find.descendant(
of: find.byType(AppBar),
matching: find.text(l10n.statsAppBarTitle),
),
findsOneWidget,
);
},
);
testWidgets(
'renders completed todos ListTile '
'with correct icon, label and value',
(tester) async {
const completedTodos = 42;
when(() => statsBloc.state).thenReturn(
const StatsState(
status: StatsStatus.success,
completedTodos: completedTodos,
),
);
await tester.pumpApp(buildSubject());
expect(find.byKey(completedTodosListTileKey), findsOneWidget);
expect(
find.descendant(
of: find.byKey(completedTodosListTileKey),
matching: find.text(l10n.statsCompletedTodoCountLabel),
),
findsOneWidget,
);
expect(
find.descendant(
of: find.byKey(completedTodosListTileKey),
matching: find.byIcon(Icons.check_rounded),
),
findsOneWidget,
);
expect(
find.descendant(
of: find.byKey(completedTodosListTileKey),
matching: find.text('$completedTodos'),
),
findsOneWidget,
);
},
);
testWidgets(
'renders active todos ListTile '
'with correct icon, label and value',
(tester) async {
const activeTodos = 42;
when(() => statsBloc.state).thenReturn(
const StatsState(
status: StatsStatus.success,
activeTodos: activeTodos,
),
);
await tester.pumpApp(buildSubject());
expect(find.byKey(activeTodosListTileKey), findsOneWidget);
expect(
find.descendant(
of: find.byKey(activeTodosListTileKey),
matching: find.text(l10n.statsActiveTodoCountLabel),
),
findsOneWidget,
);
expect(
find.descendant(
of: find.byKey(activeTodosListTileKey),
matching: find.byIcon(Icons.radio_button_unchecked_rounded),
),
findsOneWidget,
);
expect(
find.descendant(
of: find.byKey(activeTodosListTileKey),
matching: find.text('$activeTodos'),
),
findsOneWidget,
);
},
);
});
}
|
bloc/examples/flutter_todos/test/stats/view/stats_page_test.dart/0
|
{'file_path': 'bloc/examples/flutter_todos/test/stats/view/stats_page_test.dart', 'repo_id': 'bloc', 'token_count': 2130}
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'weather.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Temperature _$TemperatureFromJson(Map<String, dynamic> json) => $checkedCreate(
'Temperature',
json,
($checkedConvert) {
final val = Temperature(
value: $checkedConvert('value', (v) => (v as num).toDouble()),
);
return val;
},
);
Map<String, dynamic> _$TemperatureToJson(Temperature instance) =>
<String, dynamic>{
'value': instance.value,
};
Weather _$WeatherFromJson(Map<String, dynamic> json) => $checkedCreate(
'Weather',
json,
($checkedConvert) {
final val = Weather(
condition: $checkedConvert(
'condition', (v) => $enumDecode(_$WeatherConditionEnumMap, v)),
lastUpdated: $checkedConvert(
'last_updated', (v) => DateTime.parse(v as String)),
location: $checkedConvert('location', (v) => v as String),
temperature: $checkedConvert('temperature',
(v) => Temperature.fromJson(v as Map<String, dynamic>)),
);
return val;
},
fieldKeyMap: const {'lastUpdated': 'last_updated'},
);
Map<String, dynamic> _$WeatherToJson(Weather instance) => <String, dynamic>{
'condition': _$WeatherConditionEnumMap[instance.condition]!,
'last_updated': instance.lastUpdated.toIso8601String(),
'location': instance.location,
'temperature': instance.temperature.toJson(),
};
const _$WeatherConditionEnumMap = {
WeatherCondition.clear: 'clear',
WeatherCondition.rainy: 'rainy',
WeatherCondition.cloudy: 'cloudy',
WeatherCondition.snowy: 'snowy',
WeatherCondition.unknown: 'unknown',
};
|
bloc/examples/flutter_weather/lib/weather/models/weather.g.dart/0
|
{'file_path': 'bloc/examples/flutter_weather/lib/weather/models/weather.g.dart', 'repo_id': 'bloc', 'token_count': 702}
|
library open_meteo_api;
export 'src/models/models.dart';
export 'src/open_meteo_api_client.dart';
|
bloc/examples/flutter_weather/packages/open_meteo_api/lib/open_meteo_api.dart/0
|
{'file_path': 'bloc/examples/flutter_weather/packages/open_meteo_api/lib/open_meteo_api.dart', 'repo_id': 'bloc', 'token_count': 41}
|
import 'dart:async';
import 'package:open_meteo_api/open_meteo_api.dart' hide Weather;
import 'package:weather_repository/weather_repository.dart';
class WeatherRepository {
WeatherRepository({OpenMeteoApiClient? weatherApiClient})
: _weatherApiClient = weatherApiClient ?? OpenMeteoApiClient();
final OpenMeteoApiClient _weatherApiClient;
Future<Weather> getWeather(String city) async {
final location = await _weatherApiClient.locationSearch(city);
final weather = await _weatherApiClient.getWeather(
latitude: location.latitude,
longitude: location.longitude,
);
return Weather(
temperature: weather.temperature,
location: location.name,
condition: weather.weatherCode.toInt().toCondition,
);
}
}
extension on int {
WeatherCondition get toCondition {
switch (this) {
case 0:
return WeatherCondition.clear;
case 1:
case 2:
case 3:
case 45:
case 48:
return WeatherCondition.cloudy;
case 51:
case 53:
case 55:
case 56:
case 57:
case 61:
case 63:
case 65:
case 66:
case 67:
case 80:
case 81:
case 82:
case 95:
case 96:
case 99:
return WeatherCondition.rainy;
case 71:
case 73:
case 75:
case 77:
case 85:
case 86:
return WeatherCondition.snowy;
default:
return WeatherCondition.unknown;
}
}
}
|
bloc/examples/flutter_weather/packages/weather_repository/lib/src/weather_repository.dart/0
|
{'file_path': 'bloc/examples/flutter_weather/packages/weather_repository/lib/src/weather_repository.dart', 'repo_id': 'bloc', 'token_count': 636}
|
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_weather/weather/weather.dart';
void main() {
group('WeatherError', () {
testWidgets('renders correct text and icon', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: WeatherError(),
),
),
);
expect(find.text('Something went wrong!'), findsOneWidget);
expect(find.text('🙈'), findsOneWidget);
});
});
}
|
bloc/examples/flutter_weather/test/weather/widgets/weather_error_test.dart/0
|
{'file_path': 'bloc/examples/flutter_weather/test/weather/widgets/weather_error_test.dart', 'repo_id': 'bloc', 'token_count': 235}
|
import 'package:common_github_search/common_github_search.dart';
import 'package:ngdart/angular.dart';
@Component(
selector: 'search-result-item',
templateUrl: 'search_result_item_component.html',
)
class SearchResultItemComponent {
@Input()
late SearchResultItem item;
}
|
bloc/examples/github_search/angular_github_search/lib/src/search_form/search_body/search_results/search_result_item/search_result_item_component.dart/0
|
{'file_path': 'bloc/examples/github_search/angular_github_search/lib/src/search_form/search_body/search_results/search_result_item/search_result_item_component.dart', 'repo_id': 'bloc', 'token_count': 90}
|
import 'dart:async';
import 'dart:convert';
import 'package:common_github_search/common_github_search.dart';
import 'package:http/http.dart' as http;
class GithubClient {
GithubClient({
http.Client? httpClient,
this.baseUrl = 'https://api.github.com/search/repositories?q=',
}) : httpClient = httpClient ?? http.Client();
final String baseUrl;
final http.Client httpClient;
Future<SearchResult> search(String term) async {
final response = await httpClient.get(Uri.parse('$baseUrl$term'));
final results = json.decode(response.body) as Map<String, dynamic>;
if (response.statusCode == 200) {
return SearchResult.fromJson(results);
} else {
throw SearchResultError.fromJson(results);
}
}
}
|
bloc/examples/github_search/common_github_search/lib/src/github_client.dart/0
|
{'file_path': 'bloc/examples/github_search/common_github_search/lib/src/github_client.dart', 'repo_id': 'bloc', 'token_count': 261}
|
import 'package:bloc/bloc.dart';
import 'package:test/test.dart';
abstract class CounterEvent {}
class Increment extends CounterEvent {
@override
bool operator ==(Object value) {
if (identical(this, value)) return true;
return value is Increment;
}
@override
int get hashCode => 0;
}
const delay = Duration(milliseconds: 30);
Future<void> wait() => Future.delayed(delay);
Future<void> tick() => Future.delayed(Duration.zero);
class CounterBloc extends Bloc<CounterEvent, int> {
CounterBloc({EventTransformer<Increment>? incrementTransformer}) : super(0) {
on<Increment>(
(event, emit) {
onCalls.add(event);
return Future<void>.delayed(delay, () {
if (emit.isDone) return;
onEmitCalls.add(event);
emit(state + 1);
});
},
transformer: incrementTransformer,
);
}
final onCalls = <CounterEvent>[];
final onEmitCalls = <CounterEvent>[];
}
void main() {
late EventTransformer transformer;
setUp(() {
transformer = Bloc.transformer;
});
tearDown(() {
Bloc.transformer = transformer;
});
test('processes events concurrently by default', () async {
final states = <int>[];
final bloc = CounterBloc()
..stream.listen(states.add)
..add(Increment())
..add(Increment())
..add(Increment());
await tick();
expect(
bloc.onCalls,
equals([Increment(), Increment(), Increment()]),
);
await wait();
expect(
bloc.onEmitCalls,
equals([Increment(), Increment(), Increment()]),
);
expect(states, equals([1, 2, 3]));
await bloc.close();
expect(
bloc.onCalls,
equals([Increment(), Increment(), Increment()]),
);
expect(
bloc.onEmitCalls,
equals([Increment(), Increment(), Increment()]),
);
expect(states, equals([1, 2, 3]));
});
test(
'when processing events concurrently '
'all subscriptions are canceled on close', () async {
final states = <int>[];
final bloc = CounterBloc()
..stream.listen(states.add)
..add(Increment())
..add(Increment())
..add(Increment());
await tick();
expect(
bloc.onCalls,
equals([Increment(), Increment(), Increment()]),
);
await bloc.close();
expect(
bloc.onCalls,
equals([Increment(), Increment(), Increment()]),
);
expect(bloc.onEmitCalls, isEmpty);
expect(states, isEmpty);
});
test(
'processes events sequentially when '
'transformer is overridden.', () async {
EventTransformer<Increment> incrementTransformer() {
return (events, mapper) => events.asyncExpand(mapper);
}
final states = <int>[];
final bloc = CounterBloc(incrementTransformer: incrementTransformer())
..stream.listen(states.add)
..add(Increment())
..add(Increment())
..add(Increment());
await tick();
expect(
bloc.onCalls,
equals([Increment()]),
);
await wait();
expect(
bloc.onEmitCalls,
equals([Increment()]),
);
expect(states, equals([1]));
await tick();
expect(
bloc.onCalls,
equals([Increment(), Increment()]),
);
await wait();
expect(
bloc.onEmitCalls,
equals([Increment(), Increment()]),
);
expect(states, equals([1, 2]));
await tick();
expect(
bloc.onCalls,
equals([Increment(), Increment(), Increment()]),
);
await wait();
expect(
bloc.onEmitCalls,
equals([Increment(), Increment(), Increment()]),
);
expect(states, equals([1, 2, 3]));
await bloc.close();
expect(
bloc.onCalls,
equals([Increment(), Increment(), Increment()]),
);
expect(
bloc.onEmitCalls,
equals([Increment(), Increment(), Increment()]),
);
expect(states, equals([1, 2, 3]));
});
test(
'processes events sequentially when '
'Bloc.transformer is overridden.', () async {
Bloc.transformer = (events, mapper) => events.asyncExpand<dynamic>(mapper);
final states = <int>[];
final bloc = CounterBloc()
..stream.listen(states.add)
..add(Increment())
..add(Increment())
..add(Increment());
await tick();
expect(
bloc.onCalls,
equals([Increment()]),
);
await wait();
expect(
bloc.onEmitCalls,
equals([Increment()]),
);
expect(states, equals([1]));
await tick();
expect(
bloc.onCalls,
equals([Increment(), Increment()]),
);
await wait();
expect(
bloc.onEmitCalls,
equals([Increment(), Increment()]),
);
expect(states, equals([1, 2]));
await tick();
expect(
bloc.onCalls,
equals([
Increment(),
Increment(),
Increment(),
]),
);
await wait();
expect(
bloc.onEmitCalls,
equals([Increment(), Increment(), Increment()]),
);
expect(states, equals([1, 2, 3]));
await bloc.close();
expect(
bloc.onCalls,
equals([Increment(), Increment(), Increment()]),
);
expect(
bloc.onEmitCalls,
equals([Increment(), Increment(), Increment()]),
);
expect(states, equals([1, 2, 3]));
});
}
|
bloc/packages/bloc/test/bloc_event_transformer_test.dart/0
|
{'file_path': 'bloc/packages/bloc/test/bloc_event_transformer_test.dart', 'repo_id': 'bloc', 'token_count': 2183}
|
import 'package:bloc/bloc.dart';
import '../counter/counter_bloc.dart';
class CounterErrorBloc extends Bloc<CounterEvent, int> {
CounterErrorBloc() : super(0) {
on<CounterEvent>(_onCounterEvent);
}
void _onCounterEvent(CounterEvent event, Emitter<int> emit) {
switch (event) {
case CounterEvent.decrement:
return emit(state - 1);
case CounterEvent.increment:
throw Error();
}
}
}
|
bloc/packages/bloc/test/blocs/counter/counter_error_bloc.dart/0
|
{'file_path': 'bloc/packages/bloc/test/blocs/counter/counter_error_bloc.dart', 'repo_id': 'bloc', 'token_count': 168}
|
export 'counter_cubit.dart';
export 'fake_async_cubit.dart';
export 'seeded_cubit.dart';
|
bloc/packages/bloc/test/cubits/cubits.dart/0
|
{'file_path': 'bloc/packages/bloc/test/cubits/cubits.dart', 'repo_id': 'bloc', 'token_count': 40}
|
import 'package:bloc/bloc.dart';
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
}
|
bloc/packages/bloc_test/test/cubits/counter_cubit.dart/0
|
{'file_path': 'bloc/packages/bloc_test/test/cubits/counter_cubit.dart', 'repo_id': 'bloc', 'token_count': 52}
|
import 'package:bloc_tools/src/command_runner.dart';
import 'package:universal_io/io.dart';
Future<void> main(List<String> args) async {
await _flushThenExit(await BlocToolsCommandRunner().run(args));
}
/// Flushes the stdout and stderr streams, then exits the program with the given
/// status code.
///
/// This returns a Future that will never complete, since the program will have
/// exited already. This is useful to prevent Future chains from proceeding
/// after you've decided to exit.
Future<void> _flushThenExit(int status) {
return Future.wait<void>([stdout.close(), stderr.close()]).then<void>(
(_) => exit(status),
);
}
|
bloc/packages/bloc_tools/bin/bloc.dart/0
|
{'file_path': 'bloc/packages/bloc_tools/bin/bloc.dart', 'repo_id': 'bloc', 'token_count': 194}
|
analyzer:
strong-mode:
implicit-casts: false
implicit-dynamic: false
errors:
close_sinks: ignore
linter:
rules:
- public_member_api_docs
- annotate_overrides
- avoid_empty_else
- avoid_function_literals_in_foreach_calls
- avoid_init_to_null
- avoid_null_checks_in_equality_operators
- avoid_redundant_argument_values
- avoid_relative_lib_imports
- avoid_renaming_method_parameters
- avoid_return_types_on_setters
- avoid_returning_null
- avoid_types_as_parameter_names
- avoid_unused_constructor_parameters
- await_only_futures
- camel_case_types
- cancel_subscriptions
- cascade_invocations
- comment_references
- constant_identifier_names
- control_flow_in_finally
- directives_ordering
- empty_catches
- empty_constructor_bodies
- empty_statements
- hash_and_equals
- implementation_imports
- iterable_contains_unrelated_type
- library_names
- library_prefixes
- list_remove_unrelated_type
- lines_longer_than_80_chars
- no_adjacent_strings_in_list
- no_duplicate_case_values
- non_constant_identifier_names
- null_closures
- omit_local_variable_types
- only_throw_errors
- overridden_fields
- package_api_docs
- package_names
- package_prefixed_library_names
- prefer_adjacent_string_concatenation
- prefer_collection_literals
- prefer_conditional_assignment
- prefer_const_constructors
- prefer_contains
- prefer_equal_for_default_values
- prefer_final_fields
- prefer_initializing_formals
- prefer_interpolation_to_compose_strings
- prefer_is_empty
- prefer_is_not_empty
- prefer_single_quotes
- prefer_typing_uninitialized_variables
- recursive_getters
- slash_for_doc_comments
- sort_constructors_first
- test_types_in_equals
- throw_in_finally
- type_init_formals
- unawaited_futures
- unnecessary_brace_in_string_interps
- unnecessary_const
- unnecessary_getters_setters
- unnecessary_lambdas
- unnecessary_new
- unnecessary_null_aware_assignments
- unnecessary_statements
- unnecessary_this
- unrelated_type_equality_checks
- use_rethrow_when_possible
- valid_regexps
|
bloc/packages/flutter_bloc/example/analysis_options.yaml/0
|
{'file_path': 'bloc/packages/flutter_bloc/example/analysis_options.yaml', 'repo_id': 'bloc', 'token_count': 895}
|
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/src/bloc_provider.dart';
import 'package:provider/provider.dart';
import 'package:provider/single_child_widget.dart';
/// {@template multi_bloc_provider}
/// Merges multiple [BlocProvider] widgets into one widget tree.
///
/// [MultiBlocProvider] improves the readability and eliminates the need
/// to nest multiple [BlocProvider]s.
///
/// By using [MultiBlocProvider] we can go from:
///
/// ```dart
/// BlocProvider<BlocA>(
/// create: (BuildContext context) => BlocA(),
/// child: BlocProvider<BlocB>(
/// create: (BuildContext context) => BlocB(),
/// child: BlocProvider<BlocC>(
/// create: (BuildContext context) => BlocC(),
/// child: ChildA(),
/// )
/// )
/// )
/// ```
///
/// to:
///
/// ```dart
/// MultiBlocProvider(
/// providers: [
/// BlocProvider<BlocA>(
/// create: (BuildContext context) => BlocA(),
/// ),
/// BlocProvider<BlocB>(
/// create: (BuildContext context) => BlocB(),
/// ),
/// BlocProvider<BlocC>(
/// create: (BuildContext context) => BlocC(),
/// ),
/// ],
/// child: ChildA(),
/// )
/// ```
///
/// [MultiBlocProvider] converts the [BlocProvider] list into a tree of nested
/// [BlocProvider] widgets.
/// As a result, the only advantage of using [MultiBlocProvider] is improved
/// readability due to the reduction in nesting and boilerplate.
/// {@endtemplate}
class MultiBlocProvider extends MultiProvider {
/// {@macro multi_bloc_provider}
MultiBlocProvider({
Key? key,
required List<SingleChildWidget> providers,
required Widget child,
}) : super(key: key, providers: providers, child: child);
}
|
bloc/packages/flutter_bloc/lib/src/multi_bloc_provider.dart/0
|
{'file_path': 'bloc/packages/flutter_bloc/lib/src/multi_bloc_provider.dart', 'repo_id': 'bloc', 'token_count': 604}
|
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: implicit_dynamic_parameter
part of 'freezed_cubit.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_$_Question _$$_QuestionFromJson(Map<String, dynamic> json) => _$_Question(
id: json['id'] as int?,
question: json['question'] as String?,
);
Map<String, dynamic> _$$_QuestionToJson(_$_Question instance) =>
<String, dynamic>{
'id': instance.id,
'question': instance.question,
};
_$_QTree _$$_QTreeFromJson(Map<String, dynamic> json) => _$_QTree(
question: json['question'] == null
? null
: Question.fromJson(json['question'] as Map<String, dynamic>),
left: json['left'] == null
? null
: Tree.fromJson(json['left'] as Map<String, dynamic>),
right: json['right'] == null
? null
: Tree.fromJson(json['right'] as Map<String, dynamic>),
);
Map<String, dynamic> _$$_QTreeToJson(_$_QTree instance) => <String, dynamic>{
'question': instance.question,
'left': instance.left,
'right': instance.right,
};
|
bloc/packages/hydrated_bloc/test/cubits/freezed_cubit.g.dart/0
|
{'file_path': 'bloc/packages/hydrated_bloc/test/cubits/freezed_cubit.g.dart', 'repo_id': 'bloc', 'token_count': 468}
|
name: example
description: A new Flutter project.
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.19.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
bloc: ^8.1.1
flutter_bloc: ^8.1.2
replay_bloc: ^0.2.2
flutter:
uses-material-design: true
|
bloc/packages/replay_bloc/example/pubspec.yaml/0
|
{'file_path': 'bloc/packages/replay_bloc/example/pubspec.yaml', 'repo_id': 'bloc', 'token_count': 124}
|
import 'dart:async';
import 'package:replay_bloc/replay_bloc.dart';
import 'package:test/test.dart';
import 'blocs/counter_bloc.dart';
void main() {
group('ReplayBloc', () {
group('initial state', () {
test('is correct', () {
expect(CounterBloc().state, 0);
});
});
group('canUndo', () {
test('is false when no state changes have occurred', () async {
final bloc = CounterBloc();
expect(bloc.canUndo, isFalse);
await bloc.close();
});
test('is true when a single state change has occurred', () async {
final bloc = CounterBloc()..add(Increment());
await Future<void>.delayed(Duration.zero);
expect(bloc.canUndo, isTrue);
await bloc.close();
});
test('is false when undos have been exhausted', () async {
final bloc = CounterBloc()..add(Increment());
await Future<void>.delayed(Duration.zero, bloc.undo);
expect(bloc.canUndo, isFalse);
await bloc.close();
});
});
group('canRedo', () {
test('is false when no state changes have occurred', () async {
final bloc = CounterBloc();
expect(bloc.canRedo, isFalse);
await bloc.close();
});
test('is true when a single undo has occurred', () async {
final bloc = CounterBloc()..add(Increment());
await Future<void>.delayed(Duration.zero, bloc.undo);
expect(bloc.canRedo, isTrue);
await bloc.close();
});
test('is false when redos have been exhausted', () async {
final bloc = CounterBloc()..add(Increment());
await Future<void>.delayed(Duration.zero, bloc.undo);
await Future<void>.delayed(Duration.zero, bloc.redo);
expect(bloc.canRedo, isFalse);
await bloc.close();
});
});
group('clearHistory', () {
test('clears history and redos on new bloc', () async {
final bloc = CounterBloc()..clearHistory();
expect(bloc.canRedo, isFalse);
expect(bloc.canUndo, isFalse);
await bloc.close();
});
});
group('undo', () {
test('does nothing when no state changes have occurred', () async {
final states = <int>[];
final bloc = CounterBloc();
final subscription = bloc.stream.listen(states.add);
bloc.undo();
await bloc.close();
await subscription.cancel();
expect(states, isEmpty);
});
test('does nothing when limit is 0', () async {
final states = <int>[];
final bloc = CounterBloc(limit: 0);
final subscription = bloc.stream.listen(states.add);
bloc.add(Increment());
await Future<void>.delayed(Duration.zero);
bloc.undo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1]);
});
test('skips states filtered out by shouldReplay at undo time', () async {
final states = <int>[];
final bloc = CounterBloc(shouldReplayCallback: (i) => !i.isEven);
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc
..undo()
..undo()
..undo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 3, 1]);
});
test(
'doesn\'t skip states that would be filtered out by shouldReplay '
'at transition time but not at undo time', () async {
var replayEvens = false;
final states = <int>[];
final bloc = CounterBloc(
shouldReplayCallback: (i) => !i.isEven || replayEvens,
);
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
replayEvens = true;
bloc
..undo()
..undo()
..undo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 3, 2, 1, 0]);
});
test('loses history outside of limit', () async {
final states = <int>[];
final bloc = CounterBloc(limit: 1);
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc
..undo()
..undo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 1]);
});
test('reverts to initial state', () async {
final states = <int>[];
final bloc = CounterBloc();
final subscription = bloc.stream.listen(states.add);
bloc.add(Increment());
await Future<void>.delayed(Duration.zero);
bloc.undo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 0]);
});
test('reverts to previous state with multiple state changes ', () async {
final states = <int>[];
final bloc = CounterBloc();
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc.undo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 1]);
});
test('triggers onEvent', () async {
final onEventCalls = <ReplayEvent>[];
final bloc = CounterBloc(onEventCallback: onEventCalls.add)
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc.undo();
expect(onEventCalls.length, 2);
expect(onEventCalls.last.toString(), 'Undo');
});
test('triggers onTransition', () async {
final onTransitionCalls = <Transition<ReplayEvent, int>>[];
final bloc = CounterBloc(onTransitionCallback: onTransitionCalls.add)
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc.undo();
expect(onTransitionCalls.length, 2);
expect(
onTransitionCalls.last.toString(),
'Transition { currentState: 1, event: Undo, nextState: 0 }',
);
});
});
group('redo', () {
test('does nothing when no state changes have occurred', () async {
final states = <int>[];
final bloc = CounterBloc();
final subscription = bloc.stream.listen(states.add);
bloc.redo();
await bloc.close();
await subscription.cancel();
expect(states, isEmpty);
});
test('does nothing when no undos have occurred', () async {
final states = <int>[];
final bloc = CounterBloc();
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc.redo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2]);
});
test('works when one undo has occurred', () async {
final states = <int>[];
final bloc = CounterBloc();
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc
..undo()
..redo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 1, 2]);
});
test('triggers onEvent', () async {
final onEventCalls = <ReplayEvent>[];
final bloc = CounterBloc(onEventCallback: onEventCalls.add)
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc
..undo()
..redo();
await bloc.close();
expect(onEventCalls.length, 3);
expect(onEventCalls.last.toString(), 'Redo');
});
test('triggers onTransition', () async {
final onTransitionCalls = <Transition<ReplayEvent, int>>[];
final bloc = CounterBloc(onTransitionCallback: onTransitionCalls.add)
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc
..undo()
..redo();
await bloc.close();
expect(onTransitionCalls.length, 3);
expect(
onTransitionCalls.last.toString(),
'Transition { currentState: 0, event: Redo, nextState: 1 }',
);
});
test('does nothing when undos have been exhausted', () async {
final states = <int>[];
final bloc = CounterBloc();
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc
..undo()
..redo()
..redo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 1, 2]);
});
test(
'does nothing when undos has occurred '
'followed by a new state change', () async {
final states = <int>[];
final bloc = CounterBloc();
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc
..undo()
..add(Decrement());
await Future<void>.delayed(Duration.zero);
bloc.redo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 1, 0]);
});
test(
'redo does not redo states which were'
' filtered out by shouldReplay at undo time', () async {
final states = <int>[];
final bloc = CounterBloc(shouldReplayCallback: (i) => !i.isEven);
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc
..undo()
..undo()
..undo()
..redo()
..redo()
..redo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 3, 1, 3]);
});
test(
'redo does not redo states which were'
' filtered out by shouldReplay at transition time', () async {
var replayEvens = false;
final states = <int>[];
final bloc = CounterBloc(
shouldReplayCallback: (i) => !i.isEven || replayEvens,
);
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc
..undo()
..undo()
..undo();
replayEvens = true;
bloc
..redo()
..redo()
..redo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 3, 1, 2, 3]);
});
});
});
group('ReplayBlocMixin', () {
group('initial state', () {
test('is correct', () {
expect(CounterBlocMixin().state, 0);
});
});
group('canUndo', () {
test('is false when no state changes have occurred', () async {
final bloc = CounterBlocMixin();
expect(bloc.canUndo, isFalse);
await bloc.close();
});
test('is true when a single state change has occurred', () async {
final bloc = CounterBlocMixin()..add(Increment());
await Future<void>.delayed(Duration.zero);
expect(bloc.canUndo, isTrue);
await bloc.close();
});
test('is false when undos have been exhausted', () async {
final bloc = CounterBlocMixin()..add(Increment());
await Future<void>.delayed(Duration.zero, bloc.undo);
expect(bloc.canUndo, isFalse);
await bloc.close();
});
});
group('canRedo', () {
test('is false when no state changes have occurred', () async {
final bloc = CounterBlocMixin();
expect(bloc.canRedo, isFalse);
await bloc.close();
});
test('is true when a single undo has occurred', () async {
final bloc = CounterBlocMixin()..add(Increment());
await Future<void>.delayed(Duration.zero, bloc.undo);
expect(bloc.canRedo, isTrue);
await bloc.close();
});
test('is false when redos have been exhausted', () async {
final bloc = CounterBlocMixin()..add(Increment());
await Future<void>.delayed(Duration.zero, bloc.undo);
await Future<void>.delayed(Duration.zero, bloc.redo);
expect(bloc.canRedo, isFalse);
await bloc.close();
});
});
group('clearHistory', () {
test('clears history and redos on new bloc', () async {
final bloc = CounterBlocMixin()..clearHistory();
expect(bloc.canRedo, isFalse);
expect(bloc.canUndo, isFalse);
await bloc.close();
});
});
group('undo', () {
test('does nothing when no state changes have occurred', () async {
final states = <int>[];
final bloc = CounterBlocMixin();
final subscription = bloc.stream.listen(states.add);
bloc.undo();
await bloc.close();
await subscription.cancel();
expect(states, isEmpty);
});
test('does nothing when limit is 0', () async {
final states = <int>[];
final bloc = CounterBlocMixin(limit: 0);
final subscription = bloc.stream.listen(states.add);
bloc.add(Increment());
await Future<void>.delayed(Duration.zero);
bloc.undo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1]);
});
test('loses history outside of limit', () async {
final states = <int>[];
final bloc = CounterBlocMixin(limit: 1);
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc
..undo()
..undo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 1]);
});
test('reverts to initial state', () async {
final states = <int>[];
final bloc = CounterBlocMixin();
final subscription = bloc.stream.listen(states.add);
bloc.add(Increment());
await Future<void>.delayed(Duration.zero);
bloc.undo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 0]);
});
test('reverts to previous state with multiple state changes ', () async {
final states = <int>[];
final bloc = CounterBlocMixin();
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc.undo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 1]);
});
});
group('redo', () {
test('does nothing when no state changes have occurred', () async {
final states = <int>[];
final bloc = CounterBlocMixin();
final subscription = bloc.stream.listen(states.add);
bloc.redo();
await bloc.close();
await subscription.cancel();
expect(states, isEmpty);
});
test('does nothing when no undos have occurred', () async {
final states = <int>[];
final bloc = CounterBlocMixin();
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc.redo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2]);
});
test('works when one undo has occurred', () async {
final states = <int>[];
final bloc = CounterBlocMixin();
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc
..undo()
..redo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 1, 2]);
});
test('does nothing when undos have been exhausted', () async {
final states = <int>[];
final bloc = CounterBlocMixin();
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc
..undo()
..redo()
..redo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 1, 2]);
});
test(
'does nothing when undos has occurred '
'followed by a new state change', () async {
final states = <int>[];
final bloc = CounterBlocMixin();
final subscription = bloc.stream.listen(states.add);
bloc
..add(Increment())
..add(Increment());
await Future<void>.delayed(Duration.zero);
bloc
..undo()
..add(Decrement());
await Future<void>.delayed(Duration.zero);
bloc.redo();
await bloc.close();
await subscription.cancel();
expect(states, const <int>[1, 2, 1, 0]);
});
});
});
}
|
bloc/packages/replay_bloc/test/replay_bloc_test.dart/0
|
{'file_path': 'bloc/packages/replay_bloc/test/replay_bloc_test.dart', 'repo_id': 'bloc', 'token_count': 7976}
|
import 'dart:async';
import 'package:bloc_sample/src/user.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:shared_preferences/shared_preferences.dart';
abstract class HomeRepository {
FutureOr<int> fetch();
FutureOr<void> increment();
FutureOr<void> decrement();
}
class HomeRepositoryImpl implements HomeRepository {
final User _user;
final SharedPreferences _sharedPreferences;
String get _storageKey => 'data_${_user.id.toRadixString(36)}';
HomeRepositoryImpl({
@required User user,
@required SharedPreferences sharedPreferences,
}) : _user = user,
_sharedPreferences = sharedPreferences;
@override
FutureOr<int> fetch() async {
await Future<void>.delayed(const Duration(milliseconds: 500));
return _sharedPreferences.getInt(_storageKey) ?? 0;
}
@override
FutureOr<void> increment() async {
final data = await fetch();
await Future<void>.delayed(const Duration(milliseconds: 500));
await _sharedPreferences.setInt(_storageKey, data + 1);
}
@override
FutureOr<void> decrement() async {
final data = await fetch();
await Future<void>.delayed(const Duration(milliseconds: 500));
await _sharedPreferences.setInt(_storageKey, data - 1);
}
}
class HomeRepositoryStub implements HomeRepository {
int _data = 0;
@override
FutureOr<int> fetch() => _data;
@override
FutureOr<void> increment() => _data++;
@override
FutureOr<void> decrement() => _data--;
}
|
bloc_didchangedependencies/lib/src/home_repository.dart/0
|
{'file_path': 'bloc_didchangedependencies/lib/src/home_repository.dart', 'repo_id': 'bloc_didchangedependencies', 'token_count': 498}
|
enum VisibilityFilter { all, active, completed }
|
bloc_todos/lib/filtered_todos/models/visibility_filter.dart/0
|
{'file_path': 'bloc_todos/lib/filtered_todos/models/visibility_filter.dart', 'repo_id': 'bloc_todos', 'token_count': 12}
|
export 'bloc/stats_bloc.dart';
export 'stats_page.dart';
|
bloc_todos/lib/stats/stats.dart/0
|
{'file_path': 'bloc_todos/lib/stats/stats.dart', 'repo_id': 'bloc_todos', 'token_count': 24}
|
import 'package:bloc/bloc.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
class TodosBlocDelegate extends HydratedBlocDelegate {
TodosBlocDelegate(HydratedStorage storage) : super(storage);
@override
void onEvent(Bloc bloc, Object event) {
super.onEvent(bloc, event);
print('${bloc.runtimeType} $event');
}
@override
void onError(Bloc bloc, Object error, StackTrace stackTrace) {
super.onError(bloc, error, stackTrace);
print('${bloc.runtimeType} $error $stackTrace');
}
@override
void onTransition(Bloc bloc, Transition transition) {
super.onTransition(bloc, transition);
print('${bloc.runtimeType} $transition');
}
}
|
bloc_todos/lib/todos_bloc_delegate.dart/0
|
{'file_path': 'bloc_todos/lib/todos_bloc_delegate.dart', 'repo_id': 'bloc_todos', 'token_count': 248}
|
include: package:pedantic/analysis_options.yaml
analyzer:
exclude:
- "**/*.g.dart"
strong-mode:
implicit-casts: false
implicit-dynamic: false
errors:
todo: error
include_file_not_found: ignore
linter:
rules:
- public_member_api_docs
- annotate_overrides
- avoid_empty_else
- avoid_function_literals_in_foreach_calls
- avoid_init_to_null
- avoid_null_checks_in_equality_operators
- avoid_relative_lib_imports
- avoid_renaming_method_parameters
- avoid_return_types_on_setters
- avoid_returning_null
- avoid_types_as_parameter_names
- avoid_unused_constructor_parameters
- await_only_futures
- camel_case_types
- cancel_subscriptions
- cascade_invocations
- comment_references
- constant_identifier_names
- control_flow_in_finally
- directives_ordering
- empty_catches
- empty_constructor_bodies
- empty_statements
- hash_and_equals
- implementation_imports
- invariant_booleans
- iterable_contains_unrelated_type
- library_names
- library_prefixes
- list_remove_unrelated_type
- no_adjacent_strings_in_list
- no_duplicate_case_values
- non_constant_identifier_names
- null_closures
- omit_local_variable_types
- only_throw_errors
- overridden_fields
- package_api_docs
- package_names
- package_prefixed_library_names
- prefer_adjacent_string_concatenation
- prefer_collection_literals
- prefer_conditional_assignment
- prefer_const_constructors
- prefer_contains
- prefer_equal_for_default_values
- prefer_final_fields
- prefer_initializing_formals
- prefer_interpolation_to_compose_strings
- prefer_is_empty
- prefer_is_not_empty
- prefer_single_quotes
- prefer_typing_uninitialized_variables
- recursive_getters
- slash_for_doc_comments
- test_types_in_equals
- throw_in_finally
- type_init_formals
- unawaited_futures
- unnecessary_brace_in_string_interps
- unnecessary_const
- unnecessary_getters_setters
- unnecessary_lambdas
- unnecessary_new
- unnecessary_null_aware_assignments
- unnecessary_statements
- unnecessary_this
- unrelated_type_equality_checks
- use_rethrow_when_possible
- valid_regexps
|
boundary/analysis_options.yaml/0
|
{'file_path': 'boundary/analysis_options.yaml', 'repo_id': 'boundary', 'token_count': 907}
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// 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.
part of racer;
class Tire {
Tire(World world, this._maxForwardSpeed, this._maxBackwardSpeed,
this._maxDriveForce, this._maxLateralImpulse) {
BodyDef def = new BodyDef();
def.type = BodyType.DYNAMIC;
_body = world.createBody(def);
_body.userData = "Tire";
PolygonShape polygonShape = new PolygonShape();
polygonShape.setAsBoxXY(0.5, 1.25);
Fixture fixture = _body.createFixtureFromShape(polygonShape, 1.0);
fixture.userData = this;
_currentTraction = 1.0;
}
void addGroundArea(GroundArea ga) {
// TODO: If http://dartbug.com/4210 is fixed, check the return value of add
// before calling _updateTraction().
_groundAreas.add(ga);
_updateTraction();
}
void removeGroundArea(GroundArea ga) {
if (_groundAreas.remove(ga)) {
_updateTraction();
}
}
void updateFriction() {
final Vector2 impulse = _lateralVelocity..scale(-_body.mass);
if (impulse.length > _maxLateralImpulse) {
impulse.scale(_maxLateralImpulse / impulse.length);
}
_body.applyLinearImpulse(
impulse..scale(_currentTraction), _body.worldCenter, true);
_body.applyAngularImpulse(
0.1 * _currentTraction * _body.getInertia() * (-_body.angularVelocity));
Vector2 currentForwardNormal = _forwardVelocity;
final double currentForwardSpeed = currentForwardNormal.length;
currentForwardNormal.normalize();
final double dragForceMagnitude = -2 * currentForwardSpeed;
_body.applyForce(
currentForwardNormal..scale(_currentTraction * dragForceMagnitude),
_body.worldCenter);
}
void updateDrive(int controlState) {
double desiredSpeed = 0.0;
switch (controlState & (ControlState.UP | ControlState.DOWN)) {
case ControlState.UP:
desiredSpeed = _maxForwardSpeed;
break;
case ControlState.DOWN:
desiredSpeed = _maxBackwardSpeed;
break;
default:
return;
}
Vector2 currentForwardNormal = _body.getWorldVector(new Vector2(0.0, 1.0));
final double currentSpeed = _forwardVelocity.dot(currentForwardNormal);
double force = 0.0;
if (desiredSpeed < currentSpeed) {
force = -_maxDriveForce;
} else if (desiredSpeed > currentSpeed) {
force = _maxDriveForce;
}
if (force.abs() > 0) {
_body.applyForce(currentForwardNormal..scale(_currentTraction * force),
_body.worldCenter);
}
}
void updateTurn(int controlState) {
double desiredTorque = 0.0;
switch (controlState & (ControlState.LEFT | ControlState.RIGHT)) {
case ControlState.LEFT:
desiredTorque = 15.0;
break;
case ControlState.RIGHT:
desiredTorque = -15.0;
break;
}
_body.applyTorque(desiredTorque);
}
void _updateTraction() {
if (_groundAreas.isEmpty) {
_currentTraction = 1.0;
} else {
_currentTraction = 0.0;
_groundAreas.forEach((element) {
_currentTraction = max(_currentTraction, element.frictionModifier);
});
}
}
Vector2 get _lateralVelocity {
final Vector2 currentRightNormal = _body.getWorldVector(_worldLeft);
return currentRightNormal
..scale(currentRightNormal.dot(_body.linearVelocity));
}
Vector2 get _forwardVelocity {
final Vector2 currentForwardNormal = _body.getWorldVector(_worldUp);
return currentForwardNormal
..scale(currentForwardNormal.dot(_body.linearVelocity));
}
Body _body;
final double _maxForwardSpeed;
final double _maxBackwardSpeed;
final double _maxDriveForce;
final double _maxLateralImpulse;
double _currentTraction;
final Set<GroundArea> _groundAreas = new Set<GroundArea>();
// Cached Vectors to reduce unnecessary object creation.
final Vector2 _worldLeft = new Vector2(1.0, 0.0);
final Vector2 _worldUp = new Vector2(0.0, 1.0);
}
|
box2d.dart/example/racer/tire.dart/0
|
{'file_path': 'box2d.dart/example/racer/tire.dart', 'repo_id': 'box2d.dart', 'token_count': 1595}
|
/*******************************************************************************
* Copyright (c) 2015, Daniel Murphy, Google
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
part of box2d;
/// A manifold point is a contact point belonging to a contact
/// manifold. It holds details related to the geometry and dynamics
/// of the contact points.
/// The local point usage depends on the manifold type:
/// <ul><li>e_circles: the local center of circleB</li>
/// <li>e_faceA: the local center of cirlceB or the clip point of polygonB</li>
/// <li>e_faceB: the clip point of polygonA</li></ul>
/// This structure is stored across time steps, so we keep it small.<br/>
/// Note: the impulses are used for internal caching and may not
/// provide reliable contact forces, especially for high speed collisions.
class ManifoldPoint {
/// usage depends on manifold type
final Vector2 localPoint;
/// the non-penetration impulse
double normalImpulse = 0.0;
/// the friction impulse
double tangentImpulse = 0.0;
/// uniquely identifies a contact point between two shapes
final ContactID id;
/// Blank manifold point with everything zeroed out.
ManifoldPoint()
: localPoint = new Vector2.zero(),
id = new ContactID();
/// Creates a manifold point as a copy of the given point
/// @param cp point to copy from
ManifoldPoint.copy(final ManifoldPoint cp)
: localPoint = cp.localPoint.clone(),
normalImpulse = cp.normalImpulse,
tangentImpulse = cp.tangentImpulse,
id = new ContactID.copy(cp.id);
/// Sets this manifold point form the given one
/// @param cp the point to copy from
void set(final ManifoldPoint cp) {
localPoint.setFrom(cp.localPoint);
normalImpulse = cp.normalImpulse;
tangentImpulse = cp.tangentImpulse;
id.set(cp.id);
}
}
|
box2d.dart/lib/src/collision/manifold_point.dart/0
|
{'file_path': 'box2d.dart/lib/src/collision/manifold_point.dart', 'repo_id': 'box2d.dart', 'token_count': 912}
|
/// *****************************************************************************
/// Copyright (c) 2015, Daniel Murphy, Google
/// All rights reserved.
///
/// Redistribution and use in source and binary forms, with or without modification,
/// are permitted provided that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice,
/// this list of conditions and the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
/// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
/// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
/// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
/// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
/// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
/// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
/// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
/// *****************************************************************************
part of box2d.common;
class Rot {
double s = 0.0, c = 1.0; // sin and cos
Rot();
Rot.withAngle(double angle)
: s = Math.sin(angle),
c = Math.cos(angle);
Rot setAngle(double angle) {
s = Math.sin(angle);
c = Math.cos(angle);
return this;
}
Rot set(Rot other) {
s = other.s;
c = other.c;
return this;
}
Rot setIdentity() {
s = 0.0;
c = 1.0;
return this;
}
double getSin() => s;
String toString() {
return "Rot(s:$s, c:$c)";
}
double getCos() => c;
double getAngle() => Math.atan2(s, c);
void getXAxis(Vector2 xAxis) {
xAxis.setValues(c, s);
}
void getYAxis(Vector2 yAxis) {
yAxis.setValues(-s, c);
}
Rot clone() {
Rot copy = new Rot();
copy.s = s;
copy.c = c;
return copy;
}
static void mul(Rot q, Rot r, Rot out) {
double tempc = q.c * r.c - q.s * r.s;
out.s = q.s * r.c + q.c * r.s;
out.c = tempc;
}
static void mulUnsafe(Rot q, Rot r, Rot out) {
assert(r != out);
assert(q != out);
// [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc]
// [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc]
// s = qs * rc + qc * rs
// c = qc * rc - qs * rs
out.s = q.s * r.c + q.c * r.s;
out.c = q.c * r.c - q.s * r.s;
}
static void mulTrans(Rot q, Rot r, Rot out) {
final double tempc = q.c * r.c + q.s * r.s;
out.s = q.c * r.s - q.s * r.c;
out.c = tempc;
}
static void mulTransUnsafe(Rot q, Rot r, Rot out) {
// [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc]
// [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc]
// s = qc * rs - qs * rc
// c = qc * rc + qs * rs
out.s = q.c * r.s - q.s * r.c;
out.c = q.c * r.c + q.s * r.s;
}
static void mulToOut(Rot q, Vector2 v, Vector2 out) {
double tempy = q.s * v.x + q.c * v.y;
out.x = q.c * v.x - q.s * v.y;
out.y = tempy;
}
static void mulToOutUnsafe(Rot q, Vector2 v, Vector2 out) {
out.x = q.c * v.x - q.s * v.y;
out.y = q.s * v.x + q.c * v.y;
}
static void mulTransVec2(Rot q, Vector2 v, Vector2 out) {
final double tempy = -q.s * v.x + q.c * v.y;
out.x = q.c * v.x + q.s * v.y;
out.y = tempy;
}
static void mulTransUnsafeVec2(Rot q, Vector2 v, Vector2 out) {
out.x = q.c * v.x + q.s * v.y;
out.y = -q.s * v.x + q.c * v.y;
}
}
|
box2d.dart/lib/src/common/rot.dart/0
|
{'file_path': 'box2d.dart/lib/src/common/rot.dart', 'repo_id': 'box2d.dart', 'token_count': 1612}
|
/// *****************************************************************************
/// Copyright (c) 2015, Daniel Murphy, Google
/// All rights reserved.
///
/// Redistribution and use in source and binary forms, with or without modification,
/// are permitted provided that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice,
/// this list of conditions and the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
/// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
/// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
/// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
/// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
/// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
/// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
/// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
/// *****************************************************************************
part of box2d;
//C = norm(p2 - p1) - L
//u = (p2 - p1) / norm(p2 - p1)
//Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1))
//J = [-u -cross(r1, u) u cross(r2, u)]
//K = J * invM * JT
//= invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2
/// A distance joint constrains two points on two bodies to remain at a fixed distance from each
/// other. You can view this as a massless, rigid rod.
class DistanceJoint extends Joint {
double _frequencyHz = 0.0;
double _dampingRatio = 0.0;
double _bias = 0.0;
// Solver shared
final Vector2 _localAnchorA;
final Vector2 _localAnchorB;
double _gamma = 0.0;
double _impulse = 0.0;
double _length = 0.0;
// Solver temp
int _indexA = 0;
int _indexB = 0;
final Vector2 _u = new Vector2.zero();
final Vector2 _rA = new Vector2.zero();
final Vector2 _rB = new Vector2.zero();
final Vector2 _localCenterA = new Vector2.zero();
final Vector2 _localCenterB = new Vector2.zero();
double _invMassA = 0.0;
double _invMassB = 0.0;
double _invIA = 0.0;
double _invIB = 0.0;
double _mass = 0.0;
DistanceJoint(IWorldPool argWorld, final DistanceJointDef def)
: _localAnchorA = def.localAnchorA.clone(),
_localAnchorB = def.localAnchorB.clone(),
super(argWorld, def) {
_length = def.length;
_frequencyHz = def.frequencyHz;
_dampingRatio = def.dampingRatio;
}
void getAnchorA(Vector2 argOut) {
_bodyA.getWorldPointToOut(_localAnchorA, argOut);
}
void getAnchorB(Vector2 argOut) {
_bodyB.getWorldPointToOut(_localAnchorB, argOut);
}
/// Get the reaction force given the inverse time step. Unit is N.
void getReactionForce(double inv_dt, Vector2 argOut) {
argOut.x = _impulse * _u.x * inv_dt;
argOut.y = _impulse * _u.y * inv_dt;
}
/// Get the reaction torque given the inverse time step. Unit is N*m. This is always zero for a
/// distance joint.
double getReactionTorque(double inv_dt) {
return 0.0;
}
void initVelocityConstraints(final SolverData data) {
_indexA = _bodyA._islandIndex;
_indexB = _bodyB._islandIndex;
_localCenterA.setFrom(_bodyA._sweep.localCenter);
_localCenterB.setFrom(_bodyB._sweep.localCenter);
_invMassA = _bodyA._invMass;
_invMassB = _bodyB._invMass;
_invIA = _bodyA._invI;
_invIB = _bodyB._invI;
Vector2 cA = data.positions[_indexA].c;
double aA = data.positions[_indexA].a;
Vector2 vA = data.velocities[_indexA].v;
double wA = data.velocities[_indexA].w;
Vector2 cB = data.positions[_indexB].c;
double aB = data.positions[_indexB].a;
Vector2 vB = data.velocities[_indexB].v;
double wB = data.velocities[_indexB].w;
final Rot qA = pool.popRot();
final Rot qB = pool.popRot();
qA.setAngle(aA);
qB.setAngle(aB);
// use _u as temporary variable
Rot.mulToOutUnsafe(
qA,
_u
..setFrom(_localAnchorA)
..sub(_localCenterA),
_rA);
Rot.mulToOutUnsafe(
qB,
_u
..setFrom(_localAnchorB)
..sub(_localCenterB),
_rB);
_u
..setFrom(cB)
..add(_rB)
..sub(cA)
..sub(_rA);
pool.pushRot(2);
// Handle singularity.
double length = _u.length;
if (length > Settings.linearSlop) {
_u.x *= 1.0 / length;
_u.y *= 1.0 / length;
} else {
_u.setValues(0.0, 0.0);
}
double crAu = _rA.cross(_u);
double crBu = _rB.cross(_u);
double invMass =
_invMassA + _invIA * crAu * crAu + _invMassB + _invIB * crBu * crBu;
// Compute the effective mass matrix.
_mass = invMass != 0.0 ? 1.0 / invMass : 0.0;
if (_frequencyHz > 0.0) {
double C = length - _length;
// Frequency
double omega = 2.0 * Math.pi * _frequencyHz;
// Damping coefficient
double d = 2.0 * _mass * _dampingRatio * omega;
// Spring stiffness
double k = _mass * omega * omega;
// magic formulas
double h = data.step.dt;
_gamma = h * (d + h * k);
_gamma = _gamma != 0.0 ? 1.0 / _gamma : 0.0;
_bias = C * h * k * _gamma;
invMass += _gamma;
_mass = invMass != 0.0 ? 1.0 / invMass : 0.0;
} else {
_gamma = 0.0;
_bias = 0.0;
}
if (data.step.warmStarting) {
// Scale the impulse to support a variable time step.
_impulse *= data.step.dtRatio;
Vector2 P = pool.popVec2();
P
..setFrom(_u)
..scale(_impulse);
vA.x -= _invMassA * P.x;
vA.y -= _invMassA * P.y;
wA -= _invIA * _rA.cross(P);
vB.x += _invMassB * P.x;
vB.y += _invMassB * P.y;
wB += _invIB * _rB.cross(P);
pool.pushVec2(1);
} else {
_impulse = 0.0;
}
// data.velocities[_indexA].v.set(vA);
data.velocities[_indexA].w = wA;
// data.velocities[_indexB].v.set(vB);
data.velocities[_indexB].w = wB;
}
void solveVelocityConstraints(final SolverData data) {
Vector2 vA = data.velocities[_indexA].v;
double wA = data.velocities[_indexA].w;
Vector2 vB = data.velocities[_indexB].v;
double wB = data.velocities[_indexB].w;
final Vector2 vpA = pool.popVec2();
final Vector2 vpB = pool.popVec2();
// Cdot = dot(u, v + cross(w, r))
_rA.scaleOrthogonalInto(wA, vpA);
vpA.add(vA);
_rB.scaleOrthogonalInto(wB, vpB);
vpB.add(vB);
double Cdot = _u.dot(vpB..sub(vpA));
double impulse = -_mass * (Cdot + _bias + _gamma * _impulse);
_impulse += impulse;
double Px = impulse * _u.x;
double Py = impulse * _u.y;
vA.x -= _invMassA * Px;
vA.y -= _invMassA * Py;
wA -= _invIA * (_rA.x * Py - _rA.y * Px);
vB.x += _invMassB * Px;
vB.y += _invMassB * Py;
wB += _invIB * (_rB.x * Py - _rB.y * Px);
// data.velocities[_indexA].v.set(vA);
data.velocities[_indexA].w = wA;
// data.velocities[_indexB].v.set(vB);
data.velocities[_indexB].w = wB;
pool.pushVec2(2);
}
bool solvePositionConstraints(final SolverData data) {
if (_frequencyHz > 0.0) {
return true;
}
final Rot qA = pool.popRot();
final Rot qB = pool.popRot();
final Vector2 rA = pool.popVec2();
final Vector2 rB = pool.popVec2();
final Vector2 u = pool.popVec2();
Vector2 cA = data.positions[_indexA].c;
double aA = data.positions[_indexA].a;
Vector2 cB = data.positions[_indexB].c;
double aB = data.positions[_indexB].a;
qA.setAngle(aA);
qB.setAngle(aB);
Rot.mulToOutUnsafe(
qA,
u
..setFrom(_localAnchorA)
..sub(_localCenterA),
rA);
Rot.mulToOutUnsafe(
qB,
u
..setFrom(_localAnchorB)
..sub(_localCenterB),
rB);
u
..setFrom(cB)
..add(rB)
..sub(cA)
..sub(rA);
double length = u.normalize();
double C = length - _length;
C = MathUtils.clampDouble(
C, -Settings.maxLinearCorrection, Settings.maxLinearCorrection);
double impulse = -_mass * C;
double Px = impulse * u.x;
double Py = impulse * u.y;
cA.x -= _invMassA * Px;
cA.y -= _invMassA * Py;
aA -= _invIA * (rA.x * Py - rA.y * Px);
cB.x += _invMassB * Px;
cB.y += _invMassB * Py;
aB += _invIB * (rB.x * Py - rB.y * Px);
// data.positions[_indexA].c.set(cA);
data.positions[_indexA].a = aA;
// data.positions[_indexB].c.set(cB);
data.positions[_indexB].a = aB;
pool.pushVec2(3);
pool.pushRot(2);
return C.abs() < Settings.linearSlop;
}
}
|
box2d.dart/lib/src/dynamics/joints/distance_joint.dart/0
|
{'file_path': 'box2d.dart/lib/src/dynamics/joints/distance_joint.dart', 'repo_id': 'box2d.dart', 'token_count': 3962}
|
/// *****************************************************************************
/// Copyright (c) 2015, Daniel Murphy, Google
/// All rights reserved.
///
/// Redistribution and use in source and binary forms, with or without modification,
/// are permitted provided that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice,
/// this list of conditions and the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
/// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
/// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
/// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
/// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
/// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
/// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
/// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
/// *****************************************************************************
library box2d.math_utils;
import 'dart:math' as Math;
import 'vector_math.dart';
const double TWOPI = Math.pi * 2.0;
double distanceSquared(Vector2 v1, Vector2 v2) => v1.distanceToSquared(v2);
double distance(Vector2 v1, Vector2 v2) => v1.distanceTo(v2);
/// Returns the closest value to 'a' that is in between 'low' and 'high'
double clampDouble(final double a, final double low, final double high) =>
Math.max(low, Math.min(a, high));
Vector2 clampVec2(final Vector2 a, final Vector2 low, final Vector2 high) {
final Vector2 min = Vector2.zero();
min.x = a.x < high.x ? a.x : high.x;
min.y = a.y < high.y ? a.y : high.y;
min.x = low.x > min.x ? low.x : min.x;
min.y = low.y > min.y ? low.y : min.y;
return min;
}
/// Given a value within the range specified by [fromMin] and [fromMax],
/// returns a value with the same relative position in the range specified
/// from [toMin] and [toMax]. For example, given a [val] of 2 in the
/// "from range" of 0-4, and a "to range" of 10-20, would return 15.
double translateAndScale(
double val, double fromMin, double fromMax, double toMin, double toMax) {
final double mult = (val - fromMin) / (fromMax - fromMin);
final double res = toMin + mult * (toMax - toMin);
return res;
}
bool approxEquals(num expected, num actual, [num tolerance = null]) {
if (tolerance == null) {
tolerance = (expected / 1e4).abs();
}
return ((expected - actual).abs() <= tolerance);
}
Vector2 crossDblVec2(double s, Vector2 a) {
return Vector2(-s * a.y, s * a.x);
}
bool vector2Equals(Vector2 a, Vector2 b) {
if ((a == null) || (b == null)) return false;
if (identical(a, b)) return true;
if (a is! Vector2 || b is! Vector2) return false;
return ((a.x == b.x) && (a.y == b.y));
}
bool vector2IsValid(Vector2 v) {
return !v.x.isNaN && !v.x.isInfinite && !v.y.isNaN && !v.y.isInfinite;
}
void matrix3MulToOutUnsafe(Matrix3 A, Vector3 v, Vector3 out) {
assert(out != v);
out.x = v.x * A.entry(0, 0) + v.y * A.entry(0, 1) + v.z * A.entry(0, 2);
out.y = v.x * A.entry(1, 0) + v.y * A.entry(1, 1) + v.z * A.entry(1, 2);
out.z = v.x * A.entry(2, 0) + v.y * A.entry(2, 1) + v.z * A.entry(2, 2);
}
void matrix3Mul22ToOutUnsafe(Matrix3 A, Vector2 v, Vector2 out) {
assert(v != out);
out.y = A.entry(1, 0) * v.x + A.entry(1, 1) * v.y;
out.x = A.entry(0, 0) * v.x + A.entry(0, 1) * v.y;
}
void matrix3GetInverse22(Matrix3 m, Matrix3 M) {
double a = m.entry(0, 0),
b = m.entry(0, 1),
c = m.entry(1, 0),
d = m.entry(1, 1);
double det = a * d - b * c;
if (det != 0.0) {
det = 1.0 / det;
}
double ex_x = det * d;
double ey_x = -det * b;
double ex_z = 0.0;
double ex_y = -det * c;
double ey_y = det * a;
double ey_z = 0.0;
double ez_x = 0.0;
double ez_y = 0.0;
double ez_z = 0.0;
M.setValues(ex_x, ex_y, ex_z, ey_x, ey_y, ey_z, ez_x, ez_y, ez_z);
}
// / Returns the zero matrix if singular.
void matrix3GetSymInverse33(Matrix3 m, Matrix3 M) {
double bx = m.entry(1, 1) * m.entry(2, 2) - m.entry(2, 1) * m.entry(1, 2);
double by = m.entry(2, 1) * m.entry(0, 2) - m.entry(0, 1) * m.entry(2, 2);
double bz = m.entry(0, 1) * m.entry(1, 2) - m.entry(1, 1) * m.entry(0, 2);
double det = m.entry(0, 0) * bx + m.entry(1, 0) * by + m.entry(2, 0) * bz;
if (det != 0.0) {
det = 1.0 / det;
}
double a11 = m.entry(0, 0), a12 = m.entry(0, 1), a13 = m.entry(0, 2);
double a22 = m.entry(1, 1), a23 = m.entry(1, 2);
double a33 = m.entry(2, 2);
double ex_x = det * (a22 * a33 - a23 * a23);
double ex_y = det * (a13 * a23 - a12 * a33);
double ex_z = det * (a12 * a23 - a13 * a22);
double ey_x = M.entry(1, 0);
double ey_y = det * (a11 * a33 - a13 * a13);
double ey_z = det * (a13 * a12 - a11 * a23);
double ez_x = M.entry(2, 0);
double ez_y = M.entry(2, 1);
double ez_z = det * (a11 * a22 - a12 * a12);
M.setValues(ex_x, ex_y, ex_z, ey_x, ey_y, ey_z, ez_x, ez_y, ez_z);
}
|
box2d.dart/lib/src/math_utils.dart/0
|
{'file_path': 'box2d.dart/lib/src/math_utils.dart', 'repo_id': 'box2d.dart', 'token_count': 2153}
|
blank_issues_enabled: false
|
brache/packages/brache/.github/ISSUE_TEMPLATE/config.yml/0
|
{'file_path': 'brache/packages/brache/.github/ISSUE_TEMPLATE/config.yml', 'repo_id': 'brache', 'token_count': 7}
|
include: package:very_good_analysis/analysis_options.5.0.0.yaml
|
brache/packages/brache/analysis_options.yaml/0
|
{'file_path': 'brache/packages/brache/analysis_options.yaml', 'repo_id': 'brache', 'token_count': 23}
|
/// An extension to the bloc state management library
/// which adds support for broadcasting state changes to stream channels.
library broadcast_bloc;
export 'package:bloc/bloc.dart';
export 'src/broadcast_bloc.dart' show BroadcastBloc;
export 'src/broadcast_cubit.dart' show BroadcastCubit;
export 'src/broadcast_mixin.dart' show BroadcastMixin;
|
broadcast_bloc/lib/broadcast_bloc.dart/0
|
{'file_path': 'broadcast_bloc/lib/broadcast_bloc.dart', 'repo_id': 'broadcast_bloc', 'token_count': 104}
|
targets:
$default:
builders:
provides_builder:some_builder:
options:
throw_in_constructor: true
build_web_compilers:entrypoint:
generate_for:
- web/main.dart
- web/sub/main.dart
- test/hello_world_test.dart
- test/hello_world_test.dart.browser_test.dart
- test/hello_world_deferred_test.dart
- test/hello_world_deferred_test.dart.browser_test.dart
- test/hello_world_custom_html_test.dart
- test/hello_world_custom_html_test.dart.browser_test.dart
- test/other_test.dart.browser_test.dart
- test/sub-dir/subdir_test.dart
- test/sub-dir/subdir_test.dart.browser_test.dart
build_vm_compilers:entrypoint:
generate_for:
- test/help_test.dart.vm_test.dart
|
build/_test/build.throws.yaml/0
|
{'file_path': 'build/_test/build.throws.yaml', 'repo_id': 'build', 'token_count': 418}
|
// 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:test/test.dart';
import 'common/message.dart'
if (dart.library.io) 'common/message_io.dart'
if (dart.library.html) 'common/message_html.dart';
import 'common/message_export.dart' as exported;
void main() {
group('browser', () {
test('imports', () {
expect(message, contains('Javascript'));
});
test('exports', () {
expect(exported.message, contains('Javascript'));
});
}, testOn: 'browser');
group('vm', () {
test('imports', () {
expect(message, contains('VM'));
});
test('exports', () {
expect(exported.message, contains('VM'));
});
}, testOn: 'vm');
}
|
build/_test/test/configurable_uri_test.dart/0
|
{'file_path': 'build/_test/test/configurable_uri_test.dart', 'repo_id': 'build', 'token_count': 315}
|
// 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 'dart:async';
// ignore: implementation_imports
import 'package:build_runner_core/src/asset/reader.dart';
// ignore: implementation_imports
import 'package:build_runner_core/src/asset/writer.dart';
// ignore: implementation_imports
import 'package:build_runner_core/src/environment/build_environment.dart';
import 'package:logging/logging.dart';
import 'common.dart';
/// A [BuildEnvironment] for testing.
///
/// Defaults to using an [InMemoryRunnerAssetReader] and
/// [InMemoryRunnerAssetWriter].
///
/// To handle prompts you must first set `nextPromptResponse`. Alternatively
/// you can set `throwOnPrompt` to `true` to emulate a
/// [NonInteractiveBuildException].
class TestBuildEnvironment extends BuildEnvironment {
@override
final RunnerAssetReader reader;
@override
final RunnerAssetWriter writer;
/// If true, this will throw a [NonInteractiveBuildException] for all calls to
/// [prompt].
final bool throwOnPrompt;
final logRecords = <LogRecord>[];
/// The next response for calls to [prompt]. Must be set before calling
/// [prompt].
set nextPromptResponse(int next) {
assert(_nextPromptResponse == null);
_nextPromptResponse = next;
}
int? _nextPromptResponse;
TestBuildEnvironment(
{RunnerAssetReader? reader,
RunnerAssetWriter? writer,
this.throwOnPrompt = false})
: reader = reader ?? InMemoryRunnerAssetReader(),
writer = writer ?? InMemoryRunnerAssetWriter();
@override
void onLog(LogRecord record) => logRecords.add(record);
/// Prompt the user for input.
///
/// The message and choices are displayed to the user and the index of the
/// chosen option is returned.
///
/// If this environmment is non-interactive (such as when running in a test)
/// this method should throw [NonInteractiveBuildException].
@override
Future<int> prompt(String message, List<String> choices) {
if (throwOnPrompt) throw NonInteractiveBuildException();
assert(_nextPromptResponse != null);
return Future.value(_nextPromptResponse);
}
}
|
build/_test_common/lib/test_environment.dart/0
|
{'file_path': 'build/_test_common/lib/test_environment.dart', 'repo_id': 'build', 'token_count': 673}
|
include: package:lints/recommended.yaml
analyzer:
language:
strict-casts: true
errors:
unused_import: error
unused_local_variable: error
dead_code: error
todo: ignore
deprecated_member_use_from_same_package: ignore
exclude:
# Prevents extra work during e2e test runs.
- "_test/dart2js_test/**"
# Common top level directories containing generated files in any package.
- "*/build/**"
- "*/.dart_tool/**"
linter:
rules:
always_declare_return_types: true
avoid_bool_literals_in_conditional_expressions: true
avoid_classes_with_only_static_members: true
avoid_returning_this: true
avoid_unused_constructor_parameters: true
cascade_invocations: true
comment_references: true
directives_ordering: true
no_adjacent_strings_in_list: true
omit_local_variable_types: true
only_throw_errors: true
prefer_single_quotes: true
test_types_in_equals: true
throw_in_finally: true
unawaited_futures: true
unnecessary_lambdas: true
unnecessary_parenthesis: true
unnecessary_statements: true
# TODO: https://github.com/google/built_value.dart/issues/1115
library_private_types_in_public_api: false
no_leading_underscores_for_local_identifiers: false
|
build/analysis_options.yaml/0
|
{'file_path': 'build/analysis_options.yaml', 'repo_id': 'build', 'token_count': 466}
|
// 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 'dart:async';
import 'package:glob/glob.dart';
import 'post_process_build_step.dart';
import 'post_process_builder.dart';
/// A [PostProcessBuilder] which can be configured to consume any input
/// extensions and always deletes it primary input.
class FileDeletingBuilder implements PostProcessBuilder {
@override
final List<String> inputExtensions;
final bool isEnabled;
final List<Glob> exclude;
const FileDeletingBuilder(this.inputExtensions, {this.isEnabled = true})
: exclude = const [];
FileDeletingBuilder.withExcludes(
this.inputExtensions, Iterable<String> exclude,
{this.isEnabled = true})
: exclude = exclude.map(Glob.new).toList();
@override
FutureOr<void> build(PostProcessBuildStep buildStep) {
if (!isEnabled) return null;
if (exclude.any((g) => g.matches(buildStep.inputId.path))) return null;
buildStep.deletePrimaryInput();
return null;
}
}
|
build/build/lib/src/builder/file_deleting_builder.dart/0
|
{'file_path': 'build/build/lib/src/builder/file_deleting_builder.dart', 'repo_id': 'build', 'token_count': 366}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.