code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
import 'package:flutter/material.dart'; class XMargin extends StatelessWidget { const XMargin(this.width, {super.key}); final double width; @override Widget build(BuildContext context) { return SizedBox( width: width, ); } }
Calculator-Flutter/lib/utils/margins/x_margin.dart/0
{'file_path': 'Calculator-Flutter/lib/utils/margins/x_margin.dart', 'repo_id': 'Calculator-Flutter', 'token_count': 91}
analyzer: exclude: - nested_flutter_example/**
Dart-Code/src/test/test_projects/dart_nested_flutter2/analysis_options.yaml/0
{'file_path': 'Dart-Code/src/test/test_projects/dart_nested_flutter2/analysis_options.yaml', 'repo_id': 'Dart-Code', 'token_count': 20}
import 'package:hello_world/deferred_script.dart' deferred as def; main() async { await def.loadLibrary(); def.do_print(); }
Dart-Code/src/test/test_projects/hello_world/bin/deferred_entry.dart/0
{'file_path': 'Dart-Code/src/test/test_projects/hello_world/bin/deferred_entry.dart', 'repo_id': 'Dart-Code', 'token_count': 45}
name: hello_world_example publish_to: none environment: sdk: '>=2.12.0 <3.0.0' dev_dependencies: test: '>=0.12.34'
Dart-Code/src/test/test_projects/hello_world/example/pubspec.yaml/0
{'file_path': 'Dart-Code/src/test/test_projects/hello_world/example/pubspec.yaml', 'repo_id': 'Dart-Code', 'token_count': 59}
part 'part.dart';
Dart-Code/src/test/test_projects/hello_world/lib/part_wrapper.dart/0
{'file_path': 'Dart-Code/src/test/test_projects/hello_world/lib/part_wrapper.dart', 'repo_id': 'Dart-Code', 'token_count': 8}
import "package:test/test.dart"; // This comment is extracted by the test and compared to a text representation // built from the tree provider in the test. It must be maintained to match // the results from the tests below. // == EXPECTED RESULTS == // test/short_test.dart [1/1 passed] Passed // group1 [1/1 passed] Passed // test1 Passed // == /EXPECTED RESULTS == void main() { group("group1", () { test("test1", () {}); }); }
Dart-Code/src/test/test_projects/hello_world/test/short_test.dart/0
{'file_path': 'Dart-Code/src/test/test_projects/hello_world/test/short_test.dart', 'repo_id': 'Dart-Code', 'token_count': 150}
import 'package:first_desktop_application/app-level/assets/assets.dart'; import 'package:first_desktop_application/app-level/styles/colors.dart'; import 'package:first_desktop_application/app-level/utils/screen_size.dart'; import 'package:flutter/material.dart'; import 'image_loader.dart'; import 'link_content.dart'; typedef OnFavClick = void Function(); class ParallaxButton extends StatefulWidget { const ParallaxButton({ Key key, this.text, @required this.medium, @required this.website, @required this.youtubeLink, @required this.isFavorite, }) : super(key: key); final String medium; final String website; final String youtubeLink; final bool isFavorite; final String text; @override _ParallaxButtonState createState() => _ParallaxButtonState(); } class _ParallaxButtonState extends State<ParallaxButton> { ShapeBorder get shape => const RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(32.0), topRight: Radius.circular(32.0), ), ); double get _height => ScreenQueries.instance.height(context); double get _width => ScreenQueries.instance.width(context); double localX = 0; double localY = 0; bool defaultPosition = true; double percentageX; double percentageY; @override Widget build(BuildContext context) { // return SizedBox( width: (_width * 0.15).roundToDouble(), height: (_height * 0.41).roundToDouble(), child: LayoutBuilder( builder: (context, constraints) { // final _maxHeight = constraints.maxHeight; final _maxWidth = constraints.maxWidth; percentageX = (localX / _maxWidth) * 100; percentageY = (localY / _maxHeight) * 100; final _rotateX = defaultPosition ? 0 : (0.3 * (percentageY / 50) + -0.3); final _rotateY = defaultPosition ? 0 : (-0.3 * (percentageX / 50) + 0.3); final _translateX = defaultPosition ? 0.0 : (15 * (percentageX / 50) + -15); final _translateY = defaultPosition ? 0.0 : (15 * (percentageY / 50) + -15); return GestureDetector( onPanStart: onPanStart, onPanUpdate: (details) => onPanUpdate(details, _maxHeight, _maxWidth), onPanEnd: (details) => onPanEnd(details, _maxHeight, _maxWidth), onPanCancel: onPanCancel, onPanDown: onPanDown, child: Transform( alignment: FractionalOffset.center, transform: Matrix4.identity() ..setEntry(3, 2, 0.001) ..rotateX(_rotateX.ceilToDouble()) ..rotateY(_rotateY.ceilToDouble()), child: Stack( fit: StackFit.expand, children: [ Card( color: AppColors.brandColor, margin: const EdgeInsets.only(left: 8, right: 8, bottom: 24), elevation: 8, shape: shape, child: Transform( alignment: FractionalOffset.center, transform: Matrix4.identity() ..translate(_translateX, _translateY, 0), child: Column( children: [ const Expanded( flex: 2, child: ClipRRect( borderRadius: BorderRadius.vertical( top: Radius.circular(32), ), child: ImageWidgetPlaceholder( image: WebAssets.logo, width: double.maxFinite, fit: BoxFit.fitWidth, ), ), ), Expanded( child: Container( color: Colors.grey.shade200, child: LinkContent( isFavorite: widget.isFavorite, medium: widget.medium, text: widget.text, website: widget.website, youtubeLink: widget.youtubeLink, ), ), ), ], ), ), ), ], ), ), ); }, ), ); } void onPanStart(DragStartDetails details) {} void onPanUpdate(DragUpdateDetails details, double height, double width) { setState(() { if (mounted) { defaultPosition = false; } final _localPos = details.localPosition; if (_localPos.dx > 0 && _localPos.dy < height) { localX = _localPos.dx; localY = _localPos.dy; } }); } void onPanEnd(DragEndDetails details, double height, double width) { setState(() { localX = width / 2; localY = height / 2; defaultPosition = true; }); } void onPanCancel() { setState(() => defaultPosition = true); } void onPanDown(DragDownDetails details) { setState(() => defaultPosition = false); } } // https://medium.com/flutter-community/flutter-mouse-hover-parallax-effect-116b85bb5a80
Experiments_with_Desktop/first_desktop_application/lib/app-level/widgets/parallax_btn.dart/0
{'file_path': 'Experiments_with_Desktop/first_desktop_application/lib/app-level/widgets/parallax_btn.dart', 'repo_id': 'Experiments_with_Desktop', 'token_count': 2921}
// ignore_for_file: leading_newlines_in_multiline_strings,unnecessary_string_escapes,avoid_print class TerminalBlock { TerminalBlock._(); static void blockBoy([ String message = 'This is Aseem Wangoo! Visit flatteredwithflutter.com for more details', ]) { print(''' .-"""-. / .===. \ \/ 6 6 \/ ( \___/ ) _________________ooo__\_____/_____________________ / \ | $message | \______________________________ooo_________________/ | | | |_ | _| | | | |__|__| /-'Y'-\ (__/ \__)'''); } }
Experiments_with_Desktop/first_desktop_application/lib/ffi/utils/terminal_blocks.dart/0
{'file_path': 'Experiments_with_Desktop/first_desktop_application/lib/ffi/utils/terminal_blocks.dart', 'repo_id': 'Experiments_with_Desktop', 'token_count': 488}
import 'package:first_desktop_application/inking/constants.dart'; import 'package:flutter/material.dart'; class DarkInkContent extends StatelessWidget { final bool darkMode; // TODO(Aseem): Add scroll const DarkInkContent({Key key, this.darkMode = false}) : super(key: key); @override Widget build(BuildContext context) { const lightTextColor = Color(0xFFBCFEEA); const lightSubHeaderColor = Color(0xFF00EBAC); const darkSubHeaderColor = Color(0xFF008F9C); const darkTextColor = Color(0xFF210A3B); return SingleChildScrollView( child: Container( color: darkMode ? const Color(0xFF313466) : const Color(0xFFFFFFFF), padding: const EdgeInsets.all(37.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( InkingConstants.headerText, style: TextStyle( fontSize: 36, fontFamily: 'Merriweather', fontWeight: FontWeight.bold, color: darkMode ? lightTextColor : darkTextColor, decoration: TextDecoration.none, ), ), const Padding(padding: EdgeInsets.only(top: 24.0)), Text( InkingConstants.subHeaderText, style: TextStyle( fontSize: 12, fontFamily: 'Merriweather', color: darkMode ? lightSubHeaderColor : darkSubHeaderColor, decoration: TextDecoration.none, ), ), const Padding(padding: EdgeInsets.only(top: 12)), Container( height: 1.0, color: darkMode ? const Color(0x510098A3) : const Color(0x512B777E), ), const Padding(padding: EdgeInsets.only(top: 24.0)), Text( InkingConstants.bodyText, style: TextStyle( fontSize: 16, fontFamily: 'Barlow', letterSpacing: 0.5, height: 1.5, fontWeight: FontWeight.w500, color: darkMode ? lightTextColor : darkTextColor, decoration: TextDecoration.none, ), ), const Padding(padding: EdgeInsets.only(top: 64.0)), ], ), ), ); } }
Experiments_with_Desktop/first_desktop_application/lib/inking/widgets/dark_ink_content.dart/0
{'file_path': 'Experiments_with_Desktop/first_desktop_application/lib/inking/widgets/dark_ink_content.dart', 'repo_id': 'Experiments_with_Desktop', 'token_count': 1200}
import 'dart:math'; import 'package:flutter/material.dart'; class RoundedShadow extends StatelessWidget { final Widget child; final Color shadowColor; final double topLeftRadius; final double topRightRadius; final double bottomLeftRadius; final double bottomRightRadius; const RoundedShadow({ Key key, this.child, this.shadowColor, this.topLeftRadius = 48, this.topRightRadius = 48, this.bottomLeftRadius = 48, this.bottomRightRadius = 48, }) : super(key: key); const RoundedShadow.fromRadius( double radius, { this.child, this.shadowColor, }) : topLeftRadius = radius, topRightRadius = radius, bottomRightRadius = radius, bottomLeftRadius = radius; @override Widget build(BuildContext context) { // Create a border radius, only applies to the bottom final BorderRadius borderRadius = BorderRadius.only( topLeft: Radius.circular(topLeftRadius), topRight: Radius.circular(topRightRadius), bottomLeft: Radius.circular(bottomLeftRadius), bottomRight: Radius.circular(bottomRightRadius), ); final Color sColor = shadowColor ?? const Color(0x20000000); final double maxRadius = [ topLeftRadius, topRightRadius, bottomLeftRadius, bottomRightRadius ].reduce(max); return Container( decoration: BoxDecoration( borderRadius: borderRadius, boxShadow: [ BoxShadow(color: sColor, blurRadius: maxRadius * .5), ], ), child: ClipRRect( borderRadius: borderRadius, child: child, ), ); } }
Experiments_with_Desktop/first_desktop_application/lib/liquid_cards/widgets/rounded_shadow.dart/0
{'file_path': 'Experiments_with_Desktop/first_desktop_application/lib/liquid_cards/widgets/rounded_shadow.dart', 'repo_id': 'Experiments_with_Desktop', 'token_count': 632}
import 'package:dartz/dartz.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:xafe/app/authentication/data/datasource/authentication_data_source.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/repository/authentication_repo.dart'; import 'package:xafe/core/error/failures.dart'; import 'package:xafe/core/error/helpers/helpers.dart'; class AuthenticationRepoImpl implements AuthenticationRepo { AuthenticationRepoImpl({ this.authenticationDataSource, }); final AuthenticationDataSource authenticationDataSource; @override Future<Either<Failure, User>> loginUser(EmailPasswordParams params) async { return successFailureInterceptor( () => authenticationDataSource.postLoginUser(params), ); } @override Future<Either<Failure, User>> registerUser(EmailPasswordParams params) { return successFailureInterceptor( () => authenticationDataSource.postRegisterUser(params), ); } @override Future<Either<Failure, void>> createUser(UserModel params) { return successFailureInterceptor( () => authenticationDataSource.postCreateUser(params), ); } @override Future<Either<Failure, UserModel>> getUser(String id) { return successFailureInterceptor( () => authenticationDataSource.postGetUser(id), ); } }
Xafe/lib/app/authentication/data/repository/authentication_repo_impl.dart/0
{'file_path': 'Xafe/lib/app/authentication/data/repository/authentication_repo_impl.dart', 'repo_id': 'Xafe', 'token_count': 466}
import 'package:xafe/app/budget/data/datasource/budget_datasource.dart'; import 'package:xafe/app/budget/data/datasource/impl/budget_datasource_impl.dart'; import 'package:xafe/app/budget/data/repository/budget_repo_impl.dart'; import 'package:xafe/app/budget/domain/repository/budget_repo.dart'; import 'package:xafe/app/budget/domain/usecases/create_budget.dart'; import 'package:xafe/app/budget/domain/usecases/create_budget_expense.dart'; import 'package:xafe/app/budget/domain/usecases/delete_budget.dart'; import 'package:xafe/app/budget/domain/usecases/edit_budget.dart'; import 'package:xafe/app/budget/domain/usecases/listen_to_budgets.dart'; import 'package:xafe/core/config/di_config.dart'; import 'domain/usecases/listen_to_budget_expenses.dart'; void registerBudgetsDIs() { //Use cases locator.registerLazySingleton(() => CreateBudget(locator())); locator.registerLazySingleton(() => CreateBudgetExpense(locator())); locator.registerLazySingleton(() => DeleteBudget(locator())); locator.registerLazySingleton(() => EditBudget(locator())); locator.registerLazySingleton(() => ListenToBudgets(locator())); locator.registerLazySingleton(() => ListenToBudgetExpenses(locator())); //Repository locator.registerLazySingleton<BudgetRepo>( () => BudgetRepoImpl( locator(), ), ); // Data sources locator.registerLazySingleton<BudgetDataSource>( () => BudgetDataSourceImpl( locator(), ), ); }
Xafe/lib/app/budget/budget_dependencies.dart/0
{'file_path': 'Xafe/lib/app/budget/budget_dependencies.dart', 'repo_id': 'Xafe', 'token_count': 530}
import 'package:flutter/material.dart'; import 'package:stacked/stacked.dart'; import 'package:uuid/uuid.dart'; import 'package:xafe/app/categories/data/model/category_model.dart'; import 'package:xafe/app/categories/presentation/logic/viewmodels/create_category_viewmodel.dart'; import 'package:xafe/core/config/di_config.dart'; import 'package:xafe/src/res/components/back_arrow/src/app_back_arrow.dart'; import 'package:xafe/src/res/components/buttons/src/xafe_button.dart'; import 'package:xafe/src/res/res.dart'; import 'package:xafe/src/utils/scaler/scaler.dart'; class AddSpendingCategoryScreen extends StatefulWidget { @override _AddSpendingCategoryScreenState createState() => _AddSpendingCategoryScreenState(); } class _AddSpendingCategoryScreenState extends State<AddSpendingCategoryScreen> { final _categoryEmojis = [ 'πŸ–', '✈️', 'πŸ€΅β€β™‚οΈ', 'πŸ›’', 'πŸ₯', '🏑', 'πŸŽ₯', ]; final ValueNotifier<String> _currentSelectedValue = ValueNotifier(null); TextEditingController _categoryNameController; TextEditingController _categoryEmojiController; @override void initState() { super.initState(); _categoryNameController = TextEditingController( text: '', ); _categoryEmojiController = TextEditingController( text: '', ); } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: true, body: Padding( padding: context.insetsSymetric( horizontal: 20.0, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const YMargin(66.45), KAppBackArrow(), const YMargin(60.45), const Text( '‍Add a spending category', style: TextStyle( fontWeight: FontWeight.w400, fontSize: 24, color: kColorAppBlack, ), ), const YMargin(35), TextFormField( decoration: const InputDecoration(hintText: 'Enter category name'), controller: _categoryNameController, ), const YMargin(10), ValueListenableBuilder( valueListenable: _currentSelectedValue, builder: (_, value, child) { return DropdownButtonFormField( iconEnabledColor: kColorAppBlack, iconDisabledColor: kColorAppBlack, value: value, onChanged: (value) { _currentSelectedValue.value = value; }, items: _categoryEmojis.map((String value) { return DropdownMenuItem<String>( value: value, child: Text(value), ); }).toList(), decoration: const InputDecoration( hintText: 'Choose category emoji', ), ); }), const Spacer(), ViewModelBuilder<CreateCategoryViewmodel>.reactive( viewModelBuilder: () => CreateCategoryViewmodel(locator()), builder: (_, model, __) { return XafeButton( isLoading: model.isBusy, onPressed: () { model.createCategory( params: CategoryModel( categoryId: const Uuid().v4(), categoryName: _categoryNameController.text, categoryEmoji: _currentSelectedValue.value, ), context: context, ); }, text: 'Create Category', ); }), const YMargin(80), ], ), ), ); } }
Xafe/lib/app/categories/presentation/screens/add_spending_category_screen.dart/0
{'file_path': 'Xafe/lib/app/categories/presentation/screens/add_spending_category_screen.dart', 'repo_id': 'Xafe', 'token_count': 2081}
export 'services/auth_service.dart'; export 'services/firestore_service.dart';
Xafe/lib/core/config/firebase/firebase.dart/0
{'file_path': 'Xafe/lib/core/config/firebase/firebase.dart', 'repo_id': 'Xafe', 'token_count': 25}
import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:xafe/src/res/values/assets/svgs/svgs.dart'; import 'package:xafe/src/utils/navigation/navigation.dart'; import 'package:xafe/src/utils/scaler/scaler.dart'; class KAppBackArrow extends StatelessWidget { @override Widget build(BuildContext context) { return InkWell( onTap: () => popView(context), child: SvgPicture.asset( kBackArrowIcon, height: context.scaleY(19), ), ); } }
Xafe/lib/src/res/components/back_arrow/src/app_back_arrow.dart/0
{'file_path': 'Xafe/lib/src/res/components/back_arrow/src/app_back_arrow.dart', 'repo_id': 'Xafe', 'token_count': 213}
import 'package:flutter/widgets.dart'; import 'scale.dart'; import 'scale_aware.dart'; extension BuildContextExtensions on BuildContext { Scale get _scale { // ignore: always_specify_types final data = MediaQuery.of(this); return Scale( size: data.size, textScaleFactor: data.textScaleFactor, config: ScaleAware.of(this)); } /// Pixels scaled per device from design. /// Where One pixel on a 160px screen equals two pixels on a 320px screen. /// Also and alias for scaleX double scale(num width) => _scale.scale(width); /// Pixels scaled per device from design in the Vertical direction. /// Where One pixel on a 160px screen equals two pixels on a 320px screen. double scaleY(num height) => _scale.scaleY(height); /// Relative to the font-size setting of the actual device double fontSize(num fontSize) => _scale.fontScale(fontSize); EdgeInsets insetsZero() => _scale.zero; ///. EdgeInsets insetsAll(num inset) => _scale.all(inset.toDouble()); ///. EdgeInsets insetsOnly({ double left = 0, double top = 0, double right = 0, double bottom = 0, }) => _scale.only(left, top, right, bottom); ///. EdgeInsets insetsFromLTRB({ double left = 0, double top = 0, double right = 0, double bottom = 0, }) => _scale.fromLTRB(left, top, right, bottom); ///. EdgeInsets insetsSymetric({ double vertical = 0, double horizontal = 0, }) => _scale.symmetric(vertical, horizontal); double get height => MediaQuery.of(this).size.height; double get width => MediaQuery.of(this).size.width; }
Xafe/lib/src/utils/scaler/src/extensions.dart/0
{'file_path': 'Xafe/lib/src/utils/scaler/src/extensions.dart', 'repo_id': 'Xafe', 'token_count': 567}
import 'package:equatable/equatable.dart'; import 'package:{{project_name.snakeCase()}}/models/Todo.dart'; enum TodosPageStatus { initial, loading, success, failure } class TodosPageState extends Equatable { const TodosPageState({ this.status = TodosPageStatus.initial, this.todos = const [], }); final TodosPageStatus status; final List<Todo> todos; TodosPageState copyWith({ TodosPageStatus Function()? status, List<Todo> Function()? todos, }) => TodosPageState( status: status != null ? status() : this.status, todos: todos != null ? todos() : this.todos, ); @override List<Object?> get props => [ status, todos, ]; }
amplify_starter/__brick__/{{project_name}}/lib/todos/todos_list/bloc/todos_page_states.dart/0
{'file_path': 'amplify_starter/__brick__/{{project_name}}/lib/todos/todos_list/bloc/todos_page_states.dart', 'repo_id': 'amplify_starter', 'token_count': 284}
import 'dart:convert'; class Utils { static String formatJson(jsonObj) { // ignore: prefer_final_locals JsonEncoder encoder = new JsonEncoder.withIndent(' '); return encoder.convert(jsonObj); } }
appsflyer-flutter-plugin/example/lib/utils.dart/0
{'file_path': 'appsflyer-flutter-plugin/example/lib/utils.dart', 'repo_id': 'appsflyer-flutter-plugin', 'token_count': 83}
part of appsflyer_sdk; class AppsFlyerOptions { final String afDevKey; final bool showDebug; final String appId; final double? timeToWaitForATTUserAuthorization; final String? appInviteOneLink; final bool? disableAdvertisingIdentifier; final bool? disableCollectASA; AppsFlyerOptions({ required this.afDevKey, this.showDebug = false, this.appId = "", this.timeToWaitForATTUserAuthorization, this.appInviteOneLink, this.disableAdvertisingIdentifier, this.disableCollectASA, }); }
appsflyer-flutter-plugin/lib/src/appsflyer_options.dart/0
{'file_path': 'appsflyer-flutter-plugin/lib/src/appsflyer_options.dart', 'repo_id': 'appsflyer-flutter-plugin', 'token_count': 181}
export 'view/app.dart';
article-hub/flame-game/sample/lib/app/app.dart/0
{'file_path': 'article-hub/flame-game/sample/lib/app/app.dart', 'repo_id': 'article-hub', 'token_count': 10}
export 'title_page.dart';
article-hub/flame-game/sample/lib/title/view/view.dart/0
{'file_path': 'article-hub/flame-game/sample/lib/title/view/view.dart', 'repo_id': 'article-hub', 'token_count': 10}
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockingjay/mockingjay.dart'; import 'package:sample/title/title.dart'; import '../../helpers/helpers.dart'; void main() { group('TitlePage', () { testWidgets('renders TitleView', (tester) async { await tester.pumpApp(const TitlePage()); expect(find.byType(TitleView), findsOneWidget); }); }); group('TitleView', () { testWidgets('renders start button', (tester) async { await tester.pumpApp(const TitleView()); expect(find.byType(ElevatedButton), findsOneWidget); }); testWidgets('starts the game when start button is tapped', (tester) async { final navigator = MockNavigator(); when( () => navigator.pushReplacement<void, void>(any()), ).thenAnswer((_) async {}); await tester.pumpApp(const TitleView(), navigator: navigator); await tester.tap(find.byType(ElevatedButton)); verify(() => navigator.pushReplacement<void, void>(any())).called(1); }); }); }
article-hub/flame-game/sample/test/title/view/title_page_test.dart/0
{'file_path': 'article-hub/flame-game/sample/test/title/view/title_page_test.dart', 'repo_id': 'article-hub', 'token_count': 402}
// 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'; /// Simple delegating wrapper around a [Stream]. /// /// Subclasses can override individual methods, or use this to expose only the /// [Stream] methods of a subclass. /// /// Note that this is identical to [StreamView] in `dart:async`. It's provided /// under this name for consistency with other `Delegating*` classes. class DelegatingStream<T> extends StreamView<T> { DelegatingStream(Stream<T> stream) : super(stream); /// Creates a wrapper which throws if [stream]'s events aren't instances of /// `T`. /// /// This soundly converts a [Stream] to a `Stream<T>`, regardless of its /// original generic type, by asserting that its events are instances of `T` /// whenever they're provided. If they're not, the stream throws a /// [CastError]. static Stream<T> typed<T>(Stream stream) => stream.cast(); }
async/lib/src/delegate/stream.dart/0
{'file_path': 'async/lib/src/delegate/stream.dart', 'repo_id': 'async', 'token_count': 294}
// 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'; /// A transformer that converts a broadcast stream into a single-subscription /// stream. /// /// This buffers the broadcast stream's events, which means that it starts /// listening to a stream as soon as it's bound. /// /// This also casts the source stream's events to type `T`. If the cast fails, /// the result stream will emit a [CastError]. This behavior is deprecated, and /// should not be relied upon. class SingleSubscriptionTransformer<S, T> extends StreamTransformerBase<S, T> { const SingleSubscriptionTransformer(); @override Stream<T> bind(Stream<S> stream) { StreamSubscription<S> subscription; var controller = StreamController<T>(sync: true, onCancel: () => subscription.cancel()); subscription = stream.listen((value) { // TODO(nweiz): When we release a new major version, get rid of the second // type parameter and avoid this conversion. try { controller.add(value as T); } on CastError catch (error, stackTrace) { controller.addError(error, stackTrace); } }, onError: controller.addError, onDone: controller.close); return controller.stream; } }
async/lib/src/single_subscription_transformer.dart/0
{'file_path': 'async/lib/src/single_subscription_transformer.dart', 'repo_id': 'async', 'token_count': 420}
name: async version: 2.4.1-dev description: Utility functions and classes related to the 'dart:async' library. homepage: https://www.github.com/dart-lang/async environment: sdk: '>=2.2.0 <3.0.0' dependencies: collection: ^1.5.0 dev_dependencies: fake_async: ^1.0.0 stack_trace: ^1.0.0 test: ^1.0.0 pedantic: ^1.0.0
async/pubspec.yaml/0
{'file_path': 'async/pubspec.yaml', 'repo_id': 'async', 'token_count': 145}
// 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 filevents. import 'dart:async'; import 'package:async/async.dart'; import 'package:test/test.dart'; import 'utils.dart'; void main() { group('source stream', () { test('is listened to on first request, paused between requests', () async { var controller = StreamController<int>(); var events = StreamQueue<int>(controller.stream); await flushMicrotasks(); expect(controller.hasListener, isFalse); var next = events.next; expect(controller.hasListener, isTrue); expect(controller.isPaused, isFalse); controller.add(1); expect(await next, 1); expect(controller.hasListener, isTrue); expect(controller.isPaused, isTrue); next = events.next; expect(controller.hasListener, isTrue); expect(controller.isPaused, isFalse); controller.add(2); expect(await next, 2); expect(controller.hasListener, isTrue); expect(controller.isPaused, isTrue); events.cancel(); expect(controller.hasListener, isFalse); }); }); group('eventsDispatched', () { test('increments after a next future completes', () async { var events = StreamQueue<int>(createStream()); expect(events.eventsDispatched, equals(0)); await flushMicrotasks(); expect(events.eventsDispatched, equals(0)); var next = events.next; expect(events.eventsDispatched, equals(0)); await next; expect(events.eventsDispatched, equals(1)); await events.next; expect(events.eventsDispatched, equals(2)); }); test('increments multiple times for multi-value requests', () async { var events = StreamQueue<int>(createStream()); await events.take(3); expect(events.eventsDispatched, equals(3)); }); test('increments multiple times for an accepted transaction', () async { var events = StreamQueue<int>(createStream()); await events.withTransaction((queue) async { await queue.next; await queue.next; return true; }); expect(events.eventsDispatched, equals(2)); }); test("doesn't increment for rest requests", () async { var events = StreamQueue<int>(createStream()); await events.rest.toList(); expect(events.eventsDispatched, equals(0)); }); }); group('lookAhead operation', () { test('as simple list of events', () async { var events = StreamQueue<int>(createStream()); expect(await events.lookAhead(4), [1, 2, 3, 4]); expect(await events.next, 1); expect(await events.lookAhead(2), [2, 3]); expect(await events.take(2), [2, 3]); expect(await events.next, 4); await events.cancel(); }); test('of 0 events', () async { var events = StreamQueue<int>(createStream()); expect(events.lookAhead(0), completion([])); expect(events.next, completion(1)); expect(events.lookAhead(0), completion([])); expect(events.next, completion(2)); expect(events.lookAhead(0), completion([])); expect(events.next, completion(3)); expect(events.lookAhead(0), completion([])); expect(events.next, completion(4)); expect(events.lookAhead(0), completion([])); expect(events.lookAhead(5), completion([])); expect(events.next, throwsStateError); await events.cancel(); }); test('with bad arguments throws', () async { var events = StreamQueue<int>(createStream()); expect(() => events.lookAhead(-1), throwsArgumentError); expect(await events.next, 1); // Did not consume event. expect(() => events.lookAhead(-1), throwsArgumentError); expect(await events.next, 2); // Did not consume event. await events.cancel(); }); test('of too many arguments', () async { var events = StreamQueue<int>(createStream()); expect(await events.lookAhead(6), [1, 2, 3, 4]); await events.cancel(); }); test('too large later', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.next, 2); expect(await events.lookAhead(6), [3, 4]); await events.cancel(); }); test('error', () async { var events = StreamQueue<int>(createErrorStream()); expect(events.lookAhead(4), throwsA('To err is divine!')); expect(events.take(4), throwsA('To err is divine!')); expect(await events.next, 4); await events.cancel(); }); }); group('next operation', () { test('simple sequence of requests', () async { var events = StreamQueue<int>(createStream()); for (var i = 1; i <= 4; i++) { expect(await events.next, i); } expect(events.next, throwsStateError); }); test('multiple requests at the same time', () async { var events = StreamQueue<int>(createStream()); var result = await Future.wait( [events.next, events.next, events.next, events.next]); expect(result, [1, 2, 3, 4]); await events.cancel(); }); test('sequence of requests with error', () async { var events = StreamQueue<int>(createErrorStream()); expect(await events.next, 1); expect(await events.next, 2); expect(events.next, throwsA('To err is divine!')); expect(await events.next, 4); await events.cancel(); }); }); group('skip operation', () { test('of two elements in the middle of sequence', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.skip(2), 0); expect(await events.next, 4); await events.cancel(); }); test('with negative/bad arguments throws', () async { var events = StreamQueue<int>(createStream()); expect(() => events.skip(-1), throwsArgumentError); // A non-int throws either a type error or an argument error, // depending on whether it's checked mode or not. expect(await events.next, 1); // Did not consume event. expect(() => events.skip(-1), throwsArgumentError); expect(await events.next, 2); // Did not consume event. await events.cancel(); }); test('of 0 elements works', () async { var events = StreamQueue<int>(createStream()); expect(events.skip(0), completion(0)); expect(events.next, completion(1)); expect(events.skip(0), completion(0)); expect(events.next, completion(2)); expect(events.skip(0), completion(0)); expect(events.next, completion(3)); expect(events.skip(0), completion(0)); expect(events.next, completion(4)); expect(events.skip(0), completion(0)); expect(events.skip(5), completion(5)); expect(events.next, throwsStateError); await events.cancel(); }); test('of too many events ends at stream start', () async { var events = StreamQueue<int>(createStream()); expect(await events.skip(6), 2); await events.cancel(); }); test('of too many events after some events', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.next, 2); expect(await events.skip(6), 4); await events.cancel(); }); test('of too many events ends at stream end', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.next, 2); expect(await events.next, 3); expect(await events.next, 4); expect(await events.skip(2), 2); await events.cancel(); }); test('of events with error', () async { var events = StreamQueue<int>(createErrorStream()); expect(events.skip(4), throwsA('To err is divine!')); expect(await events.next, 4); await events.cancel(); }); test('of events with error, and skip again after', () async { var events = StreamQueue<int>(createErrorStream()); expect(events.skip(4), throwsA('To err is divine!')); expect(events.skip(2), completion(1)); await events.cancel(); }); test('multiple skips at same time complete in order.', () async { var events = StreamQueue<int>(createStream()); var skip1 = events.skip(1); var skip2 = events.skip(0); var skip3 = events.skip(4); var skip4 = events.skip(1); var index = 0; // Check that futures complete in order. Func1Required<int> sequence(expectedValue, sequenceIndex) => (value) { expect(value, expectedValue); expect(index, sequenceIndex); index++; return null; }; await Future.wait([ skip1.then(sequence(0, 0)), skip2.then(sequence(0, 1)), skip3.then(sequence(1, 2)), skip4.then(sequence(1, 3)) ]); await events.cancel(); }); }); group('take operation', () { test('as simple take of events', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.take(2), [2, 3]); expect(await events.next, 4); await events.cancel(); }); test('of 0 events', () async { var events = StreamQueue<int>(createStream()); expect(events.take(0), completion([])); expect(events.next, completion(1)); expect(events.take(0), completion([])); expect(events.next, completion(2)); expect(events.take(0), completion([])); expect(events.next, completion(3)); expect(events.take(0), completion([])); expect(events.next, completion(4)); expect(events.take(0), completion([])); expect(events.take(5), completion([])); expect(events.next, throwsStateError); await events.cancel(); }); test('with bad arguments throws', () async { var events = StreamQueue<int>(createStream()); expect(() => events.take(-1), throwsArgumentError); expect(await events.next, 1); // Did not consume event. expect(() => events.take(-1), throwsArgumentError); expect(await events.next, 2); // Did not consume event. await events.cancel(); }); test('of too many arguments', () async { var events = StreamQueue<int>(createStream()); expect(await events.take(6), [1, 2, 3, 4]); await events.cancel(); }); test('too large later', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.next, 2); expect(await events.take(6), [3, 4]); await events.cancel(); }); test('error', () async { var events = StreamQueue<int>(createErrorStream()); expect(events.take(4), throwsA('To err is divine!')); expect(await events.next, 4); await events.cancel(); }); }); group('rest operation', () { test('after single next', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.rest.toList(), [2, 3, 4]); }); test('at start', () async { var events = StreamQueue<int>(createStream()); expect(await events.rest.toList(), [1, 2, 3, 4]); }); test('at end', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.next, 2); expect(await events.next, 3); expect(await events.next, 4); expect(await events.rest.toList(), isEmpty); }); test('after end', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.next, 2); expect(await events.next, 3); expect(await events.next, 4); expect(events.next, throwsStateError); expect(await events.rest.toList(), isEmpty); }); test('after receiving done requested before', () async { var events = StreamQueue<int>(createStream()); var next1 = events.next; var next2 = events.next; var next3 = events.next; var rest = events.rest; for (var i = 0; i < 10; i++) { await flushMicrotasks(); } expect(await next1, 1); expect(await next2, 2); expect(await next3, 3); expect(await rest.toList(), [4]); }); test('with an error event error', () async { var events = StreamQueue<int>(createErrorStream()); expect(await events.next, 1); var rest = events.rest; var events2 = StreamQueue(rest); expect(await events2.next, 2); expect(events2.next, throwsA('To err is divine!')); expect(await events2.next, 4); }); test('closes the events, prevents other operations', () async { var events = StreamQueue<int>(createStream()); var stream = events.rest; expect(() => events.next, throwsStateError); expect(() => events.skip(1), throwsStateError); expect(() => events.take(1), throwsStateError); expect(() => events.rest, throwsStateError); expect(() => events.cancel(), throwsStateError); expect(stream.toList(), completion([1, 2, 3, 4])); }); test('forwards to underlying stream', () async { var cancel = Completer(); var controller = StreamController<int>(onCancel: () => cancel.future); var events = StreamQueue<int>(controller.stream); expect(controller.hasListener, isFalse); var next = events.next; expect(controller.hasListener, isTrue); expect(controller.isPaused, isFalse); controller.add(1); expect(await next, 1); expect(controller.isPaused, isTrue); var rest = events.rest; var subscription = rest.listen(null); expect(controller.hasListener, isTrue); expect(controller.isPaused, isFalse); dynamic lastEvent; subscription.onData((value) => lastEvent = value); controller.add(2); await flushMicrotasks(); expect(lastEvent, 2); expect(controller.hasListener, isTrue); expect(controller.isPaused, isFalse); subscription.pause(); expect(controller.isPaused, isTrue); controller.add(3); await flushMicrotasks(); expect(lastEvent, 2); subscription.resume(); await flushMicrotasks(); expect(lastEvent, 3); var cancelFuture = subscription.cancel(); expect(controller.hasListener, isFalse); cancel.complete(42); expect(cancelFuture, completion(42)); }); }); group('peek operation', () { test('peeks one event', () async { var events = StreamQueue<int>(createStream()); expect(await events.peek, 1); expect(await events.next, 1); expect(await events.peek, 2); expect(await events.take(2), [2, 3]); expect(await events.peek, 4); expect(await events.next, 4); // Throws at end. expect(events.peek, throwsA(anything)); await events.cancel(); }); test('multiple requests at the same time', () async { var events = StreamQueue<int>(createStream()); var result = await Future.wait( [events.peek, events.peek, events.next, events.peek, events.peek]); expect(result, [1, 1, 1, 2, 2]); await events.cancel(); }); test('sequence of requests with error', () async { var events = StreamQueue<int>(createErrorStream()); expect(await events.next, 1); expect(await events.next, 2); expect(events.peek, throwsA('To err is divine!')); // Error stays in queue. expect(events.peek, throwsA('To err is divine!')); expect(events.next, throwsA('To err is divine!')); expect(await events.next, 4); await events.cancel(); }); }); group('cancel operation', () { test('closes the events, prevents any other operation', () async { var events = StreamQueue<int>(createStream()); await events.cancel(); expect(() => events.lookAhead(1), throwsStateError); expect(() => events.next, throwsStateError); expect(() => events.peek, throwsStateError); expect(() => events.skip(1), throwsStateError); expect(() => events.take(1), throwsStateError); expect(() => events.rest, throwsStateError); expect(() => events.cancel(), throwsStateError); }); test('cancels underlying subscription when called before any event', () async { var cancelFuture = Future.value(42); var controller = StreamController<int>(onCancel: () => cancelFuture); var events = StreamQueue<int>(controller.stream); expect(await events.cancel(), 42); }); test('cancels underlying subscription, returns result', () async { var cancelFuture = Future.value(42); var controller = StreamController<int>(onCancel: () => cancelFuture); var events = StreamQueue<int>(controller.stream); controller.add(1); expect(await events.next, 1); expect(await events.cancel(), 42); }); group('with immediate: true', () { test('closes the events, prevents any other operation', () async { var events = StreamQueue<int>(createStream()); await events.cancel(immediate: true); expect(() => events.next, throwsStateError); expect(() => events.skip(1), throwsStateError); expect(() => events.take(1), throwsStateError); expect(() => events.rest, throwsStateError); expect(() => events.cancel(), throwsStateError); }); test('cancels the underlying subscription immediately', () async { var controller = StreamController<int>(); controller.add(1); var events = StreamQueue<int>(controller.stream); expect(await events.next, 1); expect(controller.hasListener, isTrue); await events.cancel(immediate: true); expect(controller.hasListener, isFalse); }); test('cancels the underlying subscription when called before any event', () async { var cancelFuture = Future.value(42); var controller = StreamController<int>(onCancel: () => cancelFuture); var events = StreamQueue<int>(controller.stream); expect(await events.cancel(immediate: true), 42); }); test('closes pending requests', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(events.next, throwsStateError); expect(events.hasNext, completion(isFalse)); await events.cancel(immediate: true); }); test('returns the result of closing the underlying subscription', () async { var controller = StreamController<int>(onCancel: () => Future.value(42)); var events = StreamQueue<int>(controller.stream); expect(await events.cancel(immediate: true), 42); }); test("listens and then cancels a stream that hasn't been listened to yet", () async { var wasListened = false; var controller = StreamController<int>(onListen: () => wasListened = true); var events = StreamQueue<int>(controller.stream); expect(wasListened, isFalse); expect(controller.hasListener, isFalse); await events.cancel(immediate: true); expect(wasListened, isTrue); expect(controller.hasListener, isFalse); }); }); }); group('hasNext operation', () { test('true at start', () async { var events = StreamQueue<int>(createStream()); expect(await events.hasNext, isTrue); }); test('true after start', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.hasNext, isTrue); }); test('true at end', () async { var events = StreamQueue<int>(createStream()); for (var i = 1; i <= 4; i++) { expect(await events.next, i); } expect(await events.hasNext, isFalse); }); test('true when enqueued', () async { var events = StreamQueue<int>(createStream()); var values = <int>[]; for (var i = 1; i <= 3; i++) { events.next.then(values.add); } expect(values, isEmpty); expect(await events.hasNext, isTrue); expect(values, [1, 2, 3]); }); test('false when enqueued', () async { var events = StreamQueue<int>(createStream()); var values = <int>[]; for (var i = 1; i <= 4; i++) { events.next.then(values.add); } expect(values, isEmpty); expect(await events.hasNext, isFalse); expect(values, [1, 2, 3, 4]); }); test('true when data event', () async { var controller = StreamController<int>(); var events = StreamQueue<int>(controller.stream); bool hasNext; events.hasNext.then((result) { hasNext = result; }); await flushMicrotasks(); expect(hasNext, isNull); controller.add(42); expect(hasNext, isNull); await flushMicrotasks(); expect(hasNext, isTrue); }); test('true when error event', () async { var controller = StreamController<int>(); var events = StreamQueue<int>(controller.stream); bool hasNext; events.hasNext.then((result) { hasNext = result; }); await flushMicrotasks(); expect(hasNext, isNull); controller.addError('BAD'); expect(hasNext, isNull); await flushMicrotasks(); expect(hasNext, isTrue); expect(events.next, throwsA('BAD')); }); test('- hasNext after hasNext', () async { var events = StreamQueue<int>(createStream()); expect(await events.hasNext, true); expect(await events.hasNext, true); expect(await events.next, 1); expect(await events.hasNext, true); expect(await events.hasNext, true); expect(await events.next, 2); expect(await events.hasNext, true); expect(await events.hasNext, true); expect(await events.next, 3); expect(await events.hasNext, true); expect(await events.hasNext, true); expect(await events.next, 4); expect(await events.hasNext, false); expect(await events.hasNext, false); }); test('- next after true', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.hasNext, true); expect(await events.next, 2); expect(await events.next, 3); }); test('- next after true, enqueued', () async { var events = StreamQueue<int>(createStream()); var responses = <Object>[]; events.next.then(responses.add); events.hasNext.then(responses.add); events.next.then(responses.add); do { await flushMicrotasks(); } while (responses.length < 3); expect(responses, [1, true, 2]); }); test('- skip 0 after true', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.hasNext, true); expect(await events.skip(0), 0); expect(await events.next, 2); }); test('- skip 1 after true', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.hasNext, true); expect(await events.skip(1), 0); expect(await events.next, 3); }); test('- skip 2 after true', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.hasNext, true); expect(await events.skip(2), 0); expect(await events.next, 4); }); test('- take 0 after true', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.hasNext, true); expect(await events.take(0), isEmpty); expect(await events.next, 2); }); test('- take 1 after true', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.hasNext, true); expect(await events.take(1), [2]); expect(await events.next, 3); }); test('- take 2 after true', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.hasNext, true); expect(await events.take(2), [2, 3]); expect(await events.next, 4); }); test('- rest after true', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.hasNext, true); var stream = events.rest; expect(await stream.toList(), [2, 3, 4]); }); test('- rest after true, at last', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.next, 2); expect(await events.next, 3); expect(await events.hasNext, true); var stream = events.rest; expect(await stream.toList(), [4]); }); test('- rest after false', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.next, 2); expect(await events.next, 3); expect(await events.next, 4); expect(await events.hasNext, false); var stream = events.rest; expect(await stream.toList(), isEmpty); }); test('- cancel after true on data', () async { var events = StreamQueue<int>(createStream()); expect(await events.next, 1); expect(await events.next, 2); expect(await events.hasNext, true); expect(await events.cancel(), null); }); test('- cancel after true on error', () async { var events = StreamQueue<int>(createErrorStream()); expect(await events.next, 1); expect(await events.next, 2); expect(await events.hasNext, true); expect(await events.cancel(), null); }); }); group('startTransaction operation produces a transaction that', () { StreamQueue<int> events; StreamQueueTransaction<int> transaction; StreamQueue<int> queue1; StreamQueue<int> queue2; setUp(() async { events = StreamQueue(createStream()); expect(await events.next, 1); transaction = events.startTransaction(); queue1 = transaction.newQueue(); queue2 = transaction.newQueue(); }); group('emits queues that', () { test('independently emit events', () async { expect(await queue1.next, 2); expect(await queue2.next, 2); expect(await queue2.next, 3); expect(await queue1.next, 3); expect(await queue1.next, 4); expect(await queue2.next, 4); expect(await queue1.hasNext, isFalse); expect(await queue2.hasNext, isFalse); }); test('queue requests for events', () async { expect(queue1.next, completion(2)); expect(queue2.next, completion(2)); expect(queue2.next, completion(3)); expect(queue1.next, completion(3)); expect(queue1.next, completion(4)); expect(queue2.next, completion(4)); expect(queue1.hasNext, completion(isFalse)); expect(queue2.hasNext, completion(isFalse)); }); test('independently emit errors', () async { events = StreamQueue(createErrorStream()); expect(await events.next, 1); transaction = events.startTransaction(); queue1 = transaction.newQueue(); queue2 = transaction.newQueue(); expect(queue1.next, completion(2)); expect(queue2.next, completion(2)); expect(queue2.next, throwsA('To err is divine!')); expect(queue1.next, throwsA('To err is divine!')); expect(queue1.next, completion(4)); expect(queue2.next, completion(4)); expect(queue1.hasNext, completion(isFalse)); expect(queue2.hasNext, completion(isFalse)); }); }); group('when rejected', () { test('further original requests use the previous state', () async { expect(await queue1.next, 2); expect(await queue2.next, 2); expect(await queue2.next, 3); await flushMicrotasks(); transaction.reject(); expect(await events.next, 2); expect(await events.next, 3); expect(await events.next, 4); expect(await events.hasNext, isFalse); }); test('pending original requests use the previous state', () async { expect(await queue1.next, 2); expect(await queue2.next, 2); expect(await queue2.next, 3); expect(events.next, completion(2)); expect(events.next, completion(3)); expect(events.next, completion(4)); expect(events.hasNext, completion(isFalse)); await flushMicrotasks(); transaction.reject(); }); test('further child requests act as though the stream was closed', () async { expect(await queue1.next, 2); transaction.reject(); expect(await queue1.hasNext, isFalse); expect(queue1.next, throwsStateError); }); test('pending child requests act as though the stream was closed', () async { expect(await queue1.next, 2); expect(queue1.hasNext, completion(isFalse)); expect(queue1.next, throwsStateError); transaction.reject(); }); // Regression test. test('pending child rest requests emit no more events', () async { var controller = StreamController(); var events = StreamQueue(controller.stream); var transaction = events.startTransaction(); var queue = transaction.newQueue(); // This should emit no more events after the transaction is rejected. queue.rest.listen(expectAsync1((_) {}, count: 3), onDone: expectAsync0(() {}, count: 0)); controller.add(1); controller.add(2); controller.add(3); await flushMicrotasks(); transaction.reject(); await flushMicrotasks(); // These shouldn't affect the result of `queue.rest.toList()`. controller.add(4); controller.add(5); }); test("child requests' cancel() may still be called explicitly", () async { transaction.reject(); await queue1.cancel(); }); test('calls to commit() or reject() fail', () async { transaction.reject(); expect(transaction.reject, throwsStateError); expect(() => transaction.commit(queue1), throwsStateError); }); test('before the transaction emits any events, does nothing', () async { var controller = StreamController(); var events = StreamQueue(controller.stream); // Queue a request before the transaction, but don't let it complete // until we're done with the transaction. expect(events.next, completion(equals(1))); events.startTransaction().reject(); expect(events.next, completion(equals(2))); await flushMicrotasks(); controller.add(1); await flushMicrotasks(); controller.add(2); await flushMicrotasks(); controller.close(); }); }); group('when committed', () { test('further original requests use the committed state', () async { expect(await queue1.next, 2); await flushMicrotasks(); transaction.commit(queue1); expect(await events.next, 3); }); test('pending original requests use the committed state', () async { expect(await queue1.next, 2); expect(events.next, completion(3)); await flushMicrotasks(); transaction.commit(queue1); }); test('further child requests act as though the stream was closed', () async { expect(await queue2.next, 2); transaction.commit(queue2); expect(await queue1.hasNext, isFalse); expect(queue1.next, throwsStateError); }); test('pending child requests act as though the stream was closed', () async { expect(await queue2.next, 2); expect(queue1.hasNext, completion(isFalse)); expect(queue1.next, throwsStateError); transaction.commit(queue2); }); test('further requests act as though the stream was closed', () async { expect(await queue1.next, 2); transaction.commit(queue1); expect(await queue1.hasNext, isFalse); expect(queue1.next, throwsStateError); }); test('cancel() may still be called explicitly', () async { expect(await queue1.next, 2); transaction.commit(queue1); await queue1.cancel(); }); test('throws if there are pending requests', () async { expect(await queue1.next, 2); expect(queue1.hasNext, completion(isTrue)); expect(() => transaction.commit(queue1), throwsStateError); }); test('calls to commit() or reject() fail', () async { transaction.commit(queue1); expect(transaction.reject, throwsStateError); expect(() => transaction.commit(queue1), throwsStateError); }); test('before the transaction emits any events, does nothing', () async { var controller = StreamController(); var events = StreamQueue(controller.stream); // Queue a request before the transaction, but don't let it complete // until we're done with the transaction. expect(events.next, completion(equals(1))); var transaction = events.startTransaction(); transaction.commit(transaction.newQueue()); expect(events.next, completion(equals(2))); await flushMicrotasks(); controller.add(1); await flushMicrotasks(); controller.add(2); await flushMicrotasks(); controller.close(); }); }); }); group('withTransaction operation', () { StreamQueue<int> events; setUp(() async { events = StreamQueue(createStream()); expect(await events.next, 1); }); test('passes a copy of the parent queue', () async { await events.withTransaction(expectAsync1((queue) async { expect(await queue.next, 2); expect(await queue.next, 3); expect(await queue.next, 4); expect(await queue.hasNext, isFalse); return true; })); }); test( 'the parent queue continues from the child position if it returns ' 'true', () async { await events.withTransaction(expectAsync1((queue) async { expect(await queue.next, 2); return true; })); expect(await events.next, 3); }); test( 'the parent queue continues from its original position if it returns ' 'false', () async { await events.withTransaction(expectAsync1((queue) async { expect(await queue.next, 2); return false; })); expect(await events.next, 2); }); test('the parent queue continues from the child position if it throws', () { expect(events.withTransaction(expectAsync1((queue) async { expect(await queue.next, 2); throw 'oh no'; })), throwsA('oh no')); expect(events.next, completion(3)); }); test('returns whether the transaction succeeded', () { expect(events.withTransaction((_) async => true), completion(isTrue)); expect(events.withTransaction((_) async => false), completion(isFalse)); }); }); group('cancelable operation', () { StreamQueue<int> events; setUp(() async { events = StreamQueue(createStream()); expect(await events.next, 1); }); test('passes a copy of the parent queue', () async { await events.cancelable(expectAsync1((queue) async { expect(await queue.next, 2); expect(await queue.next, 3); expect(await queue.next, 4); expect(await queue.hasNext, isFalse); })).value; }); test('the parent queue continues from the child position by default', () async { await events.cancelable(expectAsync1((queue) async { expect(await queue.next, 2); })).value; expect(await events.next, 3); }); test( 'the parent queue continues from the child position if an error is ' 'thrown', () async { expect( events.cancelable(expectAsync1((queue) async { expect(await queue.next, 2); throw 'oh no'; })).value, throwsA('oh no')); expect(events.next, completion(3)); }); test('the parent queue continues from the original position if canceled', () async { var operation = events.cancelable(expectAsync1((queue) async { expect(await queue.next, 2); })); operation.cancel(); expect(await events.next, 2); }); test('forwards the value from the callback', () async { expect( await events.cancelable(expectAsync1((queue) async { expect(await queue.next, 2); return 'value'; })).value, 'value'); }); }); test('all combinations sequential skip/next/take operations', () async { // Takes all combinations of two of next, skip and take, then ends with // doing rest. Each of the first rounds do 10 events of each type, // the rest does 20 elements. var eventCount = 20 * (3 * 3 + 1); var events = StreamQueue<int>(createLongStream(eventCount)); // Test expecting [startIndex .. startIndex + 9] as events using // `next`. void nextTest(startIndex) { for (var i = 0; i < 10; i++) { expect(events.next, completion(startIndex + i)); } } // Test expecting 10 events to be skipped. void skipTest(startIndex) { expect(events.skip(10), completion(0)); } // Test expecting [startIndex .. startIndex + 9] as events using // `take(10)`. void takeTest(startIndex) { expect(events.take(10), completion(List.generate(10, (i) => startIndex + i))); } var tests = [nextTest, skipTest, takeTest]; var counter = 0; // Run through all pairs of two tests and run them. for (var i = 0; i < tests.length; i++) { for (var j = 0; j < tests.length; j++) { tests[i](counter); tests[j](counter + 10); counter += 20; } } // Then expect 20 more events as a `rest` call. expect(events.rest.toList(), completion(List.generate(20, (i) => counter + i))); }); } typedef Func1Required<T> = T Function(T value); Stream<int> createStream() async* { yield 1; await flushMicrotasks(); yield 2; await flushMicrotasks(); yield 3; await flushMicrotasks(); yield 4; } Stream<int> createErrorStream() { var controller = StreamController<int>(); () async { controller.add(1); await flushMicrotasks(); controller.add(2); await flushMicrotasks(); controller.addError('To err is divine!'); await flushMicrotasks(); controller.add(4); await flushMicrotasks(); controller.close(); }(); return controller.stream; } Stream<int> createLongStream(int eventCount) async* { for (var i = 0; i < eventCount; i++) { yield i; } }
async/test/stream_queue_test.dart/0
{'file_path': 'async/test/stream_queue_test.dart', 'repo_id': 'async', 'token_count': 15334}
import 'package:flutter/widgets.dart'; import 'package:atlas/atlas.dart'; /// Callback function taking a single argument. typedef void ArgumentCallback<T>(T argument); /// The `Provider` defines the interface to which all `AtlasProviders` must conform. /// In order to implement a custom `AtlasProvider` you must simply implement `Provider` /// and set your `AtlasProvider.instance` to the instance of your custom `Provider`. abstract class Provider { /// Allows the respective map provider to declare /// what underlying map types are supported. /// /// This info can then be used to either cycle through /// MapTypes with a button on the GUI, or to set the initial /// [Atlas.mapType] property. Set<MapType> supportedMapTypes; Widget build({ final CameraPosition initialCameraPosition, final Set<Marker> markers, final Set<Circle> circles, final Set<Polygon> polygons, final Set<Polyline> polylines, final ArgumentCallback<LatLng> onTap, final ArgumentCallback<LatLng> onLongPress, final ArgumentCallback<AtlasController> onMapCreated, final ArgumentCallback<CameraPosition> onCameraPositionChanged, final bool showMyLocation, final bool showMyLocationButton, final MapType mapType, final bool showTraffic, }); }
atlas/packages/atlas/lib/src/provider.dart/0
{'file_path': 'atlas/packages/atlas/lib/src/provider.dart', 'repo_id': 'atlas', 'token_count': 373}
import 'package:atlas/atlas.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_atlas/src/google_atlas_controller.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart' as GoogleMaps; import 'package:mockito/mockito.dart'; class MockGoogleMapController extends Mock implements GoogleMaps.GoogleMapController {} main() { group('GoogleAtlasController', () { GoogleMaps.GoogleMapController googleMapController; GoogleAtlasController googleAtlasController; setUp(() { googleMapController = MockGoogleMapController(); googleAtlasController = GoogleAtlasController( controller: googleMapController, ); }); test('throws AssertionError if GoogleMaps.GoogleMapsController is null', () { try { GoogleAtlasController(controller: null); } catch (error) { expect(error, isAssertionError); } }); group('moveCamera', () { test('invokes moveCamera', () async { final CameraPosition cameraPosition = CameraPosition( target: LatLng(latitude: 10.1, longitude: -80.7), zoom: 15, ); await googleAtlasController.moveCamera(cameraPosition); verify(googleMapController.moveCamera(any)).called(1); }); }); group('updateBounds', () { test('invokes newLatLngBounds', () async { final LatLngBounds bounds = LatLngBounds( northeast: LatLng(latitude: 1, longitude: 1), southwest: LatLng(latitude: 0, longitude: 3), ); await googleAtlasController.updateBounds(bounds, 20); verify(googleMapController.moveCamera(any)).called(1); }); }); group('getLatLng', () { test('invokes getLatLng', () async { final ScreenCoordinates coordinates = ScreenCoordinates( x: 1, y: 2, ); var googleLatLng = GoogleMaps.LatLng(1.1, 2.2); when(googleMapController.getLatLng(any)) .thenAnswer((_) => Future.value(googleLatLng)); await googleAtlasController.getLatLng(coordinates); List<dynamic> results = verify(googleMapController.getLatLng(captureAny)).captured; GoogleMaps.ScreenCoordinate resultingScreenCoordinate = results.first; expect(coordinates.x, resultingScreenCoordinate.x); expect(coordinates.y, resultingScreenCoordinate.y); }); }); group('getScreenCoordinate', () { test('invokes getScreenCoordinate', () async { final LatLng inputLatLng = LatLng( latitude: 1.1, longitude: 2.2, ); var returnedGoogleScreenCoordinate = GoogleMaps.ScreenCoordinate( x: 1, y: 2, ); when(googleMapController.getScreenCoordinate(any)) .thenAnswer((_) => Future.value(returnedGoogleScreenCoordinate)); await googleAtlasController.getScreenCoordinate(inputLatLng); List<dynamic> results = verify(googleMapController.getScreenCoordinate(captureAny)) .captured; GoogleMaps.LatLng resultingLatLng = results.first; expect(inputLatLng.latitude, resultingLatLng.latitude); expect(inputLatLng.longitude, resultingLatLng.longitude); }); }); }); }
atlas/packages/google_atlas/test/widget_tests/google_atlas_controller_test.dart/0
{'file_path': 'atlas/packages/google_atlas/test/widget_tests/google_atlas_controller_test.dart', 'repo_id': 'atlas', 'token_count': 1345}
import '../platform_features.dart'; import '../source_test_data.dart'; /// Data of a ui test source. class AppSourceTestData extends SourceTestData { String sourceKey; AppSourceTestData({ required this.sourceKey, required super.duration, super.isVBR, }); @override String toString() { return 'UiSourceTestData(' 'sourceKey: $sourceKey, ' 'duration: $duration, ' 'isVBR: $isVBR' ')'; } } final _features = PlatformFeatures.instance(); // All sources are tested again in lib or platform tests, // therefore comment most of them to save testing time final audioTestDataList = [ if (_features.hasUrlSource) AppSourceTestData( sourceKey: 'url-remote-wav-1', duration: const Duration(milliseconds: 451), ), /*if (_features.hasUrlSource) AppSourceTestData( sourceKey: 'url-remote-wav-2', duration: const Duration(seconds: 1, milliseconds: 068), ),*/ /*if (_features.hasUrlSource) AppSourceTestData( sourceKey: 'url-remote-mp3-1', isVBR: true, duration: const Duration(minutes: 3, seconds: 30, milliseconds: 77), ),*/ /*if (_features.hasUrlSource) AppSourceTestData( sourceKey: 'url-remote-mp3-2', duration: const Duration(minutes: 1, seconds: 34, milliseconds: 119), ),*/ if (_features.hasUrlSource && _features.hasPlaylistSourceType) AppSourceTestData( sourceKey: 'url-remote-m3u8', duration: null, ), /*if (_features.hasUrlSource) AppSourceTestData( sourceKey: 'url-remote-mpga', duration: null, ),*/ /*if (_features.hasAssetSource) AppSourceTestData( sourceKey: 'asset-wav', duration: const Duration(seconds: 1, milliseconds: 068), ),*/ /*if (_features.hasAssetSource) AppSourceTestData( sourceKey: 'asset-mp3', duration: const Duration(minutes: 1, seconds: 34, milliseconds: 119), ),*/ /*if (_features.hasBytesSource) AppSourceTestData( sourceKey: 'bytes-local', duration: const Duration(seconds: 1, milliseconds: 068), ),*/ /*if (_features.hasBytesSource) AppSourceTestData( sourceKey: 'bytes-remote', duration: const Duration(minutes: 3, seconds: 30, milliseconds: 76), ),*/ ];
audioplayers/packages/audioplayers/example/integration_test/app/app_source_test_data.dart/0
{'file_path': 'audioplayers/packages/audioplayers/example/integration_test/app/app_source_test_data.dart', 'repo_id': 'audioplayers', 'token_count': 866}
import 'package:flutter/material.dart'; class Cbx extends StatelessWidget { final String label; final bool value; final void Function({required bool? value}) update; const Cbx( this.label, this.update, { required this.value, super.key, }); @override Widget build(BuildContext context) { return CheckboxListTile( title: Text(label), value: value, onChanged: (v) => update(value: v), ); } }
audioplayers/packages/audioplayers/example/lib/components/cbx.dart/0
{'file_path': 'audioplayers/packages/audioplayers/example/lib/components/cbx.dart', 'repo_id': 'audioplayers', 'token_count': 170}
import 'package:audioplayers/audioplayers.dart'; import 'package:audioplayers_example/components/btn.dart'; import 'package:flutter/material.dart'; class LoggerTab extends StatefulWidget { final AudioPlayer player; const LoggerTab({ required this.player, super.key, }); @override LoggerTabState createState() => LoggerTabState(); } class LoggerTabState extends State<LoggerTab> with AutomaticKeepAliveClientMixin<LoggerTab> { AudioLogLevel get currentLogLevel => AudioLogger.logLevel; set currentLogLevel(AudioLogLevel level) { AudioLogger.logLevel = level; } List<Log> logs = []; List<Log> globalLogs = []; @override void initState() { super.initState(); AudioPlayer.global.onLog.listen( (message) { if (AudioLogLevel.info.level <= currentLogLevel.level) { setState(() { globalLogs.add(Log(message, level: AudioLogLevel.info)); }); } }, onError: (Object o, [StackTrace? stackTrace]) { if (AudioLogLevel.error.level <= currentLogLevel.level) { setState(() { globalLogs.add( Log( AudioLogger.errorToString(o, stackTrace), level: AudioLogLevel.error, ), ); }); } }, ); widget.player.onLog.listen( (message) { if (AudioLogLevel.info.level <= currentLogLevel.level) { final msg = '$message\nSource: ${widget.player.source}'; setState(() { logs.add(Log(msg, level: AudioLogLevel.info)); }); } }, onError: (Object o, [StackTrace? stackTrace]) { if (AudioLogLevel.error.level <= currentLogLevel.level) { setState(() { logs.add( Log( AudioLogger.errorToString( AudioPlayerException(widget.player, cause: o), stackTrace, ), level: AudioLogLevel.error, ), ); }); } }, ); } @override Widget build(BuildContext context) { super.build(context); return Padding( padding: const EdgeInsets.all(16), child: Column( children: [ ListTile( title: Text(currentLogLevel.toString()), subtitle: const Text('Log Level'), ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: AudioLogLevel.values .map( (level) => Btn( txt: level.toString().replaceAll('AudioLogLevel.', ''), onPressed: () { setState(() => currentLogLevel = level); }, ), ) .toList(), ), const Divider(color: Colors.black), Expanded( child: LogView( title: 'Player Logs:', logs: logs, onDelete: () => setState(() { logs.clear(); }), ), ), const Divider(color: Colors.black), Expanded( child: LogView( title: 'Global Logs:', logs: globalLogs, onDelete: () => setState(() { globalLogs.clear(); }), ), ), ], ), ); } @override bool get wantKeepAlive => true; } class LogView extends StatelessWidget { final String title; final List<Log> logs; final VoidCallback onDelete; const LogView({ required this.logs, required this.title, required this.onDelete, super.key, }); @override Widget build(BuildContext context) { return Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(title), IconButton(onPressed: onDelete, icon: const Icon(Icons.delete)), ], ), Expanded( child: ListView( children: logs .map( (log) => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SelectableText( '${log.level}: ${log.message}', style: log.level == AudioLogLevel.error ? const TextStyle(color: Colors.red) : null, ), Divider(color: Colors.grey.shade400), ], ), ) .toList(), ), ), ], ); } } class Log { Log(this.message, {required this.level}); final AudioLogLevel level; final String message; }
audioplayers/packages/audioplayers/example/lib/tabs/logger.dart/0
{'file_path': 'audioplayers/packages/audioplayers/example/lib/tabs/logger.dart', 'repo_id': 'audioplayers', 'token_count': 2556}
// ignore_for_file: avoid_print import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; import 'package:async/async.dart'; import 'package:shelf/shelf.dart'; import 'package:shelf_router/shelf_router.dart'; class StreamRoute { static const timesRadioUrl = 'https://timesradio.wireless.radio/stream'; static const mpegRecordPath = 'public/files/live_streams/mpeg-record.bin'; final mpegStreamController = StreamController<List<int>>.broadcast(); StreamRoute({bool isLiveMode = false, bool isRecordMode = false}) : assert(!isRecordMode || isLiveMode) { if (isRecordMode) { recordLiveStream(); } if (isLiveMode) { playLiveStream(); } else { playLocalStream(); } } Future<void> recordLiveStream() async { const recordingTime = Duration(seconds: 10); // Save lists of bytes in a file, where each first four bytes indicate the // length of its following list. final recordOutput = File(mpegRecordPath); final fileBytes = <int>[]; final mpegSub = mpegStreamController.stream.listen((bytes) async { fileBytes.addAll([...int32ToBytes(bytes.length), ...bytes]); }); Future.delayed(recordingTime).then((value) async { print('Recording finished'); await mpegSub.cancel(); await recordOutput.writeAsBytes( fileBytes, flush: true, ); }); } Uint8List int32ToBytes(int value) => Uint8List(4)..buffer.asInt32List()[0] = value; int bytesToInt32(List<int> bytes) => Uint8List.fromList(bytes).buffer.asInt32List()[0]; Future<void> playLiveStream() async { final client = HttpClient(); final request = await client.getUrl(Uri.parse(timesRadioUrl)); final response = await request.close(); mpegStreamController.addStream(response); } Future<void> playLocalStream() async { final recordInput = File(mpegRecordPath); final streamReader = ChunkedStreamReader(recordInput.openRead()); final fileSize = await recordInput.length(); var position = 0; final mpegBytes = <List<int>>[]; while (position < fileSize) { final chunkLength = bytesToInt32(await streamReader.readChunk(4)); final chunk = await streamReader.readChunk(chunkLength); position += chunkLength + 4; mpegBytes.add(chunk); } var mpegBytesPosition = 0; Timer.periodic(const Duration(milliseconds: 150), (timer) { mpegStreamController.add(mpegBytes[mpegBytesPosition]); mpegBytesPosition++; if (mpegBytesPosition >= mpegBytes.length) { mpegBytesPosition = 0; } }); } Router get router { final router = Router(); router.get('/wav', (Request request) async { final range = request.headers['range']; const contentType = {'Content-Type': 'audio/wav'}; final file = File('public/files/audio/laser.wav'); if (range != null) { final fileSize = await file.length(); final parts = range.replaceFirst('bytes=', '').split('-'); final start = int.parse(parts[0]); final end = int.tryParse(parts[1]) ?? fileSize - 1; if (start >= fileSize) { return Response( 416, body: 'Requested range not satisfiable\n$start >= $fileSize', ); } final streamReader = ChunkedStreamReader<int>(file.openRead()); final chunkLength = end - start + 1; final head = { 'Content-Range': 'bytes $start-$end/$fileSize', 'Accept-Ranges': 'bytes', 'Content-Length': '$chunkLength', ...contentType, }; if (start > 0) { await streamReader.readChunk(start); } final res = Response.ok( await streamReader.readChunk(chunkLength), headers: head, ); return res; } else { final bytes = await file.readAsBytes(); final fileSize = bytes.length; final head = { 'Content-Length': '$fileSize', ...contentType, }; final res = Response.ok( bytes.toList(), headers: head, ); return res; } }); router.get('/mpeg', (Request request) async { const contentType = {'Content-Type': 'audio/mpeg'}; final head = { 'Accept-Ranges': 'bytes', ...contentType, }; final res = Response.ok( mpegStreamController.stream, headers: head, ); return res; }); return router; } Handler get pipeline { return const Pipeline().addHandler(router); } }
audioplayers/packages/audioplayers/example/server/bin/stream_route.dart/0
{'file_path': 'audioplayers/packages/audioplayers/example/server/bin/stream_route.dart', 'repo_id': 'audioplayers', 'token_count': 1850}
import 'dart:async'; import 'package:audioplayers/audioplayers.dart'; import 'package:flutter/foundation.dart'; import 'package:synchronized/synchronized.dart'; /// Represents a function that can stop an audio playing. typedef StopFunction = Future<void> Function(); /// An AudioPool is a provider of AudioPlayers that are pre-loaded with an asset /// to minimize delays. /// /// All AudioPlayers are loaded with the same audio [source]. /// If you want multiple sounds use multiple [AudioPool]s. /// /// Use this class if you for example have extremely quick firing, repetitive /// or simultaneous sounds. class AudioPool { @visibleForTesting final Map<String, AudioPlayer> currentPlayers = {}; @visibleForTesting final List<AudioPlayer> availablePlayers = []; /// Instance of [AudioCache] to be used by all players. final AudioCache audioCache; /// The source of the sound for this pool. final Source source; /// The minimum numbers of players, this is the amount of players that the /// pool is initialized with. final int minPlayers; /// The maximum number of players to be kept in the pool. /// /// If `start` is called after the pool is full there will still be new /// [AudioPlayer]s created, but once they are stopped they will not be /// returned to the pool. final int maxPlayers; final Lock _lock = Lock(); AudioPool._({ required this.minPlayers, required this.maxPlayers, required this.source, AudioCache? audioCache, }) : audioCache = audioCache ?? AudioCache.instance; /// Creates an [AudioPool] instance with the given parameters. static Future<AudioPool> create({ required Source source, required int maxPlayers, AudioCache? audioCache, int minPlayers = 1, }) async { final instance = AudioPool._( source: source, audioCache: audioCache, maxPlayers: maxPlayers, minPlayers: minPlayers, ); final players = await Future.wait( List.generate(minPlayers, (_) => instance._createNewAudioPlayer()), ); return instance..availablePlayers.addAll(players); } /// Creates an [AudioPool] instance with the asset from the given [path]. static Future<AudioPool> createFromAsset({ required String path, required int maxPlayers, AudioCache? audioCache, int minPlayers = 1, }) async { return create( source: AssetSource(path), audioCache: audioCache, minPlayers: minPlayers, maxPlayers: maxPlayers, ); } /// Starts playing the audio, returns a function that can stop the audio. Future<StopFunction> start({double volume = 1.0}) async { return _lock.synchronized(() async { if (availablePlayers.isEmpty) { availablePlayers.add(await _createNewAudioPlayer()); } final player = availablePlayers.removeAt(0); currentPlayers[player.playerId] = player; await player.setVolume(volume); await player.resume(); late StreamSubscription<void> subscription; Future<void> stop() { return _lock.synchronized(() async { final removedPlayer = currentPlayers.remove(player.playerId); if (removedPlayer != null) { subscription.cancel(); await removedPlayer.stop(); if (availablePlayers.length >= maxPlayers) { await removedPlayer.release(); } else { availablePlayers.add(removedPlayer); } } }); } subscription = player.onPlayerComplete.listen((_) => stop()); return stop; }); } Future<AudioPlayer> _createNewAudioPlayer() async { final player = AudioPlayer()..audioCache = audioCache; await player.setSource(source); await player.setReleaseMode(ReleaseMode.stop); return player; } /// Disposes the audio pool. Then it cannot be used anymore. Future<void> dispose() => Future.wait(availablePlayers.map((e) => e.dispose())); }
audioplayers/packages/audioplayers/lib/src/audio_pool.dart/0
{'file_path': 'audioplayers/packages/audioplayers/lib/src/audio_pool.dart', 'repo_id': 'audioplayers', 'token_count': 1310}
import 'package:audioplayers_platform_interface/src/api/audio_context.dart'; import 'package:audioplayers_platform_interface/src/api/global_audio_event.dart'; import 'package:audioplayers_platform_interface/src/global_audioplayers_platform_interface.dart'; import 'package:audioplayers_platform_interface/src/map_extension.dart'; import 'package:audioplayers_platform_interface/src/method_channel_extension.dart'; import 'package:flutter/services.dart'; class GlobalAudioplayersPlatform extends GlobalAudioplayersPlatformInterface with MethodChannelGlobalAudioplayersPlatform, EventChannelGlobalAudioplayersPlatform { GlobalAudioplayersPlatform(); } mixin MethodChannelGlobalAudioplayersPlatform implements MethodChannelGlobalAudioplayersPlatformInterface { static const MethodChannel _globalMethodChannel = MethodChannel('xyz.luan/audioplayers.global'); @override Future<void> setGlobalAudioContext(AudioContext ctx) { return _globalMethodChannel.call( 'setAudioContext', ctx.toJson(), ); } @override Future<void> emitGlobalLog(String message) { return _globalMethodChannel.call( 'emitLog', <String, dynamic>{ 'message': message, }, ); } @override Future<void> emitGlobalError(String code, String message) { return _globalMethodChannel.call( 'emitError', <String, dynamic>{ 'code': code, 'message': message, }, ); } } mixin EventChannelGlobalAudioplayersPlatform implements EventChannelGlobalAudioplayersPlatformInterface { static const _globalEventChannel = EventChannel('xyz.luan/audioplayers.global/events'); @override Stream<GlobalAudioEvent> getGlobalEventStream() { return _globalEventChannel.receiveBroadcastStream().map((dynamic event) { final map = event as Map<dynamic, dynamic>; final eventType = map.getString('event'); switch (eventType) { case 'audio.onLog': final value = map.getString('value'); return GlobalAudioEvent( eventType: GlobalAudioEventType.log, logMessage: value, ); default: throw UnimplementedError( 'Global Event Method does not exist $eventType', ); } }); } }
audioplayers/packages/audioplayers_platform_interface/lib/src/global_audioplayers_platform.dart/0
{'file_path': 'audioplayers/packages/audioplayers_platform_interface/lib/src/global_audioplayers_platform.dart', 'repo_id': 'audioplayers', 'token_count': 848}
import 'dart:async'; import 'package:audioplayers_platform_interface/audioplayers_platform_interface.dart'; import 'package:flutter/services.dart'; class WebGlobalAudioplayersPlatform extends GlobalAudioplayersPlatformInterface { final _eventStreamController = StreamController<GlobalAudioEvent>.broadcast(); @override Future<void> setGlobalAudioContext(AudioContext ctx) async { _eventStreamController.add( const GlobalAudioEvent( eventType: GlobalAudioEventType.log, logMessage: 'Setting global AudioContext is not supported on Web', ), ); } @override Stream<GlobalAudioEvent> getGlobalEventStream() { return _eventStreamController.stream; } @override Future<void> emitGlobalLog(String message) async { _eventStreamController.add( GlobalAudioEvent( eventType: GlobalAudioEventType.log, logMessage: message, ), ); } @override Future<void> emitGlobalError(String code, String message) async { _eventStreamController .addError(PlatformException(code: code, message: message)); } }
audioplayers/packages/audioplayers_web/lib/global_audioplayers_web.dart/0
{'file_path': 'audioplayers/packages/audioplayers_web/lib/global_audioplayers_web.dart', 'repo_id': 'audioplayers', 'token_count': 370}
import 'package:benckmark/item.dart'; import 'package:get/get.dart'; class Controller extends GetController { @override onInit() async { for (int i = 0; i < 10; i++) { await Future.delayed(Duration(milliseconds: 500)); addItem(Item(title: DateTime.now().toString())); } print("It's done. Print now!"); super.onInit(); } final items = List<Item>.of(sampleItems); void addItem(Item item) { items.add(item); update(); } }
benchmarks/state_managers/lib/_get/_store.dart/0
{'file_path': 'benchmarks/state_managers/lib/_get/_store.dart', 'repo_id': 'benchmarks', 'token_count': 182}
import 'dart:async'; import 'dart:convert'; import 'package:uuid/uuid.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:play_games/play_games.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'async_saver.dart'; import 'buy.dart'; import 'iap.dart'; import 'options.dart'; import 'play_user.dart'; import 'skin_list.dart'; import 'stats.dart'; part 'data.g.dart'; @JsonSerializable() class SavedData { Options options; Stats stats; Buy buy; bool showTutorial; SavedData() { showTutorial = true; options = Options(); stats = Stats(); buy = Buy(); } factory SavedData.fromJson(Map<String, dynamic> json) => _$SavedDataFromJson(json); Map<String, dynamic> toJson() => _$SavedDataToJson(this); static SavedData merge(SavedData s1, SavedData s2) { return SavedData() ..showTutorial = s1.showTutorial || s2.showTutorial ..options = s1.options ?? s2.options ..stats = Stats.merge(s1.stats, s2.stats) ..buy = Buy.merge(s1.buy, s2.buy); } } class Data { static const SAVE_NAME = 'bgug.data.v3'; static SkinList skinList; static SavedData _data; static Options get options => _data.options ??= Options(); static set options(Options options) => _data.options = options ?? Options(); static Stats get stats => _data.stats ??= Stats(); static Buy get buy => _data.buy ??= Buy(); static PlayUser _user; static PlayUser get user => _user; static set user(PlayUser user) { _user = user; userStream.values.forEach((fn) => fn(user)); } static Options currentOptions; static bool pristine = true; static bool isSaving = false; static bool hasOpened = false; static Map<String, void Function(PlayUser)> userStream = {}; static String addUserCallback(void Function(PlayUser) fn) { final key = Uuid().v4(); userStream[key] = fn; return key; } static void removeUserCallback(String key) { userStream.remove(key); } static void checkAchievementsAndSkins() { if (stats.totalDistance >= 21000) { _achievement('achievement_half_marathoner'); } if (stats.totalDistance >= 42000) { _achievement('achievement_marathoner'); if (!buy.skinsOwned.contains('marathonist.png')) { buy.skinsOwned.add('marathonist.png'); } } if (stats.totalJumps > 500) { _achievement('achievement_jumper'); } if (stats.totalJumps > 1000) { _achievement('achievement_super_jumper'); if (!buy.skinsOwned.contains('jumping.png')) { buy.skinsOwned.add('jumping.png'); } } if (buy.skinsOwned.length > 1) { _achievement('achievement_the_disguised_bot'); } if (buy.skinsOwned.length > 10) { _achievement('achievement_a_small_collection'); } if (buy.skinsOwned.length > 20) { _achievement('achievement_the_collector'); } if (buy.skinsOwned.length > 30) { _achievement('achievement_the_completionist'); } } static Future _achievement(String name) async { if (user != null) { await PlayGames.unlockAchievementByName(name); } } static Future loadHardData() { return SkinList.fetch().then((r) => skinList = r); } static Future loadLocalSoftData() async { pristine = true; _data = await Data.fetch(true); validatePro(IAP.pro); } static bool get hasData => _data != null; static bool get playGames => user != null; static Future<bool> getAndToggleShowTutorial() async { if (_data.showTutorial) { _data.showTutorial = false; await save(); return true; } return false; } static Future save() async { if (isSaving) { print('will save in a while!'); return Future.delayed(const Duration(seconds: 3)).then((_) => save()); } isSaving = true; pristine = false; final data = json.encode(_data.toJson()); final result = await _saveInternal(data); print('Saved data! playGames: $playGames'); isSaving = false; return result; } static Future<Object> _saveInternal(String data) async { if (playGames) { if (!hasOpened) { await _openInternal(); hasOpened = true; } print('Saving $data'); final status = await PlayGames.saveSnapshot(SAVE_NAME, data); print('Saved $status'); return await _openInternal(); } else { final SharedPreferences prefs = await SharedPreferences.getInstance(); return prefs.setString(SAVE_NAME, data); } } static Future<Snapshot> _openInternal() async { try { return await PlayGames.openSnapshot(SAVE_NAME); } catch (ex) { if (ex is CloudSaveConflictError) { final result = _mergeInternal(ex.local, ex.server); return await PlayGames.resolveSnapshotConflict(SAVE_NAME, ex.conflictId, result); } rethrow; } } static Future<SavedData> fetch(bool createNew) async { final loaded = await _doFetch(createNew); loaded?.stats?.firstTimeScoreCheck(); return loaded; } static Future<SavedData> _doFetch(bool createNew) async { if (playGames) { return await _fetchFromPlayGames(createNew); } else { return await _fetchFromSharedPreferences(createNew); } } static Future<SavedData> _fetchFromPlayGames(bool createNew) async { final snap = await _openInternal(); if (snap.content == null || snap.content.trim().isEmpty) { return createNew ? SavedData() : null; } hasOpened = true; return SavedData.fromJson(json.decode(snap.content)); } static Future<SavedData> _fetchFromSharedPreferences(bool createNew) async { final SharedPreferences prefs = await SharedPreferences.getInstance(); final jsonStr = prefs.getString(SAVE_NAME); if (jsonStr == null) { return createNew ? SavedData() : null; } return SavedData.fromJson(json.decode(jsonStr)); } static void forceData(SavedData data) { pristine = false; _data = data; validatePro(IAP.pro); } static void mergeData(SavedData other) { _data = SavedData.merge(other, _data); validatePro(IAP.pro); } static void setData(SavedData data) { if (Data.pristine) { Data.forceData(data); } else { Data.mergeData(data); } } static String _mergeInternal(Snapshot local, Snapshot server) { final s1 = SavedData.fromJson(json.decode(local.content)); final s2 = SavedData.fromJson(json.decode(server.content)); return json.encode(SavedData.merge(s1, s2).toJson()); } static void saveAsync() async { final saver = AsyncSaver.start(); await Data.save(); saver.stop(); } static void validatePro(bool pro) { const goldSkin = 'gold.png'; if (pro == true) { if (!buy.skinsOwned.contains(goldSkin)) { buy.skinsOwned.add(goldSkin); } } else { buy.skinsOwned.remove(goldSkin); if (buy.selectedSkin == goldSkin) { buy.selectedSkin = 'asimov.png'; } } } }
bgug/lib/data.dart/0
{'file_path': 'bgug/lib/data.dart', 'repo_id': 'bgug', 'token_count': 2750}
import 'dart:typed_data'; import '../bitmap.dart'; import 'operation.dart'; class BitmapRotate implements BitmapOperation { final _Rotate _rotate; BitmapRotate.rotateClockwise() : _rotate = _RotateClockwise(); BitmapRotate.rotate180() : _rotate = _Rotate180(); BitmapRotate.rotateCounterClockwise() : _rotate = _RotateCounterClockwise(); @override Bitmap applyTo(Bitmap bitmap) { return _rotate.doRotate(bitmap); } } abstract class _Rotate { Bitmap doRotate(Bitmap bitmap); } class _RotateClockwise implements _Rotate { @override Bitmap doRotate(Bitmap bitmap) { final Bitmap rotated = Bitmap.fromHeadless( bitmap.height, bitmap.width, Uint8List(bitmap.width * bitmap.height * RGBA32BitmapHeader.pixelLength), ); _rotateClockwiseCore( bitmap.content, rotated.content, bitmap.width, bitmap.height, ); return rotated; } void _rotateClockwiseCore( Uint8List sourceBmp, Uint8List destBmp, int width, int height, ) { assert(width > 0 && height > 0); const pixelLength = RGBA32BitmapHeader.pixelLength; final int lineLength = width * pixelLength; for (int line = 0; line < height; line++) { final startOfLine = line * lineLength; for (int column = 0; column < width; column++) { final int columnStart = column * pixelLength; final int pixelStart = startOfLine + columnStart; final int pixelEnd = pixelStart + pixelLength; final int rotatedStart = (height * column) * pixelLength + (height - line - 1) * pixelLength; final int rotatedEnd = rotatedStart + pixelLength; final Uint8List sourcePixel = sourceBmp.sublist(pixelStart, pixelEnd); destBmp.setRange(rotatedStart, rotatedEnd, sourcePixel); } } } } class _RotateCounterClockwise implements _Rotate { @override Bitmap doRotate(Bitmap bitmap) { final Bitmap rotated = Bitmap.fromHeadless( bitmap.height, bitmap.width, Uint8List(bitmap.width * bitmap.height * RGBA32BitmapHeader.pixelLength), ); _rotateCounterClockwiseCore( bitmap.content, rotated.content, bitmap.width, bitmap.height, ); return rotated; } void _rotateCounterClockwiseCore( Uint8List sourceBmp, Uint8List destBmp, int width, int height, ) { assert(width > 0 && height > 0); const pixelLength = RGBA32BitmapHeader.pixelLength; final int lineLength = width * pixelLength; for (int line = 0; line < height; line++) { final startOfLine = line * lineLength; for (int column = 0; column < width; column++) { final int columnStart = column * pixelLength; final int pixelStart = startOfLine + columnStart; final int pixelEnd = pixelStart + pixelLength; final int rotatedStart = (height * (width - column - 1)) * pixelLength + line * pixelLength; final int rotatedEnd = rotatedStart + pixelLength; final Uint8List sourcePixel = sourceBmp.sublist(pixelStart, pixelEnd); destBmp.setRange(rotatedStart, rotatedEnd, sourcePixel); } } } } class _Rotate180 implements _Rotate { @override Bitmap doRotate(Bitmap bitmap) { final Bitmap rotated = Bitmap.fromHeadless( bitmap.height, bitmap.width, Uint8List(bitmap.width * bitmap.height * RGBA32BitmapHeader.pixelLength), ); _rotate180Core( bitmap.content, rotated.content, bitmap.width, bitmap.height, ); return rotated; } void _rotate180Core( Uint8List sourceBmp, Uint8List destBmp, int width, int height, ) { assert(width > 0 && height > 0); const pixelLength = RGBA32BitmapHeader.pixelLength; final int lineLength = width * pixelLength; for (int line = 0; line < height; line++) { final startOfLine = line * lineLength; for (int column = 0; column < width; column++) { final int columnStart = column * pixelLength; final int pixelStart = startOfLine + columnStart; final int pixelEnd = pixelStart + pixelLength; final int rotatedStart = width * (height - line - 1) * pixelLength + (width - column - 1) * pixelLength; final int rotatedEnd = rotatedStart + pixelLength; final Uint8List sourcePixel = sourceBmp.sublist(pixelStart, pixelEnd); destBmp.setRange(rotatedStart, rotatedEnd, sourcePixel); } } } }
bitmap/lib/src/operation/rotation.dart/0
{'file_path': 'bitmap/lib/src/operation/rotation.dart', 'repo_id': 'bitmap', 'token_count': 1744}
blank_issues_enabled: false
bloc/.github/ISSUE_TEMPLATE/config.yml/0
{'file_path': 'bloc/.github/ISSUE_TEMPLATE/config.yml', 'repo_id': 'bloc', 'token_count': 7}
name: docs on: push: branches: - master paths: - '.github/workflows/docs.yaml' - 'README.md' - 'docs/*' jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: JasonEtco/create-an-issue@v2 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: filename: .github/DOCS_ISSUE_TEMPLATE.md
bloc/.github/workflows/docs.yaml/0
{'file_path': 'bloc/.github/workflows/docs.yaml', 'repo_id': 'bloc', 'token_count': 207}
import 'package:flutter/widgets.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../{{name.snakeCase()}}.dart'; class {{name.pascalCase()}}Page extends StatelessWidget { const {{name.pascalCase()}}Page({super.key}); @override Widget build(BuildContext context) { {{#is_bloc}}{{> bloc_provider }}{{/is_bloc}}{{^is_bloc}}{{> cubit_bloc_provider }}{{/is_bloc}} } } class {{name.pascalCase()}}View extends StatelessWidget { const {{name.pascalCase()}}View({super.key}); @override Widget build(BuildContext context) { {{#is_bloc}}{{> bloc_builder }}{{/is_bloc}}{{^is_bloc}}{{> cubit_bloc_builder }}{{/is_bloc}} } }
bloc/bricks/flutter_bloc_feature/__brick__/{{name.snakeCase()}}/view/{{name.snakeCase()}}_page.dart/0
{'file_path': 'bloc/bricks/flutter_bloc_feature/__brick__/{{name.snakeCase()}}/view/{{name.snakeCase()}}_page.dart', 'repo_id': 'bloc', 'token_count': 257}
// ignore_for_file: prefer_const_constructors import 'package:flutter_bloc_with_stream/bloc/ticker_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('TickerEvent', () { group('TickerStarted', () { test('supports value comparison', () { expect(TickerStarted(), equals(TickerStarted())); }); }); }); }
bloc/examples/flutter_bloc_with_stream/test/bloc/ticker_event_test.dart/0
{'file_path': 'bloc/examples/flutter_bloc_with_stream/test/bloc/ticker_event_test.dart', 'repo_id': 'bloc', 'token_count': 144}
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_complex_list/complex_list/complex_list.dart'; import 'package:flutter_complex_list/repository.dart'; class App extends MaterialApp { App({super.key, required Repository repository}) : super( home: RepositoryProvider.value( value: repository, child: const ComplexListPage(), ), ); }
bloc/examples/flutter_complex_list/lib/app.dart/0
{'file_path': 'bloc/examples/flutter_complex_list/lib/app.dart', 'repo_id': 'bloc', 'token_count': 180}
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_complex_list/complex_list/complex_list.dart'; import 'package:flutter_complex_list/repository.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; class MockRepository extends Mock implements Repository {} class MockComplexListCubit extends MockCubit<ComplexListState> implements ComplexListCubit {} class FakeComplexListState extends Fake implements ComplexListState {} extension on WidgetTester { Future<void> pumpListPage(Repository repository) { return pumpWidget( MaterialApp( home: RepositoryProvider.value( value: repository, child: const ComplexListPage(), ), ), ); } Future<void> pumpListView(ComplexListCubit listCubit) { return pumpWidget( MaterialApp( home: BlocProvider.value( value: listCubit, child: const ComplexListView(), ), ), ); } } void main() { const mockItems = [ Item(id: '1', value: 'Item 1'), Item(id: '2', value: 'Item 2'), Item(id: '3', value: 'Item 3'), ]; late Repository repository; late ComplexListCubit listCubit; setUpAll(() { registerFallbackValue(FakeComplexListState()); }); setUp(() { repository = MockRepository(); listCubit = MockComplexListCubit(); }); group('ListPage', () { testWidgets('renders ComplexListView', (tester) async { when(() => repository.fetchItems()).thenAnswer((_) async => []); await tester.pumpListPage(repository); expect(find.byType(ComplexListView), findsOneWidget); }); }); group('ComplexListView', () { testWidgets( 'renders CircularProgressIndicator while ' 'waiting for items to load', (tester) async { when(() => listCubit.state).thenReturn(const ComplexListState.loading()); await tester.pumpListView(listCubit); expect(find.byType(CircularProgressIndicator), findsOneWidget); }); testWidgets( 'renders error text ' 'when items fail to load', (tester) async { when(() => listCubit.state).thenReturn(const ComplexListState.failure()); await tester.pumpListView(listCubit); expect(find.text('Oops something went wrong!'), findsOneWidget); }); testWidgets( 'renders ComplexListView after items ' 'are finished loading', (tester) async { when(() => listCubit.state).thenReturn( const ComplexListState.success(mockItems), ); await tester.pumpListView(listCubit); expect(find.byType(ComplexListView), findsOneWidget); }); testWidgets( 'renders no content text when ' 'no items are present', (tester) async { when(() => listCubit.state).thenReturn( const ComplexListState.success([]), ); await tester.pumpListView(listCubit); expect(find.text('no content'), findsOneWidget); }); testWidgets('renders three ItemTiles', (tester) async { when(() => listCubit.state).thenReturn( const ComplexListState.success(mockItems), ); await tester.pumpListView(listCubit); expect(find.byType(ItemTile), findsNWidgets(3)); }); testWidgets('deletes first item', (tester) async { when(() => listCubit.state).thenReturn( const ComplexListState.success(mockItems), ); when(() => listCubit.deleteItem('1')).thenAnswer((_) async {}); await tester.pumpListView(listCubit); await tester.tap(find.byIcon(Icons.delete).first); verify(() => listCubit.deleteItem('1')).called(1); }); }); group('ItemTile', () { testWidgets('renders id and value text', (tester) async { const mockItem = Item(id: '1', value: 'Item 1'); when(() => listCubit.state).thenReturn( const ComplexListState.success([mockItem]), ); await tester.pumpListView(listCubit); expect(find.text('#1'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); }); testWidgets( 'renders delete icon button ' 'when item is not being deleted', (tester) async { const mockItem = Item(id: '1', value: 'Item 1'); when(() => listCubit.state).thenReturn( const ComplexListState.success([mockItem]), ); await tester.pumpListView(listCubit); expect(find.byIcon(Icons.delete), findsOneWidget); }); testWidgets( 'renders CircularProgressIndicator ' 'when item is being deleting', (tester) async { const mockItem = Item(id: '1', value: 'Item 1', isDeleting: true); when(() => listCubit.state).thenReturn( const ComplexListState.success([mockItem]), ); await tester.pumpListView(listCubit); expect(find.byType(CircularProgressIndicator), findsOneWidget); }); }); }
bloc/examples/flutter_complex_list/test/complex_list/view/complex_list_page_test.dart/0
{'file_path': 'bloc/examples/flutter_complex_list/test/complex_list/view/complex_list_page_test.dart', 'repo_id': 'bloc', 'token_count': 1954}
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_counter/counter/counter.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('CounterCubit', () { test('initial state is 0', () { expect(CounterCubit().state, 0); }); group('increment', () { blocTest<CounterCubit, int>( 'emits [1] when state is 0', build: CounterCubit.new, act: (cubit) => cubit.increment(), expect: () => const <int>[1], ); blocTest<CounterCubit, int>( 'emits [1, 2] when state is 0 and invoked twice', build: CounterCubit.new, act: (cubit) => cubit ..increment() ..increment(), expect: () => const <int>[1, 2], ); blocTest<CounterCubit, int>( 'emits [42] when state is 41', build: CounterCubit.new, seed: () => 41, act: (cubit) => cubit.increment(), expect: () => const <int>[42], ); }); group('decrement', () { blocTest<CounterCubit, int>( 'emits [-1] when state is 0', build: CounterCubit.new, act: (cubit) => cubit.decrement(), expect: () => const <int>[-1], ); blocTest<CounterCubit, int>( 'emits [-1, -2] when state is 0 and invoked twice', build: CounterCubit.new, act: (cubit) => cubit ..decrement() ..decrement(), expect: () => const <int>[-1, -2], ); blocTest<CounterCubit, int>( 'emits [42] when state is 43', build: CounterCubit.new, seed: () => 43, act: (cubit) => cubit.decrement(), expect: () => const <int>[42], ); }); }); }
bloc/examples/flutter_counter/test/counter/cubit/counter_cubit_test.dart/0
{'file_path': 'bloc/examples/flutter_counter/test/counter/cubit/counter_cubit_test.dart', 'repo_id': 'bloc', 'token_count': 821}
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dynamic_form/new_car/new_car.dart'; import 'package:flutter_dynamic_form/new_car_repository.dart'; class NewCarPage extends StatelessWidget { const NewCarPage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Flutter Dynamic Form')), body: BlocProvider( create: (_) => NewCarBloc( newCarRepository: context.read<NewCarRepository>(), )..add(const NewCarFormLoaded()), child: const NewCarForm(), ), ); } } class NewCarForm extends StatelessWidget { const NewCarForm({super.key}); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: const <Widget>[ _BrandDropdownButton(), _ModelDropdownButton(), _YearDropdownButton(), _FormSubmitButton(), ], ); } } class _BrandDropdownButton extends StatelessWidget { const _BrandDropdownButton(); @override Widget build(BuildContext context) { final brands = context.select((NewCarBloc bloc) => bloc.state.brands); final brand = context.select((NewCarBloc bloc) => bloc.state.brand); return Material( child: DropdownButton<String>( key: const Key('newCarForm_brand_dropdownButton'), items: brands.isNotEmpty ? brands.map((brand) { return DropdownMenuItem(value: brand, child: Text(brand)); }).toList() : const [], value: brand, hint: const Text('Select a Brand'), onChanged: (brand) { context.read<NewCarBloc>().add(NewCarBrandChanged(brand: brand)); }, ), ); } } class _ModelDropdownButton extends StatelessWidget { const _ModelDropdownButton(); @override Widget build(BuildContext context) { final models = context.select((NewCarBloc bloc) => bloc.state.models); final model = context.select((NewCarBloc bloc) => bloc.state.model); return Material( child: DropdownButton<String>( key: const Key('newCarForm_model_dropdownButton'), items: models.isNotEmpty ? models.map((model) { return DropdownMenuItem(value: model, child: Text(model)); }).toList() : const [], value: model, hint: const Text('Select a Model'), onChanged: (model) { context.read<NewCarBloc>().add(NewCarModelChanged(model: model)); }, ), ); } } class _YearDropdownButton extends StatelessWidget { const _YearDropdownButton(); @override Widget build(BuildContext context) { final years = context.select((NewCarBloc bloc) => bloc.state.years); final year = context.select((NewCarBloc bloc) => bloc.state.year); return Material( child: DropdownButton<String>( key: const Key('newCarForm_year_dropdownButton'), items: years.isNotEmpty ? years.map((year) { return DropdownMenuItem(value: year, child: Text(year)); }).toList() : const [], value: year, hint: const Text('Select a Year'), onChanged: (year) { context.read<NewCarBloc>().add(NewCarYearChanged(year: year)); }, ), ); } } class _FormSubmitButton extends StatelessWidget { const _FormSubmitButton(); @override Widget build(BuildContext context) { final state = context.watch<NewCarBloc>().state; void onFormSubmitted() { ScaffoldMessenger.of(context) ..hideCurrentSnackBar() ..showSnackBar( SnackBar( content: Text('Submitted ${state.brand} ${state.model} ${state.year}'), ), ); } return ElevatedButton( onPressed: state.isComplete ? onFormSubmitted : null, child: const Text('Submit'), ); } }
bloc/examples/flutter_dynamic_form/lib/new_car/view/new_car_page.dart/0
{'file_path': 'bloc/examples/flutter_dynamic_form/lib/new_car/view/new_car_page.dart', 'repo_id': 'bloc', 'token_count': 1662}
// ignore_for_file: avoid_print import 'package:bloc/bloc.dart'; class AppBlocObserver extends BlocObserver { const AppBlocObserver(); @override void onEvent(Bloc<dynamic, dynamic> bloc, Object? event) { super.onEvent(bloc, event); print(event); } @override void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) { print(error); super.onError(bloc, error, stackTrace); } @override void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) { super.onChange(bloc, change); print(change); } @override void onTransition( Bloc<dynamic, dynamic> bloc, Transition<dynamic, dynamic> transition, ) { super.onTransition(bloc, transition); print(transition); } }
bloc/examples/flutter_firebase_login/lib/app/bloc_observer.dart/0
{'file_path': 'bloc/examples/flutter_firebase_login/lib/app/bloc_observer.dart', 'repo_id': 'bloc', 'token_count': 284}
part of 'sign_up_cubit.dart'; enum ConfirmPasswordValidationError { invalid } class SignUpState extends Equatable { const SignUpState({ this.email = const Email.pure(), this.password = const Password.pure(), this.confirmedPassword = const ConfirmedPassword.pure(), this.status = FormzStatus.pure, this.errorMessage, }); final Email email; final Password password; final ConfirmedPassword confirmedPassword; final FormzStatus status; final String? errorMessage; @override List<Object> get props => [email, password, confirmedPassword, status]; SignUpState copyWith({ Email? email, Password? password, ConfirmedPassword? confirmedPassword, FormzStatus? status, String? errorMessage, }) { return SignUpState( email: email ?? this.email, password: password ?? this.password, confirmedPassword: confirmedPassword ?? this.confirmedPassword, status: status ?? this.status, errorMessage: errorMessage ?? this.errorMessage, ); } }
bloc/examples/flutter_firebase_login/lib/sign_up/cubit/sign_up_state.dart/0
{'file_path': 'bloc/examples/flutter_firebase_login/lib/sign_up/cubit/sign_up_state.dart', 'repo_id': 'bloc', 'token_count': 326}
name: cache description: A simple in memory cache made for dart version: 1.0.0 publish_to: none environment: sdk: ">=2.19.0 <3.0.0" dev_dependencies: test: ^1.17.11 very_good_analysis: ^3.1.0
bloc/examples/flutter_firebase_login/packages/cache/pubspec.yaml/0
{'file_path': 'bloc/examples/flutter_firebase_login/packages/cache/pubspec.yaml', 'repo_id': 'bloc', 'token_count': 85}
// ignore_for_file: prefer_const_constructors import 'package:authentication_repository/authentication_repository.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_firebase_login/login/login.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:form_inputs/form_inputs.dart'; import 'package:formz/formz.dart'; import 'package:mocktail/mocktail.dart'; class MockAuthenticationRepository extends Mock implements AuthenticationRepository {} void main() { const invalidEmailString = 'invalid'; const invalidEmail = Email.dirty(invalidEmailString); const validEmailString = 'test@gmail.com'; const validEmail = Email.dirty(validEmailString); const invalidPasswordString = 'invalid'; const invalidPassword = Password.dirty(invalidPasswordString); const validPasswordString = 't0pS3cret1234'; const validPassword = Password.dirty(validPasswordString); group('LoginCubit', () { late AuthenticationRepository authenticationRepository; setUp(() { authenticationRepository = MockAuthenticationRepository(); when( () => authenticationRepository.logInWithGoogle(), ).thenAnswer((_) async {}); when( () => authenticationRepository.logInWithEmailAndPassword( email: any(named: 'email'), password: any(named: 'password'), ), ).thenAnswer((_) async {}); }); test('initial state is LoginState', () { expect(LoginCubit(authenticationRepository).state, LoginState()); }); group('emailChanged', () { blocTest<LoginCubit, LoginState>( 'emits [invalid] when email/password are invalid', build: () => LoginCubit(authenticationRepository), act: (cubit) => cubit.emailChanged(invalidEmailString), expect: () => const <LoginState>[ LoginState(email: invalidEmail, status: FormzStatus.invalid), ], ); blocTest<LoginCubit, LoginState>( 'emits [valid] when email/password are valid', build: () => LoginCubit(authenticationRepository), seed: () => LoginState(password: validPassword), act: (cubit) => cubit.emailChanged(validEmailString), expect: () => const <LoginState>[ LoginState( email: validEmail, password: validPassword, status: FormzStatus.valid, ), ], ); }); group('passwordChanged', () { blocTest<LoginCubit, LoginState>( 'emits [invalid] when email/password are invalid', build: () => LoginCubit(authenticationRepository), act: (cubit) => cubit.passwordChanged(invalidPasswordString), expect: () => const <LoginState>[ LoginState( password: invalidPassword, status: FormzStatus.invalid, ), ], ); blocTest<LoginCubit, LoginState>( 'emits [valid] when email/password are valid', build: () => LoginCubit(authenticationRepository), seed: () => LoginState(email: validEmail), act: (cubit) => cubit.passwordChanged(validPasswordString), expect: () => const <LoginState>[ LoginState( email: validEmail, password: validPassword, status: FormzStatus.valid, ), ], ); }); group('logInWithCredentials', () { blocTest<LoginCubit, LoginState>( 'does nothing when status is not validated', build: () => LoginCubit(authenticationRepository), act: (cubit) => cubit.logInWithCredentials(), expect: () => const <LoginState>[], ); blocTest<LoginCubit, LoginState>( 'calls logInWithEmailAndPassword with correct email/password', build: () => LoginCubit(authenticationRepository), seed: () => LoginState( status: FormzStatus.valid, email: validEmail, password: validPassword, ), act: (cubit) => cubit.logInWithCredentials(), verify: (_) { verify( () => authenticationRepository.logInWithEmailAndPassword( email: validEmailString, password: validPasswordString, ), ).called(1); }, ); blocTest<LoginCubit, LoginState>( 'emits [submissionInProgress, submissionSuccess] ' 'when logInWithEmailAndPassword succeeds', build: () => LoginCubit(authenticationRepository), seed: () => LoginState( status: FormzStatus.valid, email: validEmail, password: validPassword, ), act: (cubit) => cubit.logInWithCredentials(), expect: () => const <LoginState>[ LoginState( status: FormzStatus.submissionInProgress, email: validEmail, password: validPassword, ), LoginState( status: FormzStatus.submissionSuccess, email: validEmail, password: validPassword, ) ], ); blocTest<LoginCubit, LoginState>( 'emits [submissionInProgress, submissionFailure] ' 'when logInWithEmailAndPassword fails ' 'due to LogInWithEmailAndPasswordFailure', setUp: () { when( () => authenticationRepository.logInWithEmailAndPassword( email: any(named: 'email'), password: any(named: 'password'), ), ).thenThrow(LogInWithEmailAndPasswordFailure('oops')); }, build: () => LoginCubit(authenticationRepository), seed: () => LoginState( status: FormzStatus.valid, email: validEmail, password: validPassword, ), act: (cubit) => cubit.logInWithCredentials(), expect: () => const <LoginState>[ LoginState( status: FormzStatus.submissionInProgress, email: validEmail, password: validPassword, ), LoginState( status: FormzStatus.submissionFailure, errorMessage: 'oops', email: validEmail, password: validPassword, ) ], ); blocTest<LoginCubit, LoginState>( 'emits [submissionInProgress, submissionFailure] ' 'when logInWithEmailAndPassword fails due to generic exception', setUp: () { when( () => authenticationRepository.logInWithEmailAndPassword( email: any(named: 'email'), password: any(named: 'password'), ), ).thenThrow(Exception('oops')); }, build: () => LoginCubit(authenticationRepository), seed: () => LoginState( status: FormzStatus.valid, email: validEmail, password: validPassword, ), act: (cubit) => cubit.logInWithCredentials(), expect: () => const <LoginState>[ LoginState( status: FormzStatus.submissionInProgress, email: validEmail, password: validPassword, ), LoginState( status: FormzStatus.submissionFailure, email: validEmail, password: validPassword, ) ], ); }); group('logInWithGoogle', () { blocTest<LoginCubit, LoginState>( 'calls logInWithGoogle', build: () => LoginCubit(authenticationRepository), act: (cubit) => cubit.logInWithGoogle(), verify: (_) { verify(() => authenticationRepository.logInWithGoogle()).called(1); }, ); blocTest<LoginCubit, LoginState>( 'emits [submissionInProgress, submissionSuccess] ' 'when logInWithGoogle succeeds', build: () => LoginCubit(authenticationRepository), act: (cubit) => cubit.logInWithGoogle(), expect: () => const <LoginState>[ LoginState(status: FormzStatus.submissionInProgress), LoginState(status: FormzStatus.submissionSuccess) ], ); blocTest<LoginCubit, LoginState>( 'emits [submissionInProgress, submissionFailure] ' 'when logInWithGoogle fails due to LogInWithGoogleFailure', setUp: () { when( () => authenticationRepository.logInWithGoogle(), ).thenThrow(LogInWithGoogleFailure('oops')); }, build: () => LoginCubit(authenticationRepository), act: (cubit) => cubit.logInWithGoogle(), expect: () => const <LoginState>[ LoginState(status: FormzStatus.submissionInProgress), LoginState( status: FormzStatus.submissionFailure, errorMessage: 'oops', ) ], ); blocTest<LoginCubit, LoginState>( 'emits [submissionInProgress, submissionFailure] ' 'when logInWithGoogle fails due to generic exception', setUp: () { when( () => authenticationRepository.logInWithGoogle(), ).thenThrow(Exception('oops')); }, build: () => LoginCubit(authenticationRepository), act: (cubit) => cubit.logInWithGoogle(), expect: () => const <LoginState>[ LoginState(status: FormzStatus.submissionInProgress), LoginState(status: FormzStatus.submissionFailure) ], ); }); }); }
bloc/examples/flutter_firebase_login/test/login/cubit/login_cubit_test.dart/0
{'file_path': 'bloc/examples/flutter_firebase_login/test/login/cubit/login_cubit_test.dart', 'repo_id': 'bloc', 'token_count': 4033}
part of 'my_form_bloc.dart'; abstract class MyFormEvent extends Equatable { const MyFormEvent(); @override List<Object> get props => []; } class EmailChanged extends MyFormEvent { const EmailChanged({required this.email}); final String email; @override List<Object> get props => [email]; } class EmailUnfocused extends MyFormEvent {} class PasswordChanged extends MyFormEvent { const PasswordChanged({required this.password}); final String password; @override List<Object> get props => [password]; } class PasswordUnfocused extends MyFormEvent {} class FormSubmitted extends MyFormEvent {}
bloc/examples/flutter_form_validation/lib/bloc/my_form_event.dart/0
{'file_path': 'bloc/examples/flutter_form_validation/lib/bloc/my_form_event.dart', 'repo_id': 'bloc', 'token_count': 175}
part of 'post_bloc.dart'; abstract class PostEvent extends Equatable { @override List<Object> get props => []; } class PostFetched extends PostEvent {}
bloc/examples/flutter_infinite_list/lib/posts/bloc/post_event.dart/0
{'file_path': 'bloc/examples/flutter_infinite_list/lib/posts/bloc/post_event.dart', 'repo_id': 'bloc', 'token_count': 51}
name: flutter_infinite_list description: A new Flutter project. version: 1.0.0+1 publish_to: none environment: sdk: ">=2.19.0 <3.0.0" dependencies: bloc: ^8.1.0 bloc_concurrency: ^0.2.0 equatable: ^2.0.3 flutter: sdk: flutter flutter_bloc: ^8.1.1 http: ^0.13.0 stream_transform: ^2.0.0 dev_dependencies: bloc_test: ^9.0.0 flutter_test: sdk: flutter mocktail: ^0.3.0 very_good_analysis: ^3.1.0 dependency_overrides: bloc: path: ../../packages/bloc bloc_test: path: ../../packages/bloc_test flutter_bloc: path: ../../packages/flutter_bloc flutter: uses-material-design: true
bloc/examples/flutter_infinite_list/pubspec.yaml/0
{'file_path': 'bloc/examples/flutter_infinite_list/pubspec.yaml', 'repo_id': 'bloc', 'token_count': 294}
import 'package:authentication_repository/authentication_repository.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_login/login/login.dart'; class LoginPage extends StatelessWidget { const LoginPage({super.key}); static Route<void> route() { return MaterialPageRoute<void>(builder: (_) => const LoginPage()); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Login')), body: Padding( padding: const EdgeInsets.all(12), child: BlocProvider( create: (context) { return LoginBloc( authenticationRepository: RepositoryProvider.of<AuthenticationRepository>(context), ); }, child: const LoginForm(), ), ), ); } }
bloc/examples/flutter_login/lib/login/view/login_page.dart/0
{'file_path': 'bloc/examples/flutter_login/lib/login/view/login_page.dart', 'repo_id': 'bloc', 'token_count': 362}
import 'dart:async'; import 'package:user_repository/src/models/models.dart'; import 'package:uuid/uuid.dart'; class UserRepository { User? _user; Future<User?> getUser() async { if (_user != null) return _user; return Future.delayed( const Duration(milliseconds: 300), () => _user = User(const Uuid().v4()), ); } }
bloc/examples/flutter_login/packages/user_repository/lib/src/user_repository.dart/0
{'file_path': 'bloc/examples/flutter_login/packages/user_repository/lib/src/user_repository.dart', 'repo_id': 'bloc', 'token_count': 140}
import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; class Item extends Equatable { Item(this.id, this.name) : color = Colors.primaries[id % Colors.primaries.length]; final int id; final String name; final Color color; final int price = 42; @override List<Object> get props => [id, name, color, price]; }
bloc/examples/flutter_shopping_cart/lib/catalog/models/item.dart/0
{'file_path': 'bloc/examples/flutter_shopping_cart/lib/catalog/models/item.dart', 'repo_id': 'bloc', 'token_count': 121}
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_shopping_cart/cart/cart.dart'; import 'package:flutter_shopping_cart/catalog/catalog.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import '../../helper.dart'; void main() { late CartBloc cartBloc; final mockItems = [ Item(1, 'item #1'), Item(2, 'item #2'), Item(3, 'item #3'), ]; setUp(() { cartBloc = MockCartBloc(); }); group('CartPage', () { testWidgets('renders CartList and CartTotal', (tester) async { when(() => cartBloc.state).thenReturn(CartLoading()); await tester.pumpApp( cartBloc: cartBloc, child: CartPage(), ); expect(find.byType(CartList), findsOneWidget); expect(find.byType(CartTotal), findsOneWidget); }); }); group('CartList', () { testWidgets( 'renders CircularProgressIndicator ' 'when cart is loading', (tester) async { when(() => cartBloc.state).thenReturn(CartLoading()); await tester.pumpApp( cartBloc: cartBloc, child: CartList(), ); expect(find.byType(CircularProgressIndicator), findsOneWidget); }); testWidgets( 'renders 3 ListTile ' 'when cart is loaded with three items', (tester) async { when(() => cartBloc.state) .thenReturn(CartLoaded(cart: Cart(items: mockItems))); await tester.pumpApp( cartBloc: cartBloc, child: CartList(), ); expect(find.byType(ListTile), findsNWidgets(3)); }); testWidgets( 'renders error text ' 'when cart fails to load', (tester) async { when(() => cartBloc.state).thenReturn(CartError()); await tester.pumpApp( cartBloc: cartBloc, child: CartList(), ); expect(find.text('Something went wrong!'), findsOneWidget); }); }); group('CartTotal', () { testWidgets( 'renders CircularProgressIndicator ' 'when cart is loading', (tester) async { when(() => cartBloc.state).thenReturn(CartLoading()); await tester.pumpApp( cartBloc: cartBloc, child: CartTotal(), ); expect(find.byType(CircularProgressIndicator), findsOneWidget); }); testWidgets( 'renders total price ' 'when cart is loaded with three items', (tester) async { when(() => cartBloc.state) .thenReturn(CartLoaded(cart: Cart(items: mockItems))); await tester.pumpApp( cartBloc: cartBloc, child: CartTotal(), ); expect(find.text('\$${42 * 3}'), findsOneWidget); }); testWidgets( 'renders error text ' 'when cart fails to load', (tester) async { when(() => cartBloc.state).thenReturn(CartError()); await tester.pumpApp( cartBloc: cartBloc, child: CartTotal(), ); expect(find.text('Something went wrong!'), findsOneWidget); }); testWidgets( 'renders SnackBar after ' "tapping the 'BUY' button", (tester) async { when(() => cartBloc.state) .thenReturn(CartLoaded(cart: Cart(items: mockItems))); await tester.pumpApp( cartBloc: cartBloc, child: Scaffold(body: CartTotal()), ); await tester.tap(find.text('BUY')); await tester.pumpAndSettle(); expect(find.byType(SnackBar), findsOneWidget); expect(find.text('Buying not supported yet.'), findsOneWidget); }); testWidgets('adds CartItemRemoved on long press', (tester) async { when(() => cartBloc.state).thenReturn( CartLoaded(cart: Cart(items: mockItems)), ); final mockItemToRemove = mockItems.last; await tester.pumpApp( cartBloc: cartBloc, child: Scaffold(body: CartList()), ); await tester.longPress(find.text(mockItemToRemove.name)); verify(() => cartBloc.add(CartItemRemoved(mockItemToRemove))).called(1); }); }); }
bloc/examples/flutter_shopping_cart/test/cart/view/cart_page_test.dart/0
{'file_path': 'bloc/examples/flutter_shopping_cart/test/cart/view/cart_page_test.dart', 'repo_id': 'bloc', 'token_count': 1737}
import 'package:flutter/material.dart'; import 'package:flutter_timer/app.dart'; void main() => runApp(const App());
bloc/examples/flutter_timer/lib/main.dart/0
{'file_path': 'bloc/examples/flutter_timer/lib/main.dart', 'repo_id': 'bloc', 'token_count': 40}
import 'dart:async'; 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_timer/timer/timer.dart'; import 'package:mocktail/mocktail.dart'; class _MockTimerBloc extends MockBloc<TimerEvent, TimerState> implements TimerBloc {} class _FakeTimerEvent extends Fake implements TimerEvent {} extension on WidgetTester { Future<void> pumpTimerView(TimerBloc timerBloc) { return pumpWidget( MaterialApp( home: BlocProvider.value(value: timerBloc, child: const TimerView()), ), ); } } void main() { late TimerBloc timerBloc; setUpAll(() { registerFallbackValue(_FakeTimerEvent()); }); setUp(() { timerBloc = _MockTimerBloc(); }); tearDown(() => reset(timerBloc)); group('TimerPage', () { testWidgets('renders TimerView', (tester) async { await tester.pumpWidget(const MaterialApp(home: TimerPage())); expect(find.byType(TimerView), findsOneWidget); }); }); group('TimerView', () { testWidgets('renders initial Timer view', (tester) async { when(() => timerBloc.state).thenReturn(const TimerInitial(60)); await tester.pumpTimerView(timerBloc); expect(find.text('01:00'), findsOneWidget); expect(find.byIcon(Icons.play_arrow), findsOneWidget); }); testWidgets('renders pause and reset button when timer is in progress', (tester) async { when(() => timerBloc.state).thenReturn(const TimerRunInProgress(59)); await tester.pumpTimerView(timerBloc); expect(find.text('00:59'), findsOneWidget); expect(find.byIcon(Icons.pause), findsOneWidget); expect(find.byIcon(Icons.replay), findsOneWidget); }); testWidgets('renders play and reset button when timer is paused', (tester) async { when(() => timerBloc.state).thenReturn(const TimerRunPause(600)); await tester.pumpTimerView(timerBloc); expect(find.text('10:00'), findsOneWidget); expect(find.byIcon(Icons.play_arrow), findsOneWidget); expect(find.byIcon(Icons.replay), findsOneWidget); }); testWidgets('renders replay button when timer is finished', (tester) async { when(() => timerBloc.state).thenReturn(const TimerRunComplete()); await tester.pumpTimerView(timerBloc); expect(find.text('00:00'), findsOneWidget); expect(find.byIcon(Icons.replay), findsOneWidget); }); testWidgets('timer started when play arrow button is pressed', (tester) async { when(() => timerBloc.state).thenReturn(const TimerInitial(60)); await tester.pumpTimerView(timerBloc); await tester.tap(find.byIcon(Icons.play_arrow)); verify( () => timerBloc.add( any( that: isA<TimerStarted>().having((e) => e.duration, 'duration', 60), ), ), ).called(1); }); testWidgets( 'timer pauses when pause button is pressed ' 'while timer is in progress', (tester) async { when(() => timerBloc.state).thenReturn(const TimerRunInProgress(30)); await tester.pumpTimerView(timerBloc); await tester.tap(find.byIcon(Icons.pause)); verify(() => timerBloc.add(const TimerPaused())).called(1); }); testWidgets( 'timer resets when replay button is pressed ' 'while timer is in progress', (tester) async { when(() => timerBloc.state).thenReturn(const TimerRunInProgress(30)); await tester.pumpTimerView(timerBloc); await tester.tap(find.byIcon(Icons.replay)); verify(() => timerBloc.add(const TimerReset())).called(1); }); testWidgets( 'timer resumes when play arrow button is pressed ' 'while timer is paused', (tester) async { when(() => timerBloc.state).thenReturn(const TimerRunPause(30)); await tester.pumpTimerView(timerBloc); await tester.tap(find.byIcon(Icons.play_arrow)); verify(() => timerBloc.add(const TimerResumed())).called(1); }); testWidgets( 'timer resets when reset button is pressed ' 'while timer is paused', (tester) async { when(() => timerBloc.state).thenReturn(const TimerRunPause(30)); await tester.pumpTimerView(timerBloc); await tester.tap(find.byIcon(Icons.replay)); verify(() => timerBloc.add(const TimerReset())).called(1); }); testWidgets( 'timer resets when reset button is pressed ' 'when timer is finished', (tester) async { when(() => timerBloc.state).thenReturn(const TimerRunComplete()); await tester.pumpTimerView(timerBloc); await tester.tap(find.byIcon(Icons.replay)); verify(() => timerBloc.add(const TimerReset())).called(1); }); testWidgets('actions are not rebuilt when timer is running', (tester) async { final controller = StreamController<TimerState>(); whenListen( timerBloc, controller.stream, initialState: const TimerRunInProgress(10), ); await tester.pumpTimerView(timerBloc); FloatingActionButton findPauseButton() { return tester.widget<FloatingActionButton>( find.byWidgetPredicate( (widget) => widget is FloatingActionButton && widget.child is Icon && (widget.child! as Icon).icon == Icons.pause, ), ); } final pauseButton = findPauseButton(); controller.add(const TimerRunInProgress(9)); await tester.pump(); expect(pauseButton, equals(findPauseButton())); }); }); }
bloc/examples/flutter_timer/test/timer/view/timer_page_test.dart/0
{'file_path': 'bloc/examples/flutter_timer/test/timer/view/timer_page_test.dart', 'repo_id': 'bloc', 'token_count': 2275}
export 'edit_todo_page.dart';
bloc/examples/flutter_todos/lib/edit_todo/view/view.dart/0
{'file_path': 'bloc/examples/flutter_todos/lib/edit_todo/view/view.dart', 'repo_id': 'bloc', 'token_count': 13}
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_todos/l10n/l10n.dart'; import 'package:flutter_todos/stats/stats.dart'; import 'package:todos_repository/todos_repository.dart'; class StatsPage extends StatelessWidget { const StatsPage({super.key}); @override Widget build(BuildContext context) { return BlocProvider( create: (context) => StatsBloc( todosRepository: context.read<TodosRepository>(), )..add(const StatsSubscriptionRequested()), child: const StatsView(), ); } } class StatsView extends StatelessWidget { const StatsView({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final state = context.watch<StatsBloc>().state; final textTheme = Theme.of(context).textTheme; return Scaffold( appBar: AppBar( title: Text(l10n.statsAppBarTitle), ), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ListTile( key: const Key('statsView_completedTodos_listTile'), leading: const Icon(Icons.check_rounded), title: Text(l10n.statsCompletedTodoCountLabel), trailing: Text( '${state.completedTodos}', style: textTheme.headlineSmall, ), ), ListTile( key: const Key('statsView_activeTodos_listTile'), leading: const Icon(Icons.radio_button_unchecked_rounded), title: Text(l10n.statsActiveTodoCountLabel), trailing: Text( '${state.activeTodos}', style: textTheme.headlineSmall, ), ), ], ), ); } }
bloc/examples/flutter_todos/lib/stats/view/stats_page.dart/0
{'file_path': 'bloc/examples/flutter_todos/lib/stats/view/stats_page.dart', 'repo_id': 'bloc', 'token_count': 793}
// ignore_for_file: avoid_redundant_argument_values import 'package:test/test.dart'; import 'package:todos_api/todos_api.dart'; void main() { group('Todo', () { Todo createSubject({ String? id = '1', String title = 'title', String description = 'description', bool isCompleted = true, }) { return Todo( id: id, title: title, description: description, isCompleted: isCompleted, ); } group('constructor', () { test('works correctly', () { expect( createSubject, returnsNormally, ); }); test('throws AssertionError when id is empty', () { expect( () => createSubject(id: ''), throwsA(isA<AssertionError>()), ); }); test('sets id if not provided', () { expect( createSubject(id: null).id, isNotEmpty, ); }); }); test('supports value equality', () { expect( createSubject(), equals(createSubject()), ); }); test('props are correct', () { expect( createSubject().props, equals([ '1', // id 'title', // title 'description', // description true, // isCompleted ]), ); }); group('copyWith', () { test('returns the same object if not arguments are provided', () { expect( createSubject().copyWith(), equals(createSubject()), ); }); test('retains the old value for every parameter if null is provided', () { expect( createSubject().copyWith( id: null, title: null, description: null, isCompleted: null, ), equals(createSubject()), ); }); test('replaces every non-null parameter', () { expect( createSubject().copyWith( id: '2', title: 'new title', description: 'new description', isCompleted: false, ), equals( createSubject( id: '2', title: 'new title', description: 'new description', isCompleted: false, ), ), ); }); }); group('fromJson', () { test('works correctly', () { expect( Todo.fromJson(<String, dynamic>{ 'id': '1', 'title': 'title', 'description': 'description', 'isCompleted': true, }), equals(createSubject()), ); }); }); group('toJson', () { test('works correctly', () { expect( createSubject().toJson(), equals(<String, dynamic>{ 'id': '1', 'title': 'title', 'description': 'description', 'isCompleted': true, }), ); }); }); }); }
bloc/examples/flutter_todos/packages/todos_api/test/models/todo_test.dart/0
{'file_path': 'bloc/examples/flutter_todos/packages/todos_api/test/models/todo_test.dart', 'repo_id': 'bloc', 'token_count': 1511}
import 'package:flutter_test/flutter_test.dart'; extension ExtraFinders on CommonFinders { /// Finds a widget by a specific type [T]. /// /// ```dart /// find.bySpecificType<Foo<Bar>>() /// ``` Finder bySpecificType<T>() => find.byType(T); }
bloc/examples/flutter_todos/test/helpers/finders.dart/0
{'file_path': 'bloc/examples/flutter_todos/test/helpers/finders.dart', 'repo_id': 'bloc', 'token_count': 94}
// ignore_for_file: avoid_redundant_argument_values 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/todos_overview/todos_overview.dart'; import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; class MockTodosOverviewBloc extends MockBloc<TodosOverviewEvent, TodosOverviewState> implements TodosOverviewBloc {} extension on CommonFinders { Finder filterMenuItem({ required TodosViewFilter filter, required String title, }) { return find.descendant( of: find.byWidgetPredicate( (w) => w is PopupMenuItem && w.value == filter, ), matching: find.text(title), ); } } extension on WidgetTester { Future<void> openPopup() async { await tap(find.byType(TodosOverviewFilterButton)); await pumpAndSettle(); } } void main() { group('TodosOverviewFilterButton', () { late TodosOverviewBloc todosOverviewBloc; setUp(() { todosOverviewBloc = MockTodosOverviewBloc(); when(() => todosOverviewBloc.state).thenReturn( const TodosOverviewState( status: TodosOverviewStatus.success, todos: [], ), ); }); Widget buildSubject() { return BlocProvider.value( value: todosOverviewBloc, child: const TodosOverviewFilterButton(), ); } group('constructor', () { test('works properly', () { expect( () => const TodosOverviewFilterButton(), returnsNormally, ); }); }); testWidgets('renders filter list icon', (tester) async { await tester.pumpApp(buildSubject()); expect( find.byIcon(Icons.filter_list_rounded), findsOneWidget, ); }); group('internal PopupMenuButton', () { testWidgets('is rendered', (tester) async { await tester.pumpApp(buildSubject()); expect( find.bySpecificType<PopupMenuButton<TodosViewFilter>>(), findsOneWidget, ); }); testWidgets('has initial value set to active filter', (tester) async { when(() => todosOverviewBloc.state).thenReturn( const TodosOverviewState( filter: TodosViewFilter.completedOnly, ), ); await tester.pumpApp(buildSubject()); final popupMenuButton = tester.widget<PopupMenuButton<TodosViewFilter>>( find.bySpecificType<PopupMenuButton<TodosViewFilter>>(), ); expect( popupMenuButton.initialValue, equals(TodosViewFilter.completedOnly), ); }); testWidgets( 'renders items for each filter type when pressed', (tester) async { await tester.pumpApp(buildSubject()); await tester.openPopup(); expect( find.filterMenuItem( filter: TodosViewFilter.all, title: l10n.todosOverviewFilterAll, ), findsOneWidget, ); expect( find.filterMenuItem( filter: TodosViewFilter.activeOnly, title: l10n.todosOverviewFilterActiveOnly, ), findsOneWidget, ); expect( find.filterMenuItem( filter: TodosViewFilter.completedOnly, title: l10n.todosOverviewFilterCompletedOnly, ), findsOneWidget, ); }, ); testWidgets( 'adds TodosOverviewFilterChanged ' 'to TodosOverviewBloc ' 'when new filter is pressed', (tester) async { when(() => todosOverviewBloc.state).thenReturn( const TodosOverviewState( filter: TodosViewFilter.all, ), ); await tester.pumpApp(buildSubject()); await tester.openPopup(); await tester.tap(find.text(l10n.todosOverviewFilterCompletedOnly)); await tester.pumpAndSettle(); verify( () => todosOverviewBloc.add( const TodosOverviewFilterChanged(TodosViewFilter.completedOnly), ), ).called(1); }, ); }); }); }
bloc/examples/flutter_todos/test/todos_overview/widgets/todos_overview_filter_button_test.dart/0
{'file_path': 'bloc/examples/flutter_todos/test/todos_overview/widgets/todos_overview_filter_button_test.dart', 'repo_id': 'bloc', 'token_count': 1999}
export 'view/settings_page.dart';
bloc/examples/flutter_weather/lib/settings/settings.dart/0
{'file_path': 'bloc/examples/flutter_weather/lib/settings/settings.dart', 'repo_id': 'bloc', 'token_count': 12}
name: open_meteo_api description: A Dart API Client for the Open-Meteo API. version: 1.0.0+1 environment: sdk: ">=2.19.0 <3.0.0" dependencies: http: ^0.13.0 json_annotation: ^4.6.0 dev_dependencies: build_runner: ^2.0.0 json_serializable: ^6.3.1 mocktail: ^0.3.0 test: ^1.16.4 very_good_analysis: ^3.0.2
bloc/examples/flutter_weather/packages/open_meteo_api/pubspec.yaml/0
{'file_path': 'bloc/examples/flutter_weather/packages/open_meteo_api/pubspec.yaml', 'repo_id': 'bloc', 'token_count': 155}
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_weather/app.dart'; import 'package:flutter_weather/theme/theme.dart'; import 'package:flutter_weather/weather/weather.dart'; import 'package:mocktail/mocktail.dart'; import 'package:weather_repository/weather_repository.dart'; import 'helpers/hydrated_bloc.dart'; class MockThemeCubit extends MockCubit<Color> implements ThemeCubit {} class MockWeatherRepository extends Mock implements WeatherRepository {} void main() { initHydratedStorage(); group('WeatherApp', () { late WeatherRepository weatherRepository; setUp(() { weatherRepository = MockWeatherRepository(); }); testWidgets('renders WeatherAppView', (tester) async { await tester.pumpWidget( WeatherApp(weatherRepository: weatherRepository), ); expect(find.byType(WeatherAppView), findsOneWidget); }); }); group('WeatherAppView', () { late ThemeCubit themeCubit; late WeatherRepository weatherRepository; setUp(() { themeCubit = MockThemeCubit(); weatherRepository = MockWeatherRepository(); }); testWidgets('renders WeatherPage', (tester) async { when(() => themeCubit.state).thenReturn(Colors.blue); await tester.pumpWidget( RepositoryProvider.value( value: weatherRepository, child: BlocProvider.value( value: themeCubit, child: const WeatherAppView(), ), ), ); expect(find.byType(WeatherPage), findsOneWidget); }); testWidgets('has correct theme primary color', (tester) async { const color = Color(0xFFD2D2D2); when(() => themeCubit.state).thenReturn(color); await tester.pumpWidget( RepositoryProvider.value( value: weatherRepository, child: BlocProvider.value( value: themeCubit, child: const WeatherAppView(), ), ), ); final materialApp = tester.widget<MaterialApp>(find.byType(MaterialApp)); expect(materialApp.theme?.primaryColor, color); }); }); }
bloc/examples/flutter_weather/test/app_test.dart/0
{'file_path': 'bloc/examples/flutter_weather/test/app_test.dart', 'repo_id': 'bloc', 'token_count': 873}
name: angular_github_search description: A web app that uses AngularDart Components environment: sdk: ">=2.19.0 <3.0.0" dependencies: angular_bloc: ^8.0.0 bloc: ^8.1.0 common_github_search: path: ../common_github_search ngdart: ^8.0.0-dev.0 dev_dependencies: build_runner: ^2.0.0 build_web_compilers: ^3.0.0 very_good_analysis: ^4.0.0
bloc/examples/github_search/angular_github_search/pubspec.yaml/0
{'file_path': 'bloc/examples/github_search/angular_github_search/pubspec.yaml', 'repo_id': 'bloc', 'token_count': 157}
import 'package:common_github_search/common_github_search.dart'; class SearchResult { const SearchResult({required this.items}); factory SearchResult.fromJson(Map<String, dynamic> json) { final items = (json['items'] as List<dynamic>) .map( (dynamic item) => SearchResultItem.fromJson(item as Map<String, dynamic>), ) .toList(); return SearchResult(items: items); } final List<SearchResultItem> items; }
bloc/examples/github_search/common_github_search/lib/src/models/search_result.dart/0
{'file_path': 'bloc/examples/github_search/common_github_search/lib/src/models/search_result.dart', 'repo_id': 'bloc', 'token_count': 181}
# As of test: ^0.12.32, we can use a common/base dart_test.yaml, which this is. # # See documentation: # * https://github.com/dart-lang/test/blob/master/doc/configuration.md # * https://github.com/dart-lang/test/blob/master/doc/configuration.md#include presets: # When run with -P travis, we have different settings/options. # # 1: We don't use Chrome --headless: # 2: We use --reporter expanded # 3: We skip anything tagged "fails-on-travis". travis: override_platforms: chrome: settings: # Disable some security options, since this is only on Travis. # https://chromium.googlesource.com/chromium/src/+/master/docs/design/sandbox.md # https://docs.travis-ci.com/user/chrome#Sandboxing arguments: --no-sandbox # TODO(https://github.com/dart-lang/test/issues/772) headless: false # Don't run any tests that are tagged ["fails-on-travis"]. exclude_tags: "fails-on-travis" # https://github.com/dart-lang/test/blob/master/doc/configuration.md#reporter reporter: expanded # This repository has only web tests. platforms: - chrome
bloc/packages/angular_bloc/dart_test.yaml/0
{'file_path': 'bloc/packages/angular_bloc/dart_test.yaml', 'repo_id': 'bloc', 'token_count': 442}
part of 'bloc.dart'; /// An object that provides access to a stream of states over time. abstract class Streamable<State extends Object?> { /// The current [stream] of states. Stream<State> get stream; } /// A [Streamable] that provides synchronous access to the current [state]. abstract class StateStreamable<State> implements Streamable<State> { /// The current [state]. State get state; } /// A [StateStreamable] that must be closed when no longer in use. abstract class StateStreamableSource<State> implements StateStreamable<State>, Closable {} /// An object that must be closed when no longer in use. abstract class Closable { /// Closes the current instance. /// The returned future completes when the instance has been closed. FutureOr<void> close(); /// Whether the object is closed. /// /// An object is considered closed once [close] is called. bool get isClosed; } /// An object that can emit new states. abstract class Emittable<State extends Object?> { /// Emits a new [state]. void emit(State state); } /// A generic destination for errors. /// /// Multiple errors can be reported to the sink via `addError`. abstract class ErrorSink implements Closable { /// Adds an [error] to the sink with an optional [stackTrace]. /// /// Must not be called on a closed sink. void addError(Object error, [StackTrace? stackTrace]); } /// {@template bloc_base} /// An interface for the core functionality implemented by /// both [Bloc] and [Cubit]. /// {@endtemplate} abstract class BlocBase<State> implements StateStreamableSource<State>, Emittable<State>, ErrorSink { /// {@macro bloc_base} BlocBase(this._state) { // ignore: invalid_use_of_protected_member _blocObserver.onCreate(this); } // ignore: deprecated_member_use_from_same_package final _blocObserver = BlocOverrides.current?.blocObserver ?? Bloc.observer; late final _stateController = StreamController<State>.broadcast(); State _state; bool _emitted = false; @override State get state => _state; @override Stream<State> get stream => _stateController.stream; /// Whether the bloc is closed. /// /// A bloc is considered closed once [close] is called. /// Subsequent state changes cannot occur within a closed bloc. @override bool get isClosed => _stateController.isClosed; /// Updates the [state] to the provided [state]. /// [emit] does nothing if the [state] being emitted /// is equal to the current [state]. /// /// To allow for the possibility of notifying listeners of the initial state, /// emitting a state which is equal to the initial state is allowed as long /// as it is the first thing emitted by the instance. /// /// * Throws a [StateError] if the bloc is closed. @protected @visibleForTesting @override void emit(State state) { try { if (isClosed) { throw StateError('Cannot emit new states after calling close'); } if (state == _state && _emitted) return; onChange(Change<State>(currentState: this.state, nextState: state)); _state = state; _stateController.add(_state); _emitted = true; } catch (error, stackTrace) { onError(error, stackTrace); rethrow; } } /// Called whenever a [change] occurs with the given [change]. /// A [change] occurs when a new `state` is emitted. /// [onChange] is called before the `state` of the `cubit` is updated. /// [onChange] is a great spot to add logging/analytics for a specific `cubit`. /// /// **Note: `super.onChange` should always be called first.** /// ```dart /// @override /// void onChange(Change change) { /// // Always call super.onChange with the current change /// super.onChange(change); /// /// // Custom onChange logic goes here /// } /// ``` /// /// See also: /// /// * [BlocObserver] for observing [Cubit] behavior globally. /// @protected @mustCallSuper void onChange(Change<State> change) { // ignore: invalid_use_of_protected_member _blocObserver.onChange(this, change); } /// Reports an [error] which triggers [onError] with an optional [StackTrace]. @protected @mustCallSuper @override void addError(Object error, [StackTrace? stackTrace]) { onError(error, stackTrace ?? StackTrace.current); } /// Called whenever an [error] occurs and notifies [BlocObserver.onError]. /// /// **Note: `super.onError` should always be called last.** /// /// ```dart /// @override /// void onError(Object error, StackTrace stackTrace) { /// // Custom onError logic goes here /// /// // Always call super.onError with the current error and stackTrace /// super.onError(error, stackTrace); /// } /// ``` @protected @mustCallSuper void onError(Object error, StackTrace stackTrace) { // ignore: invalid_use_of_protected_member _blocObserver.onError(this, error, stackTrace); } /// Closes the instance. /// This method should be called when the instance is no longer needed. /// Once [close] is called, the instance can no longer be used. @mustCallSuper @override Future<void> close() async { // ignore: invalid_use_of_protected_member _blocObserver.onClose(this); await _stateController.close(); } }
bloc/packages/bloc/lib/src/bloc_base.dart/0
{'file_path': 'bloc/packages/bloc/lib/src/bloc_base.dart', 'repo_id': 'bloc', 'token_count': 1662}
import 'dart:async'; import 'package:bloc/bloc.dart'; import 'package:meta/meta.dart'; part 'async_event.dart'; part 'async_state.dart'; class AsyncBloc extends Bloc<AsyncEvent, AsyncState> { AsyncBloc() : super(AsyncState.initial()) { on<AsyncEvent>( (event, emit) async { emit(state.copyWith(isLoading: true, isSuccess: false)); await Future<void>.delayed(Duration.zero); emit(state.copyWith(isLoading: false, isSuccess: true)); }, transformer: (events, mapper) => events.asyncExpand(mapper), ); } }
bloc/packages/bloc/test/blocs/async/async_bloc.dart/0
{'file_path': 'bloc/packages/bloc/test/blocs/async/async_bloc.dart', 'repo_id': 'bloc', 'token_count': 228}
import 'package:bloc/bloc.dart'; class SeededBloc extends Bloc<String, int> { SeededBloc({required this.seed, required this.states}) : super(seed) { on<String>((event, emit) { for (final state in states) { emit(state); } }); } final List<int> states; final int seed; }
bloc/packages/bloc/test/blocs/seeded/seeded_bloc.dart/0
{'file_path': 'bloc/packages/bloc/test/blocs/seeded/seeded_bloc.dart', 'repo_id': 'bloc', 'token_count': 125}
import 'package:bloc/bloc.dart'; import 'blocs.dart'; class ErrorCounterBlocError extends Error {} class ErrorCounterBloc extends Bloc<CounterEvent, int> { ErrorCounterBloc() : super(0) { on<CounterEvent>((event, emit) { switch (event) { case CounterEvent.increment: emit(state + 1); throw ErrorCounterBlocError(); } }); } }
bloc/packages/bloc_test/test/blocs/error_counter_bloc.dart/0
{'file_path': 'bloc/packages/bloc_test/test/blocs/error_counter_bloc.dart', 'repo_id': 'bloc', 'token_count': 157}
import 'package:bloc/bloc.dart'; class Repository { void sideEffect() {} } class SideEffectCounterCubit extends Cubit<int> { SideEffectCounterCubit(this.repository) : super(0); final Repository repository; void increment() { repository.sideEffect(); emit(state + 1); } }
bloc/packages/bloc_test/test/cubits/side_effect_counter_cubit.dart/0
{'file_path': 'bloc/packages/bloc_test/test/cubits/side_effect_counter_cubit.dart', 'repo_id': 'bloc', 'token_count': 100}
@Tags(['pull-request-only']) import 'package:build_verify/build_verify.dart'; import 'package:test/test.dart'; void main() { test('ensure_build', () { expectBuildClean(packageRelativeDirectory: 'packages/bloc_tools'); }); }
bloc/packages/bloc_tools/test/ensure_build_test.dart/0
{'file_path': 'bloc/packages/bloc_tools/test/ensure_build_test.dart', 'repo_id': 'bloc', 'token_count': 85}
import 'dart:typed_data'; import 'package:hive/hive.dart'; /// Abstract cipher can be implemented to customize encryption. abstract class HydratedCipher implements HiveCipher { /// Calculate a hash of the key. Make sure to use a secure hash. @override int calculateKeyCrc(); /// The maximum size the input can have after it has been encrypted. @override int maxEncryptedSize(Uint8List inp); /// Encrypt the given bytes. @override int encrypt( Uint8List inp, int inpOff, int inpLength, Uint8List out, int outOff, ); /// Decrypt the given bytes. @override int decrypt( Uint8List inp, int inpOff, int inpLength, Uint8List out, int outOff, ); } /// Default encryption algorithm. Uses AES256 CBC with PKCS7 padding. class HydratedAesCipher extends HiveAesCipher implements HydratedCipher { /// Create a cipher with the given [key]. HydratedAesCipher(List<int> key) : super(key); }
bloc/packages/hydrated_bloc/lib/src/hydrated_cipher.dart/0
{'file_path': 'bloc/packages/hydrated_bloc/lib/src/hydrated_cipher.dart', 'repo_id': 'bloc', 'token_count': 330}
import 'dart:io'; import 'package:hive/hive.dart'; // ignore: implementation_imports import 'package:hive/src/hive_impl.dart'; import 'package:path/path.dart' as p; import 'package:test/test.dart'; void main() { group('Hive interference', () { tearDown(() { Hive.close(); (Hive as HiveImpl).homePath = null; }); test('odd singleton interference', () async { final cwd = Directory.current.absolute.path; var impl1 = HiveImpl()..init(cwd); var box1 = await impl1.openBox<dynamic>('impl1'); var impl2 = HiveImpl()..init(cwd); var box2 = await impl2.openBox<dynamic>('impl2'); await impl1.close(); expect(box1.isOpen, false); expect(box2.isOpen, true); impl1 = HiveImpl()..init(cwd); box1 = await impl1.openBox<dynamic>('impl1'); Hive.init(cwd); await box1.deleteFromDisk(); await box2.close(); await Hive.deleteBoxFromDisk('impl2'); }); test('two hive impls beside same directory', () async { final cwd = Directory.current.absolute.path; final impl1 = Hive..init(cwd); var box1 = await impl1.openBox<dynamic>('impl1'); final impl2 = HiveImpl()..init(cwd); var box2 = await impl2.openBox<dynamic>('impl2'); await box1.put('instance', 'impl1'); await box2.put('instance', 'impl2'); await impl1.close(); await impl2.close(); box1 = await impl1.openBox<dynamic>('impl1'); box2 = await impl2.openBox<dynamic>('impl2'); expect(box1.get('instance'), 'impl1'); expect(box2.get('instance'), 'impl2'); await impl1.deleteFromDisk(); expect(box1.isOpen, false); expect(box2.isOpen, true); expect(box2.get('instance'), 'impl2'); await impl2.deleteFromDisk(); expect(box2.isOpen, false); }); test('two hive impls reside distinct directories', () async { final cwd1 = p.join(Directory.current.absolute.path, 'cwd1'); final cwd2 = p.join(Directory.current.absolute.path, 'cwd2'); final impl1 = Hive..init(cwd1); var box1 = await impl1.openBox<dynamic>('impl1'); final impl2 = HiveImpl()..init(cwd2); var box2 = await impl2.openBox<dynamic>('impl2'); await box1.put('instance', 'impl1'); await box2.put('instance', 'impl2'); await impl1.close(); await impl2.close(); box1 = await impl1.openBox<dynamic>('impl1'); box2 = await impl2.openBox<dynamic>('impl2'); expect(box1.get('instance'), 'impl1'); expect(box2.get('instance'), 'impl2'); await impl1.deleteFromDisk(); expect(box1.isOpen, false); expect(box2.isOpen, true); expect(box2.get('instance'), 'impl2'); await impl2.deleteFromDisk(); expect(box2.isOpen, false); await Directory(cwd1).delete(); await Directory(cwd2).delete(); }); }); }
bloc/packages/hydrated_bloc/test/hive_interference_test.dart/0
{'file_path': 'bloc/packages/hydrated_bloc/test/hive_interference_test.dart', 'repo_id': 'bloc', 'token_count': 1199}
/// An extension to the [bloc state management library](https://pub.dev/packages/bloc) /// which adds support for undo and redo. /// /// Get started at [bloclibrary.dev](https://bloclibrary.dev) πŸš€ library replay_bloc; export 'package:bloc/bloc.dart'; export 'src/replay_cubit.dart';
bloc/packages/replay_bloc/lib/replay_bloc.dart/0
{'file_path': 'bloc/packages/replay_bloc/lib/replay_bloc.dart', 'repo_id': 'bloc', 'token_count': 97}
export 'add_todo_page.dart';
bloc_todos/lib/add_todo/add_todo.dart/0
{'file_path': 'bloc_todos/lib/add_todo/add_todo.dart', 'repo_id': 'bloc_todos', 'token_count': 13}
import 'package:bloc_todos/add_todo/add_todo.dart'; import 'package:bloc_todos/filtered_todos/bloc/filtered_todos_bloc.dart'; import 'package:bloc_todos/home/home.dart'; import 'package:bloc_todos/stats/stats.dart'; import 'package:bloc_todos/todos/todos.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider(create: (_) => HomeBloc()), BlocProvider( create: (context) => FilteredTodosBloc( todos: context.bloc<TodosBloc>(), ), ), ], child: Home(), ); } } class Home extends StatelessWidget { @override Widget build(BuildContext context) { return BlocBuilder<HomeBloc, HomeState>( builder: (context, state) { return GestureDetector( onTap: () { final focusNode = FocusScope.of(context); if (!focusNode.hasPrimaryFocus) { focusNode.unfocus(); } context.bloc<TodosBloc>().add(const TodoSelected(null)); }, child: Scaffold( appBar: AppBar( title: const Text('Flutter Todos'), actions: [ TodoToggleButton(visible: state.activeTab == HomeTab.todos), TodoFilterButton(visible: state.activeTab == HomeTab.todos), const ExtraActions(), ], ), body: state.activeTab == HomeTab.stats ? const StatsPage() : const TodosPage(), floatingActionButton: FloatingActionButton( onPressed: () => Navigator.of(context).push(AddTodoPage.route()), child: const Icon(Icons.add), tooltip: 'Add Todo', ), bottomNavigationBar: BottomNavigation( activeTab: state.activeTab, onTabChanged: (index) { context.bloc<HomeBloc>().add(HomeTabChanged(index)); }, ), ), ); }, ); } }
bloc_todos/lib/home/home_page.dart/0
{'file_path': 'bloc_todos/lib/home/home_page.dart', 'repo_id': 'bloc_todos', 'token_count': 1080}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'todo.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** Todo _$TodoFromJson(Map<String, dynamic> json) { return Todo( json['task'] as String, complete: json['complete'] as bool, note: json['note'] as String, id: json['id'] as String, ); } Map<String, dynamic> _$TodoToJson(Todo instance) => <String, dynamic>{ 'complete': instance.complete, 'id': instance.id, 'note': instance.note, 'task': instance.task, };
bloc_todos/lib/todos/models/todo.g.dart/0
{'file_path': 'bloc_todos/lib/todos/models/todo.g.dart', 'repo_id': 'bloc_todos', 'token_count': 213}
int calcHatPrice(int length) => ((length * 50) + 10);
bob_box/game/lib/screens/util.dart/0
{'file_path': 'bob_box/game/lib/screens/util.dart', 'repo_id': 'bob_box', 'token_count': 18}
import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; typedef BoundaryWidgetBuilder = Widget Function( BuildContext context, dynamic error); /// No `Boundary<valueType>` were found as an ancestor of a [Defer] was used. class BoundaryNotFoundError extends Error { /// The type of the widget that tried (and failed) to access `Boundary<valueType>`. final Type valueType; /// Allows specifying [valueType] BoundaryNotFoundError(this.valueType); @override String toString() { return ''' Error: No Boundary<$valueType> found. '''; } } class _InheritedBoundary extends InheritedWidget { _InheritedBoundary({Key key, this.element, Widget child}) : super(key: key, child: child); static _BoundaryElement of(BuildContext context) { var widget = context .getElementForInheritedWidgetOfExactType<_InheritedBoundary>() ?.widget; if (widget is _InheritedBoundary) { return widget.element; } return null; } final _BoundaryElement element; @override bool updateShouldNotify(_InheritedBoundary oldWidget) { return oldWidget.element != element; } } /// Defines a fallback behavior for [Defer] widget used inside `child`. class Boundary extends StatelessWidget { /// [fallbackBuilder] and [child] must not be `null`. const Boundary({ Key key, @required this.fallbackBuilder, @required this.child, }) : assert(child != null), assert(fallbackBuilder != null), super(key: key); /// The subtree from which [Boundary] will capture errors. /// /// If [child] or any of its descendants throws when building the widget, /// then [fallbackBuilder] will be called with the exception. final Widget child; /// A callback used to create a fallback UI if [child] fails to build. /// /// It is fine for [fallbackBuilder] to throws too, in which case the error /// will be propagated to other boundaries. final BoundaryWidgetBuilder fallbackBuilder; @override _BoundaryElement createElement() => _BoundaryElement(this); @override Widget build(BuildContext context) { return _Internal( child: child, showChild: true, element: context as _BoundaryElement, exception: (context as _BoundaryElement).exception, fallbackBuilder: fallbackBuilder, ); } } /// A widget that asks the nearest [Boundary] in its ancestors to call /// [Boundary.fallbackBuilder]. class Defer extends StatelessWidget { /// Allows specifying [details]. Defer(this.details, {Key key}) : super(key: key); /// The object that will be passed as parameter to [Boundary.fallbackBuilder]. final Object details; @override _FallbackElement createElement() => _FallbackElement(this); @override Widget build(BuildContext context) => const SizedBox(); } class _FallbackElement extends StatelessElement { _FallbackElement(Defer widget) : super(widget); @override Defer get widget => super.widget as Defer; _BoundaryElement boundary; _BoundaryElement didCatch; @override Element updateChild(Element child, Widget newWidget, dynamic newSlot) { final res = super.updateChild(child, newWidget, newSlot); boundary = _InheritedBoundary.of(this); if (boundary == null) { FlutterError.reportError(FlutterErrorDetails( library: 'boundary', exception: BoundaryNotFoundError(widget.details.runtimeType), )); } else { boundary.markSubtreeFailed(widget.details); } return res; } @override void deactivate() { if (boundary?.activated == true) { boundary.markSubtreeFailed(null); } super.deactivate(); } } class _Internal extends StatelessWidget { const _Internal({ Key key, this.element, this.child, this.fallbackBuilder, this.exception, this.showChild, }) : super(key: key); final _BoundaryElement element; final Widget child; final BoundaryWidgetBuilder fallbackBuilder; final dynamic exception; final bool showChild; @override Widget build(BuildContext context) { if (exception != null) { if (!showChild) { element.errorWidget = _InheritedBoundary( element: _InheritedBoundary.of(context), child: Builder( builder: (context) => fallbackBuilder(context, exception)), ); } } else { element.errorWidget = null; } final valid = Offstage( offstage: !showChild && exception != null, child: child, ); return _InheritedBoundary( element: element, child: Stack( fit: StackFit.passthrough, alignment: Alignment.center, children: element.errorWidget != null ? [valid, element.errorWidget] : [valid], ), ); } } class _BoundaryElement extends StatelessElement { _BoundaryElement(Boundary widget) : super(widget); @override Boundary get widget => super.widget as Boundary; Object failure; bool isBuilding = false; bool activated = false; dynamic exception; Widget errorWidget; Element _child; dynamic _slot; @override Element updateChild(Element child, Widget newWidget, dynamic newSlot) { _child ??= child; _slot = newSlot; return _child = super.updateChild(child, newWidget, newSlot); } @override void performRebuild() { isBuilding = true; final hadError = failure != null; failure = null; super.performRebuild(); isBuilding = false; final hasError = failure != null; if (hasError != hadError) { exception = failure; rebuildWithError(exception); } } @override void mount(Element parent, dynamic newSlot) { super.mount(parent, newSlot); activated = true; } @override void activate() { super.activate(); activated = true; } @override void deactivate() { activated = false; super.deactivate(); } void markSubtreeFailed(Object failure) { this.failure = failure; exception = failure; if (!isBuilding) { rebuildWithError(exception); } } void rebuildWithError(dynamic exception) { updateChild( _child, _Internal( element: this, showChild: false, fallbackBuilder: widget.fallbackBuilder, exception: exception, child: widget.child, ), _slot, ); } }
boundary/lib/boundary.dart/0
{'file_path': 'boundary/lib/boundary.dart', 'repo_id': 'boundary', 'token_count': 2246}
/// ***************************************************************************** /// 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 demo; import 'dart:async'; import 'dart:html' hide Body; import 'package:box2d_flame/box2d_browser.dart' hide Timer; /// An abstract class for any Demo of the Box2D library. abstract class Demo { static const int WORLD_POOL_SIZE = 100; static const int WORLD_POOL_CONTAINER_SIZE = 10; /// All of the bodies in a simulation. List<Body> bodies = new List<Body>(); /// The default canvas width and height. static const int CANVAS_WIDTH = 900; static const int CANVAS_HEIGHT = 600; /// Scale of the viewport. static const double _VIEWPORT_SCALE = 10.0; /// The gravity vector's y value. static const double GRAVITY = -10.0; /// The timestep and iteration numbers. static const double TIME_STEP = 1 / 60; static const int VELOCITY_ITERATIONS = 10; static const int POSITION_ITERATIONS = 10; /// The physics world. final World world; // For timing the world.step call. It is kept running but reset and polled // every frame to minimize overhead. final Stopwatch _stopwatch; final double _viewportScale; /// The drawing canvas. CanvasElement canvas; /// The canvas rendering context. CanvasRenderingContext2D ctx; /// The transform abstraction layer between the world and drawing canvas. ViewportTransform viewport; /// The debug drawing tool. DebugDraw debugDraw; /// Frame count for fps int frameCount; /// HTML element used to display the FPS counter Element fpsCounter; /// Microseconds for world step update int elapsedUs; /// HTML element used to display the world step time Element worldStepTime; Demo(String name, [Vector2 gravity, this._viewportScale = _VIEWPORT_SCALE]) : this.world = new World.withPool( (gravity == null) ? new Vector2(0.0, GRAVITY) : gravity, new DefaultWorldPool(WORLD_POOL_SIZE, WORLD_POOL_CONTAINER_SIZE)), _stopwatch = new Stopwatch()..start() { querySelector("#title").innerHtml = name; } /// Advances the world forward by timestep seconds. void step(num timestamp) { _stopwatch.reset(); world.stepDt(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS); elapsedUs = _stopwatch.elapsedMicroseconds; // Clear the animation panel and draw new frame. ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); world.drawDebugData(); frameCount++; window.requestAnimationFrame(step); } /// Creates the canvas and readies the demo for animation. Must be called /// before calling runAnimation. void initializeAnimation() { // Setup the canvas. canvas = (new Element.tag('canvas') as CanvasElement) ..width = CANVAS_WIDTH ..height = CANVAS_HEIGHT; document.body.nodes.add(canvas); ctx = canvas.context2D; // Create the viewport transform with the center at extents. var extents = new Vector2(CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2); viewport = new CanvasViewportTransform(extents, extents) ..scale = _viewportScale; // Create our canvas drawing tool to give to the world. debugDraw = new CanvasDraw(viewport, ctx); // Have the world draw itself for debugging purposes. world.debugDraw = debugDraw; frameCount = 0; fpsCounter = querySelector("#fps-counter"); worldStepTime = querySelector("#world-step-time"); new Timer.periodic(new Duration(seconds: 1), (Timer t) { fpsCounter.innerHtml = frameCount.toString(); frameCount = 0; }); new Timer.periodic(new Duration(milliseconds: 200), (Timer t) { if (elapsedUs == null) return; worldStepTime.innerHtml = "${elapsedUs / 1000} ms"; }); } void initialize(); /// Starts running the demo as an animation using an animation scheduler. void runAnimation() { window.requestAnimationFrame(step); } }
box2d.dart/example/demo.dart/0
{'file_path': 'box2d.dart/example/demo.dart', 'repo_id': 'box2d.dart', 'token_count': 1652}
/******************************************************************************* * 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; /// Implement this class to get contact information. You can use these results for /// things like sounds and game logic. You can also get contact results by /// traversing the contact lists after the time step. However, you might miss /// some contacts because continuous physics leads to sub-stepping. /// Additionally you may receive multiple callbacks for the same contact in a /// single time step. /// You should strive to make your callbacks efficient because there may be /// many callbacks per time step. /// @warning You cannot create/destroy Box2D entities inside these callbacks. abstract class ContactListener { /// Called when two fixtures begin to touch. void beginContact(Contact contact); /// Called when two fixtures cease to touch. void endContact(Contact contact); /// This is called after a contact is updated. This allows you to inspect a /// contact before it goes to the solver. If you are careful, you can modify the /// contact manifold (e.g. disable contact). /// A copy of the old manifold is provided so that you can detect changes. /// Note: this is called only for awake bodies. /// Note: this is called even when the number of contact points is zero. /// Note: this is not called for sensors. /// Note: if you set the number of contact points to zero, you will not /// get an EndContact callback. However, you may get a BeginContact callback /// the next step. /// Note: the oldManifold parameter is pooled, so it will be the same object for every callback /// for each thread. void preSolve(Contact contact, Manifold oldManifold); /// This lets you inspect a contact after the solver is finished. This is useful /// for inspecting impulses. /// Note: the contact manifold does not include time of impact impulses, which can be /// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly /// in a separate data structure. /// Note: this is only called for contacts that are touching, solid, and awake. /// @param contact /// @param impulse this is usually a pooled variable, so it will be modified after this call void postSolve(Contact contact, ContactImpulse impulse); }
box2d.dart/lib/src/callbacks/contact_listener.dart/0
{'file_path': 'box2d.dart/lib/src/callbacks/contact_listener.dart', 'repo_id': 'box2d.dart', 'token_count': 919}
/******************************************************************************* * 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; class DynamicTreeFlatNodes implements BroadPhaseStrategy { static const int MAX_STACK_SIZE = 64; static const int NULL_NODE = -1; static const int INITIAL_BUFFER_LENGTH = 16; int _root = NULL_NODE; List<AABB> _aabb; List<Object> _userData; List<int> _parent; List<int> _child1; List<int> _child2; List<int> _height; int _nodeCount = 0; int _nodeCapacity = 16; int _freeList; final List<Vector2> drawVecs = new List<Vector2>(4); DynamicTreeFlatNodes() { _expandBuffers(0, _nodeCapacity); for (int i = 0; i < drawVecs.length; i++) { drawVecs[i] = new Vector2.zero(); } } static AABB allocAABB() => new AABB(); static Object allocObject() => new Object(); void _expandBuffers(int oldSize, int newSize) { _aabb = BufferUtils.reallocateBufferWithAlloc( _aabb, oldSize, newSize, allocAABB); _userData = BufferUtils.reallocateBufferWithAlloc( _userData, oldSize, newSize, allocObject); _parent = BufferUtils.reallocateBufferInt(_parent, oldSize, newSize); _child1 = BufferUtils.reallocateBufferInt(_child1, oldSize, newSize); _child2 = BufferUtils.reallocateBufferInt(_child2, oldSize, newSize); _height = BufferUtils.reallocateBufferInt(_height, oldSize, newSize); // Build a linked list for the free list. for (int i = oldSize; i < newSize; i++) { _aabb[i] = new AABB(); _parent[i] = (i == newSize - 1) ? NULL_NODE : i + 1; _height[i] = -1; _child1[i] = -1; _child2[i] = -1; } _freeList = oldSize; } int createProxy(final AABB aabb, Object userData) { final int node = _allocateNode(); // Fatten the aabb final AABB nodeAABB = _aabb[node]; nodeAABB.lowerBound.x = aabb.lowerBound.x - Settings.aabbExtension; nodeAABB.lowerBound.y = aabb.lowerBound.y - Settings.aabbExtension; nodeAABB.upperBound.x = aabb.upperBound.x + Settings.aabbExtension; nodeAABB.upperBound.y = aabb.upperBound.y + Settings.aabbExtension; _userData[node] = userData; _insertLeaf(node); return node; } void destroyProxy(int proxyId) { assert(0 <= proxyId && proxyId < _nodeCapacity); assert(_child1[proxyId] == NULL_NODE); _removeLeaf(proxyId); _freeNode(proxyId); } bool moveProxy(int proxyId, final AABB aabb, Vector2 displacement) { assert(0 <= proxyId && proxyId < _nodeCapacity); final int node = proxyId; assert(_child1[node] == NULL_NODE); final AABB nodeAABB = _aabb[node]; // if (nodeAABB.contains(aabb)) { if (nodeAABB.lowerBound.x <= aabb.lowerBound.x && nodeAABB.lowerBound.y <= aabb.lowerBound.y && aabb.upperBound.x <= nodeAABB.upperBound.x && aabb.upperBound.y <= nodeAABB.upperBound.y) { return false; } _removeLeaf(node); // Extend AABB final Vector2 lowerBound = nodeAABB.lowerBound; final Vector2 upperBound = nodeAABB.upperBound; lowerBound.x = aabb.lowerBound.x - Settings.aabbExtension; lowerBound.y = aabb.lowerBound.y - Settings.aabbExtension; upperBound.x = aabb.upperBound.x + Settings.aabbExtension; upperBound.y = aabb.upperBound.y + Settings.aabbExtension; // Predict AABB displacement. final double dx = displacement.x * Settings.aabbMultiplier; final double dy = displacement.y * Settings.aabbMultiplier; if (dx < 0.0) { lowerBound.x += dx; } else { upperBound.x += dx; } if (dy < 0.0) { lowerBound.y += dy; } else { upperBound.y += dy; } _insertLeaf(proxyId); return true; } Object getUserData(int proxyId) { assert(0 <= proxyId && proxyId < _nodeCount); return _userData[proxyId]; } AABB getFatAABB(int proxyId) { assert(0 <= proxyId && proxyId < _nodeCount); return _aabb[proxyId]; } List<int> _nodeStack = BufferUtils.allocClearIntList(20); int _nodeStackIndex = 0; void query(TreeCallback callback, AABB aabb) { _nodeStackIndex = 0; _nodeStack[_nodeStackIndex++] = _root; while (_nodeStackIndex > 0) { int node = _nodeStack[--_nodeStackIndex]; if (node == NULL_NODE) { continue; } if (AABB.testOverlap(_aabb[node], aabb)) { int child1 = _child1[node]; if (child1 == NULL_NODE) { bool proceed = callback.treeCallback(node); if (!proceed) { return; } } else { if (_nodeStack.length - _nodeStackIndex - 2 <= 0) { _nodeStack = BufferUtils.reallocateBufferInt( _nodeStack, _nodeStack.length, _nodeStack.length * 2); } _nodeStack[_nodeStackIndex++] = child1; _nodeStack[_nodeStackIndex++] = _child2[node]; } } } } final Vector2 _r = new Vector2.zero(); final AABB _aabbTemp = new AABB(); final RayCastInput _subInput = new RayCastInput(); void raycast(TreeRayCastCallback callback, RayCastInput input) { final Vector2 p1 = input.p1; final Vector2 p2 = input.p2; double p1x = p1.x, p2x = p2.x, p1y = p1.y, p2y = p2.y; double vx, vy; double rx, ry; double absVx, absVy; double cx, cy; double hx, hy; double tempx, tempy; _r.x = p2x - p1x; _r.y = p2y - p1y; assert((_r.x * _r.x + _r.y * _r.y) > 0.0); _r.normalize(); rx = _r.x; ry = _r.y; // v is perpendicular to the segment. vx = -1.0 * ry; vy = 1.0 * rx; absVx = vx.abs(); absVy = vy.abs(); // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) double maxFraction = input.maxFraction; // Build a bounding box for the segment. final AABB segAABB = _aabbTemp; // Vec2 t = p1 + maxFraction * (p2 - p1); // before inline // temp.set(p2).subLocal(p1).mulLocal(maxFraction).addLocal(p1); // Vec2.minToOut(p1, temp, segAABB.lowerBound); // Vec2.maxToOut(p1, temp, segAABB.upperBound); tempx = (p2x - p1x) * maxFraction + p1x; tempy = (p2y - p1y) * maxFraction + p1y; segAABB.lowerBound.x = p1x < tempx ? p1x : tempx; segAABB.lowerBound.y = p1y < tempy ? p1y : tempy; segAABB.upperBound.x = p1x > tempx ? p1x : tempx; segAABB.upperBound.y = p1y > tempy ? p1y : tempy; // end inline _nodeStackIndex = 0; _nodeStack[_nodeStackIndex++] = _root; while (_nodeStackIndex > 0) { int node = _nodeStack[--_nodeStackIndex] = _root; if (node == NULL_NODE) { continue; } final AABB nodeAABB = _aabb[node]; if (!AABB.testOverlap(nodeAABB, segAABB)) { continue; } // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) // node.aabb.getCenterToOut(c); // node.aabb.getExtentsToOut(h); cx = (nodeAABB.lowerBound.x + nodeAABB.upperBound.x) * .5; cy = (nodeAABB.lowerBound.y + nodeAABB.upperBound.y) * .5; hx = (nodeAABB.upperBound.x - nodeAABB.lowerBound.x) * .5; hy = (nodeAABB.upperBound.y - nodeAABB.lowerBound.y) * .5; tempx = p1x - cx; tempy = p1y - cy; double separation = (vx * tempx + vy * tempy).abs() - (absVx * hx + absVy * hy); if (separation > 0.0) { continue; } int child1 = _child1[node]; if (child1 == NULL_NODE) { _subInput.p1.x = p1x; _subInput.p1.y = p1y; _subInput.p2.x = p2x; _subInput.p2.y = p2y; _subInput.maxFraction = maxFraction; double value = callback.raycastCallback(_subInput, node); if (value == 0.0) { // The client has terminated the ray cast. return; } if (value > 0.0) { // Update segment bounding box. maxFraction = value; // temp.set(p2).subLocal(p1).mulLocal(maxFraction).addLocal(p1); // Vec2.minToOut(p1, temp, segAABB.lowerBound); // Vec2.maxToOut(p1, temp, segAABB.upperBound); tempx = (p2x - p1x) * maxFraction + p1x; tempy = (p2y - p1y) * maxFraction + p1y; segAABB.lowerBound.x = p1x < tempx ? p1x : tempx; segAABB.lowerBound.y = p1y < tempy ? p1y : tempy; segAABB.upperBound.x = p1x > tempx ? p1x : tempx; segAABB.upperBound.y = p1y > tempy ? p1y : tempy; } } else { _nodeStack[_nodeStackIndex++] = child1; _nodeStack[_nodeStackIndex++] = _child2[node]; } } } int computeHeight() { return _computeHeight(_root); } int _computeHeight(int node) { assert(0 <= node && node < _nodeCapacity); if (_child1[node] == NULL_NODE) { return 0; } int height1 = _computeHeight(_child1[node]); int height2 = _computeHeight(_child2[node]); return 1 + Math.max<int>(height1, height2); } /// Validate this tree. For testing. void validate() { _validateStructure(_root); _validateMetrics(_root); int freeCount = 0; int freeNode = _freeList; while (freeNode != NULL_NODE) { assert(0 <= freeNode && freeNode < _nodeCapacity); freeNode = _parent[freeNode]; ++freeCount; } assert(getHeight() == computeHeight()); assert(_nodeCount + freeCount == _nodeCapacity); } int getHeight() { if (_root == NULL_NODE) { return 0; } return _height[_root]; } int getMaxBalance() { int maxBalance = 0; for (int i = 0; i < _nodeCapacity; ++i) { if (_height[i] <= 1) { continue; } assert(_child1[i] != NULL_NODE); int child1 = _child1[i]; int child2 = _child2[i]; int balance = (_height[child2] - _height[child1]).abs(); maxBalance = Math.max(maxBalance, balance); } return maxBalance; } double getAreaRatio() { if (_root == NULL_NODE) { return 0.0; } final int root = _root; double rootArea = _aabb[root].getPerimeter(); double totalArea = 0.0; for (int i = 0; i < _nodeCapacity; ++i) { if (_height[i] < 0) { // Free node in pool continue; } totalArea += _aabb[i].getPerimeter(); } return totalArea / rootArea; } int _allocateNode() { if (_freeList == NULL_NODE) { assert(_nodeCount == _nodeCapacity); _nodeCapacity *= 2; _expandBuffers(_nodeCount, _nodeCapacity); } assert(_freeList != NULL_NODE); int node = _freeList; _freeList = _parent[node]; _parent[node] = NULL_NODE; _child1[node] = NULL_NODE; _height[node] = 0; ++_nodeCount; return node; } /// returns a node to the pool void _freeNode(int node) { assert(node != NULL_NODE); assert(0 < _nodeCount); _parent[node] = _freeList != NULL_NODE ? _freeList : NULL_NODE; _height[node] = -1; _freeList = node; _nodeCount--; } final AABB _combinedAABB = new AABB(); void _insertLeaf(int leaf) { if (_root == NULL_NODE) { _root = leaf; _parent[_root] = NULL_NODE; return; } // find the best sibling AABB leafAABB = _aabb[leaf]; int index = _root; while (_child1[index] != NULL_NODE) { final int node = index; int child1 = _child1[node]; int child2 = _child2[node]; final AABB nodeAABB = _aabb[node]; double area = nodeAABB.getPerimeter(); _combinedAABB.combine2(nodeAABB, leafAABB); double combinedArea = _combinedAABB.getPerimeter(); // Cost of creating a new parent for this node and the new leaf double cost = 2.0 * combinedArea; // Minimum cost of pushing the leaf further down the tree double inheritanceCost = 2.0 * (combinedArea - area); // Cost of descending into child1 double cost1; AABB child1AABB = _aabb[child1]; if (_child1[child1] == NULL_NODE) { _combinedAABB.combine2(leafAABB, child1AABB); cost1 = _combinedAABB.getPerimeter() + inheritanceCost; } else { _combinedAABB.combine2(leafAABB, child1AABB); double oldArea = child1AABB.getPerimeter(); double newArea = _combinedAABB.getPerimeter(); cost1 = (newArea - oldArea) + inheritanceCost; } // Cost of descending into child2 double cost2; AABB child2AABB = _aabb[child2]; if (_child1[child2] == NULL_NODE) { _combinedAABB.combine2(leafAABB, child2AABB); cost2 = _combinedAABB.getPerimeter() + inheritanceCost; } else { _combinedAABB.combine2(leafAABB, child2AABB); double oldArea = child2AABB.getPerimeter(); double newArea = _combinedAABB.getPerimeter(); cost2 = newArea - oldArea + inheritanceCost; } // Descend according to the minimum cost. if (cost < cost1 && cost < cost2) { break; } // Descend if (cost1 < cost2) { index = child1; } else { index = child2; } } int sibling = index; int oldParent = _parent[sibling]; final int newParent = _allocateNode(); _parent[newParent] = oldParent; _userData[newParent] = null; _aabb[newParent].combine2(leafAABB, _aabb[sibling]); _height[newParent] = _height[sibling] + 1; if (oldParent != NULL_NODE) { // The sibling was not the root. if (_child1[oldParent] == sibling) { _child1[oldParent] = newParent; } else { _child2[oldParent] = newParent; } _child1[newParent] = sibling; _child2[newParent] = leaf; _parent[sibling] = newParent; _parent[leaf] = newParent; } else { // The sibling was the root. _child1[newParent] = sibling; _child2[newParent] = leaf; _parent[sibling] = newParent; _parent[leaf] = newParent; _root = newParent; } // Walk back up the tree fixing heights and AABBs index = _parent[leaf]; while (index != NULL_NODE) { index = _balance(index); int child1 = _child1[index]; int child2 = _child2[index]; assert(child1 != NULL_NODE); assert(child2 != NULL_NODE); _height[index] = 1 + Math.max<int>(_height[child1], _height[child2]); _aabb[index].combine2(_aabb[child1], _aabb[child2]); index = _parent[index]; } // validate(); } void _removeLeaf(int leaf) { if (leaf == _root) { _root = NULL_NODE; return; } int parent = _parent[leaf]; int grandParent = _parent[parent]; int parentChild1 = _child1[parent]; int parentChild2 = _child2[parent]; int sibling; if (parentChild1 == leaf) { sibling = parentChild2; } else { sibling = parentChild1; } if (grandParent != NULL_NODE) { // Destroy parent and connect sibling to grandParent. if (_child1[grandParent] == parent) { _child1[grandParent] = sibling; } else { _child2[grandParent] = sibling; } _parent[sibling] = grandParent; _freeNode(parent); // Adjust ancestor bounds. int index = grandParent; while (index != NULL_NODE) { index = _balance(index); int child1 = _child1[index]; int child2 = _child2[index]; _aabb[index].combine2(_aabb[child1], _aabb[child2]); _height[index] = 1 + Math.max<int>(_height[child1], _height[child2]); index = _parent[index]; } } else { _root = sibling; _parent[sibling] = NULL_NODE; _freeNode(parent); } // validate(); } // Perform a left or right rotation if node A is imbalanced. // Returns the new root index. int _balance(int iA) { assert(iA != NULL_NODE); int A = iA; if (_child1[A] == NULL_NODE || _height[A] < 2) { return iA; } int iB = _child1[A]; int iC = _child2[A]; assert(0 <= iB && iB < _nodeCapacity); assert(0 <= iC && iC < _nodeCapacity); int B = iB; int C = iC; int balance = _height[C] - _height[B]; // Rotate C up if (balance > 1) { int iF = _child1[C]; int iG = _child2[C]; int F = iF; int G = iG; // assert (F != null); // assert (G != null); assert(0 <= iF && iF < _nodeCapacity); assert(0 <= iG && iG < _nodeCapacity); // Swap A and C _child1[C] = iA; int cParent = _parent[C] = _parent[A]; _parent[A] = iC; // A's old parent should point to C if (cParent != NULL_NODE) { if (_child1[cParent] == iA) { _child1[cParent] = iC; } else { assert(_child2[cParent] == iA); _child2[cParent] = iC; } } else { _root = iC; } // Rotate if (_height[F] > _height[G]) { _child2[C] = iF; _child2[A] = iG; _parent[G] = iA; _aabb[A].combine2(_aabb[B], _aabb[G]); _aabb[C].combine2(_aabb[A], _aabb[F]); _height[A] = 1 + Math.max<int>(_height[B], _height[G]); _height[C] = 1 + Math.max<int>(_height[A], _height[F]); } else { _child2[C] = iG; _child2[A] = iF; _parent[F] = iA; _aabb[A].combine2(_aabb[B], _aabb[F]); _aabb[C].combine2(_aabb[A], _aabb[G]); _height[A] = 1 + Math.max<int>(_height[B], _height[F]); _height[C] = 1 + Math.max<int>(_height[A], _height[G]); } return iC; } // Rotate B up if (balance < -1) { int iD = _child1[B]; int iE = _child2[B]; int D = iD; int E = iE; assert(0 <= iD && iD < _nodeCapacity); assert(0 <= iE && iE < _nodeCapacity); // Swap A and B _child1[B] = iA; int Bparent = _parent[B] = _parent[A]; _parent[A] = iB; // A's old parent should point to B if (Bparent != NULL_NODE) { if (_child1[Bparent] == iA) { _child1[Bparent] = iB; } else { assert(_child2[Bparent] == iA); _child2[Bparent] = iB; } } else { _root = iB; } // Rotate if (_height[D] > _height[E]) { _child2[B] = iD; _child1[A] = iE; _parent[E] = iA; _aabb[A].combine2(_aabb[C], _aabb[E]); _aabb[B].combine2(_aabb[A], _aabb[D]); _height[A] = 1 + Math.max<int>(_height[C], _height[E]); _height[B] = 1 + Math.max<int>(_height[A], _height[D]); } else { _child2[B] = iE; _child1[A] = iD; _parent[D] = iA; _aabb[A].combine2(_aabb[C], _aabb[D]); _aabb[B].combine2(_aabb[A], _aabb[E]); _height[A] = 1 + Math.max<int>(_height[C], _height[D]); _height[B] = 1 + Math.max<int>(_height[A], _height[E]); } return iB; } return iA; } void _validateStructure(int node) { if (node == NULL_NODE) { return; } if (node == _root) { assert(_parent[node] == NULL_NODE); } int child1 = _child1[node]; int child2 = _child2[node]; if (child1 == NULL_NODE) { assert(child1 == NULL_NODE); assert(child2 == NULL_NODE); assert(_height[node] == 0); return; } assert(child1 != NULL_NODE && 0 <= child1 && child1 < _nodeCapacity); assert(child2 != NULL_NODE && 0 <= child2 && child2 < _nodeCapacity); assert(_parent[child1] == node); assert(_parent[child2] == node); _validateStructure(child1); _validateStructure(child2); } void _validateMetrics(int node) { if (node == NULL_NODE) { return; } int child1 = _child1[node]; int child2 = _child2[node]; if (child1 == NULL_NODE) { assert(child1 == NULL_NODE); assert(child2 == NULL_NODE); assert(_height[node] == 0); return; } assert(child1 != NULL_NODE && 0 <= child1 && child1 < _nodeCapacity); assert(child2 != child1 && 0 <= child2 && child2 < _nodeCapacity); int height1 = _height[child1]; int height2 = _height[child2]; int height; height = 1 + Math.max<int>(height1, height2); assert(_height[node] == height); AABB aabb = new AABB(); aabb.combine2(_aabb[child1], _aabb[child2]); assert(MathUtils.vector2Equals(aabb.lowerBound, _aabb[node].lowerBound)); assert(MathUtils.vector2Equals(aabb.upperBound, _aabb[node].upperBound)); _validateMetrics(child1); _validateMetrics(child2); } void drawTree(DebugDraw argDraw) { if (_root == NULL_NODE) { return; } int height = computeHeight(); drawTreeX(argDraw, _root, 0, height); } final Color3i _color = new Color3i.zero(); void drawTreeX(DebugDraw argDraw, int node, int spot, int height) { AABB a = _aabb[node]; a.getVertices(drawVecs); _color.setFromRGBd( 1.0, (height - spot) * 1.0 / height, (height - spot) * 1.0 / height); argDraw.drawPolygon(drawVecs, 4, _color); Vector2 textVec = argDraw.getViewportTranform().getWorldToScreen(a.upperBound); argDraw.drawStringXY( textVec.x, textVec.y, "$node-${(spot + 1)}/$height", _color); int c1 = _child1[node]; int c2 = _child2[node]; if (c1 != NULL_NODE) { drawTreeX(argDraw, c1, spot + 1, height); } if (c2 != NULL_NODE) { drawTreeX(argDraw, c2, spot + 1, height); } } }
box2d.dart/lib/src/collision/broadphase/dynamic_tree_flatnodes.dart/0
{'file_path': 'box2d.dart/lib/src/collision/broadphase/dynamic_tree_flatnodes.dart', 'repo_id': 'box2d.dart', 'token_count': 10127}
/// ***************************************************************************** /// 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 convex polygon shape. Polygons have a maximum number of vertices equal to _maxPolygonVertices. /// In most cases you should not need many vertices for a convex polygon. class PolygonShape extends Shape { /// Dump lots of debug information. static const bool _debug = false; /// Local position of the shape centroid in parent body frame. final Vector2 centroid = Vector2.zero(); /// The vertices of the shape. Note: use getVertexCount(), not _vertices.length, to get number of /// active vertices. final List<Vector2> vertices = List<Vector2>(Settings.maxPolygonVertices); /// The normals of the shape. Note: use getVertexCount(), not _normals.length, to get number of /// active normals. final List<Vector2> normals = List<Vector2>(Settings.maxPolygonVertices); /// Number of active vertices in the shape. int count = 0; // pooling final Vector2 _pool1 = Vector2.zero(); final Vector2 _pool2 = Vector2.zero(); final Vector2 _pool3 = Vector2.zero(); final Vector2 _pool4 = Vector2.zero(); Transform _poolt1 = Transform.zero(); PolygonShape() : super(ShapeType.POLYGON) { for (int i = 0; i < vertices.length; i++) { vertices[i] = Vector2.zero(); } for (int i = 0; i < normals.length; i++) { normals[i] = Vector2.zero(); } radius = Settings.polygonRadius; } Shape clone() { PolygonShape shape = PolygonShape(); shape.centroid.setFrom(this.centroid); for (int i = 0; i < shape.normals.length; i++) { shape.normals[i].setFrom(normals[i]); shape.vertices[i].setFrom(vertices[i]); } shape.radius = this.radius; shape.count = this.count; return shape; } /// Create a convex hull from the given array of points. The count must be in the range [3, /// Settings.maxPolygonVertices]. /// @warning the points may be re-ordered, even if they form a convex polygon. /// @warning collinear points are removed. void set(final List<Vector2> vertices, final int count) { setWithPools(vertices, count, null, null); } /// Create a convex hull from the given array of points. The count must be in the range [3, /// Settings.maxPolygonVertices]. This method takes an arraypool for pooling. /// @warning the points may be re-ordered, even if they form a convex polygon. /// @warning collinear points are removed. void setWithPools(final List<Vector2> verts, final int num, final Vec2Array vecPool, final IntArray intPool) { assert(3 <= num && num <= Settings.maxPolygonVertices); if (num < 3) { setAsBoxXY(1.0, 1.0); return; } int n = Math.min(num, Settings.maxPolygonVertices); // Perform welding and copy vertices into local buffer. List<Vector2> ps = (vecPool != null) ? vecPool.get(Settings.maxPolygonVertices) : List<Vector2>(Settings.maxPolygonVertices); int tempCount = 0; for (int i = 0; i < n; ++i) { Vector2 v = verts[i]; bool unique = true; for (int j = 0; j < tempCount; ++j) { if (MathUtils.distanceSquared(v, ps[j]) < 0.5 * Settings.linearSlop) { unique = false; break; } } if (unique) { ps[tempCount++] = v; } } n = tempCount; if (n < 3) { // Polygon is degenerate. assert(false); setAsBoxXY(1.0, 1.0); return; } // Create the convex hull using the Gift wrapping algorithm // http://en.wikipedia.org/wiki/Gift_wrapping_algorithm // Find the right most point on the hull int i0 = 0; double x0 = ps[0].x; for (int i = 1; i < n; ++i) { double x = ps[i].x; if (x > x0 || (x == x0 && ps[i].y < ps[i0].y)) { i0 = i; x0 = x; } } List<int> hull = (intPool != null) ? intPool.get(Settings.maxPolygonVertices) : BufferUtils.allocClearIntList(Settings.maxPolygonVertices); int m = 0; int ih = i0; while (true) { hull[m] = ih; int ie = 0; for (int j = 1; j < n; ++j) { if (ie == ih) { ie = j; continue; } Vector2 r = _pool1 ..setFrom(ps[ie]) ..sub(ps[hull[m]]); Vector2 v = _pool2 ..setFrom(ps[j]) ..sub(ps[hull[m]]); double c = r.cross(v); if (c < 0.0) { ie = j; } // Collinearity check if (c == 0.0 && v.length2 > r.length2) { ie = j; } } ++m; ih = ie; if (ie == i0) { break; } } this.count = m; // Copy vertices. for (int i = 0; i < count; ++i) { if (vertices[i] == null) { vertices[i] = Vector2.zero(); } vertices[i].setFrom(ps[hull[i]]); } final Vector2 edge = _pool1; // Compute normals. Ensure the edges have non-zero length. for (int i = 0; i < count; ++i) { final int i1 = i; final int i2 = i + 1 < count ? i + 1 : 0; edge ..setFrom(vertices[i2]) ..sub(vertices[i1]); assert(edge.length2 > Settings.EPSILON * Settings.EPSILON); edge.scaleOrthogonalInto(-1.0, normals[i]); normals[i].normalize(); } // Compute the polygon centroid. computeCentroidToOut(vertices, count, centroid); } /// Build vertices to represent an axis-aligned box. /// /// @param hx the half-width. /// @param hy the half-height. void setAsBoxXY(final double hx, final double hy) { count = 4; vertices[0].setValues(-hx, -hy); vertices[1].setValues(hx, -hy); vertices[2].setValues(hx, hy); vertices[3].setValues(-hx, hy); normals[0].setValues(0.0, -1.0); normals[1].setValues(1.0, 0.0); normals[2].setValues(0.0, 1.0); normals[3].setValues(-1.0, 0.0); centroid.setZero(); } /// Build vertices to represent an oriented box. /// /// @param hx the half-width. /// @param hy the half-height. /// @param center the center of the box in local coordinates. /// @param angle the rotation of the box in local coordinates. void setAsBox(final double hx, final double hy, final Vector2 center, final double angle) { count = 4; vertices[0].setValues(-hx, -hy); vertices[1].setValues(hx, -hy); vertices[2].setValues(hx, hy); vertices[3].setValues(-hx, hy); normals[0].setValues(0.0, -1.0); normals[1].setValues(1.0, 0.0); normals[2].setValues(0.0, 1.0); normals[3].setValues(-1.0, 0.0); centroid.setFrom(center); final Transform xf = _poolt1; xf.p.setFrom(center); xf.q.setAngle(angle); // Transform vertices and normals. for (int i = 0; i < count; ++i) { Transform.mulToOutVec2(xf, vertices[i], vertices[i]); Rot.mulToOut(xf.q, normals[i], normals[i]); } } /// Set this as a single edge. void setAsEdge(Vector2 v1, Vector2 v2) { count = 2; vertices[0].setFrom(v1); vertices[1].setFrom(v2); centroid ..setFrom(v1) ..add(v2) ..scale(0.5); normals[0] ..setFrom(v2) ..sub(v1); normals[0].scaleOrthogonalInto(-1.0, normals[0]); normals[0].normalize(); normals[1] ..setFrom(normals[0]) ..negate(); } int getChildCount() { return 1; } bool testPoint(final Transform xf, final Vector2 p) { double tempx, tempy; final Rot xfq = xf.q; tempx = p.x - xf.p.x; tempy = p.y - xf.p.y; final double pLocalx = xfq.c * tempx + xfq.s * tempy; final double pLocaly = -xfq.s * tempx + xfq.c * tempy; if (_debug) { print("--testPoint debug--"); print("Vertices: "); for (int i = 0; i < count; ++i) { print(vertices[i]); } print("pLocal: $pLocalx, $pLocaly"); } for (int i = 0; i < count; ++i) { Vector2 vertex = vertices[i]; Vector2 normal = normals[i]; tempx = pLocalx - vertex.x; tempy = pLocaly - vertex.y; final double dot = normal.x * tempx + normal.y * tempy; if (dot > 0.0) { return false; } } return true; } void computeAABB(final AABB aabb, final Transform xf, int childIndex) { final Vector2 lower = aabb.lowerBound; final Vector2 upper = aabb.upperBound; final Vector2 v1 = vertices[0]; final double xfqc = xf.q.c; final double xfqs = xf.q.s; final double xfpx = xf.p.x; final double xfpy = xf.p.y; lower.x = (xfqc * v1.x - xfqs * v1.y) + xfpx; lower.y = (xfqs * v1.x + xfqc * v1.y) + xfpy; upper.x = lower.x; upper.y = lower.y; for (int i = 1; i < count; ++i) { Vector2 v2 = vertices[i]; // Vec2 v = Mul(xf, _vertices[i]); double vx = (xfqc * v2.x - xfqs * v2.y) + xfpx; double vy = (xfqs * v2.x + xfqc * v2.y) + xfpy; lower.x = lower.x < vx ? lower.x : vx; lower.y = lower.y < vy ? lower.y : vy; upper.x = upper.x > vx ? upper.x : vx; upper.y = upper.y > vy ? upper.y : vy; } lower.x -= radius; lower.y -= radius; upper.x += radius; upper.y += radius; } /// Get the vertex count. int getVertexCount() { return count; } /// Get a vertex by index. Vector2 getVertex(final int index) { assert(0 <= index && index < count); return vertices[index]; } double computeDistanceToOut( Transform xf, Vector2 p, int childIndex, Vector2 normalOut) { double xfqc = xf.q.c; double xfqs = xf.q.s; double tx = p.x - xf.p.x; double ty = p.y - xf.p.y; double pLocalx = xfqc * tx + xfqs * ty; double pLocaly = -xfqs * tx + xfqc * ty; double maxDistance = -double.maxFinite; double normalForMaxDistanceX = pLocalx; double normalForMaxDistanceY = pLocaly; for (int i = 0; i < count; ++i) { Vector2 vertex = vertices[i]; Vector2 normal = normals[i]; tx = pLocalx - vertex.x; ty = pLocaly - vertex.y; double dot = normal.x * tx + normal.y * ty; if (dot > maxDistance) { maxDistance = dot; normalForMaxDistanceX = normal.x; normalForMaxDistanceY = normal.y; } } double distance; if (maxDistance > 0) { double minDistanceX = normalForMaxDistanceX; double minDistanceY = normalForMaxDistanceY; double minDistance2 = maxDistance * maxDistance; for (int i = 0; i < count; ++i) { Vector2 vertex = vertices[i]; double distanceVecX = pLocalx - vertex.x; double distanceVecY = pLocaly - vertex.y; double distance2 = (distanceVecX * distanceVecX + distanceVecY * distanceVecY); if (minDistance2 > distance2) { minDistanceX = distanceVecX; minDistanceY = distanceVecY; minDistance2 = distance2; } } distance = Math.sqrt(minDistance2); normalOut.x = xfqc * minDistanceX - xfqs * minDistanceY; normalOut.y = xfqs * minDistanceX + xfqc * minDistanceY; normalOut.normalize(); } else { distance = maxDistance; normalOut.x = xfqc * normalForMaxDistanceX - xfqs * normalForMaxDistanceY; normalOut.y = xfqs * normalForMaxDistanceX + xfqc * normalForMaxDistanceY; } return distance; } bool raycast( RayCastOutput output, RayCastInput input, Transform xf, int childIndex) { final double xfqc = xf.q.c; final double xfqs = xf.q.s; final Vector2 xfp = xf.p; double tempx, tempy; // b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); // b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); tempx = input.p1.x - xfp.x; tempy = input.p1.y - xfp.y; final double p1x = xfqc * tempx + xfqs * tempy; final double p1y = -xfqs * tempx + xfqc * tempy; tempx = input.p2.x - xfp.x; tempy = input.p2.y - xfp.y; final double p2x = xfqc * tempx + xfqs * tempy; final double p2y = -xfqs * tempx + xfqc * tempy; final double dx = p2x - p1x; final double dy = p2y - p1y; double lower = 0.0, upper = input.maxFraction; int index = -1; for (int i = 0; i < count; ++i) { Vector2 normal = normals[i]; Vector2 vertex = vertices[i]; // p = p1 + a * d // dot(normal, p - v) = 0 // dot(normal, p1 - v) + a * dot(normal, d) = 0 double tempxn = vertex.x - p1x; double tempyn = vertex.y - p1y; final double numerator = normal.x * tempxn + normal.y * tempyn; final double denominator = normal.x * dx + normal.y * dy; if (denominator == 0.0) { if (numerator < 0.0) { return false; } } else { // Note: we want this predicate without division: // lower < numerator / denominator, where denominator < 0 // Since denominator < 0, we have to flip the inequality: // lower < numerator / denominator <==> denominator * lower > // numerator. if (denominator < 0.0 && numerator < lower * denominator) { // Increase lower. // The segment enters this half-space. lower = numerator / denominator; index = i; } else if (denominator > 0.0 && numerator < upper * denominator) { // Decrease upper. // The segment exits this half-space. upper = numerator / denominator; } } if (upper < lower) { return false; } } assert(0.0 <= lower && lower <= input.maxFraction); if (index >= 0) { output.fraction = lower; // normal = Mul(xf.R, _normals[index]); Vector2 normal = normals[index]; Vector2 out = output.normal; out.x = xfqc * normal.x - xfqs * normal.y; out.y = xfqs * normal.x + xfqc * normal.y; return true; } return false; } void computeCentroidToOut( final List<Vector2> vs, final int count, final Vector2 out) { assert(count >= 3); out.setValues(0.0, 0.0); double area = 0.0; // pRef is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). final Vector2 pRef = _pool1; pRef.setZero(); final Vector2 e1 = _pool2; final Vector2 e2 = _pool3; final double inv3 = 1.0 / 3.0; for (int i = 0; i < count; ++i) { // Triangle vertices. final Vector2 p1 = pRef; final Vector2 p2 = vs[i]; final Vector2 p3 = i + 1 < count ? vs[i + 1] : vs[0]; e1 ..setFrom(p2) ..sub(p1); e2 ..setFrom(p3) ..sub(p1); final double D = e1.cross(e2); final double triangleArea = 0.5 * D; area += triangleArea; // Area weighted centroid e1 ..setFrom(p1) ..add(p2) ..add(p3) ..scale(triangleArea * inv3); out.add(e1); } // Centroid assert(area > Settings.EPSILON); out.scale(1.0 / area); } void computeMass(final MassData massData, double density) { // Polygon mass, centroid, and inertia. // Let rho be the polygon density in mass per unit area. // Then: // mass = rho * int(dA) // centroid.x = (1/mass) * rho * int(x * dA) // centroid.y = (1/mass) * rho * int(y * dA) // I = rho * int((x*x + y*y) * dA) // // We can compute these integrals by summing all the integrals // for each triangle of the polygon. To evaluate the integral // for a single triangle, we make a change of variables to // the (u,v) coordinates of the triangle: // x = x0 + e1x * u + e2x * v // y = y0 + e1y * u + e2y * v // where 0 <= u && 0 <= v && u + v <= 1. // // We integrate u from [0,1-v] and then v from [0,1]. // We also need to use the Jacobian of the transformation: // D = cross(e1, e2) // // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) // // The rest of the derivation is handled by computer algebra. assert(count >= 3); final Vector2 center = _pool1; center.setZero(); double area = 0.0; double I = 0.0; // pRef is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). final Vector2 s = _pool2; s.setZero(); // This code would put the reference point inside the polygon. for (int i = 0; i < count; ++i) { s.add(vertices[i]); } s.scale(1.0 / count.toDouble()); final double k_inv3 = 1.0 / 3.0; final Vector2 e1 = _pool3; final Vector2 e2 = _pool4; for (int i = 0; i < count; ++i) { // Triangle vertices. e1 ..setFrom(vertices[i]) ..sub(s); e2 ..setFrom(s) ..negate() ..add(i + 1 < count ? vertices[i + 1] : vertices[0]); final double D = e1.cross(e2); final double triangleArea = 0.5 * D; area += triangleArea; // Area weighted centroid center.x += triangleArea * k_inv3 * (e1.x + e2.x); center.y += triangleArea * k_inv3 * (e1.y + e2.y); final double ex1 = e1.x, ey1 = e1.y; final double ex2 = e2.x, ey2 = e2.y; double intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2; double inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2; I += (0.25 * k_inv3 * D) * (intx2 + inty2); } // Total mass massData.mass = density * area; // Center of mass assert(area > Settings.EPSILON); center.scale(1.0 / area); massData.center ..setFrom(center) ..add(s); // Inertia tensor relative to the local origin (point s) massData.I = I * density; // Shift to center of mass then to original body origin. massData.I += massData.mass * (massData.center.dot(massData.center)); } /// Validate convexity. This is a very time consuming operation. bool validate() { for (int i = 0; i < count; ++i) { int i1 = i; int i2 = i < count - 1 ? i1 + 1 : 0; Vector2 p = vertices[i1]; Vector2 e = _pool1 ..setFrom(vertices[i2]) ..sub(p); for (int j = 0; j < count; ++j) { if (j == i1 || j == i2) { continue; } Vector2 v = _pool2 ..setFrom(vertices[j]) ..sub(p); double c = e.cross(v); if (c < 0.0) { return false; } } } return true; } /// Get the centroid and apply the supplied transform. Vector2 applyToCentroid(final Transform xf) { return Transform.mulVec2(xf, centroid); } /// Get the centroid and apply the supplied transform. Vector2 centroidToOut(final Transform xf, final Vector2 out) { Transform.mulToOutUnsafeVec2(xf, centroid, out); return out; } }
box2d.dart/lib/src/collision/shapes/polygon_shape.dart/0
{'file_path': 'box2d.dart/lib/src/collision/shapes/polygon_shape.dart', 'repo_id': 'box2d.dart', 'token_count': 8620}
part of box2d; /// The body type. /// static: zero mass, zero velocity, may be manually moved /// kinematic: zero mass, non-zero velocity set by user, moved by solver /// dynamic: positive mass, non-zero velocity determined by forces, moved by solver enum BodyType { STATIC, KINEMATIC, DYNAMIC }
box2d.dart/lib/src/dynamics/body_type.dart/0
{'file_path': 'box2d.dart/lib/src/dynamics/body_type.dart', 'repo_id': 'box2d.dart', 'token_count': 87}
/******************************************************************************* * 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; /// The base joint class. Joints are used to constrain two bodies together in various fashions. Some /// joints also feature limits and motors. abstract class Joint { static Joint create(World world, JointDef def) { switch (def.type) { case JointType.MOUSE: return new MouseJoint(world.getPool(), def as MouseJointDef); case JointType.DISTANCE: return new DistanceJoint(world.getPool(), def as DistanceJointDef); case JointType.PRISMATIC: return new PrismaticJoint(world.getPool(), def as PrismaticJointDef); case JointType.REVOLUTE: return new RevoluteJoint(world.getPool(), def as RevoluteJointDef); case JointType.WELD: return new WeldJoint(world.getPool(), def as WeldJointDef); case JointType.FRICTION: return new FrictionJoint(world.getPool(), def as FrictionJointDef); case JointType.WHEEL: return new WheelJoint(world.getPool(), def as WheelJointDef); case JointType.GEAR: return new GearJoint(world.getPool(), def as GearJointDef); case JointType.PULLEY: return new PulleyJoint(world.getPool(), def as PulleyJointDef); case JointType.CONSTANT_VOLUME: return new ConstantVolumeJoint(world, def as ConstantVolumeJointDef); case JointType.ROPE: return new RopeJoint(world.getPool(), def as RopeJointDef); case JointType.MOTOR: return new MotorJoint(world.getPool(), def as MotorJointDef); case JointType.UNKNOWN: default: return null; } } static void destroy(Joint joint) { joint.destructor(); } final JointType _type; Joint _prev; Joint _next; JointEdge _edgeA; JointEdge _edgeB; Body _bodyA; Body _bodyB; bool _islandFlag = false; bool _collideConnected = false; IWorldPool pool; Joint(IWorldPool worldPool, JointDef def) : _type = def.type { assert(def.bodyA != def.bodyB); pool = worldPool; _prev = null; _next = null; _bodyA = def.bodyA; _bodyB = def.bodyB; _collideConnected = def.collideConnected; _islandFlag = false; _edgeA = new JointEdge(); _edgeA.joint = null; _edgeA.other = null; _edgeA.prev = null; _edgeA.next = null; _edgeB = new JointEdge(); _edgeB.joint = null; _edgeB.other = null; _edgeB.prev = null; _edgeB.next = null; } /// get the type of the concrete joint. /// /// @return JointType getType() { return _type; } /// get the first body attached to this joint. Body getBodyA() { return _bodyA; } /// get the second body attached to this joint. /// /// @return Body getBodyB() { return _bodyB; } /// get the anchor point on bodyA in world coordinates. /// /// @return void getAnchorA(Vector2 out); /// get the anchor point on bodyB in world coordinates. /// /// @return void getAnchorB(Vector2 out); /// get the reaction force on body2 at the joint anchor in Newtons. /// /// @param inv_dt /// @return void getReactionForce(double inv_dt, Vector2 out); /// get the reaction torque on body2 in N*m. /// /// @param inv_dt /// @return double getReactionTorque(double inv_dt); /// get the next joint the world joint list. Joint getNext() { return _next; } /// Get collide connected. Note: modifying the collide connect flag won't work correctly because /// the flag is only checked when fixture AABBs begin to overlap. bool getCollideConnected() { return _collideConnected; } /// Short-cut function to determine if either body is inactive. /// /// @return bool isActive() { return _bodyA.isActive() && _bodyB.isActive(); } /// Internal void initVelocityConstraints(SolverData data); /// Internal void solveVelocityConstraints(SolverData data); /// This returns true if the position errors are within tolerance. Internal. bool solvePositionConstraints(SolverData data); /// Override to handle destruction of joint void destructor() {} }
box2d.dart/lib/src/dynamics/joints/joint.dart/0
{'file_path': 'box2d.dart/lib/src/dynamics/joints/joint.dart', 'repo_id': 'box2d.dart', 'token_count': 1850}
export 'src/bezier_curve.dart'; export 'src/path.dart'; export 'src/quadratic_curve.dart';
brache/packages/brache/lib/src/components/src/paths/paths.dart/0
{'file_path': 'brache/packages/brache/lib/src/components/src/paths/paths.dart', 'repo_id': 'brache', 'token_count': 40}
import 'dart:async'; class AnimationController { AnimationController({ required this.duration, required this.onUpdate, required this.onComplete, }); Duration duration; final Function(double) onUpdate; final Function onComplete; late DateTime _startTime; Timer? _timer; void start() { _startTime = DateTime.now(); _timer = Timer.periodic(const Duration(milliseconds: 16), _tick); } void _tick(Timer timer) { final elapsed = DateTime.now().difference(_startTime); if (elapsed > duration) { timer.cancel(); onComplete(); return; } onUpdate(elapsed.inMilliseconds / duration.inMilliseconds); } void dispose() { _timer?.cancel(); } }
brache/packages/brache/lib/src/core/src/component/animation_controller.dart/0
{'file_path': 'brache/packages/brache/lib/src/core/src/component/animation_controller.dart', 'repo_id': 'brache', 'token_count': 258}
// 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:build/build.dart'; class _SomeBuilder implements Builder { const _SomeBuilder(); factory _SomeBuilder.fromOptions(BuilderOptions options) { if (options.config['throw_in_constructor'] == true) { throw StateError('Throwing on purpose cause you asked for it!'); } return const _SomeBuilder(); } @override final buildExtensions = const { '.dart': ['.something.dart'] }; @override Future build(BuildStep buildStep) async { if (!await buildStep.canRead(buildStep.inputId)) return; await buildStep.writeAsBytes( buildStep.inputId.changeExtension('.something.dart'), buildStep.readAsBytes(buildStep.inputId)); } } class _SomePostProcessBuilder extends PostProcessBuilder { @override final inputExtensions = const ['.txt']; final String? defaultContent; _SomePostProcessBuilder.fromOptions(BuilderOptions options) : defaultContent = options.config['default_content'] as String?; @override Future<void> build(PostProcessBuildStep buildStep) async { var content = defaultContent ?? await buildStep.readInputAsString(); await buildStep.writeAsString( buildStep.inputId.changeExtension('.txt.post'), content); } } class _ThrowingBuilder extends Builder { @override final buildExtensions = { '.fail': ['.fail.message'] }; @override Future<void> build(BuildStep buildStep) async { throw UnsupportedError(await buildStep.readAsString(buildStep.inputId)); } } Builder someBuilder(BuilderOptions options) => _SomeBuilder.fromOptions(options); Builder notApplied(BuilderOptions options) => _SomeBuilder.fromOptions(options); PostProcessBuilder somePostProcessBuilder(BuilderOptions options) => _SomePostProcessBuilder.fromOptions(options); Builder throwingBuilder(_) => _ThrowingBuilder();
build/_test/pkgs/provides_builder/lib/builders.dart/0
{'file_path': 'build/_test/pkgs/provides_builder/lib/builders.dart', 'repo_id': 'build', 'token_count': 634}
// 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:build/build.dart'; class CopyingPostProcessBuilder implements PostProcessBuilder { final String outputExtension; @override final inputExtensions = ['.txt']; CopyingPostProcessBuilder({this.outputExtension = '.copy'}); @override Future<void> build(PostProcessBuildStep buildStep) async { await buildStep.writeAsString( buildStep.inputId.addExtension(outputExtension), await buildStep.readInputAsString()); } } class DeletePostProcessBuilder implements PostProcessBuilder { @override final inputExtensions = ['.txt']; DeletePostProcessBuilder(); @override Future<void> build(PostProcessBuildStep buildStep) async { buildStep.deletePrimaryInput(); } } /// A [Builder] which behaves exactly like it's [delegate] but has a different /// runtime type. class DelegatingBuilder implements Builder { final Builder delegate; DelegatingBuilder(this.delegate); @override Map<String, List<String>> get buildExtensions => delegate.buildExtensions; @override Future build(BuildStep buildStep) async => delegate.build(buildStep); }
build/_test_common/lib/builders.dart/0
{'file_path': 'build/_test_common/lib/builders.dart', 'repo_id': 'build', 'token_count': 391}
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:analyzer/dart/analysis/results.dart'; import 'package:analyzer/dart/analysis/session.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/error/error.dart'; import '../asset/id.dart'; import '../builder/build_step.dart'; /// Standard interface for resolving Dart source code as part of a build. abstract class Resolver { /// Returns whether [assetId] represents an Dart library file. /// /// This will be `false` in the case where the file is not Dart source code, /// or is a `part of` file (not a standalone Dart library). Future<bool> isLibrary(AssetId assetId); /// All libraries recursively accessible from the entry point or subsequent /// calls to [libraryFor] and [isLibrary]. /// /// **NOTE**: This includes all Dart SDK libraries as well. Stream<LibraryElement> get libraries; /// Returns the parsed [AstNode] for [Element]. /// /// This should always be preferred over using the [AnalysisSession] /// directly, because it avoids [InconsistentAnalysisException] issues. /// /// If [resolve] is `true` then you will get a resolved ast node, otherwise /// it will only be a parsed ast node. /// /// Returns `null` if the ast node can not be found. This can happen if an /// element is coming from a summary, or is unavailable for some other /// reason. Future<AstNode?> astNodeFor(Element element, {bool resolve = false}); /// Returns a parsed AST structor representing the file defined in [assetId]. /// /// * If the [assetId] has syntax errors, and [allowSyntaxErrors] is set to /// `false` (the default), throws a [SyntaxErrorInAssetException]. /// /// This is a much cheaper api compared to [libraryFor], because it will only /// parse a single file and does not give you a resolved element model. Future<CompilationUnit> compilationUnitFor(AssetId assetId, {bool allowSyntaxErrors = false}); /// Returns a resolved library representing the file defined in [assetId]. /// /// * Throws [NonLibraryAssetException] if [assetId] is not a Dart library. /// * If the [assetId] has syntax errors, and [allowSyntaxErrors] is set to /// `false` (the default), throws a [SyntaxErrorInAssetException]. Future<LibraryElement> libraryFor(AssetId assetId, {bool allowSyntaxErrors = false}); /// Returns the first resolved library identified by [libraryName]. /// /// A library is resolved if it's recursively accessible from the entry point /// or subsequent calls to [libraryFor] and [isLibrary]. If no library can be /// found, returns `null`. /// /// **NOTE**: In general, its recommended to use [libraryFor] with an absolute /// asset id instead of a named identifier that has the possibility of not /// being unique. Future<LibraryElement?> findLibraryByName(String libraryName); /// Returns the [AssetId] of the Dart library or part declaring [element]. /// /// If [element] is defined in the SDK or in a summary throws /// `UnresolvableAssetException`, although a non-throwing return here does not /// guarantee that the asset is readable. /// /// The returned asset is not necessarily the asset that should be imported to /// use the element, it may be a part file instead of the library. Future<AssetId> assetIdForElement(Element element); } /// A resolver that should be manually released at the end of a build step. abstract class ReleasableResolver implements Resolver { /// Release this resolver so it can be updated by following build steps. void release(); } /// A factory that returns a resolver for a given [BuildStep]. abstract class Resolvers { const Resolvers(); Future<ReleasableResolver> get(BuildStep buildStep); /// Reset the state of any caches within [Resolver] instances produced by /// this [Resolvers]. /// /// In between calls to [reset] no Assets should change, so every call to /// `BuildStep.readAsString` for a given AssetId should return identical /// contents. Any time an Asset's contents may change [reset] must be called. void reset() {} } /// Thrown when attempting to read a non-Dart library in a [Resolver]. class NonLibraryAssetException implements Exception { final AssetId assetId; const NonLibraryAssetException(this.assetId); @override String toString() => 'Asset [$assetId] is not a Dart library. ' 'It may be a part file or a file without Dart source code.'; } /// Exception thrown by a resolver when attempting to resolve a Dart library /// with syntax errors. /// /// Builders are not expected to catch this exception unless they have special /// behavior for inputs with syntax errors. This exception has a descriptive /// [toString] implementation that the build system will show to users. class SyntaxErrorInAssetException implements Exception { static const _maxErrorsInToString = 3; /// The syntactically invalid [AssetId] that couldn't be resolved. final AssetId assetId; /// A list analysis error results for files related to the [assetId]. /// /// In addition to the asset itself, the resolver also considers syntax errors /// in part files. final List<AnalysisResultWithErrors> filesWithErrors; SyntaxErrorInAssetException(this.assetId, this.filesWithErrors) : assert(filesWithErrors.isNotEmpty); /// The errors reported by the parser when trying to resolve the [assetId]. /// /// This only contains syntax errors since most semantic errors are expected /// during a build (e.g. due to missing part files that haven't been generated /// yet). Iterable<AnalysisError> get syntaxErrors { return filesWithErrors .expand((result) => result.errors) .where(_isSyntaxError); } /// A map from [syntaxErrors] to per-file results Map<AnalysisError, AnalysisResultWithErrors> get errorToResult { return { for (final file in filesWithErrors) for (final error in file.errors) if (_isSyntaxError(error)) error: file, }; } bool _isSyntaxError(AnalysisError error) { return error.errorCode.type == ErrorType.SYNTACTIC_ERROR; } @override String toString() { final buffer = StringBuffer() ..writeln('This builder requires Dart inputs without syntax errors.') ..writeln('However, ${assetId.uri} (or an existing part) contains the ' 'following errors.'); // Avoid generating too much output for syntax errors. The user likely has // an editor that shows them anyway. final entries = errorToResult.entries.toList(); for (final errorAndResult in entries.take(_maxErrorsInToString)) { final error = errorAndResult.key; // Use a short name: We present the full context by including the asset id // and this is easier to skim through final sourceName = error.source.shortName; final lineInfo = errorAndResult.value.lineInfo; final position = lineInfo.getLocation(error.offset); // Output messages like "foo.dart:3:4: Expected a semicolon here." buffer.writeln( '$sourceName:${position.lineNumber}:${position.columnNumber}: ' '${error.message}'); } final additionalErrors = entries.length - _maxErrorsInToString; if (additionalErrors > 0) { buffer.writeln('And $additionalErrors more...'); } buffer.writeln('\nTry fixing the errors and re-running the build.'); return buffer.toString(); } }
build/build/lib/src/analyzer/resolver.dart/0
{'file_path': 'build/build/lib/src/analyzer/resolver.dart', 'repo_id': 'build', 'token_count': 2231}
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:logging/logging.dart'; import '../analyzer/resolver.dart'; import '../asset/id.dart'; import '../asset/reader.dart'; import '../asset/writer.dart'; import '../builder/build_step.dart'; import '../builder/build_step_impl.dart'; import '../builder/builder.dart'; import '../builder/logging.dart'; import '../resource/resource.dart'; import 'expected_outputs.dart'; /// Run [builder] with each asset in [inputs] as the primary input. /// /// Builds for all inputs are run asynchronously and ordering is not guaranteed. /// The [log] instance inside the builds will be scoped to [logger] which is /// defaulted to a [Logger] name 'runBuilder'. /// /// If a [resourceManager] is provided it will be used and it will not be /// automatically disposed of (its up to the caller to dispose of it later). If /// one is not provided then one will be created and disposed at the end of /// this function call. /// /// If [reportUnusedAssetsForInput] is provided then all calls to /// `BuildStep.reportUnusedAssets` in [builder] will be forwarded to this /// function with the associated primary input. Future<void> runBuilder(Builder builder, Iterable<AssetId> inputs, AssetReader reader, AssetWriter writer, Resolvers? resolvers, {Logger? logger, ResourceManager? resourceManager, StageTracker stageTracker = NoOpStageTracker.instance, void Function(AssetId input, Iterable<AssetId> assets)? reportUnusedAssetsForInput}) async { var shouldDisposeResourceManager = resourceManager == null; final resources = resourceManager ?? ResourceManager(); logger ??= Logger('runBuilder'); //TODO(nbosch) check overlapping outputs? Future<void> buildForInput(AssetId input) async { var outputs = expectedOutputs(builder, input); if (outputs.isEmpty) return; var buildStep = BuildStepImpl( input, outputs, reader, writer, resolvers, resources, stageTracker: stageTracker, reportUnusedAssets: reportUnusedAssetsForInput == null ? null : (assets) => reportUnusedAssetsForInput(input, assets)); try { await builder.build(buildStep); } finally { await buildStep.complete(); } } await scopeLogAsync(() => Future.wait(inputs.map(buildForInput)), logger); if (shouldDisposeResourceManager) { await resources.disposeAll(); await resources.beforeExit(); } }
build/build/lib/src/generate/run_builder.dart/0
{'file_path': 'build/build/lib/src/generate/run_builder.dart', 'repo_id': 'build', 'token_count': 810}
name: build_config version: 1.1.0 description: Support for parsing `build.yaml` configuration. repository: https://github.com/dart-lang/build/tree/master/build_config environment: sdk: '>=2.14.0 <3.0.0' dependencies: checked_yaml: ^2.0.0 json_annotation: ^4.5.0 path: ^1.8.0 pubspec_parse: ^1.0.0 yaml: ^3.0.0 dev_dependencies: build_runner: ^2.0.0 lints: '>=1.0.0 <3.0.0' json_serializable: ^6.0.0 term_glyph: ^1.2.0 test: ^1.16.0
build/build_config/pubspec.yaml/0
{'file_path': 'build/build_config/pubspec.yaml', 'repo_id': 'build', 'token_count': 217}
import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; import 'build_status.dart'; part 'build_target.g.dart'; /// The string representation of a build target, e.g. folder path. abstract class BuildTarget { String get target; } abstract class DefaultBuildTarget implements BuildTarget, Built<DefaultBuildTarget, DefaultBuildTargetBuilder> { static Serializer<DefaultBuildTarget> get serializer => _$defaultBuildTargetSerializer; @BuiltValueHook(initializeBuilder: true) static void _setDefaults(DefaultBuildTargetBuilder b) => b.reportChangedAssets = false; factory DefaultBuildTarget([void Function(DefaultBuildTargetBuilder) b]) = _$DefaultBuildTarget; DefaultBuildTarget._(); /// A set of file path patterns to match changes against. /// /// If a change matches a pattern this target will not be built. BuiltSet<RegExp> get blackListPatterns; OutputLocation? get outputLocation; /// A set of globs patterns for files to build. /// /// Relative glob paths (from the package) root as well as `package:` uris /// are supported. In the case of a `package:` uri glob syntax is supported /// for the package name as well as the path. /// /// If null then the default is the following patterns: /// - package:*/** /// - $target/** BuiltSet<String>? get buildFilters; /// Whether the [BuildResults] events emitted for this target should report a /// list of assets invalidated in a build. /// /// This defaults to `false` to reduce the serialization overhead when this /// information is not required. bool get reportChangedAssets; } /// The location to write the build outputs. abstract class OutputLocation implements Built<OutputLocation, OutputLocationBuilder> { static Serializer<OutputLocation> get serializer => _$outputLocationSerializer; factory OutputLocation([Function(OutputLocationBuilder b) updates]) = _$OutputLocation; OutputLocation._(); String get output; /// Whether to use symlinks for build outputs. bool get useSymlinks; /// Whether to hoist the build output. /// /// Hoisted outputs will not contain the build target folder within their /// path. /// /// For example hoisting the build target web: /// <web>/<web-contents> /// Should result in: /// <output-folder>/<web-contents> bool get hoist; }
build/build_daemon/lib/data/build_target.dart/0
{'file_path': 'build/build_daemon/lib/data/build_target.dart', 'repo_id': 'build', 'token_count': 712}
// 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:build/build.dart'; import 'package:graphs/graphs.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:path/path.dart' as p; import 'common.dart'; import 'module_library.dart'; import 'modules.dart'; import 'platform.dart'; part 'meta_module.g.dart'; /// Returns the top level directory in [path]. /// /// Throws an [ArgumentError] if [path] is just a filename with no directory. String _topLevelDir(String path) { var parts = p.url.split(p.url.normalize(path)); String? error; if (parts.length == 1) { error = 'The path `$path` does not contain a directory.'; } else if (parts.first == '..') { error = 'The path `$path` reaches outside the root directory.'; } if (error != null) { throw ArgumentError( 'Cannot compute top level dir for path `$path`. $error'); } return parts.first; } /// Creates a module containing [componentLibraries]. Module _moduleForComponent( List<ModuleLibrary> componentLibraries, DartPlatform platform) { // Name components based on first alphabetically sorted node, preferring // public srcs (not under lib/src). var sources = componentLibraries.map((n) => n.id).toSet(); var nonSrcIds = sources.where((id) => !id.path.startsWith('lib/src/')); var primaryId = nonSrcIds.isNotEmpty ? nonSrcIds.reduce(_min) : sources.reduce(_min); // Expand to include all the part files of each node, these aren't // included as individual `_AssetNodes`s in `connectedComponents`. sources.addAll(componentLibraries.expand((n) => n.parts)); var directDependencies = <AssetId>{} ..addAll(componentLibraries.expand((n) => n.depsForPlatform(platform))) ..removeAll(sources); var isSupported = componentLibraries .expand((l) => l.sdkDeps) .every(platform.supportsLibrary); return Module(primaryId, sources, directDependencies, platform, isSupported); } /// Gets the local (same top level dir of the same package) transitive deps of /// [module] using [assetsToModules]. Set<AssetId> _localTransitiveDeps( Module module, Map<AssetId, Module> assetsToModules) { var localTransitiveDeps = <AssetId>{}; var nextIds = module.directDependencies; var seenIds = <AssetId>{}; while (nextIds.isNotEmpty) { var ids = nextIds; seenIds.addAll(ids); nextIds = <AssetId>{}; for (var id in ids) { var module = assetsToModules[id]; if (module == null) continue; // Skip non-local modules if (localTransitiveDeps.add(module.primarySource)) { nextIds.addAll(module.directDependencies.difference(seenIds)); } } } return localTransitiveDeps; } /// Creates a map of modules to the entrypoint modules that transitively /// depend on those modules. Map<AssetId, Set<AssetId>> _findReverseEntrypointDeps( Iterable<Module> entrypointModules, Iterable<Module> modules) { var reverseDeps = <AssetId, Set<AssetId>>{}; var assetsToModules = <AssetId, Module>{}; for (var module in modules) { for (var assetId in module.sources) { assetsToModules[assetId] = module; } } for (var module in entrypointModules) { for (var moduleDep in _localTransitiveDeps(module, assetsToModules)) { reverseDeps .putIfAbsent(moduleDep, () => <AssetId>{}) .add(module.primarySource); } } return reverseDeps; } /// Merges [modules] into a minimum set of [Module]s using the /// following rules: /// /// * If it is an entrypoint module do not merge it. /// * If it is not depended on my any entrypoint do not merge it. /// * If it is depended on by no entrypoint merge it into the entrypoint /// modules /// * Else merge it into with others that are depended on by the same set of /// entrypoints List<Module> _mergeModules(Iterable<Module> modules, Set<AssetId> entrypoints) { var entrypointModules = modules.where((m) => m.sources.any(entrypoints.contains)).toList(); // Groups of modules that can be merged into an existing entrypoint module. var entrypointModuleGroups = { for (var m in entrypointModules) m.primarySource: [m], }; // Maps modules to entrypoint modules that transitively depend on them. var modulesToEntryPoints = _findReverseEntrypointDeps(entrypointModules, modules); // Modules which are not depended on by any entrypoint var standaloneModules = <Module>[]; // Modules which are merged with others. var mergedModules = <String, List<Module>>{}; for (var module in modules) { // Skip entrypoint modules. if (entrypointModuleGroups.containsKey(module.primarySource)) continue; // The entry points that transitively import this module. var entrypointIds = modulesToEntryPoints[module.primarySource]; // If no entrypoint imports the module, just leave it alone. if (entrypointIds == null || entrypointIds.isEmpty) { standaloneModules.add(module); continue; } // If there are multiple entry points for a given resource we must create // a new shared module. Use `$` to signal that it is a shared module. if (entrypointIds.length > 1) { var mId = (entrypointIds.toList()..sort()).map((m) => m.path).join('\$'); mergedModules.putIfAbsent(mId, () => []).add(module); } else { entrypointModuleGroups[entrypointIds.single]!.add(module); } } return [ for (var module in mergedModules.values) _withConsistentPrimarySource(Module.merge(module)), for (var module in entrypointModuleGroups.values) Module.merge(module), ...standaloneModules ]; } Module _withConsistentPrimarySource(Module m) => Module(m.sources.reduce(_min), m.sources, m.directDependencies, m.platform, m.isSupported); T _min<T extends Comparable<T>>(T a, T b) => a.compareTo(b) < 0 ? a : b; /// Compute modules for the internal strongly connected components of /// [libraries]. /// /// This should only be called with [libraries] all in the same package and top /// level directory within the package. /// /// A dependency is considered "internal" if it is within [libraries]. Any /// "external" deps are ignored during this computation since we are only /// considering the strongly connected components within [libraries], but they /// will be maintained as a dependency of the module to be used at a later step. /// /// Part files are also tracked but ignored during computation of strongly /// connected components, as they must always be a part of the containing /// library's module. List<Module> _computeModules( Map<AssetId, ModuleLibrary> libraries, DartPlatform platform) { assert(() { var dir = _topLevelDir(libraries.values.first.id.path); return libraries.values.every((l) => _topLevelDir(l.id.path) == dir); }()); final connectedComponents = stronglyConnectedComponents<ModuleLibrary>( libraries.values, (n) => n .depsForPlatform(platform) // Only "internal" dependencies .where(libraries.containsKey) .map((dep) => libraries[dep]!), equals: (a, b) => a.id == b.id, hashCode: (l) => l.id.hashCode); final entryIds = libraries.values.where((l) => l.isEntryPoint).map((l) => l.id).toSet(); return _mergeModules( connectedComponents.map((c) => _moduleForComponent(c, platform)), entryIds); } @JsonSerializable() class MetaModule { @JsonKey(name: 'm') final List<Module> modules; MetaModule(List<Module> modules) : modules = List.unmodifiable(modules); /// Generated factory constructor. factory MetaModule.fromJson(Map<String, dynamic> json) => _$MetaModuleFromJson(json); Map<String, dynamic> toJson() => _$MetaModuleToJson(this); static Future<MetaModule> forLibraries( AssetReader reader, List<AssetId> libraryIds, ModuleStrategy strategy, DartPlatform platform) async { var libraries = <ModuleLibrary>[]; for (var id in libraryIds) { libraries.add(ModuleLibrary.deserialize( id.changeExtension('').changeExtension('.dart'), await reader.readAsString(id))); } switch (strategy) { case ModuleStrategy.fine: return _fineModulesForLibraries(reader, libraries, platform); case ModuleStrategy.coarse: return _coarseModulesForLibraries(reader, libraries, platform); } } } MetaModule _coarseModulesForLibraries( AssetReader reader, List<ModuleLibrary> libraries, DartPlatform platform) { var librariesByDirectory = <String, Map<AssetId, ModuleLibrary>>{}; for (var library in libraries) { final dir = _topLevelDir(library.id.path); (librariesByDirectory[dir] ??= {})[library.id] = library; } final modules = [ for (var libraries in librariesByDirectory.values) ..._computeModules(libraries, platform) ]; _sortModules(modules); return MetaModule(modules); } MetaModule _fineModulesForLibraries( AssetReader reader, List<ModuleLibrary> libraries, DartPlatform platform) { var modules = [ for (var library in libraries) Module( library.id, [...library.parts, library.id], library.depsForPlatform(platform), platform, library.sdkDeps.every(platform.supportsLibrary)) ]; _sortModules(modules); return MetaModule(modules); } /// Sorts [modules] in place so we get deterministic output. void _sortModules(List<Module> modules) { modules.sort((a, b) => a.primarySource.compareTo(b.primarySource)); }
build/build_modules/lib/src/meta_module.dart/0
{'file_path': 'build/build_modules/lib/src/meta_module.dart', 'repo_id': 'build', 'token_count': 3297}
// 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. @Tags(['presubmit-only']) @OnPlatform({'windows': Skip('line endings are different')}) import 'dart:convert'; import 'dart:io'; import 'package:path/path.dart' as p; import 'package:test/test.dart'; // TODO: Generalize this test and move it to package:build_test. This is copied // wholesale from the json_serializable package. void main() { String pkgRoot; try { pkgRoot = _runProc('git', ['rev-parse', '--show-toplevel']); var currentDir = Directory.current.resolveSymbolicLinksSync(); if (!p.isWithin(pkgRoot, currentDir)) { throw StateError('Expected the git root ($pkgRoot) ' 'to be a parent of the current directory ($currentDir).'); } } catch (e) { print("Skipping this test – git didn't run correctly"); print(e); return; } test('ensure local build succeeds with no changes', () { // 1 - get a list of modified `.g.dart` files - should be empty expect(_changedGeneratedFiles(), isEmpty); // 2 - run build - should be no output, since nothing should change var result = _runProc('dart', ['run', 'build_runner', 'build', '--delete-conflicting-outputs']); expect(result, contains(RegExp(r'Succeeded after \S+( \S+)? with \d+ outputs'))); // 3 - get a list of modified `.g.dart` files - should still be empty expect(_changedGeneratedFiles(), isEmpty); }); } final _whitespace = RegExp(r'\s'); Set<String> _changedGeneratedFiles() { var output = _runProc('git', ['status', '--porcelain']); return LineSplitter.split(output) .map((line) => line.split(_whitespace).last) .where((path) => path.endsWith('.g.dart')) .toSet(); } String _runProc(String proc, List<String> args) { var result = Process.runSync(proc, args); if (result.exitCode != 0) { throw ProcessException( proc, args, 'Stdout:\n${result.stdout}\n\nStderr:\n${result.stderr}', result.exitCode); } var stderr = result.stderr as String; if (stderr.isNotEmpty) print('stderr: $stderr'); return (result.stdout as String).trim(); }
build/build_modules/test/build_test.dart/0
{'file_path': 'build/build_modules/test/build_test.dart', 'repo_id': 'build', 'token_count': 842}