code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:mini_sprite_editor/sprite/sprite.dart';
part 'tools_state.dart';
class ToolsCubit extends Cubit<ToolsState> {
ToolsCubit() : super(const ToolsState.initial());
void zoomIn() {
emit(state.copyWith(pixelSize: state.pixelSize + 10));
}
void zoomOut() {
emit(state.copyWith(pixelSize: state.pixelSize - 10));
}
void selectTool(SpriteTool tool) {
emit(state.copyWith(tool: tool));
}
void toogleGrid() {
emit(state.copyWith(gridActive: !state.gridActive));
}
void setColor(int color) {
emit(state.copyWith(currentColor: color));
}
}
| mini_sprite/packages/mini_sprite_editor/lib/sprite/cubit/tools_cubit.dart/0 | {'file_path': 'mini_sprite/packages/mini_sprite_editor/lib/sprite/cubit/tools_cubit.dart', 'repo_id': 'mini_sprite', 'token_count': 243} |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mini_sprite_editor/workspace/workspace.dart';
class TabWorkspace extends StatelessWidget {
const TabWorkspace({super.key});
@override
Widget build(BuildContext context) {
final workspaceCubit = context.watch<WorkspaceCubit>();
final workspaceState = workspaceCubit.state;
return Column(
children: [
Row(
children: [
for (final panel in WorkspacePanel.values)
_Tab(
panel: panel,
selected: panel == workspaceState.activePanel,
onPressed: () {
workspaceCubit.selectPanel(panel);
},
onRemoved: () {
workspaceCubit.closePanel(panel);
},
),
],
),
Expanded(
child: Stack(
children: [
for (final panel in WorkspacePanel.values)
Panel(
panel: panel,
isActive: workspaceState.activePanel == panel,
),
],
),
),
],
);
}
}
class _Tab extends StatelessWidget {
const _Tab({
required this.panel,
required this.selected,
required this.onPressed,
required this.onRemoved,
});
final WorkspacePanel panel;
final bool selected;
final VoidCallback onPressed;
final VoidCallback onRemoved;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: onPressed,
child: Card(
child: DecoratedBox(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: selected
? Theme.of(context).buttonTheme.colorScheme!.primary
: Colors.transparent,
),
),
),
child: Row(
children: [
const SizedBox(width: 16),
SizedBox(height: 32, child: Center(child: Text(panel.name))),
const SizedBox(width: 16),
//IconButton(
// onPressed: onRemoved,
// icon: const Icon(Icons.close),
//),
],
),
),
),
);
}
}
| mini_sprite/packages/mini_sprite_editor/lib/workspace/view/tab_workspace.dart/0 | {'file_path': 'mini_sprite/packages/mini_sprite_editor/lib/workspace/view/tab_workspace.dart', 'repo_id': 'mini_sprite', 'token_count': 1181} |
import 'package:flutter/material.dart';
import 'package:mini_treasure_quest/game/stages.dart';
import 'package:mini_treasure_quest/game/views/view.dart';
class StagesPage extends StatelessWidget {
const StagesPage({super.key});
static Route<void> route() {
return MaterialPageRoute(
builder: (_) => const StagesPage(),
);
}
@override
Widget build(BuildContext context) {
return const StagesView();
}
}
class StagesView extends StatelessWidget {
const StagesView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(32),
child: Wrap(
children: [
for (var i = 0; i < stages.length; i++)
ElevatedButton(
onPressed: () {
Navigator.of(context).push(GamePage.route(i));
},
autofocus: i == stages.length - 1,
child: SizedBox(
width: 100,
height: 100,
child: Center(
child: Text(
'${i + 1}',
style: Theme.of(context).textTheme.displayMedium,
),
),
),
),
],
),
),
);
}
}
| mini_sprite/packages/mini_treasure_quest/lib/stages/views/stages_view.dart/0 | {'file_path': 'mini_sprite/packages/mini_treasure_quest/lib/stages/views/stages_view.dart', 'repo_id': 'mini_sprite', 'token_count': 684} |
import 'package:mobx/mobx.dart';
import 'package:test/test.dart';
void main() {
group('ReactiveContext', () {
test('comes with default config', () {
final ctx = ReactiveContext();
expect(ctx.config, equals(ReactiveConfig.main));
});
test('global onReactionError is invoked for reaction errors', () {
var caught = false;
final dispose = mainContext.onReactionError((_, rxn) {
caught = true;
expect(rxn.errorValue, isNotNull);
});
final dispose1 = autorun((_) => throw Exception('autorun FAIL'));
expect(caught, isTrue);
dispose();
dispose1();
});
test('can change observables inside computed if there are no observers',
() {
final x = Observable(0);
final c = Computed(() => x.value++);
expect(() => c.value, returnsNormally);
});
test('cannot change observables inside computed if they have observers',
() {
final x = Observable(0);
final c = Computed<int>(() => x.value++);
expect(() {
final d = autorun((_) => x.value);
// Fetch the value which is in turn mutating the observable (x.value).
// This is not allowed because there is an observer: autorun.
c.value;
d();
}, throwsException);
});
test('throws Exception for reactions that do not converge', () {
var firstTime = true;
final a = Observable(0);
final d = autorun((_) {
a.value;
if (firstTime) {
firstTime = false;
return;
}
// cyclic-dependency!!!
// this autorun() will keep on getting triggered as a.value keeps changing
// every time it's invoked
a.value = a.value + 1;
}, name: 'Cyclic Reaction');
expect(() => a.value = 1, throwsException);
d();
});
});
group('ReactiveConfig', () {
test('clone works', () {
final config = ReactiveConfig.main;
final clone = config.clone(maxIterations: 10);
expect(clone.maxIterations, equals(10));
expect(clone.maxIterations != config.maxIterations, isTrue);
expect(clone.disableErrorBoundaries == config.disableErrorBoundaries,
isTrue);
expect(clone.enforceActions == config.enforceActions, isTrue);
});
});
}
| mobx.dart/mobx/test/context_test.dart/0 | {'file_path': 'mobx.dart/mobx/test/context_test.dart', 'repo_id': 'mobx.dart', 'token_count': 924} |
library mobx_codegen;
export 'src/mobx_codegen_base.dart';
| mobx.dart/mobx_codegen/lib/mobx_codegen.dart/0 | {'file_path': 'mobx.dart/mobx_codegen/lib/mobx_codegen.dart', 'repo_id': 'mobx.dart', 'token_count': 25} |
import 'package:flutter/material.dart';
import 'package:mobx_examples/clock/clock_widgets.dart';
import 'package:mobx_examples/counter/counter_widgets.dart';
import 'package:mobx_examples/form/form_widgets.dart';
import 'package:mobx_examples/github/github_widgets.dart';
import 'package:mobx_examples/hackernews/news_widgets.dart';
import 'package:mobx_examples/multi_counter/multi_counter_widgets.dart';
import 'package:mobx_examples/todos/todo_widgets.dart';
class Example {
Example(
{@required this.title,
@required this.description,
@required this.path,
@required this.widgetBuilder});
final WidgetBuilder widgetBuilder;
final String path;
final String title;
final String description;
}
final List<Example> examples = [
Example(
title: 'Counter',
description: 'The classic Counter that can be incremented.',
path: '/counter',
widgetBuilder: (_) => const CounterExample(),
),
Example(
title: 'Multi Counter',
description: 'Multiple Counters with a shared Store using Provider.',
path: '/multi-counter',
widgetBuilder: (_) => const MultiCounterExample(),
),
Example(
title: 'Todos',
description: 'Managing a list of Todos, the TodoMVC way.',
path: '/todos',
widgetBuilder: (_) => const TodoExample(),
),
Example(
title: 'Github Repos',
description: 'Get a list of repos for a user',
path: '/github',
widgetBuilder: (_) => const GithubExample(),
),
Example(
title: 'Clock',
description: 'A simple ticking Clock, made with an Atom',
path: '/clock',
widgetBuilder: (_) => const ClockExample(),
),
Example(
title: 'Login Form',
description: 'A login form with validations',
path: '/form',
widgetBuilder: (_) => const FormExample(),
),
Example(
title: 'Hacker News',
description: 'Simple reader for Hacker News',
path: '/hn',
widgetBuilder: (_) => const HackerNewsExample(),
),
];
| mobx.dart/mobx_examples/lib/examples.dart/0 | {'file_path': 'mobx.dart/mobx_examples/lib/examples.dart', 'repo_id': 'mobx.dart', 'token_count': 678} |
import 'package:mobx/mobx.dart';
import 'package:mobx_examples/todos/todo.dart';
part 'todo_list.g.dart';
enum VisibilityFilter { all, pending, completed }
class TodoList = _TodoList with _$TodoList;
abstract class _TodoList with Store {
@observable
ObservableList<Todo> todos = ObservableList<Todo>();
@observable
VisibilityFilter filter = VisibilityFilter.all;
@observable
String currentDescription = '';
@computed
ObservableList<Todo> get pendingTodos =>
ObservableList.of(todos.where((todo) => todo.done != true));
@computed
ObservableList<Todo> get completedTodos =>
ObservableList.of(todos.where((todo) => todo.done == true));
@computed
bool get hasCompletedTodos => completedTodos.isNotEmpty;
@computed
bool get hasPendingTodos => pendingTodos.isNotEmpty;
@computed
String get itemsDescription {
if (todos.isEmpty) {
return "There are no Todos here. Why don't you add one?.";
}
final suffix = pendingTodos.length == 1 ? 'todo' : 'todos';
return '${pendingTodos.length} pending $suffix, ${completedTodos.length} completed';
}
@computed
ObservableList<Todo> get visibleTodos {
switch (filter) {
case VisibilityFilter.pending:
return pendingTodos;
case VisibilityFilter.completed:
return completedTodos;
default:
return todos;
}
}
@computed
bool get canRemoveAllCompleted =>
hasCompletedTodos && filter != VisibilityFilter.pending;
@computed
bool get canMarkAllCompleted =>
hasPendingTodos && filter != VisibilityFilter.completed;
@action
void addTodo(String description) {
final todo = Todo(description);
todos.add(todo);
currentDescription = '';
}
@action
void removeTodo(Todo todo) {
todos.removeWhere((x) => x == todo);
}
@action
void changeDescription(String description) =>
currentDescription = description;
@action
void changeFilter(VisibilityFilter filter) => this.filter = filter;
@action
void removeCompleted() {
todos.removeWhere((todo) => todo.done);
}
@action
void markAllAsCompleted() {
for (final todo in todos) {
todo.done = true;
}
}
}
| mobx.dart/mobx_examples/lib/todos/todo_list.dart/0 | {'file_path': 'mobx.dart/mobx_examples/lib/todos/todo_list.dart', 'repo_id': 'mobx.dart', 'token_count': 818} |
include: package:very_good_analysis/analysis_options.5.1.0.yaml
| mockingjay/analysis_options.yaml/0 | {'file_path': 'mockingjay/analysis_options.yaml', 'repo_id': 'mockingjay', 'token_count': 23} |
import 'package:example/ui/ui.dart';
import 'package:flutter/material.dart';
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Mockingjay Example',
color: Colors.black,
theme: ThemeData.light().copyWith(primaryColor: Colors.black),
darkTheme: ThemeData.dark().copyWith(primaryColor: Colors.black),
home: const HomeScreen(),
);
}
}
| mockingjay/example/lib/app.dart/0 | {'file_path': 'mockingjay/example/lib/app.dart', 'repo_id': 'mockingjay', 'token_count': 164} |
# TODO(https://github.com/dart-lang/test/issues/772): Headless chrome timeout.
override_platforms:
chrome:
settings:
headless: false
| mockito/dart_test.yaml/0 | {'file_path': 'mockito/dart_test.yaml', 'repo_id': 'mockito', 'token_count': 54} |
// Copyright 2018 Dart Mockito authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ignore_for_file: strong_mode_implicit_dynamic_function
@deprecated
library mockito.test.deprecated_apis.capture_test;
import 'package:mockito/mockito.dart';
import 'package:test/test.dart';
import '../utils.dart';
class _RealClass {
_RealClass innerObj;
String methodWithNormalArgs(int x) => 'Real';
String methodWithListArgs(List<int> x) => 'Real';
String methodWithPositionalArgs(int x, [int y]) => 'Real';
set setter(String arg) {
throw StateError('I must be mocked');
}
}
class MockedClass extends Mock implements _RealClass {}
void main() {
MockedClass mock;
var isNsmForwarding = assessNsmForwarding();
setUp(() {
mock = MockedClass();
});
tearDown(() {
// In some of the tests that expect an Error to be thrown, Mockito's
// global state can become invalid. Reset it.
resetMockitoState();
});
group('capture', () {
test('captureAny should match anything', () {
mock.methodWithNormalArgs(42);
expect(
verify(mock.methodWithNormalArgs(typed(captureAny))).captured.single,
equals(42));
});
test('captureThat should match some things', () {
mock.methodWithNormalArgs(42);
mock.methodWithNormalArgs(44);
mock.methodWithNormalArgs(43);
mock.methodWithNormalArgs(45);
expect(
verify(mock.methodWithNormalArgs(typed(captureThat(lessThan(44)))))
.captured,
equals([42, 43]));
});
test('should capture list arguments', () {
mock.methodWithListArgs([42]);
expect(verify(mock.methodWithListArgs(typed(captureAny))).captured.single,
equals([42]));
});
test('should capture multiple arguments', () {
mock.methodWithPositionalArgs(1, 2);
expect(
verify(mock.methodWithPositionalArgs(
typed(captureAny), typed(captureAny)))
.captured,
equals([1, 2]));
});
test('should capture with matching arguments', () {
mock.methodWithPositionalArgs(1);
mock.methodWithPositionalArgs(2, 3);
var expectedCaptures = isNsmForwarding ? [1, null, 2, 3] : [2, 3];
expect(
verify(mock.methodWithPositionalArgs(
typed(captureAny), typed(captureAny)))
.captured,
equals(expectedCaptures));
});
test('should capture multiple invocations', () {
mock.methodWithNormalArgs(1);
mock.methodWithNormalArgs(2);
expect(verify(mock.methodWithNormalArgs(typed(captureAny))).captured,
equals([1, 2]));
});
});
}
| mockito/test/deprecated_apis/capture_test.dart/0 | {'file_path': 'mockito/test/deprecated_apis/capture_test.dart', 'repo_id': 'mockito', 'token_count': 1186} |
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:io';
import 'package:args/command_runner.dart';
import 'package:mono_repo/mono_repo.dart';
import 'package:io/ansi.dart' as ansi;
import 'package:io/io.dart';
void main(List<String> arguments) async {
try {
await run(arguments);
} on UserException catch (e) {
print(ansi.red.wrap(e.message));
if (e.details != null) {
print(e.details);
}
exitCode = ExitCode.config.code;
} on UsageException catch (e) {
print(ansi.red.wrap(e.message));
if (e.usage != null) {
print('');
print(e.usage);
}
exitCode = ExitCode.usage.code;
}
}
| mono_repo/mono_repo/bin/mono_repo.dart/0 | {'file_path': 'mono_repo/mono_repo/bin/mono_repo.dart', 'repo_id': 'mono_repo', 'token_count': 314} |
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:args/args.dart';
import 'package:args/command_runner.dart';
import 'commands/check.dart';
import 'commands/mono_repo_command.dart';
import 'commands/presubmit.dart';
import 'commands/pub.dart';
import 'commands/travis.dart';
import 'version.dart';
final List<Command<Null>> commands = List<Command<Null>>.unmodifiable(
[CheckCommand(), PresubmitCommand(), PubCommand(), TravisCommand()]);
class MonoRepoRunner extends CommandRunner<Null> {
MonoRepoRunner()
: super(
'mono_repo', 'Manage multiple packages in one source repository.') {
commands.forEach(addCommand);
argParser.addFlag('version',
negatable: false, help: 'Prints the version of mono_repo.');
argParser.addFlag(recursiveFlag,
help:
'Whether to recursively walk sub-directorys looking for packages.',
defaultsTo: false);
}
@override
Future<Null> runCommand(ArgResults topLevelResults) async {
if (topLevelResults.wasParsed('version')) {
print(packageVersion);
return null;
}
return super.runCommand(topLevelResults);
}
}
| mono_repo/mono_repo/lib/src/runner.dart/0 | {'file_path': 'mono_repo/mono_repo/lib/src/runner.dart', 'repo_id': 'mono_repo', 'token_count': 472} |
include: package:very_good_analysis/analysis_options.yaml
linter:
rules:
prefer_single_quotes: true
always_use_package_imports: true
flutter_style_todos: false
avoid_redundant_argument_values: false
sort_pub_dependencies: false
| movies_app/analysis_options.yaml/0 | {'file_path': 'movies_app/analysis_options.yaml', 'repo_id': 'movies_app', 'token_count': 93} |
import 'dart:io';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:gallery_saver/gallery_saver.dart';
/// Provider that maps an [MediaService] interface to implementation
final mediaServiceProvider = Provider<MediaService>(
(_) => GallerySaverMediaService(),
);
/// Interface for a media service
abstract class MediaService {
/// Saves a network image to device gallery
Future<void> saveNetworkImageToGallery(String imageUrl);
/// Saves a file image to device gallery
Future<void> saveFileImageToGallery(File file);
}
/// [MediaService] interface implementation using the [GallerySaver] package
///
/// See: https://pub.dev/packages/gallery_saver
class GallerySaverMediaService implements MediaService {
// coverage:ignore-start
@override
Future<void> saveNetworkImageToGallery(String imageUrl) async {
await GallerySaver.saveImage(imageUrl);
}
@override
Future<void> saveFileImageToGallery(File file) {
// TODO: implement saveFileImageToGallery
throw UnimplementedError();
} // coverage:ignore-end
}
| movies_app/lib/core/services/media/media_service.dart/0 | {'file_path': 'movies_app/lib/core/services/media/media_service.dart', 'repo_id': 'movies_app', 'token_count': 307} |
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:movies_app/features/people/models/person.dart';
/// The provider that provides the Person data for each list item
///
/// Initially it throws an UnimplementedError because we won't use it
/// before overriding it
///
/// For infinite scroll tutorial:
/// https://github.com/Roaa94/movies_app/tree/main#infinite-scroll-functionality
final currentPopularPersonProvider = Provider<AsyncValue<Person>>((ref) {
throw UnimplementedError();
});
| movies_app/lib/features/people/providers/current_popular_person_provider.dart/0 | {'file_path': 'movies_app/lib/features/people/providers/current_popular_person_provider.dart', 'repo_id': 'movies_app', 'token_count': 146} |
import 'package:flutter/material.dart';
import 'package:movies_app/features/people/models/person_image.dart';
import 'package:movies_app/features/people/views/pages/person_images_slider_page.dart';
import 'package:movies_app/features/people/views/widgets/person_images_grid_item.dart';
/// Widget of the images grid section of the person details
class PersonImagesGrid extends StatelessWidget {
/// Creates a new instance of [PersonImagesGrid]
const PersonImagesGrid(
this.images, {
super.key,
});
/// List of person images to be displayed in the grid
final List<PersonImage> images;
@override
Widget build(BuildContext context) {
return SizedBox(
height: (images.length / 3).ceil() *
((MediaQuery.of(context).size.width - 10 * 4) / 3),
child: GridView.builder(
physics: const NeverScrollableScrollPhysics(),
itemCount: images.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
padding: const EdgeInsetsDirectional.only(start: 40, end: 17),
itemBuilder: (context, index) => ClipRRect(
borderRadius: BorderRadius.circular(10),
child: PersonImagesGridItem(
images[index],
onTap: () {
Navigator.of(context).push<PersonImagesSliderPage>(
MaterialPageRoute<PersonImagesSliderPage>(
builder: (context) => PersonImagesSliderPage(
images: images,
initialImageIndex: index,
),
),
);
},
),
),
),
);
}
}
| movies_app/lib/features/people/views/widgets/person_images_grid.dart/0 | {'file_path': 'movies_app/lib/features/people/views/widgets/person_images_grid.dart', 'repo_id': 'movies_app', 'token_count': 748} |
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:movies_app/core/services/storage/hive_storage_service.dart';
import 'package:movies_app/core/services/storage/storage_service.dart';
import 'package:movies_app/core/services/storage/storage_service_provider.dart';
import 'package:movies_app/movies_app.dart';
void main() {
runZonedGuarded<Future<void>>(
() async {
// Hive-specific initialization
await Hive.initFlutter();
final StorageService initializedStorageService = HiveStorageService();
await initializedStorageService.init();
runApp(
ProviderScope(
overrides: [
storageServiceProvider.overrideWithValue(initializedStorageService),
],
child: const MoviesApp(),
),
);
},
// ignore: only_throw_errors
(e, _) => throw e,
);
}
| movies_app/lib/main.dart/0 | {'file_path': 'movies_app/lib/main.dart', 'repo_id': 'movies_app', 'token_count': 373} |
import 'package:clock/clock.dart';
import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http_mock_adapter/http_mock_adapter.dart';
import 'package:mocktail/mocktail.dart';
import 'package:movies_app/core/models/cache_response.dart';
import 'package:movies_app/core/services/http/dio-interceptors/cache_interceptor.dart';
import 'package:movies_app/core/services/http/dio_http_service.dart';
import 'package:movies_app/core/services/storage/storage_service.dart';
import '../../../../test-utils/mocks.dart';
void main() {
late DioHttpService dioHttpService;
final StorageService storageService = MockStorageService();
late DioAdapter dioAdapter;
final cacheInterceptor = CacheInterceptor(storageService);
const baseUrl = 'https://api.test/';
final headers = <String, dynamic>{
'accept': 'application/json',
'content-type': 'application/json'
};
final responseHeaders = <String, List<String>>{
'content-type': ['application/json; charset=utf-8']
};
setUp(() {
dioAdapter = DioAdapter(
dio: Dio(
BaseOptions(baseUrl: baseUrl, headers: headers),
),
);
dioHttpService = DioHttpService(
storageService,
dioOverride: dioAdapter.dio,
enableCaching: false,
);
dioAdapter.dio.interceptors.add(cacheInterceptor);
});
test('Creates appropriate storage key from request information', () async {
const path = 'storage-key-test';
final storageKey = cacheInterceptor.createStorageKey(
'get',
baseUrl,
path,
<String, dynamic>{
'param1': 'value1',
'param2': 'value2',
},
);
expect(
storageKey,
equals('GET:$baseUrl$path/?param1=value1¶m2=value2&'),
);
});
test(
'creates correct cache response from request information',
() {
final responseData = <String, dynamic>{'data': 'Success!'};
final cachedResponse = CachedResponse(
data: responseData,
headers: Headers.fromMap(responseHeaders),
age: DateTime(2022, 1, 1, 12, 0),
statusCode: 200,
);
final rawCachedResponse = <String, dynamic>{
'data': {'data': 'Success!'},
'age': '2022-01-01 12:00:00.000',
'statusCode': 200,
'headers': {
'content-type': ['application/json; charset=utf-8'],
},
};
expect(cachedResponse.toJson(), equals(rawCachedResponse));
},
);
test('cache response is invalid when it passes max age', () {
final responseData = <String, dynamic>{'data': 'Success!'};
final cachedResponse = CachedResponse(
data: responseData,
headers: Headers.fromMap(responseHeaders),
age: DateTime(2022, 1, 1, 12, 0),
statusCode: 200,
);
withClock(Clock.fixed(DateTime(2022, 1, 1, 14, 0)), () {
expect(cachedResponse.isValid, isFalse);
});
});
test('cache response is valid when it is not older than max age', () {
final responseData = <String, dynamic>{'data': 'Success!'};
final cachedResponse = CachedResponse(
data: responseData,
headers: Headers.fromMap(responseHeaders),
age: DateTime(2022, 1, 1, 12, 0),
statusCode: 200,
);
withClock(Clock.fixed(DateTime(2022, 1, 1, 12, 30)), () {
expect(cachedResponse.isValid, isTrue);
});
});
test(
'Retrieves data from network when it does not exist, '
'then caches it in storage',
() async {
final fetchTime = DateTime(2022, 1, 1, 12, 0);
const path = 'retrieve-data-from-network-test';
final responseData = <String, dynamic>{'data': 'Success!'};
dioAdapter.onGet(
path,
(server) => server.reply(200, responseData),
);
final storageKey = cacheInterceptor.createStorageKey(
'get',
baseUrl,
path,
);
when(() => storageService.has(storageKey)).thenReturn(false);
final cachedResponse = CachedResponse(
data: responseData,
headers: Headers.fromMap(responseHeaders),
age: fetchTime,
statusCode: 200,
);
when(() => storageService.has(storageKey)).thenReturn(false);
when(() => storageService.set(storageKey, cachedResponse.toJson()))
.thenAnswer((_) async {});
await withClock(Clock.fixed(fetchTime), () async {
final response = await dioHttpService.get(path);
expect(response, {'data': 'Success!'});
});
},
);
test('Retrieves data from cache when it exists and the cache is valid',
() async {
final fetchTime = DateTime(2022, 1, 1, 12, 0);
const path = 'retrieve-data-from-cache-test';
final responseData = <String, dynamic>{'data': 'Success!'};
dioAdapter.onGet(
path,
(server) => server.reply(200, responseData),
);
final storageKey = cacheInterceptor.createStorageKey(
'get',
baseUrl,
path,
);
when(() => storageService.has(storageKey)).thenReturn(true);
final cachedResponse = CachedResponse(
data: responseData,
headers: Headers.fromMap(responseHeaders),
age: fetchTime.subtract(const Duration(minutes: 30)),
statusCode: 200,
);
await withClock(Clock.fixed(fetchTime), () async {
expect(cachedResponse.isValid, isTrue);
when<dynamic>(() => storageService.get(storageKey))
.thenReturn(cachedResponse.toJson());
final response = await dioHttpService.get(path);
expect(response, cachedResponse.data);
});
});
test('Retrieves data from network when cache exists but is too old',
() async {
final fetchTime = DateTime(2022, 1, 1, 12, 0);
const path = 'retrieve-data-from-old-cache-test';
final responseData = <String, dynamic>{'data': 'Success!'};
dioAdapter.onGet(
path,
(server) => server.reply(200, responseData),
);
final storageKey = cacheInterceptor.createStorageKey('get', baseUrl, path);
when(() => storageService.has(storageKey)).thenReturn(true);
final cachedResponse = CachedResponse(
data: responseData,
headers: Headers.fromMap(responseHeaders),
age: fetchTime.subtract(const Duration(hours: 2)),
statusCode: 200,
);
await withClock(Clock.fixed(fetchTime), () async {
expect(cachedResponse.isValid, isFalse);
when<dynamic>(() => storageService.get(storageKey))
.thenReturn(cachedResponse.toJson());
final newCachedResponse = CachedResponse(
data: responseData,
headers: Headers.fromMap(responseHeaders),
age: fetchTime,
statusCode: 200,
);
when(() => storageService.set(storageKey, newCachedResponse.toJson()))
.thenAnswer((_) async {});
final response = await dioHttpService.get(path);
expect(response, responseData);
});
});
test('Retrieves data from network when refresh is forced', () async {
final fetchTime = DateTime(2022, 1, 1, 12, 0);
const path = 'force-refresh-test';
final responseData = <String, dynamic>{'data': 'Success!'};
dioAdapter.onGet(
path,
(server) => server.reply(200, responseData),
);
final storageKey = cacheInterceptor.createStorageKey('get', baseUrl, path);
final refreshedCachedResponse = CachedResponse(
data: responseData,
headers: Headers.fromMap(responseHeaders),
age: fetchTime,
statusCode: 200,
);
when(() => storageService.set(storageKey, refreshedCachedResponse.toJson()))
.thenAnswer((_) async {});
await withClock(Clock.fixed(fetchTime), () async {
final response = await dioHttpService.get(
path,
forceRefresh: true,
);
expect(response, responseData);
});
});
test(
'Retrieves data from cache when an error occurs and the cache exists',
() async {
final fetchTime = DateTime(2022, 1, 1, 12, 0);
const path = '404-get-request-test';
dioAdapter.onGet(
path,
(server) => server.reply(404, {'error': 'no data returned!'}),
);
final storageKey =
cacheInterceptor.createStorageKey('get', baseUrl, path);
when(() => storageService.has(storageKey)).thenReturn(true);
final cachedResponse = CachedResponse(
data: {'data': 'Success!'},
headers: Headers.fromMap(responseHeaders),
age: fetchTime,
statusCode: 200,
);
when<dynamic>(() => storageService.get(storageKey))
.thenReturn(cachedResponse.toJson());
await withClock(Clock.fixed(fetchTime), () async {
final response = await dioHttpService.get(
path,
forceRefresh: true,
);
expect(response, cachedResponse.data);
});
},
);
test(
'Throws error when http error occurs and no cache exists',
() async {
const path = '404-get-request-test';
dioAdapter.onGet(
path,
(server) => server.reply(404, {'error': 'no data returned!'}),
);
final storageKey =
cacheInterceptor.createStorageKey('get', baseUrl, path);
when(() => storageService.has(storageKey)).thenReturn(false);
expect(() => dioHttpService.get(path), throwsA(isA<DioError>()));
// expect(() async => await dioHttpService.get('404-get-request-test'),
// throwsA(isA<HttpException>()));
//
// try {
// await dioHttpService.get('404-get-request-test');
// } on HttpException catch (e) {
// expect(e.title, 'Http Error!');
// expect(e.statusCode, 404);
// }
},
);
}
| movies_app/test/core/services/http/dio-intercepters/caching_interceptor_test.dart/0 | {'file_path': 'movies_app/test/core/services/http/dio-intercepters/caching_interceptor_test.dart', 'repo_id': 'movies_app', 'token_count': 3819} |
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:movies_app/core/models/paginated_response.dart';
import 'package:movies_app/features/people/models/person.dart';
import 'package:movies_app/features/people/providers/paginated_popular_people_provider.dart';
import 'package:movies_app/features/people/providers/popular_people_count_provider.dart';
import '../../../test-utils/dummy-data/dummy_people.dart';
void main() {
test('returns correct results count', () async {
final providerContainer = ProviderContainer(
overrides: [
paginatedPopularPeopleProvider(0).overrideWithProvider(
FutureProvider<PaginatedResponse<Person>>(
(ref) async =>
Future.value(DummyPeople.paginatedPopularPeopleResponse),
),
),
],
);
addTearDown(providerContainer.dispose);
providerContainer.read(popularPeopleCountProvider);
await Future<void>.delayed(Duration.zero);
final count = providerContainer.read(popularPeopleCountProvider).value;
expect(
count,
equals(DummyPeople.paginatedPopularPeopleResponse.totalResults),
);
});
}
| movies_app/test/features/people/providers/popular_people_count_provider_test.dart/0 | {'file_path': 'movies_app/test/features/people/providers/popular_people_count_provider_test.dart', 'repo_id': 'movies_app', 'token_count': 442} |
import 'package:flutter_test/flutter_test.dart';
import 'package:movies_app/features/tmdb-configs/enums/image_size.dart';
import 'package:movies_app/features/tmdb-configs/models/tmdb_image_configs.dart';
import '../../../test-utils/dummy-data/dummy_configs.dart';
void main() {
test('returns TMDBConfigs model from valid json', () {
final rawValidConfigs = <String, dynamic>{
'base_url': 'http://image.tmdb.org/t/p/',
'secure_base_url': 'https://image.tmdb.org/t/p/',
'backdrop_sizes': ['w300', 'w780', 'w1280', 'original'],
'logo_sizes': ['w45', 'w92', 'w154', 'w185', 'w300', 'w500', 'original'],
'poster_sizes': [
'w92',
'w154',
'w185',
'w342',
'w500',
'w780',
'original'
],
'profile_sizes': ['w45', 'w185', 'h632', 'original'],
'still_sizes': ['w92', 'w185', 'w300', 'original']
};
expect(
TMDBImageConfigs.fromJson(rawValidConfigs),
equals(DummyConfigs.imageConfigs),
);
});
test(
'returns TMDBConfigs model with original '
'image sizes from empty configs image sizes',
() {
final rawInvalidConfigs = <String, dynamic>{
'base_url': 'http://image.tmdb.org/t/p/',
'secure_base_url': 'https://image.tmdb.org/t/p/',
'backdrop_sizes': <String>[],
'logo_sizes': <String>[],
'poster_sizes': ['invalidValue'],
'profile_sizes': <String>[],
'still_sizes': <String>[]
};
const validConfigs = TMDBImageConfigs(
baseUrl: 'http://image.tmdb.org/t/p/',
secureBaseUrl: 'https://image.tmdb.org/t/p/',
backdropSizes: <ImageSize>[],
logoSizes: [],
posterSizes: [ImageSize.original],
profileSizes: [],
stillSizes: [],
);
expect(
TMDBImageConfigs.fromJson(rawInvalidConfigs),
equals(validConfigs),
);
},
);
test(
'returns TMDBConfigs model with empty image '
'sizes from null configs image sizes',
() {
final rawInvalidConfigs = <String, dynamic>{
'base_url': 'http://image.tmdb.org/t/p/',
'secure_base_url': 'https://image.tmdb.org/t/p/',
'backdrop_sizes': null,
'logo_sizes': null,
'poster_sizes': null,
'profile_sizes': null,
'still_sizes': null
};
const validConfigs = TMDBImageConfigs(
baseUrl: 'http://image.tmdb.org/t/p/',
secureBaseUrl: 'https://image.tmdb.org/t/p/',
backdropSizes: [],
logoSizes: [],
posterSizes: [],
profileSizes: [],
stillSizes: [],
);
expect(
TMDBImageConfigs.fromJson(rawInvalidConfigs),
equals(validConfigs),
);
},
);
test('can build profile image Url from size and path', () {
final generatedImageUrl = DummyConfigs.imageConfigs.buildProfileImage(
ImageSize.h632,
'/image-path.png',
);
expect(
generatedImageUrl,
equals('https://image.tmdb.org/t/p/h632/image-path.png'),
);
});
test('can build backdrop image Url from size and path', () {
final generatedImageUrl = DummyConfigs.imageConfigs.buildBackdropImage(
ImageSize.w1280,
'/image-path.png',
);
expect(
generatedImageUrl,
equals('https://image.tmdb.org/t/p/w1280/image-path.png'),
);
});
test('can build poster image Url from size and path', () {
final generatedImageUrl = DummyConfigs.imageConfigs.buildPosterImage(
ImageSize.w780,
'/image-path.png',
);
expect(
generatedImageUrl,
equals('https://image.tmdb.org/t/p/w780/image-path.png'),
);
});
test('can build still image Url from size and path', () {
final generatedImageUrl = DummyConfigs.imageConfigs.buildStillImage(
ImageSize.w300,
'/image-path.png',
);
expect(
generatedImageUrl,
equals('https://image.tmdb.org/t/p/w300/image-path.png'),
);
});
test('can build logo image Url from size and path', () {
final generatedImageUrl = DummyConfigs.imageConfigs.buildLogoImage(
ImageSize.w45,
'/image-path.png',
);
expect(
generatedImageUrl,
equals('https://image.tmdb.org/t/p/w45/image-path.png'),
);
final generatedImageUrlInvalidSize =
DummyConfigs.imageConfigs.buildLogoImage(
ImageSize.h632,
'/image-path.png',
);
expect(
generatedImageUrlInvalidSize,
equals('https://image.tmdb.org/t/p/original/image-path.png'),
);
});
}
| movies_app/test/features/tmdb-configs/models/tmdb_image_configs_test.dart/0 | {'file_path': 'movies_app/test/features/tmdb-configs/models/tmdb_image_configs_test.dart', 'repo_id': 'movies_app', 'token_count': 2096} |
import 'package:mustache_template/mustache.dart' as m;
import 'node.dart';
import 'parser.dart' as parser;
import 'renderer.dart';
import 'template_exception.dart';
/// Passed as an argument to a mustache lambda function.
class LambdaContext implements m.LambdaContext {
final Node _node;
final Renderer _renderer;
bool _closed = false;
LambdaContext(this._node, this._renderer);
void close() {
_closed = true;
}
void _checkClosed() {
if (_closed) throw _error('LambdaContext accessed outside of callback.');
}
TemplateException _error(String msg) {
return TemplateException(
msg, _renderer.templateName, _renderer.source, _node.start);
}
@override
String renderString({Object? value}) {
_checkClosed();
if (_node is! SectionNode) {
_error(
'LambdaContext.renderString() can only be called on section tags.');
}
var sink = StringBuffer();
_renderSubtree(sink, value);
return sink.toString();
}
void _renderSubtree(StringSink sink, Object? value) {
var renderer = Renderer.subtree(_renderer, sink);
var section = _node as SectionNode;
if (value != null) renderer.push(value);
renderer.render(section.children);
}
@override
void render({Object? value}) {
_checkClosed();
if (_node is! SectionNode) {
_error('LambdaContext.render() can only be called on section tags.');
}
_renderSubtree(_renderer.sink, value);
}
@override
void write(Object object) {
_checkClosed();
_renderer.write(object);
}
@override
String get source {
_checkClosed();
if (_node is! SectionNode) return '';
var node = _node as SectionNode;
var nodes = node.children;
if (nodes.isEmpty) return '';
if (nodes.length == 1 && nodes.first is TextNode) {
return (nodes.single as TextNode).text;
}
return _renderer.source.substring(node.contentStart, node.contentEnd);
}
@override
String renderSource(String source, {Object? value}) {
_checkClosed();
var sink = StringBuffer();
// Lambdas used for sections should parse with the current delimiters.
var delimiters = '{{ }}';
if (_node is SectionNode) {
var node = _node as SectionNode;
delimiters = node.delimiters;
}
var nodes = parser.parse(
source, _renderer.lenient, _renderer.templateName, delimiters);
var renderer =
Renderer.lambda(_renderer, source, _renderer.indent, sink, delimiters);
if (value != null) renderer.push(value);
renderer.render(nodes);
return sink.toString();
}
@override
Object? lookup(String variableName) {
_checkClosed();
return _renderer.resolveValue(variableName);
}
}
| mustache/lib/src/lambda_context.dart/0 | {'file_path': 'mustache/lib/src/lambda_context.dart', 'repo_id': 'mustache', 'token_count': 983} |
import 'package:hacker_news_vanilla/src/models/feed_item.dart';
class Feed {
final List<FeedItem> items;
final int currentPage;
final int nextPage;
Feed({this.items, this.currentPage, this.nextPage});
bool get hasNextPage => nextPage != null;
factory Feed.from({
List<Map<String, dynamic>> items,
int currentPage,
int nextPage,
}) {
return Feed(
items:
items != null ? items.map((i) => FeedItem.fromJson(i)).toList() : [],
currentPage: currentPage,
nextPage: nextPage,
);
}
@override
String toString() {
return 'Feed{items: $items, currentPage: $currentPage, nextPage: $nextPage}';
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Feed &&
runtimeType == other.runtimeType &&
items == other.items &&
currentPage == other.currentPage &&
nextPage == other.nextPage;
@override
int get hashCode => items.hashCode ^ currentPage.hashCode ^ nextPage.hashCode;
}
| new_flutter_template/evaluations/hacker_news_vanilla/lib/src/models/feed.dart/0 | {'file_path': 'new_flutter_template/evaluations/hacker_news_vanilla/lib/src/models/feed.dart', 'repo_id': 'new_flutter_template', 'token_count': 390} |
import 'package:flutter/material.dart';
import 'package:journal_mvc/src/app.dart';
import 'package:journal_mvc/src/journal/controllers/journal_controller.dart';
import 'package:journal_mvc/src/journal/repositories/journal_repository.dart';
import 'package:journal_mvc/src/user_settings/controllers/user_settings_controller.dart';
import 'package:journal_mvc/src/user_settings/repositories/user_settings_repository.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() async {
// Set up the Repositories, which are responsible for storing and retrieving
// data.
final preferences = await SharedPreferences.getInstance();
final journalRepository = JournalRepository(preferences);
final userSettingsRepository = UserSettingsRepository(preferences);
// Finally, use the Services to Setup our Controllers! Controllers glue
// Repositories to Widgets.
final journalController = JournalController(journalRepository);
final userSettingsController = UserSettingsController(userSettingsRepository);
// Sometimes, you may need to load some data before showing the app. In this
// case, load the correct theme and language.
await userSettingsController.loadUserSettings();
runApp(
JournalApp(
journalController: journalController,
userSettingsController: userSettingsController,
),
);
}
| new_flutter_template/evaluations/journal_mvc/lib/main.dart/0 | {'file_path': 'new_flutter_template/evaluations/journal_mvc/lib/main.dart', 'repo_id': 'new_flutter_template', 'token_count': 380} |
import 'package:flutter/material.dart';
import 'package:list_detail_breadcrumbs/src/user_list.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'List/Detail Demo',
theme: ThemeData.dark(),
home: MyListPage(),
);
}
}
| new_flutter_template/evaluations/list_detail_breadcrumbs/lib/main.dart/0 | {'file_path': 'new_flutter_template/evaluations/list_detail_breadcrumbs/lib/main.dart', 'repo_id': 'new_flutter_template', 'token_count': 151} |
import 'package:flutter/material.dart';
import 'package:list_detail_mvc_dummy/src/dummy.dart';
class DummyDetailsPage extends StatelessWidget {
final Dummy dummy;
const DummyDetailsPage({Key key, this.dummy}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dummy Details'),
),
body: Center(
child: Text('Dummy Content'),
),
);
}
}
| new_flutter_template/evaluations/list_detail_mvc_dummy/lib/src/dummy_details_view.dart/0 | {'file_path': 'new_flutter_template/evaluations/list_detail_mvc_dummy/lib/src/dummy_details_view.dart', 'repo_id': 'new_flutter_template', 'token_count': 181} |
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:list_detail_mvc_provider/src/users/user.dart';
import 'package:list_detail_mvc_provider/src/users/user_list_controller.dart';
import 'package:provider/provider.dart';
class UserListView extends StatefulWidget {
@override
_UserListViewState createState() => _UserListViewState();
}
class _UserListViewState extends State<UserListView> {
@override
void initState() {
context.read<UserController>().loadUsers();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('User List')),
body: Consumer<UserController>(
builder: (context, controller, child) {
if (controller.loading) {
return Center(child: CircularProgressIndicator());
}
return ListView.builder(
itemCount: controller.users.length,
itemBuilder: (context, index) {
var user = controller.users[index];
return ListTile(
title: Text('User #${user.id}'),
onTap: () =>
Navigator.pushNamed(context, '/user', arguments: user),
);
},
);
},
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
final newUser = User(Random().nextInt(1000));
context.read<UserController>().addUser(newUser);
},
),
);
}
}
| new_flutter_template/evaluations/list_detail_mvc_provider/lib/src/users/user_list_view.dart/0 | {'file_path': 'new_flutter_template/evaluations/list_detail_mvc_provider/lib/src/users/user_list_view.dart', 'repo_id': 'new_flutter_template', 'token_count': 662} |
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:list_detail_mvc_value_notifier/src/users/user.dart';
import 'package:list_detail_mvc_value_notifier/src/users/user_list_model.dart';
import 'package:list_detail_mvc_value_notifier/src/users/user_repository.dart';
class UserListController extends ValueNotifier<UserListModel> {
UserListController(this.repository) : super(UserListModel.initial());
final UserRepository repository;
Future<void> loadUsers() async {
value = UserListModel.loading();
try {
value = UserListModel.populated(await repository.users());
} catch (error) {
value = UserListModel.error();
}
}
Future<void> addUser(User user) async {
value = UserListModel.populated([...value.users, user]);
await repository.addUser(user);
}
Future<void> removeUser(User user) async {
value = UserListModel.populated(value.users..remove(user));
await repository.addUser(user);
}
}
| new_flutter_template/evaluations/list_detail_mvc_value_notifier/lib/src/users/user_list_controller.dart/0 | {'file_path': 'new_flutter_template/evaluations/list_detail_mvc_value_notifier/lib/src/users/user_list_controller.dart', 'repo_id': 'new_flutter_template', 'token_count': 342} |
import 'package:flutter/material.dart';
import 'package:list_detail_mvc_vn_responsive_dummies/src/dummies/dummy_details_view.dart';
import 'package:list_detail_mvc_vn_responsive_dummies/src/dummies/dummy_list_controller.dart';
import 'package:list_detail_mvc_vn_responsive_dummies/src/dummies/dummy_list_view.dart';
class DummyListApp extends StatelessWidget {
final DummyListController controller;
const DummyListApp({Key key, @required this.controller}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'List/Detail Demo',
theme: ThemeData.dark(),
initialRoute: '/',
onGenerateRoute: (settings) {
return MaterialPageRoute(
builder: (context) {
return settings.name.contains('dummy')
? DummyDetailsView(id: int.parse(settings.name.split('/').last))
: DummyListView(controller: controller);
},
);
},
home: DummyListView(controller: controller),
);
}
}
| new_flutter_template/evaluations/list_detail_mvc_vn_responsive_dummies/lib/src/app.dart/0 | {'file_path': 'new_flutter_template/evaluations/list_detail_mvc_vn_responsive_dummies/lib/src/app.dart', 'repo_id': 'new_flutter_template', 'token_count': 411} |
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:list_detail_with_some_boilerplate/src/user.dart';
import 'package:list_detail_with_some_boilerplate/src/user_details.dart';
class UserListPage extends StatelessWidget {
final List<User> users;
const UserListPage({Key key, @required this.users}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context).userList),
),
body: ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
var user = users[index];
return ListTile(
title: Text(AppLocalizations.of(context).userName(user.id)),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (_) => UserDetailsPage(user: user)),
);
},
);
},
),
);
}
}
| new_flutter_template/evaluations/list_detail_with_some_boilerplate/lib/src/user_list.dart/0 | {'file_path': 'new_flutter_template/evaluations/list_detail_with_some_boilerplate/lib/src/user_list.dart', 'repo_id': 'new_flutter_template', 'token_count': 456} |
import 'dart:convert';
import 'package:http/http.dart';
import 'package:login_mvc/src/auth/auth_repository.dart';
import 'package:login_mvc/src/users/user.dart';
import 'package:login_mvc/src/users/user_not_found_error.dart';
class UserRepository {
final Client httpClient;
final AuthRepository authRepository;
UserRepository(this.httpClient, this.authRepository);
Future<User> user(int id) async {
final response = await httpClient.get(
'https://reqres.in/api/users/$id',
headers: {'authorization': await authRepository.token},
);
if (response.statusCode == 200) {
return User.fromJson(json.decode(utf8.decode(response.bodyBytes)));
} else {
throw UserNotFoundError(id);
}
}
}
| new_flutter_template/evaluations/login_mvc/lib/src/users/user_repository.dart/0 | {'file_path': 'new_flutter_template/evaluations/login_mvc/lib/src/users/user_repository.dart', 'repo_id': 'new_flutter_template', 'token_count': 276} |
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
const kGrey1 = Color(0xFF9F9F9F);
const kGrey2 = Color(0xFF6D6D6D);
const kGrey3 = Color(0xFFEAEAEA);
const kBlack = Color(0xFF1C1C1C);
var kNonActiveTabStyle = GoogleFonts.roboto(
textStyle: TextStyle(fontSize: 14.0, color: kGrey1),
);
var kActiveTabStyle = GoogleFonts.exo2(
textStyle: TextStyle(
fontSize: 16.0,
color: kBlack,
fontWeight: FontWeight.bold,
),
);
var kCategoryTitle = GoogleFonts.roboto(
textStyle: TextStyle(
fontSize: 14.0,
color: kGrey2,
fontWeight: FontWeight.bold,
),
);
var kDetailContent = GoogleFonts.josefinSans(
textStyle: TextStyle(
fontSize: 14.0,
color: kGrey2,
),
);
var kTitleCard = GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 18.0,
color: kBlack,
fontWeight: FontWeight.bold,
),
);
var descriptionStyle = GoogleFonts.roboto(
textStyle: TextStyle(
fontSize: 15.0,
height: 2.0,
));
//profile
const kSpacingUnit = 10;
const kDarkPrimaryColor = Color(0xFF212121);
const kDarkSecondaryColor = Color(0xFF373737);
const kLightPrimaryColor = Color(0xFFFFFFFF);
const kLightSecondaryColor = Color(0xFFF3F7FB);
const kAccentColor = Color(0xFFFFC107);
final kTitleTextStyle = TextStyle(
fontSize: ScreenUtil().setSp(kSpacingUnit.w * 1.7),
fontWeight: FontWeight.w600,
);
final kCaptionTextStyle = TextStyle(
fontSize: ScreenUtil().setSp(kSpacingUnit.w * 1.3),
fontWeight: FontWeight.w100,
);
final kButtonTextStyle = TextStyle(
fontSize: ScreenUtil().setSp(kSpacingUnit.w * 1.5),
fontWeight: FontWeight.w400,
color: Colors.white,
);
//profile
final kDarkTheme = ThemeData(
brightness: Brightness.dark,
fontFamily: 'SFProText',
primaryColor: kDarkPrimaryColor,
canvasColor: kDarkPrimaryColor,
backgroundColor: kDarkSecondaryColor,
accentColor: kAccentColor,
iconTheme: ThemeData.dark().iconTheme.copyWith(
color: kLightSecondaryColor,
),
textTheme: ThemeData.dark().textTheme.apply(
fontFamily: 'SFProText',
bodyColor: kLightSecondaryColor,
displayColor: kLightSecondaryColor,
),
);
final kLightTheme = ThemeData(
brightness: Brightness.light,
fontFamily: 'SFProText',
primaryColor: kLightPrimaryColor,
canvasColor: kLightPrimaryColor,
backgroundColor: kLightSecondaryColor,
accentColor: kAccentColor,
iconTheme: ThemeData.light().iconTheme.copyWith(
color: kDarkSecondaryColor,
),
textTheme: ThemeData.light().textTheme.apply(
fontFamily: 'SFProText',
bodyColor: kDarkSecondaryColor,
displayColor: kDarkSecondaryColor,
),
);
| news_app/lib/constants.dart/0 | {'file_path': 'news_app/lib/constants.dart', 'repo_id': 'news_app', 'token_count': 1001} |
name: purchase_client
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
pull_request:
paths:
- "flutter_news_example/packages/purchase_client/**"
- ".github/workflows/purchase_client.yaml"
branches:
- main
jobs:
build:
uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1
with:
flutter_version: 3.10.2
working_directory: flutter_news_example/packages/purchase_client
| news_toolkit/.github/workflows/purchase_client.yaml/0 | {'file_path': 'news_toolkit/.github/workflows/purchase_client.yaml', 'repo_id': 'news_toolkit', 'token_count': 197} |
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:news_blocks/news_blocks.dart';
part 'article.g.dart';
/// {@template article}
/// A news article object which contains paginated contents.
/// {@endtemplate}
@JsonSerializable()
class Article extends Equatable {
/// {@macro article}
const Article({
required this.title,
required this.blocks,
required this.totalBlocks,
required this.url,
});
/// Converts a `Map<String, dynamic>` into a [Article] instance.
factory Article.fromJson(Map<String, dynamic> json) =>
_$ArticleFromJson(json);
/// The article title.
final String title;
/// The list of news blocks for the associated article (paginated).
@NewsBlocksConverter()
final List<NewsBlock> blocks;
/// The total number of blocks for this article.
final int totalBlocks;
/// The article url.
final Uri url;
/// Converts the current instance to a `Map<String, dynamic>`.
Map<String, dynamic> toJson() => _$ArticleToJson(this);
@override
List<Object> get props => [title, blocks, totalBlocks, url];
}
| news_toolkit/flutter_news_example/api/lib/src/data/models/article.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/api/lib/src/data/models/article.dart', 'repo_id': 'news_toolkit', 'token_count': 355} |
import 'package:dart_frog/dart_frog.dart';
/// A lightweight user object associated with an incoming [Request].
class RequestUser {
const RequestUser._({required this.id});
/// The unique user identifier.
final String id;
/// An anonymous user.
static const anonymous = RequestUser._(id: '');
/// Whether the user is anonymous.
bool get isAnonymous => this == RequestUser.anonymous;
}
/// Provider a [RequestUser] to the current [RequestContext].
Middleware userProvider() {
return (handler) {
return handler.use(
provider<RequestUser>((context) {
final userId = _extractUserId(context.request);
return userId != null
? RequestUser._(id: userId)
: RequestUser.anonymous;
}),
);
};
}
String? _extractUserId(Request request) {
final authorizationHeader = request.headers['authorization'];
if (authorizationHeader == null) return null;
final segments = authorizationHeader.split(' ');
if (segments.length != 2) return null;
if (segments.first.toLowerCase() != 'bearer') return null;
final userId = segments.last;
return userId;
}
| news_toolkit/flutter_news_example/api/lib/src/middleware/user_provider.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/api/lib/src/middleware/user_provider.dart', 'repo_id': 'news_toolkit', 'token_count': 364} |
import 'package:equatable/equatable.dart';
import 'package:flutter_news_example_api/api.dart';
import 'package:json_annotation/json_annotation.dart';
part 'subscriptions_response.g.dart';
/// {@template subscriptions_response}
/// A subscriptions response object which
/// contains a list of all available subscriptions.
/// {@endtemplate}
@JsonSerializable(explicitToJson: true)
class SubscriptionsResponse extends Equatable {
/// {@macro subscriptions_response}
const SubscriptionsResponse({required this.subscriptions});
/// Converts a `Map<String, dynamic>` into a
/// [SubscriptionsResponse] instance.
factory SubscriptionsResponse.fromJson(Map<String, dynamic> json) =>
_$SubscriptionsResponseFromJson(json);
/// The list of subscriptions.
final List<Subscription> subscriptions;
/// Converts the current instance to a `Map<String, dynamic>`.
Map<String, dynamic> toJson() => _$SubscriptionsResponseToJson(this);
@override
List<Object> get props => [subscriptions];
}
| news_toolkit/flutter_news_example/api/lib/src/models/subscriptions_response/subscriptions_response.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/api/lib/src/models/subscriptions_response/subscriptions_response.dart', 'repo_id': 'news_toolkit', 'token_count': 299} |
import 'package:news_blocks/news_blocks.dart';
import 'package:test/test.dart';
void main() {
group('ArticleIntroductionBlock', () {
test('can be (de)serialized', () {
final block = ArticleIntroductionBlock(
category: PostCategory.technology,
author: 'author',
publishedAt: DateTime(2022, 3, 9),
imageUrl: 'imageUrl',
title: 'title',
);
expect(ArticleIntroductionBlock.fromJson(block.toJson()), equals(block));
});
});
}
| news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/article_introduction_block_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/article_introduction_block_test.dart', 'repo_id': 'news_toolkit', 'token_count': 194} |
import 'package:news_blocks/news_blocks.dart';
import 'package:test/test.dart';
void main() {
group('PostSmallBlock', () {
test('can be (de)serialized', () {
final block = PostSmallBlock(
id: 'id',
category: PostCategory.health,
author: 'author',
publishedAt: DateTime(2022, 3, 11),
imageUrl: 'imageUrl',
title: 'title',
);
expect(PostSmallBlock.fromJson(block.toJson()), equals(block));
});
});
}
| news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/post_small_block_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/post_small_block_test.dart', 'repo_id': 'news_toolkit', 'token_count': 208} |
import 'package:dart_frog/dart_frog.dart';
import 'package:flutter_news_example_api/api.dart';
Handler middleware(Handler handler) {
return handler
.use(requestLogger())
.use(userProvider())
.use(newsDataSourceProvider());
}
| news_toolkit/flutter_news_example/api/routes/_middleware.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/api/routes/_middleware.dart', 'repo_id': 'news_toolkit', 'token_count': 93} |
import 'dart:io';
import 'package:dart_frog/dart_frog.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
import '../../routes/index.dart' as route;
class _MockRequestContext extends Mock implements RequestContext {}
void main() {
group('GET /', () {
test('responds with a 204.', () {
final context = _MockRequestContext();
final response = route.onRequest(context);
expect(response.statusCode, equals(HttpStatus.noContent));
});
});
}
| news_toolkit/flutter_news_example/api/test/routes/index_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/api/test/routes/index_test.dart', 'repo_id': 'news_toolkit', 'token_count': 179} |
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart' as ads;
import 'package:news_blocks_ui/news_blocks_ui.dart';
import 'package:platform/platform.dart';
part 'full_screen_ads_event.dart';
part 'full_screen_ads_state.dart';
/// Signature for the interstitial ad loader.
typedef InterstitialAdLoader = Future<void> Function({
required String adUnitId,
required ads.InterstitialAdLoadCallback adLoadCallback,
required ads.AdRequest request,
});
/// Signature for the rewarded ad loader.
typedef RewardedAdLoader = Future<void> Function({
required String adUnitId,
required ads.RewardedAdLoadCallback rewardedAdLoadCallback,
required ads.AdRequest request,
});
/// A bloc that manages pre-loading and showing interstitial and rewarded ads
/// with an [_adsRetryPolicy].
class FullScreenAdsBloc extends Bloc<FullScreenAdsEvent, FullScreenAdsState> {
FullScreenAdsBloc({
required AdsRetryPolicy adsRetryPolicy,
required InterstitialAdLoader interstitialAdLoader,
required RewardedAdLoader rewardedAdLoader,
required LocalPlatform localPlatform,
FullScreenAdsConfig? fullScreenAdsConfig,
}) : _adsRetryPolicy = adsRetryPolicy,
_interstitialAdLoader = interstitialAdLoader,
_rewardedAdLoader = rewardedAdLoader,
_localPlatform = localPlatform,
_fullScreenAdsConfig =
fullScreenAdsConfig ?? const FullScreenAdsConfig(),
super(const FullScreenAdsState.initial()) {
on<LoadInterstitialAdRequested>(_onLoadInterstitialAdRequested);
on<LoadRewardedAdRequested>(_onLoadRewardedAdRequested);
on<ShowInterstitialAdRequested>(_onShowInterstitialAdRequested);
on<ShowRewardedAdRequested>(_onShowRewardedAdRequested);
on<EarnedReward>(_onEarnedReward);
}
/// The retry policy for loading interstitial and rewarded ads.
final AdsRetryPolicy _adsRetryPolicy;
/// The config of interstitial and rewarded ads.
final FullScreenAdsConfig _fullScreenAdsConfig;
/// The loader of interstitial ads.
final InterstitialAdLoader _interstitialAdLoader;
/// The loader of rewarded ads.
final RewardedAdLoader _rewardedAdLoader;
/// The current platform.
final LocalPlatform _localPlatform;
Future<void> _onLoadInterstitialAdRequested(
LoadInterstitialAdRequested event,
Emitter<FullScreenAdsState> emit,
) async {
try {
final ad = Completer<ads.InterstitialAd>();
emit(state.copyWith(status: FullScreenAdsStatus.loadingInterstitialAd));
await _interstitialAdLoader(
adUnitId: _fullScreenAdsConfig.interstitialAdUnitId ??
(_localPlatform.isAndroid
? FullScreenAdsConfig.androidTestInterstitialAdUnitId
: FullScreenAdsConfig.iosTestInterstitialAdUnitId),
request: const ads.AdRequest(),
adLoadCallback: ads.InterstitialAdLoadCallback(
onAdLoaded: ad.complete,
onAdFailedToLoad: ad.completeError,
),
);
final adResult = await ad.future;
emit(
state.copyWith(
interstitialAd: adResult,
status: FullScreenAdsStatus.loadingInterstitialAdSucceeded,
),
);
} catch (error, stackTrace) {
emit(
state.copyWith(
status: FullScreenAdsStatus.loadingInterstitialAdFailed,
),
);
addError(error, stackTrace);
if (event.retry < _adsRetryPolicy.maxRetryCount) {
final nextRetry = event.retry + 1;
await Future<void>.delayed(
_adsRetryPolicy.getIntervalForRetry(nextRetry),
);
add(LoadInterstitialAdRequested(retry: nextRetry));
}
}
}
Future<void> _onLoadRewardedAdRequested(
LoadRewardedAdRequested event,
Emitter<FullScreenAdsState> emit,
) async {
try {
final ad = Completer<ads.RewardedAd>();
emit(state.copyWith(status: FullScreenAdsStatus.loadingRewardedAd));
await _rewardedAdLoader(
adUnitId: _fullScreenAdsConfig.rewardedAdUnitId ??
(_localPlatform.isAndroid
? FullScreenAdsConfig.androidTestRewardedAdUnitId
: FullScreenAdsConfig.iosTestRewardedAdUnitId),
request: const ads.AdRequest(),
rewardedAdLoadCallback: ads.RewardedAdLoadCallback(
onAdLoaded: ad.complete,
onAdFailedToLoad: ad.completeError,
),
);
final adResult = await ad.future;
emit(
state.copyWith(
rewardedAd: adResult,
status: FullScreenAdsStatus.loadingRewardedAdSucceeded,
),
);
} catch (error, stackTrace) {
emit(
state.copyWith(
status: FullScreenAdsStatus.loadingRewardedAdFailed,
),
);
addError(error, stackTrace);
if (event.retry < _adsRetryPolicy.maxRetryCount) {
final nextRetry = event.retry + 1;
await Future<void>.delayed(
_adsRetryPolicy.getIntervalForRetry(nextRetry),
);
add(LoadRewardedAdRequested(retry: nextRetry));
}
}
}
Future<void> _onShowInterstitialAdRequested(
ShowInterstitialAdRequested event,
Emitter<FullScreenAdsState> emit,
) async {
try {
emit(state.copyWith(status: FullScreenAdsStatus.showingInterstitialAd));
state.interstitialAd?.fullScreenContentCallback =
ads.FullScreenContentCallback(
onAdDismissedFullScreenContent: (ad) => ad.dispose(),
onAdFailedToShowFullScreenContent: (ad, error) {
ad.dispose();
addError(error);
},
);
// Show currently available interstitial ad.
await state.interstitialAd?.show();
emit(
state.copyWith(
status: FullScreenAdsStatus.showingInterstitialAdSucceeded,
),
);
// Load the next interstitial ad.
add(const LoadInterstitialAdRequested());
} catch (error, stackTrace) {
emit(
state.copyWith(
status: FullScreenAdsStatus.showingInterstitialAdFailed,
),
);
addError(error, stackTrace);
}
}
Future<void> _onShowRewardedAdRequested(
ShowRewardedAdRequested event,
Emitter<FullScreenAdsState> emit,
) async {
try {
emit(state.copyWith(status: FullScreenAdsStatus.showingRewardedAd));
state.rewardedAd?.fullScreenContentCallback =
ads.FullScreenContentCallback(
onAdDismissedFullScreenContent: (ad) => ad.dispose(),
onAdFailedToShowFullScreenContent: (ad, error) {
ad.dispose();
addError(error);
},
);
// Show currently available rewarded ad.
await state.rewardedAd?.show(
onUserEarnedReward: (ad, earnedReward) => add(
EarnedReward(earnedReward),
),
);
emit(
state.copyWith(
status: FullScreenAdsStatus.showingRewardedAdSucceeded,
),
);
// Load the next rewarded ad.
add(const LoadRewardedAdRequested());
} catch (error, stackTrace) {
emit(
state.copyWith(
status: FullScreenAdsStatus.showingRewardedAdFailed,
),
);
addError(error, stackTrace);
}
}
void _onEarnedReward(EarnedReward event, Emitter<FullScreenAdsState> emit) =>
emit(state.copyWith(earnedReward: event.reward));
}
| news_toolkit/flutter_news_example/lib/ads/bloc/full_screen_ads_bloc.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/ads/bloc/full_screen_ads_bloc.dart', 'repo_id': 'news_toolkit', 'token_count': 2940} |
export 'authenticated_user_listener.dart';
| news_toolkit/flutter_news_example/lib/app/widgets/widgets.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/app/widgets/widgets.dart', 'repo_id': 'news_toolkit', 'token_count': 14} |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'categories_bloc.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
CategoriesState _$CategoriesStateFromJson(Map<String, dynamic> json) =>
CategoriesState(
status: $enumDecode(_$CategoriesStatusEnumMap, json['status']),
categories: (json['categories'] as List<dynamic>?)
?.map((e) => $enumDecode(_$CategoryEnumMap, e))
.toList(),
selectedCategory:
$enumDecodeNullable(_$CategoryEnumMap, json['selectedCategory']),
);
Map<String, dynamic> _$CategoriesStateToJson(CategoriesState instance) =>
<String, dynamic>{
'status': _$CategoriesStatusEnumMap[instance.status]!,
'categories':
instance.categories?.map((e) => _$CategoryEnumMap[e]!).toList(),
'selectedCategory': _$CategoryEnumMap[instance.selectedCategory],
};
const _$CategoriesStatusEnumMap = {
CategoriesStatus.initial: 'initial',
CategoriesStatus.loading: 'loading',
CategoriesStatus.populated: 'populated',
CategoriesStatus.failure: 'failure',
};
const _$CategoryEnumMap = {
Category.business: 'business',
Category.entertainment: 'entertainment',
Category.top: 'top',
Category.health: 'health',
Category.science: 'science',
Category.sports: 'sports',
Category.technology: 'technology',
};
| news_toolkit/flutter_news_example/lib/categories/bloc/categories_bloc.g.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/categories/bloc/categories_bloc.g.dart', 'repo_id': 'news_toolkit', 'token_count': 480} |
export 'category_feed.dart';
export 'category_feed_item.dart';
export 'category_feed_loader_item.dart';
| news_toolkit/flutter_news_example/lib/feed/widgets/widgets.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/feed/widgets/widgets.dart', 'repo_id': 'news_toolkit', 'token_count': 36} |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/login/login.dart';
import 'package:user_repository/user_repository.dart';
class LoginModal extends StatelessWidget {
const LoginModal({super.key});
static Route<void> route() =>
MaterialPageRoute<void>(builder: (_) => const LoginModal());
static const String name = '/loginModal';
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => LoginBloc(
userRepository: context.read<UserRepository>(),
),
child: const LoginForm(),
);
}
}
| news_toolkit/flutter_news_example/lib/login/view/login_modal.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/login/view/login_modal.dart', 'repo_id': 'news_toolkit', 'token_count': 228} |
import 'package:flutter/material.dart';
import 'package:flutter_news_example/l10n/l10n.dart';
@visibleForTesting
class BottomNavBar extends StatelessWidget {
const BottomNavBar({
required this.currentIndex,
required this.onTap,
super.key,
});
final int currentIndex;
final ValueSetter<int> onTap;
@override
Widget build(BuildContext context) {
return BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon: const Icon(Icons.home_outlined),
label: context.l10n.bottomNavBarTopStories,
),
BottomNavigationBarItem(
icon: const Icon(
Icons.search,
key: Key('bottomNavBar_search'),
),
label: context.l10n.bottomNavBarSearch,
),
],
currentIndex: currentIndex,
onTap: onTap,
);
}
}
| news_toolkit/flutter_news_example/lib/navigation/view/bottom_nav_bar.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/navigation/view/bottom_nav_bar.dart', 'repo_id': 'news_toolkit', 'token_count': 367} |
export 'bloc/notification_preferences_bloc.dart';
export 'view/view.dart';
export 'widgets/widgets.dart';
| news_toolkit/flutter_news_example/lib/notification_preferences/notification_preferences.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/notification_preferences/notification_preferences.dart', 'repo_id': 'news_toolkit', 'token_count': 41} |
part of 'search_bloc.dart';
enum SearchStatus {
initial,
loading,
populated,
failure,
}
enum SearchType {
popular,
relevant,
}
class SearchState extends Equatable {
const SearchState({
required this.articles,
required this.topics,
required this.status,
required this.searchType,
});
const SearchState.initial()
: this(
articles: const [],
topics: const [],
status: SearchStatus.initial,
searchType: SearchType.popular,
);
final List<NewsBlock> articles;
final List<String> topics;
final SearchStatus status;
final SearchType searchType;
@override
List<Object?> get props => [articles, topics, status, searchType];
SearchState copyWith({
List<NewsBlock>? articles,
List<String>? topics,
SearchStatus? status,
SearchType? searchType,
}) =>
SearchState(
articles: articles ?? this.articles,
topics: topics ?? this.topics,
status: status ?? this.status,
searchType: searchType ?? this.searchType,
);
}
| news_toolkit/flutter_news_example/lib/search/bloc/search_state.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/search/bloc/search_state.dart', 'repo_id': 'news_toolkit', 'token_count': 397} |
export 'bloc/subscriptions_bloc.dart';
export 'view/purchase_subscription_dialog.dart';
| news_toolkit/flutter_news_example/lib/subscriptions/dialog/dialog.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/subscriptions/dialog/dialog.dart', 'repo_id': 'news_toolkit', 'token_count': 33} |
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
part 'theme_mode_event.dart';
/// Keeps track of and allows changing the application's [ThemeMode].
class ThemeModeBloc extends HydratedBloc<ThemeModeEvent, ThemeMode> {
/// Create a new object
ThemeModeBloc() : super(ThemeMode.system) {
on<ThemeModeChanged>((event, emit) => emit(event.themeMode ?? state));
}
@override
ThemeMode fromJson(Map<dynamic, dynamic> json) =>
ThemeMode.values[json['theme_mode'] as int];
@override
Map<String, int> toJson(ThemeMode state) => {'theme_mode': state.index};
}
| news_toolkit/flutter_news_example/lib/theme_selector/bloc/theme_mode_bloc.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/theme_selector/bloc/theme_mode_bloc.dart', 'repo_id': 'news_toolkit', 'token_count': 225} |
export 'src/ads_consent_client.dart';
| news_toolkit/flutter_news_example/packages/ads_consent_client/lib/ads_consent_client.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/ads_consent_client/lib/ads_consent_client.dart', 'repo_id': 'news_toolkit', 'token_count': 15} |
export 'spacing_page.dart';
| news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/spacing/spacing.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/spacing/spacing.dart', 'repo_id': 'news_toolkit', 'token_count': 11} |
export 'app_font_weight.dart';
export 'app_text_styles.dart';
| news_toolkit/flutter_news_example/packages/app_ui/lib/src/typography/typography.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/app_ui/lib/src/typography/typography.dart', 'repo_id': 'news_toolkit', 'token_count': 24} |
// ignore_for_file: prefer_const_literals_to_create_immutables
// ignore_for_file: prefer_const_constructors
// ignore_for_file: avoid_redundant_argument_values
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import '../helpers/helpers.dart';
void main() {
group('AppButton', () {
final theme = AppTheme().themeData;
final buttonTextTheme = theme.textTheme.labelLarge!.copyWith(
inherit: false,
);
testWidgets('renders button', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
Column(
children: [
AppButton.black(
child: buttonText,
),
AppButton.smallOutlineTransparent(
child: buttonText,
),
AppButton.redWine(
child: buttonText,
),
AppButton.blueDress(
child: buttonText,
),
],
),
);
expect(find.byType(AppButton), findsNWidgets(4));
expect(find.text('buttonText'), findsNWidgets(4));
});
testWidgets(
'renders black button '
'when `AppButton.black()` called', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.black(
child: buttonText,
onPressed: () {},
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.black,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 56),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(double.infinity, 56),
);
});
testWidgets(
'renders blueDress button '
'when `AppButton.blueDress()` called', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.blueDress(
child: buttonText,
onPressed: () {},
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.blueDress,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 56),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(double.infinity, 56),
);
});
testWidgets(
'renders crystalBlue button '
'when `AppButton.crystalBlue()` called', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.crystalBlue(
child: buttonText,
onPressed: () {},
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.crystalBlue,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 56),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(double.infinity, 56),
);
});
testWidgets(
'renders redWine button '
'when `AppButton.redWine()` called', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.redWine(
child: buttonText,
onPressed: () {},
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.redWine,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 56),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(double.infinity, 56),
);
});
testWidgets(
'renders secondary button '
'when `AppButton.secondary()` called', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.secondary(
child: buttonText,
onPressed: () {},
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.secondary,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 40),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(0, 40),
);
});
testWidgets(
'renders darkAqua button '
'when `AppButton.darkAqua()` called', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.darkAqua(
child: buttonText,
onPressed: () {},
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.darkAqua,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 56),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(double.infinity, 56),
);
});
testWidgets(
'renders outlinedWhite button '
'when `AppButton.outlinedWhite()` called', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.outlinedWhite(
child: buttonText,
onPressed: () {},
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.white,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 56),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(double.infinity, 56),
);
});
testWidgets(
'renders outlinedTransparentDarkAqua button '
'when `AppButton.outlinedTransparentDarkAqua()` called',
(tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.outlinedTransparentDarkAqua(
child: buttonText,
onPressed: () {},
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.transparent,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 56),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(double.infinity, 56),
);
});
testWidgets(
'renders outlinedTransparentWhite button '
'when `AppButton.outlinedTransparentWhite()` called', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.outlinedTransparentWhite(
onPressed: () {},
child: buttonText,
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.transparent,
);
expect(
widget.style?.foregroundColor?.resolve({}),
AppColors.white,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 56),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(double.infinity, 56),
);
});
testWidgets(
'renders smallRedWine button '
'when `AppButton.smallRedWine()` called', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.smallRedWine(
child: buttonText,
onPressed: () {},
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.redWine,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 40),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(0, 40),
);
});
testWidgets(
'renders smallDarkAqua button '
'when `AppButton.smallDarkAqua()` called', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.smallDarkAqua(
child: buttonText,
onPressed: () {},
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.darkAqua,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 40),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(0, 40),
);
});
testWidgets(
'renders smallTransparent button '
'when `AppButton.smallTransparent()` called', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.smallTransparent(
child: buttonText,
onPressed: () {},
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.transparent,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 40),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(0, 40),
);
});
testWidgets(
'renders smallOutlineTransparent button '
'when `AppButton.smallOutlineTransparent()` called', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.smallOutlineTransparent(
child: buttonText,
onPressed: () {},
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.transparent,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 40),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(0, 40),
);
});
testWidgets(
'renders transparentDarkAqua button '
'when `AppButton.transparentDarkAqua()` called', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.transparentDarkAqua(
onPressed: () {},
child: buttonText,
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.transparent,
);
expect(
widget.style?.foregroundColor?.resolve({}),
AppColors.darkAqua,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 56),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(double.infinity, 56),
);
});
testWidgets(
'renders transparentWhite button '
'when `AppButton.transparentWhite()` called', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.transparentWhite(
onPressed: () {},
child: buttonText,
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.transparent,
);
expect(
widget.style?.foregroundColor?.resolve({}),
AppColors.white,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 56),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(double.infinity, 56),
);
});
testWidgets(
'renders disabled transparentWhite button '
'when `AppButton.transparentWhite()` called '
'with onPressed equal to null', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.transparentWhite(
onPressed: null,
child: buttonText,
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.transparent,
);
expect(
widget.style?.foregroundColor?.resolve({}),
AppColors.white,
);
expect(
widget.style?.textStyle?.resolve({}),
buttonTextTheme,
);
expect(
widget.style?.maximumSize?.resolve({}),
Size(double.infinity, 56),
);
expect(
widget.style?.minimumSize?.resolve({}),
Size(double.infinity, 56),
);
});
testWidgets(
'changes background color to AppColors.black.withOpacity(.12) '
'when `onPressed` is null', (tester) async {
final buttonText = Text('buttonText');
await tester.pumpApp(
AppButton.smallOutlineTransparent(
child: buttonText,
),
theme: theme,
);
final finder = find.byType(ElevatedButton);
final widget = tester.widget(finder) as ElevatedButton;
expect(
widget.style?.backgroundColor?.resolve({}),
AppColors.black.withOpacity(.12),
);
});
});
}
| news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/app_button_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/app_button_test.dart', 'repo_id': 'news_toolkit', 'token_count': 7605} |
import 'package:article_repository/article_repository.dart';
import 'package:mocktail/mocktail.dart';
import 'package:storage/storage.dart';
import 'package:test/test.dart';
class MockStorage extends Mock implements Storage {}
void main() {
group('ArticleStorage', () {
late Storage storage;
setUp(() {
storage = MockStorage();
when(
() => storage.write(
key: any(named: 'key'),
value: any(named: 'value'),
),
).thenAnswer((_) async {});
});
group('setArticleViews', () {
test('saves the value in Storage', () async {
const views = 3;
await ArticleStorage(storage: storage).setArticleViews(views);
verify(
() => storage.write(
key: ArticleStorageKeys.articleViews,
value: views.toString(),
),
).called(1);
});
});
group('fetchArticleViews', () {
test('returns the value from Storage', () async {
when(
() => storage.read(key: ArticleStorageKeys.articleViews),
).thenAnswer((_) async => '3');
final result =
await ArticleStorage(storage: storage).fetchArticleViews();
verify(
() => storage.read(
key: ArticleStorageKeys.articleViews,
),
).called(1);
expect(result, equals(3));
});
test('returns 0 when no value exists in Storage', () async {
when(
() => storage.read(key: ArticleStorageKeys.articleViews),
).thenAnswer((_) async => null);
final result =
await ArticleStorage(storage: storage).fetchArticleViews();
verify(
() => storage.read(
key: ArticleStorageKeys.articleViews,
),
).called(1);
expect(result, isZero);
});
});
group('setArticleViewsResetDate', () {
test('saves the value in Storage', () async {
final date = DateTime(2022, 6, 7);
await ArticleStorage(storage: storage).setArticleViewsResetDate(date);
verify(
() => storage.write(
key: ArticleStorageKeys.articleViewsResetAt,
value: date.toIso8601String(),
),
).called(1);
});
});
group('fetchArticleViewsResetDate', () {
test('returns the value from Storage', () async {
final date = DateTime(2022, 6, 7);
when(
() => storage.read(key: ArticleStorageKeys.articleViewsResetAt),
).thenAnswer((_) async => date.toIso8601String());
final result =
await ArticleStorage(storage: storage).fetchArticleViewsResetDate();
verify(
() => storage.read(
key: ArticleStorageKeys.articleViewsResetAt,
),
).called(1);
expect(result, equals(date));
});
test('returns null when no value exists in Storage', () async {
when(
() => storage.read(key: ArticleStorageKeys.articleViewsResetAt),
).thenAnswer((_) async => null);
final result =
await ArticleStorage(storage: storage).fetchArticleViewsResetDate();
verify(
() => storage.read(
key: ArticleStorageKeys.articleViewsResetAt,
),
).called(1);
expect(result, isNull);
});
});
group('setTotalArticleViews', () {
test('saves the value in Storage', () async {
const views = 3;
await ArticleStorage(storage: storage).setTotalArticleViews(views);
verify(
() => storage.write(
key: ArticleStorageKeys.totalArticleViews,
value: views.toString(),
),
).called(1);
});
});
group('fetchTotalArticleViews', () {
test('returns the value from Storage', () async {
when(
() => storage.read(key: ArticleStorageKeys.totalArticleViews),
).thenAnswer((_) async => '3');
final result =
await ArticleStorage(storage: storage).fetchTotalArticleViews();
verify(
() => storage.read(
key: ArticleStorageKeys.totalArticleViews,
),
).called(1);
expect(result, equals(3));
});
test('returns 0 when no value exists in Storage', () async {
when(
() => storage.read(key: ArticleStorageKeys.totalArticleViews),
).thenAnswer((_) async => null);
final result =
await ArticleStorage(storage: storage).fetchTotalArticleViews();
verify(
() => storage.read(
key: ArticleStorageKeys.totalArticleViews,
),
).called(1);
expect(result, isZero);
});
test('returns 0 when stored value is malformed', () async {
when(
() => storage.read(key: ArticleStorageKeys.totalArticleViews),
).thenAnswer((_) async => 'malformed');
final result =
await ArticleStorage(storage: storage).fetchTotalArticleViews();
verify(
() => storage.read(
key: ArticleStorageKeys.totalArticleViews,
),
).called(1);
expect(result, isZero);
});
});
});
}
| news_toolkit/flutter_news_example/packages/article_repository/test/src/article_storage_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/article_repository/test/src/article_storage_test.dart', 'repo_id': 'news_toolkit', 'token_count': 2297} |
name: firebase_authentication_client
description: A Firebase implementation of the authentication client interface
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
dependencies:
authentication_client:
path: ../authentication_client
firebase_auth: ^4.16.0
firebase_auth_platform_interface: ^7.0.9
firebase_core: ^2.24.2
firebase_core_platform_interface: ^5.0.0
flutter:
sdk: flutter
flutter_facebook_auth: ^6.0.0
google_sign_in: ^6.0.2
plugin_platform_interface: ^2.1.3
sign_in_with_apple: ^5.0.0
token_storage:
path: ../token_storage
twitter_login: ^4.2.2
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^1.0.2
very_good_analysis: ^5.1.0
| news_toolkit/flutter_news_example/packages/authentication_client/firebase_authentication_client/pubspec.yaml/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/authentication_client/firebase_authentication_client/pubspec.yaml', 'repo_id': 'news_toolkit', 'token_count': 296} |
include: package:very_good_analysis/analysis_options.5.1.0.yaml
| news_toolkit/flutter_news_example/packages/email_launcher/analysis_options.yaml/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/email_launcher/analysis_options.yaml', 'repo_id': 'news_toolkit', 'token_count': 23} |
include: package:very_good_analysis/analysis_options.5.1.0.yaml
| news_toolkit/flutter_news_example/packages/in_app_purchase_repository/analysis_options.yaml/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/in_app_purchase_repository/analysis_options.yaml', 'repo_id': 'news_toolkit', 'token_count': 23} |
import 'package:news_blocks/news_blocks.dart';
/// Signature of callbacks invoked when [BlockAction] is triggered.
typedef BlockActionCallback = void Function(BlockAction action);
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/block_action_callback.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/block_action_callback.dart', 'repo_id': 'news_toolkit', 'token_count': 47} |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:news_blocks_ui/src/widgets/widgets.dart';
/// {@template post_medium_description_layout}
/// A reusable post medium news block widget showing post description.
/// {@endtemplate}
class PostMediumDescriptionLayout extends StatelessWidget {
/// {@macro post_medium_description_layout}
const PostMediumDescriptionLayout({
required this.title,
required this.imageUrl,
required this.publishedAt,
this.description,
this.author,
this.onShare,
super.key,
});
/// Title of post.
final String title;
/// Description of post.
final String? description;
/// The date when this post was published.
final DateTime publishedAt;
/// The author of this post.
final String? author;
/// Called when the share button is tapped.
final VoidCallback? onShare;
/// The url of this post image.
final String imageUrl;
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Padding(
padding: const EdgeInsets.all(AppSpacing.lg),
child: Column(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Text(
title,
style: textTheme.titleLarge
?.copyWith(color: AppColors.highEmphasisSurface),
),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: InlineImage(imageUrl: imageUrl),
),
],
),
Text(
description ?? '',
style: textTheme.bodyMedium
?.copyWith(color: AppColors.mediumEmphasisSurface),
),
const SizedBox(height: AppSpacing.sm),
PostFooter(
publishedAt: publishedAt,
author: author,
onShare: onShare,
),
],
),
);
}
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_medium/post_medium_description_layout.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_medium/post_medium_description_layout.dart', 'repo_id': 'news_toolkit', 'token_count': 901} |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:news_blocks/news_blocks.dart';
/// {@template banner_ad_container}
/// A reusable banner ad container widget.
/// {@endtemplate}
class BannerAdContainer extends StatelessWidget {
/// {@macro banner_ad_container}
const BannerAdContainer({required this.size, required this.child, super.key});
/// The size of this banner ad.
final BannerAdSize size;
/// The [Widget] displayed in this container.
final Widget child;
@override
Widget build(BuildContext context) {
final horizontalPadding = size == BannerAdSize.normal
? AppSpacing.lg + AppSpacing.xs
: AppSpacing.xlg + AppSpacing.xs + AppSpacing.xxs;
final verticalPadding = size == BannerAdSize.normal
? AppSpacing.lg
: AppSpacing.xlg + AppSpacing.sm;
return ColoredBox(
key: const Key('bannerAdContainer_coloredBox'),
color: AppColors.brightGrey,
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: horizontalPadding,
vertical: verticalPadding,
),
child: child,
),
);
}
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/banner_ad_container.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/banner_ad_container.dart', 'repo_id': 'news_toolkit', 'token_count': 433} |
export 'fake_video_player_platform.dart';
export 'path_provider.dart';
export 'pump_app.dart';
export 'pump_content_themed_app.dart';
export 'tolerant_comparator.dart';
| news_toolkit/flutter_news_example/packages/news_blocks_ui/test/helpers/helpers.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/test/helpers/helpers.dart', 'repo_id': 'news_toolkit', 'token_count': 65} |
// ignore_for_file: unnecessary_const, prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:news_blocks_ui/news_blocks_ui.dart';
import '../helpers/helpers.dart';
void main() {
group('TextCaption', () {
setUpAll(setUpTolerantComparator);
testWidgets(
'renders correctly '
'with default normal color', (tester) async {
final widget = Center(
child: TextCaption(
block: TextCaptionBlock(
text: 'Text caption',
color: TextCaptionColor.normal,
),
),
);
await tester.pumpApp(widget);
await expectLater(
find.byType(TextCaption),
matchesGoldenFile('text_caption_normal_color_default.png'),
);
});
testWidgets(
'renders correctly '
'with default light color', (tester) async {
final widget = Center(
child: TextCaption(
block: TextCaptionBlock(
text: 'Text caption',
color: TextCaptionColor.light,
),
),
);
await tester.pumpApp(widget);
await expectLater(
find.byType(TextCaption),
matchesGoldenFile('text_caption_light_color_default.png'),
);
});
testWidgets(
'renders correctly '
'with provided normal color', (tester) async {
final widget = Center(
child: TextCaption(
block: TextCaptionBlock(
text: 'Text caption',
color: TextCaptionColor.normal,
),
colorValues: const {
TextCaptionColor.normal: Colors.green,
},
),
);
await tester.pumpApp(widget);
await expectLater(
find.byType(TextCaption),
matchesGoldenFile('text_caption_normal_color_provided.png'),
);
});
testWidgets(
'renders correctly '
'with provided light color', (tester) async {
final widget = Center(
child: TextCaption(
block: TextCaptionBlock(
text: 'Text caption',
color: TextCaptionColor.light,
),
colorValues: const {
TextCaptionColor.light: Colors.green,
},
),
);
await tester.pumpApp(widget);
await expectLater(
find.byType(TextCaption),
matchesGoldenFile('text_caption_light_color_provided.png'),
);
});
});
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/text_caption_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/text_caption_test.dart', 'repo_id': 'news_toolkit', 'token_count': 1155} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:news_blocks_ui/src/widgets/widgets.dart';
import '../../helpers/helpers.dart';
void main() {
group('LockIcon', () {
testWidgets('renders correctly', (tester) async {
await tester.pumpApp(LockIcon());
expect(find.byType(Icon), findsOneWidget);
});
});
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/lock_icon_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/lock_icon_test.dart', 'repo_id': 'news_toolkit', 'token_count': 163} |
include: package:very_good_analysis/analysis_options.5.1.0.yaml
| news_toolkit/flutter_news_example/packages/news_repository/analysis_options.yaml/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/news_repository/analysis_options.yaml', 'repo_id': 'news_toolkit', 'token_count': 23} |
/// {@template notification_exception}
/// Exceptions from the notification client.
/// {@endtemplate}
abstract class NotificationException implements Exception {
/// {@macro notification_exception}
const NotificationException(this.error);
/// The error which was caught.
final Object error;
}
/// {@template subscribe_to_category_failure}
/// Thrown during the subscription to category if a failure occurs.
/// {@endtemplate}
class SubscribeToCategoryFailure extends NotificationException {
/// {@macro subscribe_to_category_failure}
const SubscribeToCategoryFailure(super.error);
}
/// {@template unsubscribe_from_category_failure}
/// Thrown during the subscription to category if a failure occurs.
/// {@endtemplate}
class UnsubscribeFromCategoryFailure extends NotificationException {
/// {@macro unsubscribe_from_category_failure}
const UnsubscribeFromCategoryFailure(super.error);
}
/// {@template notifications_client}
/// A Generic Notifications Client Interface.
/// {@endtemplate}
abstract class NotificationsClient {
/// Subscribes user to the notification group based on [category].
Future<void> subscribeToCategory(String category);
/// Unsubscribes user from the notification group based on [category].
Future<void> unsubscribeFromCategory(String category);
}
| news_toolkit/flutter_news_example/packages/notifications_client/notifications_client/lib/src/notifications_client.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/notifications_client/notifications_client/lib/src/notifications_client.dart', 'repo_id': 'news_toolkit', 'token_count': 328} |
name: notifications_repository
description: A repository that manages notification permissions and topic subscriptions.
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
dependencies:
equatable: ^2.0.3
flutter:
sdk: flutter
flutter_news_example_api:
path: ../../api
notifications_client:
path: ../notifications_client/notifications_client
permission_client:
path: ../permission_client
storage:
path: ../storage/storage
test: ^1.21.4
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^1.0.2
very_good_analysis: ^5.1.0
| news_toolkit/flutter_news_example/packages/notifications_repository/pubspec.yaml/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/notifications_repository/pubspec.yaml', 'repo_id': 'news_toolkit', 'token_count': 227} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:permission_client/permission_client.dart';
import 'package:permission_handler/permission_handler.dart';
void main() {
final binding = TestWidgetsFlutterBinding.ensureInitialized();
group('PermissionClient', () {
late PermissionClient permissionClient;
late List<MethodCall> calls;
const methodChannelName = 'flutter.baseflow.com/permissions/methods';
setUp(() {
permissionClient = PermissionClient();
calls = [];
binding.defaultBinaryMessenger.setMockMethodCallHandler(
MethodChannel(methodChannelName),
(call) async {
calls.add(call);
if (call.method == 'checkPermissionStatus') {
return PermissionStatus.granted.index;
} else if (call.method == 'requestPermissions') {
return <dynamic, dynamic>{
for (final key in call.arguments as List<dynamic>)
key: PermissionStatus.granted.index,
};
} else if (call.method == 'openAppSettings') {
return true;
}
return null;
},
);
});
tearDown(() {
binding.defaultBinaryMessenger.setMockMethodCallHandler(
MethodChannel(methodChannelName),
(call) async => null,
);
});
Matcher permissionWasRequested(Permission permission) => contains(
isA<MethodCall>()
.having(
(c) => c.method,
'method',
'requestPermissions',
)
.having(
(c) => c.arguments,
'arguments',
contains(permission.value),
),
);
Matcher permissionWasChecked(Permission permission) => contains(
isA<MethodCall>()
.having(
(c) => c.method,
'method',
'checkPermissionStatus',
)
.having(
(c) => c.arguments,
'arguments',
equals(permission.value),
),
);
group('requestNotifications', () {
test('calls correct method', () async {
await permissionClient.requestNotifications();
expect(calls, permissionWasRequested(Permission.notification));
});
});
group('notificationsStatus', () {
test('calls correct method', () async {
await permissionClient.notificationsStatus();
expect(calls, permissionWasChecked(Permission.notification));
});
});
group('openPermissionSettings', () {
test('calls correct method', () async {
await permissionClient.openPermissionSettings();
expect(
calls,
contains(
isA<MethodCall>().having(
(c) => c.method,
'method',
'openAppSettings',
),
),
);
});
});
});
}
| news_toolkit/flutter_news_example/packages/permission_client/test/src/permission_client_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/permission_client/test/src/permission_client_test.dart', 'repo_id': 'news_toolkit', 'token_count': 1423} |
/// {@template storage_exception}
/// Exception thrown if a storage operation fails.
/// {@endtemplate}
class StorageException implements Exception {
/// {@macro storage_exception}
const StorageException(this.error);
/// Error thrown during the storage operation.
final Object error;
}
/// A Dart Storage Client Interface
abstract class Storage {
/// Returns value for the provided [key].
/// Read returns `null` if no value is found for the given [key].
/// * Throws a [StorageException] if the read fails.
Future<String?> read({required String key});
/// Writes the provided [key], [value] pair asynchronously.
/// * Throws a [StorageException] if the write fails.
Future<void> write({required String key, required String value});
/// Removes the value for the provided [key] asynchronously.
/// * Throws a [StorageException] if the delete fails.
Future<void> delete({required String key});
/// Removes all key, value pairs asynchronously.
/// * Throws a [StorageException] if the delete fails.
Future<void> clear();
}
| news_toolkit/flutter_news_example/packages/storage/storage/lib/storage.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/storage/storage/lib/storage.dart', 'repo_id': 'news_toolkit', 'token_count': 282} |
// ignore_for_file: prefer_const_constructors
import 'dart:async';
import 'package:bloc_test/bloc_test.dart';
import 'package:fake_async/fake_async.dart';
import 'package:flutter_news_example/ads/ads.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart' as ads;
import 'package:mocktail/mocktail.dart';
import 'package:news_blocks_ui/news_blocks_ui.dart';
import 'package:platform/platform.dart';
class MockInterstitialAd extends Mock implements ads.InterstitialAd {}
class FakeInterstitialAd extends Fake implements ads.InterstitialAd {
ads.FullScreenContentCallback<ads.InterstitialAd>? contentCallback;
bool disposeCalled = false;
@override
Future<void> show() async {}
@override
Future<void> dispose() async => disposeCalled = true;
@override
set fullScreenContentCallback(
ads.FullScreenContentCallback<ads.InterstitialAd>?
fullScreenContentCallback,
) {
contentCallback = fullScreenContentCallback;
}
@override
ads.FullScreenContentCallback<ads.InterstitialAd>?
get fullScreenContentCallback => contentCallback;
}
class MockRewardedAd extends Mock implements ads.RewardedAd {}
class FakeRewardedAd extends Fake implements ads.RewardedAd {
ads.FullScreenContentCallback<ads.RewardedAd>? contentCallback;
bool disposeCalled = false;
@override
Future<void> show({
required ads.OnUserEarnedRewardCallback onUserEarnedReward,
}) async {}
@override
Future<void> dispose() async => disposeCalled = true;
@override
set fullScreenContentCallback(
ads.FullScreenContentCallback<ads.RewardedAd>? fullScreenContentCallback,
) {
contentCallback = fullScreenContentCallback;
}
@override
ads.FullScreenContentCallback<ads.RewardedAd>?
get fullScreenContentCallback => contentCallback;
}
class MockRewardItem extends Mock implements ads.RewardItem {}
class MockLoadAdError extends Mock implements ads.LoadAdError {}
class MockLocalPlatform extends Mock implements LocalPlatform {}
void main() {
group('FullScreenAdsBloc', () {
String? capturedAdUnitId;
late LocalPlatform localPlatform;
late ads.InterstitialAd interstitialAd;
late InterstitialAdLoader interstitialAdLoader;
late ads.RewardedAd rewardedAd;
late RewardedAdLoader rewardedAdLoader;
setUp(() {
localPlatform = MockLocalPlatform();
when(() => localPlatform.isAndroid).thenReturn(true);
when(() => localPlatform.isIOS).thenReturn(false);
interstitialAd = MockInterstitialAd();
when(interstitialAd.show).thenAnswer((_) async {});
when(interstitialAd.dispose).thenAnswer((_) async {});
interstitialAdLoader = ({
required String adUnitId,
required ads.InterstitialAdLoadCallback adLoadCallback,
required ads.AdRequest request,
}) async {
capturedAdUnitId = adUnitId;
};
rewardedAd = MockRewardedAd();
when(
() => rewardedAd.show(
onUserEarnedReward: any(named: 'onUserEarnedReward'),
),
).thenAnswer((_) async {});
when(rewardedAd.dispose).thenAnswer((_) async {});
rewardedAdLoader = ({
required String adUnitId,
required ads.RewardedAdLoadCallback rewardedAdLoadCallback,
required ads.AdRequest request,
}) async {
capturedAdUnitId = adUnitId;
};
});
group('LoadInterstitialAdRequested', () {
blocTest<FullScreenAdsBloc, FullScreenAdsState>(
'loads ad object correctly on Android',
build: () => FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
),
act: (bloc) => bloc.add(LoadInterstitialAdRequested()),
verify: (bloc) {
expect(
capturedAdUnitId,
equals(FullScreenAdsConfig.androidTestInterstitialAdUnitId),
);
},
);
blocTest<FullScreenAdsBloc, FullScreenAdsState>(
'loads ad object correctly on iOS',
setUp: () {
when(() => localPlatform.isIOS).thenReturn(true);
when(() => localPlatform.isAndroid).thenReturn(false);
},
build: () => FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
),
act: (bloc) => bloc.add(LoadInterstitialAdRequested()),
verify: (bloc) {
expect(
capturedAdUnitId,
equals(FullScreenAdsConfig.iosTestInterstitialAdUnitId),
);
},
);
blocTest<FullScreenAdsBloc, FullScreenAdsState>(
'loads ad object correctly using provided FullScreenAdsConfig',
setUp: () {
when(() => localPlatform.isIOS).thenReturn(true);
when(() => localPlatform.isAndroid).thenReturn(false);
},
build: () => FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
fullScreenAdsConfig:
FullScreenAdsConfig(interstitialAdUnitId: 'interstitialAdUnitId'),
),
act: (bloc) => bloc.add(LoadInterstitialAdRequested()),
verify: (bloc) {
expect(capturedAdUnitId, equals('interstitialAdUnitId'));
},
);
blocTest<FullScreenAdsBloc, FullScreenAdsState>(
'emits ad when ad is loaded',
setUp: () {
interstitialAdLoader = ({
required String adUnitId,
required ads.InterstitialAdLoadCallback adLoadCallback,
required ads.AdRequest request,
}) async {
await Future.microtask(
() => adLoadCallback.onAdLoaded(interstitialAd),
);
};
},
build: () => FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
),
act: (bloc) => bloc.add(LoadInterstitialAdRequested()),
expect: () => [
FullScreenAdsState(status: FullScreenAdsStatus.loadingInterstitialAd),
FullScreenAdsState(
status: FullScreenAdsStatus.loadingInterstitialAdSucceeded,
interstitialAd: interstitialAd,
),
],
);
blocTest<FullScreenAdsBloc, FullScreenAdsState>(
'adds error when ad fails to load',
setUp: () {
interstitialAdLoader = ({
required String adUnitId,
required ads.InterstitialAdLoadCallback adLoadCallback,
required ads.AdRequest request,
}) async {
await Future.microtask(
() => adLoadCallback.onAdFailedToLoad(
ads.LoadAdError(0, 'domain', 'message', null),
),
);
};
},
build: () => FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
),
act: (bloc) => bloc.add(LoadInterstitialAdRequested()),
expect: () => [
FullScreenAdsState(status: FullScreenAdsStatus.loadingInterstitialAd),
FullScreenAdsState(
status: FullScreenAdsStatus.loadingInterstitialAdFailed,
),
],
errors: () => [isA<ads.LoadAdError>()],
);
test('retries loading ad based on AdsRetryPolicy', () async {
final fakeAsync = FakeAsync();
unawaited(
fakeAsync.run((async) async {
final adsRetryPolicy = AdsRetryPolicy();
interstitialAdLoader = ({
required String adUnitId,
required ads.InterstitialAdLoadCallback adLoadCallback,
required ads.AdRequest request,
}) async {
await Future.microtask(
() => adLoadCallback.onAdFailedToLoad(
ads.LoadAdError(0, 'domain', 'message', null),
),
);
};
final bloc = FullScreenAdsBloc(
adsRetryPolicy: adsRetryPolicy,
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
)..add(LoadInterstitialAdRequested());
expect(
(await bloc.stream.first).status,
equals(FullScreenAdsStatus.loadingInterstitialAd),
);
expect(
(await bloc.stream.first).status,
equals(FullScreenAdsStatus.loadingInterstitialAdFailed),
);
for (var i = 1; i <= adsRetryPolicy.maxRetryCount; i++) {
expect(
bloc.stream,
emitsInOrder(
<FullScreenAdsState>[
FullScreenAdsState(
status: FullScreenAdsStatus.loadingInterstitialAd,
),
FullScreenAdsState(
status: FullScreenAdsStatus.loadingInterstitialAdFailed,
),
],
),
);
async.elapse(adsRetryPolicy.getIntervalForRetry(i));
}
}),
);
fakeAsync.flushMicrotasks();
});
});
group('ShowInterstitialAdRequested', () {
final ad = FakeInterstitialAd();
blocTest<FullScreenAdsBloc, FullScreenAdsState>(
'shows ad and loads next ad',
seed: () => FullScreenAdsState(
status: FullScreenAdsStatus.loadingInterstitialAdSucceeded,
interstitialAd: interstitialAd,
),
build: () => FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
),
act: (bloc) => bloc.add(ShowInterstitialAdRequested()),
expect: () => [
FullScreenAdsState(
status: FullScreenAdsStatus.showingInterstitialAd,
interstitialAd: interstitialAd,
),
FullScreenAdsState(
status: FullScreenAdsStatus.showingInterstitialAdSucceeded,
interstitialAd: interstitialAd,
),
FullScreenAdsState(
status: FullScreenAdsStatus.loadingInterstitialAd,
interstitialAd: interstitialAd,
),
],
verify: (bloc) {
verify(interstitialAd.show).called(1);
},
);
test('disposes ad on ad dismissed', () async {
final bloc = FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
)
..emit(
FullScreenAdsState(
status: FullScreenAdsStatus.loadingInterstitialAdSucceeded,
interstitialAd: ad,
),
)
..add(ShowInterstitialAdRequested());
await expectLater(
bloc.stream,
emitsInOrder(<FullScreenAdsState>[
FullScreenAdsState(
status: FullScreenAdsStatus.showingInterstitialAd,
interstitialAd: ad,
),
FullScreenAdsState(
status: FullScreenAdsStatus.showingInterstitialAdSucceeded,
interstitialAd: ad,
),
]),
);
ad.fullScreenContentCallback!.onAdDismissedFullScreenContent!(ad);
expect(ad.disposeCalled, isTrue);
});
test('disposes ad when ads fails to show', () async {
final bloc = FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
)
..emit(
FullScreenAdsState(
status: FullScreenAdsStatus.loadingInterstitialAdSucceeded,
interstitialAd: ad,
),
)
..add(ShowInterstitialAdRequested());
await expectLater(
bloc.stream,
emitsInOrder(<FullScreenAdsState>[
FullScreenAdsState(
status: FullScreenAdsStatus.showingInterstitialAd,
interstitialAd: ad,
),
FullScreenAdsState(
status: FullScreenAdsStatus.showingInterstitialAdSucceeded,
interstitialAd: ad,
),
]),
);
final error = MockLoadAdError();
ad.fullScreenContentCallback!.onAdFailedToShowFullScreenContent!(
ad,
error,
);
expect(ad.disposeCalled, isTrue);
});
blocTest<FullScreenAdsBloc, FullScreenAdsState>(
'adds error when ad fails to show',
seed: () => FullScreenAdsState(
status: FullScreenAdsStatus.loadingInterstitialAdSucceeded,
interstitialAd: interstitialAd,
),
setUp: () {
when(interstitialAd.show).thenThrow(Exception('Oops'));
},
build: () => FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
),
act: (bloc) => bloc.add(ShowInterstitialAdRequested()),
expect: () => [
FullScreenAdsState(
status: FullScreenAdsStatus.showingInterstitialAd,
interstitialAd: interstitialAd,
),
FullScreenAdsState(
status: FullScreenAdsStatus.showingInterstitialAdFailed,
interstitialAd: interstitialAd,
),
],
errors: () => [isA<Exception>()],
);
});
group('LoadRewardedAdRequested', () {
blocTest<FullScreenAdsBloc, FullScreenAdsState>(
'loads ad object correctly on Android',
build: () => FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
),
act: (bloc) => bloc.add(LoadRewardedAdRequested()),
verify: (bloc) {
expect(
capturedAdUnitId,
equals(FullScreenAdsConfig.androidTestRewardedAdUnitId),
);
},
);
blocTest<FullScreenAdsBloc, FullScreenAdsState>(
'loads ad object correctly on iOS',
setUp: () {
when(() => localPlatform.isIOS).thenReturn(true);
when(() => localPlatform.isAndroid).thenReturn(false);
},
build: () => FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
),
act: (bloc) => bloc.add(LoadRewardedAdRequested()),
verify: (bloc) {
expect(
capturedAdUnitId,
equals(FullScreenAdsConfig.iosTestRewardedAdUnitId),
);
},
);
blocTest<FullScreenAdsBloc, FullScreenAdsState>(
'loads ad object correctly using provided FullScreenAdsConfig',
setUp: () {
when(() => localPlatform.isIOS).thenReturn(true);
when(() => localPlatform.isAndroid).thenReturn(false);
},
build: () => FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
fullScreenAdsConfig:
FullScreenAdsConfig(rewardedAdUnitId: 'rewardedAdUnitId'),
),
act: (bloc) => bloc.add(LoadRewardedAdRequested()),
verify: (bloc) {
expect(capturedAdUnitId, equals('rewardedAdUnitId'));
},
);
blocTest<FullScreenAdsBloc, FullScreenAdsState>(
'emits ad when ad is loaded',
setUp: () {
rewardedAdLoader = ({
required String adUnitId,
required ads.RewardedAdLoadCallback rewardedAdLoadCallback,
required ads.AdRequest request,
}) async {
await Future.microtask(
() => rewardedAdLoadCallback.onAdLoaded(rewardedAd),
);
};
},
build: () => FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
),
act: (bloc) => bloc.add(LoadRewardedAdRequested()),
expect: () => [
FullScreenAdsState(status: FullScreenAdsStatus.loadingRewardedAd),
FullScreenAdsState(
status: FullScreenAdsStatus.loadingRewardedAdSucceeded,
rewardedAd: rewardedAd,
),
],
);
blocTest<FullScreenAdsBloc, FullScreenAdsState>(
'adds error when ad fails to load',
setUp: () {
rewardedAdLoader = ({
required String adUnitId,
required ads.RewardedAdLoadCallback rewardedAdLoadCallback,
required ads.AdRequest request,
}) async {
await Future.microtask(
() => rewardedAdLoadCallback.onAdFailedToLoad(
ads.LoadAdError(0, 'domain', 'message', null),
),
);
};
},
build: () => FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
),
act: (bloc) => bloc.add(LoadRewardedAdRequested()),
expect: () => [
FullScreenAdsState(status: FullScreenAdsStatus.loadingRewardedAd),
FullScreenAdsState(
status: FullScreenAdsStatus.loadingRewardedAdFailed,
),
],
errors: () => [isA<ads.LoadAdError>()],
);
test('retries loading ad based on AdsRetryPolicy', () async {
final fakeAsync = FakeAsync();
unawaited(
fakeAsync.run((async) async {
final adsRetryPolicy = AdsRetryPolicy();
rewardedAdLoader = ({
required String adUnitId,
required ads.RewardedAdLoadCallback rewardedAdLoadCallback,
required ads.AdRequest request,
}) async {
await Future.microtask(
() => rewardedAdLoadCallback.onAdFailedToLoad(
ads.LoadAdError(0, 'domain', 'message', null),
),
);
};
final bloc = FullScreenAdsBloc(
adsRetryPolicy: adsRetryPolicy,
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
)..add(LoadRewardedAdRequested());
expect(
(await bloc.stream.first).status,
equals(FullScreenAdsStatus.loadingRewardedAd),
);
expect(
(await bloc.stream.first).status,
equals(FullScreenAdsStatus.loadingRewardedAdFailed),
);
for (var i = 1; i <= adsRetryPolicy.maxRetryCount; i++) {
expect(
bloc.stream,
emitsInOrder(
<FullScreenAdsState>[
FullScreenAdsState(
status: FullScreenAdsStatus.loadingRewardedAd,
),
FullScreenAdsState(
status: FullScreenAdsStatus.loadingRewardedAdFailed,
),
],
),
);
async.elapse(adsRetryPolicy.getIntervalForRetry(i));
}
}),
);
fakeAsync.flushMicrotasks();
});
});
group('ShowRewardedAdRequested', () {
final ad = FakeRewardedAd();
final rewardItem = MockRewardItem();
blocTest<FullScreenAdsBloc, FullScreenAdsState>(
'shows ad and loads next ad',
seed: () => FullScreenAdsState(
status: FullScreenAdsStatus.loadingRewardedAdSucceeded,
rewardedAd: rewardedAd,
),
build: () => FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
),
act: (bloc) => bloc.add(ShowRewardedAdRequested()),
expect: () => [
FullScreenAdsState(
status: FullScreenAdsStatus.showingRewardedAd,
rewardedAd: rewardedAd,
),
FullScreenAdsState(
status: FullScreenAdsStatus.showingRewardedAdSucceeded,
rewardedAd: rewardedAd,
),
FullScreenAdsState(
status: FullScreenAdsStatus.loadingRewardedAd,
rewardedAd: rewardedAd,
),
],
verify: (bloc) {
verify(
() => rewardedAd.show(
onUserEarnedReward: any(named: 'onUserEarnedReward'),
),
).called(1);
},
);
blocTest<FullScreenAdsBloc, FullScreenAdsState>(
'emits earned reward when ad is watched',
seed: () => FullScreenAdsState(
status: FullScreenAdsStatus.loadingRewardedAdSucceeded,
rewardedAd: rewardedAd,
),
setUp: () {
when(
() => rewardedAd.show(
onUserEarnedReward: any(named: 'onUserEarnedReward'),
),
).thenAnswer((invocation) async {
(invocation.namedArguments[Symbol('onUserEarnedReward')]
as ads.OnUserEarnedRewardCallback)
.call(ad, rewardItem);
});
},
build: () => FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
),
act: (bloc) => bloc.add(ShowRewardedAdRequested()),
// Skip showingRewardedAd, showingRewardedAdSucceeded
// and loadingRewardedAd.
skip: 3,
expect: () => [
FullScreenAdsState(
status: FullScreenAdsStatus.loadingRewardedAd,
rewardedAd: rewardedAd,
earnedReward: rewardItem,
),
],
);
test('disposes ad on ad dismissed', () async {
final bloc = FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
)
..emit(
FullScreenAdsState(
status: FullScreenAdsStatus.loadingRewardedAdSucceeded,
rewardedAd: ad,
),
)
..add(ShowRewardedAdRequested());
await expectLater(
bloc.stream,
emitsInOrder(<FullScreenAdsState>[
FullScreenAdsState(
status: FullScreenAdsStatus.showingRewardedAd,
rewardedAd: ad,
),
FullScreenAdsState(
status: FullScreenAdsStatus.showingRewardedAdSucceeded,
rewardedAd: ad,
),
]),
);
ad.fullScreenContentCallback!.onAdDismissedFullScreenContent!(ad);
expect(ad.disposeCalled, isTrue);
});
test('disposes ad when ads fails to show', () async {
final bloc = FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
)
..emit(
FullScreenAdsState(
status: FullScreenAdsStatus.loadingRewardedAdSucceeded,
rewardedAd: ad,
),
)
..add(ShowRewardedAdRequested());
await expectLater(
bloc.stream,
emitsInOrder(<FullScreenAdsState>[
FullScreenAdsState(
status: FullScreenAdsStatus.showingRewardedAd,
rewardedAd: ad,
),
FullScreenAdsState(
status: FullScreenAdsStatus.showingRewardedAdSucceeded,
rewardedAd: ad,
),
]),
);
final error = MockLoadAdError();
ad.fullScreenContentCallback!.onAdFailedToShowFullScreenContent!(
ad,
error,
);
expect(ad.disposeCalled, isTrue);
});
blocTest<FullScreenAdsBloc, FullScreenAdsState>(
'adds error when ad fails to show',
seed: () => FullScreenAdsState(
status: FullScreenAdsStatus.loadingRewardedAdSucceeded,
rewardedAd: rewardedAd,
),
setUp: () {
when(
() => rewardedAd.show(
onUserEarnedReward: any(named: 'onUserEarnedReward'),
),
).thenThrow(Exception('Oops'));
},
build: () => FullScreenAdsBloc(
adsRetryPolicy: AdsRetryPolicy(),
localPlatform: localPlatform,
interstitialAdLoader: interstitialAdLoader,
rewardedAdLoader: rewardedAdLoader,
),
act: (bloc) => bloc.add(ShowRewardedAdRequested()),
expect: () => [
FullScreenAdsState(
status: FullScreenAdsStatus.showingRewardedAd,
rewardedAd: rewardedAd,
),
FullScreenAdsState(
status: FullScreenAdsStatus.showingRewardedAdFailed,
rewardedAd: rewardedAd,
),
],
errors: () => [isA<Exception>()],
);
});
});
}
| news_toolkit/flutter_news_example/test/ads/bloc/full_screen_ads_bloc_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/test/ads/bloc/full_screen_ads_bloc_test.dart', 'repo_id': 'news_toolkit', 'token_count': 12241} |
export 'fake_video_player_platform.dart';
| news_toolkit/flutter_news_example/test/article/helpers/helpers.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/test/article/helpers/helpers.dart', 'repo_id': 'news_toolkit', 'token_count': 14} |
// ignore_for_file: prefer_const_constructors
import 'dart:async';
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart' hide Spacer;
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/categories/categories.dart';
import 'package:flutter_news_example/feed/feed.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:news_blocks_ui/news_blocks_ui.dart';
import '../../helpers/helpers.dart';
class MockFeedBloc extends MockBloc<FeedEvent, FeedState> implements FeedBloc {}
class MockCategoriesBloc extends MockBloc<CategoriesEvent, CategoriesState>
implements CategoriesBloc {}
void main() {
group('FeedView', () {
late CategoriesBloc categoriesBloc;
late FeedBloc feedBloc;
const categories = [Category.top, Category.technology];
final feed = <Category, List<NewsBlock>>{
Category.top: [
SectionHeaderBlock(title: 'Top'),
SpacerBlock(spacing: Spacing.medium),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
DividerHorizontalBlock(),
],
Category.technology: [
SectionHeaderBlock(title: 'Technology'),
DividerHorizontalBlock(),
SpacerBlock(spacing: Spacing.medium),
],
};
setUp(() {
categoriesBloc = MockCategoriesBloc();
feedBloc = MockFeedBloc();
when(() => categoriesBloc.state).thenReturn(
CategoriesState(
categories: categories,
status: CategoriesStatus.populated,
),
);
when(() => feedBloc.state).thenReturn(
FeedState(
feed: feed,
status: FeedStatus.populated,
),
);
});
testWidgets(
'renders empty feed '
'when categories are empty', (tester) async {
when(() => categoriesBloc.state).thenReturn(
CategoriesState(
categories: const [],
status: CategoriesStatus.populated,
),
);
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(value: categoriesBloc),
BlocProvider.value(value: feedBloc),
],
child: FeedView(),
),
);
expect(find.byKey(Key('feedView_empty')), findsOneWidget);
expect(find.byType(FeedViewPopulated), findsNothing);
});
testWidgets(
'renders FeedViewPopulated '
'when categories are available', (tester) async {
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(value: categoriesBloc),
BlocProvider.value(value: feedBloc),
],
child: FeedView(),
),
);
expect(
find.byWidgetPredicate(
(widget) =>
widget is FeedViewPopulated && widget.categories == categories,
),
findsOneWidget,
);
expect(find.byKey(Key('feedView_empty')), findsNothing);
});
testWidgets(
'adds FeedResumed when the app is resumed',
(tester) async {
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(value: categoriesBloc),
BlocProvider.value(value: feedBloc),
],
child: FeedView(),
),
);
tester.binding.handleAppLifecycleStateChanged(
AppLifecycleState.resumed,
);
verify(
() => feedBloc.add(FeedResumed()),
).called(1);
},
);
group('FeedViewPopulated', () {
testWidgets('renders CategoryTabBar with CategoryTab for each category',
(tester) async {
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(value: categoriesBloc),
BlocProvider.value(value: feedBloc),
],
child: FeedViewPopulated(categories: categories),
),
);
expect(find.byType(CategoriesTabBar), findsOneWidget);
for (final category in categories) {
expect(
find.descendant(
of: find.byType(CategoriesTabBar),
matching: find.byWidgetPredicate(
(widget) =>
widget is CategoryTab &&
widget.categoryName == category.name,
),
),
findsOneWidget,
);
}
});
testWidgets('renders TabBarView', (tester) async {
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(value: categoriesBloc),
BlocProvider.value(value: feedBloc),
],
child: FeedViewPopulated(categories: categories),
),
);
expect(find.byType(TabBarView), findsOneWidget);
expect(find.byType(CategoryFeed), findsOneWidget);
});
testWidgets(
'adds CategorySelected to CategoriesBloc '
'when CategoryTab is tapped', (tester) async {
final selectedCategory = categories[1];
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(value: categoriesBloc),
BlocProvider.value(value: feedBloc),
],
child: FeedViewPopulated(categories: categories),
),
);
final categoryTab = find.byWidgetPredicate(
(widget) =>
widget is CategoryTab &&
widget.categoryName == selectedCategory.name,
);
await tester.ensureVisible(categoryTab);
await tester.tap(categoryTab);
await tester.pump(kTabScrollDuration);
verify(
() => categoriesBloc.add(
CategorySelected(category: selectedCategory),
),
).called(1);
});
testWidgets(
'animates to CategoryFeed in TabBarView '
'when selectedCategory changes', (tester) async {
final categoriesStateController =
StreamController<CategoriesState>.broadcast();
final categoriesState = CategoriesState(
categories: categories,
status: CategoriesStatus.populated,
);
whenListen(
categoriesBloc,
categoriesStateController.stream,
initialState: categoriesState,
);
final defaultCategory = categories.first;
final selectedCategory = categories[1];
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(value: categoriesBloc),
BlocProvider.value(value: feedBloc),
],
child: FeedViewPopulated(categories: categories),
),
);
Finder findCategoryFeed(Category category) => find.byWidgetPredicate(
(widget) => widget is CategoryFeed && widget.category == category,
);
expect(findCategoryFeed(defaultCategory), findsOneWidget);
expect(findCategoryFeed(selectedCategory), findsNothing);
categoriesStateController.add(
categoriesState.copyWith(selectedCategory: selectedCategory),
);
await tester.pump(kTabScrollDuration);
await tester.pump(kTabScrollDuration);
expect(findCategoryFeed(defaultCategory), findsNothing);
expect(findCategoryFeed(selectedCategory), findsOneWidget);
});
testWidgets(
'scrolls to the top of CategoryFeed on double tap on CategoryTab',
(tester) async {
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(value: categoriesBloc),
BlocProvider.value(value: feedBloc),
],
child: FeedViewPopulated(categories: categories),
),
);
expect(
find.byType(DividerHorizontal),
findsNothing,
);
expect(
find.text('Top'),
findsOneWidget,
);
await tester.dragUntilVisible(
find.byType(DividerHorizontal),
find.byType(FeedViewPopulated),
Offset(0, -100),
duration: Duration.zero,
);
expect(
find.byType(DividerHorizontal),
findsOneWidget,
);
final tab = find.widgetWithText(
CategoryTab,
categories.first.name.toUpperCase(),
);
await tester.tap(tab);
await tester.pump(kDoubleTapMinTime);
await tester.tap(tab);
await tester.pump(Duration(milliseconds: 300));
await tester.pump(Duration(milliseconds: 300));
expect(
find.byType(DividerHorizontal),
findsNothing,
);
expect(
find.text('Top'),
findsOneWidget,
);
},
);
});
});
}
| news_toolkit/flutter_news_example/test/feed/view/feed_view_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/test/feed/view/feed_view_test.dart', 'repo_id': 'news_toolkit', 'token_count': 4430} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_news_example/login/login.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('LoginWithEmailLinkEvent', () {
group('LoginWithEmailLinkSubmitted', () {
test('supports value comparisons', () {
final emailLink = Uri.https('example.com');
expect(
LoginWithEmailLinkSubmitted(emailLink),
LoginWithEmailLinkSubmitted(emailLink),
);
});
});
});
}
| news_toolkit/flutter_news_example/test/login/bloc/login_with_email_link_event_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/test/login/bloc/login_with_email_link_event_test.dart', 'repo_id': 'news_toolkit', 'token_count': 196} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_news_example/newsletter/newsletter.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('NewsletterEvent', () {
const testEmail = 'test@test.com';
group('EmailChanged', () {
test('supports value comparisons', () {
expect(
EmailChanged(email: testEmail),
EmailChanged(email: testEmail),
);
expect(
EmailChanged(email: ''),
isNot(EmailChanged(email: testEmail)),
);
});
});
group('NewsletterSubscribed', () {
test('supports value comparisons', () {
expect(NewsletterSubscribed(), NewsletterSubscribed());
});
});
});
}
| news_toolkit/flutter_news_example/test/newsletter/bloc/newsletter_event_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/test/newsletter/bloc/newsletter_event_test.dart', 'repo_id': 'news_toolkit', 'token_count': 295} |
// ignore_for_file: prefer_const_constructors
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/feed/feed.dart';
import 'package:flutter_news_example/search/search.dart';
import 'package:flutter_news_example_api/client.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import '../../helpers/helpers.dart';
class MockSearchBloc extends MockBloc<SearchEvent, SearchState>
implements SearchBloc {}
void main() {
late SearchBloc searchBloc;
setUp(() async {
searchBloc = MockSearchBloc();
when(() => searchBloc.state).thenReturn(
const SearchState(
articles: [DividerHorizontalBlock()],
searchType: SearchType.popular,
status: SearchStatus.initial,
topics: ['topic'],
),
);
});
group('SearchPage', () {
testWidgets('renders SearchView', (tester) async {
await tester.pumpApp(const SearchPage());
expect(find.byType(SearchView), findsOneWidget);
});
});
group('SearchView', () {
testWidgets('renders filter chips', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: searchBloc,
child: const SearchView(),
),
);
await tester.pump();
expect(find.byKey(Key('searchFilterChip_topic')), findsOneWidget);
});
testWidgets(
'when SearchFilterChip clicked adds SearchTermChanged to SearchBloc',
(tester) async {
await tester.pumpApp(
BlocProvider.value(
value: searchBloc,
child: const SearchView(),
),
);
await tester.tap(find.byKey(Key('searchFilterChip_topic')));
verify(() => searchBloc.add(SearchTermChanged(searchTerm: 'topic')))
.called(1);
});
testWidgets('renders articles', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: searchBloc,
child: const SearchView(),
),
);
expect(find.byType(CategoryFeedItem), findsOneWidget);
});
testWidgets('in SearchType.relevant renders two headline titles',
(tester) async {
when(() => searchBloc.state).thenReturn(
const SearchState(
articles: [],
searchType: SearchType.relevant,
status: SearchStatus.initial,
topics: [],
),
);
await tester.pumpApp(
BlocProvider.value(
value: searchBloc,
child: const SearchView(),
),
);
expect(find.byType(SearchHeadlineText), findsNWidgets(2));
});
testWidgets(
'when SearchTextField changes to non-empty value '
'adds SearchTermChanged to SearchBloc', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: searchBloc,
child: const SearchView(),
),
);
await tester.enterText(
find.byKey(Key('searchPage_searchTextField')),
'test',
);
verify(() => searchBloc.add(SearchTermChanged(searchTerm: 'test')))
.called(1);
});
testWidgets(
'when SearchTextField changes to an empty value '
'adds empty SearchTermChanged to SearchBloc', (tester) async {
when(() => searchBloc.state).thenReturn(
const SearchState(
articles: [],
searchType: SearchType.relevant,
status: SearchStatus.initial,
topics: [],
),
);
await tester.pumpApp(
BlocProvider.value(
value: searchBloc,
child: const SearchView(),
),
);
await tester.enterText(
find.byKey(Key('searchPage_searchTextField')),
'',
);
verify(() => searchBloc.add(SearchTermChanged())).called(1);
});
testWidgets('shows snackbar when SearchBloc SearchStatus is failure',
(tester) async {
final expectedStates = [
SearchState.initial(),
SearchState.initial().copyWith(
status: SearchStatus.failure,
),
];
whenListen(searchBloc, Stream.fromIterable(expectedStates));
await tester.pumpApp(
BlocProvider.value(
value: searchBloc,
child: const SearchView(),
),
);
expect(find.byType(SnackBar), findsOneWidget);
});
});
}
| news_toolkit/flutter_news_example/test/search/view/search_page_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/test/search/view/search_page_test.dart', 'repo_id': 'news_toolkit', 'token_count': 1923} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_news_example/terms_of_service/terms_of_service.dart';
import 'package:flutter_test/flutter_test.dart';
import '../../helpers/helpers.dart';
void main() {
const termsOfServiceBodyTextKey = Key('termsOfServiceBody_text');
group('TermsOfServiceBody', () {
group('renders', () {
testWidgets('SingleChildScrollView', (tester) async {
await tester.pumpApp(
Column(
children: const [
TermsOfServiceBody(),
],
),
);
expect(find.byType(SingleChildScrollView), findsOneWidget);
});
testWidgets('terms of service body text', (tester) async {
await tester.pumpApp(
Column(
children: const [
TermsOfServiceBody(),
],
),
);
expect(find.byKey(termsOfServiceBodyTextKey), findsOneWidget);
});
});
});
}
| news_toolkit/flutter_news_example/test/terms_of_service/widgets/terms_of_service_body_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/test/terms_of_service/widgets/terms_of_service_body_test.dart', 'repo_id': 'news_toolkit', 'token_count': 447} |
name: ocarina_example
description: Demonstrates how to use the ocarina plugin.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
path_provider: ^2.0.2
http: ^0.13.3
ocarina:
path: ../
cupertino_icons: ^1.0.3
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter_driver:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/Loop-Menu.wav
| ocarina/example/pubspec.yaml/0 | {'file_path': 'ocarina/example/pubspec.yaml', 'repo_id': 'ocarina', 'token_count': 224} |
// ignore_for_file: depend_on_referenced_packages
import 'package:test/test.dart';
import 'utils.dart';
void main() {
group('Utils', () {
group('calculateNewVersion', () {
test('works', () {
expect(calculateNewVersion('0.1.2', VersionBumpType.major), '1.0.0+1');
expect(calculateNewVersion('0.1.2+1', VersionBumpType.major), '1.0.0+1');
expect(calculateNewVersion('1.1.2', VersionBumpType.major), '2.0.0+1');
expect(calculateNewVersion('0.1.2', VersionBumpType.minor), '0.2.0+1');
expect(calculateNewVersion('0.0.1', VersionBumpType.minor), '0.1.0+1');
expect(calculateNewVersion('1.0.2', VersionBumpType.minor), '1.1.0+1');
expect(calculateNewVersion('0.1.2', VersionBumpType.patch), '0.1.3+1');
expect(calculateNewVersion('1.0.1', VersionBumpType.patch), '1.0.2+1');
expect(calculateNewVersion('0.1.0', VersionBumpType.patch), '0.1.1+1');
expect(calculateNewVersion('0.0.0', VersionBumpType.build), '0.0.0+1');
expect(calculateNewVersion('0.1.0+1', VersionBumpType.build), '0.1.0+2');
});
});
group('VersionBumpType', () {
test('works', () {
expect(VersionBumpType.fromName(null), VersionBumpType.patch);
expect(VersionBumpType.fromName('unknown'), VersionBumpType.patch);
expect(VersionBumpType.fromName('build'), VersionBumpType.build);
expect(VersionBumpType.fromName('patch'), VersionBumpType.patch);
expect(VersionBumpType.fromName('minor'), VersionBumpType.minor);
expect(VersionBumpType.fromName('major'), VersionBumpType.major);
});
});
});
}
| ovavue/bin/utils_test.dart/0 | {'file_path': 'ovavue/bin/utils_test.dart', 'repo_id': 'ovavue', 'token_count': 723} |
import 'analytics_event.dart';
abstract class Analytics {
Future<void> setUserId(String id);
Future<void> removeUserId();
Future<void> log(AnalyticsEvent event);
Future<void> setCurrentScreen(String name);
}
| ovavue/lib/domain/analytics/analytics.dart/0 | {'file_path': 'ovavue/lib/domain/analytics/analytics.dart', 'repo_id': 'ovavue', 'token_count': 69} |
typedef ReferenceEntity = ({String id, String path});
| ovavue/lib/domain/entities/reference_entity.dart/0 | {'file_path': 'ovavue/lib/domain/entities/reference_entity.dart', 'repo_id': 'ovavue', 'token_count': 14} |
import '../analytics/analytics.dart';
import '../analytics/analytics_event.dart';
import '../entities/reference_entity.dart';
import '../repositories/budget_metadata.dart';
class AddMetadataToPlanUseCase {
const AddMetadataToPlanUseCase({
required BudgetMetadataRepository metadata,
required Analytics analytics,
}) : _metadata = metadata,
_analytics = analytics;
final BudgetMetadataRepository _metadata;
final Analytics _analytics;
Future<bool> call({
required String userId,
required ReferenceEntity plan,
required ReferenceEntity metadata,
}) {
_analytics.log(AnalyticsEvent.addMetadataToPlan(metadata.path)).ignore();
return _metadata.addMetadataToPlan(userId: userId, plan: plan, metadata: metadata);
}
}
| ovavue/lib/domain/use_cases/add_metadata_to_plan_use_case.dart/0 | {'file_path': 'ovavue/lib/domain/use_cases/add_metadata_to_plan_use_case.dart', 'repo_id': 'ovavue', 'token_count': 241} |
import '../entities/budget_metadata_value_entity.dart';
import '../repositories/budget_metadata.dart';
class FetchBudgetMetadataByPlanUseCase {
const FetchBudgetMetadataByPlanUseCase({
required BudgetMetadataRepository metadata,
}) : _metadata = metadata;
final BudgetMetadataRepository _metadata;
Stream<BudgetMetadataValueEntityList> call({
required String userId,
required String planId,
}) =>
_metadata.fetchAllByPlan(userId: userId, planId: planId);
}
| ovavue/lib/domain/use_cases/fetch_budget_metadata_by_plan_use_case.dart/0 | {'file_path': 'ovavue/lib/domain/use_cases/fetch_budget_metadata_by_plan_use_case.dart', 'repo_id': 'ovavue', 'token_count': 159} |
import 'package:flutter/material.dart';
import '../theme.dart';
class AppIcon extends StatelessWidget {
const AppIcon({super.key, this.heroTag, this.size = const Size.square(56), this.backgroundColor});
final Size size;
final String? heroTag;
final Color? backgroundColor;
@override
Widget build(BuildContext context) => Hero(
tag: heroTag ?? 'TheAmazingAppIcon',
child: Container(
constraints: BoxConstraints.tight(size),
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: backgroundColor ?? context.theme.colorScheme.onBackground,
borderRadius: BorderRadius.circular(size.shortestSide / 4),
),
child: const FlutterLogo(), // TODO(Jogboms): fix icon
),
);
}
| ovavue/lib/presentation/widgets/app_icon.dart/0 | {'file_path': 'ovavue/lib/presentation/widgets/app_icon.dart', 'repo_id': 'ovavue', 'token_count': 310} |
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:ovavue/data.dart';
import 'package:ovavue/domain.dart';
import '../../utils.dart';
void main() {
group('FetchAccountUseCase', () {
final FetchAccountUseCase useCase = FetchAccountUseCase(auth: mockRepositories.auth);
final AccountEntity dummyAccount = AuthMockImpl.generateAccount();
tearDown(mockRepositories.reset);
test('should fetch auth', () {
when(mockRepositories.auth.fetch).thenAnswer((_) async => dummyAccount);
expect(useCase(), completion(dummyAccount));
});
test('should bubble fetch errors', () {
when(mockRepositories.auth.fetch).thenThrow(Exception('an error'));
// ignore: unnecessary_lambdas, causes the test to fail
expect(() => useCase(), throwsException);
});
});
}
| ovavue/test/domain/use_cases/fetch_account_use_case_test.dart/0 | {'file_path': 'ovavue/test/domain/use_cases/fetch_account_use_case_test.dart', 'repo_id': 'ovavue', 'token_count': 299} |
import 'package:oxygen/oxygen.dart';
enum Direction {
up,
down,
left,
right,
}
class DirectionComponent extends ValueComponent<Direction> {}
| oxygen/example/lib/components/direction_component.dart/0 | {'file_path': 'oxygen/example/lib/components/direction_component.dart', 'repo_id': 'oxygen', 'token_count': 50} |
tasks:
- name: prepare tool
script: .ci/scripts/prepare_tool.sh
infra_step: true # Note infra steps failing prevents "always" from running.
- name: create all_packages app
script: .ci/scripts/create_all_packages_app.sh
infra_step: true # Note infra steps failing prevents "always" from running.
- name: build all_packages for iOS debug
script: .ci/scripts/build_all_packages_app.sh
args: ["ios", "debug", "--no-codesign"]
- name: build all_packages for iOS release
script: .ci/scripts/build_all_packages_app.sh
args: ["ios", "release", "--no-codesign"]
| packages/.ci/targets/ios_build_all_packages.yaml/0 | {'file_path': 'packages/.ci/targets/ios_build_all_packages.yaml', 'repo_id': 'packages', 'token_count': 206} |
'p: animations':
- changed-files:
- any-glob-to-any-file:
- packages/animations/**/*
'p: camera':
- changed-files:
- any-glob-to-any-file:
- packages/camera/**/*
'p: cross_file':
- changed-files:
- any-glob-to-any-file:
- packages/cross_file/**/*
'p: css_colors':
- changed-files:
- any-glob-to-any-file:
- packages/css_colors/**/*
'p: cupertino_icons':
- changed-files:
- any-glob-to-any-file:
- third_party/packages/cupertino_icons/**/*
'p: dynamic_layouts':
- changed-files:
- any-glob-to-any-file:
- packages/dynamic_layouts/**/*
'p: espresso':
- changed-files:
- any-glob-to-any-file:
- packages/espresso/**/*
'p: extension_google_sign_in_as_googleapis_auth':
- changed-files:
- any-glob-to-any-file:
- packages/extension_google_sign_in_as_googleapis_auth/**/*
'p: file_selector':
- changed-files:
- any-glob-to-any-file:
- packages/file_selector/**/*
'p: flutter_adaptive_scaffold':
- changed-files:
- any-glob-to-any-file:
- packages/flutter_adaptive_scaffold/**/*
'p: flutter_image':
- changed-files:
- any-glob-to-any-file:
- packages/flutter_image/**/*
'p: flutter_lints':
- changed-files:
- any-glob-to-any-file:
- packages/flutter_lints/**/*
'p: flutter_markdown':
- changed-files:
- any-glob-to-any-file:
- packages/flutter_markdown/**/*
'p: flutter_migrate':
- changed-files:
- any-glob-to-any-file:
- packages/flutter_migrate/**/*
'p: flutter_plugin_android_lifecycle':
- changed-files:
- any-glob-to-any-file:
- packages/flutter_plugin_android_lifecycle/**/*
'p: flutter_template_images':
- changed-files:
- any-glob-to-any-file:
- packages/flutter_template_images/**/*
'p: go_router':
- changed-files:
- any-glob-to-any-file:
- packages/go_router/**/*
'p: go_router_builder':
- changed-files:
- any-glob-to-any-file:
- packages/go_router_builder/**/*
'p: google_identity_services':
- changed-files:
- any-glob-to-any-file:
- packages/google_indentity_services_web/**
'p: google_maps_flutter':
- changed-files:
- any-glob-to-any-file:
- packages/google_maps_flutter/**/*
'p: google_sign_in':
- changed-files:
- any-glob-to-any-file:
- packages/google_sign_in/**/*
'p: image_picker':
- changed-files:
- any-glob-to-any-file:
- packages/image_picker/**/*
'p: in_app_purchase':
- changed-files:
- any-glob-to-any-file:
- packages/in_app_purchase/**/*
'p: ios_platform_images':
- changed-files:
- any-glob-to-any-file:
- packages/ios_platform_images/**/*
'p: local_auth':
- changed-files:
- any-glob-to-any-file:
- packages/local_auth/**/*
'p: metrics_center':
- changed-files:
- any-glob-to-any-file:
- packages/metrics_center/**/*
'p: multicast_dns':
- changed-files:
- any-glob-to-any-file:
- packages/multicast_dns/**/*
'p: palette_generator':
- changed-files:
- any-glob-to-any-file:
- packages/palette_generator/**/*
'p: path_provider':
- changed-files:
- any-glob-to-any-file:
- packages/path_provider/**/*
'p: pigeon':
- changed-files:
- any-glob-to-any-file:
- packages/pigeon/**/*
'p: plugin_platform_interface':
- changed-files:
- any-glob-to-any-file:
- packages/plugin_platform_interface/**/*
'p: pointer_interceptor':
- changed-files:
- any-glob-to-any-file:
- packages/pointer_interceptor/**/*
'p: quick_actions':
- changed-files:
- any-glob-to-any-file:
- packages/quick_actions/**/*
'p: rfw':
- changed-files:
- any-glob-to-any-file:
- packages/rfw/**/*
'p: shared_preferences':
- changed-files:
- any-glob-to-any-file:
- packages/shared_preferences/**/*
'p: standard_message_codec':
- changed-files:
- any-glob-to-any-file:
- packages/standard_message_codec/**/*
'p: url_launcher':
- changed-files:
- any-glob-to-any-file:
- packages/url_launcher/**/*
'p: video_player':
- changed-files:
- any-glob-to-any-file:
- packages/video_player/**/*
'p: web_benchmarks':
- changed-files:
- any-glob-to-any-file:
- packages/web_benchmarks/**/*
'p: webview_flutter':
- changed-files:
- any-glob-to-any-file:
- packages/webview_flutter/**/*
'p: xdg_directories':
- changed-files:
- any-glob-to-any-file:
- packages/xdg_directories/**/*
'platform-android':
- changed-files:
- any-glob-to-any-file:
- packages/*/*_android/**/*
- packages/**/android/**/*
'platform-ios':
- changed-files:
- any-glob-to-any-file:
- packages/*/*_avfoundation/**/*
- packages/*/*_darwin/**/*
- packages/*/*_foundation/**/*
- packages/*/*_ios/**/*
- packages/*/*_storekit/**/*
- packages/*/*_wkwebview/**/*
- packages/**/darwin/**/*
- packages/**/ios/**/*
'platform-linux':
- changed-files:
- any-glob-to-any-file:
- packages/*/*_linux/**/*
- packages/**/linux/**/*
'platform-macos':
- changed-files:
- any-glob-to-any-file:
- packages/*/*_avfoundation/**/*
- packages/*/*_darwin/**/*
- packages/*/*_foundation/**/*
- packages/*/*_macos/**/*
- packages/*/*_storekit/**/*
- packages/**/darwin/**/*
- packages/**/macos/**/*
'platform-web':
- changed-files:
- any-glob-to-any-file:
- packages/*/*_web/**/*
- packages/**/web/**/*
'platform-windows':
- changed-files:
- any-glob-to-any-file:
- packages/*/*_windows/**/*
- packages/**/windows/**/*
| packages/.github/labeler.yml/0 | {'file_path': 'packages/.github/labeler.yml', 'repo_id': 'packages', 'token_count': 2541} |
// Copyright 2013 The Flutter Authors. 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 'modal.dart';
/// The modal transition configuration for a Material fade transition.
///
/// The fade pattern is used for UI elements that enter or exit from within
/// the screen bounds. Elements that enter use a quick fade in and scale from
/// 80% to 100%. Elements that exit simply fade out. The scale animation is
/// only applied to entering elements to emphasize new content over old.
///
/// ```dart
/// /// Sample widget that uses [showModal] with [FadeScaleTransitionConfiguration].
/// class MyHomePage extends StatelessWidget {
/// @override
/// Widget build(BuildContext context) {
/// return Scaffold(
/// body: Center(
/// child: ElevatedButton(
/// onPressed: () {
/// showModal(
/// context: context,
/// configuration: FadeScaleTransitionConfiguration(),
/// builder: (BuildContext context) {
/// return _CenteredFlutterLogo();
/// },
/// );
/// },
/// child: Icon(Icons.add),
/// ),
/// ),
/// );
/// }
/// }
///
/// /// Displays a centered Flutter logo with size constraints.
/// class _CenteredFlutterLogo extends StatelessWidget {
/// const _CenteredFlutterLogo();
///
/// @override
/// Widget build(BuildContext context) {
/// return Center(
/// child: SizedBox(
/// width: 250,
/// height: 250,
/// child: const Material(
/// child: Center(
/// child: FlutterLogo(size: 250),
/// ),
/// ),
/// ),
/// );
/// }
/// }
/// ```
class FadeScaleTransitionConfiguration extends ModalConfiguration {
/// Creates the Material fade transition configuration.
///
/// [barrierDismissible] configures whether or not tapping the modal's
/// scrim dismisses the modal. [barrierLabel] sets the semantic label for
/// a dismissible barrier. [barrierDismissible] cannot be null. If
/// [barrierDismissible] is true, the [barrierLabel] cannot be null.
const FadeScaleTransitionConfiguration({
super.barrierColor = Colors.black54,
super.barrierDismissible = true,
super.transitionDuration = const Duration(milliseconds: 150),
super.reverseTransitionDuration = const Duration(milliseconds: 75),
String super.barrierLabel = 'Dismiss',
});
@override
Widget transitionBuilder(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
return FadeScaleTransition(
animation: animation,
child: child,
);
}
}
/// A widget that implements the Material fade transition.
///
/// The fade pattern is used for UI elements that enter or exit from within
/// the screen bounds. Elements that enter use a quick fade in and scale from
/// 80% to 100%. Elements that exit simply fade out. The scale animation is
/// only applied to entering elements to emphasize new content over old.
///
/// This widget is not to be confused with Flutter's [FadeTransition] widget,
/// which animates only the opacity of its child widget.
class FadeScaleTransition extends StatelessWidget {
/// Creates a widget that implements the Material fade transition.
///
/// The fade pattern is used for UI elements that enter or exit from within
/// the screen bounds. Elements that enter use a quick fade in and scale from
/// 80% to 100%. Elements that exit simply fade out. The scale animation is
/// only applied to entering elements to emphasize new content over old.
///
/// This widget is not to be confused with Flutter's [FadeTransition] widget,
/// which animates only the opacity of its child widget.
///
/// [animation] is typically an [AnimationController] that drives the transition
/// animation. [animation] cannot be null.
const FadeScaleTransition({
super.key,
required this.animation,
this.child,
});
/// The animation that drives the [child]'s entrance and exit.
///
/// See also:
///
/// * [TransitionRoute.animate], which is the value given to this property
/// when it is used as a page transition.
final Animation<double> animation;
/// The widget below this widget in the tree.
///
/// This widget will transition in and out as driven by [animation] and
/// [secondaryAnimation].
final Widget? child;
static final Animatable<double> _fadeInTransition = CurveTween(
curve: const Interval(0.0, 0.3),
);
static final Animatable<double> _scaleInTransition = Tween<double>(
begin: 0.80,
end: 1.00,
).chain(CurveTween(curve: Easing.legacyDecelerate));
static final Animatable<double> _fadeOutTransition = Tween<double>(
begin: 1.0,
end: 0.0,
);
@override
Widget build(BuildContext context) {
return DualTransitionBuilder(
animation: animation,
forwardBuilder: (
BuildContext context,
Animation<double> animation,
Widget? child,
) {
return FadeTransition(
opacity: _fadeInTransition.animate(animation),
child: ScaleTransition(
scale: _scaleInTransition.animate(animation),
child: child,
),
);
},
reverseBuilder: (
BuildContext context,
Animation<double> animation,
Widget? child,
) {
return FadeTransition(
opacity: _fadeOutTransition.animate(animation),
child: child,
);
},
child: child,
);
}
}
| packages/packages/animations/lib/src/fade_scale_transition.dart/0 | {'file_path': 'packages/packages/animations/lib/src/fade_scale_transition.dart', 'repo_id': 'packages', 'token_count': 1959} |
// Copyright 2013 The Flutter Authors. 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/services.dart' show BinaryMessenger;
import 'package:meta/meta.dart' show immutable;
import 'android_camera_camerax_flutter_api_impls.dart';
import 'camera_control.dart';
import 'camera_info.dart';
import 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
/// The interface used to control the flow of data of use cases, control the
/// camera, and publich the state of the camera.
///
/// See https://developer.android.com/reference/androidx/camera/core/Camera.
@immutable
class Camera extends JavaObject {
/// Constructs a [Camera] that is not automatically attached to a native object.
Camera.detached(
{BinaryMessenger? binaryMessenger, InstanceManager? instanceManager})
: super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager) {
_api = _CameraHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
}
late final _CameraHostApiImpl _api;
/// Retrieves the [CameraInfo] instance that contains information about this
/// instance.
Future<CameraInfo> getCameraInfo() async {
return _api.getCameraInfoFromInstance(this);
}
/// Retrieves the [CameraControl] instance that provides asynchronous
/// operations like zoom and focus & metering for this instance.
Future<CameraControl> getCameraControl() async {
return _api.getCameraControlFromInstance(this);
}
}
/// Host API implementation of [Camera].
class _CameraHostApiImpl extends CameraHostApi {
/// Constructs a [_CameraHostApiImpl].
///
/// An [instanceManager] is typically passed when a copy of an instance
/// contained by an [InstanceManager] is being created.
_CameraHostApiImpl({this.binaryMessenger, InstanceManager? instanceManager})
: super(binaryMessenger: binaryMessenger) {
this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
}
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
late final InstanceManager instanceManager;
/// Gets the [CameraInfo] associated with the specified [Camera] instance.
Future<CameraInfo> getCameraInfoFromInstance(Camera instance) async {
final int identifier = instanceManager.getIdentifier(instance)!;
final int cameraInfoId = await getCameraInfo(identifier);
return instanceManager
.getInstanceWithWeakReference<CameraInfo>(cameraInfoId)!;
}
/// Gets the [CameraControl] associated with the specified [Camera] instance.
Future<CameraControl> getCameraControlFromInstance(Camera instance) async {
final int identifier = instanceManager.getIdentifier(instance)!;
final int cameraControlId = await getCameraControl(identifier);
return instanceManager
.getInstanceWithWeakReference<CameraControl>(cameraControlId)!;
}
}
/// Flutter API implementation of [Camera].
class CameraFlutterApiImpl implements CameraFlutterApi {
/// Constructs a [CameraFlutterApiImpl].
///
/// If [binaryMessenger] is null, the default [BinaryMessenger] will be used,
/// which routes to the host platform.
///
/// An [instanceManager] is typically passed when a copy of an instance
/// contained by an [InstanceManager] is being created. If left null, it
/// will default to the global instance defined in [JavaObject].
CameraFlutterApiImpl({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) : _binaryMessenger = binaryMessenger,
_instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
/// Receives binary data across the Flutter platform barrier.
final BinaryMessenger? _binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager _instanceManager;
@override
void create(int identifier) {
_instanceManager.addHostCreatedInstance(
Camera.detached(
binaryMessenger: _binaryMessenger, instanceManager: _instanceManager),
identifier,
onCopy: (Camera original) {
return Camera.detached(
binaryMessenger: _binaryMessenger,
instanceManager: _instanceManager);
},
);
}
}
| packages/packages/camera/camera_android_camerax/lib/src/camera.dart/0 | {'file_path': 'packages/packages/camera/camera_android_camerax/lib/src/camera.dart', 'repo_id': 'packages', 'token_count': 1341} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Maintains instances used to communicate with the native objects they
/// represent.
///
/// Added instances are stored as weak references and their copies are stored
/// as strong references to maintain access to their variables and callback
/// methods. Both are stored with the same identifier.
///
/// When a weak referenced instance becomes inaccessible,
/// [onWeakReferenceRemoved] is called with its associated identifier.
///
/// If an instance is retrieved and has the possibility to be used,
/// (e.g. calling [getInstanceWithWeakReference]) a copy of the strong reference
/// is added as a weak reference with the same identifier. This prevents a
/// scenario where the weak referenced instance was released and then later
/// returned by the host platform.
class InstanceManager {
/// Constructs an [InstanceManager].
InstanceManager({required void Function(int) onWeakReferenceRemoved}) {
this.onWeakReferenceRemoved = (int identifier) {
_weakInstances.remove(identifier);
onWeakReferenceRemoved(identifier);
};
_finalizer = Finalizer<int>(this.onWeakReferenceRemoved);
}
// Identifiers are locked to a specific range to avoid collisions with objects
// created simultaneously by the host platform.
// Host uses identifiers >= 2^16 and Dart is expected to use values n where,
// 0 <= n < 2^16.
static const int _maxDartCreatedIdentifier = 65536;
// Expando is used because it doesn't prevent its keys from becoming
// inaccessible. This allows the manager to efficiently retrieve an identifier
// of an instance without holding a strong reference to that instance.
//
// It also doesn't use `==` to search for identifiers, which would lead to an
// infinite loop when comparing an object to its copy. (i.e. which was caused
// by calling instanceManager.getIdentifier() inside of `==` while this was a
// HashMap).
final Expando<int> _identifiers = Expando<int>();
final Map<int, WeakReference<Object>> _weakInstances =
<int, WeakReference<Object>>{};
final Map<int, Object> _strongInstances = <int, Object>{};
final Map<int, Function> _copyCallbacks = <int, Function>{};
late final Finalizer<int> _finalizer;
int _nextIdentifier = 0;
/// Called when a weak referenced instance is removed by [removeWeakReference]
/// or becomes inaccessible.
late final void Function(int) onWeakReferenceRemoved;
/// Adds a new instance that was instantiated by Dart.
///
/// In other words, Dart wants to add a new instance that will represent
/// an object that will be instantiated on the host platform.
///
/// Throws assertion error if the instance has already been added.
///
/// Returns the randomly generated id of the [instance] added.
int addDartCreatedInstance<T extends Object>(
T instance, {
required T Function(T original) onCopy,
}) {
final int identifier = _nextUniqueIdentifier();
_addInstanceWithIdentifier(instance, identifier, onCopy: onCopy);
return identifier;
}
/// Removes the instance, if present, and call [onWeakReferenceRemoved] with
/// its identifier.
///
/// Returns the identifier associated with the removed instance. Otherwise,
/// `null` if the instance was not found in this manager.
///
/// This does not remove the the strong referenced instance associated with
/// [instance]. This can be done with [remove].
int? removeWeakReference(Object instance) {
final int? identifier = getIdentifier(instance);
if (identifier == null) {
return null;
}
_identifiers[instance] = null;
_finalizer.detach(instance);
onWeakReferenceRemoved(identifier);
return identifier;
}
/// Removes [identifier] and its associated strongly referenced instance, if
/// present, from the manager.
///
/// Returns the strong referenced instance associated with [identifier] before
/// it was removed. Returns `null` if [identifier] was not associated with
/// any strong reference.
///
/// This does not remove the the weak referenced instance associtated with
/// [identifier]. This can be done with [removeWeakReference].
T? remove<T extends Object>(int identifier) {
_copyCallbacks.remove(identifier);
return _strongInstances.remove(identifier) as T?;
}
/// Retrieves the instance associated with identifier.
///
/// The value returned is chosen from the following order:
///
/// 1. A weakly referenced instance associated with identifier.
/// 2. If the only instance associated with identifier is a strongly
/// referenced instance, a copy of the instance is added as a weak reference
/// with the same identifier. Returning the newly created copy.
/// 3. If no instance is associated with identifier, returns null.
///
/// This method also expects the host `InstanceManager` to have a strong
/// reference to the instance the identifier is associated with.
T? getInstanceWithWeakReference<T extends Object>(int identifier) {
final T? weakInstance = _weakInstances[identifier]?.target as T?;
if (weakInstance == null) {
final T? strongInstance = _strongInstances[identifier] as T?;
if (strongInstance != null) {
final Function copyCallback = _copyCallbacks[identifier]!;
// This avoid_dynamic_calls is safe since the type of strongInstance
// matches the argument type for _addInstanceWithIdentifier, which is
// the only place _copyCallbacks is populated.
// ignore: avoid_dynamic_calls
final T copy = copyCallback(strongInstance) as T;
_identifiers[copy] = identifier;
_weakInstances[identifier] = WeakReference<Object>(copy);
_finalizer.attach(copy, identifier, detach: copy);
return copy;
}
return strongInstance;
}
return weakInstance;
}
/// Retrieves the identifier associated with instance.
int? getIdentifier(Object instance) {
return _identifiers[instance];
}
/// Adds a new instance that was instantiated by the host platform.
///
/// In other words, the host platform wants to add a new instance that
/// represents an object on the host platform. Stored with [identifier].
///
/// Throws assertion error if the instance or its identifier has already been
/// added.
///
/// Returns unique identifier of the [instance] added.
void addHostCreatedInstance<T extends Object>(
T instance,
int identifier, {
required T Function(T original) onCopy,
}) {
_addInstanceWithIdentifier(instance, identifier, onCopy: onCopy);
}
void _addInstanceWithIdentifier<T extends Object>(
T instance,
int identifier, {
required T Function(T original) onCopy,
}) {
assert(!containsIdentifier(identifier));
assert(getIdentifier(instance) == null);
assert(identifier >= 0);
_identifiers[instance] = identifier;
_weakInstances[identifier] = WeakReference<Object>(instance);
_finalizer.attach(instance, identifier, detach: instance);
final Object copy = onCopy(instance);
_identifiers[copy] = identifier;
_strongInstances[identifier] = copy;
_copyCallbacks[identifier] = onCopy;
}
/// Whether this manager contains the given [identifier].
bool containsIdentifier(int identifier) {
return _weakInstances.containsKey(identifier) ||
_strongInstances.containsKey(identifier);
}
int _nextUniqueIdentifier() {
late int identifier;
do {
identifier = _nextIdentifier;
_nextIdentifier = (_nextIdentifier + 1) % _maxDartCreatedIdentifier;
} while (containsIdentifier(identifier));
return identifier;
}
}
| packages/packages/camera/camera_android_camerax/lib/src/instance_manager.dart/0 | {'file_path': 'packages/packages/camera/camera_android_camerax/lib/src/instance_manager.dart', 'repo_id': 'packages', 'token_count': 2197} |
// Mocks generated by Mockito 5.4.4 from annotations
// in camera_android_camerax/test/camera_selector_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:mockito/mockito.dart' as _i1;
import 'test_camerax_library.g.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
/// A class which mocks [TestCameraSelectorHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestCameraSelectorHostApi extends _i1.Mock
implements _i2.TestCameraSelectorHostApi {
MockTestCameraSelectorHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? identifier,
int? lensFacing,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
identifier,
lensFacing,
],
),
returnValueForMissingStub: null,
);
@override
List<int?> filter(
int? identifier,
List<int?>? cameraInfoIds,
) =>
(super.noSuchMethod(
Invocation.method(
#filter,
[
identifier,
cameraInfoIds,
],
),
returnValue: <int?>[],
) as List<int?>);
}
/// A class which mocks [TestInstanceManagerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestInstanceManagerHostApi extends _i1.Mock
implements _i2.TestInstanceManagerHostApi {
MockTestInstanceManagerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void clear() => super.noSuchMethod(
Invocation.method(
#clear,
[],
),
returnValueForMissingStub: null,
);
}
| packages/packages/camera/camera_android_camerax/test/camera_selector_test.mocks.dart/0 | {'file_path': 'packages/packages/camera/camera_android_camerax/test/camera_selector_test.mocks.dart', 'repo_id': 'packages', 'token_count': 906} |
// Mocks generated by Mockito 5.4.3 from annotations
// in camera_android_camerax/test/focus_metering_result_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:camera_android_camerax/src/metering_point.dart' as _i2;
import 'package:mockito/mockito.dart' as _i1;
import 'test_camerax_library.g.dart' as _i3;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
/// A class which mocks [MeteringPoint].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockMeteringPoint extends _i1.Mock implements _i2.MeteringPoint {
MockMeteringPoint() {
_i1.throwOnMissingStub(this);
}
@override
double get x => (super.noSuchMethod(
Invocation.getter(#x),
returnValue: 0.0,
) as double);
@override
double get y => (super.noSuchMethod(
Invocation.getter(#y),
returnValue: 0.0,
) as double);
}
/// A class which mocks [TestFocusMeteringResultHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestFocusMeteringResultHostApi extends _i1.Mock
implements _i3.TestFocusMeteringResultHostApi {
MockTestFocusMeteringResultHostApi() {
_i1.throwOnMissingStub(this);
}
@override
bool isFocusSuccessful(int? identifier) => (super.noSuchMethod(
Invocation.method(
#isFocusSuccessful,
[identifier],
),
returnValue: false,
) as bool);
}
/// A class which mocks [TestInstanceManagerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestInstanceManagerHostApi extends _i1.Mock
implements _i3.TestInstanceManagerHostApi {
MockTestInstanceManagerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void clear() => super.noSuchMethod(
Invocation.method(
#clear,
[],
),
returnValueForMissingStub: null,
);
}
| packages/packages/camera/camera_android_camerax/test/focus_metering_result_test.mocks.dart/0 | {'file_path': 'packages/packages/camera/camera_android_camerax/test/focus_metering_result_test.mocks.dart', 'repo_id': 'packages', 'token_count': 924} |
// Copyright 2013 The Flutter Authors. 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:typed_data';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:camera_android_camerax/src/plane_proxy.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'plane_proxy_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[TestInstanceManagerHostApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
group('PlaneProxy', () {
test('FlutterAPI create', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final PlaneProxyFlutterApiImpl api = PlaneProxyFlutterApiImpl(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
final Uint8List buffer = Uint8List(1);
const int pixelStride = 3;
const int rowStride = 6;
api.create(instanceIdentifier, buffer, pixelStride, rowStride);
final PlaneProxy planeProxy =
instanceManager.getInstanceWithWeakReference(instanceIdentifier)!;
expect(planeProxy.buffer, equals(buffer));
expect(planeProxy.pixelStride, equals(pixelStride));
expect(planeProxy.rowStride, equals(rowStride));
});
});
}
| packages/packages/camera/camera_android_camerax/test/plane_proxy_test.dart/0 | {'file_path': 'packages/packages/camera/camera_android_camerax/test/plane_proxy_test.dart', 'repo_id': 'packages', 'token_count': 536} |
// Copyright 2013 The Flutter Authors. 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:camera_android_camerax/src/camerax_library.g.dart'
show CameraPermissionsErrorData;
import 'package:camera_android_camerax/src/system_services.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart'
show CameraException;
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'system_services_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[TestInstanceManagerHostApi, TestSystemServicesHostApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
group('SystemServices', () {
tearDown(() => TestProcessCameraProviderHostApi.setup(null));
test(
'requestCameraPermissionsFromInstance completes normally without errors test',
() async {
final MockTestSystemServicesHostApi mockApi =
MockTestSystemServicesHostApi();
TestSystemServicesHostApi.setup(mockApi);
when(mockApi.requestCameraPermissions(true))
.thenAnswer((_) async => null);
await SystemServices.requestCameraPermissions(true);
verify(mockApi.requestCameraPermissions(true));
});
test(
'requestCameraPermissionsFromInstance throws CameraException if there was a request error',
() {
final MockTestSystemServicesHostApi mockApi =
MockTestSystemServicesHostApi();
TestSystemServicesHostApi.setup(mockApi);
final CameraPermissionsErrorData error = CameraPermissionsErrorData(
errorCode: 'Test error code',
description: 'Test error description',
);
when(mockApi.requestCameraPermissions(true))
.thenAnswer((_) async => error);
expect(
() async => SystemServices.requestCameraPermissions(true),
throwsA(isA<CameraException>()
.having((CameraException e) => e.code, 'code', 'Test error code')
.having((CameraException e) => e.description, 'description',
'Test error description')));
verify(mockApi.requestCameraPermissions(true));
});
test('onCameraError adds new error to stream', () {
const String testErrorDescription = 'Test error description!';
SystemServices.cameraErrorStreamController.stream
.listen((String errorDescription) {
expect(errorDescription, equals(testErrorDescription));
});
SystemServicesFlutterApiImpl().onCameraError(testErrorDescription);
});
test('getTempFilePath completes normally', () async {
final MockTestSystemServicesHostApi mockApi =
MockTestSystemServicesHostApi();
TestSystemServicesHostApi.setup(mockApi);
const String testPath = '/test/path/';
const String testPrefix = 'MOV';
const String testSuffix = '.mp4';
when(mockApi.getTempFilePath(testPrefix, testSuffix))
.thenReturn(testPath + testPrefix + testSuffix);
expect(await SystemServices.getTempFilePath(testPrefix, testSuffix),
testPath + testPrefix + testSuffix);
verify(mockApi.getTempFilePath(testPrefix, testSuffix));
});
});
}
| packages/packages/camera/camera_android_camerax/test/system_services_test.dart/0 | {'file_path': 'packages/packages/camera/camera_android_camerax/test/system_services_test.dart', 'repo_id': 'packages', 'token_count': 1238} |
// Copyright 2013 The Flutter Authors. 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:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('CameraImageData can be created', () {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
final CameraImageData cameraImage = CameraImageData(
format: const CameraImageFormat(ImageFormatGroup.jpeg, raw: 42),
height: 100,
width: 200,
lensAperture: 1.8,
sensorExposureTime: 11,
sensorSensitivity: 92.0,
planes: <CameraImagePlane>[
CameraImagePlane(
bytes: Uint8List.fromList(<int>[1, 2, 3, 4]),
bytesPerRow: 4,
bytesPerPixel: 2,
height: 100,
width: 200)
],
);
expect(cameraImage.format.group, ImageFormatGroup.jpeg);
expect(cameraImage.lensAperture, 1.8);
expect(cameraImage.sensorExposureTime, 11);
expect(cameraImage.sensorSensitivity, 92.0);
expect(cameraImage.height, 100);
expect(cameraImage.width, 200);
expect(cameraImage.planes.length, 1);
});
}
| packages/packages/camera/camera_platform_interface/test/types/camera_image_data_test.dart/0 | {'file_path': 'packages/packages/camera/camera_platform_interface/test/types/camera_image_data_test.dart', 'repo_id': 'packages', 'token_count': 486} |
// Copyright 2013 The Flutter Authors. 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:camera_web/src/types/types.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('CameraOptions', () {
testWidgets('serializes correctly', (WidgetTester tester) async {
final CameraOptions cameraOptions = CameraOptions(
audio: const AudioConstraints(enabled: true),
video: VideoConstraints(
facingMode: FacingModeConstraint.exact(CameraType.user),
),
);
expect(
cameraOptions.toJson(),
equals(<String, Object>{
'audio': cameraOptions.audio.toJson(),
'video': cameraOptions.video.toJson(),
}),
);
});
testWidgets('supports value equality', (WidgetTester tester) async {
expect(
CameraOptions(
audio: const AudioConstraints(),
video: VideoConstraints(
facingMode: FacingModeConstraint(CameraType.environment),
width:
const VideoSizeConstraint(minimum: 10, ideal: 15, maximum: 20),
height:
const VideoSizeConstraint(minimum: 15, ideal: 20, maximum: 25),
deviceId: 'deviceId',
),
),
equals(
CameraOptions(
audio: const AudioConstraints(),
video: VideoConstraints(
facingMode: FacingModeConstraint(CameraType.environment),
width: const VideoSizeConstraint(
minimum: 10, ideal: 15, maximum: 20),
height: const VideoSizeConstraint(
minimum: 15, ideal: 20, maximum: 25),
deviceId: 'deviceId',
),
),
),
);
});
});
group('AudioConstraints', () {
testWidgets('serializes correctly', (WidgetTester tester) async {
expect(
const AudioConstraints(enabled: true).toJson(),
equals(true),
);
});
testWidgets('supports value equality', (WidgetTester tester) async {
expect(
const AudioConstraints(enabled: true),
equals(const AudioConstraints(enabled: true)),
);
});
});
group('VideoConstraints', () {
testWidgets('serializes correctly', (WidgetTester tester) async {
final VideoConstraints videoConstraints = VideoConstraints(
facingMode: FacingModeConstraint.exact(CameraType.user),
width: const VideoSizeConstraint(ideal: 100, maximum: 100),
height: const VideoSizeConstraint(ideal: 50, maximum: 50),
deviceId: 'deviceId',
);
expect(
videoConstraints.toJson(),
equals(<String, Object>{
'facingMode': videoConstraints.facingMode!.toJson(),
'width': videoConstraints.width!.toJson(),
'height': videoConstraints.height!.toJson(),
'deviceId': <String, Object>{
'exact': 'deviceId',
}
}),
);
});
testWidgets('supports value equality', (WidgetTester tester) async {
expect(
VideoConstraints(
facingMode: FacingModeConstraint.exact(CameraType.environment),
width:
const VideoSizeConstraint(minimum: 90, ideal: 100, maximum: 100),
height:
const VideoSizeConstraint(minimum: 40, ideal: 50, maximum: 50),
deviceId: 'deviceId',
),
equals(
VideoConstraints(
facingMode: FacingModeConstraint.exact(CameraType.environment),
width: const VideoSizeConstraint(
minimum: 90, ideal: 100, maximum: 100),
height:
const VideoSizeConstraint(minimum: 40, ideal: 50, maximum: 50),
deviceId: 'deviceId',
),
),
);
});
});
group('FacingModeConstraint', () {
group('ideal', () {
testWidgets(
'serializes correctly '
'for environment camera type', (WidgetTester tester) async {
expect(
FacingModeConstraint(CameraType.environment).toJson(),
equals(<String, Object>{'ideal': 'environment'}),
);
});
testWidgets(
'serializes correctly '
'for user camera type', (WidgetTester tester) async {
expect(
FacingModeConstraint(CameraType.user).toJson(),
equals(<String, Object>{'ideal': 'user'}),
);
});
testWidgets('supports value equality', (WidgetTester tester) async {
expect(
FacingModeConstraint(CameraType.user),
equals(FacingModeConstraint(CameraType.user)),
);
});
});
group('exact', () {
testWidgets(
'serializes correctly '
'for environment camera type', (WidgetTester tester) async {
expect(
FacingModeConstraint.exact(CameraType.environment).toJson(),
equals(<String, Object>{'exact': 'environment'}),
);
});
testWidgets(
'serializes correctly '
'for user camera type', (WidgetTester tester) async {
expect(
FacingModeConstraint.exact(CameraType.user).toJson(),
equals(<String, Object>{'exact': 'user'}),
);
});
testWidgets('supports value equality', (WidgetTester tester) async {
expect(
FacingModeConstraint.exact(CameraType.environment),
equals(FacingModeConstraint.exact(CameraType.environment)),
);
});
});
});
group('VideoSizeConstraint ', () {
testWidgets('serializes correctly', (WidgetTester tester) async {
expect(
const VideoSizeConstraint(
minimum: 200,
ideal: 400,
maximum: 400,
).toJson(),
equals(<String, Object>{
'min': 200,
'ideal': 400,
'max': 400,
}),
);
});
testWidgets('supports value equality', (WidgetTester tester) async {
expect(
const VideoSizeConstraint(
minimum: 100,
ideal: 200,
maximum: 300,
),
equals(
const VideoSizeConstraint(
minimum: 100,
ideal: 200,
maximum: 300,
),
),
);
});
});
}
| packages/packages/camera/camera_web/example/integration_test/camera_options_test.dart/0 | {'file_path': 'packages/packages/camera/camera_web/example/integration_test/camera_options_test.dart', 'repo_id': 'packages', 'token_count': 2942} |
// Copyright 2013 The Flutter Authors. 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:example/wrap_layout_example.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Check wrap layout', (WidgetTester tester) async {
const MaterialApp app = MaterialApp(
home: WrapExample(),
);
await tester.pumpWidget(app);
await tester.pumpAndSettle();
// Validate which children are laid out.
for (int i = 0; i <= 12; i++) {
expect(find.text('Index $i'), findsOneWidget);
}
for (int i = 13; i < 19; i++) {
expect(find.text('Index $i'), findsNothing);
}
// Validate with the position of the box, not the text.
Finder getContainer(String text) {
return find.ancestor(
of: find.text(text),
matching: find.byType(Container),
);
}
// Validate layout position.
expect(
tester.getTopLeft(getContainer('Index 0')),
const Offset(0.0, 56.0),
);
expect(
tester.getTopLeft(getContainer('Index 1')),
const Offset(40.0, 56.0),
);
expect(
tester.getTopLeft(getContainer('Index 2')),
const Offset(190.0, 56.0),
);
expect(
tester.getTopLeft(getContainer('Index 3')),
const Offset(270.0, 56.0),
);
expect(
tester.getTopLeft(getContainer('Index 4')),
const Offset(370.0, 56.0),
);
expect(
tester.getTopLeft(getContainer('Index 5')),
const Offset(490.0, 56.0),
);
expect(
tester.getTopLeft(getContainer('Index 6')),
const Offset(690.0, 56.0),
);
expect(
tester.getTopLeft(getContainer('Index 7')),
const Offset(0.0, 506.0),
);
expect(
tester.getTopLeft(getContainer('Index 8')),
const Offset(150.0, 506.0),
);
expect(
tester.getTopLeft(getContainer('Index 9')),
const Offset(250.0, 506.0),
);
expect(
tester.getTopLeft(getContainer('Index 10')),
const Offset(350.0, 506.0),
);
expect(
tester.getTopLeft(getContainer('Index 11')),
const Offset(390.0, 506.0),
);
expect(
tester.getTopLeft(getContainer('Index 12')),
const Offset(590.0, 506.0),
);
});
}
| packages/packages/dynamic_layouts/example/test/wrap_example_test.dart/0 | {'file_path': 'packages/packages/dynamic_layouts/example/test/wrap_example_test.dart', 'repo_id': 'packages', 'token_count': 1015} |
// Copyright 2013 The Flutter Authors. 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:dynamic_layouts/dynamic_layouts.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('DynamicGridView works with simple layout',
(WidgetTester tester) async {
// Can have no children
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DynamicGridView(
gridDelegate: TestDelegate(crossAxisCount: 2),
),
),
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DynamicGridView(
gridDelegate: TestDelegate(crossAxisCount: 2),
children: List<Widget>.generate(
50,
(int index) => SizedBox.square(
dimension: TestSimpleLayout.childExtent,
child: Text('Index $index'),
),
),
),
),
),
);
// Only the visible tiles have been laid out.
expect(find.text('Index 0'), findsOneWidget);
expect(tester.getTopLeft(find.text('Index 0')), Offset.zero);
expect(find.text('Index 1'), findsOneWidget);
expect(tester.getTopLeft(find.text('Index 1')), const Offset(50.0, 0.0));
expect(find.text('Index 2'), findsOneWidget);
expect(tester.getTopLeft(find.text('Index 2')), const Offset(0.0, 50.0));
expect(find.text('Index 47'), findsNothing);
expect(find.text('Index 48'), findsNothing);
expect(find.text('Index 49'), findsNothing);
});
testWidgets('DynamicGridView.builder works with simple layout',
(WidgetTester tester) async {
// Only a few number of tiles
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DynamicGridView.builder(
gridDelegate: TestDelegate(crossAxisCount: 2),
itemCount: 3,
itemBuilder: (BuildContext context, int index) {
return SizedBox.square(
dimension: TestSimpleLayout.childExtent,
child: Text('Index $index'),
);
},
),
),
),
);
// Only the visible tiles have been laid out, up to itemCount.
expect(find.text('Index 0'), findsOneWidget);
expect(tester.getTopLeft(find.text('Index 0')), Offset.zero);
expect(find.text('Index 1'), findsOneWidget);
expect(tester.getTopLeft(find.text('Index 1')), const Offset(50.0, 0.0));
expect(find.text('Index 2'), findsOneWidget);
expect(tester.getTopLeft(find.text('Index 2')), const Offset(0.0, 50.0));
expect(find.text('Index 3'), findsNothing);
expect(find.text('Index 4'), findsNothing);
expect(find.text('Index 5'), findsNothing);
// Infinite number of tiles
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DynamicGridView.builder(
gridDelegate: TestDelegate(crossAxisCount: 2),
itemBuilder: (BuildContext context, int index) {
return SizedBox.square(
dimension: TestSimpleLayout.childExtent,
child: Text('Index $index'),
);
},
),
),
),
);
// Only the visible tiles have been laid out.
expect(find.text('Index 0'), findsOneWidget);
expect(tester.getTopLeft(find.text('Index 0')), Offset.zero);
expect(find.text('Index 1'), findsOneWidget);
expect(tester.getTopLeft(find.text('Index 1')), const Offset(50.0, 0.0));
expect(find.text('Index 2'), findsOneWidget);
expect(tester.getTopLeft(find.text('Index 2')), const Offset(0.0, 50.0));
expect(find.text('Index 47'), findsNothing);
expect(find.text('Index 48'), findsNothing);
expect(find.text('Index 49'), findsNothing);
});
}
class TestSimpleLayout extends DynamicSliverGridLayout {
TestSimpleLayout({
required this.crossAxisCount,
});
final int crossAxisCount;
static const double childExtent = 50.0;
@override
DynamicSliverGridGeometry getGeometryForChildIndex(int index) {
final double crossAxisStart = (index % crossAxisCount) * childExtent;
return DynamicSliverGridGeometry(
scrollOffset: (index ~/ crossAxisCount) * childExtent,
crossAxisOffset: crossAxisStart,
mainAxisExtent: childExtent,
crossAxisExtent: childExtent,
);
}
@override
bool reachedTargetScrollOffset(double targetOffset) => true;
@override
DynamicSliverGridGeometry updateGeometryForChildIndex(
int index,
Size childSize,
) {
return getGeometryForChildIndex(index);
}
}
class TestDelegate extends SliverGridDelegateWithFixedCrossAxisCount {
TestDelegate({required super.crossAxisCount});
@override
DynamicSliverGridLayout getLayout(SliverConstraints constraints) {
return TestSimpleLayout(crossAxisCount: crossAxisCount);
}
}
| packages/packages/dynamic_layouts/test/dynamic_grid_test.dart/0 | {'file_path': 'packages/packages/dynamic_layouts/test/dynamic_grid_test.dart', 'repo_id': 'packages', 'token_count': 2031} |
name: espresso_example
description: Demonstrates how to use the espresso plugin.
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
flutter: ">=3.10.0"
dependencies:
flutter:
sdk: flutter
dev_dependencies:
espresso:
# When depending on this package from a real application you should use:
# espresso: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| packages/packages/espresso/example/pubspec.yaml/0 | {'file_path': 'packages/packages/espresso/example/pubspec.yaml', 'repo_id': 'packages', 'token_count': 257} |
// Copyright 2013 The Flutter Authors. 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:google_sign_in/google_sign_in.dart';
import 'package:googleapis_auth/googleapis_auth.dart' as gapis;
import 'package:http/http.dart' as http;
import 'package:meta/meta.dart';
/// Extension on [GoogleSignIn] that adds an `authenticatedClient` method.
///
/// This method can be used to retrieve an authenticated [gapis.AuthClient]
/// client that can be used with the rest of the `googleapis` libraries.
extension GoogleApisGoogleSignInAuth on GoogleSignIn {
/// Retrieve a `googleapis` authenticated client.
Future<gapis.AuthClient?> authenticatedClient({
@visibleForTesting GoogleSignInAuthentication? debugAuthentication,
@visibleForTesting List<String>? debugScopes,
}) async {
final GoogleSignInAuthentication? auth =
debugAuthentication ?? await currentUser?.authentication;
final String? oauthTokenString = auth?.accessToken;
if (oauthTokenString == null) {
return null;
}
final gapis.AccessCredentials credentials = gapis.AccessCredentials(
gapis.AccessToken(
'Bearer',
oauthTokenString,
// TODO(kevmoo): Use the correct value once it's available from authentication
// See https://github.com/flutter/flutter/issues/80905
DateTime.now().toUtc().add(const Duration(days: 365)),
),
null, // We don't have a refreshToken
debugScopes ?? scopes,
);
return gapis.authenticatedClient(http.Client(), credentials);
}
}
| packages/packages/extension_google_sign_in_as_googleapis_auth/lib/extension_google_sign_in_as_googleapis_auth.dart/0 | {'file_path': 'packages/packages/extension_google_sign_in_as_googleapis_auth/lib/extension_google_sign_in_as_googleapis_auth.dart', 'repo_id': 'packages', 'token_count': 535} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.