code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
import 'package:calculator_3d/utils/calculator_config.dart';
import 'package:calculator_3d/utils/calculator_key_data.dart';
import 'package:calculator_3d/widgets/calculator_view.dart';
import 'package:flame_audio/flame_audio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage>
with SingleTickerProviderStateMixin {
late final AnimationController animationController;
late final Animation<double> scaleAnimation;
final FocusNode keyboardListenerFocusNode = FocusNode();
final tappedKeyTypes = <CalculatorKeyType>{};
bool muted = false;
void _playSound(String assetName) {
if (!muted) {
FlameAudio.play("../$assetName");
}
}
void _onKeyDown(CalculatorKeyType keyType) async {
if (defaultTargetPlatform == TargetPlatform.iOS) {
HapticFeedback.mediumImpact();
}
setState(() {
tappedKeyTypes.add(keyType);
});
_playSound('keyboard_down.wav');
}
void _onKeyUp(CalculatorKeyType keyType) async {
setState(() {
tappedKeyTypes.remove(keyType);
});
_playSound('keyboard_up.wav');
}
KeyEventResult _handleKeyboardEvent(FocusNode node, RawKeyEvent event) {
if (event is RawKeyDownEvent) {
if (event.data.physicalKey == PhysicalKeyboardKey.tab) {
if (animationController.isCompleted) {
animationController.reverse();
} else {
animationController.forward();
}
return KeyEventResult.handled;
}
final logicalKey = event.data.logicalKey;
CalculatorKeyType? calculatorKeyType =
CalculatorKeyType.getFromKey(logicalKey);
if (calculatorKeyType != null && !event.repeat) {
_onKeyDown(calculatorKeyType);
return KeyEventResult.handled;
}
} else if (event is RawKeyUpEvent) {
final logicalKey = event.data.logicalKey;
CalculatorKeyType? calculatorKeyType =
CalculatorKeyType.getFromKey(logicalKey);
if (calculatorKeyType != null) {
_onKeyUp(calculatorKeyType);
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
}
@override
void initState() {
super.initState();
animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 300),
);
}
@override
void dispose() {
animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
FocusScope.of(context).requestFocus(keyboardListenerFocusNode);
Size screenSize = MediaQuery.of(context).size;
double size = screenSize.width > 600 ? 460 : screenSize.width * 0.7;
return Scaffold(
backgroundColor: Colors.blueGrey.shade200,
body: Focus(
focusNode: keyboardListenerFocusNode,
onKey: _handleKeyboardEvent,
child: SingleChildScrollView(
padding: const EdgeInsets.all(50),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
IconButton(
onPressed: () => setState(() => muted = !muted),
icon: Icon(muted ? Icons.volume_off : Icons.volume_up),
),
const SizedBox(width: 20),
IconButton(
onPressed: () {
if (animationController.isCompleted) {
animationController.reverse();
} else {
animationController.forward();
}
},
icon: const Icon(Icons.threed_rotation_rounded),
),
],
),
const SizedBox(height: 50),
Center(
child: CalculatorView(
animationController: animationController,
onKeyDown: _onKeyDown,
onKeyUp: _onKeyUp,
currentTappedKeys: tappedKeyTypes,
config: CalculatorConfig(
calculatorSide: size,
startAt3D: true,
// This can be used to have the calculator scale with the screen
// However the performance is not good and some glitches happen
// calculatorSide: screenSize.width * 0.6,
keysHaveShadow: true,
),
),
),
const SizedBox(height: 70),
Align(
alignment: Alignment.bottomRight,
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: const [
Text(
'@roaakdm',
style: TextStyle(fontSize: 16),
),
SizedBox(height: 5),
Text(
'A 3d-ish/Isometric Calculator built with Flutter 💙',
style: TextStyle(fontSize: 12),
),
Text(
"Inspired by @yoavikadosh's CSS implementation",
style: TextStyle(fontSize: 12),
),
],
),
),
],
),
),
),
);
}
}
| flutter_3d_calculator/lib/home_page.dart/0 | {'file_path': 'flutter_3d_calculator/lib/home_page.dart', 'repo_id': 'flutter_3d_calculator', 'token_count': 2727} |
import 'package:flutter_and_friends/schedule/schedule.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
part 'favorites_state.dart';
class FavoritesCubit extends HydratedCubit<FavoritesState> {
FavoritesCubit() : super(const FavoritesState());
void toggleFavorite(Event event) {
final events = [...state.events];
events.contains(event) ? events.remove(event) : events.add(event);
events.sort((a, b) => a.startTime.compareTo(b.startTime));
emit(state.copyWith(events: events));
}
@override
FavoritesState? fromJson(Map<String, dynamic> json) {
final events = (json['events'] as List)
.map((e) => Event.fromJson(e as Map<String, dynamic>))
.toList();
return FavoritesState(events: events);
}
@override
Map<String, dynamic>? toJson(FavoritesState state) {
return {'events': state.events.map(Event.toJson).toList()};
}
}
| flutter_and_friends/lib/favorites/cubit/favorites_cubit.dart/0 | {'file_path': 'flutter_and_friends/lib/favorites/cubit/favorites_cubit.dart', 'repo_id': 'flutter_and_friends', 'token_count': 332} |
import 'package:hydrated_bloc/hydrated_bloc.dart';
part 'schedule_state.dart';
class ScheduleCubit extends HydratedCubit<ScheduleState> {
ScheduleCubit() : super(ScheduleState.day1);
void toggleTab(int index) => emit(ScheduleState.values[index]);
@override
ScheduleState? fromJson(Map<String, dynamic> json) {
return ScheduleState.values[json['index'] as int];
}
@override
Map<String, dynamic>? toJson(ScheduleState state) => {'index': state.index};
}
| flutter_and_friends/lib/schedule/cubit/schedule_cubit.dart/0 | {'file_path': 'flutter_and_friends/lib/schedule/cubit/schedule_cubit.dart', 'repo_id': 'flutter_and_friends', 'token_count': 162} |
export 'sponsors.dart';
| flutter_and_friends/lib/sponsors/data/data.dart/0 | {'file_path': 'flutter_and_friends/lib/sponsors/data/data.dart', 'repo_id': 'flutter_and_friends', 'token_count': 9} |
export 'widgets/widgets.dart';
| flutter_and_friends/lib/twitter/twitter.dart/0 | {'file_path': 'flutter_and_friends/lib/twitter/twitter.dart', 'repo_id': 'flutter_and_friends', 'token_count': 12} |
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_animations_workshop/colors.dart';
import 'package:flutter_animations_workshop/pickers/2/color_item.dart';
class ColorPicker extends StatefulWidget {
const ColorPicker({super.key});
@override
State<ColorPicker> createState() => _ColorPickerState();
}
class _ColorPickerState extends State<ColorPicker> {
int _selectedColorIndex = 0;
bool _pickerVisible = false;
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextButton(
onPressed: () {
setState(() {
_pickerVisible = !_pickerVisible;
});
},
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'Toggle Picker',
style: TextStyle(color: Colors.white, fontSize: 22),
),
),
),
const SizedBox(height: 10),
Stack(
children: [
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.1),
borderRadius: BorderRadius.circular(20),
border: Border.all(color: Colors.white, width: 0.5),
),
child: Wrap(
spacing: 10,
runSpacing: 10,
children: List.generate(
colors.length,
(index) => ColorItem(
onTap: () {
setState(() {
_selectedColorIndex = index;
});
},
isSelected: _selectedColorIndex == index,
color: colors[index],
size: 60,
),
),
),
),
Positioned.fill(
child: IgnorePointer(
ignoring: _pickerVisible ? true : false,
child: Padding(
padding: const EdgeInsets.all(1),
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: TweenAnimationBuilder<double>(
duration: const Duration(milliseconds: 500),
tween: Tween<double>(
begin: 12, end: _pickerVisible ? 0 : 12),
builder: (context, double value, _) => BackdropFilter(
filter: ImageFilter.blur(sigmaY: value, sigmaX: value),
child: Container(
color: Colors.white.withOpacity(0),
),
),
),
),
),
),
),
],
),
],
);
}
}
| flutter_animations_workshop/lib/pickers/2/color_picker.dart/0 | {'file_path': 'flutter_animations_workshop/lib/pickers/2/color_picker.dart', 'repo_id': 'flutter_animations_workshop', 'token_count': 1688} |
# Pedantic 1.9.0
#
# Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
#
# Google internally enforced rules. See README.md for more information,
# including a list of lints that are intentionally _not_ enforced.
linter:
rules:
- always_declare_return_types
- always_require_non_null_named_parameters
- annotate_overrides
- avoid_empty_else
- avoid_init_to_null
- avoid_null_checks_in_equality_operators
- avoid_relative_lib_imports
- avoid_return_types_on_setters
- avoid_shadowing_type_parameters
- avoid_types_as_parameter_names
- camel_case_extensions
- curly_braces_in_flow_control_structures
- empty_catches
- empty_constructor_bodies
- library_names
- library_prefixes
- no_duplicate_case_values
- null_closures
- omit_local_variable_types
- prefer_adjacent_string_concatenation
- prefer_collection_literals
- prefer_conditional_assignment
- prefer_contains
- prefer_equal_for_default_values
- prefer_final_fields
- prefer_for_elements_to_map_fromIterable
- prefer_generic_function_type_aliases
- prefer_if_null_operators
- prefer_is_empty
- prefer_is_not_empty
- prefer_iterable_whereType
- prefer_single_quotes
- prefer_spread_collections
- recursive_getters
- slash_for_doc_comments
- type_init_formals
- unawaited_futures
- unnecessary_const
- unnecessary_new
- unnecessary_null_in_if_null_operators
- unnecessary_this
- unrelated_type_equality_checks
- use_function_type_syntax_for_parameters
- use_rethrow_when_possible
- valid_regexps
| flutter_architecture_samples/analysis_options.yaml/0 | {'file_path': 'flutter_architecture_samples/analysis_options.yaml', 'repo_id': 'flutter_architecture_samples', 'token_count': 661} |
import 'dart:async';
import 'package:meta/meta.dart';
import 'package:bloc/bloc.dart';
import 'package:bloc_library/blocs/blocs.dart';
class StatsBloc extends Bloc<StatsEvent, StatsState> {
final TodosBloc todosBloc;
StreamSubscription todosSubscription;
StatsBloc({@required this.todosBloc}) {
todosSubscription = todosBloc.listen((state) {
if (state is TodosLoaded) {
add(UpdateStats(state.todos));
}
});
}
@override
StatsState get initialState => StatsLoading();
@override
Stream<StatsState> mapEventToState(StatsEvent event) async* {
if (event is UpdateStats) {
var numActive =
event.todos.where((todo) => !todo.complete).toList().length;
var numCompleted =
event.todos.where((todo) => todo.complete).toList().length;
yield StatsLoaded(numActive, numCompleted);
}
}
@override
Future<void> close() {
todosSubscription?.cancel();
return super.close();
}
}
| flutter_architecture_samples/bloc_library/lib/blocs/stats/stats_bloc.dart/0 | {'file_path': 'flutter_architecture_samples/bloc_library/lib/blocs/stats/stats_bloc.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 387} |
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.
import 'package:bloc_library/blocs/blocs.dart';
import 'package:bloc_library/blocs/tab/tab_bloc.dart';
import 'package:bloc_library/models/app_tab.dart';
import 'package:bloc_library/screens/screens.dart';
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:bloc_library/blocs/todos/todos.dart';
import 'package:bloc_library/screens/home_screen.dart';
import 'package:bloc_library/localization.dart';
import 'package:todos_app_core/todos_app_core.dart';
class MockTodosBloc extends MockBloc<TodosEvent, TodosState>
implements TodosBloc {}
class MockFilteredTodosBloc
extends MockBloc<FilteredTodosLoaded, FilteredTodosState>
implements FilteredTodosBloc {}
class MockTabBloc extends MockBloc<TabEvent, AppTab> implements TabBloc {}
class MockStatsBloc extends MockBloc<StatsEvent, StatsState>
implements StatsBloc {}
void main() {
group('HomeScreen', () {
TodosBloc todosBloc;
FilteredTodosBloc filteredTodosBloc;
TabBloc tabBloc;
StatsBloc statsBloc;
setUp(() {
todosBloc = MockTodosBloc();
filteredTodosBloc = MockFilteredTodosBloc();
tabBloc = MockTabBloc();
statsBloc = MockStatsBloc();
});
testWidgets('renders correctly', (WidgetTester tester) async {
when(todosBloc.state).thenAnswer((_) => TodosLoaded([]));
when(tabBloc.state).thenAnswer((_) => AppTab.todos);
await tester.pumpWidget(
MultiBlocProvider(
providers: [
BlocProvider<TodosBloc>.value(
value: todosBloc,
),
BlocProvider<FilteredTodosBloc>.value(
value: filteredTodosBloc,
),
BlocProvider<TabBloc>.value(
value: tabBloc,
),
BlocProvider<StatsBloc>.value(
value: statsBloc,
),
],
child: MaterialApp(
home: Scaffold(
body: HomeScreen(),
),
localizationsDelegates: [
ArchSampleLocalizationsDelegate(),
FlutterBlocLocalizationsDelegate(),
],
),
),
);
await tester.pumpAndSettle();
expect(find.byKey(ArchSampleKeys.addTodoFab), findsOneWidget);
expect(find.text('Bloc Library Example'), findsOneWidget);
});
testWidgets('Navigates to /addTodo when Floating Action Button is tapped',
(WidgetTester tester) async {
when(todosBloc.state).thenAnswer((_) => TodosLoaded([]));
when(tabBloc.state).thenAnswer((_) => AppTab.todos);
await tester.pumpWidget(
MultiBlocProvider(
providers: [
BlocProvider<TodosBloc>.value(
value: todosBloc,
),
BlocProvider<FilteredTodosBloc>.value(
value: filteredTodosBloc,
),
BlocProvider<TabBloc>.value(
value: tabBloc,
),
BlocProvider<StatsBloc>.value(
value: statsBloc,
),
],
child: MaterialApp(
home: Scaffold(
body: HomeScreen(),
),
localizationsDelegates: [
ArchSampleLocalizationsDelegate(),
FlutterBlocLocalizationsDelegate(),
],
routes: {
ArchSampleRoutes.addTodo: (context) {
return AddEditScreen(
key: ArchSampleKeys.addTodoScreen,
onSave: (task, note) {},
isEditing: false,
);
},
},
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(ArchSampleKeys.addTodoFab));
await tester.pumpAndSettle();
expect(find.byType(AddEditScreen), findsOneWidget);
});
});
}
| flutter_architecture_samples/bloc_library/test/screens/home_screen_test.dart/0 | {'file_path': 'flutter_architecture_samples/bloc_library/test/screens/home_screen_test.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 2000} |
// 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_sample/actions/actions.dart';
import 'package:built_redux_sample/containers/typedefs.dart';
import 'package:built_redux_sample/models/models.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_built_redux/flutter_built_redux.dart';
class AppLoading extends StoreConnector<AppState, AppActions, bool> {
final ViewModelBuilder<bool> builder;
AppLoading({Key key, @required this.builder}) : super(key: key);
@override
Widget build(BuildContext context, bool state, AppActions actions) {
return builder(context, state);
}
@override
bool connect(AppState state) {
return state.isLoading;
}
}
| flutter_architecture_samples/built_redux/lib/containers/app_loading.dart/0 | {'file_path': 'flutter_architecture_samples/built_redux/lib/containers/app_loading.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 272} |
// 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_sample/models/models.dart';
import 'package:flutter/material.dart';
import 'package:todos_app_core/todos_app_core.dart';
class FilterButton extends StatelessWidget {
final PopupMenuItemSelected<VisibilityFilter> onSelected;
final VisibilityFilter activeFilter;
final bool visible;
FilterButton({this.onSelected, this.activeFilter, this.visible, Key key})
: super(key: key);
@override
Widget build(BuildContext context) {
final defaultStyle = Theme.of(context).textTheme.body1;
final activeStyle = Theme.of(context)
.textTheme
.body1
.copyWith(color: Theme.of(context).accentColor);
return AnimatedOpacity(
opacity: visible ? 1.0 : 0.0,
duration: Duration(milliseconds: 150),
child: PopupMenuButton<VisibilityFilter>(
key: ArchSampleKeys.filterButton,
tooltip: ArchSampleLocalizations.of(context).filterTodos,
onSelected: onSelected,
itemBuilder: (BuildContext context) =>
<PopupMenuItem<VisibilityFilter>>[
PopupMenuItem<VisibilityFilter>(
value: VisibilityFilter.all,
child: Text(
ArchSampleLocalizations.of(context).showAll,
key: ArchSampleKeys.allFilter,
style: activeFilter == VisibilityFilter.all
? activeStyle
: defaultStyle,
),
),
PopupMenuItem<VisibilityFilter>(
value: VisibilityFilter.active,
child: Text(
ArchSampleLocalizations.of(context).showActive,
key: ArchSampleKeys.activeFilter,
style: activeFilter == VisibilityFilter.active
? activeStyle
: defaultStyle,
),
),
PopupMenuItem<VisibilityFilter>(
value: VisibilityFilter.completed,
child: Text(
ArchSampleLocalizations.of(context).showCompleted,
key: ArchSampleKeys.completedFilter,
style: activeFilter == VisibilityFilter.completed
? activeStyle
: defaultStyle,
),
),
],
icon: Icon(Icons.filter_list),
),
);
}
}
| flutter_architecture_samples/built_redux/lib/presentation/filter_button.dart/0 | {'file_path': 'flutter_architecture_samples/built_redux/lib/presentation/filter_button.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1062} |
import 'package:flutter/cupertino.dart';
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';
class StatsView extends StatelessWidget {
const StatsView();
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: Text(
ArchSampleLocalizations.of(context).completedTodos,
style: Theme.of(context).textTheme.title,
),
),
Padding(
padding: const EdgeInsets.only(bottom: 24.0),
child: Selector<TodoListModel, int>(
selector: (_, model) => model.numCompleted,
builder: (context, numCompleted, _) => Text(
'$numCompleted',
key: ArchSampleKeys.statsNumCompleted,
style: Theme.of(context).textTheme.subhead,
),
),
),
Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: Text(
ArchSampleLocalizations.of(context).activeTodos,
style: Theme.of(context).textTheme.title,
),
),
Padding(
padding: const EdgeInsets.only(bottom: 24.0),
child: Selector<TodoListModel, int>(
selector: (_, model) => model.numActive,
builder: (context, numActive, _) => Text(
'$numActive',
key: ArchSampleKeys.statsNumActive,
style: Theme.of(context).textTheme.subhead,
),
),
)
],
),
);
}
}
| flutter_architecture_samples/change_notifier_provider/lib/home/stats_view.dart/0 | {'file_path': 'flutter_architecture_samples/change_notifier_provider/lib/home/stats_view.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 936} |
// 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:todos_repository_core/todos_repository_core.dart';
import 'package:todos_repository_local_storage/todos_repository_local_storage.dart';
class MockUserRepository implements UserRepository {
@override
Future<UserEntity> login([
delayAuth = const Duration(milliseconds: 200),
]) {
return Future<UserEntity>.delayed(delayAuth);
}
}
class MockReactiveTodosRepository implements ReactiveTodosRepository {
// ignore: close_sinks
final controller = StreamController<List<TodoEntity>>();
List<TodoEntity> _todos = [];
@override
Future<void> addNewTodo(TodoEntity newTodo) async {
_todos.add(newTodo);
controller.add(_todos);
}
@override
Future<List<void>> deleteTodo(List<String> idList) async {
_todos.removeWhere((todo) => idList.contains(todo.id));
controller.add(_todos);
return [];
}
@override
Stream<List<TodoEntity>> todos({webClient = const WebClient()}) async* {
_todos = await webClient.loadTodos();
yield _todos;
await for (var latest in controller.stream) {
yield latest;
}
}
@override
Future<void> updateTodo(TodoEntity todo) async {
_todos[_todos.indexWhere((t) => t.id == todo.id)] = todo;
controller.add(_todos);
}
}
| flutter_architecture_samples/firestore_redux/test_driver/mock_reactive_repository.dart/0 | {'file_path': 'flutter_architecture_samples/firestore_redux/test_driver/mock_reactive_repository.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 526} |
import 'package:todos_repository_core/todos_repository_core.dart';
import 'package:frideos/frideos.dart';
import 'package:frideos_library/models/models.dart';
class TodosBloc {
final TodosRepository repository;
TodosBloc({this.repository}) {
_init();
}
void _init() async {
// Load the todos from the repository
await loadTodos();
// Listening for changes in the todos list, updated the streams and save
// to the repository. It is the same as:
//
// todosItems.outStream.listen((todos) => onTodosChange(...)
//
todosItems.onChange((todos) =>
onTodosChange(allComplete, hasCompletedTodos, todos, onDataLoaded));
// Listening for changes in the VisibilityFilter and filter the visible
// todos depending on the current filter.:
activeFilter
.onChange((filter) => onFilterChange(todosItems, visibleTodos, filter));
}
// STREAMS
//
final todosItems = StreamedList<Todo>();
final visibleTodos = StreamedList<Todo>();
final activeFilter =
StreamedValue<VisibilityFilter>(initialData: VisibilityFilter.all);
final currentTodo = StreamedValue<Todo>(initialData: Todo('Initializing'));
final allComplete = StreamedValue<bool>(initialData: false);
final hasCompletedTodos = StreamedValue<bool>(initialData: false);
// SENDER (to send the todosItems list to the StatsBloc)
//
final todosSender = ListSender<Todo>();
// METHODS
//
void loadTodos() async {
var todos = await repository.loadTodos();
todosItems.value = todos.map(Todo.fromEntity).toList() ?? [];
todosSender.send(todosItems.value);
}
/// Every time the todos list changes, this method will save the todos, update
/// the visible todos, and send to the statsBloc the todos list.
void onDataLoaded() {
saveTodos();
updateVisibleItems();
todosSender.send(todosItems.value);
}
void updateVisibleItems() =>
visibleTodos.value = filterTodos(todosItems.value, activeFilter.value);
void saveTodos() => repository
.saveTodos(todosItems.value.map((item) => item.toEntity()).toList());
void addTodo(Todo todo) => todosItems.addElement(todo);
void updateTodo(Todo todo) {
todosItems.replace(currentTodo.value, todo);
currentTodo.value = todo;
}
void addEdit(bool isEditing, String task, String note) {
if (isEditing) {
updateTodo(currentTodo.value.copyWith(task: task, note: note));
} else {
addTodo(Todo(
task,
note: note,
));
}
}
void deleteTodo(Todo todo) => todosItems.removeElement(todo);
void onCheckboxChanged(Todo todo) {
var updatedTodo = todo.copyWith(complete: !todo.complete);
todosItems?.replace(todo, updatedTodo);
currentTodo.value = updatedTodo;
}
void clearCompleted() {
todosItems.value.removeWhere((todo) => todo.complete);
// Call the refresh method to update the stream when
// there is no implementation of the respective method
// on the StreamedList class, read the docs for details.
todosItems.refresh();
}
void toggleAll() {
var areAllComplete = todosItems.value.every((todo) => todo.complete);
todosItems.value = todosItems.value
.map((todo) => todo.copyWith(complete: !areAllComplete))
.toList();
}
void extraAction(ExtraAction action) {
if (action == ExtraAction.toggleAllComplete) {
toggleAll();
} else if (action == ExtraAction.clearCompleted) {
clearCompleted();
}
}
static void onTodosChange(
StreamedValue<bool> _allComplete,
StreamedValue<bool> _hasCompletedTodos,
List<Todo> todos,
Function _onDataLoaded,
) {
_allComplete.value = todos.every((todo) => todo.complete);
_hasCompletedTodos.value = todos.any((todo) => todo.complete);
// Saving items, updating visible items and sending to the statsBloc
// the todos list.
_onDataLoaded();
}
static void onFilterChange(StreamedList<Todo> _todosItems,
StreamedList<Todo> _visibleTodos, VisibilityFilter _filter) {
if (_todosItems.value != null) {
_visibleTodos.value = filterTodos(_todosItems.value, _filter);
}
}
static List<Todo> filterTodos(List<Todo> todos, VisibilityFilter filter) {
return todos.where((todo) {
switch (filter) {
case VisibilityFilter.active:
return !todo.complete;
case VisibilityFilter.completed:
return todo.complete;
case VisibilityFilter.all:
default:
return true;
}
}).toList();
}
/// To close all the streams
void dispose() {
todosItems.dispose();
currentTodo.dispose();
activeFilter.dispose();
allComplete.dispose();
hasCompletedTodos.dispose();
visibleTodos.dispose();
}
}
| flutter_architecture_samples/frideos_library/lib/blocs/todos_bloc.dart/0 | {'file_path': 'flutter_architecture_samples/frideos_library/lib/blocs/todos_bloc.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1793} |
import 'dart:async';
import 'package:test/test.dart';
import 'package:todos_repository_core/todos_repository_core.dart';
import 'package:frideos_library/blocs/todos_bloc.dart';
import 'package:frideos_library/blocs/stats_bloc.dart';
import 'package:frideos_library/models/models.dart';
class MockRepository extends TodosRepository {
List<TodoEntity> entities;
MockRepository(List<Todo> todos)
: entities = todos.map((it) => it.toEntity()).toList();
@override
Future<List<TodoEntity>> loadTodos() {
return Future.value(entities);
}
@override
Future saveTodos(List<TodoEntity> todos) {
return Future.sync(() => entities = todos);
}
}
void main() {
group('StatsBloc', () {
test('should stream the number of active todos', () async {
final statsBloc = StatsBloc();
var todos = [
Todo('a'),
Todo('b'),
Todo('c', complete: true),
];
final todosBloc = TodosBloc(repository: MockRepository(todos));
todosBloc.todosSender.setReceiver(statsBloc.todosItems);
await todosBloc.loadTodos();
await expectLater(statsBloc.numActive.outStream, emits(2));
});
test('should stream the number of completed todos', () async {
final statsBloc = StatsBloc();
final todos = [
Todo('a'),
Todo('b'),
Todo('Hallo', complete: true),
Todo('Friend', complete: true),
Todo('Flutter', complete: true),
];
final todosBloc = TodosBloc(repository: MockRepository(todos));
todosBloc.todosSender.setReceiver(statsBloc.todosItems);
await todosBloc.loadTodos();
await expectLater(statsBloc.numComplete.outStream, emits(3));
});
});
}
| flutter_architecture_samples/frideos_library/test/stats_bloc_test.dart/0 | {'file_path': 'flutter_architecture_samples/frideos_library/test/stats_bloc_test.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 715} |
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:inherited_widget_sample/localization.dart';
import 'package:inherited_widget_sample/screens/add_edit_screen.dart';
import 'package:inherited_widget_sample/screens/home_screen.dart';
import 'package:todos_app_core/todos_app_core.dart';
class InheritedWidgetApp extends StatelessWidget {
const InheritedWidgetApp();
@override
Widget build(BuildContext context) {
return MaterialApp(
onGenerateTitle: (context) =>
InheritedWidgetLocalizations.of(context).appTitle,
theme: ArchSampleTheme.theme,
localizationsDelegates: [
ArchSampleLocalizationsDelegate(),
InheritedWidgetLocalizationsDelegate(),
],
routes: {
ArchSampleRoutes.home: (context) => HomeScreen(),
ArchSampleRoutes.addTodo: (context) => AddEditScreen(),
},
);
}
}
| flutter_architecture_samples/inherited_widget/lib/app.dart/0 | {'file_path': 'flutter_architecture_samples/inherited_widget/lib/app.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 366} |
// 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 'package:integration_tests/page_objects/page_objects.dart';
import '../elements/extra_actions_element.dart';
import '../elements/filters_element.dart';
import '../elements/stats_element.dart';
import '../elements/todo_list_element.dart';
import '../utils.dart';
import 'test_screen.dart';
class HomeTestScreen extends TestScreen {
final _filterButtonFinder = find.byValueKey('__filterButton__');
final _extraActionsButtonFinder = find.byValueKey('__extraActionsButton__');
final _todosTabFinder = find.byValueKey('__todoTab__');
final _statsTabFinder = find.byValueKey('__statsTab__');
final _snackbarFinder = find.byValueKey('__snackbar__');
final _addTodoButtonFinder = find.byValueKey('__addTodoFab__');
HomeTestScreen(FlutterDriver driver) : super(driver);
@override
Future<bool> isLoading({Duration timeout}) async =>
TodoListElement(driver).isLoading;
@override
Future<bool> isReady({Duration timeout}) => TodoListElement(driver).isReady;
TodoListElement get todoList {
return TodoListElement(driver);
}
StatsElement get stats {
return StatsElement(driver);
}
TodoListElement tapTodosTab() {
driver.tap(_todosTabFinder);
return TodoListElement(driver);
}
StatsElement tapStatsTab() {
driver.tap(_statsTabFinder);
return StatsElement(driver);
}
FiltersElement tapFilterButton() {
driver.tap(_filterButtonFinder);
return FiltersElement(driver);
}
ExtraActionsElement tapExtraActionsButton() {
driver.tap(_extraActionsButtonFinder);
return ExtraActionsElement(driver);
}
Future<bool> get snackbarVisible {
return widgetExists(driver, _snackbarFinder);
}
AddTestScreen tapAddTodoButton() {
driver.tap(_addTodoButtonFinder);
return AddTestScreen(driver);
}
DetailsTestScreen tapTodo(String text) {
driver.tap(find.text(text));
return DetailsTestScreen(driver);
}
}
| flutter_architecture_samples/integration_tests/lib/page_objects/screens/home_test_screen.dart/0 | {'file_path': 'flutter_architecture_samples/integration_tests/lib/page_objects/screens/home_test_screen.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 715} |
import 'package:flutter/material.dart';
import 'package:mobx_sample/add_todo_screen.dart';
import 'package:mobx_sample/localization.dart';
import 'package:mobx_sample/models/todo.dart';
import 'package:mobx_sample/stores/todo_store.dart';
import 'package:provider/provider.dart';
import 'package:todos_app_core/todos_app_core.dart';
import 'package:todos_repository_core/todos_repository_core.dart';
import 'home/home_screen.dart';
class MobxApp extends StatelessWidget {
final TodosRepository repository;
const MobxApp({Key key, @required this.repository}) : super(key: key);
@override
Widget build(BuildContext context) {
return Provider<TodoStore>(
create: (_) {
final store = TodoStore(repository)..init();
return store;
},
dispose: (_, store) => store.dispose(), // Clean up after we're done
child: MaterialApp(
initialRoute: ArchSampleRoutes.home,
theme: ArchSampleTheme.theme,
localizationsDelegates: [
MobxLocalizationsDelegate(),
ArchSampleLocalizationsDelegate(),
],
routes: {
ArchSampleRoutes.home: (context) => const HomeScreen(),
ArchSampleRoutes.addTodo: (context) {
return AddTodoScreen(
onAdd: (Todo todo) {
Provider.of<TodoStore>(context, listen: false).todos.add(todo);
Navigator.pop(context);
},
);
}
},
),
);
}
}
| flutter_architecture_samples/mobx/lib/app.dart/0 | {'file_path': 'flutter_architecture_samples/mobx/lib/app.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 648} |
// 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:mvc/src/screens/detail_screen.dart';
import 'package:mvc/src/widgets/todo_item.dart';
import 'package:mvc/src/Controller.dart';
class TodoList extends StatelessWidget {
TodoList({Key key}) : super(key: key);
static final _con = Con.con;
@override
Widget build(BuildContext context) {
return Container(
child: Con.isLoading ? _buildLoading : _buildList(),
);
}
Center get _buildLoading {
return Center(
child: CircularProgressIndicator(
key: ArchSampleKeys.todosLoading,
),
);
}
ListView _buildList() {
final todos = Con.filteredTodos;
return ListView.builder(
key: ArchSampleKeys.todoList,
itemCount: todos.length,
itemBuilder: (BuildContext context, int index) {
final Map todo = todos.elementAt(index).cast<String, Object>();
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 Map && todo.isNotEmpty) {
_showUndoSnackbar(context, todo);
}
});
},
onCheckboxChanged: (complete) {
_con.checked(todo);
},
);
},
);
}
void _removeTodo(BuildContext context, Map todo) {
_con.remove(todo);
_showUndoSnackbar(context, todo);
}
void _showUndoSnackbar(BuildContext context, Map 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: () {
_con.undo(todo);
},
),
),
);
}
}
| flutter_architecture_samples/mvc/lib/src/widgets/todo_list.dart/0 | {'file_path': 'flutter_architecture_samples/mvc/lib/src/widgets/todo_list.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1204} |
// 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:meta/meta.dart';
import 'package:mvi_base/src/models/models.dart';
import 'package:mvi_base/src/mvi_core.dart';
import 'package:mvi_base/src/todos_interactor.dart';
mixin DetailView implements MviView {
final deleteTodo = StreamController<String>.broadcast(sync: true);
final updateTodo = StreamController<Todo>.broadcast(sync: true);
@override
Future tearDown() {
return Future.wait([
deleteTodo.close(),
updateTodo.close(),
]);
}
}
class DetailPresenter extends MviPresenter<Todo> {
final DetailView _view;
final TodosInteractor _interactor;
DetailPresenter({
@required String id,
@required DetailView view,
@required TodosInteractor interactor,
}) : _view = view,
_interactor = interactor,
super(stream: interactor.todo(id));
@override
void setUp() {
subscriptions.addAll([
_view.deleteTodo.stream.listen(_interactor.deleteTodo),
_view.updateTodo.stream.listen(_interactor.updateTodo),
]);
}
}
| flutter_architecture_samples/mvi_base/lib/src/mvi_todo.dart/0 | {'file_path': 'flutter_architecture_samples/mvi_base/lib/src/mvi_todo.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 432} |
part of details;
Widget view(BuildContext context, Dispatch<DetailsMessage> dispatch,
DetailsModel model) {
final localizations = ArchSampleLocalizations.of(context);
return Scaffold(
key: ArchSampleKeys.todoDetailsScreen,
appBar: AppBar(
title: Text(localizations.todoDetails),
actions: [
IconButton(
tooltip: localizations.deleteTodo,
icon: Icon(Icons.delete),
key: ArchSampleKeys.deleteTodoButton,
onPressed: () => dispatch(Remove()),
)
],
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: ListView(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(right: 8.0),
child: Checkbox(
key: ArchSampleKeys.detailsTodoItemCheckbox,
value: model.todo.complete,
onChanged: (_) => dispatch(ToggleCompleted()),
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(
top: 8.0,
bottom: 16.0,
),
child: Text(
model.todo.task,
key: ArchSampleKeys.detailsTodoItemTask,
style: Theme.of(context).textTheme.headline,
),
),
Text(
model.todo.note,
key: ArchSampleKeys.detailsTodoItemNote,
style: Theme.of(context).textTheme.subhead,
)
],
),
),
],
),
],
),
),
floatingActionButton: FloatingActionButton(
key: ArchSampleKeys.editTodoFab,
tooltip: localizations.editTodo,
child: Icon(Icons.edit),
onPressed: () => dispatch(Edit()),
),
);
}
| flutter_architecture_samples/mvu/lib/details/view.dart/0 | {'file_path': 'flutter_architecture_samples/mvu/lib/details/view.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1231} |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'types.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 _$StatsModel extends StatsModel {
@override
final BuiltList<TodoModel> items;
@override
final bool loading;
@override
final int activeCount;
@override
final int completedCount;
factory _$StatsModel([void Function(StatsModelBuilder b) updates]) =>
(new StatsModelBuilder()..update(updates)).build();
_$StatsModel._(
{this.items, this.loading, this.activeCount, this.completedCount})
: super._() {
if (items == null) {
throw new BuiltValueNullFieldError('StatsModel', 'items');
}
if (loading == null) {
throw new BuiltValueNullFieldError('StatsModel', 'loading');
}
if (activeCount == null) {
throw new BuiltValueNullFieldError('StatsModel', 'activeCount');
}
if (completedCount == null) {
throw new BuiltValueNullFieldError('StatsModel', 'completedCount');
}
}
@override
StatsModel rebuild(void Function(StatsModelBuilder b) updates) =>
(toBuilder()..update(updates)).build();
@override
StatsModelBuilder toBuilder() => new StatsModelBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is StatsModel &&
items == other.items &&
loading == other.loading &&
activeCount == other.activeCount &&
completedCount == other.completedCount;
}
@override
int get hashCode {
return $jf($jc(
$jc($jc($jc(0, items.hashCode), loading.hashCode),
activeCount.hashCode),
completedCount.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('StatsModel')
..add('items', items)
..add('loading', loading)
..add('activeCount', activeCount)
..add('completedCount', completedCount))
.toString();
}
}
class StatsModelBuilder implements Builder<StatsModel, StatsModelBuilder> {
_$StatsModel _$v;
ListBuilder<TodoModel> _items;
ListBuilder<TodoModel> get items =>
_$this._items ??= new ListBuilder<TodoModel>();
set items(ListBuilder<TodoModel> items) => _$this._items = items;
bool _loading;
bool get loading => _$this._loading;
set loading(bool loading) => _$this._loading = loading;
int _activeCount;
int get activeCount => _$this._activeCount;
set activeCount(int activeCount) => _$this._activeCount = activeCount;
int _completedCount;
int get completedCount => _$this._completedCount;
set completedCount(int completedCount) =>
_$this._completedCount = completedCount;
StatsModelBuilder();
StatsModelBuilder get _$this {
if (_$v != null) {
_items = _$v.items?.toBuilder();
_loading = _$v.loading;
_activeCount = _$v.activeCount;
_completedCount = _$v.completedCount;
_$v = null;
}
return this;
}
@override
void replace(StatsModel other) {
if (other == null) {
throw new ArgumentError.notNull('other');
}
_$v = other as _$StatsModel;
}
@override
void update(void Function(StatsModelBuilder b) updates) {
if (updates != null) updates(this);
}
@override
_$StatsModel build() {
_$StatsModel _$result;
try {
_$result = _$v ??
new _$StatsModel._(
items: items.build(),
loading: loading,
activeCount: activeCount,
completedCount: completedCount);
} catch (_) {
String _$failedField;
try {
_$failedField = 'items';
items.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
'StatsModel', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
| flutter_architecture_samples/mvu/lib/stats/types.g.dart/0 | {'file_path': 'flutter_architecture_samples/mvu/lib/stats/types.g.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1655} |
import 'package:mvu/common/todo_model.dart';
import 'package:mvu/stats/stats.dart';
import 'package:mvu/stats/types.dart';
import 'package:test/test.dart';
import 'cmd_runner.dart';
import 'data.dart';
void main() {
group('Home screen "Stats" ->', () {
CmdRunner<StatsMessage> _cmdRunner;
TestTodosCmdRepository _cmdRepo;
setUp(() {
_cmdRunner = CmdRunner();
_cmdRepo = TestTodosCmdRepository();
});
test('init', () {
final initResult = init();
final model = initResult.model;
final initEffects = initResult.effects;
_cmdRunner.run(initEffects);
expect(model.activeCount, 0);
expect(model.completedCount, 0);
expect(model.loading, isFalse);
expect(initEffects, isNotEmpty);
expect(_cmdRunner.producedMessages,
orderedEquals([TypeMatcher<LoadStats>()]));
});
test('LoadStats: model is in loading state', () {
var model = init().model;
final upd = update(_cmdRepo, LoadStats(), model);
final updatedModel = upd.model;
final effects = upd.effects;
_cmdRunner.run(effects);
expect(updatedModel.loading, isTrue);
expect(effects, isNotEmpty);
expect(_cmdRunner.producedMessages,
orderedEquals([TypeMatcher<OnStatsLoaded>()]));
expect(_cmdRepo.createdEffects,
orderedEquals([TypeMatcher<LoadTodosEffect>()]));
});
test('OnStatsLoaded: stats is displayed', () {
var model = init().model;
var activeCount = 5, completedCount = 8;
var items = createTodosForStats(activeCount, completedCount);
var updatedModel = update(_cmdRepo, OnStatsLoaded(items), model).model;
expect(updatedModel.loading, isFalse);
expect(updatedModel.activeCount, activeCount);
expect(updatedModel.completedCount, completedCount);
});
test('ToggleAllMessage(false->true): stats is updated', () {
var model = init().model;
var items = createTodos(complete: false);
var upd = update(_cmdRepo, OnStatsLoaded(items), model);
var updatedModel = upd.model;
upd = update(_cmdRepo, ToggleAllMessage(), updatedModel);
updatedModel = upd.model;
_cmdRunner.run(upd.effects);
expect(updatedModel.activeCount, 0);
expect(updatedModel.completedCount, items.length);
expect(upd.effects, isNotEmpty);
expect(_cmdRepo.createdEffects,
orderedEquals([TypeMatcher<SaveAllTodosEffect>()]));
});
test('ToggleAllMessage(true->false): stats is updated', () {
var model = init().model;
var items = createTodos(complete: true);
var updatedModel = update(_cmdRepo, OnStatsLoaded(items), model).model;
updatedModel = update(_cmdRepo, ToggleAllMessage(), updatedModel).model;
expect(updatedModel.activeCount, items.length);
expect(updatedModel.completedCount, 0);
});
test('ToggleAllMessage(partially): stats is updated', () {
var model = init().model;
var activeCount = 3, completedCount = 6;
var items = createTodosForStats(activeCount, completedCount);
var updatedModel = update(_cmdRepo, OnStatsLoaded(items), model).model;
updatedModel = update(_cmdRepo, ToggleAllMessage(), updatedModel).model;
expect(updatedModel.activeCount, 0);
expect(updatedModel.completedCount, items.length);
expect(updatedModel.items,
everyElement(predicate<TodoModel>((x) => x.complete)));
});
test('CleareCompletedMessage: stats is updated', () {
var model = init().model;
var activeCount = 3, completedCount = 6;
var items = createTodosForStats(activeCount, completedCount);
var updatedModel = update(_cmdRepo, OnStatsLoaded(items), model).model;
final upd = update(_cmdRepo, CleareCompletedMessage(), updatedModel);
updatedModel = upd.model;
_cmdRunner.run(upd.effects);
expect(updatedModel.activeCount, activeCount);
expect(updatedModel.completedCount, 0);
expect(updatedModel.items,
everyElement(predicate<TodoModel>((x) => !x.complete)));
expect(upd.effects, isNotEmpty);
expect(_cmdRepo.createdEffects,
orderedEquals([TypeMatcher<SaveAllTodosEffect>()]));
});
});
}
| flutter_architecture_samples/mvu/test/stats_screen_test.dart/0 | {'file_path': 'flutter_architecture_samples/mvu/test/stats_screen_test.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1593} |
// 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:key_value_store_flutter/key_value_store_flutter.dart';
import 'package:redux/redux.dart';
import 'package:redux_sample/app.dart';
import 'package:redux_sample/reducers/app_state_reducer.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:todos_repository_local_storage/todos_repository_local_storage.dart';
import 'middleware/store_todos_middleware.dart';
import 'models/app_state.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(ReduxApp(
store: Store<AppState>(
appReducer,
initialState: AppState.loading(),
middleware: createStoreTodosMiddleware(LocalStorageRepository(
localStorage: KeyValueStorage(
'redux',
FlutterKeyValueStore(await SharedPreferences.getInstance()),
),
)),
),
));
}
| flutter_architecture_samples/redux/lib/main.dart/0 | {'file_path': 'flutter_architecture_samples/redux/lib/main.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 387} |
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.
import 'dart:async';
import 'package:flutter/material.dart';
class ScopedModelLocalizations {
static ScopedModelLocalizations of(BuildContext context) {
return Localizations.of<ScopedModelLocalizations>(
context, ScopedModelLocalizations);
}
String get appTitle => 'scoped_model example';
}
class ScopedModelLocalizationsDelegate
extends LocalizationsDelegate<ScopedModelLocalizations> {
@override
Future<ScopedModelLocalizations> load(Locale locale) =>
Future(() => ScopedModelLocalizations());
@override
bool shouldReload(ScopedModelLocalizationsDelegate old) => false;
@override
bool isSupported(Locale locale) =>
locale.languageCode.toLowerCase().contains('en');
}
| flutter_architecture_samples/scoped_model/lib/localization.dart/0 | {'file_path': 'flutter_architecture_samples/scoped_model/lib/localization.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 266} |
// 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:simple_bloc_flutter_sample/dependency_injection.dart';
import 'package:simple_bloc_flutter_sample/localization.dart';
import 'package:simple_bloc_flutter_sample/screens/add_edit_screen.dart';
import 'package:simple_bloc_flutter_sample/screens/home_screen.dart';
import 'package:simple_bloc_flutter_sample/widgets/todos_bloc_provider.dart';
import 'package:simple_blocs/simple_blocs.dart';
import 'package:todos_app_core/todos_app_core.dart';
import 'package:todos_repository_core/todos_repository_core.dart';
class SimpleBlocApp extends StatelessWidget {
final TodosInteractor todosInteractor;
final UserRepository userRepository;
const SimpleBlocApp({
Key key,
this.todosInteractor,
this.userRepository,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Injector(
todosInteractor: todosInteractor,
userRepository: userRepository,
child: TodosBlocProvider(
bloc: TodosListBloc(todosInteractor),
child: MaterialApp(
onGenerateTitle: (context) => BlocLocalizations.of(context).appTitle,
theme: ArchSampleTheme.theme,
localizationsDelegates: [
ArchSampleLocalizationsDelegate(),
InheritedWidgetLocalizationsDelegate(),
],
routes: {
ArchSampleRoutes.home: (context) {
return HomeScreen(
repository: Injector.of(context).userRepository,
);
},
ArchSampleRoutes.addTodo: (context) {
return AddEditScreen(
addTodo: TodosBlocProvider.of(context).addTodo,
);
},
},
),
),
);
}
}
| flutter_architecture_samples/simple_bloc_flutter/lib/app.dart/0 | {'file_path': 'flutter_architecture_samples/simple_bloc_flutter/lib/app.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 815} |
import 'package:todos_repository_core/src/todo_entity.dart';
import 'package:todos_repository_core/src/todos_repository.dart' as core;
import '../domain/entities/todo.dart';
import '../service/exceptions/persistance_exception.dart';
import '../service/interfaces/i_todo_repository.dart';
class StatesBuilderTodosRepository implements ITodosRepository {
final core.TodosRepository _todosRepository;
StatesBuilderTodosRepository({core.TodosRepository todosRepository})
: _todosRepository = todosRepository;
@override
Future<List<Todo>> loadTodos() async {
try {
final todoEntities = await _todosRepository.loadTodos();
var todos = <Todo>[];
for (var todoEntity in todoEntities) {
todos.add(
Todo.fromJson(todoEntity.toJson()),
);
}
return todos;
} catch (e) {
throw PersistanceException('There is a problem in loading todos : $e');
}
}
@override
Future saveTodos(List<Todo> todos) {
try {
var todosEntities = <TodoEntity>[];
for (var todo in todos) {
todosEntities.add(TodoEntity.fromJson(todo.toJson()));
}
return _todosRepository.saveTodos(todosEntities);
} catch (e) {
throw PersistanceException('There is a problem in saving todos : $e');
}
}
}
| flutter_architecture_samples/states_rebuilder/lib/data_source/todo_repository.dart/0 | {'file_path': 'flutter_architecture_samples/states_rebuilder/lib/data_source/todo_repository.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 545} |
// 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:states_rebuilder/states_rebuilder.dart';
import 'package:states_rebuilder_sample/service/common/enums.dart';
import 'package:states_rebuilder_sample/service/todos_service.dart';
import 'package:todos_app_core/todos_app_core.dart';
class FilterButton extends StatelessWidget {
const FilterButton({this.isActive, Key key}) : super(key: key);
final bool isActive;
@override
Widget build(BuildContext context) {
//context is used to register FilterButton as observer in todosServiceRM
final todosServiceRM =
Injector.getAsReactive<TodosService>(context: context);
final defaultStyle = Theme.of(context).textTheme.body1;
final activeStyle = Theme.of(context)
.textTheme
.body1
.copyWith(color: Theme.of(context).accentColor);
final button = _Button(
onSelected: (filter) {
todosServiceRM.setState((s) => s.activeFilter = filter);
},
activeFilter: todosServiceRM.state.activeFilter,
activeStyle: activeStyle,
defaultStyle: defaultStyle,
);
return AnimatedOpacity(
opacity: isActive ? 1.0 : 0.0,
duration: Duration(milliseconds: 150),
child: isActive ? button : IgnorePointer(child: button),
);
}
}
class _Button extends StatelessWidget {
const _Button({
Key key,
@required this.onSelected,
@required this.activeFilter,
@required this.activeStyle,
@required this.defaultStyle,
}) : super(key: key);
final PopupMenuItemSelected<VisibilityFilter> onSelected;
final VisibilityFilter activeFilter;
final TextStyle activeStyle;
final TextStyle defaultStyle;
@override
Widget build(BuildContext context) {
return PopupMenuButton<VisibilityFilter>(
key: ArchSampleKeys.filterButton,
tooltip: ArchSampleLocalizations.of(context).filterTodos,
onSelected: onSelected,
itemBuilder: (BuildContext context) => <PopupMenuItem<VisibilityFilter>>[
PopupMenuItem<VisibilityFilter>(
key: ArchSampleKeys.allFilter,
value: VisibilityFilter.all,
child: Text(
ArchSampleLocalizations.of(context).showAll,
style: activeFilter == VisibilityFilter.all
? activeStyle
: defaultStyle,
),
),
PopupMenuItem<VisibilityFilter>(
key: ArchSampleKeys.activeFilter,
value: VisibilityFilter.active,
child: Text(
ArchSampleLocalizations.of(context).showActive,
style: activeFilter == VisibilityFilter.active
? activeStyle
: defaultStyle,
),
),
PopupMenuItem<VisibilityFilter>(
key: ArchSampleKeys.completedFilter,
value: VisibilityFilter.completed,
child: Text(
ArchSampleLocalizations.of(context).showCompleted,
style: activeFilter == VisibilityFilter.completed
? activeStyle
: defaultStyle,
),
),
],
icon: Icon(Icons.filter_list),
);
}
}
| flutter_architecture_samples/states_rebuilder/lib/ui/pages/home_screen/filter_button.dart/0 | {'file_path': 'flutter_architecture_samples/states_rebuilder/lib/ui/pages/home_screen/filter_button.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1309} |
// 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.
// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart
// This is a library that provides messages for a en locale. All the
// messages from the main program should be duplicated here with the same
// function name.
import 'package:intl/intl.dart';
import 'package:intl/message_lookup_by_library.dart';
final messages = MessageLookup();
// ignore: unused_element
final _keepAnalysisHappy = Intl.defaultLocale;
// ignore: non_constant_identifier_names
typedef MessageIfAbsent = void Function(String message_str, List args);
class MessageLookup extends MessageLookupByLibrary {
@override
String get localeName => 'en';
static String m0(task) => 'Deleted "${task}"';
@override
final messages = _notInlinedMessages(_notInlinedMessages);
static Map<String, dynamic> _notInlinedMessages(_) => {
'activeTodos': MessageLookupByLibrary.simpleMessage('Active Todos'),
'addTodo': MessageLookupByLibrary.simpleMessage('Add Todo'),
'cancel': MessageLookupByLibrary.simpleMessage('Cancel'),
'clearCompleted':
MessageLookupByLibrary.simpleMessage('Clear completed'),
'completedTodos':
MessageLookupByLibrary.simpleMessage('Completed Todos'),
'delete': MessageLookupByLibrary.simpleMessage('Delete'),
'deleteTodo': MessageLookupByLibrary.simpleMessage('Delete Todo'),
'deleteTodoConfirmation':
MessageLookupByLibrary.simpleMessage('Delete this todo?'),
'editTodo': MessageLookupByLibrary.simpleMessage('Edit Todo'),
'emptyTodoError':
MessageLookupByLibrary.simpleMessage('Please enter some text'),
'filterTodos': MessageLookupByLibrary.simpleMessage('Filter Todos'),
'markAllComplete':
MessageLookupByLibrary.simpleMessage('Mark all complete'),
'markAllIncomplete':
MessageLookupByLibrary.simpleMessage('Mark all incomplete'),
'newTodoHint':
MessageLookupByLibrary.simpleMessage('What needs to be done?'),
'notesHint':
MessageLookupByLibrary.simpleMessage('Additional Notes...'),
'saveChanges': MessageLookupByLibrary.simpleMessage('Save changes'),
'showActive': MessageLookupByLibrary.simpleMessage('Show Active'),
'showAll': MessageLookupByLibrary.simpleMessage('Show All'),
'showCompleted': MessageLookupByLibrary.simpleMessage('Show Completed'),
'stats': MessageLookupByLibrary.simpleMessage('Stats'),
'todoDeleted': m0,
'todoDetails': MessageLookupByLibrary.simpleMessage('Todo Details'),
'todos': MessageLookupByLibrary.simpleMessage('Todos'),
'undo': MessageLookupByLibrary.simpleMessage('Undo')
};
}
| flutter_architecture_samples/todos_app_core/lib/src/localizations/messages_en.dart/0 | {'file_path': 'flutter_architecture_samples/todos_app_core/lib/src/localizations/messages_en.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1005} |
// 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/foundation.dart';
import 'package:flutter/material.dart';
import 'package:todos_app_core/todos_app_core.dart';
import 'package:vanilla/models.dart';
import 'package:vanilla/widgets/typedefs.dart';
class AddEditScreen extends StatefulWidget {
final Todo todo;
final TodoAdder addTodo;
final TodoUpdater updateTodo;
AddEditScreen({
Key key,
@required this.addTodo,
@required this.updateTodo,
this.todo,
}) : super(key: key ?? ArchSampleKeys.addTodoScreen);
@override
_AddEditScreenState createState() => _AddEditScreenState();
}
class _AddEditScreenState extends State<AddEditScreen> {
static final GlobalKey<FormState> formKey = GlobalKey<FormState>();
String _task;
String _note;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(isEditing
? ArchSampleLocalizations.of(context).editTodo
: ArchSampleLocalizations.of(context).addTodo),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Form(
key: formKey,
autovalidate: false,
onWillPop: () {
return Future(() => true);
},
child: ListView(
children: [
TextFormField(
initialValue: widget.todo != null ? widget.todo.task : '',
key: ArchSampleKeys.taskField,
autofocus: isEditing ? false : true,
style: Theme.of(context).textTheme.headline,
decoration: InputDecoration(
hintText: ArchSampleLocalizations.of(context).newTodoHint),
validator: (val) => val.trim().isEmpty
? ArchSampleLocalizations.of(context).emptyTodoError
: null,
onSaved: (value) => _task = value,
),
TextFormField(
initialValue: widget.todo != null ? widget.todo.note : '',
key: ArchSampleKeys.noteField,
maxLines: 10,
style: Theme.of(context).textTheme.subhead,
decoration: InputDecoration(
hintText: ArchSampleLocalizations.of(context).notesHint,
),
onSaved: (value) => _note = value,
)
],
),
),
),
floatingActionButton: FloatingActionButton(
key: isEditing
? ArchSampleKeys.saveTodoFab
: ArchSampleKeys.saveNewTodo,
tooltip: isEditing
? ArchSampleLocalizations.of(context).saveChanges
: ArchSampleLocalizations.of(context).addTodo,
child: Icon(isEditing ? Icons.check : Icons.add),
onPressed: () {
final form = formKey.currentState;
if (form.validate()) {
form.save();
final task = _task;
final note = _note;
if (isEditing) {
widget.updateTodo(widget.todo, task: task, note: note);
} else {
widget.addTodo(Todo(
task,
note: note,
));
}
Navigator.pop(context);
}
}),
);
}
bool get isEditing => widget.todo != null;
}
| flutter_architecture_samples/vanilla/lib/screens/add_edit_screen.dart/0 | {'file_path': 'flutter_architecture_samples/vanilla/lib/screens/add_edit_screen.dart', 'repo_id': 'flutter_architecture_samples', 'token_count': 1717} |
import 'package:equatable/equatable.dart';
class Author extends Equatable {
final String name;
final String? username;
final String? twitterUsername;
final String? githubUsername;
final String? profileImage;
final String? profileImage90;
const Author({
required this.name,
this.username,
this.twitterUsername,
this.githubUsername,
this.profileImage,
this.profileImage90,
});
factory Author.fromJson(Map<String, dynamic> json) {
return Author(
name: json['name'],
username: json['username'],
twitterUsername: json['twitter_username'],
githubUsername: json['github_username'],
profileImage: json['profile_image'],
profileImage90: json['profile_image_90'],
);
}
@override
List<Object?> get props => [
name,
username,
twitterUsername,
githubUsername,
profileImage,
profileImage90,
];
}
| flutter_articles/lib/models/author.dart/0 | {'file_path': 'flutter_articles/lib/models/author.dart', 'repo_id': 'flutter_articles', 'token_count': 354} |
import 'package:flutter/material.dart';
import 'package:flutter_articles/presentation/styles/app_colors.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
class AppHtml extends StatelessWidget {
final String? data;
const AppHtml({Key? key, required this.data}) : super(key: key);
@override
Widget build(BuildContext context) {
return ConstrainedBox(
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width,
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 17, vertical: 20),
child: data == null
? Container()
: HtmlWidget(
data!,
buildAsync: false,
renderMode: RenderMode.column,
enableCaching: false,
textStyle: const TextStyle(
fontFamily: 'Roboto',
fontSize: 18,
fontWeight: FontWeight.w400,
color: AppColors.secondary,
height: 1.2,
),
),
),
);
}
}
| flutter_articles/lib/presentation/shared/app_html.dart/0 | {'file_path': 'flutter_articles/lib/presentation/shared/app_html.dart', 'repo_id': 'flutter_articles', 'token_count': 537} |
name: flutter_clock_helper
description: Helper classes for Flutter Clock contest.
version: 1.0.0+1
environment:
sdk: ">=2.2.2 <3.0.0"
dependencies:
flutter:
sdk: flutter
intl: "^0.16.0"
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| flutter_clock/flutter_clock_helper/pubspec.yaml/0 | {'file_path': 'flutter_clock/flutter_clock_helper/pubspec.yaml', 'repo_id': 'flutter_clock', 'token_count': 140} |
import 'package:flutter/material.dart';
Alignment getDragStartPositionAlignment(
double xPosition,
double yPosition,
double width,
double height,
) {
if (xPosition > width / 2) {
return yPosition > height / 2 ? Alignment.bottomRight : Alignment.topRight;
} else {
return yPosition > height / 2 ? Alignment.bottomLeft : Alignment.topLeft;
}
}
| flutter_cool_card_swiper/lib/utils.dart/0 | {'file_path': 'flutter_cool_card_swiper/lib/utils.dart', 'repo_id': 'flutter_cool_card_swiper', 'token_count': 119} |
import 'package:flutter/material.dart';
import '../widgets/cool_toolbar.dart';
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const Scaffold(
body: SafeArea(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: CoolToolbar(),
),
),
);
}
}
| flutter_cool_toolbar/lib/pages/home_page.dart/0 | {'file_path': 'flutter_cool_toolbar/lib/pages/home_page.dart', 'repo_id': 'flutter_cool_toolbar', 'token_count': 173} |
import 'package:flow_builder/flow_builder.dart';
import 'package:flutter/material.dart';
class Profile {
const Profile({this.name, this.age});
final String name;
final int age;
Profile copyWith({String name, int age}) {
return Profile(
name: name ?? this.name,
age: age ?? this.age,
);
}
}
List<Page> onGenerateProfilePages(Profile state, List<Page> pages) {
return [
ProfileName.page(),
if (state.name != null) ProfileAge.page(),
];
}
class ProfileFlow extends StatelessWidget {
static Route<Profile> route() {
return MaterialPageRoute(builder: (_) => ProfileFlow());
}
@override
Widget build(BuildContext context) {
return FlowBuilder(
state: const Profile(),
onGeneratePages: onGenerateProfilePages,
);
}
}
class ProfileName extends StatefulWidget {
static MaterialPage page() => MaterialPage(child: ProfileName());
@override
_ProfileNameState createState() => _ProfileNameState();
}
class _ProfileNameState extends State<ProfileName> {
var _name = '';
void _onNext() {
context.flow<Profile>().update((profile) {
return profile.copyWith(name: _name);
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
leading: BackButton(
onPressed: () => context.flow<Profile>().complete(),
),
title: const Text('Profile Name'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
onChanged: (name) => setState(() => _name = name),
decoration: InputDecoration(
labelText: 'Name',
hintText: 'Felix',
hintStyle: TextStyle(color: theme.disabledColor),
),
),
OutlineButton(
child: const Text('Next'),
onPressed: _name.isNotEmpty ? _onNext : null,
),
],
),
),
),
);
}
}
class ProfileAge extends StatefulWidget {
static MaterialPage page() => MaterialPage(child: ProfileAge());
@override
_ProfileAgeState createState() => _ProfileAgeState();
}
class _ProfileAgeState extends State<ProfileAge> {
int _age;
void _onComplete() {
context.flow<Profile>().complete((profile) {
return profile.copyWith(age: _age);
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(title: const Text('Profile Age')),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
onChanged: (age) => setState(() => _age = int.tryParse(age)),
decoration: InputDecoration(
labelText: 'Age',
hintText: '42',
hintStyle: TextStyle(color: theme.disabledColor),
),
),
OutlineButton(
child: const Text('Complete'),
onPressed: _age != null ? _onComplete : null,
),
],
),
),
),
);
}
}
| flutter_flows/lib/profile_flow.dart/0 | {'file_path': 'flutter_flows/lib/profile_flow.dart', 'repo_id': 'flutter_flows', 'token_count': 1540} |
import 'package:flutter/material.dart';
import 'package:flutter_generative_art/vera_molnar/animated_distorted_polygon_set.dart';
import 'package:flutter_generative_art/vera_molnar/get_started_page.dart';
import 'package:flutter_generative_art/styles/themes.dart';
import 'package:flutter_generative_art/vera_molnar/animated_distorted_polygons_grid.dart';
import 'package:flutter_generative_art/vera_molnar/distorted_polygons_grid.dart';
import 'package:flutter_generative_art/vera_molnar/distorted_polygon.dart';
import 'package:flutter_generative_art/vera_molnar/distorted_polygon_set.dart';
import 'package:flutter_generative_art/vera_molnar/randomized_recursive_squares_grid.dart';
import 'package:flutter_generative_art/vera_molnar/raw_recursive_squares_grid.dart';
import 'package:flutter_generative_art/vera_molnar/recursive_squares_grid.dart';
import 'package:flutter_generative_art/vera_molnar/square.dart';
import 'package:flutter_generative_art/vera_molnar/squares_grid.dart';
import 'package:widgetbook/widgetbook.dart';
void main() {
runApp(const WidgetbookApp());
}
class WidgetbookApp extends StatelessWidget {
const WidgetbookApp({super.key});
@override
Widget build(BuildContext context) {
return Widgetbook.material(
appBuilder: (BuildContext context, Widget child) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: AppThemes.darkTheme,
title: 'Flutter Generative Art',
home: Material(
child: child,
),
);
},
directories: [
WidgetbookFolder(
name: 'Vera Molnar',
children: [
WidgetbookCategory(
name: 'Widgets',
children: [
WidgetbookComponent(
name: 'Square',
useCases: [
WidgetbookUseCase(
name: 'Playground',
builder: (context) {
return SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: const Square(),
);
},
),
],
),
WidgetbookComponent(
name: 'SquaresGrid',
useCases: [
WidgetbookUseCase(
name: 'Playground',
builder: (context) {
return SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: const SquaresGrid(),
);
},
),
],
),
WidgetbookComponent(
name: 'RecursiveSquaresGrid',
useCases: [
WidgetbookUseCase(
name: 'Raw',
builder: (context) {
return SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: RawRecursiveSquaresGrid(
strokeWidth: context.knobs.double.slider(
label: 'Stroke Width',
initialValue: 1.5,
min: 0.5,
max: 3.5,
divisions: 6,
),
),
);
},
),
WidgetbookUseCase(
name: 'Randomized',
builder: (context) {
return SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: RandomizedRecursiveSquaresGrid(
side: context.knobs.double.slider(
label: 'Square Side Length',
initialValue: 80,
min: 30,
max: 200,
),
gap: context.knobs.double.slider(
label: 'Gap',
initialValue: 5,
min: 0,
max: 50,
divisions: 50,
),
strokeWidth: context.knobs.double.slider(
label: 'Stroke Width',
initialValue: 1.5,
min: 0.5,
max: 3.5,
divisions: 6,
),
),
);
},
),
WidgetbookUseCase(
name: 'Playground',
builder: (context) {
return SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: RecursiveSquaresGrid(
enableColors: context.knobs.boolean(
label: 'Enable Colors',
initialValue: true,
),
strokeWidth: context.knobs.double.slider(
label: 'Stroke Width',
initialValue: 1.0,
min: 0.5,
max: 3.5,
divisions: 6,
),
side: context.knobs.double.slider(
label: 'Square Side Length',
initialValue: 80,
min: 30,
max: 200,
),
gap: context.knobs.double.slider(
label: 'Gap',
initialValue: 5,
min: 5,
max: 50,
),
saturation: context.knobs.double.slider(
label: 'Saturation',
min: 0,
max: 1.0,
divisions: 10,
initialValue: 0.7,
),
lightness: context.knobs.double.slider(
label: 'Lightness',
min: 0,
max: 1.0,
divisions: 10,
initialValue: 0.5,
),
),
);
},
),
],
),
WidgetbookComponent(
name: 'DistortedPolygon',
useCases: [
WidgetbookUseCase(
name: 'Playground',
builder: (context) {
return SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: DistortedPolygon(
strokeWidth: context.knobs.double.slider(
label: 'Stroke Width',
initialValue: 2.0,
min: 0.5,
max: 3.5,
divisions: 6,
),
maxCornersOffset: context.knobs.double.slider(
label: 'Max Corners Offset',
initialValue: 20,
min: 0,
max: 100,
divisions: 100,
),
),
);
},
),
],
),
WidgetbookComponent(
name: 'DistortedPolygonSet',
useCases: [
WidgetbookUseCase(
name: 'Static',
builder: (context) {
return SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: DistortedPolygonSet(
minRepetition: context.knobs.double
.slider(
label: 'Minimum Repetition',
initialValue: 30,
min: 1,
max: 100,
divisions: 99,
)
.toInt(),
strokeWidth: context.knobs.double.slider(
label: 'Stroke Width',
initialValue: 1.5,
min: 0.5,
max: 3.5,
divisions: 6,
),
maxCornersOffset: context.knobs.double.slider(
label: 'Max Corners Offset',
initialValue: 50,
min: 0,
max: 100,
divisions: 100,
),
),
);
},
),
WidgetbookUseCase(
name: 'Animated',
builder: (context) {
return SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: AnimatedDistortedPolygonSet(
minRepetition: context.knobs.double
.slider(
label: 'Minimum Repetition',
initialValue: 30,
min: 1,
max: 50,
divisions: 49,
)
.toInt(),
strokeWidth: context.knobs.double.slider(
label: 'Stroke Width',
initialValue: 1.0,
min: 0.5,
max: 3.5,
divisions: 6,
),
maxCornersOffset: context.knobs.double.slider(
label: 'Max Corners Offset',
initialValue: 20,
min: 0,
max: 100,
divisions: 100,
),
),
);
},
),
],
),
WidgetbookComponent(
name: 'DistortedPolygonsGrid',
useCases: [
WidgetbookUseCase(
name: 'Playground',
builder: (context) {
return SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: DistortedPolygonsGrid(
enableRepetition: context.knobs.boolean(
label: 'Enable Repetition',
initialValue: true,
),
enableColors: context.knobs.boolean(
label: 'Enable Colors',
initialValue: true,
),
minRepetition: context.knobs.double
.slider(
label: 'Minimum Repetition',
initialValue: 10,
min: 1,
max: 20,
divisions: 19,
)
.toInt(),
strokeWidth: context.knobs.double.slider(
label: 'Stroke Width',
initialValue: 1.0,
min: 0.5,
max: 3.5,
divisions: 6,
),
maxSideLength: context.knobs.double.slider(
label: 'Square Side Length',
initialValue: 80,
min: 30,
max: 200,
),
gap: context.knobs.double.slider(
label: 'Gap',
initialValue: 30,
min: 5,
max: 50,
),
maxCornersOffset: context.knobs.double.slider(
label: 'Max Corners Offset',
initialValue: 5,
min: 0,
max: 30,
divisions: 30,
),
saturation: context.knobs.double.slider(
label: 'Saturation',
min: 0,
max: 1.0,
divisions: 10,
initialValue: 0.7,
),
lightness: context.knobs.double.slider(
label: 'Lightness',
min: 0,
max: 1.0,
divisions: 10,
initialValue: 0.5,
),
),
);
},
),
],
),
WidgetbookComponent(
name: 'AnimatedPolygonsGrid',
useCases: [
WidgetbookUseCase(
name: 'Playground',
builder: (context) {
return SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: AnimatedDistortedPolygonsGrid(
enableAnimation: true,
enableColors: context.knobs.boolean(
label: 'Enable Colors',
initialValue: true,
),
oneColorPerSet: context.knobs.boolean(
label: 'One Color Per Set',
initialValue: false,
),
minRepetition: context.knobs.double
.slider(
label: 'Minimum Repetition',
initialValue: 50,
min: 1,
max: 100,
divisions: 99,
)
.toInt(),
strokeWidth: context.knobs.double.slider(
label: 'Stroke Width',
initialValue: 1.0,
min: 0.5,
max: 3.5,
divisions: 6,
),
maxSideLength: context.knobs.double.slider(
label: 'Square Side Length',
initialValue: 80,
min: 30,
max: 200,
),
gap: context.knobs.double.slider(
label: 'Gap',
initialValue: 30,
min: 0,
max: 50,
),
maxCornersOffset: context.knobs.double.slider(
label: 'Max Corners Offset',
initialValue: 3,
min: 0,
max: 12,
divisions: 12,
),
saturation: context.knobs.double.slider(
label: 'Saturation',
min: 0,
max: 1.0,
divisions: 10,
initialValue: 0.5,
),
lightness: context.knobs.double.slider(
label: 'Lightness',
min: 0,
max: 1.0,
divisions: 10,
initialValue: 0.5,
),
),
);
},
),
WidgetbookUseCase(
name: 'Static',
builder: (context) {
return SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: const AnimatedDistortedPolygonsGrid(
enableColors: true,
minRepetition: 30,
),
);
},
),
WidgetbookUseCase(
name: 'Static - One Color Per Set',
builder: (context) {
return SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: const AnimatedDistortedPolygonsGrid(
enableColors: true,
oneColorPerSet: true,
saturation: 0.2,
minRepetition: 30,
),
);
},
),
],
),
],
),
WidgetbookCategory(
name: 'Pages',
children: [
WidgetbookComponent(
name: 'Get Started',
useCases: [
WidgetbookUseCase(
name: 'Playground',
builder: (context) => const GetStartedPage(),
),
],
),
],
),
],
),
// WidgetbookCategory(
// name: 'Piet Mondrian',
// children: [
// WidgetbookComponent(
// name: 'Composition',
// useCases: [
// WidgetbookUseCase(
// name: 'Random Children',
// builder: (context) => SizedBox(
// width: MediaQuery.of(context).size.width,
// height: MediaQuery.of(context).size.height,
// child: const random.MondrianComposition(),
// ),
// ),
// WidgetbookUseCase(
// name: 'Fixed Children',
// builder: (context) => SizedBox(
// width: MediaQuery.of(context).size.width,
// height: MediaQuery.of(context).size.height,
// child: MondrianComposition(
// rectanglesCount: context.knobs.double
// .slider(
// label: 'Rectangles Count',
// initialValue: 5,
// min: 3,
// max: 50,
// divisions: 49,
// )
// .toInt(),
// ),
// ),
// ),
// ],
// )
// ],
// ),
WidgetbookComponent(
name: 'Colors',
useCases: [
WidgetbookUseCase(
name: 'RGB',
builder: (context) {
return Center(
child: SizedBox(
width: 300,
height: 300,
child: ColoredBox(
color: Color.fromARGB(
context.knobs.double
.slider(
label: 'Alpha',
min: 0,
max: 255,
divisions: 255,
initialValue: 255,
)
.toInt(),
context.knobs.double
.slider(
label: 'R',
min: 0,
max: 255,
divisions: 255,
initialValue: 0,
)
.toInt(),
context.knobs.double
.slider(
label: 'G',
min: 0,
max: 255,
divisions: 255,
initialValue: 0,
)
.toInt(),
context.knobs.double
.slider(
label: 'B',
min: 0,
max: 255,
divisions: 255,
initialValue: 0,
)
.toInt(),
),
),
),
);
},
),
WidgetbookUseCase(
name: 'HSL',
builder: (context) {
return Center(
child: SizedBox(
width: 300,
height: 300,
child: ColoredBox(
color: HSLColor.fromAHSL(
context.knobs.double.slider(
label: 'Alpha',
min: 0,
max: 1.0,
divisions: 10,
initialValue: 1,
),
context.knobs.double.slider(
label: 'Hue',
min: 0,
max: 360,
divisions: 100,
initialValue: 0,
),
context.knobs.double.slider(
label: 'Saturation',
min: 0,
max: 1.0,
divisions: 10,
initialValue: 0.7,
),
context.knobs.double.slider(
label: 'Lightness',
min: 0,
max: 1.0,
divisions: 10,
initialValue: 0.5,
),
).toColor(),
),
),
);
},
),
],
),
],
);
}
}
| flutter_generative_art/lib/main.widgetbook.dart/0 | {'file_path': 'flutter_generative_art/lib/main.widgetbook.dart', 'repo_id': 'flutter_generative_art', 'token_count': 17929} |
import 'dart:math';
import 'package:flutter/material.dart';
class RandomizedRecursiveSquaresGrid extends StatelessWidget {
const RandomizedRecursiveSquaresGrid({
super.key,
this.side = 80,
this.strokeWidth = 2,
this.gap = 5,
this.minSquareSideFraction = 0.2,
});
final double side;
final double strokeWidth;
final double gap;
final double minSquareSideFraction;
@override
Widget build(BuildContext context) {
return ColoredBox(
color: Colors.white,
child: SizedBox.expand(
child: CustomPaint(
painter: _RecursiveSquaresCustomPainter(
sideLength: side,
strokeWidth: strokeWidth,
gap: gap,
minSquareSideFraction: minSquareSideFraction,
),
),
),
);
}
}
class _RecursiveSquaresCustomPainter extends CustomPainter {
_RecursiveSquaresCustomPainter({
this.sideLength = 80,
this.strokeWidth = 2,
this.gap = 10,
this.minSquareSideFraction = 0.2,
}) : minSideLength = sideLength * minSquareSideFraction;
final double sideLength;
final double strokeWidth;
final double gap;
final double minSideLength;
final double minSquareSideFraction;
static final Random random = Random();
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..style = PaintingStyle.stroke
..strokeWidth = strokeWidth;
// Calculate the number of squares that can fit on the horizontal axis
final xCount = ((size.width + gap) / (sideLength + gap)).floor();
// Calculate the number of squares that can fit on the vertical axis
final yCount = ((size.height + gap) / (sideLength + gap)).floor();
// Calculate the size of the grid of squares
final contentSize = Size(
(xCount * sideLength) + ((xCount - 1) * gap),
(yCount * sideLength) + ((yCount - 1) * gap),
);
// Calculate the offset from which we should start painting
// the grid so that it is eventually centered
final offset = Offset(
(size.width - contentSize.width) / 2,
(size.height - contentSize.height) / 2,
);
final totalCount = xCount * yCount;
canvas.save();
canvas.translate(offset.dx, offset.dy);
// Introduced a randomized `depth` value that will randomize
// the side length of the smallest square
final depth = random.nextInt(5) + 5;
for (int index = 0; index < totalCount; index++) {
int i = index ~/ yCount;
int j = index % yCount;
// Recursively draw squares
drawNestedSquares(
canvas,
Offset(
(i * (sideLength + gap)),
(j * (sideLength + gap)),
),
sideLength,
paint,
depth,
);
}
canvas.restore();
}
void drawNestedSquares(
Canvas canvas,
Offset start,
double sideLength,
Paint paint,
int depth,
) {
// Recursively draw squares until the side of the square
// reaches the minimum defined by the `minSideLength` input
// Or until the `depth` reaches 0
if (sideLength < minSideLength || depth <= 0) return;
canvas.drawRect(
Rect.fromLTWH(
start.dx,
start.dy,
sideLength,
sideLength,
),
paint,
);
// calculate the side length for the next square randomly
final nextSideLength = sideLength * (random.nextDouble() * 0.5 + 0.5);
final nextStart = Offset(
start.dx + sideLength / 2 - nextSideLength / 2,
start.dy + sideLength / 2 - nextSideLength / 2,
);
// recursive call with the next side length, starting point & `depth`
drawNestedSquares(canvas, nextStart, nextSideLength, paint, depth - 1);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
| flutter_generative_art/lib/vera_molnar/randomized_recursive_squares_grid.dart/0 | {'file_path': 'flutter_generative_art/lib/vera_molnar/randomized_recursive_squares_grid.dart', 'repo_id': 'flutter_generative_art', 'token_count': 1430} |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'redux.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
class _$AppState extends AppState {
@override
final bool isFetchingPlanets;
@override
final String? errorFetchingPlanets;
@override
final PlanetPageModel planetPage;
factory _$AppState([void Function(AppStateBuilder)? updates]) =>
(new AppStateBuilder()..update(updates))._build();
_$AppState._(
{required this.isFetchingPlanets,
this.errorFetchingPlanets,
required this.planetPage})
: super._() {
BuiltValueNullFieldError.checkNotNull(
isFetchingPlanets, r'AppState', 'isFetchingPlanets');
BuiltValueNullFieldError.checkNotNull(
planetPage, r'AppState', 'planetPage');
}
@override
AppState rebuild(void Function(AppStateBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
AppStateBuilder toBuilder() => new AppStateBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is AppState &&
isFetchingPlanets == other.isFetchingPlanets &&
errorFetchingPlanets == other.errorFetchingPlanets &&
planetPage == other.planetPage;
}
@override
int get hashCode {
var _$hash = 0;
_$hash = $jc(_$hash, isFetchingPlanets.hashCode);
_$hash = $jc(_$hash, errorFetchingPlanets.hashCode);
_$hash = $jc(_$hash, planetPage.hashCode);
_$hash = $jf(_$hash);
return _$hash;
}
@override
String toString() {
return (newBuiltValueToStringHelper(r'AppState')
..add('isFetchingPlanets', isFetchingPlanets)
..add('errorFetchingPlanets', errorFetchingPlanets)
..add('planetPage', planetPage))
.toString();
}
}
class AppStateBuilder implements Builder<AppState, AppStateBuilder> {
_$AppState? _$v;
bool? _isFetchingPlanets;
bool? get isFetchingPlanets => _$this._isFetchingPlanets;
set isFetchingPlanets(bool? isFetchingPlanets) =>
_$this._isFetchingPlanets = isFetchingPlanets;
String? _errorFetchingPlanets;
String? get errorFetchingPlanets => _$this._errorFetchingPlanets;
set errorFetchingPlanets(String? errorFetchingPlanets) =>
_$this._errorFetchingPlanets = errorFetchingPlanets;
PlanetPageModelBuilder? _planetPage;
PlanetPageModelBuilder get planetPage =>
_$this._planetPage ??= new PlanetPageModelBuilder();
set planetPage(PlanetPageModelBuilder? planetPage) =>
_$this._planetPage = planetPage;
AppStateBuilder();
AppStateBuilder get _$this {
final $v = _$v;
if ($v != null) {
_isFetchingPlanets = $v.isFetchingPlanets;
_errorFetchingPlanets = $v.errorFetchingPlanets;
_planetPage = $v.planetPage.toBuilder();
_$v = null;
}
return this;
}
@override
void replace(AppState other) {
ArgumentError.checkNotNull(other, 'other');
_$v = other as _$AppState;
}
@override
void update(void Function(AppStateBuilder)? updates) {
if (updates != null) updates(this);
}
@override
AppState build() => _build();
_$AppState _build() {
_$AppState _$result;
try {
_$result = _$v ??
new _$AppState._(
isFetchingPlanets: BuiltValueNullFieldError.checkNotNull(
isFetchingPlanets, r'AppState', 'isFetchingPlanets'),
errorFetchingPlanets: errorFetchingPlanets,
planetPage: planetPage.build());
} catch (_) {
late String _$failedField;
try {
_$failedField = 'planetPage';
planetPage.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
r'AppState', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: deprecated_member_use_from_same_package,type=lint
| flutter_hooks/packages/flutter_hooks/example/lib/star_wars/redux.g.dart/0 | {'file_path': 'flutter_hooks/packages/flutter_hooks/example/lib/star_wars/redux.g.dart', 'repo_id': 'flutter_hooks', 'token_count': 1549} |
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'
show
Brightness,
ExpansionTileController,
MaterialState,
MaterialStatesController,
SearchController,
TabController;
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
import 'framework.dart';
part 'animation.dart';
part 'async.dart';
part 'expansion_tile_controller.dart';
part 'focus_node.dart';
part 'focus_scope_node.dart';
part 'keep_alive.dart';
part 'listenable.dart';
part 'listenable_selector.dart';
part 'misc.dart';
part 'page_controller.dart';
part 'platform_brightness.dart';
part 'primitives.dart';
part 'scroll_controller.dart';
part 'search_controller.dart';
part 'tab_controller.dart';
part 'text_controller.dart';
part 'transformation_controller.dart';
part 'widgets_binding_observer.dart';
part 'material_states_controller.dart';
part 'debounced.dart';
| flutter_hooks/packages/flutter_hooks/lib/src/hooks.dart/0 | {'file_path': 'flutter_hooks/packages/flutter_hooks/lib/src/hooks.dart', 'repo_id': 'flutter_hooks', 'token_count': 357} |
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() {
testWidgets('debugFillProperties', (tester) async {
await tester.pumpWidget(
HookBuilder(builder: (context) {
useExpansionTileController();
return const SizedBox();
}),
);
await tester.pump();
final element = tester.element(find.byType(HookBuilder));
expect(
element
.toDiagnosticsNode(style: DiagnosticsTreeStyle.offstage)
.toStringDeep(),
equalsIgnoringHashCodes(
'HookBuilder\n'
" │ useExpansionTileController: Instance of 'ExpansionTileController'\n"
' └SizedBox(renderObject: RenderConstrainedBox#00000)\n',
),
);
});
group('useExpansionTileController', () {
testWidgets('initial values matches with real constructor', (tester) async {
late ExpansionTileController controller;
final controller2 = ExpansionTileController();
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: HookBuilder(builder: (context) {
controller = useExpansionTileController();
return Column(
children: [
ExpansionTile(
controller: controller,
title: const Text('Expansion Tile'),
),
ExpansionTile(
controller: controller2,
title: const Text('Expansion Tile 2'),
),
],
);
}),
),
));
expect(controller, isA<ExpansionTileController>());
expect(controller.isExpanded, controller2.isExpanded);
});
testWidgets('check expansion/collapse of tile', (tester) async {
late ExpansionTileController controller;
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: HookBuilder(builder: (context) {
controller = useExpansionTileController();
return ExpansionTile(
controller: controller,
title: const Text('Expansion Tile'),
);
}),
),
));
expect(controller.isExpanded, false);
controller.expand();
expect(controller.isExpanded, true);
controller.collapse();
expect(controller.isExpanded, false);
});
});
}
| flutter_hooks/packages/flutter_hooks/test/use_expansion_tile_controller_test.dart/0 | {'file_path': 'flutter_hooks/packages/flutter_hooks/test/use_expansion_tile_controller_test.dart', 'repo_id': 'flutter_hooks', 'token_count': 1073} |
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'mock.dart';
void main() {
testWidgets('debugFillProperties', (tester) async {
await tester.pumpWidget(
HookBuilder(builder: (context) {
useStreamController<int>();
return const SizedBox();
}),
);
await tester.pump();
final element = tester.element(find.byType(HookBuilder));
expect(
element
.toDiagnosticsNode(style: DiagnosticsTreeStyle.offstage)
.toStringDeep(),
equalsIgnoringHashCodes(
'HookBuilder\n'
' │ useStreamController: Instance of\n'
// ignore: avoid_escaping_inner_quotes
' │ \'_AsyncBroadcastStreamController<int>\'\n'
' └SizedBox(renderObject: RenderConstrainedBox#00000)\n',
),
);
});
group('useStreamController', () {
testWidgets('keys', (tester) async {
late StreamController<int> controller;
await tester.pumpWidget(HookBuilder(builder: (context) {
controller = useStreamController();
return Container();
}));
final previous = controller;
await tester.pumpWidget(HookBuilder(builder: (context) {
controller = useStreamController(keys: []);
return Container();
}));
expect(previous, isNot(controller));
});
testWidgets('basics', (tester) async {
late StreamController<int> controller;
await tester.pumpWidget(HookBuilder(builder: (context) {
controller = useStreamController();
return Container();
}));
expect(
controller,
isNot(isInstanceOf<SynchronousStreamController<Object?>>()),
);
expect(controller.onListen, isNull);
expect(controller.onCancel, isNull);
expect(() => controller.onPause, throwsUnsupportedError);
expect(() => controller.onResume, throwsUnsupportedError);
final previousController = controller;
void onListen() {}
void onCancel() {}
await tester.pumpWidget(HookBuilder(builder: (context) {
controller = useStreamController(
sync: true,
onCancel: onCancel,
onListen: onListen,
);
return Container();
}));
expect(controller, previousController);
expect(
controller,
isNot(isInstanceOf<SynchronousStreamController<Object?>>()),
);
expect(controller.onListen, onListen);
expect(controller.onCancel, onCancel);
expect(() => controller.onPause, throwsUnsupportedError);
expect(() => controller.onResume, throwsUnsupportedError);
await tester.pumpWidget(Container());
expect(controller.isClosed, true);
});
testWidgets('sync', (tester) async {
late StreamController<int> controller;
await tester.pumpWidget(HookBuilder(builder: (context) {
controller = useStreamController(sync: true);
return Container();
}));
expect(controller, isInstanceOf<SynchronousStreamController<Object?>>());
expect(controller.onListen, isNull);
expect(controller.onCancel, isNull);
expect(() => controller.onPause, throwsUnsupportedError);
expect(() => controller.onResume, throwsUnsupportedError);
final previousController = controller;
void onListen() {}
void onCancel() {}
await tester.pumpWidget(HookBuilder(builder: (context) {
controller = useStreamController(
onCancel: onCancel,
onListen: onListen,
);
return Container();
}));
expect(controller, previousController);
expect(controller, isInstanceOf<SynchronousStreamController<Object?>>());
expect(controller.onListen, onListen);
expect(controller.onCancel, onCancel);
expect(() => controller.onPause, throwsUnsupportedError);
expect(() => controller.onResume, throwsUnsupportedError);
await tester.pumpWidget(Container());
expect(controller.isClosed, true);
});
});
}
| flutter_hooks/packages/flutter_hooks/test/use_stream_controller_test.dart/0 | {'file_path': 'flutter_hooks/packages/flutter_hooks/test/use_stream_controller_test.dart', 'repo_id': 'flutter_hooks', 'token_count': 1589} |
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:reddit_repository/reddit_repository.dart';
import 'package:flutter_hub/reddit_search_bloc/bloc.dart';
class NewsSearch extends StatefulWidget {
@override
_NewsSearchState createState() => _NewsSearchState();
}
class _NewsSearchState extends State<NewsSearch>
with AutomaticKeepAliveClientMixin {
final _scrollController = ScrollController();
final _scrollThreshold = 200.0;
RedditSearchBloc _searchBloc;
@override
void initState() {
super.initState();
_scrollController.addListener(_onScroll);
_searchBloc = BlocProvider.of<RedditSearchBloc>(context);
_searchBloc.dispatch(FetchArticles());
}
@override
Widget build(BuildContext context) {
super.build(context);
return BlocBuilder<RedditSearchEvent, RedditSearchState>(
bloc: BlocProvider.of<RedditSearchBloc>(context),
builder: (BuildContext context, RedditSearchState state) {
if (state is SearchStateLoading) {
return Center(child: CircularProgressIndicator());
}
if (state is SearchStateError) {
return Center(child: Text(state.error));
}
if (state is SearchStateSuccess) {
return state.items.isEmpty
? Center(child: Text('No Results'))
: _SearchResults(
items: state.items,
scrollController: _scrollController,
);
}
},
);
}
void _onScroll() {
final maxScroll = _scrollController.position.maxScrollExtent;
final currentScroll = _scrollController.position.pixels;
if (maxScroll - currentScroll <= _scrollThreshold) {
print('dispatching Fetch');
_searchBloc.dispatch(FetchArticles());
}
}
@override
bool get wantKeepAlive => true;
}
class _SearchResults extends StatelessWidget {
final List<Article> items;
final ScrollController scrollController;
const _SearchResults({
Key key,
this.items,
this.scrollController,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final state = BlocProvider.of<RedditSearchBloc>(context).currentState
as SearchStateSuccess;
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
return index >= state.items.length
? BottomLoader()
: _SearchResultItem(item: items[index]);
},
itemCount:
state.hasReachedMax ? state.items.length : state.items.length + 1,
controller: scrollController,
);
}
}
class BottomLoader extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
child: Center(
child: SizedBox(
width: 33,
height: 33,
child: CircularProgressIndicator(
strokeWidth: 1.5,
),
),
),
);
}
}
class _SearchResultItem extends StatelessWidget {
final Article item;
const _SearchResultItem({Key key, @required this.item}) : super(key: key);
@override
Widget build(BuildContext context) {
print('item $item');
return ListTile(
leading: CircleAvatar(
backgroundColor: Colors.transparent,
child: _thumbnail(item.thumbnail),
),
title: Text(
item.title,
style: TextStyle(
fontWeight: FontWeight.bold,
color: Theme.of(context).primaryColor,
),
),
subtitle: Text(item.author),
dense: true,
onTap: () async {
if (await canLaunch(item.url)) {
await launch(item.url);
}
},
);
}
Widget _thumbnail(String url) {
if (url.contains('http')) {
return Image.network(url);
}
return Image.network(
'https://logodix.com/logo/576948.png');
}
}
| flutter_hub/lib/news_search/news_search_screen.dart/0 | {'file_path': 'flutter_hub/lib/news_search/news_search_screen.dart', 'repo_id': 'flutter_hub', 'token_count': 1588} |
class SearchResultError {}
| flutter_hub/reddit_repository/lib/src/models/search_result_error.dart/0 | {'file_path': 'flutter_hub/reddit_repository/lib/src/models/search_result_error.dart', 'repo_id': 'flutter_hub', 'token_count': 6} |
import 'package:flutter/material.dart';
import 'keyboard_actions.dart';
/// Wrapper for a single configuration of the keyboard actions bar.
class KeyboardActionsConfig {
/// Keyboard Action for specific platform
/// KeyboardActionsPlatform : ANDROID , IOS , ALL
final KeyboardActionsPlatform keyboardActionsPlatform;
/// true to display arrows prev/next to move focus between inputs
final bool nextFocus;
/// [KeyboardActionsItem] for each input
final List<KeyboardActionsItem>? actions;
/// Color of the background to the Custom keyboard buttons
final Color? keyboardBarColor;
/// Elevation of the Custom keyboard buttons
final double? keyboardBarElevation;
/// Color of the line separator between keyboard and content
final Color keyboardSeparatorColor;
/// A [Widget] to be optionally used instead of the "Done" button
/// which dismisses the keyboard.
final Widget? defaultDoneWidget;
const KeyboardActionsConfig({
this.keyboardActionsPlatform = KeyboardActionsPlatform.ALL,
this.nextFocus = true,
this.actions,
this.keyboardBarColor,
this.keyboardBarElevation,
this.keyboardSeparatorColor = Colors.transparent,
this.defaultDoneWidget,
});
}
| flutter_keyboard_actions/lib/keyboard_actions_config.dart/0 | {'file_path': 'flutter_keyboard_actions/lib/keyboard_actions_config.dart', 'repo_id': 'flutter_keyboard_actions', 'token_count': 336} |
class InvalidAndroidIconNameException implements Exception {
final String message;
const InvalidAndroidIconNameException([this.message]);
@override
String toString() {
return '*** ERROR ***\n'
'InvalidAndroidIconNameException\n'
'$message';
}
}
class InvalidConfigException implements Exception {
final String message;
const InvalidConfigException([this.message]);
@override
String toString() {
return '*** ERROR ***\n'
'InvalidConfigException\n'
'$message';
}
}
class NoConfigFoundException implements Exception {
final String message;
const NoConfigFoundException([this.message]);
@override
String toString() {
return '*** ERROR ***\n'
'NoConfigFoundException\n'
'$message';
}
}
| flutter_launcher_icons/lib/custom_exceptions.dart/0 | {'file_path': 'flutter_launcher_icons/lib/custom_exceptions.dart', 'repo_id': 'flutter_launcher_icons', 'token_count': 254} |
library flutter_load_kit;
export 'src/loadkit_spinning_arcs.dart';
export 'src/loadkit_360.dart';
export 'src/loadkit_pulse_lines.dart';
export 'src/loadkit_rotating_lines.dart';
export 'src/loadkit_rotation_arcs.dart';
export 'src/loadkit_scaling_wave.dart';
export 'src/loadkit_folding_squares.dart';
export 'src/loadkit_filled_circle.dart';
export 'src/loadkit_water_droplet.dart';
export 'src/loadkit_line_chase.dart';
| flutter_loadkit/lib/flutter_load_kit.dart/0 | {'file_path': 'flutter_loadkit/lib/flutter_load_kit.dart', 'repo_id': 'flutter_loadkit', 'token_count': 169} |
import 'package:flutter_test/flutter_test.dart';
void main() {
test('adds one to input values', () {});
}
| flutter_loadkit/test/flutter_load_kit_test.dart/0 | {'file_path': 'flutter_loadkit/test/flutter_load_kit_test.dart', 'repo_id': 'flutter_loadkit', 'token_count': 40} |
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_playlist_animation/pages/library_page.dart';
import 'package:flutter_playlist_animation/utils/library_data.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _isInit = true;
@override
void didChangeDependencies() {
if (_isInit) {
for (String image in LibraryData.playlistImages) {
precacheImage(Image.asset(image).image, context);
}
}
_isInit = false;
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
return MaterialApp(
title: 'Flutter Playlist Animation',
debugShowCheckedModeBanner: false,
theme: ThemeData(
fontFamily: 'Rubik',
scaffoldBackgroundColor: Colors.white,
appBarTheme: const AppBarTheme(
backgroundColor: Colors.transparent,
iconTheme: IconThemeData(color: Colors.black),
systemOverlayStyle: SystemUiOverlayStyle.dark,
titleTextStyle: TextStyle(
color: Colors.black,
fontSize: 18,
fontFamily: 'Rubik',
),
elevation: 0,
),
primarySwatch: Colors.blue,
),
home: const LibraryPage(),
);
}
}
| flutter_playlist_animation/lib/main.dart/0 | {'file_path': 'flutter_playlist_animation/lib/main.dart', 'repo_id': 'flutter_playlist_animation', 'token_count': 613} |
import 'package:flutter/material.dart';
import 'package:flutter_playlist_animation/utils/animation_manager.dart';
Route createFadeInRoute({required RoutePageBuilder routePageBuilder}) {
return PageRouteBuilder(
transitionDuration: AnimationManager.routeTransitionDuration,
reverseTransitionDuration: AnimationManager.routeTransitionDuration,
pageBuilder: routePageBuilder,
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
return FadeTransition(
opacity: animation,
child: child,
);
},
);
}
| flutter_playlist_animation/lib/utils/page_transitions.dart/0 | {'file_path': 'flutter_playlist_animation/lib/utils/page_transitions.dart', 'repo_id': 'flutter_playlist_animation', 'token_count': 217} |
name: skt_map_bug
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
skt:
path: ./skt-maps
flutter:
uses-material-design: true | flutter_skt_map_bug/pubspec.yaml/0 | {'file_path': 'flutter_skt_map_bug/pubspec.yaml', 'repo_id': 'flutter_skt_map_bug', 'token_count': 101} |
name: skt
description: A new flutter plugin project.
version: 0.0.1
environment:
sdk: ">=2.2.2 <3.0.0"
dependencies:
flutter:
sdk: flutter
flutter:
plugin:
androidPackage: com.mobileconnected.skt
pluginClass: SktPlugin
| flutter_skt_map_bug/skt-maps/pubspec.yaml/0 | {'file_path': 'flutter_skt_map_bug/skt-maps/pubspec.yaml', 'repo_id': 'flutter_skt_map_bug', 'token_count': 99} |
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('PouringHourglass', () {
testWidgets('works with color', (WidgetTester tester) async {
await tester.pumpWidget(
createMaterialApp(
const SpinKitPouringHourGlass(color: Colors.white),
),
);
expect(find.byType(SpinKitPouringHourGlass), findsOneWidget);
expect(find.byType(CustomPaint), findsWidgets);
tester.verifyTickersWereDisposed();
});
testWidgets('works without Material', (WidgetTester tester) async {
await tester.pumpWidget(
createWidgetsApp(const SpinKitPouringHourGlass(color: Colors.white)),
);
expect(find.byType(SpinKitPouringHourGlass), findsOneWidget);
expect(find.byType(CustomPaint), findsWidgets);
tester.verifyTickersWereDisposed();
});
});
}
| flutter_spinkit/test/pouring_hour_glass_test.dart/0 | {'file_path': 'flutter_spinkit/test/pouring_hour_glass_test.dart', 'repo_id': 'flutter_spinkit', 'token_count': 382} |
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('Wave', () {
testWidgets(
'needs either color or itemBuilder',
(WidgetTester tester) async {
expect(() => SpinKitWave(), throwsAssertionError);
expect(
() => SpinKitWave(color: Colors.white, itemBuilder: fakeBoxBuilder),
throwsAssertionError,
);
},
);
testWidgets('needs color to be non-null', (WidgetTester tester) async {
expect(() => SpinKitWave(color: null), throwsAssertionError);
});
testWidgets(
'needs itemBuilder to be non-null',
(WidgetTester tester) async {
expect(() => SpinKitWave(itemBuilder: null), throwsAssertionError);
},
);
testWidgets('works with color', (WidgetTester tester) async {
await tester.pumpWidget(
createMaterialApp(const SpinKitWave(color: Colors.white)),
);
expect(find.byType(SpinKitWave), findsOneWidget);
expect(find.byType(DecoratedBox), findsWidgets);
tester.verifyTickersWereDisposed();
});
testWidgets('works with itemBuilder', (WidgetTester tester) async {
await tester.pumpWidget(
createMaterialApp(const SpinKitWave(itemBuilder: fakeBoxBuilder)),
);
expect(find.byType(SpinKitWave), findsOneWidget);
expect(find.byType(FakeBox), findsWidgets);
tester.verifyTickersWereDisposed();
});
group('works with types', () {
testWidgets('on center', (WidgetTester tester) async {
await tester.pumpWidget(
createMaterialApp(
const SpinKitWave(
color: Colors.white,
type: SpinKitWaveType.center,
),
),
);
expect(find.byType(SpinKitWave), findsOneWidget);
expect(find.byType(DecoratedBox), findsWidgets);
tester.verifyTickersWereDisposed();
});
testWidgets('on start', (WidgetTester tester) async {
await tester.pumpWidget(
createMaterialApp(
const SpinKitWave(
color: Colors.white,
type: SpinKitWaveType.start,
),
),
);
expect(find.byType(SpinKitWave), findsOneWidget);
expect(find.byType(DecoratedBox), findsWidgets);
tester.verifyTickersWereDisposed();
});
testWidgets('on end', (WidgetTester tester) async {
await tester.pumpWidget(
createMaterialApp(
const SpinKitWave(color: Colors.white, type: SpinKitWaveType.end),
),
);
expect(find.byType(SpinKitWave), findsOneWidget);
expect(find.byType(DecoratedBox), findsWidgets);
tester.verifyTickersWereDisposed();
});
});
testWidgets('works without Material', (WidgetTester tester) async {
await tester.pumpWidget(
createWidgetsApp(const SpinKitWave(color: Colors.white)),
);
expect(find.byType(SpinKitWave), findsOneWidget);
expect(find.byType(DecoratedBox), findsWidgets);
tester.verifyTickersWereDisposed();
});
});
}
| flutter_spinkit/test/wave_test.dart/0 | {'file_path': 'flutter_spinkit/test/wave_test.dart', 'repo_id': 'flutter_spinkit', 'token_count': 1392} |
part of 'rx.dart';
/// {@template rx_list}
/// A reactive list that extends the functionality of a regular Dart list
/// and notifies its listeners when the list is modified.
///
/// The `RxList` class provides a convenient way to create and manage a
/// list of elements that can be observed for changes. It extends the
/// `ListMixin` class to provide an implementation of the `List` interface
/// and adds reactive behavior by notifying listeners whenever the list is
/// modified.
///
/// Example usage:
///
/// ```dart
/// final numberList = RxList<int>();
///
/// // Adding a listener to the list
/// numberList.addListener(() {
/// print('List changed: $numberList');
/// });
///
/// // Modifying the list
/// numberList.add(1); // This will trigger the listener and print the updated list.
/// numberList.addAll([2, 3, 4]);
///
/// // Accessing the elements
/// print(numberList[0]); // Output: 1
///
/// // Removing an element
/// numberList.remove(3);
/// ```
///
/// **Note:** When using the `RxList` class, it is important to call the
/// `dispose()` method on the object when it is no longer needed to
/// prevent memory leaks.
/// This can be done using the onDisable method of your controller.
/// {@endtemplate}
final class RxList<T> extends Rx with ListMixin<T> {
/// {@macro rx_list}
RxList([List<T>? list]) {
if (kFlutterMemoryAllocationsEnabled && !_creationDispatched) {
MemoryAllocations.instance.dispatchObjectCreated(
library: 'package:flutter/foundation.dart',
className: '$RxList',
object: this,
);
_creationDispatched = true;
}
if (list != null) {
_list = list;
} else {
_list = [];
}
}
late List<T> _list;
@override
int get length {
return _list.length;
}
@override
T get first {
return _list.first;
}
@override
T get last {
return _list.last;
}
@override
Iterable<T> get reversed {
return _list.reversed;
}
@override
bool get isEmpty {
return _list.isEmpty;
}
@override
bool get isNotEmpty {
return _list.isNotEmpty;
}
@override
Iterator<T> get iterator {
return _list.iterator;
}
@override
T get single {
return _list.single;
}
@override
Iterable<T> getRange(int start, int end) {
return _list.getRange(start, end);
}
@override
void replaceRange(int start, int end, Iterable<T> newContents) {
_list.replaceRange(start, end, newContents);
_notifyListeners();
}
@override
void setRange(int start, int end, Iterable<T> iterable, [int skipCount = 0]) {
_list.setRange(start, end, iterable, skipCount);
_notifyListeners();
}
@override
void fillRange(int start, int end, [T? fill]) {
_list.fillRange(start, end, fill);
_notifyListeners();
}
@override
void add(T element) {
_list.add(element);
_notifyListeners();
}
@override
void addAll(Iterable<T> iterable) {
_list.addAll(iterable);
_notifyListeners();
}
@override
bool remove(covariant T element) {
final removed = _list.remove(element);
if (removed) {
_notifyListeners();
}
return removed;
}
@override
T removeAt(int index) {
final removed = _list.removeAt(index);
_notifyListeners();
return removed;
}
@override
T removeLast() {
final removed = _list.removeLast();
_notifyListeners();
return removed;
}
@override
void removeRange(int start, int end) {
_list.removeRange(start, end);
_notifyListeners();
}
@override
void removeWhere(bool Function(T) test) {
_list.removeWhere(test);
_notifyListeners();
}
@override
void insert(int index, T element) {
_list.insert(index, element);
_notifyListeners();
}
@override
void insertAll(int index, Iterable<T> iterable) {
_list.insertAll(index, iterable);
_notifyListeners();
}
@override
void setAll(int index, Iterable<T> iterable) {
_list.setAll(index, iterable);
_notifyListeners();
}
@override
void shuffle([Random? random]) {
_list.shuffle(random);
_notifyListeners();
}
@override
void sort([int Function(T, T)? compare]) {
_list.sort(compare);
_notifyListeners();
}
@override
List<T> sublist(int start, [int? end]) {
return _list.sublist(start, end);
}
@override
T singleWhere(bool Function(T) test, {T Function()? orElse}) {
return _list.singleWhere(test, orElse: orElse);
}
@override
Iterable<T> skip(int count) {
return _list.skip(count);
}
@override
Iterable<T> skipWhile(bool Function(T) test) {
return _list.skipWhile(test);
}
@override
void forEach(void Function(T) action) {
_list.forEach(action);
}
@override
void clear() {
_list.clear();
_notifyListeners();
}
/// Creates an `RxList` from an existing list.
///
/// The `list` argument represents an existing list from which an
/// `RxList` instance is created. The elements of the `list` are
/// copied to the `RxList`, and any modifications made to the `RxList`
/// will not affect the original `list`.
///
/// Example:
///
/// ```dart
/// final existingList = [1, 2, 3];
/// final rxList = RxList<int>.of(existingList);
/// ```
static RxList<T> of<T>(List<T> list) => RxList<T>(list);
@override
List<T> operator +(List<T> other) {
final newList = _list + other;
return newList;
}
@override
T operator [](int index) {
return _list[index];
}
@override
void operator []=(int index, T value) {
_list[index] = value;
_notifyListeners();
}
@override
set length(int value) {
_list.length = value;
_notifyListeners();
}
}
| flutter_super/lib/src/rx/rx_list.dart/0 | {'file_path': 'flutter_super/lib/src/rx/rx_list.dart', 'repo_id': 'flutter_super', 'token_count': 2097} |
// ignore_for_file: cascade_invocations
import 'package:flutter/widgets.dart';
import 'package:flutter_super/flutter_super.dart';
import 'package:flutter_test/flutter_test.dart';
class MyController extends SuperController {
bool onEnableCalled = false;
bool onAliveCalled = false;
bool onDisableCalled = false;
@override
void onAlive() {
onAliveCalled = true;
}
@override
void onEnable() {
super.onEnable();
onEnableCalled = true;
}
@override
void onDisable() {
super.onDisable();
onDisableCalled = true;
}
}
void main() {
group('SuperController', () {
setUp(TestWidgetsFlutterBinding.ensureInitialized);
test('start() should initialize the controller', () {
final controller = MyController();
expect(controller.alive, false);
controller.start();
expect(controller.alive, true);
});
test('start() should call onEnable()', () {
final controller = MyController();
expect(controller.onEnableCalled, false);
controller.start();
expect(controller.onEnableCalled, true);
});
test('stop() should disable the controller', () {
final controller = MyController();
controller.start();
expect(controller.alive, true);
expect(controller.onDisableCalled, false);
controller.stop();
expect(controller.alive, false);
expect(controller.onDisableCalled, true);
});
test('onEnable() should call onAlive() in the next frame', () {
final controller = MyController();
controller.start();
expect(controller.onAliveCalled, false);
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
expect(controller.onAliveCalled, true);
});
});
test('onDisable() should delete the controller instance', () {
final controller = MyController();
expect(
() => Super.of<MyController>(),
throwsA(isA<FlutterError>()),
);
controller
..start()
..stop();
expect(
() => Super.of<MyController>(),
throwsA(isA<FlutterError>()),
);
});
});
}
| flutter_super/test/src/controller_test.dart/0 | {'file_path': 'flutter_super/test/src/controller_test.dart', 'repo_id': 'flutter_super', 'token_count': 794} |
// ignore_for_file: invalid_use_of_protected_member
import 'package:flutter/material.dart';
import 'package:flutter_super/flutter_super.dart';
import 'package:flutter_super/src/core/logger.dart';
import 'package:flutter_test/flutter_test.dart';
class CounterNotifier extends RxNotifier<int> {
@override
int watch() {
return 0; // Initial state
}
}
void main() {
group('SuperConsumer', () {
testWidgets('Calls builder function with initial value',
(WidgetTester tester) async {
final rx = RxT<int>(7);
await tester.pumpWidget(
MaterialApp(
home: SuperConsumer<int>(
rx: rx,
builder: (context, state) => Text('Value: $state'),
),
),
);
// Verify that the builder function is called with the initial value
expect(find.text('Value: 7'), findsOneWidget);
});
testWidgets('Calls builder function with initial RxNotidier value',
(WidgetTester tester) async {
final rx = CounterNotifier();
await tester.pumpWidget(
MaterialApp(
home: SuperConsumer<int>(
rx: rx,
builder: (context, state) => Text('Value: $state'),
),
),
);
Super.log('Value: 0', logType: LogType.success);
// Verify that the builder function is called with the initial value
expect(find.text('Value: 0'), findsOneWidget);
});
testWidgets('Calls builder function with updated value',
(WidgetTester tester) async {
final rx = RxT<int>(7);
await tester.pumpWidget(
MaterialApp(
home: SuperConsumer<int>(
rx: rx,
builder: (context, state) => Text('Value: $state'),
),
),
);
// Update the rx value
rx.value = 84;
// Rebuild the widget
await tester.pump();
// Verify that the builder function is called with the updated value
expect(find.text('Value: 84'), findsOneWidget);
});
testWidgets('Calls builder function when rx changes',
(WidgetTester tester) async {
final rx1 = RxT<int>(7);
final rx2 = RxT<int>(84);
await tester.pumpWidget(
MaterialApp(
home: SuperConsumer<int>(
rx: rx1,
builder: (context, state) => Text('Value: $state'),
),
),
);
// Verify that the builder function is called with rx1 initial value
expect(find.text('Value: 7'), findsOneWidget);
// Update the rx to use rx2
await tester.pumpWidget(
MaterialApp(
home: SuperConsumer<int>(
rx: rx2,
builder: (context, state) => Text('Value: $state'),
),
),
);
// Verify that the builder function is called with rx2 initial value
expect(find.text('Value: 84'), findsOneWidget);
});
testWidgets('Disposes the listener when widget is disposed',
(WidgetTester tester) async {
final rx = RxT<int>(7);
await tester.pumpWidget(
MaterialApp(
home: SuperConsumer<int>(
rx: rx,
builder: (context, state) => Text('Value: $state'),
),
),
);
// Verify that the listener is active initially
expect(rx.hasListeners, isTrue);
// Dispose the widget
await tester.pumpWidget(Container());
// Verify that the listener is disposed
expect(rx.hasListeners, isFalse);
});
});
}
| flutter_super/test/src/widgets/super_consumer_test.dart/0 | {'file_path': 'flutter_super/test/src/widgets/super_consumer_test.dart', 'repo_id': 'flutter_super', 'token_count': 1504} |
import 'package:equatable/equatable.dart';
import 'package:flutter_todos/models/models.dart';
abstract class FilteredTodosEvent extends Equatable {
const FilteredTodosEvent();
@override
List<Object> get props => [];
}
class TodosUpdated extends FilteredTodosEvent {
final List<Todo> todos;
const TodosUpdated(this.todos);
@override
List<Object> get props => [todos];
@override
String toString() => 'TodosUpdated { todos: $todos }';
}
class FilterUpdated extends FilteredTodosEvent {
final VisibilityFilter filter;
const FilterUpdated(this.filter);
@override
List<Object> get props => [filter];
@override
String toString() => 'FilterUpdated { filter: $filter }';
}
class ActiveTodoChanged extends FilteredTodosEvent {
final String todoId;
const ActiveTodoChanged(this.todoId);
@override
List<Object> get props => [todoId];
@override
String toString() => 'ActiveTodoChanged { todoId: $todoId }';
}
class ActiveTodoToggled extends FilteredTodosEvent {}
| flutter_todos/lib/blocs/filtered_todos/filtered_todos_event.dart/0 | {'file_path': 'flutter_todos/lib/blocs/filtered_todos/filtered_todos_event.dart', 'repo_id': 'flutter_todos', 'token_count': 338} |
part of 'bloc.dart';
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
abstract class TodoState extends Equatable {
const TodoState();
@override
List<Object> get props => [];
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
class TodoLoadInProgress extends TodoState {}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
class TodoLoadSuccess extends TodoState {
final Todo todo;
final bool dirty;
const TodoLoadSuccess(this.todo, {this.dirty});
@override
List<Object> get props => [todo, dirty];
@override
String toString() => 'TodoLoadSuccess { todo: $todo, dirty: $dirty }';
}
| flutter_todos/lib/blocs/todo/state.dart/0 | {'file_path': 'flutter_todos/lib/blocs/todo/state.dart', 'repo_id': 'flutter_todos', 'token_count': 279} |
import 'dart:io';
import 'package:mason/mason.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
import '../pre_gen.dart';
class _MockHookContext extends Mock implements HookContext {}
void main() {
group('PreGen Hook', () {
late HookContext hookContext;
late Map<String, dynamic> vars;
late Directory originalDir;
setUp(() {
vars = <String, dynamic>{};
hookContext = _MockHookContext();
when(() => hookContext.vars).thenReturn(vars);
originalDir = Directory.current;
Directory.current = Directory.systemTemp;
});
tearDown(() {
Directory.current = originalDir;
});
test('uses the user input values when they are not empty', () {
vars['project_title'] = 'MyTitle';
vars['project_description'] = 'MyDescription';
run(hookContext);
expect(
vars,
equals(
{
'project_title': 'MyTitle',
'project_description': 'MyDescription',
},
),
);
});
test('uses pubspec name and description when user input is empty', () {
vars['project_title'] = '';
vars['project_description'] = '';
File('pubspec.yaml').writeAsStringSync(
'''
name: PubspecTitle
description: PubspecDescription
''',
);
run(hookContext);
expect(
vars,
equals(
{
'project_title': 'PubspecTitle',
'project_description': 'PubspecDescription',
},
),
);
});
});
}
| flutter_web_preloader/hooks/test/pre_gen_test.dart/0 | {'file_path': 'flutter_web_preloader/hooks/test/pre_gen_test.dart', 'repo_id': 'flutter_web_preloader', 'token_count': 665} |
/*
* Copyright (c) 2016-present Invertase Limited & Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this library except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
class FirebaseApp {
const FirebaseApp({
required this.name,
required this.displayName,
required this.platform,
required this.appId,
required this.packageNameOrBundleIdentifier,
});
FirebaseApp.fromJson(Map<dynamic, dynamic> json)
: this(
platform: (json['platform'] as String).toLowerCase(),
appId: json['appId'] as String,
displayName: json['displayName'] as String?,
name: json['name'] as String,
packageNameOrBundleIdentifier:
(json['packageName'] ?? json['bundleId']) as String?,
);
final String platform;
final String? displayName;
final String name;
final String appId;
final String? packageNameOrBundleIdentifier;
@override
String toString() {
return 'FirebaseApp["$displayName", "$packageNameOrBundleIdentifier", "$platform"]';
}
}
| flutterfire_cli/packages/flutterfire_cli/lib/src/firebase/firebase_app.dart/0 | {'file_path': 'flutterfire_cli/packages/flutterfire_cli/lib/src/firebase/firebase_app.dart', 'repo_id': 'flutterfire_cli', 'token_count': 487} |
import 'package:equatable/equatable.dart';
class Suggestion extends Equatable {
const Suggestion(this.value);
final String value;
@override
List<Object> get props => [value];
}
| fluttersaurus/lib/search/models/suggestion.dart/0 | {'file_path': 'fluttersaurus/lib/search/models/suggestion.dart', 'repo_id': 'fluttersaurus', 'token_count': 58} |
include: ../../analysis_options.yaml | fluttersaurus/packages/thesaurus_repository/analysis_options.yaml/0 | {'file_path': 'fluttersaurus/packages/thesaurus_repository/analysis_options.yaml', 'repo_id': 'fluttersaurus', 'token_count': 11} |
import 'package:flutter_test/flutter_test.dart';
import 'package:fluttersaurus/fluttersaurus.dart';
import 'package:fluttersaurus/search/search.dart';
import 'package:mocktail/mocktail.dart';
import 'package:thesaurus_repository/thesaurus_repository.dart';
class MockThesaurusRepository extends Mock implements ThesaurusRepository {}
void main() {
group('Fluttersaurus', () {
testWidgets('renders SearchPage when thesaurusRepository is not null',
(tester) async {
await tester.pumpWidget(
Fluttersaurus(
thesaurusRepository: MockThesaurusRepository(),
),
);
expect(find.byType(SearchPage), findsOneWidget);
});
});
}
| fluttersaurus/test/fluttersaurus_test.dart/0 | {'file_path': 'fluttersaurus/test/fluttersaurus_test.dart', 'repo_id': 'fluttersaurus', 'token_count': 256} |
import 'package:forge2d/forge2d.dart';
abstract class ParticleDestroyListener {
/// Called when any particle group is about to be destroyed.
void onDestroyParticleGroup(ParticleGroup group);
/// Called when a particle is about to be destroyed.
void onDestroyParticle(Particle particle);
}
| forge2d/packages/forge2d/lib/src/callbacks/particle_destroy_listener.dart/0 | {'file_path': 'forge2d/packages/forge2d/lib/src/callbacks/particle_destroy_listener.dart', 'repo_id': 'forge2d', 'token_count': 81} |
import 'dart:math';
import 'package:forge2d/forge2d.dart';
import 'package:forge2d/src/settings.dart' as settings;
/// GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates.
class _SimplexVertex {
final Vector2 wA = Vector2.zero(); // support point in shapeA
final Vector2 wB = Vector2.zero(); // support point in shapeB
final Vector2 w = Vector2.zero(); // wB - wA
double a = 0.0; // barycentric coordinate for closest point
int indexA = 0; // wA index
int indexB = 0; // wB index
void set(_SimplexVertex sv) {
wA.setFrom(sv.wA);
wB.setFrom(sv.wB);
w.setFrom(sv.w);
a = sv.a;
indexA = sv.indexA;
indexB = sv.indexB;
}
}
class SimplexCache {
/// length or area
double metric = 0.0;
int count = 0;
/// vertices on shape A
final List<int> indexA = List<int>.filled(3, 0);
/// vertices on shape B
final List<int> indexB = List<int>.filled(3, 0);
SimplexCache() {
indexA[0] = settings.intMaxValue;
indexA[1] = settings.intMaxValue;
indexA[2] = settings.intMaxValue;
indexB[0] = settings.intMaxValue;
indexB[1] = settings.intMaxValue;
indexB[2] = settings.intMaxValue;
}
void set(SimplexCache sc) {
indexA.setRange(0, sc.indexA.length, sc.indexA);
indexA.setRange(0, sc.indexB.length, sc.indexB);
metric = sc.metric;
count = sc.count;
}
}
class _Simplex {
final List<_SimplexVertex> vertices = List<_SimplexVertex>.generate(
3,
(_) => _SimplexVertex(),
);
_SimplexVertex get vertex1 => vertices[0];
_SimplexVertex get vertex2 => vertices[1];
_SimplexVertex get vertex3 => vertices[2];
int count = 0;
void readCache(
SimplexCache cache,
DistanceProxy proxyA,
Transform transformA,
DistanceProxy proxyB,
Transform transformB,
) {
assert(cache.count <= 3);
// Copy data from cache.
count = cache.count;
for (var i = 0; i < count; ++i) {
final v = vertices[i];
v.indexA = cache.indexA[i];
v.indexB = cache.indexB[i];
final wALocal = proxyA.getVertex(v.indexA);
final wBLocal = proxyB.getVertex(v.indexB);
v.wA.setFrom(Transform.mulVec2(transformA, wALocal));
v.wB.setFrom(Transform.mulVec2(transformB, wBLocal));
v.w
..setFrom(v.wB)
..sub(v.wA);
v.a = 0.0;
}
// Compute the new simplex metric, if it is substantially different than
// old metric then flush the simplex.
if (count > 1) {
final metric1 = cache.metric;
final metric2 = getMetric();
if (metric2 < 0.5 * metric1 ||
2.0 * metric1 < metric2 ||
metric2 < settings.epsilon) {
// Reset the simplex.
count = 0;
}
}
// If the cache is empty or invalid ...
if (count == 0) {
final v = vertices[0];
v.indexA = 0;
v.indexB = 0;
final wALocal = proxyA.getVertex(0);
final wBLocal = proxyB.getVertex(0);
v.wA.setFrom(Transform.mulVec2(transformA, wALocal));
v.wB.setFrom(Transform.mulVec2(transformB, wBLocal));
v.w
..setFrom(v.wB)
..sub(v.wA);
count = 1;
}
}
void writeCache(SimplexCache cache) {
cache.metric = getMetric();
cache.count = count;
for (var i = 0; i < count; ++i) {
cache.indexA[i] = vertices[i].indexA;
cache.indexB[i] = vertices[i].indexB;
}
}
final Vector2 _e12 = Vector2.zero();
void getSearchDirection(Vector2 out) {
switch (count) {
case 1:
out
..setFrom(vertex1.w)
..negate();
return;
case 2:
_e12
..setFrom(vertex2.w)
..sub(vertex1.w);
// use out for a temp variable real quick
out
..setFrom(vertex1.w)
..negate();
final sgn = _e12.cross(out);
if (sgn > 0.0) {
// Origin is left of e12.
_e12.scaleOrthogonalInto(1.0, out);
} else {
// Origin is right of e12.
_e12.scaleOrthogonalInto(-1.0, out);
}
return;
default:
assert(false);
out.setZero();
return;
}
}
// djm pooled
final Vector2 _case2 = Vector2.zero();
final Vector2 _case22 = Vector2.zero();
/// This returns pooled objects. don't keep or modify them
void getClosestPoint(Vector2 out) {
switch (count) {
case 0:
assert(false);
out.setZero();
return;
case 1:
out.setFrom(vertex1.w);
return;
case 2:
_case22
..setFrom(vertex2.w)
..scale(vertex2.a);
_case2
..setFrom(vertex1.w)
..scale(vertex1.a)
..add(_case22);
out.setFrom(_case2);
return;
case 3:
out.setZero();
return;
default:
assert(false);
out.setZero();
return;
}
}
// djm pooled, and from above
final Vector2 _case3 = Vector2.zero();
final Vector2 _case33 = Vector2.zero();
void getWitnessPoints(Vector2 pA, Vector2 pB) {
switch (count) {
case 0:
assert(false);
break;
case 1:
pA.setFrom(vertex1.wA);
pB.setFrom(vertex1.wB);
break;
case 2:
_case2
..setFrom(vertex1.wA)
..scale(vertex1.a);
pA
..setFrom(vertex2.wA)
..scale(vertex2.a)
..add(_case2);
// v1.a * v1.wA + v2.a * v2.wA;
// *pB = v1.a * v1.wB + v2.a * v2.wB;
_case2
..setFrom(vertex1.wB)
..scale(vertex1.a);
pB
..setFrom(vertex2.wB)
..scale(vertex2.a)
..add(_case2);
break;
case 3:
pA
..setFrom(vertex1.wA)
..scale(vertex1.a);
_case3
..setFrom(vertex2.wA)
..scale(vertex2.a);
_case33
..setFrom(vertex3.wA)
..scale(vertex3.a);
pA
..add(_case3)
..add(_case33);
pB.setFrom(pA);
break;
default:
assert(false);
break;
}
}
// djm pooled, from above
double getMetric() {
switch (count) {
case 0:
assert(false);
return 0.0;
case 1:
return 0.0;
case 2:
return vertex1.w.distanceTo(vertex2.w);
case 3:
_case3
..setFrom(vertex2.w)
..sub(vertex1.w);
_case33
..setFrom(vertex3.w)
..sub(vertex1.w);
// return Vec2.cross(v2.w - v1.w, v3.w - v1.w);
return _case3.cross(_case33);
default:
assert(false);
return 0.0;
}
}
/// Solve a line segment using barycentric coordinates.
void solve2() {
// Solve a line segment using barycentric coordinates.
//
// p = a1 * w1 + a2 * w2
// a1 + a2 = 1
//
// The vector from the origin to the closest point on the line is
// perpendicular to the line.
// e12 = w2 - w1
// dot(p, e) = 0
// a1 * dot(w1, e) + a2 * dot(w2, e) = 0
//
// 2-by-2 linear system
// [1 1 ][a1] = [1]
// [w1.e12 w2.e12][a2] = [0]
//
// Define
// d12_1 = dot(w2, e12)
// d12_2 = -dot(w1, e12)
// d12 = d12_1 + d12_2
//
// Solution
// a1 = d12_1 / d12
// a2 = d12_2 / d12
final w1 = vertex1.w;
final w2 = vertex2.w;
_e12
..setFrom(w2)
..sub(w1);
// w1 region
final d12n2 = -w1.dot(_e12);
if (d12n2 <= 0.0) {
// a2 <= 0, so we clamp it to 0
vertex1.a = 1.0;
count = 1;
return;
}
// w2 region
final d12n1 = w2.dot(_e12);
if (d12n1 <= 0.0) {
// a1 <= 0, so we clamp it to 0
vertex2.a = 1.0;
count = 1;
vertex1.set(vertex2);
return;
}
// Must be in e12 region.
final invD12 = 1.0 / (d12n1 + d12n2);
vertex1.a = d12n1 * invD12;
vertex2.a = d12n2 * invD12;
count = 2;
}
// djm pooled, and from above
final Vector2 _e13 = Vector2.zero();
final Vector2 _e23 = Vector2.zero();
final Vector2 _w1 = Vector2.zero();
final Vector2 _w2 = Vector2.zero();
final Vector2 _w3 = Vector2.zero();
/// Solve a line segment using barycentric coordinates.<br/>
/// Possible regions:<br/>
/// - points[2]<br/>
/// - edge points[0]-points[2]<br/>
/// - edge points[1]-points[2]<br/>
/// - inside the triangle
void solve3() {
_w1.setFrom(vertex1.w);
_w2.setFrom(vertex2.w);
_w3.setFrom(vertex3.w);
// Edge12
// [1 1 ][a1] = [1]
// [w1.e12 w2.e12][a2] = [0]
// a3 = 0
_e12
..setFrom(_w2)
..sub(_w1);
final w1e12 = _w1.dot(_e12);
final w2e12 = _w2.dot(_e12);
final d12n1 = w2e12;
final d12n2 = -w1e12;
// Edge13
// [1 1 ][a1] = [1]
// [w1.e13 w3.e13][a3] = [0]
// a2 = 0
_e13
..setFrom(_w3)
..sub(_w1);
final w1e13 = _w1.dot(_e13);
final w3e13 = _w3.dot(_e13);
final d13n1 = w3e13;
final d13n2 = -w1e13;
// Edge23
// [1 1 ][a2] = [1]
// [w2.e23 w3.e23][a3] = [0]
// a1 = 0
_e23
..setFrom(_w3)
..sub(_w2);
final w2e23 = _w2.dot(_e23);
final w3e23 = _w3.dot(_e23);
final d23n1 = w3e23;
final d23n2 = -w2e23;
// Triangle123
final n123 = _e12.cross(_e13);
final d123n1 = n123 * _w2.cross(_w3);
final d123n2 = n123 * _w3.cross(_w1);
final d123n3 = n123 * _w1.cross(_w2);
// w1 region
if (d12n2 <= 0.0 && d13n2 <= 0.0) {
vertex1.a = 1.0;
count = 1;
return;
}
// e12
if (d12n1 > 0.0 && d12n2 > 0.0 && d123n3 <= 0.0) {
final invD12 = 1.0 / (d12n1 + d12n2);
vertex1.a = d12n1 * invD12;
vertex2.a = d12n2 * invD12;
count = 2;
return;
}
// e13
if (d13n1 > 0.0 && d13n2 > 0.0 && d123n2 <= 0.0) {
final invD13 = 1.0 / (d13n1 + d13n2);
vertex1.a = d13n1 * invD13;
vertex3.a = d13n2 * invD13;
count = 2;
vertex2.set(vertex3);
return;
}
// w2 region
if (d12n1 <= 0.0 && d23n2 <= 0.0) {
vertex2.a = 1.0;
count = 1;
vertex1.set(vertex2);
return;
}
// w3 region
if (d13n1 <= 0.0 && d23n1 <= 0.0) {
vertex3.a = 1.0;
count = 1;
vertex1.set(vertex3);
return;
}
// e23
if (d23n1 > 0.0 && d23n2 > 0.0 && d123n1 <= 0.0) {
final invD23 = 1.0 / (d23n1 + d23n2);
vertex2.a = d23n1 * invD23;
vertex3.a = d23n2 * invD23;
count = 2;
vertex1.set(vertex3);
return;
}
// Must be in triangle123
final invD123 = 1.0 / (d123n1 + d123n2 + d123n3);
vertex1.a = d123n1 * invD123;
vertex2.a = d123n2 * invD123;
vertex3.a = d123n3 * invD123;
count = 3;
}
} // Class _Simplex
class DistanceProxy {
final List<Vector2> vertices = List<Vector2>.generate(
settings.maxPolygonVertices,
(_) => Vector2.zero(),
);
int _count = 0;
double radius = 0.0;
final List<Vector2> buffer = List<Vector2>.generate(2, (_) => Vector2.zero());
/// Initialize the proxy using the given shape. The shape must remain in scope
/// while the proxy is in use.
void set(Shape shape, int index) {
switch (shape.shapeType) {
case ShapeType.circle:
final circle = shape as CircleShape;
vertices[0].setFrom(circle.position);
_count = 1;
radius = circle.radius;
break;
case ShapeType.polygon:
final poly = shape as PolygonShape;
_count = poly.vertices.length;
radius = poly.radius;
for (var i = 0; i < _count; i++) {
vertices[i].setFrom(poly.vertices[i]);
}
break;
case ShapeType.chain:
final chain = shape as ChainShape;
assert(0 <= index && index < chain.vertexCount);
buffer[0] = chain.vertices[index];
if (index + 1 < chain.vertexCount) {
buffer[1] = chain.vertices[index + 1];
} else {
buffer[1] = chain.vertices[0];
}
vertices[0].setFrom(buffer[0]);
vertices[1].setFrom(buffer[1]);
_count = 2;
radius = chain.radius;
break;
case ShapeType.edge:
final edge = shape as EdgeShape;
vertices[0].setFrom(edge.vertex1);
vertices[1].setFrom(edge.vertex2);
_count = 2;
radius = edge.radius;
break;
default:
assert(false);
}
}
/// Get the supporting vertex index in the given direction.
int getSupport(Vector2 d) {
var bestIndex = 0;
var bestValue = vertices[0].dot(d);
for (var i = 1; i < _count; i++) {
final value = vertices[i].dot(d);
if (value > bestValue) {
bestIndex = i;
bestValue = value;
}
}
return bestIndex;
}
/// Get the supporting vertex in the given direction.
Vector2 getSupportVertex(Vector2 d) {
var bestIndex = 0;
var bestValue = vertices[0].dot(d);
for (var i = 1; i < _count; i++) {
final value = vertices[i].dot(d);
if (value > bestValue) {
bestIndex = i;
bestValue = value;
}
}
return vertices[bestIndex];
}
/// Get the vertex count.
int getVertexCount() {
return _count;
}
/// Get a vertex by index. Used by Distance.
Vector2 getVertex(int index) {
assert(0 <= index && index < _count);
return vertices[index];
}
} // Class _DistanceProxy.
class Distance {
static const int maxIterations = 20;
static int gjkCalls = 0;
static int gjkIterations = 0;
static int gjkMaxIterations = 20;
final _Simplex _simplex = _Simplex();
final List<int> _saveA = List<int>.filled(3, 0);
final List<int> _saveB = List<int>.filled(3, 0);
final Vector2 _closestPoint = Vector2.zero();
final Vector2 _d = Vector2.zero();
final Vector2 _temp = Vector2.zero();
final Vector2 _normal = Vector2.zero();
/// Compute the closest points between two shapes. Supports any combination
/// of: CircleShape and PolygonShape. The simplex cache is input/output.
/// On the first call set [SimplexCache.count] to zero.
void compute(
DistanceOutput output,
SimplexCache cache,
DistanceInput input,
) {
gjkCalls++;
final proxyA = input.proxyA;
final proxyB = input.proxyB;
final transformA = input.transformA;
final transformB = input.transformB;
// Initialize the simplex.
_simplex.readCache(cache, proxyA, transformA, proxyB, transformB);
// Get simplex vertices as an array.
final vertices = _simplex.vertices;
// These store the vertices of the last simplex so that we
// can check for duplicates and prevent cycling.
// (pooled above)
var saveCount = 0;
_simplex.getClosestPoint(_closestPoint);
var distanceSqr1 = _closestPoint.length2;
var distanceSqr2 = distanceSqr1;
// Main iteration loop
var iter = 0;
while (iter < maxIterations) {
// Copy simplex so we can identify duplicates.
saveCount = _simplex.count;
for (var i = 0; i < saveCount; i++) {
_saveA[i] = vertices[i].indexA;
_saveB[i] = vertices[i].indexB;
}
switch (_simplex.count) {
case 1:
break;
case 2:
_simplex.solve2();
break;
case 3:
_simplex.solve3();
break;
default:
assert(false);
}
// If we have 3 points, then the origin is in the corresponding triangle.
if (_simplex.count == 3) {
break;
}
// Compute closest point.
_simplex.getClosestPoint(_closestPoint);
distanceSqr2 = _closestPoint.length2;
// ensure progress
if (distanceSqr2 >= distanceSqr1) {
// break;
}
distanceSqr1 = distanceSqr2;
// get search direction;
_simplex.getSearchDirection(_d);
// Ensure the search direction is numerically fit.
if (_d.length2 < settings.epsilon * settings.epsilon) {
// The origin is probably contained by a line segment
// or triangle. Thus the shapes are overlapped.
// We can't return zero here even though there may be overlap.
// In case the simplex is a point, segment, or triangle it is difficult
// to determine if the origin is contained in the CSO or very close to
// it.
break;
}
/*
* SimplexVertex* vertex = vertices + simplex.count; vertex.indexA =
* proxyA.GetSupport(MulT(transformA.R, -d)); vertex.wA = Mul(transformA,
* proxyA.GetVertex(vertex.indexA)); Vec2 wBLocal; vertex.indexB =
* proxyB.GetSupport(MulT(transformB.R, d)); vertex.wB = Mul(transformB,
* proxyB.GetVertex(vertex.indexB)); vertex.w = vertex.wB - vertex.wA;
*/
// Compute a tentative new simplex vertex using support points.
final vertex = vertices[_simplex.count];
_temp.setFrom(Rot.mulTransVec2(transformA.q, _d..negate()));
vertex.indexA = proxyA.getSupport(_temp);
vertex.wA.setFrom(
Transform.mulVec2(transformA, proxyA.getVertex(vertex.indexA)),
);
// Vec2 wBLocal;
_temp.setFrom(Rot.mulTransVec2(transformB.q, _d..negate()));
vertex.indexB = proxyB.getSupport(_temp);
vertex.wB.setFrom(
Transform.mulVec2(transformB, proxyB.getVertex(vertex.indexB)),
);
(vertex.w..setFrom(vertex.wB)).sub(vertex.wA);
// Iteration count is equated to the number of support point calls.
++iter;
++gjkIterations;
// Check for duplicate support points. This is the main termination
// criteria.
var duplicate = false;
for (var i = 0; i < saveCount; ++i) {
if (vertex.indexA == _saveA[i] && vertex.indexB == _saveB[i]) {
duplicate = true;
break;
}
}
// If we found a duplicate support point we must exit to avoid cycling.
if (duplicate) {
break;
}
// New vertex is ok and needed.
++_simplex.count;
}
gjkMaxIterations = max(gjkMaxIterations, iter);
// Prepare output.
_simplex.getWitnessPoints(output.pointA, output.pointB);
output.distance = output.pointA.distanceTo(output.pointB);
output.iterations = iter;
// Cache the simplex.
_simplex.writeCache(cache);
// Apply radii if requested.
if (input.useRadii) {
final rA = proxyA.radius;
final rB = proxyB.radius;
if (output.distance > rA + rB && output.distance > settings.epsilon) {
// Shapes are still no overlapped.
// Move the witness points to the outer surface.
output.distance -= rA + rB;
_normal
..setFrom(output.pointB)
..sub(output.pointA);
_normal.normalize();
_temp
..setFrom(_normal)
..scale(rA);
output.pointA.add(_temp);
_temp
..setFrom(_normal)
..scale(rB);
output.pointB.sub(_temp);
} else {
// Shapes are overlapped when radii are considered.
// Move the witness points to the middle.
// Vec2 p = 0.5f * (output.pointA + output.pointB);
output.pointA
..add(output.pointB)
..scale(.5);
output.pointB.setFrom(output.pointA);
output.distance = 0.0;
}
}
}
}
| forge2d/packages/forge2d/lib/src/collision/distance.dart/0 | {'file_path': 'forge2d/packages/forge2d/lib/src/collision/distance.dart', 'repo_id': 'forge2d', 'token_count': 9182} |
export 'common/color3i.dart';
export 'common/raycast_result.dart';
export 'common/rot.dart';
export 'common/sweep.dart';
export 'common/timer.dart';
export 'common/transform.dart';
export 'common/viewport_transform.dart';
| forge2d/packages/forge2d/lib/src/common.dart/0 | {'file_path': 'forge2d/packages/forge2d/lib/src/common.dart', 'repo_id': 'forge2d', 'token_count': 79} |
import 'dart:math';
import 'package:forge2d/forge2d.dart';
/// The class manages contact between two shapes. A contact exists for each
/// overlapping AABB in the broad-phase (except if filtered). Therefore a
/// contact object may exist that has no contact points.
abstract class Contact {
// Flags stored in _flags
// Used when crawling contact graph when forming islands.
static const int islandFlag = 0x0001;
// Set when the shapes are touching.
static const int touchingFlag = 0x0002;
// This contact can be disabled (by user)
static const int enabledFlag = 0x0004;
// This contact needs filtering because a fixture filter was changed.
static const int filterFlag = 0x0008;
// This bullet contact had a TOI event
static const int bulletHitFlag = 0x0010;
static const int toiFlag = 0x0020;
int flags = 0;
final Fixture fixtureA;
final Fixture fixtureB;
final int indexA;
final int indexB;
Body get bodyA => fixtureA.body;
Body get bodyB => fixtureB.body;
final ContactPositionConstraint positionConstraint =
ContactPositionConstraint();
final ContactVelocityConstraint velocityConstraint =
ContactVelocityConstraint();
final Manifold manifold = Manifold();
int toiCount = 0;
double toi = 0.0;
double _friction = 0.0;
double get friction => _friction;
double _restitution = 0.0;
double get restitution => _restitution;
double tangentSpeed = 0.0;
Contact(this.fixtureA, this.indexA, this.fixtureB, this.indexB) {
flags = enabledFlag;
manifold.pointCount = 0;
_friction = Contact.mixFriction(
fixtureA.friction,
fixtureB.friction,
);
_restitution = Contact.mixRestitution(
fixtureA.restitution,
fixtureB.restitution,
);
}
static Contact init(
Fixture fixtureA,
int indexA,
Fixture fixtureB,
int indexB,
) {
// Remember that we use the order in the enum here to determine in which
// order the arguments should come in the different contact classes.
// { CIRCLE, EDGE, POLYGON, CHAIN }
// TODO(spydon): Clean this mess up.
final typeA = fixtureA.type.index < fixtureB.type.index
? fixtureA.type
: fixtureB.type;
final typeB = fixtureA.type == typeA ? fixtureB.type : fixtureA.type;
final indexTemp = indexA;
final firstIndex = fixtureA.type == typeA ? indexA : indexB;
final secondIndex = fixtureB.type == typeB ? indexB : indexTemp;
final temp = fixtureA;
final firstFixture = fixtureA.type == typeA ? fixtureA : fixtureB;
final secondFixture = fixtureB.type == typeB ? fixtureB : temp;
if (typeA == ShapeType.circle && typeB == ShapeType.circle) {
return CircleContact(firstFixture, secondFixture);
} else if (typeA == ShapeType.polygon && typeB == ShapeType.polygon) {
return PolygonContact(firstFixture, secondFixture);
} else if (typeA == ShapeType.circle && typeB == ShapeType.polygon) {
return PolygonAndCircleContact(secondFixture, firstFixture);
} else if (typeA == ShapeType.circle && typeB == ShapeType.edge) {
return EdgeAndCircleContact(
secondFixture,
secondIndex,
firstFixture,
firstIndex,
);
} else if (typeA == ShapeType.edge && typeB == ShapeType.polygon) {
return EdgeAndPolygonContact(
firstFixture,
firstIndex,
secondFixture,
secondIndex,
);
} else if (typeA == ShapeType.circle && typeB == ShapeType.chain) {
return ChainAndCircleContact(
secondFixture,
secondIndex,
firstFixture,
firstIndex,
);
} else if (typeA == ShapeType.polygon && typeB == ShapeType.chain) {
return ChainAndPolygonContact(
secondFixture,
secondIndex,
firstFixture,
firstIndex,
);
} else {
assert(false, 'Not compatible contact type');
return CircleContact(firstFixture, secondFixture);
}
}
/// Get the world manifold.
void getWorldManifold(WorldManifold worldManifold) {
worldManifold.initialize(
manifold,
fixtureA.body.transform,
fixtureA.shape.radius,
fixtureB.body.transform,
fixtureB.shape.radius,
);
}
/// Whether the body is connected to the joint
bool containsBody(Body body) => body == bodyA || body == bodyB;
/// Get the other body than the argument in the contact
Body getOtherBody(Body body) {
assert(containsBody(body), 'Body is not in contact');
return body == bodyA ? bodyB : bodyA;
}
/// Is this contact touching
bool isTouching() => (flags & touchingFlag) == touchingFlag;
bool representsArguments(
Fixture fixtureA,
int indexA,
Fixture fixtureB,
int indexB,
) {
return (this.fixtureA == fixtureA &&
this.indexA == indexA &&
this.fixtureB == fixtureB &&
this.indexB == indexB) ||
(this.fixtureA == fixtureB &&
this.indexA == indexB &&
this.fixtureB == fixtureA &&
this.indexB == indexA);
}
/// Enable or disable this contact.
///
/// This can be used inside [ContactListener.preSolve]. The contact is
/// only disabled for the current time step (or sub-step in continuous
/// collisions).
set isEnabled(bool value) {
if (value) {
flags |= enabledFlag;
} else {
flags &= ~enabledFlag;
}
}
/// Whether this contact is enabled.
bool get isEnabled => (flags & enabledFlag) == enabledFlag;
void resetFriction() {
_friction = Contact.mixFriction(fixtureA.friction, fixtureB.friction);
}
void resetRestitution() {
_restitution =
Contact.mixRestitution(fixtureA.restitution, fixtureB.restitution);
}
void evaluate(Manifold manifold, Transform xfA, Transform xfB);
/// Flag this contact for filtering. Filtering will occur the next time step.
void flagForFiltering() {
flags |= filterFlag;
}
// djm pooling
final Manifold _oldManifold = Manifold();
void update(ContactListener? listener) {
_oldManifold.set(manifold);
// Re-enable this contact.
flags |= enabledFlag;
var touching = false;
final wasTouching = (flags & touchingFlag) == touchingFlag;
final sensorA = fixtureA.isSensor;
final sensorB = fixtureB.isSensor;
final sensor = sensorA || sensorB;
final bodyA = fixtureA.body;
final bodyB = fixtureB.body;
final xfA = bodyA.transform;
final xfB = bodyB.transform;
if (sensor) {
final shapeA = fixtureA.shape;
final shapeB = fixtureB.shape;
touching = World.collision.testOverlap(
shapeA,
indexA,
shapeB,
indexB,
xfA,
xfB,
);
// Sensors don't generate manifolds.
manifold.pointCount = 0;
} else {
evaluate(manifold, xfA, xfB);
touching = manifold.pointCount > 0;
// Match old contact ids to new contact ids and copy the
// stored impulses to warm start the solver.
for (var i = 0; i < manifold.pointCount; ++i) {
final mp2 = manifold.points[i];
mp2.normalImpulse = 0.0;
mp2.tangentImpulse = 0.0;
final id2 = mp2.id;
for (var j = 0; j < _oldManifold.pointCount; ++j) {
final mp1 = _oldManifold.points[j];
if (mp1.id.isEqual(id2)) {
mp2.normalImpulse = mp1.normalImpulse;
mp2.tangentImpulse = mp1.tangentImpulse;
break;
}
}
}
if (touching != wasTouching) {
bodyA.setAwake(true);
bodyB.setAwake(true);
}
}
if (touching) {
flags |= touchingFlag;
} else {
flags &= ~touchingFlag;
}
if (listener == null) {
return;
}
if (!wasTouching && touching) {
listener.beginContact(this);
}
if (wasTouching && !touching) {
listener.endContact(this);
}
if (!sensor && touching) {
listener.preSolve(this, _oldManifold);
}
}
/// Friction mixing law. The idea is to allow either fixture to drive the
/// restitution to zero. For example, anything slides on ice.
static double mixFriction(double friction1, double friction2) {
return sqrt(friction1 * friction2);
}
/// Restitution mixing law. The idea is allow for anything to bounce off an
/// inelastic surface. For example, a super ball bounces on anything.
static double mixRestitution(double restitution1, double restitution2) {
return restitution1 > restitution2 ? restitution1 : restitution2;
}
}
| forge2d/packages/forge2d/lib/src/dynamics/contacts/contact.dart/0 | {'file_path': 'forge2d/packages/forge2d/lib/src/dynamics/contacts/contact.dart', 'repo_id': 'forge2d', 'token_count': 3203} |
import 'package:forge2d/forge2d.dart';
/// Definition for a {@link ConstantVolumeJoint}, which connects a group a
/// bodies together so they maintain a constant volume within them.
class ConstantVolumeJointDef<A extends Body> extends JointDef<A, A> {
double frequencyHz = 0.0;
double dampingRatio = 0.0;
final List<A> bodies = <A>[];
final List<DistanceJoint> joints = [];
/// Adds a body to the group
void addBody(A body) {
bodies.add(body);
if (bodies.length == 1) {
bodyA = body;
}
if (bodies.length == 2) {
bodyB = body;
}
}
/// Adds a body and the pre-made distance joint. Should only be used for
/// deserialization.
void addBodyAndJoint(A argBody, DistanceJoint argJoint) {
addBody(argBody);
joints.add(argJoint);
}
}
| forge2d/packages/forge2d/lib/src/dynamics/joints/constant_volume_joint_def.dart/0 | {'file_path': 'forge2d/packages/forge2d/lib/src/dynamics/joints/constant_volume_joint_def.dart', 'repo_id': 'forge2d', 'token_count': 282} |
import 'package:forge2d/forge2d.dart';
/// Prismatic joint definition. This requires defining a line of motion using an
/// axis and an anchor point. The definition uses local anchor points and a
/// local axis so that the initial configuration can violate the constraint
/// slightly. The joint translation is zero when the local anchor points
/// coincide in world space. Using local anchors and a local axis helps when
/// saving and loading a game.
///
/// Warning: at least one body should by dynamic with a non-fixed rotation.
class PrismaticJointDef<A extends Body, B extends Body> extends JointDef<A, B> {
/// The local translation axis in body1.
final Vector2 localAxisA = Vector2(1.0, 0.0);
/// The constrained angle between the bodies: body2_angle - body1_angle.
double referenceAngle = 0.0;
/// Enable/disable the joint limit.
bool enableLimit = false;
/// The lower translation limit, usually in meters.
double lowerTranslation = 0.0;
/// The upper translation limit, usually in meters.
double upperTranslation = 0.0;
/// Enable/disable the joint motor.
bool enableMotor = false;
/// The maximum motor torque, usually in N-m.
double maxMotorForce = 0.0;
/// The desired motor speed in radians per second.
double motorSpeed = 0.0;
/// Initialize the bodies, anchors, axis, and reference angle using the world
/// anchor and world axis.
void initialize(A b1, B b2, Vector2 anchor, Vector2 axis) {
bodyA = b1;
bodyB = b2;
localAnchorA.setFrom(bodyA.localPoint(anchor));
localAnchorB.setFrom(bodyB.localPoint(anchor));
localAxisA.setFrom(bodyA.localVector(axis));
referenceAngle = bodyB.angle - bodyA.angle;
}
}
| forge2d/packages/forge2d/lib/src/dynamics/joints/prismatic_joint_def.dart/0 | {'file_path': 'forge2d/packages/forge2d/lib/src/dynamics/joints/prismatic_joint_def.dart', 'repo_id': 'forge2d', 'token_count': 491} |
import 'package:forge2d/forge2d.dart';
class ParticleBodyContact {
/// Index of the particle making contact.
final Particle particle;
/// The body making contact.
final Body body;
/// Weight of the contact. A value between 0.0f and 1.0f.
double weight = 0.0;
/// The normalized direction from the particle to the body.
final Vector2 normal = Vector2.zero();
/// The effective mass used in calculating force.
double mass = 0.0;
ParticleBodyContact(this.particle, this.body);
}
| forge2d/packages/forge2d/lib/src/particle/particle_body_contact.dart/0 | {'file_path': 'forge2d/packages/forge2d/lib/src/particle/particle_body_contact.dart', 'repo_id': 'forge2d', 'token_count': 148} |
import 'package:forge2d/forge2d.dart';
import 'package:test/test.dart';
void main() {
group('ConstantVolumeJointDef', () {
test('can be instantiated', () {
expect(ConstantVolumeJointDef(), isA<ConstantVolumeJointDef>());
});
});
}
| forge2d/packages/forge2d/test/dynamics/joints/constant_volume_joint_def_test.dart/0 | {'file_path': 'forge2d/packages/forge2d/test/dynamics/joints/constant_volume_joint_def_test.dart', 'repo_id': 'forge2d', 'token_count': 96} |
import 'package:forge2d/forge2d.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
import '../../helpers/helpers.dart';
void main() {
group('PulleyJoint', () {
test('can be instantiated', () {
final world = World();
final jointDef = PulleyJointDef()
..bodyA = Body(BodyDef(), world)
..bodyB = Body(BodyDef(), world);
expect(PulleyJoint(jointDef), isA<PulleyJoint>());
});
group('render', () {
late World world;
late DebugDraw debugDraw;
setUp(() {
world = World();
debugDraw = MockDebugDraw();
registerFallbackValue(Vector2.zero());
registerFallbackValue(Color3i.black());
});
test('draws three segments', () {
final joint = PulleyJoint(
PulleyJointDef()
..bodyA = Body(BodyDef(), world)
..bodyB = Body(BodyDef(), world),
);
joint.render(debugDraw);
verify(() => debugDraw.drawSegment(any(), any(), any())).called(3);
});
});
});
}
| forge2d/packages/forge2d/test/dynamics/joints/pulley_joint_test.dart/0 | {'file_path': 'forge2d/packages/forge2d/test/dynamics/joints/pulley_joint_test.dart', 'repo_id': 'forge2d', 'token_count': 466} |
name: freezed
description: >
Code generation for immutable classes that has a simple syntax/API without
compromising on the features.
version: 2.4.6
repository: https://github.com/rrousselGit/freezed
issue_tracker: https://github.com/rrousselGit/freezed/issues
environment:
sdk: ">=2.17.0 <3.0.0"
dependencies:
analyzer: ">=5.13.0 <7.0.0"
build: ^2.3.1
build_config: ^1.1.0
collection: ^1.15.0
meta: ^1.9.1
source_gen: ^1.2.3
freezed_annotation: ^2.4.1
json_annotation: ^4.6.0
dev_dependencies:
json_serializable: ^6.3.2
build_test: ^2.1.5
build_runner: ^2.3.3
test: ^1.21.0
matcher: ^0.12.14
source_gen_test: ^1.0.4
expect_error: ^1.0.4
| freezed/packages/freezed/pubspec.yaml/0 | {'file_path': 'freezed/packages/freezed/pubspec.yaml', 'repo_id': 'freezed', 'token_count': 301} |
import 'export_empty.dart' as concrete;
import 'export_freezed_annotation.dart';
import 'generic.dart' show Model;
part 'alias.freezed.dart';
@freezed
class Alias with _$Alias {
@With<concrete.Mixin>()
@Implements<concrete.Empty>()
factory Alias([
@Default(concrete.Empty()) concrete.Empty value,
int? a,
Model<int>? b,
]) = _Alias;
}
| freezed/packages/freezed/test/integration/alias.dart/0 | {'file_path': 'freezed/packages/freezed/test/integration/alias.dart', 'repo_id': 'freezed', 'token_count': 140} |
import 'package:freezed_annotation/freezed_annotation.dart';
part 'generics_refs.freezed.dart';
@freezed
class PageList with _$PageList {
factory PageList(List<Page> pages) = _PageList;
}
@freezed
class PageMap with _$PageMap {
factory PageMap(Map<String, Page> pages) = _PageMap;
}
@freezed
class WidgetType with _$WidgetType {
const factory WidgetType.page() = Page;
}
| freezed/packages/freezed/test/integration/generics_refs.dart/0 | {'file_path': 'freezed/packages/freezed/test/integration/generics_refs.dart', 'repo_id': 'freezed', 'token_count': 137} |
import 'package:freezed_annotation/freezed_annotation.dart';
import 'external_typedef.dart';
import 'external_typedef_two.dart' as two;
part 'typedef_parameter.freezed.dart';
typedef MyTypedef = Object? Function(String);
typedef GenericTypedef<T, S> = S Function(T);
@freezed
class ClassWithTypedef with _$ClassWithTypedef {
ClassWithTypedef._();
factory ClassWithTypedef(
MyTypedef myTypedef,
MyTypedef? maybeTypedef,
ExternalTypedef externalTypedef,
two.ExternalTypedefTwo externalTypedefTwo,
GenericTypedef<int, bool> genericTypedef,
) = _ClassWithTypedef;
}
| freezed/packages/freezed/test/integration/typedef_parameter.dart/0 | {'file_path': 'freezed/packages/freezed/test/integration/typedef_parameter.dart', 'repo_id': 'freezed', 'token_count': 228} |
import 'package:freezed_annotation/freezed_annotation.dart';
part 'missing_mixin.freezed.dart';
@freezed
// expect_lint: freezed_missing_mixin
class MissingMixin {
const factory MissingMixin() = _MissingMixin;
}
@freezed
class WithMixin with _$WithMixin {
const factory WithMixin() = _WithMixin;
}
mixin SomeMixin {
int get id;
}
@freezed
// expect_lint: freezed_missing_mixin
class FooModel with SomeMixin {
const FooModel._();
const factory FooModel(int id) = _FooModel;
@override
int get id => id;
}
@freezed
class BarModel with _$BarModel, SomeMixin {
const BarModel._();
const factory BarModel(int id) = _BarModel;
@override
int get id => id;
}
| freezed/packages/freezed_lint/example/lib/missing_mixin.dart/0 | {'file_path': 'freezed/packages/freezed_lint/example/lib/missing_mixin.dart', 'repo_id': 'freezed', 'token_count': 247} |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fresh_example/login/bloc/login_bloc.dart';
import 'package:user_repository/user_repository.dart';
class LoginPage extends StatelessWidget {
const LoginPage({super.key});
static Route<void> route() {
return MaterialPageRoute<void>(builder: (_) => const LoginPage());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Login')),
body: BlocProvider(
create: (context) => LoginBloc(context.read<UserRepository>()),
child: const Login(),
),
);
}
}
class Login extends StatelessWidget {
const Login({super.key});
@override
Widget build(BuildContext context) {
return BlocListener<LoginBloc, LoginState>(
listener: (context, state) {
if (state.status == LoginStatus.submissionFailure) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(const SnackBar(content: Text('Login Failure')));
}
},
child: Column(
children: <Widget>[
TextField(
onChanged: (value) {
context.read<LoginBloc>().add(LoginUsernameChanged(value));
},
decoration: const InputDecoration(labelText: 'Username'),
),
TextField(
onChanged: (value) {
context.read<LoginBloc>().add(LoginPasswordChanged(value));
},
decoration: const InputDecoration(labelText: 'Password'),
),
BlocBuilder<LoginBloc, LoginState>(
builder: (context, state) {
return ElevatedButton(
onPressed: state.submissionEnabled
? () => context.read<LoginBloc>().add(LoginSubmitted())
: null,
child: state.status == LoginStatus.submissionInProgress
? const CircularProgressIndicator()
: const Text('Login'),
);
},
)
],
),
);
}
}
| fresh/packages/fresh_dio/example/lib/login/login_page.dart/0 | {'file_path': 'fresh/packages/fresh_dio/example/lib/login/login_page.dart', 'repo_id': 'fresh', 'token_count': 959} |
export 'src/photos_repository.dart';
| fresh/packages/fresh_dio/example/packages/photos_repository/lib/photos_repository.dart/0 | {'file_path': 'fresh/packages/fresh_dio/example/packages/photos_repository/lib/photos_repository.dart', 'repo_id': 'fresh', 'token_count': 14} |
export 'package:dio/dio.dart' show Dio, Response;
export 'package:fresh/fresh.dart'
show
AuthenticationStatus,
FreshMixin,
InMemoryTokenStorage,
OAuth2Token,
RevokeTokenException,
TokenHeaderBuilder,
TokenStorage;
export 'src/fresh.dart';
| fresh/packages/fresh_dio/lib/fresh_dio.dart/0 | {'file_path': 'fresh/packages/fresh_dio/lib/fresh_dio.dart', 'repo_id': 'fresh', 'token_count': 132} |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'main.dart';
// **************************************************************************
// FunctionalWidgetGenerator
// **************************************************************************
class Foo extends StatelessWidget {
const Foo(
this.value, {
Key? key,
}) : super(key: key);
final int value;
@override
Widget build(BuildContext _context) => foo(value);
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(IntProperty('value', value));
}
}
| functional_widget/packages/functional_widget/example/lib/main.g.dart/0 | {'file_path': 'functional_widget/packages/functional_widget/example/lib/main.g.dart', 'repo_id': 'functional_widget', 'token_count': 167} |
import 'package:code_gen_tester/code_gen_tester.dart';
import 'package:functional_widget/function_to_widget_class.dart';
import 'package:test/test.dart';
void main() {
final tester = SourceGenTester.fromPath('test/src/success.dart');
final _generator = FunctionalWidgetGenerator();
final _expect = (String name, Matcher matcher) async =>
expectGenerateNamed(await tester, name, _generator, matcher);
group('success', () {
test('noArgument', () async {
await _expect('noArgument', completion('''
class NoArgument extends StatelessWidget {
const NoArgument({Key? key}) : super(key: key);
@override
Widget build(BuildContext _context) => noArgument();
}
'''));
});
test('namedDefault', () async {
await _expect('namedDefault', completion('''
class NamedDefault extends StatelessWidget {
const NamedDefault({
Key? key,
this.foo = 42,
}) : super(key: key);
final int foo;
@override
Widget build(BuildContext _context) => namedDefault(foo: foo);
}
'''));
});
test('context', () async {
await _expect('withContext', completion('''
class WithContext extends StatelessWidget {
const WithContext({Key? key}) : super(key: key);
@override
Widget build(BuildContext _context) => withContext(_context);
}
'''));
});
test('key', () async {
await _expect('withKey', completion('''
class WithKey extends StatelessWidget {
const WithKey({required Key key}) : super(key: key);
@override
Widget build(BuildContext _context) => withKey(key!);
}
'''));
});
test('nullable key', () async {
await _expect('withNullableKey', completion('''
class WithNullableKey extends StatelessWidget {
const WithNullableKey({Key? key}) : super(key: key);
@override
Widget build(BuildContext _context) => withNullableKey(key);
}
'''));
});
test('context then key', () async {
await _expect('withContextThenKey', completion('''
class WithContextThenKey extends StatelessWidget {
const WithContextThenKey({required Key key}) : super(key: key);
@override
Widget build(BuildContext _context) => withContextThenKey(
_context,
key!,
);
}
'''));
});
test('context then key then arg', () async {
await _expect('withContextThenKeyThenOneArg', completion('''
class WithContextThenKeyThenOneArg extends StatelessWidget {
const WithContextThenKeyThenOneArg(
this.foo, {
required Key key,
}) : super(key: key);
final int foo;
@override
Widget build(BuildContext _context) => withContextThenKeyThenOneArg(
_context,
key!,
foo,
);
}
'''));
});
test('context then context', () async {
await _expect('withContextThenContext', completion('''
class WithContextThenContext extends StatelessWidget {
const WithContextThenContext(
this.context2, {
Key? key,
}) : super(key: key);
final BuildContext context2;
@override
Widget build(BuildContext _context) => withContextThenContext(
_context,
context2,
);
}
'''));
});
test('key then context', () async {
await _expect('withKeyThenContext', completion('''
class WithKeyThenContext extends StatelessWidget {
const WithKeyThenContext({required Key key}) : super(key: key);
@override
Widget build(BuildContext _context) => withKeyThenContext(
key!,
_context,
);
}
'''));
});
test('key then context then arg', () async {
await _expect('withKeyThenContextThenOneArg', completion('''
class WithKeyThenContextThenOneArg extends StatelessWidget {
const WithKeyThenContextThenOneArg(
this.foo, {
required Key key,
}) : super(key: key);
final int foo;
@override
Widget build(BuildContext _context) => withKeyThenContextThenOneArg(
key!,
_context,
foo,
);
}
'''));
});
test('key then key', () async {
await _expect('withKeyThenKey', completion('''
class WithKeyThenKey extends StatelessWidget {
const WithKeyThenKey(
this.key2, {
Key? key,
}) : super(key: key);
final Key key2;
@override
Widget build(BuildContext _context) => withKeyThenKey(
key,
key2,
);
}
'''));
});
test('whatever then context', () async {
await _expect('whateverThenContext', completion('''
class WhateverThenContext extends StatelessWidget {
const WhateverThenContext(
this.foo,
this.bar, {
Key? key,
}) : super(key: key);
final int foo;
final BuildContext bar;
@override
Widget build(BuildContext _context) => whateverThenContext(
foo,
bar,
);
}
'''));
});
test('whatever then key', () async {
await _expect('whateverThenKey', completion('''
class WhateverThenKey extends StatelessWidget {
const WhateverThenKey(
this.foo,
this.bar, {
Key? key,
}) : super(key: key);
final int foo;
final Key bar;
@override
Widget build(BuildContext _context) => whateverThenKey(
foo,
bar,
);
}
'''));
});
test('documentation', () async {
await _expect('documentation', completion('''
/// Hello
/// World
class Documentation extends StatelessWidget {
/// Hello
/// World
const Documentation(
this.foo, {
Key? key,
}) : super(key: key);
/// Hello
/// World
final int foo;
@override
Widget build(BuildContext _context) => documentation(foo);
}
'''));
});
test('required', () async {
await _expect('withRequired', completion('''
class WithRequired extends StatelessWidget {
const WithRequired({
Key? key,
required this.foo,
}) : super(key: key);
final int foo;
@override
Widget build(BuildContext _context) => withRequired(foo: foo);
}
'''));
});
test('optional', () async {
await _expect('withOptional', completion('''
class WithOptional extends StatelessWidget {
const WithOptional({
Key? key,
this.foo,
}) : super(key: key);
final int? foo;
@override
Widget build(BuildContext _context) => withOptional(foo: foo);
}
'''));
});
test('positional optional', () async {
await _expect('withPositionalOptional', completion('''
class WithPositionalOptional extends StatelessWidget {
const WithPositionalOptional(
this.foo, {
Key? key,
}) : super(key: key);
final int? foo;
@override
Widget build(BuildContext _context) => withPositionalOptional(foo);
}
'''));
});
test('hook widget', () async {
await _expect('hookExample', completion('''
class HookExample extends HookWidget {
const HookExample({Key? key}) : super(key: key);
@override
Widget build(BuildContext _context) => hookExample();
}
'''));
});
test('consumer hook widget', () async {
await _expect('hookConsumerExample', completion('''
class HookConsumerExample extends HookConsumerWidget {
const HookConsumerExample({Key? key}) : super(key: key);
@override
Widget build(
BuildContext _context,
WidgetRef _ref,
) =>
hookConsumerExample();
}
'''));
});
test('consumer hook widget with WidgetRef', () async {
await _expect('hookConsumerExampleWithRef', completion('''
class HookConsumerExampleWithRef extends HookConsumerWidget {
const HookConsumerExampleWithRef({Key? key}) : super(key: key);
@override
Widget build(
BuildContext _context,
WidgetRef _ref,
) =>
hookConsumerExampleWithRef(_ref);
}
'''));
});
test('consumer hook widget with WidgetRef and BuildContext', () async {
await _expect('hookConsumerExampleWithRefAndContext', completion('''
class HookConsumerExampleWithRefAndContext extends HookConsumerWidget {
const HookConsumerExampleWithRefAndContext({Key? key}) : super(key: key);
@override
Widget build(
BuildContext _context,
WidgetRef _ref,
) =>
hookConsumerExampleWithRefAndContext(
_ref,
_context,
);
}
'''));
});
test('consumer widget', () async {
await _expect('consumerExample', completion('''
class ConsumerExample extends ConsumerWidget {
const ConsumerExample({Key? key}) : super(key: key);
@override
Widget build(
BuildContext _context,
WidgetRef _ref,
) =>
consumerExample();
}
'''));
});
test('consumer widget with WidgetRef', () async {
await _expect('consumerExampleWithRef', completion('''
class ConsumerExampleWithRef extends ConsumerWidget {
const ConsumerExampleWithRef({Key? key}) : super(key: key);
@override
Widget build(
BuildContext _context,
WidgetRef _ref,
) =>
consumerExampleWithRef(_ref);
}
'''));
});
test('consumer widget with WidgetRef and BuildContext', () async {
await _expect('consumerExampleWithRefAndContext', completion('''
class ConsumerExampleWithRefAndContext extends ConsumerWidget {
const ConsumerExampleWithRefAndContext({Key? key}) : super(key: key);
@override
Widget build(
BuildContext _context,
WidgetRef _ref,
) =>
consumerExampleWithRefAndContext(
_ref,
_context,
);
}
'''));
});
test('generic widget', () async {
// currently not possible to know the type
await _expect('generic', completion('''
class Generic<T> extends StatelessWidget {
const Generic(
this.foo, {
Key? key,
}) : super(key: key);
final T foo;
@override
Widget build(BuildContext _context) => generic<T>(foo);
}
'''));
});
test('generic widget extends', () async {
// currently not possible to know the type
await _expect('genericExtends', completion('''
class GenericExtends<T extends Container> extends StatelessWidget {
const GenericExtends(
this.foo, {
Key? key,
}) : super(key: key);
final T foo;
@override
Widget build(BuildContext _context) => genericExtends<T>(foo);
}
'''));
});
group('functions', () {
test('typedef', () async {
await _expect('typedefFunction', completion('''
class TypedefFunction<T> extends StatelessWidget {
const TypedefFunction(
this.t, {
Key? key,
}) : super(key: key);
final void Function(T) t;
@override
Widget build(BuildContext _context) => typedefFunction<T>(t);
}
'''));
});
test('inline', () async {
await _expect('inlineFunction', completion('''
class InlineFunction extends StatelessWidget {
const InlineFunction(
this.t, {
Key? key,
}) : super(key: key);
final void Function() t;
@override
Widget build(BuildContext _context) => inlineFunction(t);
}
'''));
});
test('inline2', () async {
await _expect('inlineFunction2', completion('''
class InlineFunction2 extends StatelessWidget {
const InlineFunction2(
this.t, {
Key? key,
}) : super(key: key);
final void Function() t;
@override
Widget build(BuildContext _context) => inlineFunction2(t);
}
'''));
});
test('inline with args', () async {
await _expect('inlineFunctionWithArgs', completion('''
class InlineFunctionWithArgs extends StatelessWidget {
const InlineFunctionWithArgs(
this.t, {
Key? key,
}) : super(key: key);
final void Function(BuildContext?) t;
@override
Widget build(BuildContext _context) => inlineFunctionWithArgs(t);
}
'''));
});
test('optional inline', () async {
await _expect('optionalInlineFunction', completion('''
class OptionalInlineFunction extends StatelessWidget {
const OptionalInlineFunction(
this.t, {
Key? key,
}) : super(key: key);
final void Function()? t;
@override
Widget build(BuildContext _context) => optionalInlineFunction(t);
}
'''));
});
test('nested function', () async {
await _expect('nestedFunction', completion('''
class NestedFunction extends StatelessWidget {
const NestedFunction(
this.t, {
Key? key,
}) : super(key: key);
final void Function(
void Function(int),
int,
) t;
@override
Widget build(BuildContext _context) => nestedFunction(t);
}
'''));
});
test('generic class', () async {
// currently not possible to know the type
await _expect('genericClass', completion('''
class GenericClass<T> extends StatelessWidget {
const GenericClass(
this.foo, {
Key? key,
}) : super(key: key);
final T Function() foo;
@override
Widget build(BuildContext _context) => genericClass<T>(foo);
}
'''));
});
test('generic class with nullable', () async {
await _expect('genericClassWithNullable', completion('''
class GenericClassWithNullable<T> extends StatelessWidget {
const GenericClassWithNullable(
this.foo, {
Key? key,
}) : super(key: key);
final T? Function() foo;
@override
Widget build(BuildContext _context) => genericClassWithNullable<T>(foo);
}
'''));
});
test('multiple generic class', () async {
await _expect('genericMultiple', completion('''
class GenericMultiple<T, S> extends StatelessWidget {
const GenericMultiple(
this.foo,
this.bar, {
Key? key,
}) : super(key: key);
final T foo;
final S bar;
@override
Widget build(BuildContext _context) => genericMultiple<T, S>(
foo,
bar,
);
}
'''));
});
test('generic function', () async {
await _expect('genericFunction', completion('''
class GenericFunction extends StatelessWidget {
const GenericFunction(
this.foo, {
Key? key,
}) : super(key: key);
final int Function(int) foo;
@override
Widget build(BuildContext _context) => genericFunction(foo);
}
'''));
});
test('generic function #2', () async {
await _expect('genericFunction2', completion('''
class GenericFunction2 extends StatelessWidget {
const GenericFunction2(
this.foo, {
Key? key,
}) : super(key: key);
final T Function<T>(T) foo;
@override
Widget build(BuildContext _context) => genericFunction2(foo);
}
'''));
});
test('generic function #3', () async {
await _expect('genericFunction3', completion('''
class GenericFunction3 extends StatelessWidget {
const GenericFunction3(
this.foo, {
Key? key,
}) : super(key: key);
final String Function(int) foo;
@override
Widget build(BuildContext _context) => genericFunction3(foo);
}
'''));
});
test('generic function #4', () async {
await _expect('genericFunction4', completion('''
class GenericFunction4 extends StatelessWidget {
const GenericFunction4(
this.foo, {
Key? key,
}) : super(key: key);
final T? Function<T>(T?)? foo;
@override
Widget build(BuildContext _context) => genericFunction4(foo);
}
'''));
});
});
group('custom named widgets', () {
test('hook widget', () async {
await _expect('hookWidgetWithCustomName', completion('''
class CustomHookWidget extends HookWidget {
const CustomHookWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext _context) => hookWidgetWithCustomName(_context);
}
'''));
});
});
group('annotations', () {
test('annotation', () async {
await _expect('annotation', completion('''
class Annotation extends StatelessWidget {
const Annotation({
Key? key,
@TestAnnotation() this.foo = 42,
}) : super(key: key);
final int foo;
@override
Widget build(BuildContext _context) => annotation(foo: foo);
}
'''));
});
test('stateless widget', () async {
await _expect('statelessWidgetWithCustomName', completion('''
class CustomStatelessWidget extends StatelessWidget {
const CustomStatelessWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext _context) =>
statelessWidgetWithCustomName(_context);
}
'''));
});
test('annotationParameter', () async {
await _expect('annotationParameter', completion('''
class AnnotationParameter extends StatelessWidget {
const AnnotationParameter({
Key? key,
@TestAnnotation('Test') this.foo = 42,
}) : super(key: key);
final int foo;
@override
Widget build(BuildContext _context) => annotationParameter(foo: foo);
}
'''));
});
test('annotationConstant', () async {
await _expect('annotationConstant', completion('''
class AnnotationConstant extends StatelessWidget {
const AnnotationConstant({
Key? key,
@testAnnotation this.foo = 42,
}) : super(key: key);
final int foo;
@override
Widget build(BuildContext _context) => annotationConstant(foo: foo);
}
'''));
});
});
});
}
| functional_widget/packages/functional_widget/test/success_test.dart/0 | {'file_path': 'functional_widget/packages/functional_widget/test/success_test.dart', 'repo_id': 'functional_widget', 'token_count': 5848} |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter_gen/gen_l10n/gallery_localizations.dart';
import 'package:gallery/data/gallery_options.dart';
import 'package:gallery/demos/cupertino/demo_types.dart';
// BEGIN cupertinoAlertDemo
class CupertinoAlertDemo extends StatefulWidget {
const CupertinoAlertDemo({
super.key,
required this.type,
});
final AlertDemoType type;
@override
State<CupertinoAlertDemo> createState() => _CupertinoAlertDemoState();
}
class _CupertinoAlertDemoState extends State<CupertinoAlertDemo>
with RestorationMixin {
RestorableStringN lastSelectedValue = RestorableStringN(null);
late RestorableRouteFuture<String> _alertDialogRoute;
late RestorableRouteFuture<String> _alertWithTitleDialogRoute;
late RestorableRouteFuture<String> _alertWithButtonsDialogRoute;
late RestorableRouteFuture<String> _alertWithButtonsOnlyDialogRoute;
late RestorableRouteFuture<String> _modalPopupRoute;
@override
String get restorationId => 'cupertino_alert_demo';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(
lastSelectedValue,
'last_selected_value',
);
registerForRestoration(
_alertDialogRoute,
'alert_demo_dialog_route',
);
registerForRestoration(
_alertWithTitleDialogRoute,
'alert_with_title_press_demo_dialog_route',
);
registerForRestoration(
_alertWithButtonsDialogRoute,
'alert_with_title_press_demo_dialog_route',
);
registerForRestoration(
_alertWithButtonsOnlyDialogRoute,
'alert_with_title_press_demo_dialog_route',
);
registerForRestoration(
_modalPopupRoute,
'modal_popup_route',
);
}
void _setSelectedValue(String value) {
setState(() {
lastSelectedValue.value = value;
});
}
@override
void initState() {
super.initState();
_alertDialogRoute = RestorableRouteFuture<String>(
onPresent: (navigator, arguments) {
return navigator.restorablePush(_alertDemoDialog);
},
onComplete: _setSelectedValue,
);
_alertWithTitleDialogRoute = RestorableRouteFuture<String>(
onPresent: (navigator, arguments) {
return navigator.restorablePush(_alertWithTitleDialog);
},
onComplete: _setSelectedValue,
);
_alertWithButtonsDialogRoute = RestorableRouteFuture<String>(
onPresent: (navigator, arguments) {
return navigator.restorablePush(_alertWithButtonsDialog);
},
onComplete: _setSelectedValue,
);
_alertWithButtonsOnlyDialogRoute = RestorableRouteFuture<String>(
onPresent: (navigator, arguments) {
return navigator.restorablePush(_alertWithButtonsOnlyDialog);
},
onComplete: _setSelectedValue,
);
_modalPopupRoute = RestorableRouteFuture<String>(
onPresent: (navigator, arguments) {
return navigator.restorablePush(_modalRoute);
},
onComplete: _setSelectedValue,
);
}
String _title(BuildContext context) {
final localizations = GalleryLocalizations.of(context)!;
switch (widget.type) {
case AlertDemoType.alert:
return localizations.demoCupertinoAlertTitle;
case AlertDemoType.alertTitle:
return localizations.demoCupertinoAlertWithTitleTitle;
case AlertDemoType.alertButtons:
return localizations.demoCupertinoAlertButtonsTitle;
case AlertDemoType.alertButtonsOnly:
return localizations.demoCupertinoAlertButtonsOnlyTitle;
case AlertDemoType.actionSheet:
return localizations.demoCupertinoActionSheetTitle;
}
}
static Route<String> _alertDemoDialog(
BuildContext context,
Object? arguments,
) {
final localizations = GalleryLocalizations.of(context)!;
return CupertinoDialogRoute<String>(
context: context,
builder: (context) => ApplyTextOptions(
child: CupertinoAlertDialog(
title: Text(localizations.dialogDiscardTitle),
actions: [
CupertinoDialogAction(
isDestructiveAction: true,
onPressed: () {
Navigator.of(
context,
).pop(localizations.cupertinoAlertDiscard);
},
child: Text(
localizations.cupertinoAlertDiscard,
),
),
CupertinoDialogAction(
isDefaultAction: true,
onPressed: () => Navigator.of(
context,
).pop(
localizations.cupertinoAlertCancel,
),
child: Text(
localizations.cupertinoAlertCancel,
),
),
],
),
),
);
}
static Route<String> _alertWithTitleDialog(
BuildContext context,
Object? arguments,
) {
final localizations = GalleryLocalizations.of(context)!;
return CupertinoDialogRoute<String>(
context: context,
builder: (context) => ApplyTextOptions(
child: CupertinoAlertDialog(
title: Text(
localizations.cupertinoAlertLocationTitle,
),
content: Text(
localizations.cupertinoAlertLocationDescription,
),
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.of(
context,
).pop(
localizations.cupertinoAlertDontAllow,
),
child: Text(
localizations.cupertinoAlertDontAllow,
),
),
CupertinoDialogAction(
onPressed: () => Navigator.of(
context,
).pop(
localizations.cupertinoAlertAllow,
),
child: Text(
localizations.cupertinoAlertAllow,
),
),
],
),
),
);
}
static Route<String> _alertWithButtonsDialog(
BuildContext context,
Object? arguments,
) {
final localizations = GalleryLocalizations.of(context)!;
return CupertinoDialogRoute<String>(
context: context,
builder: (context) => ApplyTextOptions(
child: CupertinoDessertDialog(
title: Text(
localizations.cupertinoAlertFavoriteDessert,
),
content: Text(
localizations.cupertinoAlertDessertDescription,
),
),
),
);
}
static Route<String> _alertWithButtonsOnlyDialog(
BuildContext context,
Object? arguments,
) {
return CupertinoDialogRoute<String>(
context: context,
builder: (context) => const ApplyTextOptions(
child: CupertinoDessertDialog(),
),
);
}
static Route<String> _modalRoute(
BuildContext context,
Object? arguments,
) {
final localizations = GalleryLocalizations.of(context)!;
return CupertinoModalPopupRoute<String>(
builder: (context) => ApplyTextOptions(
child: CupertinoActionSheet(
title: Text(
localizations.cupertinoAlertFavoriteDessert,
),
message: Text(
localizations.cupertinoAlertDessertDescription,
),
actions: [
CupertinoActionSheetAction(
onPressed: () => Navigator.of(
context,
).pop(
localizations.cupertinoAlertCheesecake,
),
child: Text(
localizations.cupertinoAlertCheesecake,
),
),
CupertinoActionSheetAction(
onPressed: () => Navigator.of(
context,
).pop(
localizations.cupertinoAlertTiramisu,
),
child: Text(
localizations.cupertinoAlertTiramisu,
),
),
CupertinoActionSheetAction(
onPressed: () => Navigator.of(
context,
).pop(
localizations.cupertinoAlertApplePie,
),
child: Text(
localizations.cupertinoAlertApplePie,
),
),
],
cancelButton: CupertinoActionSheetAction(
isDefaultAction: true,
onPressed: () => Navigator.of(
context,
).pop(
localizations.cupertinoAlertCancel,
),
child: Text(
localizations.cupertinoAlertCancel,
),
),
),
),
);
}
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
automaticallyImplyLeading: false,
middle: Text(_title(context)),
),
child: Builder(
builder: (context) {
return Column(
children: [
Expanded(
child: Center(
child: CupertinoButton.filled(
onPressed: () {
switch (widget.type) {
case AlertDemoType.alert:
_alertDialogRoute.present();
break;
case AlertDemoType.alertTitle:
_alertWithTitleDialogRoute.present();
break;
case AlertDemoType.alertButtons:
_alertWithButtonsDialogRoute.present();
break;
case AlertDemoType.alertButtonsOnly:
_alertWithButtonsOnlyDialogRoute.present();
break;
case AlertDemoType.actionSheet:
_modalPopupRoute.present();
break;
}
},
child: Text(
GalleryLocalizations.of(context)!.cupertinoShowAlert,
),
),
),
),
if (lastSelectedValue.value != null)
Padding(
padding: const EdgeInsets.all(16),
child: Text(
GalleryLocalizations.of(context)!
.dialogSelectedOption(lastSelectedValue.value!),
style: CupertinoTheme.of(context).textTheme.textStyle,
textAlign: TextAlign.center,
),
),
],
);
},
),
);
}
}
class CupertinoDessertDialog extends StatelessWidget {
const CupertinoDessertDialog({
super.key,
this.title,
this.content,
});
final Widget? title;
final Widget? content;
@override
Widget build(BuildContext context) {
final localizations = GalleryLocalizations.of(context)!;
return CupertinoAlertDialog(
title: title,
content: content,
actions: [
CupertinoDialogAction(
onPressed: () {
Navigator.of(
context,
).pop(
localizations.cupertinoAlertCheesecake,
);
},
child: Text(
localizations.cupertinoAlertCheesecake,
),
),
CupertinoDialogAction(
onPressed: () {
Navigator.of(
context,
).pop(
localizations.cupertinoAlertTiramisu,
);
},
child: Text(
localizations.cupertinoAlertTiramisu,
),
),
CupertinoDialogAction(
onPressed: () {
Navigator.of(
context,
).pop(
localizations.cupertinoAlertApplePie,
);
},
child: Text(
localizations.cupertinoAlertApplePie,
),
),
CupertinoDialogAction(
onPressed: () {
Navigator.of(
context,
).pop(
localizations.cupertinoAlertChocolateBrownie,
);
},
child: Text(
localizations.cupertinoAlertChocolateBrownie,
),
),
CupertinoDialogAction(
isDestructiveAction: true,
onPressed: () {
Navigator.of(
context,
).pop(
localizations.cupertinoAlertCancel,
);
},
child: Text(
localizations.cupertinoAlertCancel,
),
),
],
);
}
}
// END
| gallery/lib/demos/cupertino/cupertino_alert_demo.dart/0 | {'file_path': 'gallery/lib/demos/cupertino/cupertino_alert_demo.dart', 'repo_id': 'gallery', 'token_count': 6308} |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_gen/gen_l10n/gallery_localizations.dart';
// BEGIN bottomAppBarDemo
class BottomAppBarDemo extends StatefulWidget {
const BottomAppBarDemo({super.key});
@override
State createState() => _BottomAppBarDemoState();
}
class _BottomAppBarDemoState extends State<BottomAppBarDemo>
with RestorationMixin {
final RestorableBool _showFab = RestorableBool(true);
final RestorableBool _showNotch = RestorableBool(true);
final RestorableInt _currentFabLocation = RestorableInt(0);
@override
String get restorationId => 'bottom_app_bar_demo';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_showFab, 'show_fab');
registerForRestoration(_showNotch, 'show_notch');
registerForRestoration(_currentFabLocation, 'fab_location');
}
@override
void dispose() {
_showFab.dispose();
_showNotch.dispose();
_currentFabLocation.dispose();
super.dispose();
}
// Since FloatingActionButtonLocation is not an enum, the index of the
// selected FloatingActionButtonLocation is used for state restoration.
static const List<FloatingActionButtonLocation> _fabLocations = [
FloatingActionButtonLocation.endDocked,
FloatingActionButtonLocation.centerDocked,
FloatingActionButtonLocation.endFloat,
FloatingActionButtonLocation.centerFloat,
];
void _onShowNotchChanged(bool value) {
setState(() {
_showNotch.value = value;
});
}
void _onShowFabChanged(bool value) {
setState(() {
_showFab.value = value;
});
}
void _onFabLocationChanged(int? value) {
setState(() {
_currentFabLocation.value = value!;
});
}
@override
Widget build(BuildContext context) {
final localizations = GalleryLocalizations.of(context)!;
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(localizations.demoBottomAppBarTitle),
),
body: ListView(
padding: const EdgeInsets.only(bottom: 88),
children: [
SwitchListTile(
title: Text(
localizations.demoFloatingButtonTitle,
),
value: _showFab.value,
onChanged: _onShowFabChanged,
),
SwitchListTile(
title: Text(localizations.bottomAppBarNotch),
value: _showNotch.value,
onChanged: _onShowNotchChanged,
),
Padding(
padding: const EdgeInsets.all(16),
child: Text(localizations.bottomAppBarPosition),
),
RadioListTile<int>(
title: Text(
localizations.bottomAppBarPositionDockedEnd,
),
value: 0,
groupValue: _currentFabLocation.value,
onChanged: _onFabLocationChanged,
),
RadioListTile<int>(
title: Text(
localizations.bottomAppBarPositionDockedCenter,
),
value: 1,
groupValue: _currentFabLocation.value,
onChanged: _onFabLocationChanged,
),
RadioListTile<int>(
title: Text(
localizations.bottomAppBarPositionFloatingEnd,
),
value: 2,
groupValue: _currentFabLocation.value,
onChanged: _onFabLocationChanged,
),
RadioListTile<int>(
title: Text(
localizations.bottomAppBarPositionFloatingCenter,
),
value: 3,
groupValue: _currentFabLocation.value,
onChanged: _onFabLocationChanged,
),
],
),
floatingActionButton: _showFab.value
? Semantics(
container: true,
sortKey: const OrdinalSortKey(0),
child: FloatingActionButton(
onPressed: () {},
tooltip: localizations.buttonTextCreate,
child: const Icon(Icons.add),
),
)
: null,
floatingActionButtonLocation: _fabLocations[_currentFabLocation.value],
bottomNavigationBar: _DemoBottomAppBar(
fabLocation: _fabLocations[_currentFabLocation.value],
shape: _showNotch.value ? const CircularNotchedRectangle() : null,
),
);
}
}
class _DemoBottomAppBar extends StatelessWidget {
const _DemoBottomAppBar({
required this.fabLocation,
this.shape,
});
final FloatingActionButtonLocation fabLocation;
final NotchedShape? shape;
static final centerLocations = <FloatingActionButtonLocation>[
FloatingActionButtonLocation.centerDocked,
FloatingActionButtonLocation.centerFloat,
];
@override
Widget build(BuildContext context) {
final localizations = GalleryLocalizations.of(context)!;
return Semantics(
sortKey: const OrdinalSortKey(1),
container: true,
label: localizations.bottomAppBar,
child: BottomAppBar(
shape: shape,
child: IconTheme(
data: IconThemeData(color: Theme.of(context).colorScheme.onPrimary),
child: Row(
children: [
IconButton(
tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
icon: const Icon(Icons.menu),
onPressed: () {},
),
if (centerLocations.contains(fabLocation)) const Spacer(),
IconButton(
tooltip: localizations.starterAppTooltipSearch,
icon: const Icon(Icons.search),
onPressed: () {},
),
IconButton(
tooltip: localizations.starterAppTooltipFavorite,
icon: const Icon(Icons.favorite),
onPressed: () {},
)
],
),
),
),
);
}
}
// END
| gallery/lib/demos/material/bottom_app_bar_demo.dart/0 | {'file_path': 'gallery/lib/demos/material/bottom_app_bar_demo.dart', 'repo_id': 'gallery', 'token_count': 2651} |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:collection' show IterableMixin;
import 'dart:math';
import 'dart:ui' show Vertices;
import 'package:flutter/material.dart';
import 'package:vector_math/vector_math_64.dart' show Vector3;
// BEGIN transformationsDemo#2
// The entire state of the hex board and abstraction to get information about
// it. Iterable so that all BoardPoints on the board can be iterated over.
@immutable
class Board extends Object with IterableMixin<BoardPoint?> {
Board({
required this.boardRadius,
required this.hexagonRadius,
required this.hexagonMargin,
this.selected,
List<BoardPoint>? boardPoints,
}) : assert(boardRadius > 0),
assert(hexagonRadius > 0),
assert(hexagonMargin >= 0) {
// Set up the positions for the center hexagon where the entire board is
// centered on the origin.
// Start point of hexagon (top vertex).
final hexStart = Point<double>(0, -hexagonRadius);
final hexagonRadiusPadded = hexagonRadius - hexagonMargin;
final centerToFlat = sqrt(3) / 2 * hexagonRadiusPadded;
positionsForHexagonAtOrigin.addAll(<Offset>[
Offset(hexStart.x, hexStart.y),
Offset(hexStart.x + centerToFlat, hexStart.y + 0.5 * hexagonRadiusPadded),
Offset(hexStart.x + centerToFlat, hexStart.y + 1.5 * hexagonRadiusPadded),
Offset(hexStart.x + centerToFlat, hexStart.y + 1.5 * hexagonRadiusPadded),
Offset(hexStart.x, hexStart.y + 2 * hexagonRadiusPadded),
Offset(hexStart.x, hexStart.y + 2 * hexagonRadiusPadded),
Offset(hexStart.x - centerToFlat, hexStart.y + 1.5 * hexagonRadiusPadded),
Offset(hexStart.x - centerToFlat, hexStart.y + 1.5 * hexagonRadiusPadded),
Offset(hexStart.x - centerToFlat, hexStart.y + 0.5 * hexagonRadiusPadded),
]);
if (boardPoints != null) {
_boardPoints.addAll(boardPoints);
} else {
// Generate boardPoints for a fresh board.
var boardPoint = _getNextBoardPoint(null);
while (boardPoint != null) {
_boardPoints.add(boardPoint);
boardPoint = _getNextBoardPoint(boardPoint);
}
}
}
final int boardRadius; // Number of hexagons from center to edge.
final double hexagonRadius; // Pixel radius of a hexagon (center to vertex).
final double hexagonMargin; // Margin between hexagons.
final List<Offset> positionsForHexagonAtOrigin = <Offset>[];
final BoardPoint? selected;
final List<BoardPoint> _boardPoints = <BoardPoint>[];
@override
Iterator<BoardPoint?> get iterator => _BoardIterator(_boardPoints);
// For a given q axial coordinate, get the range of possible r values
// See the definition of BoardPoint for more information about hex grids and
// axial coordinates.
_Range _getRRangeForQ(int q) {
int rStart;
int rEnd;
if (q <= 0) {
rStart = -boardRadius - q;
rEnd = boardRadius;
} else {
rEnd = boardRadius - q;
rStart = -boardRadius;
}
return _Range(rStart, rEnd);
}
// Get the BoardPoint that comes after the given BoardPoint. If given null,
// returns the origin BoardPoint. If given BoardPoint is the last, returns
// null.
BoardPoint? _getNextBoardPoint(BoardPoint? boardPoint) {
// If before the first element.
if (boardPoint == null) {
return BoardPoint(-boardRadius, 0);
}
final rRange = _getRRangeForQ(boardPoint.q);
// If at or after the last element.
if (boardPoint.q >= boardRadius && boardPoint.r >= rRange.max) {
return null;
}
// If wrapping from one q to the next.
if (boardPoint.r >= rRange.max) {
return BoardPoint(boardPoint.q + 1, _getRRangeForQ(boardPoint.q + 1).min);
}
// Otherwise we're just incrementing r.
return BoardPoint(boardPoint.q, boardPoint.r + 1);
}
// Check if the board point is actually on the board.
bool _validateBoardPoint(BoardPoint boardPoint) {
const center = BoardPoint(0, 0);
final distanceFromCenter = getDistance(center, boardPoint);
return distanceFromCenter <= boardRadius;
}
// Get the size in pixels of the entire board.
Size get size {
final centerToFlat = sqrt(3) / 2 * hexagonRadius;
return Size(
(boardRadius * 2 + 1) * centerToFlat * 2,
2 * (hexagonRadius + boardRadius * 1.5 * hexagonRadius),
);
}
// Get the distance between two BoardPoints.
static int getDistance(BoardPoint a, BoardPoint b) {
final a3 = a.cubeCoordinates;
final b3 = b.cubeCoordinates;
return ((a3.x - b3.x).abs() + (a3.y - b3.y).abs() + (a3.z - b3.z).abs()) ~/
2;
}
// Return the q,r BoardPoint for a point in the scene, where the origin is in
// the center of the board in both coordinate systems. If no BoardPoint at the
// location, return null.
BoardPoint? pointToBoardPoint(Offset point) {
final pointCentered = Offset(
point.dx - size.width / 2,
point.dy - size.height / 2,
);
final boardPoint = BoardPoint(
((sqrt(3) / 3 * pointCentered.dx - 1 / 3 * pointCentered.dy) /
hexagonRadius)
.round(),
((2 / 3 * pointCentered.dy) / hexagonRadius).round(),
);
if (!_validateBoardPoint(boardPoint)) {
return null;
}
return _boardPoints.firstWhere((boardPointI) {
return boardPointI.q == boardPoint.q && boardPointI.r == boardPoint.r;
});
}
// Return a scene point for the center of a hexagon given its q,r point.
Point<double> boardPointToPoint(BoardPoint boardPoint) {
return Point<double>(
sqrt(3) * hexagonRadius * boardPoint.q +
sqrt(3) / 2 * hexagonRadius * boardPoint.r +
size.width / 2,
1.5 * hexagonRadius * boardPoint.r + size.height / 2,
);
}
// Get Vertices that can be drawn to a Canvas for the given BoardPoint.
Vertices getVerticesForBoardPoint(BoardPoint boardPoint, Color color) {
final centerOfHexZeroCenter = boardPointToPoint(boardPoint);
final positions = positionsForHexagonAtOrigin.map((offset) {
return offset.translate(centerOfHexZeroCenter.x, centerOfHexZeroCenter.y);
}).toList();
return Vertices(
VertexMode.triangleFan,
positions,
colors: List<Color>.filled(positions.length, color),
);
}
// Return a new board with the given BoardPoint selected.
Board copyWithSelected(BoardPoint? boardPoint) {
if (selected == boardPoint) {
return this;
}
final nextBoard = Board(
boardRadius: boardRadius,
hexagonRadius: hexagonRadius,
hexagonMargin: hexagonMargin,
selected: boardPoint,
boardPoints: _boardPoints,
);
return nextBoard;
}
// Return a new board where boardPoint has the given color.
Board copyWithBoardPointColor(BoardPoint boardPoint, Color color) {
final nextBoardPoint = boardPoint.copyWithColor(color);
final boardPointIndex = _boardPoints.indexWhere((boardPointI) =>
boardPointI.q == boardPoint.q && boardPointI.r == boardPoint.r);
if (elementAt(boardPointIndex) == boardPoint && boardPoint.color == color) {
return this;
}
final nextBoardPoints = List<BoardPoint>.from(_boardPoints);
nextBoardPoints[boardPointIndex] = nextBoardPoint;
final selectedBoardPoint =
boardPoint == selected ? nextBoardPoint : selected;
return Board(
boardRadius: boardRadius,
hexagonRadius: hexagonRadius,
hexagonMargin: hexagonMargin,
selected: selectedBoardPoint,
boardPoints: nextBoardPoints,
);
}
}
class _BoardIterator implements Iterator<BoardPoint?> {
_BoardIterator(this.boardPoints);
final List<BoardPoint> boardPoints;
int? currentIndex;
@override
BoardPoint? current;
@override
bool moveNext() {
if (currentIndex == null) {
currentIndex = 0;
} else {
currentIndex = currentIndex! + 1;
}
if (currentIndex! >= boardPoints.length) {
current = null;
return false;
}
current = boardPoints[currentIndex!];
return true;
}
}
// A range of q/r board coordinate values.
@immutable
class _Range {
const _Range(this.min, this.max) : assert(min <= max);
final int min;
final int max;
}
// A location on the board in axial coordinates.
// Axial coordinates use two integers, q and r, to locate a hexagon on a grid.
// https://www.redblobgames.com/grids/hexagons/#coordinates-axial
@immutable
class BoardPoint {
const BoardPoint(
this.q,
this.r, {
this.color = const Color(0xFFCDCDCD),
});
final int q;
final int r;
final Color color;
@override
String toString() {
return 'BoardPoint($q, $r, $color)';
}
// Only compares by location.
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is BoardPoint && other.q == q && other.r == r;
}
@override
int get hashCode => Object.hash(q, r);
BoardPoint copyWithColor(Color nextColor) =>
BoardPoint(q, r, color: nextColor);
// Convert from q,r axial coords to x,y,z cube coords.
Vector3 get cubeCoordinates {
return Vector3(
q.toDouble(),
r.toDouble(),
(-q - r).toDouble(),
);
}
}
// END
| gallery/lib/demos/reference/transformations_demo_board.dart/0 | {'file_path': 'gallery/lib/demos/reference/transformations_demo_board.dart', 'repo_id': 'gallery', 'token_count': 3406} |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math';
import 'package:dual_screen/dual_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/gallery_localizations.dart';
import 'package:gallery/constants.dart';
import 'package:gallery/layout/adaptive.dart';
import 'package:gallery/pages/home.dart';
const homePeekDesktop = 210.0;
const homePeekMobile = 60.0;
class SplashPageAnimation extends InheritedWidget {
const SplashPageAnimation({
super.key,
required this.isFinished,
required super.child,
});
final bool isFinished;
static SplashPageAnimation? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType();
}
@override
bool updateShouldNotify(SplashPageAnimation oldWidget) => true;
}
class SplashPage extends StatefulWidget {
const SplashPage({
super.key,
required this.child,
});
final Widget child;
@override
State<SplashPage> createState() => _SplashPageState();
}
class _SplashPageState extends State<SplashPage>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late int _effect;
final _random = Random();
// A map of the effect index to its duration. This duration is used to
// determine how long to display the splash animation at launch.
//
// If a new effect is added, this map should be updated.
final _effectDurations = {
1: 5,
2: 4,
3: 4,
4: 5,
5: 5,
6: 4,
7: 4,
8: 4,
9: 3,
10: 6,
};
bool get _isSplashVisible {
return _controller.status == AnimationStatus.completed ||
_controller.status == AnimationStatus.forward;
}
@override
void initState() {
super.initState();
// If the number of included effects changes, this number should be changed.
_effect = _random.nextInt(_effectDurations.length) + 1;
_controller =
AnimationController(duration: splashPageAnimationDuration, vsync: this)
..addListener(() {
setState(() {});
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Animation<RelativeRect> _getPanelAnimation(
BuildContext context,
BoxConstraints constraints,
) {
final height = constraints.biggest.height -
(isDisplayDesktop(context) ? homePeekDesktop : homePeekMobile);
return RelativeRectTween(
begin: const RelativeRect.fromLTRB(0, 0, 0, 0),
end: RelativeRect.fromLTRB(0, height, 0, 0),
).animate(CurvedAnimation(parent: _controller, curve: Curves.easeInOut));
}
@override
Widget build(BuildContext context) {
return NotificationListener<ToggleSplashNotification>(
onNotification: (_) {
_controller.forward();
return true;
},
child: SplashPageAnimation(
isFinished: _controller.status == AnimationStatus.dismissed,
child: LayoutBuilder(
builder: (context, constraints) {
final animation = _getPanelAnimation(context, constraints);
var frontLayer = widget.child;
if (_isSplashVisible) {
frontLayer = MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
_controller.reverse();
},
onVerticalDragEnd: (details) {
if (details.velocity.pixelsPerSecond.dy < -200) {
_controller.reverse();
}
},
child: IgnorePointer(child: frontLayer),
),
);
}
if (isDisplayDesktop(context)) {
frontLayer = Padding(
padding: const EdgeInsets.only(top: 136),
child: ClipRRect(
borderRadius: const BorderRadius.vertical(
top: Radius.circular(40),
),
child: frontLayer,
),
);
}
if (isDisplayFoldable(context)) {
return TwoPane(
startPane: frontLayer,
endPane: GestureDetector(
onTap: () {
if (_isSplashVisible) {
_controller.reverse();
} else {
_controller.forward();
}
},
child: _SplashBackLayer(
isSplashCollapsed: !_isSplashVisible, effect: _effect),
),
);
} else {
return Stack(
children: [
_SplashBackLayer(
isSplashCollapsed: !_isSplashVisible,
effect: _effect,
onTap: () {
_controller.forward();
},
),
PositionedTransition(
rect: animation,
child: frontLayer,
),
],
);
}
},
),
),
);
}
}
class _SplashBackLayer extends StatelessWidget {
const _SplashBackLayer({
required this.isSplashCollapsed,
required this.effect,
this.onTap,
});
final bool isSplashCollapsed;
final int effect;
final GestureTapCallback? onTap;
@override
Widget build(BuildContext context) {
var effectAsset = 'splash_effects/splash_effect_$effect.gif';
final flutterLogo = Image.asset(
'assets/logo/flutter_logo.png',
package: 'flutter_gallery_assets',
);
Widget? child;
if (isSplashCollapsed) {
if (isDisplayDesktop(context)) {
child = Padding(
padding: const EdgeInsets.only(top: 50),
child: Align(
alignment: Alignment.topCenter,
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: onTap,
child: flutterLogo,
),
),
),
);
}
if (isDisplayFoldable(context)) {
child = Container(
color: Theme.of(context).colorScheme.background,
child: Stack(
children: [
Center(
child: flutterLogo,
),
Padding(
padding: const EdgeInsets.only(top: 100.0),
child: Center(
child: Text(
GalleryLocalizations.of(context)!.splashSelectDemo,
),
),
)
],
),
);
}
} else {
child = Stack(
children: [
Center(
child: Image.asset(
effectAsset,
package: 'flutter_gallery_assets',
),
),
Center(child: flutterLogo),
],
);
}
return ExcludeSemantics(
child: Material(
// This is the background color of the gifs.
color: const Color(0xFF030303),
child: Padding(
padding: EdgeInsets.only(
bottom: isDisplayDesktop(context)
? homePeekDesktop
: isDisplayFoldable(context)
? 0
: homePeekMobile,
),
child: child,
),
),
);
}
}
| gallery/lib/pages/splash.dart/0 | {'file_path': 'gallery/lib/pages/splash.dart', 'repo_id': 'gallery', 'token_count': 3727} |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:gallery/layout/letter_spacing.dart';
import 'package:gallery/studies/crane/colors.dart';
import 'package:google_fonts/google_fonts.dart';
final ThemeData craneTheme = _buildCraneTheme();
IconThemeData _customIconTheme(IconThemeData original, Color color) {
return original.copyWith(color: color);
}
ThemeData _buildCraneTheme() {
final base = ThemeData.light();
return base.copyWith(
colorScheme: const ColorScheme.light().copyWith(
primary: cranePurple800,
secondary: craneRed700,
error: craneErrorOrange,
),
hintColor: craneWhite60,
indicatorColor: cranePrimaryWhite,
scaffoldBackgroundColor: cranePrimaryWhite,
cardColor: cranePrimaryWhite,
highlightColor: Colors.transparent,
textTheme: _buildCraneTextTheme(base.textTheme),
textSelectionTheme: const TextSelectionThemeData(
selectionColor: cranePurple700,
),
primaryTextTheme: _buildCraneTextTheme(base.primaryTextTheme),
iconTheme: _customIconTheme(base.iconTheme, craneWhite60),
primaryIconTheme: _customIconTheme(base.iconTheme, cranePrimaryWhite),
);
}
TextTheme _buildCraneTextTheme(TextTheme base) {
return GoogleFonts.ralewayTextTheme(
base.copyWith(
displayLarge: base.displayLarge!.copyWith(
fontWeight: FontWeight.w300,
fontSize: 96,
),
displayMedium: base.displayMedium!.copyWith(
fontWeight: FontWeight.w400,
fontSize: 60,
),
displaySmall: base.displaySmall!.copyWith(
fontWeight: FontWeight.w600,
fontSize: 48,
),
headlineMedium: base.headlineMedium!.copyWith(
fontWeight: FontWeight.w600,
fontSize: 34,
),
headlineSmall: base.headlineSmall!.copyWith(
fontWeight: FontWeight.w600,
fontSize: 24,
),
titleLarge: base.titleLarge!.copyWith(
fontWeight: FontWeight.w600,
fontSize: 20,
),
titleMedium: base.titleMedium!.copyWith(
fontWeight: FontWeight.w500,
fontSize: 16,
letterSpacing: letterSpacingOrNone(0.5),
),
titleSmall: base.titleSmall!.copyWith(
fontWeight: FontWeight.w600,
fontSize: 12,
color: craneGrey,
),
bodyLarge: base.bodyLarge!.copyWith(
fontWeight: FontWeight.w500,
fontSize: 16,
),
bodyMedium: base.bodyMedium!.copyWith(
fontWeight: FontWeight.w400,
fontSize: 14,
),
labelLarge: base.labelLarge!.copyWith(
fontWeight: FontWeight.w600,
fontSize: 13,
letterSpacing: letterSpacingOrNone(0.8),
),
bodySmall: base.bodySmall!.copyWith(
fontWeight: FontWeight.w500,
fontSize: 12,
color: craneGrey,
),
labelSmall: base.labelSmall!.copyWith(
fontWeight: FontWeight.w600,
fontSize: 12,
),
),
);
}
| gallery/lib/studies/crane/theme.dart/0 | {'file_path': 'gallery/lib/studies/crane/theme.dart', 'repo_id': 'gallery', 'token_count': 1247} |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_gen/gen_l10n/gallery_localizations.dart';
import 'package:gallery/studies/rally/charts/pie_chart.dart';
import 'package:gallery/studies/rally/data.dart';
import 'package:gallery/studies/rally/finance.dart';
import 'package:gallery/studies/rally/tabs/sidebar.dart';
/// A page that shows a summary of bills.
class BillsView extends StatefulWidget {
const BillsView({super.key});
@override
State<BillsView> createState() => _BillsViewState();
}
class _BillsViewState extends State<BillsView>
with SingleTickerProviderStateMixin {
@override
Widget build(BuildContext context) {
final items = DummyDataService.getBillDataList(context);
final dueTotal = sumBillDataPrimaryAmount(items);
final paidTotal = sumBillDataPaidAmount(items);
final detailItems = DummyDataService.getBillDetailList(
context,
dueTotal: dueTotal,
paidTotal: paidTotal,
);
return TabWithSidebar(
restorationId: 'bills_view',
mainView: FinancialEntityView(
heroLabel: GalleryLocalizations.of(context)!.rallyBillsDue,
heroAmount: dueTotal,
segments: buildSegmentsFromBillItems(items),
wholeAmount: dueTotal,
financialEntityCards: buildBillDataListViews(items, context),
),
sidebarItems: [
for (UserDetailData item in detailItems)
SidebarItem(title: item.title, value: item.value)
],
);
}
}
| gallery/lib/studies/rally/tabs/bills.dart/0 | {'file_path': 'gallery/lib/studies/rally/tabs/bills.dart', 'repo_id': 'gallery', 'token_count': 585} |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_gen/gen_l10n/gallery_localizations.dart';
import 'package:gallery/layout/letter_spacing.dart';
import 'package:gallery/studies/shrine/colors.dart';
import 'package:gallery/studies/shrine/expanding_bottom_sheet.dart';
import 'package:gallery/studies/shrine/model/app_state_model.dart';
import 'package:gallery/studies/shrine/model/product.dart';
import 'package:gallery/studies/shrine/theme.dart';
import 'package:intl/intl.dart';
import 'package:scoped_model/scoped_model.dart';
const _startColumnWidth = 60.0;
const _ordinalSortKeyName = 'shopping_cart';
class ShoppingCartPage extends StatefulWidget {
const ShoppingCartPage({super.key});
@override
State<ShoppingCartPage> createState() => _ShoppingCartPageState();
}
class _ShoppingCartPageState extends State<ShoppingCartPage> {
List<Widget> _createShoppingCartRows(AppStateModel model) {
return model.productsInCart.keys
.map(
(id) => ShoppingCartRow(
product: model.getProductById(id),
quantity: model.productsInCart[id],
onPressed: () {
model.removeItemFromCart(id);
},
),
)
.toList();
}
@override
Widget build(BuildContext context) {
final localTheme = Theme.of(context);
return Scaffold(
backgroundColor: shrinePink50,
body: SafeArea(
child: ScopedModelDescendant<AppStateModel>(
builder: (context, child, model) {
final localizations = GalleryLocalizations.of(context)!;
final expandingBottomSheet = ExpandingBottomSheet.of(context);
return Stack(
children: [
ListView(
children: [
Semantics(
sortKey:
const OrdinalSortKey(0, name: _ordinalSortKeyName),
child: Row(
children: [
SizedBox(
width: _startColumnWidth,
child: IconButton(
icon: const Icon(Icons.keyboard_arrow_down),
onPressed: () => expandingBottomSheet!.close(),
tooltip: localizations.shrineTooltipCloseCart,
),
),
Text(
localizations.shrineCartPageCaption,
style: localTheme.textTheme.titleMedium!
.copyWith(fontWeight: FontWeight.w600),
),
const SizedBox(width: 16),
Text(
localizations.shrineCartItemCount(
model.totalCartQuantity,
),
),
],
),
),
const SizedBox(height: 16),
Semantics(
sortKey:
const OrdinalSortKey(1, name: _ordinalSortKeyName),
child: Column(
children: _createShoppingCartRows(model),
),
),
Semantics(
sortKey:
const OrdinalSortKey(2, name: _ordinalSortKeyName),
child: ShoppingCartSummary(model: model),
),
const SizedBox(height: 100),
],
),
PositionedDirectional(
bottom: 16,
start: 16,
end: 16,
child: Semantics(
sortKey: const OrdinalSortKey(3, name: _ordinalSortKeyName),
child: ElevatedButton(
style: ElevatedButton.styleFrom(
shape: const BeveledRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(7)),
),
backgroundColor: shrinePink100,
),
onPressed: () {
model.clearCart();
expandingBottomSheet!.close();
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 12),
child: Text(
localizations.shrineCartClearButtonCaption,
style: TextStyle(
letterSpacing:
letterSpacingOrNone(largeLetterSpacing)),
),
),
),
),
),
],
);
},
),
),
);
}
}
class ShoppingCartSummary extends StatelessWidget {
const ShoppingCartSummary({
super.key,
required this.model,
});
final AppStateModel model;
@override
Widget build(BuildContext context) {
final smallAmountStyle =
Theme.of(context).textTheme.bodyMedium!.copyWith(color: shrineBrown600);
final largeAmountStyle = Theme.of(context)
.textTheme
.headlineMedium!
.copyWith(letterSpacing: letterSpacingOrNone(mediumLetterSpacing));
final formatter = NumberFormat.simpleCurrency(
decimalDigits: 2,
locale: Localizations.localeOf(context).toString(),
);
final localizations = GalleryLocalizations.of(context)!;
return Row(
children: [
const SizedBox(width: _startColumnWidth),
Expanded(
child: Padding(
padding: const EdgeInsetsDirectional.only(end: 16),
child: Column(
children: [
MergeSemantics(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SelectableText(
localizations.shrineCartTotalCaption,
),
Expanded(
child: SelectableText(
formatter.format(model.totalCost),
style: largeAmountStyle,
textAlign: TextAlign.end,
),
),
],
),
),
const SizedBox(height: 16),
MergeSemantics(
child: Row(
children: [
SelectableText(
localizations.shrineCartSubtotalCaption,
),
Expanded(
child: SelectableText(
formatter.format(model.subtotalCost),
style: smallAmountStyle,
textAlign: TextAlign.end,
),
),
],
),
),
const SizedBox(height: 4),
MergeSemantics(
child: Row(
children: [
SelectableText(
localizations.shrineCartShippingCaption,
),
Expanded(
child: SelectableText(
formatter.format(model.shippingCost),
style: smallAmountStyle,
textAlign: TextAlign.end,
),
),
],
),
),
const SizedBox(height: 4),
MergeSemantics(
child: Row(
children: [
SelectableText(
localizations.shrineCartTaxCaption,
),
Expanded(
child: SelectableText(
formatter.format(model.tax),
style: smallAmountStyle,
textAlign: TextAlign.end,
),
),
],
),
),
],
),
),
),
],
);
}
}
class ShoppingCartRow extends StatelessWidget {
const ShoppingCartRow({
super.key,
required this.product,
required this.quantity,
this.onPressed,
});
final Product product;
final int? quantity;
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) {
final formatter = NumberFormat.simpleCurrency(
decimalDigits: 0,
locale: Localizations.localeOf(context).toString(),
);
final localTheme = Theme.of(context);
final localizations = GalleryLocalizations.of(context)!;
return Padding(
padding: const EdgeInsets.only(bottom: 16),
child: Row(
key: ValueKey<int>(product.id),
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Semantics(
container: true,
label: localizations
.shrineScreenReaderRemoveProductButton(product.name(context)),
button: true,
enabled: true,
child: ExcludeSemantics(
child: SizedBox(
width: _startColumnWidth,
child: IconButton(
icon: const Icon(Icons.remove_circle_outline),
onPressed: onPressed,
tooltip: localizations.shrineTooltipRemoveItem,
),
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsetsDirectional.only(end: 16),
child: Column(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Image.asset(
product.assetName,
package: product.assetPackage,
fit: BoxFit.cover,
width: 75,
height: 75,
excludeFromSemantics: true,
),
const SizedBox(width: 16),
Expanded(
child: MergeSemantics(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
MergeSemantics(
child: Row(
children: [
Expanded(
child: SelectableText(
localizations
.shrineProductQuantity(quantity!),
),
),
SelectableText(
localizations.shrineProductPrice(
formatter.format(product.price),
),
),
],
),
),
SelectableText(
product.name(context),
style: localTheme.textTheme.titleMedium!
.copyWith(fontWeight: FontWeight.w600),
),
],
),
),
),
],
),
const SizedBox(height: 16),
const Divider(
color: shrineBrown900,
height: 10,
),
],
),
),
),
],
),
);
}
}
| gallery/lib/studies/shrine/shopping_cart.dart/0 | {'file_path': 'gallery/lib/studies/shrine/shopping_cart.dart', 'repo_id': 'gallery', 'token_count': 7541} |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Replace Windows line endings with Unix line endings
String standardizeLineEndings(String str) => str.replaceAll('\r\n', '\n');
| gallery/test/utils.dart/0 | {'file_path': 'gallery/test/utils.dart', 'repo_id': 'gallery', 'token_count': 78} |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'testing/font_loader.dart';
Future<void> testExecutable(FutureOr<void> Function() testMain) async {
final defaultReportTestException = reportTestException;
reportTestException = (details, testDescription) {
defaultReportTestException(details, testDescription);
stdout.writeln(
'\nThe golden tests failed. Please read test_goldens/README.md for how '
'to update them.',
);
};
TestWidgetsFlutterBinding.ensureInitialized();
await loadFonts();
await testMain();
}
| gallery/test_goldens/flutter_test_config.dart/0 | {'file_path': 'gallery/test_goldens/flutter_test_config.dart', 'repo_id': 'gallery', 'token_count': 240} |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'package:grinder/grinder.dart';
import 'package:path/path.dart' as path;
void main(List<String> args) => grind(args);
@Task('Get packages')
Future<void> pubGet({String? directory}) async {
await _runProcess(
'flutter',
['pub', 'get', if (directory != null) directory],
);
}
@Task('Format dart files')
Future<void> format({String path = '.'}) async {
await _runProcess('flutter', ['format', path]);
}
@Task('Transform arb to xml for English')
Future<void> l10n() async {
final l10nPath =
path.join(Directory.current.path, 'tool', 'l10n_cli', 'main.dart');
Dart.run(l10nPath);
}
@Task('Update code segments')
Future<void> updateCodeSegments() async {
final codeviewerPath =
path.join(Directory.current.path, 'tool', 'codeviewer_cli', 'main.dart');
Dart.run(codeviewerPath);
}
Future<void> _runProcess(String executable, List<String> arguments) async {
final result = await Process.run(executable, arguments);
stdout.write(result.stdout);
stderr.write(result.stderr);
}
| gallery/tool/grind.dart/0 | {'file_path': 'gallery/tool/grind.dart', 'repo_id': 'gallery', 'token_count': 421} |
include: package:flame_lint/analysis_options.yaml | gamepads/packages/gamepads_platform_interface/analysis_options.yaml/0 | {'file_path': 'gamepads/packages/gamepads_platform_interface/analysis_options.yaml', 'repo_id': 'gamepads', 'token_count': 15} |
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../game_internals/board_state.dart';
import 'playing_card_widget.dart';
class PlayerHandWidget extends StatelessWidget {
const PlayerHandWidget({super.key});
@override
Widget build(BuildContext context) {
final boardState = context.watch<BoardState>();
return Padding(
padding: const EdgeInsets.all(10),
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: PlayingCardWidget.height),
child: ListenableBuilder(
// Make sure we rebuild every time there's an update
// to the player's hand.
listenable: boardState.player,
builder: (context, child) {
return Wrap(
alignment: WrapAlignment.center,
spacing: 10,
runSpacing: 10,
children: [
...boardState.player.hand.map((card) =>
PlayingCardWidget(card, player: boardState.player)),
],
);
},
),
),
);
}
}
| games/templates/card/lib/play_session/player_hand_widget.dart/0 | {'file_path': 'games/templates/card/lib/play_session/player_hand_widget.dart', 'repo_id': 'games', 'token_count': 479} |
import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flutter/animation.dart';
/// The [JumpEffect] is simply a [MoveByEffect] which has the properties of the
/// effect pre-defined.
class JumpEffect extends MoveByEffect {
JumpEffect(Vector2 offset)
: super(offset, EffectController(duration: 0.3, curve: Curves.ease));
}
| games/templates/endless_runner/lib/flame_game/effects/jump_effect.dart/0 | {'file_path': 'games/templates/endless_runner/lib/flame_game/effects/jump_effect.dart', 'repo_id': 'games', 'token_count': 116} |
import 'package:endless_runner/app_lifecycle/app_lifecycle.dart';
import 'package:endless_runner/audio/audio_controller.dart';
import 'package:endless_runner/audio/sounds.dart';
import 'package:endless_runner/flame_game/endless_runner.dart';
import 'package:endless_runner/flame_game/game_screen.dart';
import 'package:endless_runner/player_progress/persistence/memory_player_progress_persistence.dart';
import 'package:endless_runner/player_progress/player_progress.dart';
import 'package:endless_runner/settings/settings.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:endless_runner/main.dart';
void main() {
testWidgets('smoke test menus', (tester) async {
// Build our game and trigger a frame.
await tester.pumpWidget(const MyGame());
// Verify that the 'Play' button is shown.
expect(find.text('Play'), findsOneWidget);
// Verify that the 'Settings' button is shown.
expect(find.text('Settings'), findsOneWidget);
// Go to 'Settings'.
await tester.tap(find.text('Settings'));
await tester.pumpAndSettle();
expect(find.text('Music'), findsOneWidget);
// Go back to main menu.
await tester.tap(find.text('Back'));
await tester.pumpAndSettle();
// Tap 'Play'.
await tester.tap(find.text('Play'));
await tester.pumpAndSettle();
expect(find.text('Select level'), findsOneWidget);
// Tap level 1.
await tester.tap(find.text('Level #1'));
await tester.pump();
});
testWithGame(
'smoke test flame game',
() {
return EndlessRunner(
level: (
number: 1,
winScore: 3,
canSpawnTall: false,
),
playerProgress: PlayerProgress(
store: MemoryOnlyPlayerProgressPersistence(),
),
audioController: _MockAudioController(),
);
},
(game) async {
game.overlays.addEntry(
GameScreen.backButtonKey,
(context, game) => Container(),
);
game.overlays.addEntry(
GameScreen.winDialogKey,
(context, game) => Container(),
);
await game.onLoad();
game.update(0);
expect(game.children.length, 3);
expect(game.world.children.length, 2);
expect(game.camera.viewport.children.length, 2);
expect(game.world.player.isLoading, isTrue);
},
);
}
class _MockAudioController implements AudioController {
@override
void attachDependencies(AppLifecycleStateNotifier lifecycleNotifier,
SettingsController settingsController) {}
@override
void dispose() {}
@override
void playSfx(SfxType type) {}
}
| games/templates/endless_runner/test/smoke_test.dart/0 | {'file_path': 'games/templates/endless_runner/test/smoke_test.dart', 'repo_id': 'games', 'token_count': 1020} |
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// This library provides a low-level API for accessing Google's Cloud
/// Datastore.
///
/// For more information on Cloud Datastore, please refer to the following
/// developers page: https://cloud.google.com/datastore/docs
library;
import 'dart:async';
import 'package:http/http.dart' as http;
import 'common.dart' show Page;
import 'service_scope.dart' as ss;
import 'src/datastore_impl.dart' show DatastoreImpl;
const Symbol _datastoreKey = #gcloud.datastore;
/// Access the [Datastore] object available in the current service scope.
///
/// The returned object will be the one which was previously registered with
/// [registerDatastoreService] within the current (or a parent) service scope.
///
/// Accessing this getter outside of a service scope will result in an error.
/// See the `package:gcloud/service_scope.dart` library for more information.
Datastore get datastoreService => ss.lookup(_datastoreKey) as Datastore;
/// Registers the [Datastore] object within the current service scope.
///
/// The provided `datastore` object will be available via the top-level
/// `datastore` getter.
///
/// Calling this function outside of a service scope will result in an error.
/// Calling this function more than once inside the same service scope is not
/// allowed.
void registerDatastoreService(Datastore datastore) {
ss.register(_datastoreKey, datastore);
}
class ApplicationError implements Exception {
final String message;
ApplicationError(this.message);
@override
String toString() => 'ApplicationError: $message';
}
class DatastoreError implements Exception {
final String message;
DatastoreError([String? message])
: message = message ?? 'DatastoreError: An unknown error occured';
@override
String toString() => message;
}
class UnknownDatastoreError extends DatastoreError {
UnknownDatastoreError(error) : super('An unknown error occured ($error).');
}
class TransactionAbortedError extends DatastoreError {
TransactionAbortedError() : super('The transaction was aborted.');
}
class TimeoutError extends DatastoreError {
TimeoutError() : super('The operation timed out.');
}
/// Thrown when a query would require an index which was not set.
///
/// An application needs to specify indices in a `index.yaml` file and needs to
/// create indices using the `gcloud preview datastore create-indexes` command.
class NeedIndexError extends DatastoreError {
NeedIndexError() : super('An index is needed for the query to succeed.');
}
class PermissionDeniedError extends DatastoreError {
PermissionDeniedError() : super('Permission denied.');
}
class InternalError extends DatastoreError {
InternalError() : super('Internal service error.');
}
class QuotaExceededError extends DatastoreError {
QuotaExceededError(error) : super('Quota was exceeded ($error).');
}
/// A datastore Entity
///
/// An entity is identified by a unique `key` and consists of a number of
/// `properties`. If a property should not be indexed, it needs to be included
/// in the `unIndexedProperties` set.
///
/// The `properties` field maps names to values. Values can be of a primitive
/// type or of a composed type.
///
/// The following primitive types are supported:
/// bool, int, double, String, DateTime, BlobValue, Key
///
/// It is possible to have a `List` of values. The values must be primitive.
/// Lists inside lists are not supported.
///
/// Whether a property is indexed or not applies to all values (this is only
/// relevant if the value is a list of primitive values).
class Entity {
final Key key;
final Map<String, Object?> properties;
final Set<String> unIndexedProperties;
Entity(this.key, this.properties,
{this.unIndexedProperties = const <String>{}});
}
/// A complete or partial key.
///
/// A key can uniquely identify a datastore `Entity`s. It consists of a
/// partition and path. The path consists of one or more `KeyElement`s.
///
/// A key may be incomplete. This is usesful when inserting `Entity`s which IDs
/// should be automatically allocated.
///
/// Example of a fully populated [Key]:
///
/// var fullKey = new Key([new KeyElement('Person', 1),
/// new KeyElement('Address', 2)]);
///
/// Example of a partially populated [Key] / an incomplete [Key]:
///
/// var partialKey = new Key([new KeyElement('Person', 1),
/// new KeyElement('Address', null)]);
class Key {
/// The partition of this `Key`.
final Partition partition;
/// The path of `KeyElement`s.
final List<KeyElement> elements;
Key(this.elements, {this.partition = Partition.DEFAULT});
factory Key.fromParent(String kind, int id, {Key? parent}) {
var partition = Partition.DEFAULT;
var elements = <KeyElement>[];
if (parent != null) {
partition = parent.partition;
elements.addAll(parent.elements);
}
elements.add(KeyElement(kind, id));
return Key(elements, partition: partition);
}
@override
int get hashCode =>
elements.fold(partition.hashCode, (a, b) => a ^ b.hashCode);
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
if (other is Key &&
partition == other.partition &&
elements.length == other.elements.length) {
for (var i = 0; i < elements.length; i++) {
if (elements[i] != other.elements[i]) return false;
}
return true;
}
return false;
}
@override
String toString() {
var namespaceString =
partition.namespace == null ? 'null' : "'${partition.namespace}'";
return "Key(namespace=$namespaceString, path=[${elements.join(', ')}])";
}
}
/// A datastore partition.
///
/// A partition is used for partitioning a dataset into multiple namespaces.
/// The default namespace is `null`. Using empty Strings as namespaces is
/// invalid.
///
// TODO(Issue #6): Add dataset-id here.
class Partition {
// ignore: constant_identifier_names
static const Partition DEFAULT = Partition._default();
/// The namespace of this partition.
///
/// The default namespace is `null`.
final String? namespace;
Partition(this.namespace) {
if (namespace == '') {
throw ArgumentError("'namespace' must not be empty");
}
}
const Partition._default() : namespace = null;
@override
int get hashCode => namespace.hashCode;
@override
bool operator ==(Object other) =>
other is Partition && namespace == other.namespace;
}
/// An element in a `Key`s path.
class KeyElement {
/// The kind of this element.
final String kind;
/// The ID of this element. It must be either an `int` or a `String.
///
/// This may be `null`, in which case it does not identify an Entity. It is
/// possible to insert [Entity]s with incomplete keys and let Datastore
/// automatically select a unused integer ID.
final dynamic id;
KeyElement(this.kind, this.id) {
if (id != null) {
if (id is! int && id is! String) {
throw ArgumentError("'id' must be either null, a String or an int");
}
}
}
@override
int get hashCode => kind.hashCode ^ id.hashCode;
@override
bool operator ==(Object other) =>
other is KeyElement && kind == other.kind && id == other.id;
@override
String toString() => '$kind.$id';
}
/// A relation used in query filters.
class FilterRelation {
// ignore: constant_identifier_names
static const FilterRelation LessThan = FilterRelation._('<');
// ignore: constant_identifier_names
static const FilterRelation LessThanOrEqual = FilterRelation._('<=');
// ignore: constant_identifier_names
static const FilterRelation GreatherThan = FilterRelation._('>');
// ignore: constant_identifier_names
static const FilterRelation GreatherThanOrEqual = FilterRelation._('>=');
// ignore: constant_identifier_names
static const FilterRelation Equal = FilterRelation._('==');
final String name;
const FilterRelation._(this.name);
@override
String toString() => name;
}
/// A filter used in queries.
class Filter {
/// The relation used for comparing `name` with `value`.
final FilterRelation relation;
/// The name of the datastore property used in the comparison.
final String name;
/// The value used for comparing against the property named by `name`.
final Object value;
Filter(this.relation, this.name, this.value);
}
/// The direction of a order.
///
// TODO(Issue #6): Make this class Private and add the two statics to the
/// 'Order' class.
/// [i.e. so one can write Order.Ascending, Order.Descending].
class OrderDirection {
// ignore: constant_identifier_names
static const OrderDirection Ascending = OrderDirection._('Ascending');
// ignore: constant_identifier_names
static const OrderDirection Decending = OrderDirection._('Decending');
final String name;
const OrderDirection._(this.name);
}
/// A order used in queries.
class Order {
/// The direction of the order.
final OrderDirection direction;
/// The name of the property used for the order.
final String propertyName;
// TODO(Issue #6): Make [direction] the second argument and make it optional.
Order(this.direction, this.propertyName);
}
/// A datastore query.
///
/// A query consists of filters (kind, ancestor and property filters), one or
/// more orders and a offset/limit pair.
///
/// All fields may be optional.
///
/// Example of building a [Query]:
/// var person = ....;
/// var query = new Query(ancestorKey: personKey, kind: 'Address')
class Query {
/// Restrict the result set to entities of this kind.
final String? kind;
/// Restrict the result set to entities which have this ancestorKey / parent.
final Key? ancestorKey;
/// Restrict the result set by a list of property [Filter]s.
final List<Filter>? filters;
/// Order the matching entities following the given property [Order]s.
final List<Order>? orders;
/// Skip the first [offset] entities in the result set.
final int? offset;
/// Limit the number of entities returned to [limit].
final int? limit;
Query({
this.ancestorKey,
this.kind,
this.filters,
this.orders,
this.offset,
this.limit,
});
}
/// The result of a commit.
class CommitResult {
/// If the commit included `autoIdInserts`, this list will be the fully
/// populated Keys, including the automatically allocated integer IDs.
final List<Key> autoIdInsertKeys;
CommitResult(this.autoIdInsertKeys);
}
/// A blob value which can be used as a property value in `Entity`s.
class BlobValue {
/// The binary data of this blob.
final List<int> bytes;
BlobValue(this.bytes);
}
/// An opaque token returned by the `beginTransaction` method of a [Datastore].
///
/// This token can be passed to the `commit` and `lookup` calls if they should
/// operate within this transaction.
abstract class Transaction {}
/// Interface used to talk to the Google Cloud Datastore service.
///
/// It can be used to insert/update/delete [Entity]s, lookup/query [Entity]s
/// and allocate IDs from the auto ID allocation policy.
abstract class Datastore {
/// List of required OAuth2 scopes for Datastore operation.
// ignore: constant_identifier_names
static const Scopes = DatastoreImpl.scopes;
/// Access Datastore using an authenticated client.
///
/// The [client] is an authenticated HTTP client. This client must
/// provide access to at least the scopes in `Datastore.Scopes`.
///
/// The [project] is the name of the Google Cloud project.
///
/// Returs an object providing access to Datastore. The passed-in [client]
/// will not be closed automatically. The caller is responsible for closing
/// it.
factory Datastore(http.Client client, String project) {
return DatastoreImpl(client, project);
}
/// Allocate integer IDs for the partially populated [keys] given as argument.
///
/// The returned [Key]s will be fully populated with the allocated IDs.
Future<List<Key>> allocateIds(List<Key> keys);
/// Starts a new transaction and returns an opaque value representing it.
///
/// If [crossEntityGroup] is `true`, the transaction can work on up to 5
/// entity groups. Otherwise the transaction will be limited to only operate
/// on a single entity group.
Future<Transaction> beginTransaction({bool crossEntityGroup = false});
/// Make modifications to the datastore.
///
/// - `inserts` are [Entity]s which have a fully populated [Key] and should
/// be either added to the datastore or updated.
///
/// - `autoIdInserts` are [Entity]s which do not have a fully populated [Key]
/// and should be added to the dataset, automatically assigning integer
/// IDs.
/// The returned [CommitResult] will contain the fully populated keys.
///
/// - `deletes` are a list of fully populated [Key]s which uniquely identify
/// the [Entity]s which should be deleted.
///
/// If a [transaction] is given, all modifications will be done within that
/// transaction.
///
/// This method might complete with a [TransactionAbortedError] error.
/// Users must take care of retrying transactions.
// TODO(Issue #6): Consider splitting `inserts` into insert/update/upsert.
Future<CommitResult> commit(
{List<Entity> inserts,
List<Entity> autoIdInserts,
List<Key> deletes,
Transaction transaction});
/// Roll a started transaction back.
Future rollback(Transaction transaction);
/// Looks up the fully populated [keys] in the datastore and returns either
/// the [Entity] corresponding to the [Key] or `null`. The order in the
/// returned [Entity]s is the same as in [keys].
///
/// If a [transaction] is given, the lookup will be within this transaction.
Future<List<Entity?>> lookup(List<Key> keys, {Transaction transaction});
/// Runs a query on the dataset and returns a [Page] of matching [Entity]s.
///
/// The [Page] instance returned might not contain all matching [Entity]s -
/// in which case `isLast` is set to `false`. The page's `next` method can
/// be used to page through the whole result set.
/// The maximum number of [Entity]s returned within a single page is
/// implementation specific.
///
/// - `query` is used to restrict the number of returned [Entity]s and may
/// may specify an order.
///
/// - `partition` can be used to specify the namespace used for the lookup.
///
/// If a [transaction] is given, the query will be within this transaction.
/// But note that arbitrary queries within a transaction are not possible.
/// A transaction is limited to a very small number of entity groups. Usually
/// queries with transactions are restricted by providing an ancestor filter.
///
/// Outside of transactions, the result set might be stale. Queries are by
/// default eventually consistent.
Future<Page<Entity>> query(Query query,
{Partition partition, Transaction transaction});
}
| gcloud/lib/datastore.dart/0 | {'file_path': 'gcloud/lib/datastore.dart', 'repo_id': 'gcloud', 'token_count': 4440} |
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// This library provides access to Google Cloud Storage.
///
/// Google Cloud Storage is an object store for binary objects. Each
/// object has a set of metadata attached to it. For more information on
/// Google Cloud Storage see https://developers.google.com/storage/.
///
/// There are two main concepts in Google Cloud Storage: Buckets and Objects.
/// A bucket is a container for objects and objects are the actual binary
/// objects.
///
/// The API has two main classes for dealing with buckets and objects.
///
/// The class `Storage` is the main API class providing access to working
/// with buckets. This is the 'bucket service' interface.
///
/// The class `Bucket` provide access to working with objects in a specific
/// bucket. This is the 'object service' interface.
///
/// Both buckets have objects, have names. The bucket namespace is flat and
/// global across all projects. This means that a bucket is always
/// addressable using its name without requiring further context.
///
/// Within buckets the object namespace is also flat. Object are *not*
/// organized hierarchical. However, as object names allow the slash `/`
/// character this is often used to simulate a hierarchical structure
/// based on common prefixes.
///
/// This package uses relative and absolute names to refer to objects. A
/// relative name is just the object name within a bucket, and requires the
/// context of a bucket to be used. A relative name just looks like this:
///
/// object_name
///
/// An absolute name includes the bucket name and uses the `gs://` prefix
/// also used by the `gsutil` tool. An absolute name looks like this.
///
/// gs://bucket_name/object_name
///
/// In most cases relative names are used. Absolute names are typically
/// only used for operations involving objects in different buckets.
///
/// For most of the APIs in ths library which take instances of other classes
/// from this library it is the assumption that the actual implementations
/// provided here are used.
library;
import 'dart:async';
import 'dart:collection' show UnmodifiableListView, UnmodifiableMapView;
import 'dart:convert';
import 'dart:typed_data';
import 'package:_discoveryapis_commons/_discoveryapis_commons.dart' as commons;
import 'package:googleapis/storage/v1.dart' as storage_api;
import 'package:http/http.dart' as http;
import 'common.dart';
import 'service_scope.dart' as ss;
export 'common.dart';
part 'src/storage_impl.dart';
const Symbol _storageKey = #gcloud.storage;
/// Access the [Storage] object available in the current service scope.
///
/// The returned object will be the one which was previously registered with
/// [registerStorageService] within the current (or a parent) service scope.
///
/// Accessing this getter outside of a service scope will result in an error.
/// See the `package:gcloud/service_scope.dart` library for more information.
Storage get storageService => ss.lookup(_storageKey) as Storage;
/// Registers the [storage] object within the current service scope.
///
/// The provided `storage` object will be available via the top-level
/// `storageService` getter.
///
/// Calling this function outside of a service scope will result in an error.
/// Calling this function more than once inside the same service scope is not
/// allowed.
void registerStorageService(Storage storage) {
ss.register(_storageKey, storage);
}
/// An ACL (Access Control List) describes access rights to buckets and
/// objects.
///
/// An ACL is a prioritized sequence of access control specifications,
/// which individually prevent or grant access.
/// The access controls are described by [AclEntry] objects.
class Acl {
final List<AclEntry> _entries;
/// The entries in the ACL.
List<AclEntry> get entries => UnmodifiableListView<AclEntry>(_entries);
/// Create a new ACL with a list of ACL entries.
Acl(Iterable<AclEntry> entries) : _entries = List.from(entries);
Acl._fromBucketAcl(storage_api.Bucket bucket)
: _entries = [
for (final control
in bucket.acl ?? const <storage_api.BucketAccessControl>[])
AclEntry(_aclScopeFromEntity(control.entity!),
_aclPermissionFromRole(control.role))
];
Acl._fromObjectAcl(storage_api.Object object)
: _entries = [
for (final entry in object.acl ?? <storage_api.ObjectAccessControl>[])
AclEntry(_aclScopeFromEntity(entry.entity!),
_aclPermissionFromRole(entry.role)),
];
static AclScope _aclScopeFromEntity(String entity) {
if (entity.startsWith('user-')) {
var tmp = entity.substring(5);
var at = tmp.indexOf('@');
if (at != -1) {
return AccountScope(tmp);
} else {
return StorageIdScope(tmp);
}
} else if (entity.startsWith('group-')) {
return GroupScope(entity.substring(6));
} else if (entity.startsWith('domain-')) {
return DomainScope(entity.substring(7));
} else if (entity.startsWith('allAuthenticatedUsers-')) {
return AclScope.allAuthenticated;
} else if (entity.startsWith('allUsers-')) {
return AclScope.allUsers;
} else if (entity.startsWith('project-')) {
var tmp = entity.substring(8);
var dash = tmp.indexOf('-');
if (dash != -1) {
return ProjectScope(tmp.substring(dash + 1), tmp.substring(0, dash));
}
}
return OpaqueScope(entity);
}
static AclPermission _aclPermissionFromRole(String? role) {
if (role == 'READER') return AclPermission.READ;
if (role == 'WRITER') return AclPermission.WRITE;
if (role == 'OWNER') return AclPermission.FULL_CONTROL;
throw UnsupportedError(
"Server returned a unsupported permission role '$role'");
}
List<storage_api.BucketAccessControl> _toBucketAccessControlList() {
return _entries.map((entry) => entry._toBucketAccessControl()).toList();
}
List<storage_api.ObjectAccessControl> _toObjectAccessControlList() {
return _entries.map((entry) => entry._toObjectAccessControl()).toList();
}
@override
late final int hashCode = Object.hashAll(_entries);
@override
bool operator ==(Object other) {
if (other is Acl) {
List entries = _entries;
List otherEntries = other._entries;
if (entries.length != otherEntries.length) return false;
for (var i = 0; i < entries.length; i++) {
if (entries[i] != otherEntries[i]) return false;
}
return true;
} else {
return false;
}
}
@override
String toString() => 'Acl($_entries)';
}
/// An ACL entry specifies that an entity has a specific access permission.
///
/// A permission grants a specific permission to the entity.
class AclEntry {
final AclScope scope;
final AclPermission permission;
AclEntry(this.scope, this.permission);
storage_api.BucketAccessControl _toBucketAccessControl() {
var acl = storage_api.BucketAccessControl();
acl.entity = scope._storageEntity;
acl.role = permission._storageBucketRole;
return acl;
}
storage_api.ObjectAccessControl _toObjectAccessControl() {
var acl = storage_api.ObjectAccessControl();
acl.entity = scope._storageEntity;
acl.role = permission._storageObjectRole;
return acl;
}
@override
late final int hashCode = Object.hash(scope, permission);
@override
bool operator ==(Object other) {
return other is AclEntry &&
scope == other.scope &&
permission == other.permission;
}
@override
String toString() => 'AclEntry($scope, $permission)';
}
/// An ACL scope specifies an entity for which a permission applies.
///
/// A scope can be one of:
///
/// * Google Storage ID
/// * Google account email address
/// * Google group email address
/// * Google Apps domain
/// * Special identifier for all Google account holders
/// * Special identifier for all users
///
/// See https://cloud.google.com/storage/docs/accesscontrol for more details.
abstract class AclScope {
/// ACL type for scope representing a Google Storage id.
static const int _typeStorageId = 0;
/// ACL type for scope representing a project entity.
static const int _typeProject = 1;
/// ACL type for scope representing an account holder.
static const int _typeAccount = 2;
/// ACL type for scope representing a group.
static const int _typeGroup = 3;
/// ACL type for scope representing a domain.
static const int _typeDomain = 4;
/// ACL type for scope representing all authenticated users.
static const int _typeAllAuthenticated = 5;
/// ACL type for scope representing all users.
static const int _typeAllUsers = 6;
/// ACL type for scope representing an unsupported scope.
static const int _typeOpaque = 7;
/// The id of the actual entity this ACL scope represents. The actual values
/// are set in the different subclasses.
final String _id;
/// The type of this acope this ACL scope represents.
final int _type;
/// ACL scope for all authenticated users.
static AllAuthenticatedScope allAuthenticated = AllAuthenticatedScope();
/// ACL scope for all users.
static AllUsersScope allUsers = AllUsersScope();
AclScope._(this._type, this._id);
@override
late final int hashCode = Object.hash(_type, _id);
@override
bool operator ==(Object other) {
return other is AclScope && _type == other._type && _id == other._id;
}
@override
String toString() => 'AclScope($_storageEntity)';
String get _storageEntity;
}
/// An ACL scope for an entity identified by a 'Google Storage ID'.
///
/// The [storageId] is a string of 64 hexadecimal digits that identifies a
/// specific Google account holder or a specific Google group.
class StorageIdScope extends AclScope {
StorageIdScope(String storageId)
: super._(AclScope._typeStorageId, storageId);
/// Google Storage ID.
String get storageId => _id;
@override
String get _storageEntity => 'user-$_id';
}
/// An ACL scope for an entity identified by an individual email address.
class AccountScope extends AclScope {
AccountScope(String email) : super._(AclScope._typeAccount, email);
/// Email address.
String get email => _id;
@override
String get _storageEntity => 'user-$_id';
}
/// An ACL scope for an entity identified by an Google Groups email.
class GroupScope extends AclScope {
GroupScope(String group) : super._(AclScope._typeGroup, group);
/// Group name.
String get group => _id;
@override
String get _storageEntity => 'group-$_id';
}
/// An ACL scope for an entity identified by a domain name.
class DomainScope extends AclScope {
DomainScope(String domain) : super._(AclScope._typeDomain, domain);
/// Domain name.
String get domain => _id;
@override
String get _storageEntity => 'domain-$_id';
}
/// An ACL scope for an project related entity.
class ProjectScope extends AclScope {
/// Project role.
///
/// Possible values are `owners`, `editors` and `viewers`.
final String role;
ProjectScope(String project, this.role)
: super._(AclScope._typeProject, project);
/// Project ID.
String get project => _id;
@override
String get _storageEntity => 'project-$role-$_id';
}
/// An ACL scope for an unsupported scope.
class OpaqueScope extends AclScope {
OpaqueScope(String id) : super._(AclScope._typeOpaque, id);
@override
String get _storageEntity => _id;
}
/// ACL scope for a all authenticated users.
class AllAuthenticatedScope extends AclScope {
AllAuthenticatedScope() : super._(AclScope._typeAllAuthenticated, 'invalid');
@override
String get _storageEntity => 'allAuthenticatedUsers';
}
/// ACL scope for a all users.
class AllUsersScope extends AclScope {
AllUsersScope() : super._(AclScope._typeAllUsers, 'invalid');
@override
String get _storageEntity => 'allUsers';
}
/// Permissions for individual scopes in an ACL.
class AclPermission {
/// Provide read access.
// ignore: constant_identifier_names
static const READ = AclPermission._('READER');
/// Provide write access.
///
/// For objects this permission is the same as [FULL_CONTROL].
// ignore: constant_identifier_names
static const WRITE = AclPermission._('WRITER');
/// Provide full control.
///
/// For objects this permission is the same as [WRITE].
// ignore: constant_identifier_names
static const FULL_CONTROL = AclPermission._('OWNER');
final String _id;
const AclPermission._(this._id);
String get _storageBucketRole => _id;
String get _storageObjectRole => this == WRITE ? FULL_CONTROL._id : _id;
@override
int get hashCode => _id.hashCode;
@override
bool operator ==(Object other) {
return other is AclPermission && _id == other._id;
}
@override
String toString() => 'AclPermission($_id)';
}
/// Definition of predefined ACLs.
///
/// There is a convenient way of referring to number of _predefined_ ACLs. These
/// predefined ACLs have explicit names, and can _only_ be used to set an ACL,
/// when either creating or updating a bucket or object. This set of predefined
/// ACLs are expanded on the server to their actual list of [AclEntry] objects.
/// When information is retrieved on a bucket or object, this expanded list will
/// be present. For a description of these predefined ACLs see:
/// https://cloud.google.com/storage/docs/accesscontrol#extension.
class PredefinedAcl {
final String _name;
const PredefinedAcl._(this._name);
/// Predefined ACL for the 'authenticated-read' ACL. Applies to both buckets
/// and objects.
static const PredefinedAcl authenticatedRead =
PredefinedAcl._('authenticatedRead');
/// Predefined ACL for the 'private' ACL. Applies to both buckets
/// and objects.
static const PredefinedAcl private = PredefinedAcl._('private');
/// Predefined ACL for the 'project-private' ACL. Applies to both buckets
/// and objects.
static const PredefinedAcl projectPrivate = PredefinedAcl._('projectPrivate');
/// Predefined ACL for the 'public-read' ACL. Applies to both buckets
/// and objects.
static const PredefinedAcl publicRead = PredefinedAcl._('publicRead');
/// Predefined ACL for the 'public-read-write' ACL. Applies only to buckets.
static const PredefinedAcl publicReadWrite =
PredefinedAcl._('publicReadWrite');
/// Predefined ACL for the 'bucket-owner-full-control' ACL. Applies only to
/// objects.
static const PredefinedAcl bucketOwnerFullControl =
PredefinedAcl._('bucketOwnerFullControl');
/// Predefined ACL for the 'bucket-owner-read' ACL. Applies only to
/// objects.
static const PredefinedAcl bucketOwnerRead =
PredefinedAcl._('bucketOwnerRead');
@override
String toString() => 'PredefinedAcl($_name)';
}
/// Information on a bucket.
abstract class BucketInfo {
/// Name of the bucket.
String get bucketName;
/// Entity tag for the bucket.
String get etag;
/// When this bucket was created.
DateTime get created;
/// Bucket ID.
String get id;
/// Acl of the bucket.
Acl get acl;
}
/// Access to Cloud Storage
abstract class Storage {
/// List of required OAuth2 scopes for Cloud Storage operation.
// ignore: constant_identifier_names
static const List<String> SCOPES = <String>[
storage_api.StorageApi.devstorageFullControlScope
];
/// Initializes access to cloud storage.
factory Storage(http.Client client, String project) = _StorageImpl;
/// Create a cloud storage bucket.
///
/// Creates a cloud storage bucket named [bucketName].
///
/// The bucket ACL can be set by passing [predefinedAcl] or [acl]. If both
/// are passed the entries from [acl] with be followed by the expansion of
/// [predefinedAcl].
///
/// Returns a [Future] which completes when the bucket has been created.
Future createBucket(String bucketName,
{PredefinedAcl? predefinedAcl, Acl? acl});
/// Delete a cloud storage bucket.
///
/// Deletes the cloud storage bucket named [bucketName].
///
/// If the bucket is not empty the operation will fail.
///
/// The returned [Future] completes when the operation is finished.
Future deleteBucket(String bucketName);
/// Access bucket object operations.
///
/// Instantiates a `Bucket` object referring to the bucket named [bucketName].
///
/// When an object is created using the resulting `Bucket` an ACL will always
/// be set. If the object creation does not pass any explicit ACL information
/// a default ACL will be used.
///
/// If the arguments [defaultPredefinedObjectAcl] or [defaultObjectAcl] are
/// passed they define the default ACL. If both are passed the entries from
/// [defaultObjectAcl] with be followed by the expansion of
/// [defaultPredefinedObjectAcl] when an object is created.
///
/// Otherwise the default object ACL attached to the bucket will be used.
///
/// Returns a `Bucket` instance.
Bucket bucket(String bucketName,
{PredefinedAcl? defaultPredefinedObjectAcl, Acl? defaultObjectAcl});
/// Check whether a cloud storage bucket exists.
///
/// Checks whether the bucket named [bucketName] exists.
///
/// Returns a [Future] which completes with `true` if the bucket exists.
Future<bool> bucketExists(String bucketName);
/// Get information on a bucket
///
/// Provide metadata information for bucket named [bucketName].
///
/// Returns a [Future] which completes with a `BucketInfo` object.
Future<BucketInfo> bucketInfo(String bucketName);
/// List names of all buckets.
///
/// Returns a [Stream] of bucket names.
Stream<String> listBucketNames();
/// Start paging through names of all buckets.
///
/// The maximum number of buckets in each page is specified in [pageSize].
///
/// Returns a [Future] which completes with a `Page` object holding the
/// first page. Use the `Page` object to move to the next page of buckets.
Future<Page<String>> pageBucketNames({int pageSize = 50});
/// Copy an object.
///
/// Copy object [src] to object [dest].
///
/// The names of [src] and [dest] must be absolute.
Future copyObject(String src, String dest);
}
/// Information on a specific object.
///
/// This class provides access to information on an object. This includes
/// both the properties which are provided by Cloud Storage (such as the
/// MD5 hash) and the properties which can be changed (such as content type).
///
/// The properties provided by Cloud Storage are direct properties on this
/// object.
///
/// The mutable properties are properties on the `metadata` property.
abstract class ObjectInfo {
/// Name of the object.
String get name;
/// Length of the data.
int get length;
/// When this object was updated.
DateTime get updated;
/// Entity tag for the object.
String get etag;
/// MD5 hash of the object.
List<int> get md5Hash;
/// CRC32c checksum, as described in RFC 4960.
int get crc32CChecksum;
/// URL for direct download.
Uri get downloadLink;
/// Object generation.
ObjectGeneration get generation;
/// Additional metadata.
ObjectMetadata get metadata;
}
/// Generational information on an object.
class ObjectGeneration {
/// Object generation.
final String objectGeneration;
/// Metadata generation.
final int metaGeneration;
const ObjectGeneration(this.objectGeneration, this.metaGeneration);
}
/// Access to object metadata.
abstract class ObjectMetadata {
factory ObjectMetadata(
{Acl? acl,
String? contentType,
String? contentEncoding,
String? cacheControl,
String? contentDisposition,
String? contentLanguage,
Map<String, String>? custom}) = _ObjectMetadata;
/// ACL.
Acl? get acl;
/// `Content-Type` for this object.
String? get contentType;
/// `Content-Encoding` for this object.
String? get contentEncoding;
/// `Cache-Control` for this object.
String? get cacheControl;
/// `Content-Disposition` for this object.
String? get contentDisposition;
/// `Content-Language` for this object.
///
/// The value of this field must confirm to RFC 3282.
String? get contentLanguage;
/// Custom metadata.
Map<String, String>? get custom;
/// Create a copy of this object with some values replaced.
///
// TODO: This cannot be used to set values to null.
ObjectMetadata replace(
{Acl? acl,
String? contentType,
String? contentEncoding,
String? cacheControl,
String? contentDisposition,
String? contentLanguage,
Map<String, String>? custom});
}
/// Result from List objects in a bucket.
///
/// Listing operate like a directory listing, despite the object
/// namespace being flat.
///
/// See [Bucket.list] for information on how the hierarchical structure
/// is determined.
class BucketEntry {
/// Whether this is information on an object.
final bool isObject;
/// Name of object or directory.
final String name;
BucketEntry._object(this.name) : isObject = true;
BucketEntry._directory(this.name) : isObject = false;
/// Whether this is a prefix.
bool get isDirectory => !isObject;
}
/// Access to operations on a specific cloud storage bucket.
abstract class Bucket {
/// Name of this bucket.
String get bucketName;
/// Absolute name of an object in this bucket. This includes the gs:// prefix.
String absoluteObjectName(String objectName);
/// Create a new object.
///
/// Create an object named [objectName] in the bucket.
///
/// If an object named [objectName] already exists this object will be
/// replaced.
///
/// If the length of the data to write is known in advance this can be passed
/// as [length]. This can help to optimize the upload process.
///
/// Additional metadata on the object can be passed either through the
/// `metadata` argument or through the specific named arguments
/// (such as `contentType`). Values passed through the specific named
/// arguments takes precedence over the values in `metadata`.
///
/// If [contentType] is not passed the default value of
/// `application/octet-stream` will be used.
///
/// It is possible to at one of the predefined ACLs on the created object
/// using the [predefinedAcl] argument. If the [metadata] argument contain a
/// ACL as well, this ACL with be followed by the expansion of
/// [predefinedAcl].
///
/// Returns a `StreamSink` where the object content can be written. When
/// The object content has been written the `StreamSink` completes with
/// an `ObjectInfo` instance with the information on the object created.
StreamSink<List<int>> write(String objectName,
{int? length,
ObjectMetadata? metadata,
Acl? acl,
PredefinedAcl? predefinedAcl,
String? contentType});
/// Create an new object in the bucket with specified content.
///
/// Writes [bytes] to the created object.
///
/// See [write] for more information on the additional arguments.
///
/// Returns a `Future` which completes with an `ObjectInfo` instance when
/// the object is written.
Future<ObjectInfo> writeBytes(String name, List<int> bytes,
{ObjectMetadata? metadata,
Acl? acl,
PredefinedAcl? predefinedAcl,
String? contentType});
/// Read object content as byte stream.
///
/// If [offset] is provided, [length] must also be provided.
///
/// If [length] is provided, it must be greater than `0`.
///
/// If there is a problem accessing the file, a [DetailedApiRequestError] is
/// thrown.
Stream<List<int>> read(String objectName, {int? offset, int? length});
/// Lookup object metadata.
///
// TODO: More documentation
Future<ObjectInfo> info(String name);
/// Delete an object.
///
// TODO: More documentation
Future delete(String name);
/// Update object metadata.
///
// TODO: More documentation
Future updateMetadata(String objectName, ObjectMetadata metadata);
/// List objects in the bucket.
///
/// Listing operates like a directory listing, despite the object
/// namespace being flat. Unless [delimiter] is specified, the character `/`
/// is being used to separate object names into directory components.
/// To list objects recursively, the [delimiter] can be set to empty string.
///
/// Retrieves a list of objects and directory components starting
/// with [prefix].
///
/// Returns a [Stream] of [BucketEntry]. Each element of the stream
/// represents either an object or a directory component.
Stream<BucketEntry> list({String? prefix, String? delimiter});
/// Start paging through objects in the bucket.
///
/// The maximum number of objects in each page is specified in [pageSize].
///
/// See [list] for more information on the other arguments.
///
/// Returns a `Future` which completes with a `Page` object holding the
/// first page. Use the `Page` object to move to the next page.
Future<Page<BucketEntry>> page(
{String? prefix, String? delimiter, int pageSize = 50});
}
| gcloud/lib/storage.dart/0 | {'file_path': 'gcloud/lib/storage.dart', 'repo_id': 'gcloud', 'token_count': 7396} |
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// ignore_for_file: only_throw_errors
import 'dart:typed_data';
import 'package:gcloud/datastore.dart' as datastore;
import 'package:gcloud/db.dart';
import 'package:test/test.dart';
void main() {
group('properties', () {
var datastoreKey = datastore.Key([datastore.KeyElement('MyKind', 42)],
partition: datastore.Partition('foonamespace'));
var dbKey = KeyMock(datastoreKey);
var modelDBMock = ModelDBMock(datastoreKey, dbKey);
test('bool_property', () {
var prop = const BoolProperty(required: true);
expect(prop.validate(modelDBMock, null), isFalse);
prop = const BoolProperty(required: false);
expect(prop.validate(modelDBMock, null), isTrue);
expect(prop.validate(modelDBMock, true), isTrue);
expect(prop.validate(modelDBMock, false), isTrue);
expect(prop.encodeValue(modelDBMock, null), equals(null));
expect(prop.encodeValue(modelDBMock, true), equals(true));
expect(prop.encodeValue(modelDBMock, false), equals(false));
expect(prop.decodePrimitiveValue(modelDBMock, null), equals(null));
expect(prop.decodePrimitiveValue(modelDBMock, true), equals(true));
expect(prop.decodePrimitiveValue(modelDBMock, false), equals(false));
});
test('int_property', () {
var prop = const IntProperty(required: true);
expect(prop.validate(modelDBMock, null), isFalse);
prop = const IntProperty(required: false);
expect(prop.validate(modelDBMock, null), isTrue);
expect(prop.validate(modelDBMock, 33), isTrue);
expect(prop.encodeValue(modelDBMock, null), equals(null));
expect(prop.encodeValue(modelDBMock, 42), equals(42));
expect(prop.decodePrimitiveValue(modelDBMock, null), equals(null));
expect(prop.decodePrimitiveValue(modelDBMock, 99), equals(99));
});
test('double_property', () {
var prop = const DoubleProperty(required: true);
expect(prop.validate(modelDBMock, null), isFalse);
prop = const DoubleProperty(required: false);
expect(prop.validate(modelDBMock, null), isTrue);
expect(prop.validate(modelDBMock, 33.0), isTrue);
expect(prop.encodeValue(modelDBMock, null), equals(null));
expect(prop.encodeValue(modelDBMock, 42.3), equals(42.3));
expect(prop.decodePrimitiveValue(modelDBMock, null), equals(null));
expect(prop.decodePrimitiveValue(modelDBMock, 99.1), equals(99.1));
});
test('string_property', () {
var prop = const StringProperty(required: true);
expect(prop.validate(modelDBMock, null), isFalse);
prop = const StringProperty(required: false);
expect(prop.validate(modelDBMock, null), isTrue);
expect(prop.validate(modelDBMock, 'foobar'), isTrue);
expect(prop.encodeValue(modelDBMock, null), equals(null));
expect(prop.encodeValue(modelDBMock, 'foo'), equals('foo'));
expect(prop.decodePrimitiveValue(modelDBMock, null), equals(null));
expect(prop.decodePrimitiveValue(modelDBMock, 'bar'), equals('bar'));
});
test('blob_property', () {
var prop = const BlobProperty(required: true);
expect(prop.validate(modelDBMock, null), isFalse);
prop = const BlobProperty(required: false);
expect(prop.validate(modelDBMock, null), isTrue);
expect(prop.validate(modelDBMock, [1, 2]), isTrue);
expect(prop.encodeValue(modelDBMock, null), equals(null));
expect(
(prop.encodeValue(modelDBMock, <int>[]) as datastore.BlobValue).bytes,
equals([]));
expect(
(prop.encodeValue(modelDBMock, [1, 2]) as datastore.BlobValue).bytes,
equals([1, 2]));
expect(
(prop.encodeValue(modelDBMock, Uint8List.fromList([1, 2]))
as datastore.BlobValue)
.bytes,
equals([1, 2]));
expect(prop.decodePrimitiveValue(modelDBMock, null), equals(null));
expect(prop.decodePrimitiveValue(modelDBMock, datastore.BlobValue([])),
equals([]));
expect(
prop.decodePrimitiveValue(modelDBMock, datastore.BlobValue([5, 6])),
equals([5, 6]));
expect(
prop.decodePrimitiveValue(
modelDBMock, datastore.BlobValue(Uint8List.fromList([5, 6]))),
equals([5, 6]));
});
test('datetime_property', () {
var utc99 = DateTime.fromMillisecondsSinceEpoch(99, isUtc: true);
var prop = const DateTimeProperty(required: true);
expect(prop.validate(modelDBMock, null), isFalse);
prop = const DateTimeProperty(required: false);
expect(prop.validate(modelDBMock, null), isTrue);
expect(prop.validate(modelDBMock, utc99), isTrue);
expect(prop.encodeValue(modelDBMock, null), equals(null));
expect(prop.encodeValue(modelDBMock, utc99), equals(utc99));
expect(prop.decodePrimitiveValue(modelDBMock, null), equals(null));
expect(prop.decodePrimitiveValue(modelDBMock, 99 * 1000), equals(utc99));
expect(
prop.decodePrimitiveValue(modelDBMock, 99 * 1000 + 1), equals(utc99));
expect(prop.decodePrimitiveValue(modelDBMock, utc99), equals(utc99));
});
test('list_property', () {
var prop = const ListProperty(BoolProperty());
expect(prop.validate(modelDBMock, null), isFalse);
expect(prop.validate(modelDBMock, []), isTrue);
expect(prop.validate(modelDBMock, [true]), isTrue);
expect(prop.validate(modelDBMock, [true, false]), isTrue);
expect(prop.validate(modelDBMock, [true, false, 1]), isFalse);
expect(prop.encodeValue(modelDBMock, []), equals(null));
expect(prop.encodeValue(modelDBMock, [true]), equals(true));
expect(
prop.encodeValue(modelDBMock, [true, false]), equals([true, false]));
expect(prop.encodeValue(modelDBMock, true, forComparison: true),
equals(true));
expect(prop.encodeValue(modelDBMock, false, forComparison: true),
equals(false));
expect(prop.encodeValue(modelDBMock, null, forComparison: true),
equals(null));
expect(prop.decodePrimitiveValue(modelDBMock, null), equals([]));
expect(prop.decodePrimitiveValue(modelDBMock, []), equals([]));
expect(prop.decodePrimitiveValue(modelDBMock, true), equals([true]));
expect(prop.decodePrimitiveValue(modelDBMock, [true, false]),
equals([true, false]));
});
test('composed_list_property', () {
var prop = const ListProperty(CustomProperty());
var c1 = Custom()..customValue = 'c1';
var c2 = Custom()..customValue = 'c2';
expect(prop.validate(modelDBMock, null), isFalse);
expect(prop.validate(modelDBMock, []), isTrue);
expect(prop.validate(modelDBMock, [c1]), isTrue);
expect(prop.validate(modelDBMock, [c1, c2]), isTrue);
expect(prop.validate(modelDBMock, [c1, c2, 1]), isFalse);
expect(prop.encodeValue(modelDBMock, []), equals(null));
expect(prop.encodeValue(modelDBMock, [c1]), equals(c1.customValue));
expect(prop.encodeValue(modelDBMock, [c1, c2]),
equals([c1.customValue, c2.customValue]));
expect(prop.decodePrimitiveValue(modelDBMock, null), equals([]));
expect(prop.decodePrimitiveValue(modelDBMock, []), equals([]));
expect(
prop.decodePrimitiveValue(modelDBMock, c1.customValue), equals([c1]));
expect(
prop.decodePrimitiveValue(
modelDBMock, [c1.customValue, c2.customValue]),
equals([c1, c2]));
});
test('modelkey_property', () {
var prop = const ModelKeyProperty(required: true);
expect(prop.validate(modelDBMock, null), isFalse);
prop = const ModelKeyProperty(required: false);
expect(prop.validate(modelDBMock, null), isTrue);
expect(prop.validate(modelDBMock, dbKey), isTrue);
expect(prop.validate(modelDBMock, datastoreKey), isFalse);
expect(prop.encodeValue(modelDBMock, null), equals(null));
expect(prop.encodeValue(modelDBMock, dbKey), equals(datastoreKey));
expect(prop.decodePrimitiveValue(modelDBMock, null), equals(null));
expect(
prop.decodePrimitiveValue(modelDBMock, datastoreKey), equals(dbKey));
});
});
}
class Custom {
String? customValue;
@override
int get hashCode => customValue.hashCode;
@override
bool operator ==(Object other) {
return other is Custom && other.customValue == customValue;
}
}
class CustomProperty extends StringProperty {
const CustomProperty(
{String? propertyName, bool required = false, bool indexed = true});
@override
bool validate(ModelDB db, Object? value) {
if (required && value == null) return false;
return value == null || value is Custom;
}
@override
Object? decodePrimitiveValue(ModelDB db, Object? value) {
if (value == null) return null;
return Custom()..customValue = value as String;
}
@override
Object? encodeValue(ModelDB db, Object? value, {bool forComparison = false}) {
if (value == null) return null;
return (value as Custom).customValue;
}
}
class KeyMock implements Key {
final datastore.Key _datastoreKey;
KeyMock(this._datastoreKey);
@override
Object id = 1;
@override
Type? type;
@override
Key get parent => this;
@override
bool get isEmpty => false;
@override
Partition get partition => throw UnimplementedError('not mocked');
datastore.Key get datastoreKey => _datastoreKey;
@override
Key<T> append<T>(Type modelType, {T? id}) =>
throw UnimplementedError('not mocked');
@override
Key<U> cast<U>() => Key<U>(parent, type, id as U);
@override
// ignore: hash_and_equals
int get hashCode => 1;
}
class ModelDBMock implements ModelDB {
final datastore.Key _datastoreKey;
final Key _dbKey;
ModelDBMock(this._datastoreKey, this._dbKey);
@override
Key fromDatastoreKey(datastore.Key datastoreKey) {
if (!identical(_datastoreKey, datastoreKey)) {
throw 'Broken test';
}
return _dbKey;
}
@override
datastore.Key toDatastoreKey(Key key) {
if (!identical(_dbKey, key)) {
throw 'Broken test';
}
return _datastoreKey;
}
@override
T? fromDatastoreEntity<T extends Model>(datastore.Entity? entity) => null;
@override
datastore.Entity toDatastoreEntity(Model model) =>
throw UnimplementedError('not mocked');
@override
String? fieldNameToPropertyName(String kind, String fieldName) => null;
@override
String kindName(Type type) => throw UnimplementedError('not mocked');
@override
Object? toDatastoreValue(String kind, String fieldName, Object? value,
{bool forComparison = false}) =>
null;
}
| gcloud/test/db/properties_test.dart/0 | {'file_path': 'gcloud/test/db/properties_test.dart', 'repo_id': 'gcloud', 'token_count': 4270} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.