code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
export 'firebase.dart'; export 'version.dart';
flutter_and_friends/lib/config/config.dart/0
{'file_path': 'flutter_and_friends/lib/config/config.dart', 'repo_id': 'flutter_and_friends', 'token_count': 17}
export './launchpad_page.dart';
flutter_and_friends/lib/launchpad/view/view.dart/0
{'file_path': 'flutter_and_friends/lib/launchpad/view/view.dart', 'repo_id': 'flutter_and_friends', 'token_count': 12}
export 'activity.dart'; export 'event.dart'; export 'location.dart'; export 'schedule.dart'; export 'speaker.dart'; export 'talk.dart'; export 'workshop.dart';
flutter_and_friends/lib/schedule/models/models.dart/0
{'file_path': 'flutter_and_friends/lib/schedule/models/models.dart', 'repo_id': 'flutter_and_friends', 'token_count': 58}
import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter_and_friends/config/config.dart'; import 'package:pub_semver/pub_semver.dart'; import 'package:shorebird_code_push/shorebird_code_push.dart'; part 'settings_state.dart'; class SettingsCubit extends Cubit<SettingsState> { SettingsCubit({ShorebirdCodePush? codePush}) : _codePush = codePush ?? ShorebirdCodePush(), super(SettingsState(version: version)); final ShorebirdCodePush _codePush; Future<void> init() async { final patchNumber = await _codePush.currentPatchNumber(); emit(state.copyWith(patchNumber: patchNumber)); } }
flutter_and_friends/lib/settings/cubit/settings_cubit.dart/0
{'file_path': 'flutter_and_friends/lib/settings/cubit/settings_cubit.dart', 'repo_id': 'flutter_and_friends', 'token_count': 223}
part of 'theme_cubit.dart'; enum ThemeState { light, dark }
flutter_and_friends/lib/theme/cubit/theme_state.dart/0
{'file_path': 'flutter_and_friends/lib/theme/cubit/theme_state.dart', 'repo_id': 'flutter_and_friends', 'token_count': 23}
import 'package:flutter/material.dart'; import 'package:flutter_animations_workshop/pages/home_page.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', debugShowCheckedModeBanner: false, theme: ThemeData( scaffoldBackgroundColor: const Color(0xff131A3B), primarySwatch: Colors.blue, ), home: const HomePage(), ); } }
flutter_animations_workshop/lib/main.dart/0
{'file_path': 'flutter_animations_workshop/lib/main.dart', 'repo_id': 'flutter_animations_workshop', 'token_count': 216}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. // A poor man's DI. This should be replaced by a proper solution once they // are more stable. library dependency_injector; import 'package:blocs/blocs.dart'; import 'package:flutter/widgets.dart'; import 'package:meta/meta.dart'; import 'package:todos_repository_core/todos_repository_core.dart'; class Injector extends InheritedWidget { final TodosInteractor todosInteractor; final UserRepository userRepository; Injector({ Key key, @required this.todosInteractor, @required this.userRepository, @required Widget child, }) : super(key: key, child: child); static Injector of(BuildContext context) => context.dependOnInheritedWidgetOfExactType<Injector>(); @override bool updateShouldNotify(Injector oldWidget) => todosInteractor != oldWidget.todosInteractor || userRepository != oldWidget.userRepository; }
flutter_architecture_samples/bloc_flutter/lib/dependency_injection.dart/0
{'file_path': 'flutter_architecture_samples/bloc_flutter/lib/dependency_injection.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 337}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. // This line imports the extension import 'package:bloc_flutter_sample/main.dart' as app; import 'package:flutter_driver/driver_extension.dart'; void main() { enableFlutterDriverExtension(); app.main(); }
flutter_architecture_samples/bloc_flutter/test_driver/todo_app.dart/0
{'file_path': 'flutter_architecture_samples/bloc_flutter/test_driver/todo_app.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 110}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'dart:async'; import 'package:bloc/bloc.dart'; import 'package:meta/meta.dart'; import 'package:bloc_library/blocs/filtered_todos/filtered_todos.dart'; import 'package:bloc_library/blocs/todos/todos.dart'; import 'package:bloc_library/models/models.dart'; class FilteredTodosBloc extends Bloc<FilteredTodosEvent, FilteredTodosState> { final TodosBloc todosBloc; StreamSubscription todosSubscription; FilteredTodosBloc({@required this.todosBloc}) { todosSubscription = todosBloc.listen((state) { if (state is TodosLoaded) { add(UpdateTodos(state.todos)); } }); } @override FilteredTodosState get initialState { return todosBloc.state is TodosLoaded ? FilteredTodosLoaded( (todosBloc.state as TodosLoaded).todos, VisibilityFilter.all, ) : FilteredTodosLoading(); } @override Stream<FilteredTodosState> mapEventToState(FilteredTodosEvent event) async* { if (event is UpdateFilter) { yield* _mapUpdateFilterToState(event); } else if (event is UpdateTodos) { yield* _mapTodosUpdatedToState(event); } } Stream<FilteredTodosState> _mapUpdateFilterToState( UpdateFilter event, ) async* { if (todosBloc.state is TodosLoaded) { yield FilteredTodosLoaded( _mapTodosToFilteredTodos( (todosBloc.state as TodosLoaded).todos, event.filter, ), event.filter, ); } } Stream<FilteredTodosState> _mapTodosUpdatedToState( UpdateTodos event, ) async* { final visibilityFilter = state is FilteredTodosLoaded ? (state as FilteredTodosLoaded).activeFilter : VisibilityFilter.all; yield FilteredTodosLoaded( _mapTodosToFilteredTodos( (todosBloc.state as TodosLoaded).todos, visibilityFilter, ), visibilityFilter, ); } List<Todo> _mapTodosToFilteredTodos( List<Todo> todos, VisibilityFilter filter, ) { return todos.where((todo) { if (filter == VisibilityFilter.all) { return true; } else if (filter == VisibilityFilter.active) { return !todo.complete; } else { return todo.complete; } }).toList(); } @override Future<void> close() { todosSubscription?.cancel(); return super.close(); } }
flutter_architecture_samples/bloc_library/lib/blocs/filtered_todos/filtered_todos_bloc.dart/0
{'file_path': 'flutter_architecture_samples/bloc_library/lib/blocs/filtered_todos/filtered_todos_bloc.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1082}
import 'package:bloc_library/run_app.dart'; import 'package:flutter/cupertino.dart'; import 'package:key_value_store_flutter/key_value_store_flutter.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:todos_repository_local_storage/todos_repository_local_storage.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); runBlocLibraryApp(LocalStorageRepository( localStorage: KeyValueStorage( 'bloc_library', FlutterKeyValueStore(await SharedPreferences.getInstance()), ), )); }
flutter_architecture_samples/bloc_library/lib/main.dart/0
{'file_path': 'flutter_architecture_samples/bloc_library/lib/main.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 201}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:bloc_library/blocs/blocs.dart'; import 'package:bloc_library/models/models.dart'; void main() { group('TodosState', () { group('TodosLoading', () { test('toString returns correct value', () { expect( TodosLoading().toString(), 'TodosLoading', ); }); }); group('TodosLoaded', () { test('toString returns correct value', () { expect( TodosLoaded([Todo('wash car', id: '0')]).toString(), 'TodosLoaded { todos: [${Todo("wash car", id: "0")}] }', ); }); }); group('TodosNotLoaded', () { test('toString returns correct value', () { expect( TodosNotLoaded().toString(), 'TodosNotLoaded', ); }); }); }); }
flutter_architecture_samples/bloc_library/test/blocs/todos_state_test.dart/0
{'file_path': 'flutter_architecture_samples/bloc_library/test/blocs/todos_state_test.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 442}
import 'stats_bloc_test.dart' as statsBloc; import 'todo_bloc_test.dart' as todoBloc; import 'todos_bloc_test.dart' as todosBloc; import 'todos_interactor_test.dart' as todosInteractor; void main() { statsBloc.main(); todoBloc.main(); todosBloc.main(); todosInteractor.main(); }
flutter_architecture_samples/blocs/test/all_tests.dart/0
{'file_path': 'flutter_architecture_samples/blocs/test/all_tests.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 123}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. library actions; import 'package:built_redux/built_redux.dart'; import 'package:built_redux_sample/models/models.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; part 'actions.g.dart'; abstract class AppActions extends ReduxActions { ActionDispatcher<Todo> addTodoAction; ActionDispatcher<Null> clearCompletedAction; ActionDispatcher<String> deleteTodoAction; ActionDispatcher<Null> fetchTodosAction; ActionDispatcher<Null> toggleAllAction; ActionDispatcher<List<Todo>> loadTodosSuccess; ActionDispatcher<Object> loadTodosFailure; ActionDispatcher<VisibilityFilter> updateFilterAction; ActionDispatcher<AppTab> updateTabAction; ActionDispatcher<UpdateTodoActionPayload> updateTodoAction; AppActions._(); factory AppActions() => _$AppActions(); } abstract class UpdateTodoActionPayload implements Built<UpdateTodoActionPayload, UpdateTodoActionPayloadBuilder> { static Serializer<UpdateTodoActionPayload> get serializer => _$updateTodoActionPayloadSerializer; String get id; Todo get updatedTodo; UpdateTodoActionPayload._(); factory UpdateTodoActionPayload(String id, Todo updatedTodo) => _$UpdateTodoActionPayload._( id: id, updatedTodo: updatedTodo, ); }
flutter_architecture_samples/built_redux/lib/actions/actions.dart/0
{'file_path': 'flutter_architecture_samples/built_redux/lib/actions/actions.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 478}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'dart:async'; import 'dart:core'; import 'package:built_redux_sample/data/file_storage.dart'; import 'package:built_redux_sample/data/web_client.dart'; import 'package:built_redux_sample/models/models.dart'; import 'package:path_provider/path_provider.dart'; /// A class that glues together our local file storage and web client. It has a /// clear responsibility: Load Todos and Persist todos. /// /// In most apps, we use the provided repository. In this case, it makes sense /// to demonstrate the built_value serializers, which are used in the /// FileStorage part of this app. /// /// Please see the `todos_repository` library for more information about the /// Repository pattern. class TodosRepository { final FileStorage fileStorage; final WebClient webClient; const TodosRepository({ this.fileStorage = const FileStorage( '__built_redux_sample_app__', getApplicationDocumentsDirectory, ), this.webClient = const WebClient(), }); /// Loads todos first from File storage. If they don't exist or encounter an /// error, it attempts to load the Todos from a Web Service. Future<List<Todo>> loadTodos() async { try { return await fileStorage.loadTodos(); } catch (e) { return webClient.fetchTodos(); } } // Persists todos to local disk and the web Future saveTodos(List<Todo> todos) { return Future.wait([ fileStorage.saveTodos(todos), webClient.postTodos(todos), ]); } }
flutter_architecture_samples/built_redux/lib/data/todos_repository.dart/0
{'file_path': 'flutter_architecture_samples/built_redux/lib/data/todos_repository.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 539}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. library visibility_filter; import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; part 'visibility_filter.g.dart'; class VisibilityFilter extends EnumClass { static Serializer<VisibilityFilter> get serializer => _$visibilityFilterSerializer; static const VisibilityFilter all = _$all; static const VisibilityFilter active = _$active; static const VisibilityFilter completed = _$completed; const VisibilityFilter._(String name) : super(name); static BuiltSet<VisibilityFilter> get values => _$visibilityFilterValues; static VisibilityFilter valueOf(String name) => _$visibilityFilterValueOf(name); }
flutter_architecture_samples/built_redux/lib/models/visibility_filter.dart/0
{'file_path': 'flutter_architecture_samples/built_redux/lib/models/visibility_filter.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 255}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'package:built_redux/built_redux.dart'; import 'package:built_redux_sample/actions/actions.dart'; import 'package:built_redux_sample/models/models.dart'; import 'package:built_redux_sample/reducers/reducers.dart'; import 'package:test/test.dart'; void main() { group('State Reducer', () { test('should add a todo to the list in response to an AddTodoAction', () { final todo = Todo('Hallo'); final store = Store<AppState, AppStateBuilder, AppActions>( reducerBuilder.build(), AppState(), AppActions(), ); store.actions.addTodoAction(todo); expect(store.state.todos, [todo]); }); test('should remove from the list in response to a DeleteTodoAction', () { final todo = Todo('Hallo'); final store = Store<AppState, AppStateBuilder, AppActions>( reducerBuilder.build(), AppState.fromTodos([todo]), AppActions(), ); expect(store.state.todos, [todo]); store.actions.deleteTodoAction(todo.id); expect(store.state.todos, []); }); test('should update a todo in response to an UpdateTodoAction', () { final todo = Todo('Hallo'); final updatedTodo = todo.rebuild((b) => b.task = 'Tschuss'); final store = Store<AppState, AppStateBuilder, AppActions>( reducerBuilder.build(), AppState.fromTodos([todo]), AppActions(), ); store.actions .updateTodoAction(UpdateTodoActionPayload(todo.id, updatedTodo)); expect(store.state.todos, [updatedTodo]); }); test('should clear completed todos', () { final todo1 = Todo('Hallo'); final todo2 = Todo.builder( (b) => b ..task = 'Tschüss' ..complete = true, ); final store = Store<AppState, AppStateBuilder, AppActions>( reducerBuilder.build(), AppState.fromTodos([todo1, todo2]), AppActions(), ); expect(store.state.todos, [todo1, todo2]); store.actions.clearCompletedAction(); expect(store.state.todos, [todo1]); }); test('should mark all as completed if some todos are incomplete', () { final todo1 = Todo('Hallo'); final todo2 = Todo.builder( (b) => b ..task = 'Tschüss' ..complete = true, ); final store = Store<AppState, AppStateBuilder, AppActions>( reducerBuilder.build(), AppState.fromTodos([todo1, todo2]), AppActions(), ); expect(store.state.todos, [todo1, todo2]); store.actions.toggleAllAction(); expect(store.state.allCompleteSelector, isTrue); }); test('should mark all as incomplete if all todos are complete', () { final todo1 = Todo.builder( (b) => b ..task = 'Hallo' ..complete = true, ); final todo2 = Todo.builder( (b) => b ..task = 'Tschüss' ..complete = true, ); final store = Store<AppState, AppStateBuilder, AppActions>( reducerBuilder.build(), AppState.fromTodos([todo1, todo2]), AppActions(), ); expect(store.state.todos, [todo1, todo2]); store.actions.toggleAllAction(); expect(store.state.allCompleteSelector, isFalse); expect(store.state.todos.every((todo) => !todo.complete), isTrue); }); test('should update the VisibilityFilter', () { final store = Store<AppState, AppStateBuilder, AppActions>( reducerBuilder.build(), AppState(), AppActions(), ); store.actions.updateFilterAction(VisibilityFilter.completed); expect(store.state.activeFilter, VisibilityFilter.completed); }); test('should update the AppTab', () { final store = Store<AppState, AppStateBuilder, AppActions>( reducerBuilder.build(), AppState(), AppActions(), ); store.actions.updateTabAction(AppTab.stats); expect(store.state.activeTab, AppTab.stats); }); }); }
flutter_architecture_samples/built_redux/test/reducer_test.dart/0
{'file_path': 'flutter_architecture_samples/built_redux/test/reducer_test.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1766}
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:change_notifier_provider_sample/todo_list_model.dart'; import 'package:todos_app_core/todos_app_core.dart'; import 'edit_todo_screen.dart'; import 'models.dart'; import 'todo_list_model.dart'; class DetailsScreen extends StatelessWidget { final String id; final VoidCallback onRemove; const DetailsScreen({@required this.id, @required this.onRemove}) : super(key: ArchSampleKeys.todoDetailsScreen); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(ArchSampleLocalizations.of(context).todoDetails), actions: <Widget>[ IconButton( key: ArchSampleKeys.deleteTodoButton, tooltip: ArchSampleLocalizations.of(context).deleteTodo, icon: const Icon(Icons.delete), onPressed: onRemove, ) ], ), body: Selector<TodoListModel, Todo>( selector: (context, model) => model.todoById(id), shouldRebuild: (prev, next) => next != null, builder: (context, todo, _) { return Padding( padding: const EdgeInsets.all(16.0), child: ListView( children: [ Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(right: 8.0), child: Checkbox( key: ArchSampleKeys.detailsTodoItemCheckbox, value: todo.complete, onChanged: (complete) { Provider.of<TodoListModel>(context, listen: false) .updateTodo(todo.copy(complete: !todo.complete)); }, ), ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only( top: 8.0, bottom: 16.0, ), child: Text( todo.task, key: ArchSampleKeys.detailsTodoItemTask, style: Theme.of(context).textTheme.headline, ), ), Text( todo.note, key: ArchSampleKeys.detailsTodoItemNote, style: Theme.of(context).textTheme.subhead, ) ], ), ), ], ), ], ), ); }, ), floatingActionButton: FloatingActionButton( key: ArchSampleKeys.editTodoFab, onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => EditTodoScreen( id: id, onEdit: (task, note) { final model = Provider.of<TodoListModel>(context, listen: false); final todo = model.todoById(id); model.updateTodo(todo.copy(task: task, note: note)); return Navigator.pop(context); }, ), ), ); }, child: const Icon(Icons.edit), ), ); } }
flutter_architecture_samples/change_notifier_provider/lib/details_screen.dart/0
{'file_path': 'flutter_architecture_samples/change_notifier_provider/lib/details_screen.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 2185}
// Provides a Mock repository that can be used for testing in place of the real // thing. import 'package:change_notifier_provider_sample/models.dart'; import 'package:todos_repository_core/todos_repository_core.dart'; class MockRepository extends TodosRepository { List<TodoEntity> entities; int saveCount = 0; MockRepository([List<Todo> todos = const []]) : entities = todos.map((it) => it.toEntity()).toList(); @override Future<List<TodoEntity>> loadTodos() async => entities; @override Future saveTodos(List<TodoEntity> todos) async { saveCount++; entities = todos; } }
flutter_architecture_samples/change_notifier_provider/test/mock_repository.dart/0
{'file_path': 'flutter_architecture_samples/change_notifier_provider/test/mock_repository.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 213}
import 'package:flutter/material.dart'; class LoadingSpinner extends StatelessWidget { LoadingSpinner({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Center( child: CircularProgressIndicator(), ); } }
flutter_architecture_samples/frideos_library/lib/widgets/loading.dart/0
{'file_path': 'flutter_architecture_samples/frideos_library/lib/widgets/loading.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 87}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:todos_app_core/todos_app_core.dart'; import 'package:inherited_widget_sample/state_container.dart'; class StatsCounter extends StatelessWidget { StatsCounter() : super(key: ArchSampleKeys.statsCounter); @override Widget build(BuildContext context) { final container = StateContainer.of(context); final numCompleted = container.state.numCompleted; final numActive = container.state.numActive; return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: EdgeInsets.only(bottom: 8.0), child: Text( ArchSampleLocalizations.of(context).completedTodos, style: Theme.of(context).textTheme.title, ), ), Padding( padding: EdgeInsets.only(bottom: 24.0), child: Text( '$numCompleted', key: ArchSampleKeys.statsNumCompleted, style: Theme.of(context).textTheme.subhead, ), ), Padding( padding: EdgeInsets.only(bottom: 8.0), child: Text( ArchSampleLocalizations.of(context).activeTodos, style: Theme.of(context).textTheme.title, ), ), Padding( padding: EdgeInsets.only(bottom: 24.0), child: Text( '$numActive', key: ArchSampleKeys.statsNumActive, style: Theme.of(context).textTheme.subhead, ), ) ], ), ); } }
flutter_architecture_samples/inherited_widget/lib/widgets/stats_counter.dart/0
{'file_path': 'flutter_architecture_samples/inherited_widget/lib/widgets/stats_counter.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 845}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'dart:async'; import 'package:flutter_driver/flutter_driver.dart'; import '../utils.dart'; import 'test_element.dart'; import 'todo_item_element.dart'; class TodoListElement extends TestElement { final _todoListFinder = find.byValueKey('__todoList__'); final _loadingFinder = find.byValueKey('__todosLoading__'); TodoListElement(FlutterDriver driver) : super(driver); Future<bool> get isLoading { // We need to run this command "unsynchronized". This means it immediately // checks if the loading widget is on screen, rather than waiting for any // pending animations to complete. // // Since the CircularProgressIndicator runs a continuous animation, if we // do not `runUnsynchronized`, this check will never work. return driver.runUnsynchronized(() { return widgetExists(driver, _loadingFinder); }); } Future<bool> get isReady => widgetExists(driver, _todoListFinder); TodoItemElement todoItem(String id) => TodoItemElement(id, driver); TodoItemElement todoItemAbsent(String id) => TodoItemElement(id, driver); }
flutter_architecture_samples/integration_tests/lib/page_objects/elements/todo_list_element.dart/0
{'file_path': 'flutter_architecture_samples/integration_tests/lib/page_objects/elements/todo_list_element.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 391}
import 'package:mobx/mobx.dart'; import 'package:todos_app_core/todos_app_core.dart'; part 'todo.g.dart'; /// A reactive class that holds information about a task that needs to be /// completed class Todo = _Todo with _$Todo; abstract class _Todo with Store { _Todo({ String id, this.task = '', this.note = '', this.complete = false, }) : id = id ?? Uuid().generateV4(); final String id; @observable String task; @observable String note; @observable bool complete; @override String toString() { return '_Todo{id: $id, task: $task, note: $note, complete: $complete}'; } @override bool operator ==(Object other) => identical(this, other) || other is _Todo && runtimeType == other.runtimeType && id == other.id && task == other.task && note == other.note && complete == other.complete; @override int get hashCode => id.hashCode ^ task.hashCode ^ note.hashCode ^ complete.hashCode; }
flutter_architecture_samples/mobx/lib/models/todo.dart/0
{'file_path': 'flutter_architecture_samples/mobx/lib/models/todo.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 400}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'dart:async'; import 'package:path_provider/path_provider.dart'; import 'package:todos_repository_core/todos_repository_core.dart'; import 'package:todos_repository_local_storage/todos_repository_local_storage.dart'; import 'package:mvc/src/models.dart'; class TodoListModel { TodoListModel({TodosRepository repo, VisibilityFilter activeFilter}) : _activeFilter = activeFilter ?? VisibilityFilter.all { /// The rest of the app need not know of its existence. repository = repo ?? LocalStorageRepository( localStorage: const FileStorage( 'mvc_app', getApplicationDocumentsDirectory, ), ); } TodosRepository repository; VisibilityFilter get activeFilter => _activeFilter; set activeFilter(VisibilityFilter filter) => _activeFilter = filter; VisibilityFilter _activeFilter; List<Todo> get todos => _todos.toList(); List<Todo> _todos = []; bool get isLoading => _isLoading; bool _isLoading = false; /// Loads remote data Future loadTodos() { _isLoading = true; return repository.loadTodos().then((loadedTodos) { _todos = loadedTodos.map(Todo.fromEntity).toList(); _isLoading = false; }).catchError((err) { _isLoading = false; _todos = []; }); } List<Todo> get filteredTodos => _todos.where((todo) { switch (activeFilter) { case VisibilityFilter.active: return !todo.complete; case VisibilityFilter.completed: return todo.complete; case VisibilityFilter.all: default: return true; } }).toList(); void clearCompleted() { _todos.removeWhere((todo) => todo.complete); _uploadItems(); } void toggleAll() { var allComplete = todos.every((todo) => todo.complete); _todos = _todos.map((todo) => todo.copy(complete: !allComplete)).toList(); _uploadItems(); } /// updates by replacing the item with the same id by the parameter void updateTodo(Todo todo) { assert(todo != null); assert(todo.id != null); var oldTodo = _todos.firstWhere((it) => it.id == todo.id); var replaceIndex = _todos.indexOf(oldTodo); _todos.replaceRange(replaceIndex, replaceIndex + 1, [todo]); _uploadItems(); } void removeTodo(Todo todo) { _todos.removeWhere((it) => it.id == todo.id); _uploadItems(); } void addTodo(Todo todo) { _todos.add(todo); _uploadItems(); } void _uploadItems() { repository.saveTodos(_todos.map((it) => it.toEntity()).toList()); } Todo todoById(String id) { return _todos.firstWhere((it) => it.id == id, orElse: () => null); } } enum VisibilityFilter { all, active, completed } class To { /// Convert from a Map object static Todo todo(Map data) { return Todo(data['task'], complete: data['complete'], note: data['note'], id: data['id']); } /// Used to 'interface' with the View in the MVC design pattern. static Map map(Todo obj) => { 'task': obj == null ? '' : obj.task, 'note': obj == null ? '' : obj.note, 'complete': obj == null ? false : obj.complete, 'id': obj == null ? null : obj.id, }; }
flutter_architecture_samples/mvc/lib/src/todo_list_model.dart/0
{'file_path': 'flutter_architecture_samples/mvc/lib/src/todo_list_model.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1336}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'dart:async'; import 'package:mockito/mockito.dart'; import 'package:mvi_base/mvi_base.dart'; import 'package:test/test.dart'; import 'package:todos_repository_core/todos_repository_core.dart'; class MockUserRepository extends Mock implements UserRepository {} void main() { group('UserInteractor', () { test('should convert repo entities into Todos', () async { final repository = MockUserRepository(); final interactor = UserInteractor(repository); when(repository.login()) .thenAnswer((_) => Future.value(UserEntity(displayName: 'Frida'))); expect(await interactor.login(), User('Frida')); }); }); }
flutter_architecture_samples/mvi_base/test/user_interactor_test.dart/0
{'file_path': 'flutter_architecture_samples/mvi_base/test/user_interactor_test.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 283}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'dart:async'; import 'dart:html'; import 'package:flutter/widgets.dart'; import 'package:key_value_store_web/key_value_store_web.dart'; import 'package:mvi_base/mvi_base.dart'; import 'package:mvi_flutter_sample/mvi_app.dart'; import 'package:todos_repository_core/todos_repository_core.dart'; import 'package:todos_repository_local_storage/todos_repository_local_storage.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); runApp(MviApp( todosRepository: TodosInteractor( ReactiveLocalStorageRepository( repository: LocalStorageRepository( localStorage: KeyValueStorage( 'mvi_flutter', WebKeyValueStore(window.localStorage), ), ), ), ), userInteractor: UserInteractor(AnonymousUserRepository()), )); } class AnonymousUserRepository implements UserRepository { @override Future<UserEntity> login() { return Future.value(UserEntity(id: 'anonymous')); } }
flutter_architecture_samples/mvi_flutter/lib/main_web.dart/0
{'file_path': 'flutter_architecture_samples/mvi_flutter/lib/main_web.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 435}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'todo_model.dart'; // ************************************************************************** // BuiltValueGenerator // ************************************************************************** // ignore_for_file: always_put_control_body_on_new_line // ignore_for_file: annotate_overrides // ignore_for_file: avoid_annotating_with_dynamic // ignore_for_file: avoid_catches_without_on_clauses // ignore_for_file: avoid_returning_this // ignore_for_file: lines_longer_than_80_chars // ignore_for_file: omit_local_variable_types // ignore_for_file: prefer_expression_function_bodies // ignore_for_file: sort_constructors_first // ignore_for_file: unnecessary_const // ignore_for_file: unnecessary_new // ignore_for_file: test_types_in_equals class _$TodoModel extends TodoModel { @override final String id; @override final bool complete; @override final String note; @override final String task; factory _$TodoModel([void Function(TodoModelBuilder b) updates]) => (new TodoModelBuilder()..update(updates)).build(); _$TodoModel._({this.id, this.complete, this.note, this.task}) : super._() { if (id == null) { throw new BuiltValueNullFieldError('TodoModel', 'id'); } if (complete == null) { throw new BuiltValueNullFieldError('TodoModel', 'complete'); } if (note == null) { throw new BuiltValueNullFieldError('TodoModel', 'note'); } if (task == null) { throw new BuiltValueNullFieldError('TodoModel', 'task'); } } @override TodoModel rebuild(void Function(TodoModelBuilder b) updates) => (toBuilder()..update(updates)).build(); @override TodoModelBuilder toBuilder() => new TodoModelBuilder()..replace(this); @override bool operator ==(Object other) { if (identical(other, this)) return true; return other is TodoModel && id == other.id && complete == other.complete && note == other.note && task == other.task; } @override int get hashCode { return $jf($jc( $jc($jc($jc(0, id.hashCode), complete.hashCode), note.hashCode), task.hashCode)); } @override String toString() { return (newBuiltValueToStringHelper('TodoModel') ..add('id', id) ..add('complete', complete) ..add('note', note) ..add('task', task)) .toString(); } } class TodoModelBuilder implements Builder<TodoModel, TodoModelBuilder> { _$TodoModel _$v; String _id; String get id => _$this._id; set id(String id) => _$this._id = id; bool _complete; bool get complete => _$this._complete; set complete(bool complete) => _$this._complete = complete; String _note; String get note => _$this._note; set note(String note) => _$this._note = note; String _task; String get task => _$this._task; set task(String task) => _$this._task = task; TodoModelBuilder(); TodoModelBuilder get _$this { if (_$v != null) { _id = _$v.id; _complete = _$v.complete; _note = _$v.note; _task = _$v.task; _$v = null; } return this; } @override void replace(TodoModel other) { if (other == null) { throw new ArgumentError.notNull('other'); } _$v = other as _$TodoModel; } @override void update(void Function(TodoModelBuilder b) updates) { if (updates != null) updates(this); } @override _$TodoModel build() { final _$result = _$v ?? new _$TodoModel._(id: id, complete: complete, note: note, task: task); replace(_$result); return _$result; } }
flutter_architecture_samples/mvu/lib/common/todo_model.g.dart/0
{'file_path': 'flutter_architecture_samples/mvu/lib/common/todo_model.g.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1348}
import 'dart:async'; import 'package:flutter/material.dart'; class MvuLocalizations { static MvuLocalizations of(BuildContext context) { return Localizations.of<MvuLocalizations>( context, MvuLocalizations, ); } String get appTitle => 'MVU Example'; } class MvuLocalizationsDelegate extends LocalizationsDelegate<MvuLocalizations> { @override Future<MvuLocalizations> load(Locale locale) => Future(() => MvuLocalizations()); @override bool shouldReload(MvuLocalizationsDelegate old) => false; @override bool isSupported(Locale locale) => locale.languageCode.toLowerCase().contains('en'); }
flutter_architecture_samples/mvu/lib/localization.dart/0
{'file_path': 'flutter_architecture_samples/mvu/lib/localization.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 220}
import 'dart:async'; import 'package:mvu/common/repository_commands.dart'; import 'package:dartea/dartea.dart'; import 'package:todos_repository_core/todos_repository_core.dart'; List<TodoEntity> createTodos({bool complete}) => [ TodoEntity('Buy milk', '1', 'soy', complete ?? false), TodoEntity('Buy bread', '2', 'italian one', complete ?? true), TodoEntity('Buy meat', '3', 'or chicken', complete ?? false), TodoEntity('Buy water', '4', 'carbonated and still', complete ?? true), TodoEntity('Read book', '5', 'interesting one', complete ?? false), TodoEntity('Watch football', '6', '', complete ?? true), TodoEntity('Sleep', '7', 'well', complete ?? false), ]; List<TodoEntity> createTodosForStats(int activeCount, int completedCount) { final result = <TodoEntity>[]; for (var i = 0; i < activeCount; i++) { var todo = TodoEntity('todo $i', '$i', 'note for todo #$i', false); result.add(todo); } var totalLength = result.length + completedCount; for (var i = result.length; i < totalLength; i++) { var todo = TodoEntity('todo $i', '$i', 'note for todo #$i', true); result.add(todo); } return result; } class InMemoryTodosRepository implements TodosRepository { final items = <TodoEntity>[]; final bool isBrokern; InMemoryTodosRepository( {Iterable<TodoEntity> initialItems, this.isBrokern = false}) { if (initialItems != null) { items.addAll(initialItems); } } @override Future<List<TodoEntity>> loadTodos() { if (isBrokern) { throw Exception('repo is broken'); } return Future.value(items.toList()); } @override Future saveTodos(List<TodoEntity> todos) => Future.sync(() { items.clear(); items.addAll(todos); }); } class TestTodosCmdRepository implements CmdRepository { final createdEffects = <RepoEffect>[]; @override Cmd<T> createCmd<T>( T Function(TodoEntity todo) onSuccess, String task, String note) { final entity = TodoEntity(task, 'new_id', note, false); createdEffects.add(CreateTodoEffect(task, note)); return Cmd.ofFunc(() => entity, onSuccess: onSuccess); } @override Cmd<T> loadTodosCmd<T>(T Function(List<TodoEntity> items) onSuccess, {T Function(Exception exc) onError}) { final todos = createTodos(); createdEffects.add(LoadTodosEffect()); return Cmd.ofFunc(() => todos, onSuccess: onSuccess); } @override Cmd<T> removeCmd<T>(TodoEntity todo, {T Function() onSuccess}) { createdEffects.add(RemoveTodoEffect(todo)); return Cmd.ofAction(() {}, onSuccess: onSuccess); } @override Cmd<T> saveAllCmd<T>(List<TodoEntity> entities, {T Function() onSuccess}) { createdEffects.add(SaveAllTodosEffect(entities)); return Cmd.ofAction(() {}, onSuccess: onSuccess); } @override Cmd<T> saveCmd<T>(TodoEntity todo, {T Function() onSuccess}) { createdEffects.add(SaveTodoEffect(todo)); return Cmd.ofAction(() {}, onSuccess: onSuccess); } @override Cmd<T> updateDetailsCmd<T>(T Function(TodoEntity todo) onSuccess, String id, String task, String note) { createdEffects.add(UpdateDetailsEffect(id, task, note)); final updatedTodo = TodoEntity(task, id, note, false); return Cmd.ofFunc(() => updatedTodo, onSuccess: onSuccess); } void invalidate() => createdEffects.clear(); @override Stream<RepositoryEvent> get events => events.asBroadcastStream(); } abstract class RepoEffect {} class LoadTodosEffect implements RepoEffect {} class CreateTodoEffect implements RepoEffect { final String task; final String note; CreateTodoEffect(this.task, this.note); } class RemoveTodoEffect implements RepoEffect { final TodoEntity entity; RemoveTodoEffect(this.entity); } class SaveAllTodosEffect implements RepoEffect { final List<TodoEntity> entities; SaveAllTodosEffect(this.entities); } class SaveTodoEffect implements RepoEffect { final TodoEntity entity; SaveTodoEffect(this.entity); } class UpdateDetailsEffect implements RepoEffect { final String id; final String task; final String note; UpdateDetailsEffect(this.id, this.task, this.note); }
flutter_architecture_samples/mvu/test/data.dart/0
{'file_path': 'flutter_architecture_samples/mvu/test/data.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1518}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_redux/flutter_redux.dart'; import 'package:redux/redux.dart'; import 'package:redux_sample/actions/actions.dart'; import 'package:redux_sample/models/models.dart'; import 'package:redux_sample/presentation/todo_list.dart'; import 'package:redux_sample/selectors/selectors.dart'; class FilteredTodos extends StatelessWidget { FilteredTodos({Key key}) : super(key: key); @override Widget build(BuildContext context) { return StoreConnector<AppState, _ViewModel>( converter: _ViewModel.fromStore, builder: (context, vm) { return TodoList( todos: vm.todos, onCheckboxChanged: vm.onCheckboxChanged, onRemove: vm.onRemove, onUndoRemove: vm.onUndoRemove, ); }, ); } } class _ViewModel { final List<Todo> todos; final bool loading; final Function(Todo, bool) onCheckboxChanged; final Function(Todo) onRemove; final Function(Todo) onUndoRemove; _ViewModel({ @required this.todos, @required this.loading, @required this.onCheckboxChanged, @required this.onRemove, @required this.onUndoRemove, }); static _ViewModel fromStore(Store<AppState> store) { return _ViewModel( todos: filteredTodosSelector( todosSelector(store.state), activeFilterSelector(store.state), ), loading: store.state.isLoading, onCheckboxChanged: (todo, complete) { store.dispatch(UpdateTodoAction( todo.id, todo.copyWith(complete: !todo.complete), )); }, onRemove: (todo) { store.dispatch(DeleteTodoAction(todo.id)); }, onUndoRemove: (todo) { store.dispatch(AddTodoAction(todo)); }, ); } }
flutter_architecture_samples/redux/lib/containers/filtered_todos.dart/0
{'file_path': 'flutter_architecture_samples/redux/lib/containers/filtered_todos.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 805}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'package:flutter/material.dart'; import 'package:todos_app_core/todos_app_core.dart'; import 'package:redux_sample/models/models.dart'; class ExtraActionsButton extends StatelessWidget { final PopupMenuItemSelected<ExtraAction> onSelected; final bool allComplete; ExtraActionsButton({ this.onSelected, this.allComplete = false, Key key, }) : super(key: ArchSampleKeys.extraActionsButton); @override Widget build(BuildContext context) { return PopupMenuButton<ExtraAction>( onSelected: onSelected, itemBuilder: (BuildContext context) => <PopupMenuItem<ExtraAction>>[ PopupMenuItem<ExtraAction>( key: ArchSampleKeys.toggleAll, value: ExtraAction.toggleAllComplete, child: Text(allComplete ? ArchSampleLocalizations.of(context).markAllIncomplete : ArchSampleLocalizations.of(context).markAllComplete), ), PopupMenuItem<ExtraAction>( key: ArchSampleKeys.clearCompleted, value: ExtraAction.clearCompleted, child: Text(ArchSampleLocalizations.of(context).clearCompleted), ), ], ); } }
flutter_architecture_samples/redux/lib/presentation/extra_actions_button.dart/0
{'file_path': 'flutter_architecture_samples/redux/lib/presentation/extra_actions_button.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 491}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import 'package:redux/redux.dart'; import 'package:redux_sample/actions/actions.dart'; import 'package:redux_sample/middleware/store_todos_middleware.dart'; import 'package:redux_sample/models/models.dart'; import 'package:redux_sample/reducers/app_state_reducer.dart'; import 'package:todos_repository_core/todos_repository_core.dart'; class MockTodosRepository extends Mock implements TodosRepository {} void main() { group('Save State Middleware', () { test('should load the todos in response to a LoadTodosAction', () { final repository = MockTodosRepository(); final store = Store<AppState>( appReducer, initialState: AppState.loading(), middleware: createStoreTodosMiddleware(repository), ); final todos = [ TodoEntity('Moin', '1', 'Note', false), ]; when(repository.loadTodos()).thenAnswer((_) => Future.value(todos)); store.dispatch(LoadTodosAction()); verify(repository.loadTodos()); }); test('should save the state on every update action', () { final repository = MockTodosRepository(); final store = Store<AppState>( appReducer, initialState: AppState.loading(), middleware: createStoreTodosMiddleware(repository), ); final todo = Todo('Hallo'); store.dispatch(AddTodoAction(todo)); store.dispatch(ClearCompletedAction()); store.dispatch(ToggleAllAction()); store.dispatch(TodosLoadedAction([Todo('Hi')])); store.dispatch(ToggleAllAction()); store.dispatch(UpdateTodoAction('', Todo(''))); store.dispatch(DeleteTodoAction('')); verify(repository.saveTodos(any)).called(7); }); }); }
flutter_architecture_samples/redux/test/middleware_test.dart/0
{'file_path': 'flutter_architecture_samples/redux/test/middleware_test.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 744}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'package:flutter/material.dart'; import 'package:todos_app_core/todos_app_core.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:scoped_model_sample/models.dart'; import 'package:scoped_model_sample/screens/detail_screen.dart'; import 'package:scoped_model_sample/todo_list_model.dart'; import 'package:scoped_model_sample/widgets/todo_item.dart'; class TodoList extends StatelessWidget { TodoList({Key key}) : super(key: key); @override Widget build(BuildContext context) { return ScopedModelDescendant<TodoListModel>( builder: (context, child, model) { return Container( child: model.isLoading ? _buildLoading : _buildList(model), ); }, ); } Center get _buildLoading { return Center( child: CircularProgressIndicator( key: ArchSampleKeys.todosLoading, ), ); } ListView _buildList(TodoListModel model) { final todos = model.filteredTodos; return ListView.builder( key: ArchSampleKeys.todoList, itemCount: todos.length, itemBuilder: (BuildContext context, int index) { final todo = todos[index]; return TodoItem( todo: todo, onDismissed: (direction) { _removeTodo(context, todo); }, onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (_) { return DetailScreen( todoId: todo.id, ); }, ), ).then((todo) { if (todo is Todo) { _showUndoSnackbar(context, todo); } }); }, onCheckboxChanged: (complete) { var toggled = todo.copy(complete: !todo.complete); model.updateTodo(toggled); }, ); }, ); } void _removeTodo(BuildContext context, Todo todo) { TodoListModel.of(context).removeTodo(todo); _showUndoSnackbar(context, todo); } void _showUndoSnackbar(BuildContext context, Todo todo) { Scaffold.of(context).showSnackBar( SnackBar( key: ArchSampleKeys.snackbar, duration: Duration(seconds: 2), content: Text( ArchSampleLocalizations.of(context).todoDeleted(todo.task), maxLines: 1, overflow: TextOverflow.ellipsis, ), action: SnackBarAction( key: ArchSampleKeys.snackbarAction(todo.id), label: ArchSampleLocalizations.of(context).undo, onPressed: () { TodoListModel.of(context).addTodo(todo); }, ), ), ); } }
flutter_architecture_samples/scoped_model/lib/widgets/todo_list.dart/0
{'file_path': 'flutter_architecture_samples/scoped_model/lib/widgets/todo_list.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1332}
import 'package:flutter/material.dart'; import 'package:states_rebuilder/states_rebuilder.dart'; import 'package:todos_app_core/todos_app_core.dart'; import '../../domain/entities/todo.dart'; import '../../service/todos_service.dart'; class HelperMethods { static void removeTodo(Todo todo) { final todosServiceRM = Injector.getAsReactive<TodosService>(); todosServiceRM.setState( (s) => s.deleteTodo(todo), onSetState: (context) { Scaffold.of(context).showSnackBar( SnackBar( key: ArchSampleKeys.snackbar, duration: Duration(seconds: 2), content: Text( ArchSampleLocalizations.of(context).todoDeleted(todo.task), maxLines: 1, overflow: TextOverflow.ellipsis, ), action: SnackBarAction( label: ArchSampleLocalizations.of(context).undo, onPressed: () { todosServiceRM.setState((s) => s.addTodo(todo)); }, ), ), ); }, ); } }
flutter_architecture_samples/states_rebuilder/lib/ui/common/helper_methods.dart/0
{'file_path': 'flutter_architecture_samples/states_rebuilder/lib/ui/common/helper_methods.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 529}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'dart:async'; import 'dart:core'; import 'todo_entity.dart'; /// A class that Loads and Persists todos. The data layer of the app. /// /// How and where it stores the entities should defined in a concrete /// implementation, such as todos_repository_simple or todos_repository_web. /// /// The domain layer should depend on this abstract class, and each app can /// inject the correct implementation depending on the environment, such as /// web or Flutter. abstract class TodosRepository { /// Loads todos first from File storage. If they don't exist or encounter an /// error, it attempts to load the Todos from a Web Client. Future<List<TodoEntity>> loadTodos(); // Persists todos to local disk and the web Future saveTodos(List<TodoEntity> todos); }
flutter_architecture_samples/todos_repository_core/lib/src/todos_repository.dart/0
{'file_path': 'flutter_architecture_samples/todos_repository_core/lib/src/todos_repository.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 264}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'package:key_value_store/key_value_store.dart'; import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; import 'package:todos_repository_core/todos_repository_core.dart'; import 'package:todos_repository_local_storage/todos_repository_local_storage.dart'; class MockKeyValueStore extends Mock implements KeyValueStore {} void main() { group('KeyValueStorage', () { final store = MockKeyValueStore(); final todos = [TodoEntity('Task', '1', 'Hallo', true)]; final todosJson = '{"todos":[{"complete":true,"task":"Task","note":"Hallo","id":"1"}]}'; final storage = KeyValueStorage('T', store); test('Should persist TodoEntities to the store', () async { await storage.saveTodos(todos); verify(store.setString('T', todosJson)); }); test('Should load TodoEntities from disk', () async { when(store.getString('T')).thenReturn(todosJson); expect(await storage.loadTodos(), todos); }); }); }
flutter_architecture_samples/todos_repository_local_storage/test/key_value_storage_test.dart/0
{'file_path': 'flutter_architecture_samples/todos_repository_local_storage/test/key_value_storage_test.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 409}
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:todos_app_core/todos_app_core.dart'; import 'package:todos_repository_core/todos_repository_core.dart'; import 'package:vanilla/localization.dart'; import 'package:vanilla/models.dart'; import 'package:vanilla/screens/add_edit_screen.dart'; import 'package:vanilla/screens/home_screen.dart'; class VanillaApp extends StatefulWidget { final TodosRepository repository; VanillaApp({@required this.repository}); @override State<StatefulWidget> createState() { return VanillaAppState(); } } class VanillaAppState extends State<VanillaApp> { AppState appState = AppState.loading(); @override void initState() { super.initState(); widget.repository.loadTodos().then((loadedTodos) { setState(() { appState = AppState( todos: loadedTodos.map(Todo.fromEntity).toList(), ); }); }).catchError((err) { setState(() { appState.isLoading = false; }); }); } @override Widget build(BuildContext context) { return MaterialApp( onGenerateTitle: (context) => VanillaLocalizations.of(context).appTitle, theme: ArchSampleTheme.theme, localizationsDelegates: [ ArchSampleLocalizationsDelegate(), VanillaLocalizationsDelegate(), ], routes: { ArchSampleRoutes.home: (context) { return HomeScreen( appState: appState, updateTodo: updateTodo, addTodo: addTodo, removeTodo: removeTodo, toggleAll: toggleAll, clearCompleted: clearCompleted, ); }, ArchSampleRoutes.addTodo: (context) { return AddEditScreen( key: ArchSampleKeys.addTodoScreen, addTodo: addTodo, updateTodo: updateTodo, ); }, }, ); } void toggleAll() { setState(() { appState.toggleAll(); }); } void clearCompleted() { setState(() { appState.clearCompleted(); }); } void addTodo(Todo todo) { setState(() { appState.todos.add(todo); }); } void removeTodo(Todo todo) { setState(() { appState.todos.remove(todo); }); } void updateTodo( Todo todo, { bool complete, String id, String note, String task, }) { setState(() { todo.complete = complete ?? todo.complete; todo.id = id ?? todo.id; todo.note = note ?? todo.note; todo.task = task ?? todo.task; }); } @override void setState(VoidCallback fn) { super.setState(fn); widget.repository.saveTodos( appState.todos.map((todo) => todo.toEntity()).toList(), ); } }
flutter_architecture_samples/vanilla/lib/app.dart/0
{'file_path': 'flutter_architecture_samples/vanilla/lib/app.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1254}
import 'package:flutter/material.dart'; import 'package:flutter_articles/presentation/article/widgets/article_card.dart'; import 'package:flutter_articles/models/article.dart'; class ArticlesList extends StatelessWidget { final List<Article> articles; const ArticlesList(this.articles, {Key? key}) : super(key: key); @override Widget build(BuildContext context) { return ListView.builder( padding: const EdgeInsets.only(bottom: 20), itemCount: articles.length, itemBuilder: (c, i) => ArticleCard(articles[i]), ); } }
flutter_articles/lib/presentation/article/widgets/articles_list.dart/0
{'file_path': 'flutter_articles/lib/presentation/article/widgets/articles_list.dart', 'repo_id': 'flutter_articles', 'token_count': 186}
class StorageKeys { static const String test = 'test'; } abstract class StorageService { Future<void> init(); Future<void> remove(String key); dynamic get(String key); dynamic getAll(); Future<void> clear(); bool has(String key); Future<void> set(String? key, dynamic data); Future<void> close(); }
flutter_articles/lib/services/storage/storage_service.dart/0
{'file_path': 'flutter_articles/lib/services/storage/storage_service.dart', 'repo_id': 'flutter_articles', 'token_count': 99}
name: flutter_cache_manager description: Generic cache manager for flutter version: 0.1.1 author: Rene Floor <pub@renefloor.nl> homepage: https://github.com/renefloor/flutter_cache_manager environment: sdk: ">=2.0.0-dev.28.0 <3.0.0" dependencies: flutter: sdk: flutter shared_preferences: "^0.4.0" path_provider: "^0.4.0" synchronized: "^1.3.0" uuid: "^1.0.1" http: "^0.11.3+14"
flutter_cache_manager/pubspec.yaml/0
{'file_path': 'flutter_cache_manager/pubspec.yaml', 'repo_id': 'flutter_cache_manager', 'token_count': 179}
class Constants { static const double initAnimationOffset = 100; static const double cardHeight = 220; static const double dragStartEndAngle = 0.01; static const double rotationAnimationAngleDeg = 360; static const double scaleFraction = 0.05; static const double yOffset = 13; static const double throwSlideYDistance = 200; static const Duration backgroundCardsAnimationDuration = Duration(milliseconds: 300); static const Duration swipeAnimationDuration = Duration(milliseconds: 500); }
flutter_cool_card_swiper/lib/src/constants.dart/0
{'file_path': 'flutter_cool_card_swiper/lib/src/constants.dart', 'repo_id': 'flutter_cool_card_swiper', 'token_count': 129}
import 'dart:math'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter_generative_art/vera_molnar/utils.dart'; class DistortedPolygonSet extends StatelessWidget { const DistortedPolygonSet({ super.key, this.maxCornersOffset = 20, this.minRepetition = 20, this.strokeWidth = 2, this.child, }); final double maxCornersOffset; final double strokeWidth; final int minRepetition; final Widget? child; @override Widget build(BuildContext context) { return SizedBox.expand( child: ColoredBox( color: Colors.white, child: CustomPaint( painter: _DistortedPolygonSetCustomPainter( maxCornersOffset: maxCornersOffset, strokeWidth: strokeWidth, minRepetition: minRepetition, ), child: child, ), ), ); } } class _DistortedPolygonSetCustomPainter extends CustomPainter { _DistortedPolygonSetCustomPainter({ this.strokeWidth = 2, this.maxCornersOffset = 20, this.minRepetition = 20, }); final double strokeWidth; final double maxCornersOffset; final int minRepetition; static final Random random = Random(); @override void paint(Canvas canvas, Size size) { final paint = Paint() ..style = PaintingStyle.stroke ..color = Colors.black ..strokeWidth = strokeWidth; final center = Offset(size.width / 2, size.height / 2); final side = size.shortestSide * 0.7; final repetition = random.nextInt(10) + minRepetition; for (int i = 0; i < repetition; i++) { Offset topLeft = Offset.zero; Offset topRight = topLeft + Offset(side, 0); Offset bottomRight = topLeft + Offset(side, side); Offset bottomLeft = topLeft + Offset(0, side); topLeft += randomOffsetFromRange(random, maxCornersOffset); topRight += randomOffsetFromRange(random, maxCornersOffset); bottomRight += randomOffsetFromRange(random, maxCornersOffset); bottomLeft += randomOffsetFromRange(random, maxCornersOffset); Offset polygonCenter = Offset( (topLeft.dx + topRight.dx + bottomRight.dx + bottomLeft.dx) / 4, (topLeft.dy + topRight.dy + bottomRight.dy + bottomLeft.dy) / 4, ); canvas.save(); canvas.translate( center.dx - polygonCenter.dx, center.dy - polygonCenter.dy, ); canvas.drawPoints( PointMode.polygon, [ topLeft, topRight, bottomRight, bottomLeft, topLeft, ], paint, ); canvas.restore(); } } @override bool shouldRepaint(covariant CustomPainter oldDelegate) { return false; } }
flutter_generative_art/lib/vera_molnar/distorted_polygon_set.dart/0
{'file_path': 'flutter_generative_art/lib/vera_molnar/distorted_polygon_set.dart', 'repo_id': 'flutter_generative_art', 'token_count': 1100}
import 'package:flutter/material.dart'; import 'demos/custom_painter.dart'; import 'demos/multi_child_layout.dart'; import 'demos/render_object.dart'; import 'demos/widget.dart'; void main() => runApp( const App( demo: Demo.renderObject, ), ); class App extends StatelessWidget { const App({super.key, required this.demo}); final Demo demo; @override Widget build(BuildContext context) => MaterialApp(onGenerateRoute: (_) => demo.route); } enum Demo { widget(WidgetDemoPage()), multiChildLayout(MultiChildLayoutDemoPage()), customPainter(CustomPaintDemoPage()), renderObject(RenderObjectDemoPage()); const Demo(this._page); final Widget _page; PageRoute<void> get route => MaterialPageRoute(builder: (_) => _page); }
flutter_guild_demo/lib/main.dart/0
{'file_path': 'flutter_guild_demo/lib/main.dart', 'repo_id': 'flutter_guild_demo', 'token_count': 270}
name: Build on: push: pull_request: schedule: # runs the CI everyday at 10AM - cron: "0 10 * * *" jobs: flutter: runs-on: ubuntu-latest strategy: matrix: package: - flutter_hooks channel: - master steps: - uses: actions/checkout@v2 - uses: subosito/flutter-action@v1 with: channel: ${{ matrix.channel }} - name: Install dependencies run: flutter pub get working-directory: packages/${{ matrix.package }} - name: Check format run: dart format --set-exit-if-changed . if: matrix.channel == 'master' working-directory: packages/${{ matrix.package }} - name: Analyze run: dart analyze . working-directory: packages/${{ matrix.package }} - name: Run tests run: flutter test --coverage working-directory: packages/${{ matrix.package }} - name: Upload coverage to codecov run: curl -s https://codecov.io/bash | bash working-directory: packages/${{ matrix.package }}
flutter_hooks/.github/workflows/build.yml/0
{'file_path': 'flutter_hooks/.github/workflows/build.yml', 'repo_id': 'flutter_hooks', 'token_count': 460}
part of 'hooks.dart'; /// Returns a debounced version of the provided value [toDebounce], triggering /// widget updates accordingly after a specified [timeout] duration. /// /// Example: /// ```dart /// String userInput = ''; // Your input value /// /// // Create a debounced version of userInput /// final debouncedInput = useDebounced( /// userInput, /// Duration(milliseconds: 500), // Set your desired timeout /// ); /// // Assume a fetch method fetchData(String query) exists /// useEffect(() { /// fetchData(debouncedInput); // Use debouncedInput as a dependency /// return null; /// }, [debouncedInput]); /// ``` T? useDebounced<T>( T toDebounce, Duration timeout, ) { return use( _DebouncedHook( toDebounce: toDebounce, timeout: timeout, ), ); } class _DebouncedHook<T> extends Hook<T?> { const _DebouncedHook({ required this.toDebounce, required this.timeout, }); final T toDebounce; final Duration timeout; @override _DebouncedHookState<T> createState() => _DebouncedHookState(); } class _DebouncedHookState<T> extends HookState<T?, _DebouncedHook<T>> { T? _state; Timer? _timer; @override void initHook() { super.initHook(); _startDebounce(hook.toDebounce); } void _startDebounce(T toDebounce) { _timer?.cancel(); _timer = Timer(hook.timeout, () { setState(() { _state = toDebounce; }); }); } @override void didUpdateHook(_DebouncedHook<T> oldHook) { if (hook.toDebounce != oldHook.toDebounce || hook.timeout != oldHook.timeout) { _startDebounce(hook.toDebounce); } } @override T? build(BuildContext context) => _state; @override Object? get debugValue => _state; @override String get debugLabel => 'useDebounced<$T>'; @override void dispose() { _timer?.cancel(); _timer = null; super.dispose(); } }
flutter_hooks/packages/flutter_hooks/lib/src/debounced.dart/0
{'file_path': 'flutter_hooks/packages/flutter_hooks/lib/src/debounced.dart', 'repo_id': 'flutter_hooks', 'token_count': 697}
part of 'hooks.dart'; /// Creates a [TabController] that will be disposed automatically. /// /// See also: /// - [TabController] TabController useTabController({ required int initialLength, TickerProvider? vsync, int initialIndex = 0, List<Object?>? keys, }) { vsync ??= useSingleTickerProvider(keys: keys); return use( _TabControllerHook( vsync: vsync, length: initialLength, initialIndex: initialIndex, keys: keys, ), ); } class _TabControllerHook extends Hook<TabController> { const _TabControllerHook({ required this.length, required this.vsync, required this.initialIndex, List<Object?>? keys, }) : super(keys: keys); final int length; final TickerProvider vsync; final int initialIndex; @override HookState<TabController, Hook<TabController>> createState() => _TabControllerHookState(); } class _TabControllerHookState extends HookState<TabController, _TabControllerHook> { late final controller = TabController( length: hook.length, initialIndex: hook.initialIndex, vsync: hook.vsync, ); @override TabController build(BuildContext context) => controller; @override void dispose() => controller.dispose(); @override String get debugLabel => 'useTabController'; }
flutter_hooks/packages/flutter_hooks/lib/src/tab_controller.dart/0
{'file_path': 'flutter_hooks/packages/flutter_hooks/lib/src/tab_controller.dart', 'repo_id': 'flutter_hooks', 'token_count': 430}
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/src/framework.dart'; import 'package:flutter_hooks/src/hooks.dart'; import 'mock.dart'; void main() { group('useAutomaticKeepAlive', () { testWidgets('debugFillProperties', (tester) async { await tester.pumpWidget( HookBuilder(builder: (context) { useAutomaticKeepAlive(); return const SizedBox(); }), ); await tester.pump(); final element = tester.element(find.byType(HookBuilder)); expect( element .toDiagnosticsNode(style: DiagnosticsTreeStyle.offstage) .toStringDeep(), equalsIgnoringHashCodes( 'HookBuilder\n' " │ useAutomaticKeepAlive: Instance of 'KeepAliveHandle'\n" ' └SizedBox(renderObject: RenderConstrainedBox#00000)\n', ), ); }); testWidgets('keeps widget alive in a TabView', (tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: DefaultTabController( length: 2, child: TabBarView( children: [ HookBuilder(builder: (context) { useAutomaticKeepAlive(); return Container(); }), Container(), ], ), ), ), ); await tester.pump(); final findKeepAlive = find.byType(AutomaticKeepAlive); final keepAlive = tester.element(findKeepAlive); expect(findKeepAlive, findsOneWidget); expect( keepAlive .toDiagnosticsNode(style: DiagnosticsTreeStyle.shallow) .toStringDeep(), equalsIgnoringHashCodes( 'AutomaticKeepAlive:\n' ' state: _AutomaticKeepAliveState#00000(keeping subtree alive,\n' ' handles: 1 active client)\n', ), ); }); testWidgets( 'start keep alive when wantKeepAlive changes to true', (tester) async { final keepAliveNotifier = ValueNotifier(false); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: DefaultTabController( length: 2, child: TabBarView( children: [ HookBuilder(builder: (context) { final wantKeepAlive = useValueListenable(keepAliveNotifier); useAutomaticKeepAlive(wantKeepAlive: wantKeepAlive); return Container(); }), Container(), ], ), ), ), ); await tester.pump(); final findKeepAlive = find.byType(AutomaticKeepAlive); final keepAlive = tester.element(findKeepAlive); expect(findKeepAlive, findsOneWidget); expect( keepAlive .toDiagnosticsNode(style: DiagnosticsTreeStyle.shallow) .toStringDeep(), equalsIgnoringHashCodes( 'AutomaticKeepAlive:\n' ' state: _AutomaticKeepAliveState#00000(handles: no notifications\n' ' ever received)\n', ), ); keepAliveNotifier.value = true; await tester.pump(); expect(findKeepAlive, findsOneWidget); expect( keepAlive .toDiagnosticsNode(style: DiagnosticsTreeStyle.shallow) .toStringDeep(), equalsIgnoringHashCodes( 'AutomaticKeepAlive:\n' ' state: _AutomaticKeepAliveState#00000(keeping subtree alive,\n' ' handles: 1 active client)\n', ), ); }, ); }); }
flutter_hooks/packages/flutter_hooks/test/use_automatic_keep_alive_test.dart/0
{'file_path': 'flutter_hooks/packages/flutter_hooks/test/use_automatic_keep_alive_test.dart', 'repo_id': 'flutter_hooks', 'token_count': 1896}
import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'mock.dart'; void main() { testWidgets("hot-reload calls useReassemble's callback", (tester) async { final reassemble = MockReassemble(); await tester.pumpWidget(HookBuilder(builder: (context) { useReassemble(reassemble); return Container(); })); verifyNoMoreInteractions(reassemble); hotReload(tester); await tester.pump(); verify(reassemble()).called(1); verifyNoMoreInteractions(reassemble); }); testWidgets('debugFillProperties', (tester) async { await tester.pumpWidget( HookBuilder(builder: (context) { useReassemble(() {}); return const SizedBox(); }), ); final element = tester.element(find.byType(HookBuilder)); expect( element .toDiagnosticsNode(style: DiagnosticsTreeStyle.offstage) .toStringDeep(), equalsIgnoringHashCodes( 'HookBuilder\n' ' │ useReassemble\n' ' └SizedBox(renderObject: RenderConstrainedBox#00000)\n', ), ); }); }
flutter_hooks/packages/flutter_hooks/test/use_reassemble_test.dart/0
{'file_path': 'flutter_hooks/packages/flutter_hooks/test/use_reassemble_test.dart', 'repo_id': 'flutter_hooks', 'token_count': 476}
class GithubUser { final String login; final String avatarUrl; final String url; final String htmlUrl; const GithubUser({this.login, this.avatarUrl, this.url, this.htmlUrl}); static GithubUser fromJson(dynamic json) { return GithubUser( login: json['login'] as String, avatarUrl: json['avatar_url'] as String, url: json['url'] as String, htmlUrl: json['html_url'] as String, ); } }
flutter_hub/github_repository/lib/src/models/github_user.dart/0
{'file_path': 'flutter_hub/github_repository/lib/src/models/github_user.dart', 'repo_id': 'flutter_hub', 'token_count': 155}
import 'dart:async'; import 'package:meta/meta.dart'; import 'package:rxdart/rxdart.dart'; import 'package:bloc/bloc.dart'; import 'package:github_repository/github_repository.dart'; import 'package:flutter_hub/github_search_bloc/bloc.dart'; class GithubSearchBloc extends Bloc<GithubSearchEvent, GithubSearchState> { final GithubRepository githubRepository; GithubSearchBloc({@required this.githubRepository}); @override Stream<GithubSearchState> transform( Stream<GithubSearchEvent> events, Stream<GithubSearchState> Function(GithubSearchEvent event) next, ) { return super.transform( (events as Observable<GithubSearchEvent>).debounceTime( Duration(milliseconds: 500), ), next, ); } @override GithubSearchState get initialState => SearchStateLoading(); @override Stream<GithubSearchState> mapEventToState(GithubSearchEvent event) async* { if (event is ProjectTextChanged) { final String searchTerm = event.text; if (searchTerm.isEmpty) { dispatch(FetchInitialProjects()); } else { yield SearchStateLoading(); try { final results = await githubRepository.searchProjects(searchTerm); yield SearchStateSuccess(results.items); } catch (error) { yield error is SearchResultError ? SearchStateError(error.message) : SearchStateError('something went wrong'); } } } else if (event is FetchInitialProjects) { yield SearchStateLoading(); try { final results = await githubRepository.searchProjects(''); yield SearchStateSuccess(results.items); } catch (error) { yield error is SearchResultError ? SearchStateError(error.message) : SearchStateError('something went wrong'); } } else if (event is ProfileTextChanged) { final String searchTerm = event.text; if (searchTerm.isEmpty) { dispatch(FetchInitialProfiles()); } else { yield SearchStateLoading(); try { final results = await githubRepository.searchProfiles(searchTerm); yield SearchStateSuccess(results.items); } catch (error) { yield error is SearchResultError ? SearchStateError(error.message) : SearchStateError('something went wrong'); } } } else if (event is FetchInitialProfiles) { yield SearchStateLoading(); try { final results = await githubRepository.searchProfiles(''); yield SearchStateSuccess(results.items); } catch (error) { yield error is SearchResultError ? SearchStateError(error.message) : SearchStateError('something went wrong'); } } } }
flutter_hub/lib/github_search_bloc/github_search_bloc.dart/0
{'file_path': 'flutter_hub/lib/github_search_bloc/github_search_bloc.dart', 'repo_id': 'flutter_hub', 'token_count': 1078}
name: flutter_hub description: A new Flutter project. version: 1.0.0+1 environment: sdk: '>=2.0.0-dev.68.0 <3.0.0' dependencies: flutter: sdk: flutter flutter_bloc: ^0.15.0 url_launcher: ^4.0.3 fancy_bottom_navigation: ^0.3.2 github_repository: path: github_repository reddit_repository: path: reddit_repository flutter: uses-material-design: true assets: - assets/flutter_logo.png
flutter_hub/pubspec.yaml/0
{'file_path': 'flutter_hub/pubspec.yaml', 'repo_id': 'flutter_hub', 'token_count': 188}
import 'package:flutter/material.dart'; import 'dart:math' as math; import 'custom_tweens/delay_tween.dart'; enum RotationStyle { inward, outward } class RotatingArc extends StatefulWidget { const RotatingArc({ super.key, this.controller, this.size = 100, this.strokeWidth, this.stokeStyle = PaintingStyle.stroke, this.rotationStyle = RotationStyle.inward, }); final AnimationController? controller; final double size; final double? strokeWidth; final PaintingStyle stokeStyle; final RotationStyle rotationStyle; @override State<RotatingArc> createState() => _RotatingArcState(); } class _RotatingArcState extends State<RotatingArc> with TickerProviderStateMixin { late AnimationController _controller; late AnimationController _controller2; late Animation<double> _animation; @override void initState() { super.initState(); _controller = (widget.controller ?? AnimationController( vsync: this, duration: const Duration(seconds: 1), )) ..addListener(() { setState(() { if (_controller.isCompleted) { _controller2.forward(); } }); }); _controller2 = (AnimationController( vsync: this, duration: const Duration(seconds: 1), )) ..addListener(() async { if (_controller2.isCompleted) { await Future.delayed(const Duration(milliseconds: 300), () { if (mounted) { _controller2.reset(); _controller ..reset() ..forward(); } }); } }); _animation = Tween<double>(begin: math.pi, end: 0).animate(_controller2) ..addListener(() { setState(() {}); }); _controller.forward(); } @override void dispose() { if (widget.controller == null) { _controller.dispose(); } _controller2.dispose(); super.dispose(); } List<double> _getBeginAndEnd({ required RotationStyle rotationStyle, int index = 0, }) { switch (rotationStyle) { case RotationStyle.inward: return [ index == 0 ? math.pi * 2 : 0, index == 0 ? 0 : math.pi * 2, ]; case RotationStyle.outward: return [ 0, math.pi * 2, ]; } } @override Widget build(BuildContext context) { return Stack( children: List.generate(2, (i) { return Center( child: SizedBox.fromSize( size: Size.fromRadius( widget.size * .4 * math.sqrt1_2, ), child: Transform.rotate( alignment: Alignment.center, angle: Tween<double>( begin: _getBeginAndEnd( rotationStyle: widget.rotationStyle, index: i, ).first, end: _getBeginAndEnd( rotationStyle: widget.rotationStyle, index: i, ).last, ).animate(_controller).value, child: ScaleTransition( scale: DelayTween(begin: .5, end: 1, delay: 1) .animate(_controller), child: CustomPaint( painter: _ArcPaint( color: Colors.black, style: widget.stokeStyle, startAngle: i == 0 ? math.pi * 0.5 : math.pi + math.pi * 0.5, sweepAngle: math.pi, radians: _animation.value, index: i, strokeWidth: widget.strokeWidth ?? 2, ), ), ), ), ), ); }), ); } } class _ArcPaint extends CustomPainter { final double radians, strokeWidth, startAngle, sweepAngle; final Color color; final PaintingStyle style; final int index; _ArcPaint({ required this.radians, required this.startAngle, required this.sweepAngle, this.color = Colors.black, this.style = PaintingStyle.fill, required this.strokeWidth, required this.index, }); @override void paint(Canvas canvas, Size size) { final width = size.width; final height = size.height; final centerX = width / 2; final centerY = height / 2; final radius = math.min(centerX, centerY); final centerOffset = Offset( index.isEven ? centerX - ((radius * 0.2) * radians) : centerX + ((radius * 0.2) * radians), centerY, ); final rect = Rect.fromCircle(center: centerOffset, radius: radius); final arcPaint = Paint() ..color = color ..style = style ..strokeWidth = strokeWidth; canvas.drawArc(rect, startAngle, sweepAngle, false, arcPaint); } @override bool shouldRepaint(covariant CustomPainter oldDelegate) => true; }
flutter_loadkit/lib/src/loadkit_rotation_arcs.dart/0
{'file_path': 'flutter_loadkit/lib/src/loadkit_rotation_arcs.dart', 'repo_id': 'flutter_loadkit', 'token_count': 2286}
# These are supported funding model platforms github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: ['www.paypal.me/jogboms']
flutter_offline/.github/FUNDING.yml/0
{'file_path': 'flutter_offline/.github/FUNDING.yml', 'repo_id': 'flutter_offline', 'token_count': 182}
import 'package:flutter/material.dart'; import 'package:flutter_offline/flutter_offline.dart'; class Demo2 extends StatelessWidget { const Demo2({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return OfflineBuilder( connectivityBuilder: ( BuildContext context, ConnectivityResult connectivity, Widget child, ) { if (connectivity == ConnectivityResult.none) { return Container( color: Colors.white, child: const Center( child: Text( 'Oops, \n\nNow we are Offline!', style: TextStyle(color: Colors.black), ), ), ); } else { return child; } }, builder: (BuildContext context) { return const Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'There are no bottons to push :)', ), Text( 'Just turn off your internet.', ), ], ), ); }, ); } }
flutter_offline/example/lib/widgets/demo_2.dart/0
{'file_path': 'flutter_offline/example/lib/widgets/demo_2.dart', 'repo_id': 'flutter_offline', 'token_count': 606}
import 'package:flutter/material.dart'; import 'package:flutter_playlist_animation/utils/animation_manager.dart'; import 'package:flutter_playlist_animation/utils/library_data.dart'; import 'package:flutter_playlist_animation/widgets/featured_library_items.dart'; import 'package:flutter_playlist_animation/widgets/image_wrapper.dart'; class LibraryPage extends StatefulWidget { const LibraryPage({super.key}); @override State<LibraryPage> createState() => _LibraryPageState(); } class _LibraryPageState extends State<LibraryPage> with SingleTickerProviderStateMixin { late final AnimationController animationController; late Animation<Offset> offsetAnimation; @override void initState() { animationController = AnimationController( vsync: this, duration: AnimationManager.pageElementsAnimationDuration, ); offsetAnimation = Tween( begin: const Offset(0, 0), end: const Offset(0, 1), ).animate( CurvedAnimation(parent: animationController, curve: Curves.easeInOut), ); super.initState(); } @override void dispose() { animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('My Playlists'), leading: IconButton( onPressed: () {}, icon: const Icon(Icons.filter_list), ), actions: [ IconButton( onPressed: () {}, icon: const Icon(Icons.search), ), ], ), body: Column( children: [ Expanded( flex: 3, child: FeaturedLibraryItems( animationController: animationController, ), ), Expanded( child: SlideTransition( position: offsetAnimation, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Padding( padding: EdgeInsets.symmetric( horizontal: 20, vertical: 10, ), child: Text( 'Recently Played', style: TextStyle( fontWeight: FontWeight.w700, fontSize: 18, ), ), ), Expanded( child: ListView.builder( padding: EdgeInsets.only( left: 20, right: 20, bottom: MediaQuery.of(context).padding.bottom + 20, ), scrollDirection: Axis.horizontal, itemCount: LibraryData.playlistImages.length, itemBuilder: (context, index) => Padding( padding: const EdgeInsets.only(right: 10), child: ImageWrapper( image: LibraryData.playlistImages[index], size: 100, ), ), ), ) ], ), ), ), ], ), ); } }
flutter_playlist_animation/lib/pages/library_page.dart/0
{'file_path': 'flutter_playlist_animation/lib/pages/library_page.dart', 'repo_id': 'flutter_playlist_animation', 'token_count': 1740}
include: package:very_good_analysis/analysis_options.2.4.0.yaml linter: rules: public_member_api_docs: false
flutter_services_binding/example/analysis_options.yaml/0
{'file_path': 'flutter_services_binding/example/analysis_options.yaml', 'repo_id': 'flutter_services_binding', 'token_count': 45}
name: flutter_services_binding description: A subset of WidgetsFlutterBinding specifically for ServicesBinding. version: 0.1.0 repository: https://github.com/felangel/flutter_services_binding homepage: https://github.com/felangel/flutter_services_binding environment: sdk: ">=2.12.0 <3.0.0" dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter very_good_analysis: ^2.4.0
flutter_services_binding/pubspec.yaml/0
{'file_path': 'flutter_services_binding/pubspec.yaml', 'repo_id': 'flutter_services_binding', 'token_count': 156}
import 'dart:math' as math; import 'package:flutter/widgets.dart'; class SpinKitPouringHourGlassRefined extends StatefulWidget { const SpinKitPouringHourGlassRefined({ Key? key, required this.color, this.size = 50.0, this.duration = const Duration(milliseconds: 2400), this.strokeWidth, this.controller, }) : super(key: key); final double size; final Color color; final Duration duration; final double? strokeWidth; final AnimationController? controller; @override State<SpinKitPouringHourGlassRefined> createState() => _SpinKitPouringHourGlassRefinedState(); } class _SpinKitPouringHourGlassRefinedState extends State<SpinKitPouringHourGlassRefined> with SingleTickerProviderStateMixin { late AnimationController _controller; late Animation<double> _pouringAnimation; late Animation<double> _rotationAnimation; @override void initState() { super.initState(); _controller = (widget.controller ?? AnimationController(vsync: this, duration: widget.duration)) ..addListener(() { if (mounted) { setState(() {}); } }) ..repeat(); _pouringAnimation = CurvedAnimation( parent: _controller, curve: const Interval(0.0, 0.9), )..addListener(() => setState(() {})); _rotationAnimation = Tween(begin: 0.0, end: 0.5).animate( CurvedAnimation( parent: _controller, curve: const Interval(0.9, 1.0, curve: Curves.fastOutSlowIn), ), ); } @override void dispose() { if (widget.controller == null) { _controller.dispose(); } super.dispose(); } @override Widget build(BuildContext context) { return Center( child: RotationTransition( turns: _rotationAnimation, child: SizedBox.fromSize( size: Size.square(widget.size * math.sqrt1_2), child: CustomPaint( painter: _HourGlassPaint( poured: _pouringAnimation.value, color: widget.color, strokeWidth: widget.strokeWidth, ), ), ), ), ); } } class _HourGlassPaint extends CustomPainter { _HourGlassPaint({this.strokeWidth, this.poured, required Color color}) : _paint = Paint() ..style = PaintingStyle.stroke ..color = color, _powderPaint = Paint() ..style = PaintingStyle.fill ..color = color; final double? strokeWidth; final double? poured; final Paint _paint; final Paint _powderPaint; @override void paint(Canvas canvas, Size size) { final centerX = size.width / 2; final halfHeight = size.height / 2; final hourglassWidth = math.min(centerX * 0.8, halfHeight); final gapWidth = math.max(3.0, hourglassWidth * 0.05); final yPadding = gapWidth / 2; final top = yPadding; final bottom = size.height - yPadding; _paint.strokeWidth = strokeWidth ?? gapWidth; final hourglassPath = Path() ..moveTo(centerX - hourglassWidth + 2, top) ..lineTo(centerX + hourglassWidth, top) ..arcToPoint( Offset(centerX + hourglassWidth, top + 7), radius: const Radius.circular(4), clockwise: true, ) ..lineTo(centerX + hourglassWidth - 2, top + 8) ..quadraticBezierTo( centerX + hourglassWidth - 2, (top + halfHeight) / 2 + 2, centerX + gapWidth, halfHeight, ) ..quadraticBezierTo( centerX + hourglassWidth - 2, (bottom + halfHeight) / 2, centerX + hourglassWidth - 2, bottom - 7, ) ..arcToPoint( Offset(centerX + hourglassWidth, bottom), radius: const Radius.circular(4), clockwise: true, ) ..lineTo(centerX - hourglassWidth, bottom) ..arcToPoint( Offset(centerX - hourglassWidth, bottom - 7), radius: const Radius.circular(4), clockwise: true, ) ..lineTo(centerX - hourglassWidth + 2, bottom - 7) ..quadraticBezierTo( centerX - hourglassWidth + 2, (bottom + halfHeight) / 2, centerX - gapWidth, halfHeight, ) ..quadraticBezierTo( centerX - hourglassWidth + 2, (top + halfHeight) / 2 + 2, centerX - hourglassWidth + 2, top + 7, ) ..arcToPoint( Offset(centerX - hourglassWidth, top), radius: const Radius.circular(4), clockwise: true, ) ..close(); canvas.drawPath(hourglassPath, _paint); final upperPart = Path() ..moveTo(0.0, top) ..addRect( Rect.fromLTRB(0.0, halfHeight * poured!, size.width, halfHeight), ); canvas.drawPath( Path.combine(PathOperation.intersect, hourglassPath, upperPart), _powderPaint, ); final lowerPartPath = Path() ..moveTo(centerX, bottom) ..relativeLineTo(hourglassWidth * poured!, 0.0) ..lineTo(centerX, bottom - poured! * halfHeight - gapWidth) ..lineTo(centerX - hourglassWidth * poured!, bottom) ..close(); final lowerPart = Path.combine( PathOperation.intersect, lowerPartPath, Path()..addRect(Rect.fromLTRB(0.0, halfHeight, size.width, size.height)), ); canvas.drawPath(lowerPart, _powderPaint); canvas.drawLine( Offset(centerX, halfHeight), Offset(centerX, bottom), _paint, ); } @override bool shouldRepaint(CustomPainter oldDelegate) => true; }
flutter_spinkit/lib/src/pouring_hour_glass_refined.dart/0
{'file_path': 'flutter_spinkit/lib/src/pouring_hour_glass_refined.dart', 'repo_id': 'flutter_spinkit', 'token_count': 2302}
import 'package:flutter/material.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:flutter_test/flutter_test.dart'; import 'helpers.dart'; void main() { group('FoldingCube', () { testWidgets( 'needs either color or itemBuilder', (WidgetTester tester) async { expect(() => SpinKitFoldingCube(), throwsAssertionError); expect( () => SpinKitFoldingCube( color: Colors.white, itemBuilder: fakeBoxBuilder, ), throwsAssertionError, ); }, ); testWidgets('needs color to be non-null', (WidgetTester tester) async { expect(() => SpinKitFoldingCube(color: null), throwsAssertionError); }); testWidgets( 'needs itemBuilder to be non-null', (WidgetTester tester) async { expect( () => SpinKitFoldingCube(itemBuilder: null), throwsAssertionError, ); }, ); testWidgets('works with color', (WidgetTester tester) async { await tester.pumpWidget( createMaterialApp(const SpinKitFoldingCube(color: Colors.white)), ); expect(find.byType(SpinKitFoldingCube), findsOneWidget); expect(find.byType(DecoratedBox), findsWidgets); tester.verifyTickersWereDisposed(); }); testWidgets('works with itemBuilder', (WidgetTester tester) async { await tester.pumpWidget( createMaterialApp( const SpinKitFoldingCube(itemBuilder: fakeBoxBuilder), ), ); expect(find.byType(SpinKitFoldingCube), findsOneWidget); expect(find.byType(FakeBox), findsWidgets); tester.verifyTickersWereDisposed(); }); testWidgets('works without Material', (WidgetTester tester) async { await tester.pumpWidget( createWidgetsApp(const SpinKitFoldingCube(color: Colors.white)), ); expect(find.byType(SpinKitFoldingCube), findsOneWidget); expect(find.byType(DecoratedBox), findsWidgets); tester.verifyTickersWereDisposed(); }); }); }
flutter_spinkit/test/folding_cube_test.dart/0
{'file_path': 'flutter_spinkit/test/folding_cube_test.dart', 'repo_id': 'flutter_spinkit', 'token_count': 858}
import 'package:flutter/material.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:flutter_test/flutter_test.dart'; import 'helpers.dart'; void main() { group('SquareCircle', () { testWidgets( 'needs either color or itemBuilder', (WidgetTester tester) async { expect(() => SpinKitSquareCircle(), throwsAssertionError); expect( () => SpinKitSquareCircle( color: Colors.white, itemBuilder: fakeBoxBuilder, ), throwsAssertionError, ); }, ); testWidgets('needs color to be non-null', (WidgetTester tester) async { expect(() => SpinKitSquareCircle(color: null), throwsAssertionError); }); testWidgets( 'needs itemBuilder to be non-null', (WidgetTester tester) async { expect( () => SpinKitSquareCircle(itemBuilder: null), throwsAssertionError, ); }, ); testWidgets('works with color', (WidgetTester tester) async { await tester.pumpWidget( createMaterialApp(const SpinKitSquareCircle(color: Colors.white)), ); expect(find.byType(SpinKitSquareCircle), findsOneWidget); expect(find.byType(DecoratedBox), findsWidgets); tester.verifyTickersWereDisposed(); }); testWidgets('works with itemBuilder', (WidgetTester tester) async { await tester.pumpWidget( createMaterialApp( const SpinKitSquareCircle(itemBuilder: fakeBoxBuilder), ), ); expect(find.byType(SpinKitSquareCircle), findsOneWidget); expect(find.byType(FakeBox), findsWidgets); tester.verifyTickersWereDisposed(); }); testWidgets('works without Material', (WidgetTester tester) async { await tester.pumpWidget( createWidgetsApp(const SpinKitSquareCircle(color: Colors.white)), ); expect(find.byType(SpinKitSquareCircle), findsOneWidget); expect(find.byType(DecoratedBox), findsWidgets); tester.verifyTickersWereDisposed(); }); }); }
flutter_spinkit/test/square_circle_test.dart/0
{'file_path': 'flutter_spinkit/test/square_circle_test.dart', 'repo_id': 'flutter_spinkit', 'token_count': 858}
name: flutter_super on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1 with: min_coverage: 80
flutter_super/.github/workflows/main.yml/0
{'file_path': 'flutter_super/.github/workflows/main.yml', 'repo_id': 'flutter_super', 'token_count': 103}
import 'package:flutter/material.dart'; /// A function type used for overriding instances during testing /// or dependency injection. /// /// The [Override] typedef represents a function that takes a [Type] /// and an instance of a generic type [S] as parameters. It is /// used in mocking or dependency injection scenarios to replace instances /// of a particular type with a mock or custom implementation. typedef Override<S> = void Function(Type type, S dep); /// A callback function that builds a widget based on a [BuildContext]. /// /// The [RxBuilder] typedef represents a function that takes a [BuildContext] /// as a parameter and returns a widget. It is used as the builder /// callback in SuperBuilder that listens to changes in Rx objects and rebuild /// the UI in response to those changes. typedef RxBuilder = Widget Function(BuildContext context); /// A callback function that takes a [BuildContext] as a parameter. /// /// The [RxCallback] typedef represents a function that takes a [BuildContext] /// as a parameter and does not return a value. It is used as the listener /// callback in SuperListener for performing actions or side effects in response /// to changes in Rx objects. typedef RxCallback = void Function(BuildContext context); /// A condition function that determines whether to rebuild based on /// previous and current values. /// /// The [RxCondition] typedef represents a function that takes two parameters: /// the previous value and the current value of a generic type [T]. /// It returns a nullable boolean value, which determines whether to call /// the listener based on the change in values. If the condition function /// returns `null`, the listener callback is deferred to the default behavior. /// This typedef is used for the listenWhen callback in Superlistener for /// performing actions or side effects in response to changes in Rx objects. typedef RxCondition<T> = bool? Function(T previous, T current)?; /// A callback function that builds a widget based on an error and stack trace. /// /// The [AsyncErrorBuilder] typedef represents a function that takes /// an [Object] error and a [StackTrace] as parameters and returns a widget. /// It is used as a builder callback for rendering error states in /// asynchronous operations, such as network requests or data loading. typedef AsyncErrorBuilder = Widget Function( Object error, StackTrace stackTrace, ); /// A callback function that builds a widget based on asynchronous data. /// /// The [AsyncDataBuilder] typedef represents a function that takes a generic /// type [T] as a parameter and returns a widget. It is used as a /// builder callback for rendering the data received from asynchronous /// operations, such as network requests or data loading. /// The type parameter [T] represents the type of the data being received. typedef AsyncDataBuilder<T> = Widget Function(T? data);
flutter_super/lib/src/core/typedefs.dart/0
{'file_path': 'flutter_super/lib/src/core/typedefs.dart', 'repo_id': 'flutter_super', 'token_count': 679}
import 'package:flutter/material.dart'; import 'package:flutter_super/flutter_super.dart'; /// {@template super_consumer} /// A widget that consumes a [Rx] object and rebuilds whenever it changes. /// /// [SuperConsumer] is a StatefulWidget that listens to changes in a [Rx] object /// and rebuilds its child widget whenever the [Rx] object's state changes. /// /// The [SuperConsumer] widget takes a [builder] function, which is /// called whenever the [Rx] object changes. The [builder] function receives /// the current [BuildContext] and the latest state of the [Rx] object, /// and returns the widget tree to be built. /// /// Example usage: /// ```dart /// final counter = RxNotifier<int>(0); /// /// // ... /// /// SuperConsumer<int>( /// rx: counter, /// builder: (context, state) { /// return Text('Count: $state'); /// }, /// ) /// ``` /// /// In the above example, a [SuperConsumer] widget is created and given /// a [RxNotifier<int>] object called counter. Whenever the state of /// counter changes, the builder function is called with the latest state, /// and it returns a [Text] widget displaying the count. /// /// See also: /// /// * [RxNotifier] class from the `flutter_super` package. /// * [RxT] class from the `flutter_super` package. /// * [SuperBuilder] widget, which rebuilds when the [Rx] object changes /// without needing an rx parameter. /// {@endtemplate} class SuperConsumer<T> extends StatefulWidget { /// {@macro super_consumer} const SuperConsumer({ required this.builder, required this.rx, super.key, }); /// The [Rx] object to be consumed and listened to for changes. final Rx rx; /// The function that defines the widget tree to be built when the /// [Rx] object changes. /// /// The [builder] function is called with the current [BuildContext] /// and the latest value of the [Rx] object. It should return the /// widget tree to be built based on the current value. final Widget Function(BuildContext context, T state) builder; @override State<SuperConsumer<T>> createState() => _SuperConsumerState<T>(); } class _SuperConsumerState<T> extends State<SuperConsumer<T>> { late T _state; @override void initState() { super.initState(); _initValue(); // Add the listener to the rx during initialization. widget.rx.addListener(_handleChange); } @override void didUpdateWidget(SuperConsumer<T> oldWidget) { super.didUpdateWidget(oldWidget); // Check if the rx has changed and update the listener accordingly. if (widget.rx != oldWidget.rx) { oldWidget.rx.removeListener(_handleChange); widget.rx.addListener(_handleChange); } } void _initValue() { // Obtain the initial state from the rx. final rx = widget.rx; if (rx is RxT<T>) { _state = rx.value; } if (rx is RxNotifier<T>) { _state = rx.state; } } @override void dispose() { // Remove the listener from the rx when disposing the widget. widget.rx.removeListener(_handleChange); super.dispose(); } void _handleChange() { // Trigger a rebuild of the widget whenever the rx changes value. setState(() {}); } @override Widget build(BuildContext context) { _initValue(); return widget.builder(context, _state); } }
flutter_super/lib/src/widgets/super_consumer.dart/0
{'file_path': 'flutter_super/lib/src/widgets/super_consumer.dart', 'repo_id': 'flutter_super', 'token_count': 1060}
import 'package:flutter_super/flutter_super.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('Result - Success', () async { final future = Future<int>.value(10); await expectLater( future.result<Object, int>( (error) { fail('Should not execute the onError callback.'); }, (result) { expect(result, equals(10)); }, ), completes, ); }); test('Result - Error', () async { final future = Future<int>.error('Error'); await expectLater( future.result<Object, int>( (error) { expect(error, equals('Error')); }, (result) { fail('Should not execute the onSuccess callback.'); }, ), completes, ); }); }
flutter_super/test/src/utilities/future_test.dart/0
{'file_path': 'flutter_super/test/src/utilities/future_test.dart', 'repo_id': 'flutter_super', 'token_count': 349}
import 'package:flutter/material.dart'; import 'package:flutter_swiper/flutter_swiper.dart'; import 'config.dart'; import 'forms/form_widget.dart'; class ExampleCustom extends StatefulWidget { @override State<StatefulWidget> createState() { return new _ExampleCustomState(); } } class _ExampleCustomState extends State<ExampleCustom> { //properties whant to custom int _itemCount; bool _loop; bool _autoplay; int _autoplayDely; Axis _axis; double _padding; bool _outer; double _radius; double _viewportFraction; SwiperLayout _layout; int _currentIndex; double _scale; Curve _curve; CustomLayoutOption customLayoutOption; Widget _buildItem(BuildContext context, int index) { return ClipRRect( borderRadius: new BorderRadius.all(new Radius.circular(_radius)), child: new Image.asset( images[index % images.length], fit: BoxFit.fill, ), ); } @override void didUpdateWidget(ExampleCustom oldWidget) { customLayoutOption = new CustomLayoutOption(startIndex: -1, stateCount: 3) .addRotate([-45.0 / 180, 0.0, 45.0 / 180]).addTranslate([ new Offset(-370.0, -40.0), new Offset(0.0, 0.0), new Offset(370.0, -40.0) ]); super.didUpdateWidget(oldWidget); } @override void initState() { customLayoutOption = new CustomLayoutOption(startIndex: -1, stateCount: 3) .addRotate([-25.0 / 180, 0.0, 25.0 / 180]).addTranslate([ new Offset(-350.0, 0.0), new Offset(0.0, 0.0), new Offset(350.0, 0.0) ]); _currentIndex = 0; _curve = Curves.ease; _scale = 0.8; _controller = new SwiperController(); _layout = SwiperLayout.TINDER; _radius = 10.0; _padding = 0.0; _loop = true; _itemCount = 3; _autoplay = false; _autoplayDely = 3000; _axis = Axis.horizontal; _viewportFraction = 0.8; _outer = false; super.initState(); } // maintain the index Widget buildSwiper() { Navigator; return new Swiper( onTap: (int index) { // Navigator // .of(context) // .push(new MaterialPageRoute(builder: (BuildContext context) { // return Scaffold( // appBar: AppBar( // title: Text("New page"), // ), // body: Container(), // ); // })); }, customLayoutOption: customLayoutOption, index: _currentIndex, onIndexChanged: (int index) { setState(() { _currentIndex = index; }); }, curve: _curve, scale: _scale, itemWidth: 300.0, controller: _controller, layout: _layout, outer: _outer, itemHeight: 200.0, viewportFraction: _viewportFraction, autoplayDelay: _autoplayDely, loop: _loop, autoplay: _autoplay, itemBuilder: _buildItem, itemCount: _itemCount, scrollDirection: _axis, pagination: new SwiperPagination(), ); } SwiperController _controller; @override Widget build(BuildContext context) { return new Column(children: <Widget>[ new Container( color: Colors.black87, child: new SizedBox( height: 300.0, width: double.infinity, child: buildSwiper()), ), new Expanded( child: new ListView( children: <Widget>[ new Row( children: <Widget>[ new RaisedButton( onPressed: () { _controller.previous(animation: true); }, child: new Text("Prev"), ), new RaisedButton( onPressed: () { _controller.next(animation: true); }, child: new Text("Next"), ), new Text("Index:$_currentIndex") ], ), new FormWidget( label: "layout", child: new FormSelect( placeholder: "Select layout", value: _layout, values: [ SwiperLayout.DEFAULT, SwiperLayout.STACK, SwiperLayout.TINDER, SwiperLayout.CUSTOM ], valueChanged: (value) { _layout = value; setState(() {}); })), //Pannel Begin new FormWidget( label: "loop", child: new Switch( value: _loop, onChanged: (bool value) => setState(() => _loop = value)), ), new FormWidget( label: "outer", child: new Switch( value: _outer, onChanged: (bool value) => setState(() => _outer = value)), ), //Pannel Begin new FormWidget( label: "autoplay", child: new Switch( value: _autoplay, onChanged: (bool value) => setState(() => _autoplay = value)), ), new FormWidget( label: "padding", child: new NumberPad( number: _padding, step: 5.0, min: 0.0, max: 30.0, onChangeValue: (num value) { _padding = value.toDouble(); setState(() {}); }, ), ), new FormWidget( label: "scale", child: new NumberPad( number: _scale, step: 0.1, min: 0.0, max: 1.0, onChangeValue: (num value) { _scale = value.toDouble(); setState(() {}); }, ), ), new FormWidget( label: "itemCount", child: new NumberPad( number: _itemCount, step: 1, min: 0, max: 100, onChangeValue: (num value) { _itemCount = value.toInt(); setState(() {}); }, ), ), new FormWidget( label: "radius", child: new NumberPad( number: _radius, step: 1.0, min: 0.0, max: 30.0, onChangeValue: (num value) { this._radius = value.toDouble(); setState(() {}); }, ), ), new FormWidget( label: "viewportFraction", child: new NumberPad( number: _viewportFraction, step: 0.1, max: 1.0, min: 0.5, onChangeValue: (num value) { _viewportFraction = value.toDouble(); setState(() {}); }, ), ), new FormWidget( label: "curve", child: new FormSelect( placeholder: "Select curve", value: _layout, values: [ Curves.easeInOut, Curves.ease, Curves.bounceInOut, Curves.bounceOut, Curves.bounceIn, Curves.fastOutSlowIn ], valueChanged: (value) { _curve = value; setState(() {}); })), ], )) ]); } }
flutter_swiper/example/lib/src/ExampleCustom.dart/0
{'file_path': 'flutter_swiper/example/lib/src/ExampleCustom.dart', 'repo_id': 'flutter_swiper', 'token_count': 4116}
import 'package:flutter/material.dart'; import 'package:flutter_swiper/flutter_swiper.dart'; class SwiperControl extends SwiperPlugin { ///IconData for previous final IconData iconPrevious; ///iconData fopr next final IconData iconNext; ///icon size final double size; ///Icon normal color, The theme's [ThemeData.primaryColor] by default. final Color color; ///if set loop=false on Swiper, this color will be used when swiper goto the last slide. ///The theme's [ThemeData.disabledColor] by default. final Color disableColor; final EdgeInsetsGeometry padding; final Key key; const SwiperControl( {this.iconPrevious: Icons.arrow_back_ios, this.iconNext: Icons.arrow_forward_ios, this.color, this.disableColor, this.key, this.size: 30.0, this.padding: const EdgeInsets.all(5.0)}); Widget buildButton(SwiperPluginConfig config, Color color, IconData iconDaga, int quarterTurns, bool previous) { return new GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { if (previous) { config.controller.previous(animation: true); } else { config.controller.next(animation: true); } }, child: Padding( padding: padding, child: RotatedBox( quarterTurns: quarterTurns, child: Icon( iconDaga, semanticLabel: previous ? "Previous" : "Next", size: size, color: color, ))), ); } @override Widget build(BuildContext context, SwiperPluginConfig config) { ThemeData themeData = Theme.of(context); Color color = this.color ?? themeData.primaryColor; Color disableColor = this.disableColor ?? themeData.disabledColor; Color prevColor; Color nextColor; if (config.loop) { prevColor = nextColor = color; } else { bool next = config.activeIndex < config.itemCount - 1; bool prev = config.activeIndex > 0; prevColor = prev ? color : disableColor; nextColor = next ? color : disableColor; } Widget child; if (config.scrollDirection == Axis.horizontal) { child = Row( key: key, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ buildButton(config, prevColor, iconPrevious, 0, true), buildButton(config, nextColor, iconNext, 0, false) ], ); } else { child = Column( key: key, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ buildButton(config, prevColor, iconPrevious, -3, true), buildButton(config, nextColor, iconNext, -3, false) ], ); } return new Container( height: double.infinity, child: child, width: double.infinity, ); } }
flutter_swiper/lib/src/swiper_control.dart/0
{'file_path': 'flutter_swiper/lib/src/swiper_control.dart', 'repo_id': 'flutter_swiper', 'token_count': 1181}
import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; typedef void TextViewCreatedCallback(TextViewController controller); class TextView extends StatefulWidget { const TextView({ Key key, this.onTextViewCreated, }) : super(key: key); final TextViewCreatedCallback onTextViewCreated; @override State<StatefulWidget> createState() => _TextViewState(); } class _TextViewState extends State<TextView> { @override Widget build(BuildContext context) { if (defaultTargetPlatform == TargetPlatform.android) { return AndroidView( viewType: 'plugins.felix.angelov/textview', onPlatformViewCreated: _onPlatformViewCreated, ); } return Text( '$defaultTargetPlatform is not yet supported by the text_view plugin'); } void _onPlatformViewCreated(int id) { if (widget.onTextViewCreated == null) { return; } widget.onTextViewCreated(new TextViewController._(id)); } } class TextViewController { TextViewController._(int id) : _channel = new MethodChannel('plugins.felix.angelov/textview_$id'); final MethodChannel _channel; Future<void> setText(String text) async { assert(text != null); return _channel.invokeMethod('setText', text); } }
flutter_text_view_plugin/lib/text_view.dart/0
{'file_path': 'flutter_text_view_plugin/lib/text_view.dart', 'repo_id': 'flutter_text_view_plugin', 'token_count': 455}
part of 'bloc.dart'; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // abstract class TodoEvent extends Equatable { const TodoEvent(); @override List<Object> get props => []; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // class _TodosStateUpdated extends TodoEvent { final TodosState state; const _TodosStateUpdated(this.state); @override List<Object> get props => [state]; @override String toString() => 'TodosStateUpdated { state: $state }'; }
flutter_todos/lib/blocs/todo/event.dart/0
{'file_path': 'flutter_todos/lib/blocs/todo/event.dart', 'repo_id': 'flutter_todos', 'token_count': 209}
import 'package:todos_app_core/todos_app_core.dart'; import 'package:equatable/equatable.dart'; import 'package:todos_repository_core/todos_repository_core.dart'; class Todo extends Equatable { final bool complete; final String id; final String note; final String task; Todo( this.task, { this.complete = false, String note = '', String id, }) : this.note = note ?? '', this.id = id ?? Uuid().generateV4(); Todo copyWith({bool complete, String id, String note, String task}) { return Todo( task ?? this.task, complete: complete ?? this.complete, id: id ?? this.id, note: note ?? this.note, ); } @override List<Object> get props => [complete, id, note, task]; @override String toString() { return 'Todo { complete: $complete, task: $task, note: $note, id: $id }'; } TodoEntity toEntity() { return TodoEntity(task, id, note, complete); } static Todo fromEntity(TodoEntity entity) { return Todo( entity.task, complete: entity.complete ?? false, note: entity.note, id: entity.id ?? Uuid().generateV4(), ); } }
flutter_todos/lib/models/todo.dart/0
{'file_path': 'flutter_todos/lib/models/todo.dart', 'repo_id': 'flutter_todos', 'token_count': 449}
name: flutter_todos description: A new Flutter project. environment: sdk: ">=2.6.0 <3.0.0" dependencies: meta: ^1.1.8 equatable: ^1.1.1 flutter_bloc: flutter: sdk: flutter dependency_overrides: todos_app_core: git: url: https://github.com/felangel/flutter_architecture_samples path: todos_app_core ref: rxdart/0.23.0 todos_repository_core: git: url: https://github.com/felangel/flutter_architecture_samples path: todos_repository_core ref: rxdart/0.23.0 todos_repository_simple: git: url: https://github.com/felangel/flutter_architecture_samples path: todos_repository_simple ref: rxdart/0.23.0 flutter: uses-material-design: true
flutter_todos/pubspec.yaml/0
{'file_path': 'flutter_todos/pubspec.yaml', 'repo_id': 'flutter_todos', 'token_count': 340}
import 'package:flutter/material.dart'; import 'package:flutter_typeahead/flutter_typeahead.dart'; import 'package:example/data.dart'; class MyMaterialApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'flutter_typeahead demo', home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return DefaultTabController( length: 3, child: Scaffold( appBar: AppBar( title: TabBar(tabs: [ Tab(text: 'Example 1: Navigation'), Tab(text: 'Example 2: Form'), Tab(text: 'Example 3: Scroll') ]), ), body: TabBarView(children: [ NavigationExample(), FormExample(), ScrollExample(), ])), ); } } class NavigationExample extends StatelessWidget { @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.all(32.0), child: Column( children: <Widget>[ SizedBox( height: 10.0, ), TypeAheadField( textFieldConfiguration: TextFieldConfiguration( autofocus: true, style: DefaultTextStyle.of(context) .style .copyWith(fontStyle: FontStyle.italic), decoration: InputDecoration( border: OutlineInputBorder(), hintText: 'What are you looking for?'), ), suggestionsCallback: (pattern) async { return await BackendService.getSuggestions(pattern); }, itemBuilder: (context, suggestion) { return ListTile( leading: Icon(Icons.shopping_cart), title: Text(suggestion['name']), subtitle: Text('\$${suggestion['price']}'), ); }, onSuggestionSelected: (suggestion) { Navigator.of(context).push(MaterialPageRoute( builder: (context) => ProductPage(product: suggestion))); }, ), ], ), ); } } class FormExample extends StatefulWidget { @override _FormExampleState createState() => _FormExampleState(); } class _FormExampleState extends State<FormExample> { final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); final TextEditingController _typeAheadController = TextEditingController(); String _selectedCity; @override Widget build(BuildContext context) { return Form( key: this._formKey, child: Padding( padding: EdgeInsets.all(32.0), child: Column( children: <Widget>[ Text('What is your favorite city?'), TypeAheadFormField( textFieldConfiguration: TextFieldConfiguration( decoration: InputDecoration(labelText: 'City'), controller: this._typeAheadController, ), suggestionsCallback: (pattern) { return CitiesService.getSuggestions(pattern); }, itemBuilder: (context, suggestion) { return ListTile( title: Text(suggestion), ); }, transitionBuilder: (context, suggestionsBox, controller) { return suggestionsBox; }, onSuggestionSelected: (suggestion) { this._typeAheadController.text = suggestion; }, validator: (value) { if (value.isEmpty) { return 'Please select a city'; } }, onSaved: (value) => this._selectedCity = value, ), SizedBox( height: 10.0, ), RaisedButton( child: Text('Submit'), onPressed: () { if (this._formKey.currentState.validate()) { this._formKey.currentState.save(); Scaffold.of(context).showSnackBar(SnackBar( content: Text('Your Favorite City is ${this._selectedCity}'))); } }, ) ], ), ), ); } } class ScrollExample extends StatelessWidget { final List<String> items = List.generate(5, (index) => "Item $index"); @override Widget build(BuildContext context) { return ListView(children: [ Center( child: Padding( padding: const EdgeInsets.all(8.0), child: Text("Suggestion box will resize when scrolling"), )), SizedBox(height: 200), TypeAheadField<String>( getImmediateSuggestions: true, textFieldConfiguration: TextFieldConfiguration( decoration: InputDecoration( border: OutlineInputBorder(), hintText: 'What are you looking for?'), ), suggestionsCallback: (String pattern) async { return items .where((item) => item.toLowerCase().startsWith(pattern.toLowerCase())) .toList(); }, itemBuilder: (context, String suggestion) { return ListTile( title: Text(suggestion), ); }, onSuggestionSelected: (String suggestion) { print("Suggestion selected"); }, ), SizedBox(height: 500), ]); } } class ProductPage extends StatelessWidget { final Map<String, dynamic> product; ProductPage({this.product}); @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: const EdgeInsets.all(50.0), child: Column( children: [ Text( this.product['name'], style: Theme.of(context).textTheme.headline, ), Text( this.product['price'].toString() + ' USD', style: Theme.of(context).textTheme.subhead, ) ], ), ), ); } }
flutter_typeahead/example/lib/material_app.dart/0
{'file_path': 'flutter_typeahead/example/lib/material_app.dart', 'repo_id': 'flutter_typeahead', 'token_count': 3001}
name: Bug Report description: Create a bug report to help us improve the CLI. title: "[bug]: " labels: ["bug", "triage"] # assignees: # - ... body: - type: markdown attributes: value: | Thanks for taking the time to fill out this bug report! - type: checkboxes attributes: label: Is there an existing issue for this? description: | Please search to see if an issue already exists for the bug you encountered. options: - label: I have searched the existing issues. required: true - type: input id: cli_version validations: required: true attributes: label: CLI Version description: | What version of FlutterFire CLI are you running? > Tip: You can use `flutterfire --version` to get the current version. placeholder: "0.2.0" - type: input id: firebase_version validations: required: true attributes: label: Firebase Tools version description: | What version of Firebase Tools are you running? > Tip: You can use `firebase --version` to get the current version. placeholder: "10.4.2" - type: textarea id: flutter_doctor validations: required: true attributes: label: Flutter Doctor Output description: | Please provide the output from the `flutter doctor -v` command. placeholder: The output from the `flutter doctor -v` command is... - type: textarea id: description validations: required: true attributes: label: Description description: | Give us a clear and concise description of what the bug is and what happened. placeholder: The CLI throws an error if I run this command... - type: textarea id: reproduction validations: required: true attributes: label: Steps to reproduce description: | What steps can we take to reproduce the bug? placeholder: | 1. Run command '...' 2. See error - type: textarea id: expected validations: required: true attributes: label: Expected behavior description: | What did you expect to happen? placeholder: | When running ..., the CLI should ... - type: textarea id: screenshots validations: required: false attributes: label: Screenshots description: | If you have any screenshots, please attach them here. - type: textarea id: comments attributes: label: Additional context and comments description: | Anything else you want to say?
flutterfire_cli/.github/ISSUE_TEMPLATE/bug_report.yml/0
{'file_path': 'flutterfire_cli/.github/ISSUE_TEMPLATE/bug_report.yml', 'repo_id': 'flutterfire_cli', 'token_count': 968}
import 'dart:io' show Directory, File; import 'package:path/path.dart' show joinAll; import 'package:yaml/yaml.dart' show YamlMap, loadYaml; Future<void> main() async { final outputPath = joinAll( [ Directory.current.path, 'packages', 'flutterfire_cli', 'lib', 'version.g.dart' ], ); // ignore: avoid_print print('Updating generated file $outputPath'); final pubspecPath = joinAll( [Directory.current.path, 'packages', 'flutterfire_cli', 'pubspec.yaml'], ); final yamlMap = loadYaml(File(pubspecPath).readAsStringSync()) as YamlMap; final currentVersion = yamlMap['version'] as String; final fileContents = "// This file is generated. Do not manually edit.\nString cliVersion = '$currentVersion';\n"; await File(outputPath).writeAsString(fileContents); // ignore: avoid_print print('Updated version to $currentVersion in generated file $outputPath'); }
flutterfire_cli/scripts/generate_version.dart/0
{'file_path': 'flutterfire_cli/scripts/generate_version.dart', 'repo_id': 'flutterfire_cli', 'token_count': 326}
import 'package:bloc/bloc.dart'; import 'package:flutter/widgets.dart'; import 'package:fluttersaurus/bloc_observer.dart'; import 'package:fluttersaurus/fluttersaurus.dart'; import 'package:thesaurus_repository/thesaurus_repository.dart'; void main() { Bloc.observer = FluttersaurusBlocObserver(); runApp(Fluttersaurus(thesaurusRepository: ThesaurusRepository())); }
fluttersaurus/lib/main.dart/0
{'file_path': 'fluttersaurus/lib/main.dart', 'repo_id': 'fluttersaurus', 'token_count': 132}
import 'package:equatable/equatable.dart'; class Synonym extends Equatable { const Synonym(this.value); final String value; @override List<Object> get props => [value]; }
fluttersaurus/lib/synonyms/models/synonym.dart/0
{'file_path': 'fluttersaurus/lib/synonyms/models/synonym.dart', 'repo_id': 'fluttersaurus', 'token_count': 58}
export 'word.dart';
fluttersaurus/packages/datamuse_api/lib/src/models/models.dart/0
{'file_path': 'fluttersaurus/packages/datamuse_api/lib/src/models/models.dart', 'repo_id': 'fluttersaurus', 'token_count': 8}
name: cicd on: push: branches: - main pull_request: types: [opened, reopened, synchronize] jobs: # BEGIN LINTING STAGE format: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: subosito/flutter-action@v2 with: channel: 'stable' - uses: bluefireteam/melos-action@main - run: melos run format-check analyze: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: subosito/flutter-action@v2 with: channel: 'stable' - uses: bluefireteam/melos-action@main - run: melos run analyze # END LINTING STAGE # BEGIN TESTING STAGE test: needs: [format, analyze] runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: subosito/flutter-action@v2 with: channel: 'stable' - uses: bluefireteam/melos-action@main - run: melos run test # END TESTING STAGE
forge2d/.github/workflows/cicd.yml/0
{'file_path': 'forge2d/.github/workflows/cicd.yml', 'repo_id': 'forge2d', 'token_count': 446}
name: forge2d_benchmark description: Simple benchmark for Forge2D version: 1.0.0+1 publish_to: 'none' environment: sdk: ">=3.0.0 <4.0.0" dependencies: build_runner: ^2.4.5 build_web_compilers: ^4.0.3 forge2d: ^0.12.2 dev_dependencies: flame_lint: ^1.1.1
forge2d/packages/benchmark/pubspec.yaml/0
{'file_path': 'forge2d/packages/benchmark/pubspec.yaml', 'repo_id': 'forge2d', 'token_count': 127}
import 'dart:math'; import 'package:forge2d/forge2d.dart'; import 'demo.dart'; class CircleStress extends Demo { /// The number of columns of balls in the pen. static const int columns = 8; /// This number of balls will be created on each layer. static const int loadSize = 20; /// Construct a new Circle Stress Demo. CircleStress() : super('Circle stress'); /// Creates all bodies. @override void initialize() { { final bd = BodyDef(); final ground = world.createBody(bd); bodies.add(ground); final shape = PolygonShape(); shape.setAsEdge(Vector2(-40.0, 0.0), Vector2(40.0, 0.0)); ground.createFixtureFromShape(shape); } { // Ground final shape = PolygonShape(); shape.setAsBoxXY(50.0, 10.0); final bodyDef = BodyDef() ..type = BodyType.static ..position = Vector2(0.0, -10.0); final body = world.createBody(bodyDef); bodies.add(body); final fixtureDef = FixtureDef(shape)..friction = 1.0; body.createFixture(fixtureDef); // Walls shape.setAsBoxXY(3.0, 50.0); final wallDef = BodyDef()..position = Vector2(45.0, 25.0); final rightWall = world.createBody(wallDef); bodies.add(rightWall); rightWall.createFixtureFromShape(shape); wallDef.position = Vector2(-45.0, 25.0); final leftWall = world.createBody(wallDef); bodies.add(leftWall); leftWall.createFixtureFromShape(shape); // Corners final cornerDef = BodyDef(); shape.setAsBoxXY(20.0, 3.0); cornerDef.angle = -pi / 4.0; cornerDef.position = Vector2(-35.0, 8.0); var myBod = world.createBody(cornerDef); bodies.add(myBod); myBod.createFixtureFromShape(shape); cornerDef.angle = pi / 4.0; cornerDef.position = Vector2(35.0, 8.0); myBod = world.createBody(cornerDef); bodies.add(myBod); myBod.createFixtureFromShape(shape); // top shape.setAsBoxXY(50.0, 10.0); final topDef = BodyDef() ..type = BodyType.static ..angle = 0.0 ..position = Vector2(0.0, 75.0); final topBody = world.createBody(topDef); bodies.add(topBody); fixtureDef.shape = shape; fixtureDef.friction = 1.0; topBody.createFixture(fixtureDef); } { final shape = ChainShape(); final vertices = List<Vector2>.generate( 20, (i) => Vector2(i.toDouble(), i.toDouble() * i / 20), ); shape.createChain(vertices); final fixtureDef = FixtureDef(shape) ..restitution = 0.0 ..friction = 0.1; final bodyDef = BodyDef() ..position = Vector2.zero() ..type = BodyType.static; final body = world.createBody(bodyDef)..createFixture(fixtureDef); bodies.add(body); } { final bd = BodyDef() ..type = BodyType.dynamic ..position = Vector2(0.0, 10.0); const numPieces = 5; const radius = 6.0; final body = world.createBody(bd); bodies.add(body); for (var i = 0; i < numPieces; i++) { final xPos = radius * cos(2 * pi * (i / numPieces.toDouble())); final yPos = radius * sin(2 * pi * (i / numPieces.toDouble())); final shape = CircleShape() ..radius = 1.2 ..position.setValues(xPos, yPos); final fixtureDef = FixtureDef(shape) ..density = 25.0 ..friction = .1 ..restitution = .9; body.createFixture(fixtureDef); } body.isBullet = false; // Create an empty ground body. final bodyDef = BodyDef(); final groundBody = world.createBody(bodyDef); final revoluteJointDef = RevoluteJointDef() ..initialize(body, groundBody, body.position) ..motorSpeed = -pi ..maxMotorTorque = 1000000.0 ..enableMotor = true; final revoluteJoint = RevoluteJoint(revoluteJointDef); world.createJoint(revoluteJoint); for (var j = 0; j < columns; j++) { for (var i = 0; i < loadSize; i++) { final shape = CircleShape() ..radius = 1.0 + (i.isEven ? 1.0 : -1.0) * .5 * .75; final fd2 = FixtureDef(shape) ..density = shape.radius * 1.5 ..friction = 0.5 ..restitution = 0.7; final xPos = -39.0 + 2 * i; final yPos = 50.0 + j; final bodyDef = BodyDef() ..type = BodyType.dynamic ..position = Vector2(xPos, yPos); final body = world.createBody(bodyDef); bodies.add(body); body.createFixture(fd2); } } } } } void main() { CircleStress() ..initialize() ..initializeAnimation() ..viewport.scale = 4.0 ..runAnimation(); }
forge2d/packages/forge2d/example/web/circle_stress.dart/0
{'file_path': 'forge2d/packages/forge2d/example/web/circle_stress.dart', 'repo_id': 'forge2d', 'token_count': 2161}
import 'dart:typed_data'; import 'package:forge2d/src/settings.dart' as settings; /// Contact impulses for reporting. Impulses are used instead of forces because /// sub-step forces may approach infinity for rigid body collisions. These match /// up one-to-one with the contact points in b2Manifold. class ContactImpulse { Float64List normalImpulses = Float64List(settings.maxManifoldPoints); Float64List tangentImpulses = Float64List(settings.maxManifoldPoints); int count = 0; }
forge2d/packages/forge2d/lib/src/callbacks/contact_impulse.dart/0
{'file_path': 'forge2d/packages/forge2d/lib/src/callbacks/contact_impulse.dart', 'repo_id': 'forge2d', 'token_count': 143}
import 'dart:math'; import 'package:forge2d/forge2d.dart'; import 'package:forge2d/src/settings.dart' as settings; /// A dynamic tree arranges data in a binary tree to accelerate queries such as /// volume queries and ray casts. Leaves are proxies with an AABB. In the tree /// we expand the proxy AABB by _fatAABBFactor so that the proxy AABB is bigger /// than the client object. This allows the client object to move by small /// amounts without triggering a tree update. class DynamicTree implements BroadPhaseStrategy { static const int maxStackSize = 64; static const int nullNode = -1; DynamicTreeNode? _root; List<DynamicTreeNode> _nodes = List<DynamicTreeNode>.generate( 16, DynamicTreeNode.new, ); int _nodeCount = 0; int _nodeCapacity = 16; int _freeList = 0; final List<Vector2> drawVecs = List<Vector2>.generate( 4, (_) => Vector2.zero(), ); List<DynamicTreeNode?> _nodeStack = List<DynamicTreeNode?>.generate( 20, DynamicTreeNode.new, ); int nodeStackIndex = 0; DynamicTree() { // Build a linked list for the free list. for (var i = _nodeCapacity - 1; i >= 0; i--) { _nodes[i] = DynamicTreeNode(i); _nodes[i].parent = (i == _nodeCapacity - 1) ? null : _nodes[i + 1]; _nodes[i].height = -1; } for (var i = 0; i < drawVecs.length; i++) { drawVecs[i] = Vector2.zero(); } } @override int createProxy(AABB aabb, Object? userData) { assert(aabb.isValid()); final node = _allocateNode(); final proxyId = node.id; // Fatten the aabb final nodeAABB = node.aabb; 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; node.userData = userData; _insertLeaf(proxyId); return proxyId; } @override void destroyProxy(int proxyId) { assert(0 <= proxyId && proxyId < _nodeCapacity); final node = _nodes[proxyId]; assert(node.child1 == null); _removeLeaf(node); _freeNode(node); } @override bool moveProxy(int proxyId, AABB aabb, Vector2 displacement) { assert(aabb.isValid()); assert(0 <= proxyId && proxyId < _nodeCapacity); final node = _nodes[proxyId]; assert(node.child1 == null); final nodeAABB = node.aabb; // 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 lowerBound = nodeAABB.lowerBound; final 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 dx = displacement.x * settings.aabbMultiplier; final 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; } @override Object? userData(int proxyId) { assert(0 <= proxyId && proxyId < _nodeCapacity); return _nodes[proxyId].userData; } @override AABB fatAABB(int proxyId) { assert(0 <= proxyId && proxyId < _nodeCapacity); return _nodes[proxyId].aabb; } @override void query(TreeCallback callback, AABB aabb) { assert(aabb.isValid()); nodeStackIndex = 0; _nodeStack[nodeStackIndex++] = _root; while (nodeStackIndex > 0) { final node = _nodeStack[--nodeStackIndex]; if (node == null) { continue; } if (AABB.testOverlap(node.aabb, aabb)) { if (node.child1 == null) { final proceed = callback.treeCallback(node.id); if (!proceed) { return; } } else { if (_nodeStack.length - nodeStackIndex - 2 <= 0) { final previousSize = _nodeStack.length; _nodeStack = _nodeStack + List.generate( previousSize, (i) => DynamicTreeNode(previousSize + i), ); } _nodeStack[nodeStackIndex++] = node.child1; _nodeStack[nodeStackIndex++] = node.child2; } } } } final Vector2 _r = Vector2.zero(); final AABB _aabb = AABB(); final RayCastInput _subInput = RayCastInput(); @override void raycast(TreeRayCastCallback callback, RayCastInput input) { final p1 = input.p1; final p2 = input.p2; final p1x = p1.x; final p2x = p2.x; final p1y = p1.y; final p2y = p2.y; double vx; double vy; double rx; double ry; double absVx; double absVy; double cx; double cy; double hx; double hy; double tempX; double 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) var maxFraction = input.maxFraction; // Build a bounding box for the segment. final segAABB = _aabb; tempX = (p2x - p1x) * maxFraction + p1x; tempY = (p2y - p1y) * maxFraction + p1y; segAABB.lowerBound.x = min(p1x, tempX); segAABB.lowerBound.y = min(p1y, tempY); segAABB.upperBound.x = max(p1x, tempX); segAABB.upperBound.y = max(p1y, tempY); nodeStackIndex = 0; _nodeStack[nodeStackIndex++] = _root; while (nodeStackIndex > 0) { final node = _nodeStack[--nodeStackIndex]; if (node == null) { continue; } final nodeAABB = node.aabb; if (!AABB.testOverlap(nodeAABB, segAABB)) { continue; } // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, 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; final separation = (vx * tempX + vy * tempY).abs() - (absVx * hx + absVy * hy); if (separation > 0.0) { continue; } if (node.child1 == null) { _subInput.p1.x = p1x; _subInput.p1.y = p1y; _subInput.p2.x = p2x; _subInput.p2.y = p2y; _subInput.maxFraction = maxFraction; final value = callback.raycastCallback(_subInput, node.id); if (value == 0.0) { // The client has terminated the ray cast. return; } if (value > 0.0) { // Update segment bounding box. maxFraction = value; tempX = (p2x - p1x) * maxFraction + p1x; tempY = (p2y - p1y) * maxFraction + p1y; segAABB.lowerBound.x = min(p1x, tempX); segAABB.lowerBound.y = min(p1y, tempY); segAABB.upperBound.x = max(p1x, tempX); segAABB.upperBound.y = max(p1y, tempY); } } else { if (_nodeStack.length - nodeStackIndex - 2 <= 0) { final previousSize = _nodeStack.length; _nodeStack = _nodeStack + List.generate( previousSize, (i) => DynamicTreeNode(previousSize + i), ); } _nodeStack[nodeStackIndex++] = node.child1; _nodeStack[nodeStackIndex++] = node.child2; } } } @override int computeHeight() { assert(_root != null); return _computeHeight(_root!); } int _computeHeight(DynamicTreeNode node) { assert(0 <= node.id && node.id < _nodeCapacity); if (node.child1 == null) { return 0; } final height1 = _computeHeight(node.child1!); final height2 = _computeHeight(node.child2!); return 1 + max<int>(height1, height2); } /// Validate this tree. For testing. void validate() { assert(_root != null); _assertStructureValid(_root); _assertMetricsValid(_root); var freeCount = 0; var freeNode = _freeList != nullNode ? _nodes[_freeList] : null; while (freeNode != null) { assert(0 <= freeNode.id && freeNode.id < _nodeCapacity); assert(freeNode == _nodes[freeNode.id]); freeNode = freeNode.parent; ++freeCount; } assert(getHeight() == computeHeight()); assert(_nodeCount + freeCount == _nodeCapacity); } @override int getHeight() => _root?.height ?? 0; @override int getMaxBalance() { var maxBalance = 0; for (var i = 0; i < _nodeCapacity; ++i) { final node = _nodes[i]; if (node.height <= 1) { continue; } assert(node.child1 != null); assert(node.child2 != null); final balance = (node.child2!.height - node.child1!.height).abs(); maxBalance = max(maxBalance, balance); } return maxBalance; } @override double getAreaRatio() { if (_root == null) { return 0.0; } final rootArea = _root!.aabb.perimeter; var totalArea = 0.0; for (var i = 0; i < _nodeCapacity; ++i) { final node = _nodes[i]; if (node.height < 0) { // Free node in pool continue; } totalArea += node.aabb.perimeter; } return totalArea / rootArea; } /// Build an optimal tree. Very expensive. For testing. void rebuildBottomUp() { final nodes = List<int>.filled(_nodeCount, 0); var count = 0; // Build array of leaves. Free the rest. for (var i = 0; i < _nodeCapacity; ++i) { if (_nodes[i].height < 0) { // free node in pool continue; } final node = _nodes[i]; if (node.child1 == null) { node.parent = null; nodes[count] = i; ++count; } else { _freeNode(node); } } final b = AABB(); while (count > 1) { var minCost = double.maxFinite; var iMin = -1; var jMin = -1; for (var i = 0; i < count; ++i) { final aabbi = _nodes[nodes[i]].aabb; for (var j = i + 1; j < count; ++j) { final aabbj = _nodes[nodes[j]].aabb; b.combine2(aabbi, aabbj); final cost = b.perimeter; if (cost < minCost) { iMin = i; jMin = j; minCost = cost; } } } final index1 = nodes[iMin]; final index2 = nodes[jMin]; final child1 = _nodes[index1]; final child2 = _nodes[index2]; final parent = _allocateNode(); parent.child1 = child1; parent.child2 = child2; parent.height = 1 + max<int>(child1.height, child2.height); parent.aabb.combine2(child1.aabb, child2.aabb); parent.parent = null; child1.parent = parent; child2.parent = parent; nodes[jMin] = nodes[count - 1]; nodes[iMin] = parent.id; --count; } _root = _nodes[nodes[0]]; validate(); } DynamicTreeNode _allocateNode() { if (_freeList == nullNode) { assert(_nodeCount == _nodeCapacity); _nodes = _nodes + List<DynamicTreeNode>.generate( _nodeCapacity, (i) => DynamicTreeNode(_nodeCapacity + i), ); _nodeCapacity = _nodes.length; // Build a linked list for the free list. for (var i = _nodeCapacity - 1; i >= _nodeCount; i--) { _nodes[i].parent = (i == _nodeCapacity - 1) ? null : _nodes[i + 1]; _nodes[i].height = -1; } _freeList = _nodeCount; } final nodeId = _freeList; final treeNode = _nodes[nodeId]; _freeList = treeNode.parent != null ? treeNode.parent!.id : nullNode; treeNode.parent = null; treeNode.child1 = null; treeNode.child2 = null; treeNode.height = 0; treeNode.userData = null; ++_nodeCount; return treeNode; } /// returns a node to the pool void _freeNode(DynamicTreeNode node) { assert(0 < _nodeCount); node.parent = _freeList != nullNode ? _nodes[_freeList] : null; node.height = -1; _freeList = node.id; _nodeCount--; } final AABB _combinedAABB = AABB(); void _insertLeaf(int leafIndex) { final leaf = _nodes[leafIndex]; if (_root == null) { _root = leaf; _root!.parent = null; return; } // find the best sibling final leafAABB = leaf.aabb; var index = _root; while (index?.child1 != null) { final node = index!; final child1 = node.child1!; final child2 = node.child2!; final area = node.aabb.perimeter; _combinedAABB.combine2(node.aabb, leafAABB); final combinedArea = _combinedAABB.perimeter; // Cost of creating a new parent for this node and the new leaf final cost = 2.0 * combinedArea; // Minimum cost of pushing the leaf further down the tree final inheritanceCost = 2.0 * (combinedArea - area); // Cost of descending into child1 double cost1; if (child1.child1 == null) { _combinedAABB.combine2(leafAABB, child1.aabb); cost1 = _combinedAABB.perimeter + inheritanceCost; } else { _combinedAABB.combine2(leafAABB, child1.aabb); final oldArea = child1.aabb.perimeter; final newArea = _combinedAABB.perimeter; cost1 = (newArea - oldArea) + inheritanceCost; } // Cost of descending into child2 double cost2; if (child2.child1 == null) { _combinedAABB.combine2(leafAABB, child2.aabb); cost2 = _combinedAABB.perimeter + inheritanceCost; } else { _combinedAABB.combine2(leafAABB, child2.aabb); final oldArea = child2.aabb.perimeter; final newArea = _combinedAABB.perimeter; 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; } } final sibling = index!; final oldParent = _nodes[sibling.id].parent; final newParent = _allocateNode(); newParent.parent = oldParent; newParent.userData = null; newParent.aabb.combine2(leafAABB, sibling.aabb); newParent.height = sibling.height + 1; if (oldParent != null) { // The sibling was not the root. if (oldParent.child1 == sibling) { oldParent.child1 = newParent; } else { oldParent.child2 = newParent; } newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; } else { // The sibling was the root. newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; _root = newParent; } // Walk back up the tree fixing heights and AABBs index = leaf.parent; while (index != null) { index = _balance(index); assert(index.child1 != null); assert(index.child2 != null); final child1 = index.child1!; final child2 = index.child2!; index.height = 1 + max<int>(child1.height, child2.height); index.aabb.combine2(child1.aabb, child2.aabb); index = index.parent; } // validate(); } void _removeLeaf(DynamicTreeNode leaf) { if (leaf == _root) { _root = null; return; } final parent = leaf.parent; final grandParent = parent?.parent; DynamicTreeNode? sibling; if (parent?.child1 == leaf) { sibling = parent?.child2; } else { sibling = parent?.child1; } if (grandParent != null) { // Destroy parent and connect sibling to grandParent. if (grandParent.child1 == parent) { grandParent.child1 = sibling; } else { grandParent.child2 = sibling; } sibling?.parent = grandParent; _freeNode(parent!); // Adjust ancestor bounds. DynamicTreeNode? index = grandParent; while (index != null) { index = _balance(index); final child1 = index.child1!; final child2 = index.child2!; index.aabb.combine2(child1.aabb, child2.aabb); index.height = 1 + max<int>(child1.height, child2.height); index = index.parent; } } else { _root = sibling; sibling?.parent = null; _freeNode(parent!); } // validate(); } // Perform a left or right rotation if node A is imbalanced. // Returns the new root index. DynamicTreeNode _balance(DynamicTreeNode iA) { final a = iA; if (a.child1 == null || a.height < 2) { return iA; } final iB = a.child1!; final iC = a.child2!; assert(0 <= iB.id && iB.id < _nodeCapacity); assert(0 <= iC.id && iC.id < _nodeCapacity); final b = iB; final c = iC; final balance = c.height - b.height; // Rotate C up if (balance > 1) { final iF = c.child1!; final iG = c.child2!; final f = iF; final g = iG; assert(0 <= iF.id && iF.id < _nodeCapacity); assert(0 <= iG.id && iG.id < _nodeCapacity); // Swap A and C c.child1 = iA; c.parent = a.parent; a.parent = iC; // A's old parent should point to C if (c.parent != null) { if (c.parent!.child1 == iA) { c.parent!.child1 = iC; } else { assert(c.parent!.child2 == iA); c.parent!.child2 = iC; } } else { _root = iC; } // Rotate if (f.height > g.height) { c.child2 = iF; a.child2 = iG; g.parent = iA; a.aabb.combine2(b.aabb, g.aabb); c.aabb.combine2(a.aabb, f.aabb); a.height = 1 + max<int>(b.height, g.height); c.height = 1 + max<int>(a.height, f.height); } else { c.child2 = iG; a.child2 = iF; f.parent = iA; a.aabb.combine2(b.aabb, f.aabb); c.aabb.combine2(a.aabb, g.aabb); a.height = 1 + max<int>(b.height, f.height); c.height = 1 + max<int>(a.height, g.height); } return iC; } // Rotate B up if (balance < -1) { final iD = b.child1!; final iE = b.child2!; final d = iD; final e = iE; assert(0 <= iD.id && iD.id < _nodeCapacity); assert(0 <= iE.id && iE.id < _nodeCapacity); // Swap A and B b.child1 = iA; b.parent = a.parent; a.parent = iB; // A's old parent should point to B if (b.parent != null) { if (b.parent!.child1 == iA) { b.parent!.child1 = iB; } else { assert(b.parent!.child2 == iA); b.parent!.child2 = iB; } } else { _root = iB; } // Rotate if (d.height > e.height) { b.child2 = iD; a.child1 = iE; e.parent = iA; a.aabb.combine2(c.aabb, e.aabb); b.aabb.combine2(a.aabb, d.aabb); a.height = 1 + max<int>(c.height, e.height); b.height = 1 + max<int>(a.height, d.height); } else { b.child2 = iE; a.child1 = iD; d.parent = iA; a.aabb.combine2(c.aabb, d.aabb); b.aabb.combine2(a.aabb, e.aabb); a.height = 1 + max<int>(c.height, d.height); b.height = 1 + max<int>(a.height, e.height); } return iB; } return iA; } void _assertStructureValid(DynamicTreeNode? node) { if (node == null) { return; } assert(node == _nodes[node.id]); if (node == _root) { assert(node.parent == null); } final child1 = node.child1; final child2 = node.child2; if (node.child1 == null) { assert(child1 == null); assert(child2 == null); assert(node.height == 0); return; } assert(child1 != null && 0 <= child1.id && child1.id < _nodeCapacity); assert(child2 != null && 0 <= child2.id && child2.id < _nodeCapacity); assert(child1!.parent == node); assert(child2!.parent == node); _assertStructureValid(child1); _assertStructureValid(child2); } void _assertMetricsValid(DynamicTreeNode? node) { if (node == null) { return; } final child1 = node.child1; final child2 = node.child2; if (node.child1 == null) { assert(child1 == null); assert(child2 == null); assert(node.height == 0); return; } assert(child1 != null && 0 <= child1.id && child1.id < _nodeCapacity); assert(child2 != null && 0 <= child2.id && child2.id < _nodeCapacity); final height1 = child1!.height; final height2 = child2!.height; int height; height = 1 + max<int>(height1, height2); assert(node.height == height); final aabb = AABB(); aabb.combine2(child1.aabb, child2.aabb); assert(aabb.lowerBound == node.aabb.lowerBound); assert(aabb.upperBound == node.aabb.upperBound); _assertMetricsValid(child1); _assertMetricsValid(child2); } @override void drawTree(DebugDraw argDraw) { if (_root == null) { return; } final height = computeHeight(); drawTreeX(argDraw, _root!, 0, height); } final Color3i _color = Color3i.zero(); void drawTreeX( DebugDraw argDraw, DynamicTreeNode node, int spot, int height, ) { node.aabb.getVertices(drawVecs); _color.setFromRGBd( 1.0, (height - spot) * 1.0 / height, (height - spot) * 1.0 / height, ); argDraw.drawPolygon(drawVecs, _color); final textVec = argDraw.viewport.worldToScreen(node.aabb.upperBound); argDraw.drawStringXY( textVec.x, textVec.y, '$node.id-${spot + 1}/$height', _color, ); if (node.child1 != null) { drawTreeX(argDraw, node.child1!, spot + 1, height); } if (node.child2 != null) { drawTreeX(argDraw, node.child2!, spot + 1, height); } } }
forge2d/packages/forge2d/lib/src/collision/broadphase/dynamic_tree.dart/0
{'file_path': 'forge2d/packages/forge2d/lib/src/collision/broadphase/dynamic_tree.dart', 'repo_id': 'forge2d', 'token_count': 10280}
import 'dart:math'; import 'package:forge2d/forge2d.dart'; import 'package:forge2d/src/settings.dart' as settings; /// 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 { /// Local position of the shape centroid in parent body frame. final Vector2 centroid = Vector2.zero(); /// The vertices of the shape. Note: use vertexCount, not _vertices.length, /// to get number of active vertices. final List<Vector2> vertices = []; /// The normals of the shape. Note: use vertexCount, not _normals.length, to /// get number of active normals. final List<Vector2> normals = []; PolygonShape() : super(ShapeType.polygon) { radius = settings.polygonRadius; } @override Shape clone() { final shape = PolygonShape(); shape.centroid.setFrom(centroid); normals.forEach((normal) => shape.normals.add(normal.clone())); vertices.forEach((vertex) => shape.vertices.add(vertex.clone())); shape.radius = radius; return shape; } /// Create a convex hull from the given array of points. The length of the /// list 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(List<Vector2> updatedVertices) { final updatedCount = updatedVertices.length; assert(updatedCount >= 3, 'Too few vertices to form polygon'); assert(updatedCount <= settings.maxPolygonVertices, 'Too many vertices'); if (updatedCount < 3) { setAsBoxXY(1.0, 1.0); return; } // Perform welding and copy vertices into local buffer. final points = <Vector2>[]; for (final v in updatedVertices) { var unique = true; for (var j = 0; j < points.length; ++j) { if (v.distanceToSquared(points[j]) < 0.5 * settings.linearSlop) { unique = false; break; } } if (unique) { points.add(v.clone()); if (points.length == settings.maxPolygonVertices) { break; } } } if (points.length < 3) { assert(false, 'Too few vertices to be a polygon'); 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 var rightMostPoint = points.first; for (final point in points) { final x = point.x; final y = point.y; final x0 = rightMostPoint.x; final y0 = rightMostPoint.y; if (x > x0 || (x == x0 && y < y0)) { rightMostPoint = point; } } final hull = <Vector2>[rightMostPoint]; var pointOnHull = rightMostPoint; do { // Set first point in the set as the initial candidate for the // next point on the convex hull. var endPoint = points[0]; // Test the candidate point against all points in the set to find // the next convex hull point. for (final point in points) { // If the candidate point is the current last point on the convex // hull, update the candidate point to the current point and continue // checking against the remaining points. if (endPoint == pointOnHull) { endPoint = point; continue; } // Use the cross product of the vectors from the current convex hull // point to the candidate point and the test point to see if the winding // changes from CCW to CW. This indicates the current point is a better // candidate for a hull point. Update the candidate point. final r = endPoint.clone()..sub(pointOnHull); final v = point.clone()..sub(pointOnHull); final c = r.cross(v); if (c < 0.0) { endPoint = point; } // Collinearity check if (c == 0.0 && v.length2 > r.length2) { endPoint = point; } } // Set the end point candidate as the new current convex hull point. pointOnHull = endPoint; if (!hull.contains(pointOnHull)) { hull.add(pointOnHull); } } while (pointOnHull != hull.first); // Copy vertices. vertices.clear(); vertices.addAll(hull); vertices.forEach((_) => normals.add(Vector2.zero())); final edge = Vector2.zero(); // Compute normals. Ensure the edges have non-zero length. for (var i = 0; i < vertices.length; ++i) { final i1 = i; final i2 = (i + 1) % vertices.length; 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. computeCentroid(vertices, vertices.length); } /// Build vertices to represent an axis-aligned box. void setAsBoxXY(double halfWidth, double halfHeight) { vertices.clear(); vertices.addAll([ Vector2(-halfWidth, -halfHeight), Vector2(halfWidth, -halfHeight), Vector2(halfWidth, halfHeight), Vector2(-halfWidth, halfHeight), ]); normals.clear(); normals.addAll([ Vector2(0.0, -1.0), Vector2(1.0, 0.0), Vector2(0.0, 1.0), Vector2(-1.0, 0.0), ]); centroid.setZero(); } /// Build vertices to represent an oriented box. /// [center] and [angle] should be in local coordinates. void setAsBox( double halfWidth, double halfHeight, Vector2 center, double angle, ) { setAsBoxXY(halfWidth, halfHeight); centroid.setFrom(center); final xf = Transform.zero(); xf.p.setFrom(center); xf.q.setAngle(angle); // Transform vertices and normals. for (var i = 0; i < vertices.length; ++i) { vertices[i].setFrom(Transform.mulVec2(xf, vertices[i])); normals[i].setFrom(Rot.mulVec2(xf.q, normals[i])); } } /// Set this as a single edge. void setAsEdge(Vector2 v1, Vector2 v2) { vertices.clear(); vertices.add(v1.clone()); vertices.add(v2.clone()); centroid ..setFrom(v1) ..add(v2) ..scale(0.5); normals.clear(); normals.add(v2 - v1); normals[0].scaleOrthogonalInto(-1.0, normals[0]); normals[0].normalize(); normals.add(-normals[0]); } @override int get childCount { return 1; } @override bool testPoint(Transform xf, Vector2 p) { final xfq = xf.q; var tempX = p.x - xf.p.x; var tempY = p.y - xf.p.y; final pLocalX = xfq.cos * tempX + xfq.sin * tempY; final pLocalY = -xfq.sin * tempX + xfq.cos * tempY; for (var i = 0; i < vertices.length; ++i) { final vertex = vertices[i]; final normal = normals[i]; tempX = pLocalX - vertex.x; tempY = pLocalY - vertex.y; final dot = normal.x * tempX + normal.y * tempY; if (dot > 0.0) { return false; } } return true; } @override void computeAABB(AABB aabb, Transform xf, int childIndex) { final lower = aabb.lowerBound; final upper = aabb.upperBound; final v1 = vertices[0]; final xfqc = xf.q.cos; final xfqs = xf.q.sin; final xfpx = xf.p.x; final 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 (var i = 1; i < vertices.length; ++i) { final v2 = vertices[i]; // Vec2 v = Mul(xf, _vertices[i]); final vx = (xfqc * v2.x - xfqs * v2.y) + xfpx; final 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; } @override double computeDistanceToOut( Transform xf, Vector2 p, int childIndex, Vector2 normalOut, ) { final xfqc = xf.q.cos; final xfqs = xf.q.sin; var tx = p.x - xf.p.x; var ty = p.y - xf.p.y; final pLocalx = xfqc * tx + xfqs * ty; final pLocaly = -xfqs * tx + xfqc * ty; var maxDistance = -double.maxFinite; var normalForMaxDistanceX = pLocalx; var normalForMaxDistanceY = pLocaly; for (var i = 0; i < vertices.length; ++i) { final vertex = vertices[i]; final normal = normals[i]; tx = pLocalx - vertex.x; ty = pLocaly - vertex.y; final dot = normal.x * tx + normal.y * ty; if (dot > maxDistance) { maxDistance = dot; normalForMaxDistanceX = normal.x; normalForMaxDistanceY = normal.y; } } double distance; if (maxDistance > 0) { var minDistanceX = normalForMaxDistanceX; var minDistanceY = normalForMaxDistanceY; var minDistance2 = maxDistance * maxDistance; for (var i = 0; i < vertices.length; ++i) { final vertex = vertices[i]; final distanceVecX = pLocalx - vertex.x; final distanceVecY = pLocaly - vertex.y; final distance2 = distanceVecX * distanceVecX + distanceVecY * distanceVecY; if (minDistance2 > distance2) { minDistanceX = distanceVecX; minDistanceY = distanceVecY; minDistance2 = distance2; } } distance = 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; } @override bool raycast( RayCastOutput output, RayCastInput input, Transform xf, int childIndex, ) { final xfqc = xf.q.cos; final xfqs = xf.q.sin; final xfp = xf.p; var tempX = input.p1.x - xfp.x; var tempY = input.p1.y - xfp.y; final p1x = xfqc * tempX + xfqs * tempY; final p1y = -xfqs * tempX + xfqc * tempY; tempX = input.p2.x - xfp.x; tempY = input.p2.y - xfp.y; final p2x = xfqc * tempX + xfqs * tempY; final p2y = -xfqs * tempX + xfqc * tempY; final dx = p2x - p1x; final dy = p2y - p1y; var lower = 0.0; var upper = input.maxFraction; var index = -1; for (var i = 0; i < vertices.length; ++i) { final normal = normals[i]; final vertex = vertices[i]; final tempX = vertex.x - p1x; final tempY = vertex.y - p1y; final numerator = normal.x * tempX + normal.y * tempY; final 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; final normal = normals[index]; final out = output.normal; out.x = xfqc * normal.x - xfqs * normal.y; out.y = xfqs * normal.x + xfqc * normal.y; return true; } return false; } void computeCentroid(List<Vector2> vs, int count) { assert(count >= 3); centroid.setZero(); var area = 0.0; // pRef is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). final pRef = Vector2.zero(); final e1 = Vector2.zero(); final e2 = Vector2.zero(); const inv3 = 1.0 / 3.0; for (var i = 0; i < count; ++i) { // Triangle vertices. final p1 = pRef; final p2 = vs[i]; final p3 = i + 1 < count ? vs[i + 1] : vs[0]; e1 ..setFrom(p2) ..sub(p1); e2 ..setFrom(p3) ..sub(p1); final D = e1.cross(e2); final triangleArea = 0.5 * D; area += triangleArea.abs(); // Area weighted centroid e1 ..setFrom(p1) ..add(p2) ..add(p3) ..scale(triangleArea * inv3); centroid.add(e1); } // Centroid assert(area > settings.epsilon); centroid.scale(1.0 / area); } @override void computeMass(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(vertices.length >= 3); final center = Vector2.zero(); var area = 0.0; var I = 0.0; // pRef is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). final s = Vector2.zero(); // This code would put the reference point inside the polygon. for (var i = 0; i < vertices.length; ++i) { s.add(vertices[i]); } s.scale(1.0 / vertices.length.toDouble()); const kInv3 = 1.0 / 3.0; final e1 = Vector2.zero(); final e2 = Vector2.zero(); for (var i = 0; i < vertices.length; ++i) { // Triangle vertices. e1 ..setFrom(vertices[i]) ..sub(s); e2 ..setFrom(s) ..negate() ..add(i + 1 < vertices.length ? vertices[i + 1] : vertices[0]); final D = e1.cross(e2); final triangleArea = 0.5 * D; area += triangleArea.abs(); // Area weighted centroid center.x += triangleArea * kInv3 * (e1.x + e2.x); center.y += triangleArea * kInv3 * (e1.y + e2.y); final ex1 = e1.x; final ey1 = e1.y; final ex2 = e2.x; final ey2 = e2.y; final intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2; final inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2; I += (0.25 * kInv3 * 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 (var i = 0; i < vertices.length; ++i) { final i1 = i; final i2 = i < vertices.length - 1 ? i1 + 1 : 0; final p = vertices[i1]; final e = Vector2.copy(vertices[i2])..sub(p); for (var j = 0; j < vertices.length; ++j) { if (j == i1 || j == i2) { continue; } final v = Vector2.copy(vertices[j])..sub(p); final c = e.cross(v); if (c < 0.0) { return false; } } } return true; } /// Get the centroid and apply the supplied transform. Vector2 applyToCentroid(Transform xf) { return Transform.mulVec2(xf, centroid); } }
forge2d/packages/forge2d/lib/src/collision/shapes/polygon_shape.dart/0
{'file_path': 'forge2d/packages/forge2d/lib/src/collision/shapes/polygon_shape.dart', 'repo_id': 'forge2d', 'token_count': 7239}
import 'package:forge2d/forge2d.dart'; /// Defines the type of a [Body]. enum BodyType { /// Defines a [Body] with zero mass, zero velocity, may be manually moved. static, /// Defines a [Body] with zero mass, non-zero velocity set by user, moved by /// solver. kinematic, /// Defines a [Body] with positive mass, non-zero velocity determined by /// forces, moved by solver. dynamic, }
forge2d/packages/forge2d/lib/src/dynamics/body_type.dart/0
{'file_path': 'forge2d/packages/forge2d/lib/src/dynamics/body_type.dart', 'repo_id': 'forge2d', 'token_count': 128}
// TODO(any): Rewrite the setters instead of ignoring this lint. // ignore_for_file: avoid_positional_boolean_parameters import 'dart:math'; import 'package:forge2d/forge2d.dart'; import 'package:forge2d/src/settings.dart' as settings; import 'package:meta/meta.dart'; /// A fixture is used to attach a [Shape] to a [Body] for collision detection. A /// fixture inherits its transform from its parent. Fixtures hold additional /// non-geometric data such as friction, collision filters, etc. Fixtures are /// created via `body.createFixture`. /// /// Do note that you cannot reuse fixtures. class Fixture { double _density = 0.0; final Body body; late Shape shape; double friction = 0.0; double restitution = 0.0; final List<FixtureProxy> proxies = []; int _proxyCount = 0; int get proxyCount => _proxyCount; final Filter _filter = Filter(); bool _isSensor = false; /// Use this to store your application specific data. Object? userData; /// Get the type of the child shape. You can use this to down cast to the /// concrete shape. ShapeType get type => shape.shapeType; /// Is this fixture a sensor (non-solid)? bool get isSensor => _isSensor; /// Set if this fixture is a sensor. void setSensor(bool sensor) { if (sensor != _isSensor) { body.setAwake(true); _isSensor = sensor; } } /// Set the contact filtering data. This is an expensive operation and should /// not be called frequently. This will not update contacts until the next /// time step when either parent body is awake. This automatically calls /// [refilter]. set filterData(Filter filter) { _filter.set(filter); refilter(); } /// Get the contact filtering data. Filter get filterData => _filter; /// Call this if you want to establish collision that was previously disabled /// by [ContactFilter.shouldCollide]. void refilter() { // Flag associated contacts for filtering. for (final contact in body.contacts) { final fixtureA = contact.fixtureA; final fixtureB = contact.fixtureB; if (fixtureA == this || fixtureB == this) { contact.flagForFiltering(); } } // Touch each proxy so that new pairs may be created final broadPhase = body.world.contactManager.broadPhase; for (var i = 0; i < _proxyCount; ++i) { broadPhase.touchProxy(proxies[i].proxyId); } } set density(double density) { assert(density >= 0.9); _density = density; } double get density => _density; /// Test a point for containment in this fixture. This only works for convex /// shapes. /// /// [point] should be in world coordinates. bool testPoint(Vector2 point) { return shape.testPoint(body.transform, point); } /// Cast a ray against this shape. bool raycast(RayCastOutput output, RayCastInput input, int childIndex) { return shape.raycast(output, input, body.transform, childIndex); } /// Get the mass data for this fixture. The mass data is based on the density /// and the shape. The rotational inertia is about the shape's origin. void getMassData(MassData massData) { shape.computeMass(massData, _density); } /// Get the fixture's AABB. This AABB may be enlarge and/or stale. If you /// need a more accurate AABB, compute it using the shape and the body /// transform. AABB getAABB(int childIndex) { assert(childIndex >= 0 && childIndex < _proxyCount); return proxies[childIndex].aabb; } /// Compute the distance from this fixture. /// /// [point] should be in world coordinates. double computeDistance( Vector2 point, int childIndex, Vector2 normalOut, ) { return shape.computeDistanceToOut( body.transform, point, childIndex, normalOut, ); } Fixture(this.body, FixtureDef def) { userData = def.userData; friction = def.friction; restitution = def.restitution; _filter.set(def.filter); _isSensor = def.isSensor; shape = def.shape.clone(); // Reserve proxy space final childCount = shape.childCount; if (proxies.length < childCount) { final old = proxies; final newLength = max(old.length * 2, childCount); proxies.clear(); for (var x = 0; x < newLength; x++) { proxies.add(FixtureProxy(this)..proxyId = BroadPhase.nullProxy); } } _proxyCount = 0; _density = def.density; } // These support body activation/deactivation. void createProxies(BroadPhase broadPhase, Transform xf) { assert(_proxyCount == 0); // Create proxies in the broad-phase. _proxyCount = shape.childCount; for (var i = 0; i < _proxyCount; ++i) { final proxy = proxies[i]; shape.computeAABB(proxy.aabb, xf, i); proxy.proxyId = broadPhase.createProxy(proxy.aabb, proxy); proxy.childIndex = i; } } /// Internal method void destroyProxies(BroadPhase broadPhase) { // Destroy proxies in the broad-phase. for (var i = 0; i < _proxyCount; ++i) { final proxy = proxies[i]; broadPhase.destroyProxy(proxy.proxyId); proxy.proxyId = BroadPhase.nullProxy; } _proxyCount = 0; } final AABB _pool1 = AABB(); final AABB _pool2 = AABB(); final Vector2 _displacement = Vector2.zero(); @internal void synchronize( BroadPhase broadPhase, Transform transform1, Transform transform2, ) { if (_proxyCount == 0) { return; } for (var i = 0; i < _proxyCount; ++i) { final proxy = proxies[i]; // Compute an AABB that covers the swept shape // (may miss some rotation effect). final aabb1 = _pool1; final aab = _pool2; shape.computeAABB(aabb1, transform1, proxy.childIndex); shape.computeAABB(aab, transform2, proxy.childIndex); proxy.aabb.lowerBound.x = aabb1.lowerBound.x < aab.lowerBound.x ? aabb1.lowerBound.x : aab.lowerBound.x; proxy.aabb.lowerBound.y = aabb1.lowerBound.y < aab.lowerBound.y ? aabb1.lowerBound.y : aab.lowerBound.y; proxy.aabb.upperBound.x = aabb1.upperBound.x > aab.upperBound.x ? aabb1.upperBound.x : aab.upperBound.x; proxy.aabb.upperBound.y = aabb1.upperBound.y > aab.upperBound.y ? aabb1.upperBound.y : aab.upperBound.y; _displacement.x = transform2.p.x - transform1.p.x; _displacement.y = transform2.p.y - transform1.p.y; broadPhase.moveProxy(proxy.proxyId, proxy.aabb, _displacement); } } // NOTE this corresponds to the liquid test, so the debugdraw can draw // the liquid particles correctly. They should be the same. static const int liquidFlag = 1234598372; final double _liquidLength = .12; double _averageLinearVel = -1.0; final Vector2 _liquidOffset = Vector2.zero(); final Vector2 _circleCenterMoved = Vector2.zero(); final Color3i _liquidColor = Color3i.fromRGBd(0.4, .4, 1.0); final Vector2 renderCenter = Vector2.zero(); final Vector2 renderAxis = Vector2.zero(); final Vector2 _v1 = Vector2.zero(); final Vector2 _v2 = Vector2.zero(); void render( DebugDraw debugDraw, Transform xf, Color3i color, bool wireframe, ) { switch (type) { case ShapeType.circle: { final circle = shape as CircleShape; renderCenter.setFrom(Transform.mulVec2(xf, circle.position)); final radius = circle.radius; xf.q.getXAxis(out: renderAxis); if (userData != null && userData == liquidFlag) { _liquidOffset.setFrom(body.linearVelocity); final linVelLength = body.linearVelocity.length; if (_averageLinearVel == -1) { _averageLinearVel = linVelLength; } else { _averageLinearVel = .98 * _averageLinearVel + .02 * linVelLength; } _liquidOffset.scale(_liquidLength / _averageLinearVel / 2); _circleCenterMoved ..setFrom(renderCenter) ..add(_liquidOffset); renderCenter.sub(_liquidOffset); debugDraw.drawSegment( renderCenter, _circleCenterMoved, _liquidColor, ); return; } if (wireframe) { debugDraw.drawCircleAxis(renderCenter, radius, renderAxis, color); } else { debugDraw.drawSolidCircle(renderCenter, radius, color); } } break; case ShapeType.polygon: { final poly = shape as PolygonShape; assert(poly.vertices.length <= settings.maxPolygonVertices); final vertices = poly.vertices .map( (vertex) => Transform.mulVec2(xf, vertex), ) .toList(); if (wireframe) { debugDraw.drawPolygon(vertices, color); } else { debugDraw.drawSolidPolygon(vertices, color); } } break; case ShapeType.edge: { final edge = shape as EdgeShape; _v1.setFrom(Transform.mulVec2(xf, edge.vertex1)); _v2.setFrom(Transform.mulVec2(xf, edge.vertex2)); debugDraw.drawSegment(_v1, _v2, color); } break; case ShapeType.chain: { final chain = shape as ChainShape; final count = chain.vertexCount; final vertices = chain.vertices; _v1.setFrom(Transform.mulVec2(xf, vertices[0])); for (var i = 1; i < count; ++i) { _v2.setFrom(Transform.mulVec2(xf, vertices[i])); debugDraw.drawSegment(_v1, _v2, color); debugDraw.drawCircle(_v1, 0.05, color); _v1.setFrom(_v2); } } break; default: break; } } }
forge2d/packages/forge2d/lib/src/dynamics/fixture.dart/0
{'file_path': 'forge2d/packages/forge2d/lib/src/dynamics/fixture.dart', 'repo_id': 'forge2d', 'token_count': 3956}
import 'package:forge2d/forge2d.dart'; //Point-to-point constraint //Cdot = v2 - v1 // = v2 + cross(w2, r2) - v1 - cross(w1, r1) //J = [-I -r1_skew I r2_skew ] //Identity used: //w k % (rx i + ry j) = w * (-ry i + rx j) //Angle constraint //Cdot = w2 - w1 //J = [0 0 -1 0 0 1] //K = invI1 + invI2 /// A motor joint is used to control the relative motion between two bodies. /// A typical usage is to control the movement of a dynamic body with respect to /// the ground. class MotorJoint extends Joint { // Solver shared final Vector2 _linearOffset = Vector2.zero(); double _angularOffset = 0.0; final Vector2 _linearImpulse = Vector2.zero(); double _angularImpulse = 0.0; double _maxForce = 0.0; double _maxTorque = 0.0; double _correctionFactor = 0.0; // Solver temp int _indexA = 0; int _indexB = 0; final Vector2 _rA = Vector2.zero(); final Vector2 _rB = Vector2.zero(); final Vector2 _localCenterA = Vector2.zero(); final Vector2 _localCenterB = Vector2.zero(); final Vector2 _linearError = Vector2.zero(); double _angularError = 0.0; double _invMassA = 0.0; double _invMassB = 0.0; double _invIA = 0.0; double _invIB = 0.0; final Matrix2 _linearMass = Matrix2.zero(); double _angularMass = 0.0; MotorJoint(MotorJointDef def) : super(def) { _linearOffset.setFrom(def.linearOffset); _angularOffset = def.angularOffset; _angularImpulse = 0.0; _maxForce = def.maxForce; _maxTorque = def.maxTorque; _correctionFactor = def.correctionFactor; } @override Vector2 get anchorA { return Vector2.copy(bodyA.position); } @override Vector2 get anchorB { return Vector2.copy(bodyB.position); } @override Vector2 reactionForce(double invDt) { return Vector2.copy(_linearImpulse)..scale(invDt); } @override double reactionTorque(double invDt) { return _angularImpulse * invDt; } /// Set the target linear offset, in frame A, in meters. void setLinearOffset(Vector2 linearOffset) { if (linearOffset.x != _linearOffset.x || linearOffset.y != _linearOffset.y) { bodyA.setAwake(true); bodyB.setAwake(true); _linearOffset.setFrom(linearOffset); } } /// Get the target linear offset, in frame A, in meters. void getLinearOffsetOut(Vector2 out) { out.setFrom(_linearOffset); } /// Get the target linear offset, in frame A, in meters. Do not modify. Vector2 getLinearOffset() { return _linearOffset; } /// Set the target angular offset, in radians. void setAngularOffset(double angularOffset) { if (angularOffset != _angularOffset) { bodyA.setAwake(true); bodyB.setAwake(true); _angularOffset = angularOffset; } } double getAngularOffset() { return _angularOffset; } /// Set the maximum friction force in N. void setMaxForce(double force) { assert(force >= 0.0); _maxForce = force; } /// Get the maximum friction force in N. double getMaxForce() { return _maxForce; } /// Set the maximum friction torque in N*m. void setMaxTorque(double torque) { assert(torque >= 0.0); _maxTorque = torque; } /// Get the maximum friction torque in N*m. double getMaxTorque() { return _maxTorque; } @override void initVelocityConstraints(SolverData data) { _indexA = bodyA.islandIndex; _indexB = bodyB.islandIndex; _localCenterA.setFrom(bodyA.sweep.localCenter); _localCenterB.setFrom(bodyB.sweep.localCenter); _invMassA = bodyA.inverseMass; _invMassB = bodyB.inverseMass; _invIA = bodyA.inverseInertia; _invIB = bodyB.inverseInertia; final cA = data.positions[_indexA].c; final aA = data.positions[_indexA].a; final vA = data.velocities[_indexA].v; var wA = data.velocities[_indexA].w; final cB = data.positions[_indexB].c; final aB = data.positions[_indexB].a; final vB = data.velocities[_indexB].v; var wB = data.velocities[_indexB].w; final qA = Rot(); final qB = Rot(); final temp = Vector2.zero(); final k = Matrix2.zero(); qA.setAngle(aA); qB.setAngle(aB); // Compute the effective mass matrix. // _rA = b2Mul(qA, -_localCenterA); // _rB = b2Mul(qB, -_localCenterB); _rA.x = qA.cos * -_localCenterA.x - qA.sin * -_localCenterA.y; _rA.y = qA.sin * -_localCenterA.x + qA.cos * -_localCenterA.y; _rB.x = qB.cos * -_localCenterB.x - qB.sin * -_localCenterB.y; _rB.y = qB.sin * -_localCenterB.x + qB.cos * -_localCenterB.y; // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] final mA = _invMassA; final mB = _invMassB; final iA = _invIA; final iB = _invIB; final a11 = mA + mB + iA * _rA.y * _rA.y + iB * _rB.y * _rB.y; final a21 = -iA * _rA.x * _rA.y - iB * _rB.x * _rB.y; final a12 = a21; final a22 = mA + mB + iA * _rA.x * _rA.x + iB * _rB.x * _rB.x; k.setValues(a11, a21, a12, a22); _linearMass.setFrom(k); _linearMass.invert(); _angularMass = iA + iB; if (_angularMass > 0.0) { _angularMass = 1.0 / _angularMass; } temp.setFrom(Rot.mulVec2(qA, _linearOffset)); _linearError.x = cB.x + _rB.x - cA.x - _rA.x - temp.x; _linearError.y = cB.y + _rB.y - cA.y - _rA.y - temp.y; _angularError = aB - aA - _angularOffset; if (data.step.warmStarting) { // Scale impulses to support a variable time step. _linearImpulse.x *= data.step.dtRatio; _linearImpulse.y *= data.step.dtRatio; _angularImpulse *= data.step.dtRatio; final P = _linearImpulse; vA.x -= mA * P.x; vA.y -= mA * P.y; wA -= iA * (_rA.x * P.y - _rA.y * P.x + _angularImpulse); vB.x += mB * P.x; vB.y += mB * P.y; wB += iB * (_rB.x * P.y - _rB.y * P.x + _angularImpulse); } else { _linearImpulse.setZero(); _angularImpulse = 0.0; } data.velocities[_indexA].w = wA; data.velocities[_indexB].w = wB; } @override void solveVelocityConstraints(SolverData data) { final vA = data.velocities[_indexA].v; var wA = data.velocities[_indexA].w; final vB = data.velocities[_indexB].v; var wB = data.velocities[_indexB].w; final mA = _invMassA; final mB = _invMassB; final iA = _invIA; final iB = _invIB; final dt = data.step.dt; final invDt = data.step.invDt; final temp = Vector2.zero(); // Solve angular friction { final cDot = wB - wA + invDt * _correctionFactor * _angularError; var impulse = -_angularMass * cDot; final oldImpulse = _angularImpulse; final maxImpulse = dt * _maxTorque; _angularImpulse = (_angularImpulse + impulse).clamp(-maxImpulse, maxImpulse); impulse = _angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } final cDot = Vector2.zero(); // Solve linear friction { // Cdot = vB + b2Cross(wB, _rB) - vA - b2Cross(wA, _rA) + inv_h * // _correctionFactor * _linearError; cDot.x = vB.x + -wB * _rB.y - vA.x - -wA * _rA.y + invDt * _correctionFactor * _linearError.x; cDot.y = vB.y + wB * _rB.x - vA.y - wA * _rA.x + invDt * _correctionFactor * _linearError.y; final impulse = temp; _linearMass.transformed(cDot, impulse); impulse.negate(); final oldImpulse = Vector2.zero(); oldImpulse.setFrom(_linearImpulse); _linearImpulse.add(impulse); final maxImpulse = dt * _maxForce; if (_linearImpulse.length2 > maxImpulse * maxImpulse) { _linearImpulse.normalize(); _linearImpulse.scale(maxImpulse); } impulse.x = _linearImpulse.x - oldImpulse.x; impulse.y = _linearImpulse.y - oldImpulse.y; vA.x -= mA * impulse.x; vA.y -= mA * impulse.y; wA -= iA * (_rA.x * impulse.y - _rA.y * impulse.x); vB.x += mB * impulse.x; vB.y += mB * impulse.y; wB += iB * (_rB.x * impulse.y - _rB.y * impulse.x); } // data.velocities[_indexA].v.set(vA); data.velocities[_indexA].w = wA; // data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; } @override bool solvePositionConstraints(SolverData data) { return true; } @override void render(DebugDraw debugDraw) { super.render(debugDraw); final xf1 = bodyA.transform; final xf2 = bodyB.transform; final x1 = xf1.p; final x2 = xf2.p; final p1 = anchorA; final p2 = anchorB; debugDraw.drawSegment(x1, p1, renderColor); debugDraw.drawSegment(p1, p2, renderColor); debugDraw.drawSegment(x2, p2, renderColor); } }
forge2d/packages/forge2d/lib/src/dynamics/joints/motor_joint.dart/0
{'file_path': 'forge2d/packages/forge2d/lib/src/dynamics/joints/motor_joint.dart', 'repo_id': 'forge2d', 'token_count': 4051}
import 'dart:math' as math; class ProfileEntry { static const int _longAvgNums = 20; static const double _longFraction = 1.0 / _longAvgNums; static const int _shortAvgNums = 5; static const double _shortFraction = 1.0 / _shortAvgNums; double longAvg = 0.0; double shortAvg = 0.0; double min = double.maxFinite; double max = -double.maxFinite; double _accum = 0.0; void record(double value) { longAvg = longAvg * (1 - _longFraction) + value * _longFraction; shortAvg = shortAvg * (1 - _shortFraction) + value * _shortFraction; min = math.min(value, min); max = math.max(value, max); } void startAccum() { _accum = 0.0; } void accum(double value) { _accum += value; } void endAccum() { record(_accum); } @override String toString() { return '$shortAvg ($longAvg) [$min,$max]'; } } class Profile { final ProfileEntry step = ProfileEntry(); final ProfileEntry stepInit = ProfileEntry(); final ProfileEntry collide = ProfileEntry(); final ProfileEntry solveParticleSystem = ProfileEntry(); final ProfileEntry solve = ProfileEntry(); final ProfileEntry solveInit = ProfileEntry(); final ProfileEntry solveVelocity = ProfileEntry(); final ProfileEntry solvePosition = ProfileEntry(); final ProfileEntry broadphase = ProfileEntry(); final ProfileEntry solveTOI = ProfileEntry(); void toDebugStrings(List<String> strings) { strings.add('Profile:'); strings.add(' step: $step'); strings.add(' init: $stepInit'); strings.add(' collide: $collide'); strings.add(' particles: $solveParticleSystem'); strings.add(' solve: $solve'); strings.add(' solveInit: $solveInit'); strings.add(' solveVelocity: $solveVelocity'); strings.add(' solvePosition: $solvePosition'); strings.add(' broadphase: $broadphase'); strings.add(' solveTOI: $solveTOI'); } }
forge2d/packages/forge2d/lib/src/dynamics/profile.dart/0
{'file_path': 'forge2d/packages/forge2d/lib/src/dynamics/profile.dart', 'repo_id': 'forge2d', 'token_count': 647}
import 'package:forge2d/forge2d.dart'; import 'package:test/test.dart'; void main() { group('MouseJointDef', () { test('can be instantiated', () { expect(MouseJointDef(), isA<MouseJointDef>()); }); }); }
forge2d/packages/forge2d/test/dynamics/joints/mouse_joint_def_test.dart/0
{'file_path': 'forge2d/packages/forge2d/test/dynamics/joints/mouse_joint_def_test.dart', 'repo_id': 'forge2d', 'token_count': 90}
import 'package:forge2d/forge2d.dart'; import 'package:mocktail/mocktail.dart'; class MockDebugDraw extends Mock implements DebugDraw {}
forge2d/packages/forge2d/test/helpers/mocks.dart/0
{'file_path': 'forge2d/packages/forge2d/test/helpers/mocks.dart', 'repo_id': 'forge2d', 'token_count': 44}
name: Update sponsors in README on: workflow_dispatch: schedule: - cron: "0 0 * * *" push: branches: [master] jobs: update-sponsors: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set node uses: actions/setup-node@v4 with: node-version: 16.x - run: npm install yarn --global - run: yarn - name: Update sponsors run: npm run build env: SPONSORKIT_GITHUB_TOKEN: ${{ secrets.SPONSORS_TOKEN }} SPONSORKIT_GITHUB_LOGIN: rrousselGit SPONSORKIT_DIR: "./sponsorkit" - run: ls - run: ls sponsorkit - name: Commit uses: EndBug/add-and-commit@v9 with: message: "chore: update sponsors.svg" add: "./sponsorkit/sponsors.*" default_author: github_actions env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
freezed/.github/workflows/sponsor.yml/0
{'file_path': 'freezed/.github/workflows/sponsor.yml', 'repo_id': 'freezed', 'token_count': 456}
import 'package:flutter/material.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'time_slot.freezed.dart'; /// This is class has been added to address the issue described in /// https://github.com/rrousselGit/freezed/issues/220 @freezed class TimeSlot with _$TimeSlot { factory TimeSlot({ TimeOfDay? start, TimeOfDay? end, }) = _TimeSlot; }
freezed/packages/freezed/example/lib/time_slot.dart/0
{'file_path': 'freezed/packages/freezed/example/lib/time_slot.dart', 'repo_id': 'freezed', 'token_count': 132}
import 'package:analyzer/dart/element/element.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:source_gen/source_gen.dart'; import '../models.dart'; import 'parameter_template.dart'; List<String> parseDecorators(List<ElementAnnotation> metadata) { return [ for (final meta in metadata) if (!meta.isRequired && !meta.isDefault) meta.toSource(), ]; } String wrapClassField(String name) { return name.contains(r'$') ? '\${$name}' : '\$$name'; } extension FreezedElementAnnotation on ElementAnnotation { /// if the element is decorated with `@Default(value)` bool get isDefault { return const TypeChecker.fromRuntime(Default) .isExactlyType(computeConstantValue()!.type!); } /// if the element is decorated with `@With<Type>` bool get isWith { return const TypeChecker.fromRuntime(With) .isExactlyType(computeConstantValue()!.type!); } /// if the element is decorated with `@Implements<Type>` bool get isImplements { return const TypeChecker.fromRuntime(Implements) .isExactlyType(computeConstantValue()!.type!); } } String whenPrototype(List<ConstructorDetails> allConstructors) { return _whenPrototype( allConstructors, areCallbacksRequired: true, isReturnTypeNullable: false, name: 'when', ); } String whenOrNullPrototype(List<ConstructorDetails> allConstructors) { return _whenPrototype( allConstructors, areCallbacksRequired: false, isReturnTypeNullable: true, name: 'whenOrNull', ); } String maybeWhenPrototype(List<ConstructorDetails> allConstructors) { return _whenPrototype( allConstructors, areCallbacksRequired: false, isReturnTypeNullable: false, name: 'maybeWhen', ); } String mapPrototype( List<ConstructorDetails> allConstructors, GenericsParameterTemplate genericParameters, ) { return _mapPrototype( allConstructors, genericParameters, areCallbacksRequired: true, isReturnTypeNullable: false, name: 'map', ); } String mapOrNullPrototype( List<ConstructorDetails> allConstructors, GenericsParameterTemplate genericParameters, ) { return _mapPrototype( allConstructors, genericParameters, areCallbacksRequired: false, isReturnTypeNullable: true, name: 'mapOrNull', ); } String maybeMapPrototype( List<ConstructorDetails> allConstructors, GenericsParameterTemplate genericParameters, ) { return _mapPrototype( allConstructors, genericParameters, areCallbacksRequired: false, isReturnTypeNullable: false, name: 'maybeMap', ); } String _mapPrototype( List<ConstructorDetails> allConstructors, GenericsParameterTemplate genericParameters, { required bool areCallbacksRequired, required bool isReturnTypeNullable, required String name, }) { return _unionPrototype( allConstructors, areCallbacksRequired: areCallbacksRequired, isReturnTypeNullable: isReturnTypeNullable, name: name, ctor2parameters: (constructor) { return ParametersTemplate([ Parameter( name: 'value', type: '${constructor.redirectedName}$genericParameters', isRequired: false, isNullable: false, isFinal: false, isDartList: false, isDartSet: false, isDartMap: false, decorators: const [], defaultValueSource: '', doc: '', // TODO: do we want to support freezed classes that implements MapView/ListView? isPossiblyDartCollection: false, showDefaultValue: false, parameterElement: null, ), ]); }, ); } String _whenPrototype( List<ConstructorDetails> allConstructors, { required bool areCallbacksRequired, required bool isReturnTypeNullable, required String name, }) { return _unionPrototype( allConstructors, areCallbacksRequired: areCallbacksRequired, isReturnTypeNullable: isReturnTypeNullable, name: name, ctor2parameters: (constructor) { return ParametersTemplate([ ...constructor.parameters.requiredPositionalParameters .map((e) => e.copyWith(isFinal: false)), ...constructor.parameters.optionalPositionalParameters .map((e) => e.copyWith( isFinal: false, showDefaultValue: false, )), ...constructor.parameters.namedParameters.map((e) => e.copyWith( isRequired: false, isFinal: false, showDefaultValue: false, )), ]); }, ); } String _unionPrototype( List<ConstructorDetails> allConstructors, { required bool areCallbacksRequired, required bool isReturnTypeNullable, required String name, required ParametersTemplate Function(ConstructorDetails) ctor2parameters, }) { final returnType = isReturnTypeNullable ? 'TResult?' : 'TResult'; final buffer = StringBuffer( '@optionalTypeArgs $returnType $name<TResult extends Object?>('); final parameters = <CallbackParameter>[]; for (final constructor in allConstructors) { var template = CallbackParameter( name: constructorNameToCallbackName(constructor.name), type: returnType, isFinal: false, isDartList: false, isDartMap: false, isDartSet: false, isRequired: !constructor.isDefault && areCallbacksRequired, isNullable: !areCallbacksRequired, parameters: ctor2parameters(constructor), decorators: const [], defaultValueSource: '', doc: '', isPossiblyDartCollection: false, parameterElement: null, ); if (constructor.isDefault) { buffer ..write(template) ..write(','); } else { parameters.add(template); } } final hasOrElse = !areCallbacksRequired && !isReturnTypeNullable; if (parameters.isNotEmpty || hasOrElse) { buffer.write('{'); if (parameters.isNotEmpty) { buffer ..writeAll(parameters, ',') ..write(','); } if (hasOrElse) { buffer.write('required $returnType orElse(),'); } buffer.write('}'); } buffer.write(')'); return buffer.toString(); } bool isDefaultConstructor(ConstructorElement constructor) { return constructor.name.isEmpty; } String constructorNameToCallbackName(String constructorName) { return constructorName.isEmpty ? '\$default' : constructorName; } String toJsonParameters( GenericsParameterTemplate parameters, bool genericArgumentFactories, ) { if (!genericArgumentFactories) { return ''; } return '${parameters.typeParameters.map((t) => 'Object? Function($t) toJson$t').join(',')}'; } String toJsonArguments( GenericsParameterTemplate parameters, bool genericArgumentFactories, ) { if (!genericArgumentFactories) { return ''; } return '${parameters.typeParameters.map((t) => 'toJson$t').join(',')}'; } String fromJsonParameters( GenericsParameterTemplate parameters, bool genericArgumentFactories, ) { if (!genericArgumentFactories) { return ''; } return ',${parameters.typeParameters.map((t) => '$t Function(Object?) fromJson$t').join(',')}'; } String fromJsonArguments( GenericsParameterTemplate parameters, bool genericArgumentFactories, ) { if (!genericArgumentFactories) { return ''; } return ',${parameters.typeParameters.map((t) => 'fromJson$t').join(',')}'; }
freezed/packages/freezed/lib/src/templates/prototypes.dart/0
{'file_path': 'freezed/packages/freezed/lib/src/templates/prototypes.dart', 'repo_id': 'freezed', 'token_count': 2716}
import 'package:test/test.dart'; import 'integration/equal.dart'; void main() { test('Simple', () { expect( Simple(42), Simple(42), ); }); test('ListEqual', () { expect( ListEqual([1]), ListEqual([1]), ); }); test('MapEqual', () { expect( MapEqual({1: 1}), MapEqual({1: 1}), ); }); test('SetEqual', () { expect( SetEqual({1}), SetEqual({1}), ); }); test('IterableEqual', () { expect( IterableEqual([1]), IterableEqual([1]), ); }); test('ListObjectEqual', () { expect( ListObjectEqual([1]), ListObjectEqual([1.0]), ); expect( ListObjectEqual([ [1] ]), ListObjectEqual([ [1] ]), ); }); test('ListDynamicEqual', () { expect( ListDynamicEqual(<dynamic>[1]), ListDynamicEqual(<dynamic>[1.0]), ); expect( ListDynamicEqual(<dynamic>[ [1] ]), ListDynamicEqual(<dynamic>[ [1] ]), ); }); test('ObjectEqual', () { expect( ObjectEqual(1), ObjectEqual(1), ); expect( ObjectEqual([1]), ObjectEqual([1]), ); expect( ObjectEqual([ [1] ]), ObjectEqual([ [1] ]), ); }); test('DynamicEqual', () { expect( DynamicEqual(1), DynamicEqual(1), ); expect( DynamicEqual([1]), DynamicEqual([1]), ); expect( DynamicEqual([ [1] ]), DynamicEqual([ [1] ]), ); }); test('Generic', () { expect( Generic(42), Generic(42), ); expect( Generic([1]), Generic([1]), ); expect( Generic([ [1] ]), Generic([ [1] ]), ); }); test('GenericObject', () { expect( GenericObject(42), GenericObject(42), ); expect( GenericObject([1]), GenericObject([1]), ); expect( GenericObject([ [1] ]), GenericObject([ [1] ]), ); expect( GenericObject<Object>(42), isNot(GenericObject<num>(42)), ); expect( GenericObject<num>(42), isNot(GenericObject<Object>(42)), ); }); test('GenericIterable', () { expect( GenericIterable([1]), GenericIterable([1]), ); }); test('ObjectWithOtherProperty', () { expect(ObjectWithOtherProperty(const [2, 3]), ObjectWithOtherProperty(const [2, 3])); expect(ObjectWithOtherProperty(const [2, 3]), isNot(ObjectWithOtherProperty(const [2, 4]))); expect(ObjectWithOtherProperty([1, 2]), ObjectWithOtherProperty([1, 2])); expect( ObjectWithOtherProperty([1, 2]), isNot(ObjectWithOtherProperty([1]))); }); }
freezed/packages/freezed/test/equal_test.dart/0
{'file_path': 'freezed/packages/freezed/test/equal_test.dart', 'repo_id': 'freezed', 'token_count': 1408}
export 'concrete.dart';
freezed/packages/freezed/test/integration/export_empty.dart/0
{'file_path': 'freezed/packages/freezed/test/integration/export_empty.dart', 'repo_id': 'freezed', 'token_count': 9}
// ignore_for_file: unnecessary_question_mark import 'dart:async'; import 'dart:collection'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'single_class_constructor.freezed.dart'; @freezed class Dynamic with _$Dynamic { factory Dynamic({ dynamic foo, dynamic? bar, }) = DynamicFirst; } class CustomMap<A, B> extends MapBase<A, B> { CustomMap(this._source); final Map<A, B> _source; @override B? operator [](Object? key) => _source[key]; @override void operator []=(A key, B value) => _source[key] = value; @override void clear() => _source.clear(); @override Iterable<A> get keys => _source.keys; @override B? remove(Object? key) => _source.remove(key); } class CustomSet<T> extends SetBase<T> { CustomSet(this._source); final Set<T> _source; @override bool add(T value) => _source.add(value); @override bool contains(Object? element) => _source.contains(element); @override Iterator<T> get iterator => _source.iterator; @override int get length => _source.length; @override T? lookup(Object? element) => _source.lookup(element); @override bool remove(Object? value) => _source.remove(value); @override Set<T> toSet() => _source.toSet(); } class CustomList<T> extends ListBase<T?> { CustomList(this._source); final List<T?> _source; @override int get length => _source.length; @override set length(int length) => _source.length = length; @override T? operator [](int index) => _source[index]; @override void operator []=(int index, T? value) => _source[index] = value; } @freezed class CustomListEqual with _$CustomListEqual { factory CustomListEqual(CustomList<int> list) = CustomListEqualFirst; } @Freezed(makeCollectionsUnmodifiable: false) class ListEqual with _$ListEqual { factory ListEqual(List<int> list) = ListEqualFirst; } @freezed class UnmodifiableListEqual with _$UnmodifiableListEqual { factory UnmodifiableListEqual(List<int> list) = UnmodifiableListEqualFirst; } @freezed class NullUnmodifiableListEqual with _$NullUnmodifiableListEqual { factory NullUnmodifiableListEqual(List<int>? list) = NullUnmodifiableListEqualFirst; } @freezed class CustomSetEqual with _$CustomSetEqual { factory CustomSetEqual(CustomSet<int> dartSet) = CustomSetEqualFirst; } @Freezed(makeCollectionsUnmodifiable: false) class SetEqual with _$SetEqual { factory SetEqual(Set<int> dartSet) = SetEqualFirst; } @freezed class UnmodifiableSetEqual with _$UnmodifiableSetEqual { factory UnmodifiableSetEqual(Set<int> dartSet) = UnmodifiableSetEqualFirst; } @freezed class NullUnmodifiableSetEqual with _$NullUnmodifiableSetEqual { factory NullUnmodifiableSetEqual(Set<int>? dartSet) = NullUnmodifiableSetEqualFirst; } @freezed class CustomMapEqual with _$CustomMapEqual { factory CustomMapEqual(CustomMap<String, Object?> map) = CustomMapEqualFirst; } @Freezed(makeCollectionsUnmodifiable: false) class MapEqual with _$MapEqual { factory MapEqual(Map<String, Object?> map) = MapEqualFirst; } @freezed class UnmodifiableMapEqual with _$UnmodifiableMapEqual { factory UnmodifiableMapEqual(Map<String, Object?> map) = UnmodifiableMapEqualFirst; } @freezed class NullUnmodifiableMapEqual with _$NullUnmodifiableMapEqual { factory NullUnmodifiableMapEqual(Map<String, Object?>? map) = NullUnmodifiableMapEqualFirst; } mixin Some<T> { T? get value => throw UnimplementedError(); } mixin Complex<T> { T? get value => throw UnimplementedError(); } const withAlias = With<Some<Complex<Type>>>(); @freezed class WithAlias with _$WithAlias { @withAlias factory WithAlias.first() = WithAliasFirst; } const implementsAlias = Implements<Some<Complex<Type>>>(); @freezed class ImplementsAlias with _$ImplementsAlias { @implementsAlias factory ImplementsAlias.first({ Complex<Type>? value, }) = ImplementsAliasFirst; } abstract class DataEvent {} @freezed class Large with _$Large { factory Large({ @Default(0) int? a0, @Default(1) int? a1, @Default(2) int? a2, @Default(3) int? a3, @Default(4) int? a4, @Default(5) int? a5, @Default(6) int? a6, @Default(7) int? a7, @Default(8) int? a8, @Default(9) int? a9, @Default(10) int? a10, @Default(11) int? a11, @Default(12) int? a12, @Default(13) int? a13, @Default(14) int? a14, @Default(15) int? a15, @Default(16) int? a16, @Default(17) int? a17, @Default(18) int? a18, @Default(19) int? a19, @Default(20) int? a20, @Default(21) int? a21, @Default(22) int? a22, @Default(23) int? a23, @Default(24) int? a24, @Default(25) int? a25, @Default(26) int? a26, @Default(27) int? a27, @Default(28) int? a28, @Default(29) int? a29, }) = _Large; } // Regression test for https://github.com/rrousselGit/freezed/issues/131 @freezed class Regression131 extends DataEvent with _$Regression131 { factory Regression131(String versionName) = _Regression131; } @freezed class UnimplementedGetter with _$UnimplementedGetter { factory UnimplementedGetter(int value) = _UnimplementedGetter; @override int get value; } @freezed class Assertion with _$Assertion { @Assert('a > 0') @Assert('b > a') factory Assertion(int a, int b) = _Assertion; } // Regression test for https://github.com/rrousselGit/freezed/issues/326 @freezed class Doc326 with _$Doc326 { /// Hello world factory Doc326({ int? named, }) = _Doc326; } // Regression test for https://github.com/rrousselGit/freezed/issues/317 @freezed class Doc317 with _$Doc317 { factory Doc317({ /// ) int? named, }) = _Doc317; } @freezed class Doc with _$Doc { factory Doc( /// Multi /// line /// positional int positional, { /// Single line named int? named, // Simple int? simple, }) = _Doc; } /// Regression test for https://github.com/rrousselGit/freezed/issues/213 @freezed class Product with _$Product { const factory Product({ String? name, Product? parent, }) = _ProductDataClass; } @freezed class Test with _$Test { const factory Test.something(Completer<void> completer) = TestSomething; } @freezed class Private with _$Private { // This is the (private) Freezed constructor const factory Private._internal( Iterable<String> items, ) = _Private; } @freezed class MyClass with _$MyClass { const factory MyClass({String? a, int? b}) = WhateverIWant; } @freezed class MixedParam with _$MixedParam { const factory MixedParam(String a, {int? b}) = WhateverMixedParam; } @freezed class PositionalMixedParam with _$PositionalMixedParam { const factory PositionalMixedParam(String a, [int? b]) = WhateverPositionalMixedParam; } @freezed class Required with _$Required { const factory Required({required String? a}) = WhateverRequired; } @freezed class Empty with _$Empty { const factory Empty() = WhateverEmpty; } @freezed class Empty2 with _$Empty2 { const factory Empty2() = WhateverEmpty2; } @freezed class SingleNamedCtor with _$SingleNamedCtor { const factory SingleNamedCtor.named(int a) = WhateverSingleNamedCtor; } @freezed class Generic<T> with _$Generic<T> { const factory Generic(T value) = A<T>; } @freezed class Example with _$Example { const factory Example(String a, {int? b}) = Example0; factory Example.fixed() { return const Example('a', b: 42); } } @freezed class NoConst with _$NoConst { factory NoConst() = NoConstImpl; } // Regression test for https://github.com/rrousselGit/freezed/issues/40 @freezed class SecondState with _$SecondState { const factory SecondState({ String? dateTime, String? uuid, }) = _SecondState; } // Regression test for https://github.com/rrousselGit/freezed/issues/44 @freezed class Static with _$Static { const factory Static() = _Static; static int? staticVariable; static int get staticGetter => 0; static int staticMethod() => 0; } @freezed class Late with _$Late { Late._(); factory Late(int value) = _Late; late final container = LateContainer(value); } class LateContainer { LateContainer(this.value); final int value; @override String toString() { return 'Container(value: $value)'; } } @freezed class AllProperties with _$AllProperties { AllProperties._(); factory AllProperties(int value) = _AllProperties; int get a => 1; late final b = 2; final c = 3; } @freezed class Late2 with _$Late2 { Late2._(); factory Late2(int? Function() cb) = _Late2; late final int? first = cb(); } @freezed class ComplexLate with _$ComplexLate { ComplexLate._(); factory ComplexLate(List<int> values) = _ComplexLate; late final List<int> odd = values.where((value) { if (value.isOdd) return true; else return false; }).toList(); } @freezed class IntDefault with _$IntDefault { factory IntDefault([@Default(42) int value]) = _IntDefault; } @freezed class StringDefault with _$StringDefault { factory StringDefault([@Default('42') String value]) = _StringDefault; } @freezed class SpecialStringDefault with _$SpecialStringDefault { factory SpecialStringDefault([@Default('(1)[2]{3}') String value]) = _SpecialStringDefault; } /// Adds `const` to default non-literral values @freezed class DefaultNonLitteralConst with _$DefaultNonLitteralConst { factory DefaultNonLitteralConst({ @Default(Object()) Object listObject, }) = _DefaultNonLitteralConst; } /// Does not add `const` to non-literral values if already present @freezed class DefaultNonLitteralAlreadyConst with _$DefaultNonLitteralAlreadyConst { factory DefaultNonLitteralAlreadyConst({ @Default( // ignore: unnecessary_const const Object(), ) Object listObject, }) = _DefaultNonLitteralAlreadyConst; } @freezed class DoubleDefault with _$DoubleDefault { factory DoubleDefault([@Default(42.0) double value]) = _DoubleDefault; } @freezed class TypeDefault with _$TypeDefault { factory TypeDefault([@Default(TypeDefault) Type value]) = _TypeDefault; } @freezed class ListDefault with _$ListDefault { factory ListDefault([@Default(<int>[42]) List<int> value]) = _ListDefault; } @freezed class SetDefault with _$SetDefault { factory SetDefault([@Default(<int>{42}) Set<int> value]) = _SetDefault; } @freezed class MapDefault with _$MapDefault { factory MapDefault([@Default(<int, int>{42: 42}) Map<int, int> value]) = _MapDefault; } @freezed class BoolDefault with _$BoolDefault { factory BoolDefault([@Default(false) bool value]) = _BoolDefault; } @freezed class NullDefault with _$NullDefault { factory NullDefault([@Default(null) bool? value]) = _NullDefault; } @freezed class ExplicitConstDefault with _$ExplicitConstDefault { factory ExplicitConstDefault( //ignore: unnecessary_const [@Default(const <Object>[]) List<Object> value]) = _ExplicitConstDefault; } @freezed class StaticConstDefault with _$StaticConstDefault { factory StaticConstDefault([@Default(Duration.zero) Duration value]) = _StaticConstDefault; } enum _Enum { a } @freezed class EnumDefault with _$EnumDefault { factory EnumDefault([@Default(_Enum.a) _Enum value]) = _EnumDefault; }
freezed/packages/freezed/test/integration/single_class_constructor.dart/0
{'file_path': 'freezed/packages/freezed/test/integration/single_class_constructor.dart', 'repo_id': 'freezed', 'token_count': 4000}
// ignore_for_file: prefer_const_constructors, omit_local_variable_types import 'package:test/test.dart'; import 'integration/special_class_name.dart'; Future<void> main() async { test('toString will properly handle dollar signs', () { final value = Class$With$Special$Name(a: 'a', b: 1); expect( value.toString(), r'Class$With$Special$Name(a: a, b: 1)', ); }); }
freezed/packages/freezed/test/special_class_name_test.dart/0
{'file_path': 'freezed/packages/freezed/test/special_class_name_test.dart', 'repo_id': 'freezed', 'token_count': 150}
dependency_overrides: freezed_annotation: path: ../freezed_annotation
freezed/packages/freezed_lint/pubspec_overrides.yaml/0
{'file_path': 'freezed/packages/freezed_lint/pubspec_overrides.yaml', 'repo_id': 'freezed', 'token_count': 29}
part of 'authentication_bloc.dart'; abstract class AuthenticationEvent extends Equatable { @override List<Object> get props => []; @override bool get stringify => true; } class AuthenticationStatusChanged extends AuthenticationEvent { AuthenticationStatusChanged(this.authenticationStatus); final UserAuthenticationStatus authenticationStatus; @override List<Object> get props => [authenticationStatus]; } class LoggedOut extends AuthenticationEvent {}
fresh/packages/fresh_dio/example/lib/authentication/bloc/authentication_event.dart/0
{'file_path': 'fresh/packages/fresh_dio/example/lib/authentication/bloc/authentication_event.dart', 'repo_id': 'fresh', 'token_count': 117}
export 'photos_response.dart';
fresh/packages/fresh_dio/example/packages/jsonplaceholder_client/lib/src/models/models.dart/0
{'file_path': 'fresh/packages/fresh_dio/example/packages/jsonplaceholder_client/lib/src/models/models.dart', 'repo_id': 'fresh', 'token_count': 10}
name: fresh_graphql_example description: An example of how to use package:fresh_graphql version: 0.1.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: fresh_graphql: path: ../ graphql: ^5.1.3
fresh/packages/fresh_graphql/example/pubspec.yaml/0
{'file_path': 'fresh/packages/fresh_graphql/example/pubspec.yaml', 'repo_id': 'fresh', 'token_count': 96}
analyzer: exclude: - "*.g.dart" strong-mode: implicit-casts: false implicit-dynamic: false errors: import_of_legacy_library_into_null_safe: ignore linter: rules: - annotate_overrides - avoid_empty_else - avoid_function_literals_in_foreach_calls - avoid_init_to_null - avoid_null_checks_in_equality_operators - avoid_relative_lib_imports - avoid_renaming_method_parameters - avoid_return_types_on_setters - avoid_types_as_parameter_names - avoid_unused_constructor_parameters - await_only_futures - camel_case_types - cancel_subscriptions - cascade_invocations - comment_references - constant_identifier_names - control_flow_in_finally - directives_ordering - empty_catches - empty_constructor_bodies - empty_statements - hash_and_equals - implementation_imports - library_names - library_prefixes - no_adjacent_strings_in_list - no_duplicate_case_values - non_constant_identifier_names - null_closures - omit_local_variable_types - only_throw_errors - overridden_fields - package_api_docs - package_names - package_prefixed_library_names - prefer_adjacent_string_concatenation - prefer_collection_literals - prefer_conditional_assignment - prefer_const_constructors - prefer_contains - prefer_final_fields - prefer_initializing_formals - prefer_interpolation_to_compose_strings - prefer_is_empty - prefer_is_not_empty - prefer_single_quotes - prefer_typing_uninitialized_variables - recursive_getters - slash_for_doc_comments - test_types_in_equals - throw_in_finally - type_init_formals - unawaited_futures - unnecessary_brace_in_string_interps - unnecessary_const - unnecessary_getters_setters - unnecessary_lambdas - unnecessary_new - unnecessary_null_aware_assignments - unnecessary_statements - unnecessary_this - unrelated_type_equality_checks - use_rethrow_when_possible - valid_regexps
functional_widget/packages/functional_widget/analysis_options.yaml/0
{'file_path': 'functional_widget/packages/functional_widget/analysis_options.yaml', 'repo_id': 'functional_widget', 'token_count': 814}
import 'package:build/build.dart'; import 'package:functional_widget/src/utils.dart'; import 'package:functional_widget_annotation/functional_widget_annotation.dart'; import 'package:test/test.dart'; void main() { group('parseOptions', () { test('fails for anything unknown', () { expect( () => parseBuilderOptions( const BuilderOptions(<String, dynamic>{'foo': 42})), throwsA(const TypeMatcher<ArgumentError>() .having((f) => f.message, 'message', 'Unknown option `foo`: 42')), ); expect( () => parseBuilderOptions( const BuilderOptions(<String, dynamic>{'bar': 'foo'})), throwsA(const TypeMatcher<ArgumentError>() .having((f) => f.message, 'message', 'Unknown option `bar`: foo')), ); }); group('debugFillProperties', () { test('default to null', () { expect( parseBuilderOptions(const BuilderOptions(<String, dynamic>{})) .debugFillProperties, null, ); }); test('throws if not bool', () { expect( () => parseBuilderOptions(const BuilderOptions( <String, dynamic>{'debugFillProperties': 42})), throwsArgumentError, ); }); test('parses valid value', () { expect( parseBuilderOptions(const BuilderOptions( <String, dynamic>{'debugFillProperties': true})) .debugFillProperties, true, ); expect( parseBuilderOptions(const BuilderOptions( <String, dynamic>{'debugFillProperties': false})) .debugFillProperties, false, ); }); }); group('widgetType', () { test('default to stateless', () { expect( parseBuilderOptions(const BuilderOptions(<String, dynamic>{})) .widgetType, FunctionalWidgetType.stateless); }); test('throws if string but not valid', () { expect( () => parseBuilderOptions( const BuilderOptions(<String, dynamic>{'widgetType': 'foo'})), throwsArgumentError, ); }); test('throws if not string', () { expect( () => parseBuilderOptions( const BuilderOptions(<String, dynamic>{'widgetType': 42})), throwsArgumentError, ); }); test('parses valid value', () { expect( parseBuilderOptions( const BuilderOptions(<String, dynamic>{'widgetType': 'hook'})) .widgetType, FunctionalWidgetType.hook, ); expect( parseBuilderOptions(const BuilderOptions( <String, dynamic>{'widgetType': 'stateless'})).widgetType, FunctionalWidgetType.stateless, ); }); }); }); }
functional_widget/packages/functional_widget/test/parse_options_test.dart/0
{'file_path': 'functional_widget/packages/functional_widget/test/parse_options_test.dart', 'repo_id': 'functional_widget', 'token_count': 1319}