code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'constants.dart';
import 'context_menu_region.dart';
import 'platform_selector.dart';
class AnywherePage extends StatelessWidget {
AnywherePage({
super.key,
required this.onChangedPlatform,
});
static const String route = 'anywhere';
static const String title = 'Context Menu Anywhere Example';
static const String subtitle = 'A context menu outside of a text field';
final PlatformCallback onChangedPlatform;
final TextEditingController _materialController = TextEditingController(
text: 'TextField shows the default menu still.',
);
final TextEditingController _cupertinoController = TextEditingController(
text: 'CupertinoTextField shows the default menu still.',
);
final TextEditingController _editableController = TextEditingController(
text: 'EditableText has no default menu, so it shows the custom one.',
);
static const String url = '$kCodeUrl/anywhere_page.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(AnywherePage.title),
actions: <Widget>[
PlatformSelector(
onChangedPlatform: onChangedPlatform,
),
IconButton(
icon: const Icon(Icons.code),
onPressed: () async {
if (!await launchUrl(Uri.parse(url))) {
throw 'Could not launch $url';
}
},
),
],
),
body: ContextMenuRegion(
contextMenuBuilder: (context, primaryAnchor, [secondaryAnchor]) {
return AdaptiveTextSelectionToolbar.buttonItems(
anchors: TextSelectionToolbarAnchors(
primaryAnchor: primaryAnchor,
secondaryAnchor: secondaryAnchor as Offset?,
),
buttonItems: <ContextMenuButtonItem>[
ContextMenuButtonItem(
onPressed: () {
ContextMenuController.removeAny();
Navigator.of(context).pop();
},
label: 'Back',
),
],
);
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 64.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(height: 20.0),
const Text(
'Right click anywhere outside of a field to show a custom menu.',
),
Container(height: 140.0),
CupertinoTextField(controller: _cupertinoController),
Container(height: 40.0),
TextField(controller: _materialController),
Container(height: 40.0),
Container(
color: Colors.white,
child: EditableText(
controller: _editableController,
focusNode: FocusNode(),
style: Typography.material2021().black.displayMedium!,
cursorColor: Colors.blue,
backgroundCursorColor: Colors.white,
),
),
],
),
),
),
);
}
}
| samples/context_menus/lib/anywhere_page.dart/0 | {'file_path': 'samples/context_menus/lib/anywhere_page.dart', 'repo_id': 'samples', 'token_count': 1507} |
import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'constants.dart';
import 'platform_selector.dart';
class ReorderedButtonsPage extends StatelessWidget {
ReorderedButtonsPage({
super.key,
required this.onChangedPlatform,
});
static const String route = 'reordered-buttons';
static const String title = 'Reordered Buttons';
static const String subtitle = 'The usual buttons, but in a different order.';
static const String url = '$kCodeUrl/reordered_buttons_page.dart';
final PlatformCallback onChangedPlatform;
final TextEditingController _controllerNormal = TextEditingController(
text: 'This button has the default buttons for reference.',
);
final TextEditingController _controllerReordered = TextEditingController(
text: 'This field has reordered buttons.',
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(ReorderedButtonsPage.title),
actions: <Widget>[
PlatformSelector(
onChangedPlatform: onChangedPlatform,
),
IconButton(
icon: const Icon(Icons.code),
onPressed: () async {
if (!await launchUrl(Uri.parse(url))) {
throw 'Could not launch $url';
}
},
),
],
),
body: Center(
child: SizedBox(
width: 300.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
maxLines: 2,
controller: _controllerNormal,
),
const SizedBox(height: 20.0),
TextField(
controller: _controllerReordered,
maxLines: 2,
contextMenuBuilder: (context, editableTextState) {
// Reorder the button datas by type.
final HashMap<ContextMenuButtonType, ContextMenuButtonItem>
buttonItemsMap =
HashMap<ContextMenuButtonType, ContextMenuButtonItem>();
for (ContextMenuButtonItem buttonItem
in editableTextState.contextMenuButtonItems) {
buttonItemsMap[buttonItem.type] = buttonItem;
}
final List<ContextMenuButtonItem> reorderedButtonItems =
<ContextMenuButtonItem>[
if (buttonItemsMap
.containsKey(ContextMenuButtonType.selectAll))
buttonItemsMap[ContextMenuButtonType.selectAll]!,
if (buttonItemsMap.containsKey(ContextMenuButtonType.paste))
buttonItemsMap[ContextMenuButtonType.paste]!,
if (buttonItemsMap.containsKey(ContextMenuButtonType.copy))
buttonItemsMap[ContextMenuButtonType.copy]!,
if (buttonItemsMap.containsKey(ContextMenuButtonType.cut))
buttonItemsMap[ContextMenuButtonType.cut]!,
];
return AdaptiveTextSelectionToolbar.buttonItems(
anchors: editableTextState.contextMenuAnchors,
buttonItems: reorderedButtonItems,
);
},
),
],
),
),
),
);
}
}
| samples/context_menus/lib/reordered_buttons_page.dart/0 | {'file_path': 'samples/context_menus/lib/reordered_buttons_page.dart', 'repo_id': 'samples', 'token_count': 1634} |
import 'package:context_menus/default_values_page.dart';
import 'package:context_menus/main.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Gives correct behavior for all values of contextMenuBuilder',
(tester) async {
await tester.pumpWidget(const MyApp());
// Navigate to the DefaultValuesPage example.
await tester.dragUntilVisible(
find.text(DefaultValuesPage.title),
find.byType(ListView),
const Offset(0.0, -100.0),
);
await tester.pumpAndSettle();
await tester.tap(find.text(DefaultValuesPage.title));
await tester.pumpAndSettle();
expect(
find.descendant(
of: find.byType(AppBar),
matching: find.text(DefaultValuesPage.title),
),
findsOneWidget,
);
// Right click on the text field where contextMenuBuilder isn't passed.
TestGesture gesture = await tester.startGesture(
tester.getCenter(find.byType(EditableText).first),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
// The default context menu is shown.
expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget);
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
expect(
find.byType(CupertinoTextSelectionToolbarButton), findsNWidgets(2));
case TargetPlatform.macOS:
expect(find.byType(CupertinoDesktopTextSelectionToolbarButton),
findsNWidgets(2));
case TargetPlatform.android:
case TargetPlatform.fuchsia:
expect(find.byType(TextSelectionToolbarTextButton), findsNWidgets(1));
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(
find.byType(DesktopTextSelectionToolbarButton), findsNWidgets(1));
}
// Tap the next field to hide the context menu.
await tester.tap(find.byType(EditableText).at(1));
await tester.pumpAndSettle();
expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing);
// Right click on the text field where contextMenuBuilder is given null.
gesture = await tester.startGesture(
tester.getCenter(find.byType(EditableText).at(1)),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
// No context menu is shown.
expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing);
// Tap the next field to hide the context menu.
await tester.tap(find.byType(EditableText).at(2));
await tester.pumpAndSettle();
expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing);
// Right click on the text field with the custom contextMenuBuilder.
gesture = await tester.startGesture(
tester.getCenter(find.byType(EditableText).at(2)),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
// The custom context menu is shown.
expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget);
expect(find.text('Custom button'), findsOneWidget);
});
}
| samples/context_menus/test/default_values_page_test.dart/0 | {'file_path': 'samples/context_menus/test/default_values_page_test.dart', 'repo_id': 'samples', 'token_count': 1307} |
// Copyright 2019 Google LLC
//
// 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
//
// https://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.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'model/products_repository.dart';
import 'row_item.dart';
import 'styles.dart';
class ProductCategoryList extends StatelessWidget {
const ProductCategoryList({super.key});
@override
Widget build(BuildContext context) {
final GoRouterState state = GoRouterState.of(context);
final Category category = Category.values.firstWhere(
(Category value) =>
value.toString().contains(state.pathParameters['category']!),
orElse: () => Category.all,
);
final List<Widget> children =
ProductsRepository.loadProducts(category: category)
.map<Widget>((Product p) => RowItem(product: p))
.toList();
return Scaffold(
backgroundColor: Styles.scaffoldBackground,
body: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
title: Text(getCategoryTitle(category),
style: Styles.productListTitle),
backgroundColor: Styles.scaffoldAppBarBackground,
pinned: true,
),
SliverList(
delegate: SliverChildListDelegate(children),
),
],
),
);
}
}
| samples/deeplink_store_example/lib/product_category_list.dart/0 | {'file_path': 'samples/deeplink_store_example/lib/product_category_list.dart', 'repo_id': 'samples', 'token_count': 655} |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'serializers.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializers _$serializers = (new Serializers().toBuilder()
..add(ApiError.serializer)
..add(CurrentUserCollections.serializer)
..add(Exif.serializer)
..add(Links.serializer)
..add(Location.serializer)
..add(Photo.serializer)
..add(Position.serializer)
..add(Search.serializer)
..add(SearchPhotosResponse.serializer)
..add(Tags.serializer)
..add(Urls.serializer)
..add(User.serializer)
..addBuilderFactory(
const FullType(BuiltList, const [const FullType(Photo)]),
() => new ListBuilder<Photo>())
..addBuilderFactory(
const FullType(BuiltList, const [const FullType(Photo)]),
() => new ListBuilder<Photo>())
..addBuilderFactory(
const FullType(BuiltList, const [const FullType(String)]),
() => new ListBuilder<String>())
..addBuilderFactory(
const FullType(BuiltList, const [const FullType(Tags)]),
() => new ListBuilder<Tags>())
..addBuilderFactory(
const FullType(
BuiltList, const [const FullType(CurrentUserCollections)]),
() => new ListBuilder<CurrentUserCollections>()))
.build();
// ignore_for_file: deprecated_member_use_from_same_package,type=lint
| samples/desktop_photo_search/fluent_ui/lib/src/serializers.g.dart/0 | {'file_path': 'samples/desktop_photo_search/fluent_ui/lib/src/serializers.g.dart', 'repo_id': 'samples', 'token_count': 614} |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'search_photos_response.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializer<SearchPhotosResponse> _$searchPhotosResponseSerializer =
new _$SearchPhotosResponseSerializer();
class _$SearchPhotosResponseSerializer
implements StructuredSerializer<SearchPhotosResponse> {
@override
final Iterable<Type> types = const [
SearchPhotosResponse,
_$SearchPhotosResponse
];
@override
final String wireName = 'SearchPhotosResponse';
@override
Iterable<Object?> serialize(
Serializers serializers, SearchPhotosResponse object,
{FullType specifiedType = FullType.unspecified}) {
final result = <Object?>[
'results',
serializers.serialize(object.results,
specifiedType:
const FullType(BuiltList, const [const FullType(Photo)])),
];
Object? value;
value = object.total;
if (value != null) {
result
..add('total')
..add(serializers.serialize(value, specifiedType: const FullType(int)));
}
value = object.totalPages;
if (value != null) {
result
..add('total_pages')
..add(serializers.serialize(value, specifiedType: const FullType(int)));
}
return result;
}
@override
SearchPhotosResponse deserialize(
Serializers serializers, Iterable<Object?> serialized,
{FullType specifiedType = FullType.unspecified}) {
final result = new SearchPhotosResponseBuilder();
final iterator = serialized.iterator;
while (iterator.moveNext()) {
final key = iterator.current! as String;
iterator.moveNext();
final Object? value = iterator.current;
switch (key) {
case 'total':
result.total = serializers.deserialize(value,
specifiedType: const FullType(int)) as int?;
break;
case 'total_pages':
result.totalPages = serializers.deserialize(value,
specifiedType: const FullType(int)) as int?;
break;
case 'results':
result.results.replace(serializers.deserialize(value,
specifiedType:
const FullType(BuiltList, const [const FullType(Photo)]))!
as BuiltList<Object?>);
break;
}
}
return result.build();
}
}
class _$SearchPhotosResponse extends SearchPhotosResponse {
@override
final int? total;
@override
final int? totalPages;
@override
final BuiltList<Photo> results;
factory _$SearchPhotosResponse(
[void Function(SearchPhotosResponseBuilder)? updates]) =>
(new SearchPhotosResponseBuilder()..update(updates))._build();
_$SearchPhotosResponse._({this.total, this.totalPages, required this.results})
: super._() {
BuiltValueNullFieldError.checkNotNull(
results, r'SearchPhotosResponse', 'results');
}
@override
SearchPhotosResponse rebuild(
void Function(SearchPhotosResponseBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
SearchPhotosResponseBuilder toBuilder() =>
new SearchPhotosResponseBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is SearchPhotosResponse &&
total == other.total &&
totalPages == other.totalPages &&
results == other.results;
}
@override
int get hashCode {
var _$hash = 0;
_$hash = $jc(_$hash, total.hashCode);
_$hash = $jc(_$hash, totalPages.hashCode);
_$hash = $jc(_$hash, results.hashCode);
_$hash = $jf(_$hash);
return _$hash;
}
@override
String toString() {
return (newBuiltValueToStringHelper(r'SearchPhotosResponse')
..add('total', total)
..add('totalPages', totalPages)
..add('results', results))
.toString();
}
}
class SearchPhotosResponseBuilder
implements Builder<SearchPhotosResponse, SearchPhotosResponseBuilder> {
_$SearchPhotosResponse? _$v;
int? _total;
int? get total => _$this._total;
set total(int? total) => _$this._total = total;
int? _totalPages;
int? get totalPages => _$this._totalPages;
set totalPages(int? totalPages) => _$this._totalPages = totalPages;
ListBuilder<Photo>? _results;
ListBuilder<Photo> get results =>
_$this._results ??= new ListBuilder<Photo>();
set results(ListBuilder<Photo>? results) => _$this._results = results;
SearchPhotosResponseBuilder();
SearchPhotosResponseBuilder get _$this {
final $v = _$v;
if ($v != null) {
_total = $v.total;
_totalPages = $v.totalPages;
_results = $v.results.toBuilder();
_$v = null;
}
return this;
}
@override
void replace(SearchPhotosResponse other) {
ArgumentError.checkNotNull(other, 'other');
_$v = other as _$SearchPhotosResponse;
}
@override
void update(void Function(SearchPhotosResponseBuilder)? updates) {
if (updates != null) updates(this);
}
@override
SearchPhotosResponse build() => _build();
_$SearchPhotosResponse _build() {
_$SearchPhotosResponse _$result;
try {
_$result = _$v ??
new _$SearchPhotosResponse._(
total: total, totalPages: totalPages, results: results.build());
} catch (_) {
late String _$failedField;
try {
_$failedField = 'results';
results.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
r'SearchPhotosResponse', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: deprecated_member_use_from_same_package,type=lint
| samples/desktop_photo_search/fluent_ui/lib/src/unsplash/search_photos_response.g.dart/0 | {'file_path': 'samples/desktop_photo_search/fluent_ui/lib/src/unsplash/search_photos_response.g.dart', 'repo_id': 'samples', 'token_count': 2193} |
// The federated_plugin_macos uses the default BatteryMethodChannel used by
// federated_plugin_platform_interface to do platform calls.
| samples/experimental/federated_plugin/federated_plugin_macos/lib/federated_plugin_macos.dart/0 | {'file_path': 'samples/experimental/federated_plugin/federated_plugin_macos/lib/federated_plugin_macos.dart', 'repo_id': 'samples', 'token_count': 33} |
name: federated_plugin_web
description: Web implementation of federated_plugin to retrieve current battery level.
version: 0.0.1
publish_to: none
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
federated_plugin_platform_interface:
path: ../federated_plugin_platform_interface
dev_dependencies:
analysis_defaults:
path: ../../../analysis_defaults
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
mockito: ^5.0.2
flutter:
plugin:
platforms:
web:
pluginClass: FederatedPlugin
fileName: federated_plugin_web.dart
| samples/experimental/federated_plugin/federated_plugin_web/pubspec.yaml/0 | {'file_path': 'samples/experimental/federated_plugin/federated_plugin_web/pubspec.yaml', 'repo_id': 'samples', 'token_count': 247} |
// Copyright 2021 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:linting_tool/layout/adaptive.dart';
import 'package:linting_tool/model/editing_controller.dart';
import 'package:linting_tool/model/profiles_store.dart';
import 'package:linting_tool/pages/rules_page.dart';
import 'package:linting_tool/theme/colors.dart';
import 'package:provider/provider.dart';
class SavedLintsPage extends StatefulWidget {
const SavedLintsPage({super.key});
@override
State<SavedLintsPage> createState() => _SavedLintsPageState();
}
class _SavedLintsPageState extends State<SavedLintsPage> {
@override
Widget build(BuildContext context) {
return Consumer<ProfilesStore>(
builder: (context, profilesStore, child) {
if (profilesStore.isLoading) {
return const CircularProgressIndicator.adaptive();
}
if (!profilesStore.isLoading) {
if (profilesStore.savedProfiles.isNotEmpty) {
final isDesktop = isDisplayLarge(context);
final isTablet = isDisplayMedium(context);
final startPadding = isTablet
? 60.0
: isDesktop
? 120.0
: 16.0;
final endPadding = isTablet
? 60.0
: isDesktop
? 120.0
: 16.0;
return ListView.separated(
padding: EdgeInsetsDirectional.only(
start: startPadding,
end: endPadding,
top: isDesktop ? 28 : 16,
bottom: isDesktop ? kToolbarHeight : 16,
),
itemCount: profilesStore.savedProfiles.length,
cacheExtent: 5,
itemBuilder: (itemBuilderContext, index) {
var profile = profilesStore.savedProfiles[index];
return ListTile(
title: Text(
profile.name,
),
tileColor: AppColors.white50,
onTap: () {
Navigator.push<void>(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider(
create: (context) => EditingController(),
child: RulesPage(selectedProfileIndex: index),
),
),
);
},
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.edit),
onPressed: () {
Navigator.push<void>(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider(
create: (context) => EditingController(
isEditing: true,
),
child: RulesPage(selectedProfileIndex: index),
),
),
);
},
),
const SizedBox(
width: 8.0,
),
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
onSelected: (value) async {
switch (value) {
case 'Export file':
// ignore: todo
// TODO(abd99): Add option to select formatting style.
var saved = await profilesStore
.exportProfileFile(profile);
if (!context.mounted) return;
if (!saved) {
_showSnackBar(
context,
profilesStore.error ?? 'Failed to save file.',
);
}
case 'Delete':
await profilesStore.deleteProfile(profile);
default:
}
},
itemBuilder: (context) {
return [
const PopupMenuItem(
value: 'Export file',
child: Text('Export file'),
),
const PopupMenuItem(
value: 'Delete',
child: Text('Delete'),
),
];
},
),
],
),
);
},
separatorBuilder: (context, index) => const SizedBox(height: 4),
);
}
}
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(profilesStore.error ?? 'No saved profiles found.'),
const SizedBox(
height: 16.0,
),
IconButton(
onPressed: () => profilesStore.fetchSavedProfiles(),
icon: const Icon(Icons.refresh),
),
],
);
},
);
}
void _showSnackBar(BuildContext context, String data) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(data),
),
);
}
}
| samples/experimental/linting_tool/lib/pages/saved_lints_page.dart/0 | {'file_path': 'samples/experimental/linting_tool/lib/pages/saved_lints_page.dart', 'repo_id': 'samples', 'token_count': 3573} |
import 'dart:async';
import 'dart:collection';
import 'dart:ffi' as ffi;
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart';
import 'package:jni/jni.dart' as jni;
import 'package:pedometer/pedometer_bindings_generated.dart' as pd;
import 'package:pedometer/health_connect.dart' as hc;
/// Class to hold the information needed for the chart
class Steps {
String startHour;
int steps;
Steps(this.startHour, this.steps);
}
abstract class StepsRepo {
static const _formatString = "yyyy-MM-dd HH:mm:ss";
static StepsRepo? _instance;
static StepsRepo get instance =>
_instance ??= Platform.isAndroid ? _AndroidStepsRepo() : _IOSStepsRepo();
Future<List<Steps>> getSteps();
}
class _IOSStepsRepo implements StepsRepo {
static const _dylibPath =
'/System/Library/Frameworks/CoreMotion.framework/CoreMotion';
// Bindings for the CMPedometer class
final lib = pd.PedometerBindings(ffi.DynamicLibrary.open(_dylibPath));
// Bindings for the helper function
final helpLib = pd.PedometerBindings(ffi.DynamicLibrary.process());
late final pd.CMPedometer client;
late final pd.NSDateFormatter formatter;
late final pd.NSDateFormatter hourFormatter;
_IOSStepsRepo() {
// Contains the Dart API helper functions
final dylib = ffi.DynamicLibrary.open("pedometer.framework/pedometer");
// Initialize the Dart API
final initializeApi = dylib.lookupFunction<
ffi.IntPtr Function(ffi.Pointer<ffi.Void>),
int Function(ffi.Pointer<ffi.Void>)>('Dart_InitializeApiDL');
final initializeResult = initializeApi(ffi.NativeApi.initializeApiDLData);
if (initializeResult != 0) {
throw StateError('failed to init API.');
}
// Create a new CMPedometer instance.
client = pd.CMPedometer.new1(lib);
// Setting the formatter for date strings.
formatter =
pd.NSDateFormatter.castFrom(pd.NSDateFormatter.alloc(lib).init());
formatter.dateFormat = pd.NSString(lib, "${StepsRepo._formatString} zzz");
hourFormatter =
pd.NSDateFormatter.castFrom(pd.NSDateFormatter.alloc(lib).init());
hourFormatter.dateFormat = pd.NSString(lib, "HH");
}
pd.NSDate dateConverter(DateTime dartDate) {
// Format dart date to string.
final formattedDate = DateFormat(StepsRepo._formatString).format(dartDate);
// Get current timezone. If eastern african change to AST to follow with NSDate.
final tz = dartDate.timeZoneName == "EAT" ? "AST" : dartDate.timeZoneName;
// Create a new NSString with the formatted date and timezone.
final nString = pd.NSString(lib, "$formattedDate $tz");
// Convert the NSString to NSDate.
return formatter.dateFromString_(nString)!;
}
@override
Future<List<Steps>> getSteps() async {
if (!pd.CMPedometer.isStepCountingAvailable(lib)) {
debugPrint("Step counting is not available.");
return [];
}
final handlers = [];
final futures = <Future<Steps?>>[];
final now = DateTime.now();
for (var h = 0; h <= now.hour; h++) {
final start = dateConverter(DateTime(now.year, now.month, now.day, h));
final end = dateConverter(DateTime(now.year, now.month, now.day, h + 1));
final completer = Completer<Steps?>();
futures.add(completer.future);
final handler = helpLib.wrapCallback(
pd.ObjCBlock_ffiVoid_CMPedometerData_NSError.listener(lib,
(pd.CMPedometerData? result, pd.NSError? error) {
if (result != null) {
final stepCount = result.numberOfSteps.intValue;
final startHour =
hourFormatter.stringFromDate_(result.startDate).toString();
completer.complete(Steps(startHour, stepCount));
} else {
debugPrint("Query error: ${error?.localizedDescription}");
completer.complete(null);
}
}));
handlers.add(handler);
client.queryPedometerDataFromDate_toDate_withHandler_(
start, end, handler);
}
return (await Future.wait(futures)).nonNulls.toList();
}
}
class _AndroidStepsRepo implements StepsRepo {
late final hc.Activity activity;
late final hc.Context applicationContext;
late final hc.HealthConnectClient client;
_AndroidStepsRepo() {
jni.Jni.initDLApi();
activity = hc.Activity.fromRef(jni.Jni.getCurrentActivity());
applicationContext =
hc.Context.fromRef(jni.Jni.getCachedApplicationContext());
client = hc.HealthConnectClient.getOrCreate1(applicationContext);
}
@override
Future<List<Steps>> getSteps() async {
final futures = <Future<hc.AggregationResult>>[];
final now = DateTime.now();
for (var h = 0; h <= now.hour; h++) {
final start =
DateTime(now.year, now.month, now.day, h).millisecondsSinceEpoch;
final end =
DateTime(now.year, now.month, now.day, h + 1).millisecondsSinceEpoch;
final request = hc.AggregateRequest(
{hc.StepsRecord.COUNT_TOTAL}
.toJSet(hc.AggregateMetric.type(jni.JLong.type)),
hc.TimeRangeFilter.between(
hc.Instant.ofEpochMilli(start),
hc.Instant.ofEpochMilli(end),
),
jni.JSet.hash(jni.JObject.type),
);
futures.add(client.aggregate(request));
}
final data = await Future.wait(futures);
return data.asMap().entries.map((entry) {
final stepsLong = entry.value.get0(hc.StepsRecord.COUNT_TOTAL);
final steps = stepsLong.isNull ? 0 : stepsLong.intValue();
return Steps(entry.key.toString().padLeft(2, '0'), steps);
}).toList();
}
}
| samples/experimental/pedometer/example/lib/steps_repo.dart/0 | {'file_path': 'samples/experimental/pedometer/example/lib/steps_repo.dart', 'repo_id': 'samples', 'token_count': 2189} |
// Copyright 2023 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class WallpapersFlow extends StatefulWidget {
const WallpapersFlow({super.key});
@override
State<WallpapersFlow> createState() => _WallpapersFlowState();
}
class _WallpapersFlowState extends State<WallpapersFlow> {
int pageNum = 0;
int numPages = 4;
@override
void initState() {
LicenseRegistry.addLicense(() => Stream<LicenseEntry>.value(
LicenseEntryWithLineBreaks(
<String>['roboto_font'],
robotoLicense,
),
));
LicenseRegistry.addLicense(() => Stream<LicenseEntry>.value(
LicenseEntryWithLineBreaks(
<String>['amstelvar_font'],
amstelvarLicense,
),
));
super.initState();
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
PageView(
onPageChanged: (value) {
setState(() {
pageNum = value;
});
},
children: const [
DecoratedBox(
decoration: BoxDecoration(
color: Colors.black,
),
child: Center(
child: Image(
image: AssetImage('assets/images/wallpaper3.png'),
fit: BoxFit.contain,
),
),
),
DecoratedBox(
decoration: BoxDecoration(
color: Colors.black,
),
child: Center(
child: Image(
image: AssetImage('assets/images/wallpaper1.png'),
fit: BoxFit.contain,
),
),
),
DecoratedBox(
decoration: BoxDecoration(
color: Colors.black,
),
child: Center(
child: Image(
image: AssetImage('assets/images/wallpaper2.png'),
fit: BoxFit.contain,
),
),
),
LicensePage(),
],
),
Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.only(bottom: 20.0),
child: Container(
width: 100,
height: 30,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: const Color.fromARGB(220, 0, 0, 0),
),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: _buildScrollDots(),
),
),
),
),
),
],
);
}
List<Widget> _buildScrollDots() {
List<Widget> dots = [];
for (int i = 0; i < numPages; i++) {
Color dotColor = i == pageNum
? const Color.fromARGB(255, 255, 255, 255)
: const Color.fromARGB(255, 105, 105, 105);
Widget d = Container(
width: 16,
height: 16,
decoration: BoxDecoration(
color: dotColor,
borderRadius: BorderRadius.circular(8.0),
border: Border.all(color: Colors.white, width: 0.5),
),
);
dots.add(d);
}
return dots;
}
final String robotoLicense = '''
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
''';
final String amstelvarLicense = '''
Copyright 2016 The Amstelvar Project Authors (info@fontbureau.com)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
''';
}
| samples/experimental/varfont_shader_puzzle/lib/page_content/wallpapers_flow.dart/0 | {'file_path': 'samples/experimental/varfont_shader_puzzle/lib/page_content/wallpapers_flow.dart', 'repo_id': 'samples', 'token_count': 5242} |
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:firebase_auth/firebase_auth.dart' hide User;
import 'package:flutter/services.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'auth.dart';
class FirebaseAuthService implements Auth {
final GoogleSignIn _googleSignIn = GoogleSignIn();
final FirebaseAuth _auth = FirebaseAuth.instance;
@override
Future<bool> get isSignedIn => _googleSignIn.isSignedIn();
@override
Future<User> signIn() async {
try {
return await _signIn();
} on PlatformException {
throw SignInException();
}
}
Future<User> _signIn() async {
GoogleSignInAccount? googleUser;
if (await isSignedIn) {
googleUser = await _googleSignIn.signInSilently();
} else {
googleUser = await _googleSignIn.signIn();
}
var googleAuth = await googleUser!.authentication;
var credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken, idToken: googleAuth.idToken);
var authResult = await _auth.signInWithCredential(credential);
return _FirebaseUser(authResult.user!.uid);
}
@override
Future<void> signOut() async {
await Future.wait([
_auth.signOut(),
_googleSignIn.signOut(),
]);
}
}
class _FirebaseUser implements User {
@override
final String uid;
_FirebaseUser(this.uid);
}
| samples/experimental/web_dashboard/lib/src/auth/firebase.dart/0 | {'file_path': 'samples/experimental/web_dashboard/lib/src/auth/firebase.dart', 'repo_id': 'samples', 'token_count': 529} |
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:web_dashboard/src/api/api.dart';
import 'package:web_dashboard/src/api/mock.dart';
void main() {
group('mock dashboard API', () {
late DashboardApi api;
setUp(() {
api = MockDashboardApi();
});
group('items', () {
test('insert', () async {
var category = await api.categories.insert(Category('Coffees Drank'));
expect(category.name, 'Coffees Drank');
});
test('delete', () async {
await api.categories.insert(Category('Coffees Drank'));
var category = await api.categories.insert(Category('Miles Ran'));
var removed = await api.categories.delete(category.id!);
expect(removed, isNotNull);
expect(removed!.name, 'Miles Ran');
var categories = await api.categories.list();
expect(categories, hasLength(1));
});
test('update', () async {
var category = await api.categories.insert(Category('Coffees Drank'));
await api.categories.update(Category('Bagels Consumed'), category.id!);
var latest = await api.categories.get(category.id!);
expect(latest, isNotNull);
expect(latest!.name, equals('Bagels Consumed'));
});
test('subscribe', () async {
var stream = api.categories.subscribe();
stream.listen(expectAsync1((x) {
expect(x, hasLength(1));
expect(x.first.name, equals('Coffees Drank'));
}, count: 1));
await api.categories.insert(Category('Coffees Drank'));
});
});
group('entry service', () {
late Category category;
DateTime dateTime = DateTime(2020, 1, 1, 30, 45);
setUp(() async {
category =
await api.categories.insert(Category('Lines of code committed'));
});
test('insert', () async {
var entry = await api.entries.insert(category.id!, Entry(1, dateTime));
expect(entry.value, 1);
expect(entry.time, dateTime);
});
test('delete', () async {
await api.entries.insert(category.id!, Entry(1, dateTime));
var entry2 = await api.entries.insert(category.id!, Entry(2, dateTime));
await api.entries.delete(category.id!, entry2.id!);
var entries = await api.entries.list(category.id!);
expect(entries, hasLength(1));
});
test('update', () async {
var entry = await api.entries.insert(category.id!, Entry(1, dateTime));
var updated = await api.entries
.update(category.id!, entry.id!, Entry(2, dateTime));
expect(updated.value, 2);
});
test('subscribe', () async {
var stream = api.entries.subscribe(category.id!);
stream.listen(expectAsync1((x) {
expect(x, hasLength(1));
expect(x.first.value, equals(1));
}, count: 1));
await api.entries.insert(category.id!, Entry(1, dateTime));
});
});
});
}
| samples/experimental/web_dashboard/test/mock_service_test.dart/0 | {'file_path': 'samples/experimental/web_dashboard/test/mock_service_test.dart', 'repo_id': 'samples', 'token_count': 1306} |
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:english_words/english_words.dart' as english_words;
import 'package:flutter/material.dart';
class FormValidationDemo extends StatefulWidget {
const FormValidationDemo({super.key});
@override
State<FormValidationDemo> createState() => _FormValidationDemoState();
}
class _FormValidationDemoState extends State<FormValidationDemo> {
final _formKey = GlobalKey<FormState>();
String? adjective;
String? noun;
bool? agreedToTerms = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('📖 Story Generator'),
actions: [
Padding(
padding: const EdgeInsets.all(8),
child: TextButton(
child: const Text('Submit'),
onPressed: () {
// Validate the form by getting the FormState from the GlobalKey
// and calling validate() on it.
var valid = _formKey.currentState!.validate();
if (!valid) {
return;
}
showDialog<void>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Your story'),
content: Text('The $adjective developer saw a $noun'),
actions: [
TextButton(
child: const Text('Done'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
),
);
},
),
),
],
),
body: Form(
key: _formKey,
child: Scrollbar(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
children: [
// A text field that validates that the text is an adjective.
TextFormField(
autofocus: true,
textInputAction: TextInputAction.next,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter an adjective.';
}
if (english_words.adjectives.contains(value)) {
return null;
}
return 'Not a valid adjective.';
},
decoration: const InputDecoration(
filled: true,
hintText: 'e.g. quick, beautiful, interesting',
labelText: 'Enter an adjective',
),
onChanged: (value) {
adjective = value;
},
),
const SizedBox(
height: 24,
),
// A text field that validates that the text is a noun.
TextFormField(
validator: (value) {
if (value!.isEmpty) {
return 'Please enter a noun.';
}
if (english_words.nouns.contains(value)) {
return null;
}
return 'Not a valid noun.';
},
decoration: const InputDecoration(
filled: true,
hintText: 'i.e. a person, place or thing',
labelText: 'Enter a noun',
),
onChanged: (value) {
noun = value;
},
),
const SizedBox(
height: 24,
),
// A custom form field that requires the user to check a
// checkbox.
FormField<bool>(
initialValue: false,
validator: (value) {
if (value == false) {
return 'You must agree to the terms of service.';
}
return null;
},
builder: (formFieldState) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Checkbox(
value: agreedToTerms,
onChanged: (value) {
// When the value of the checkbox changes,
// update the FormFieldState so the form is
// re-validated.
formFieldState.didChange(value);
setState(() {
agreedToTerms = value;
});
},
),
Text(
'I agree to the terms of service.',
style: Theme.of(context).textTheme.titleMedium,
),
],
),
if (!formFieldState.isValid)
Text(
formFieldState.errorText ?? "",
style: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(
color: Theme.of(context).colorScheme.error),
),
],
);
},
),
],
),
),
),
),
);
}
}
| samples/form_app/lib/src/validation.dart/0 | {'file_path': 'samples/form_app/lib/src/validation.dart', 'repo_id': 'samples', 'token_count': 3721} |
# Run with tooling from https://github.com/flutter/codelabs/tree/main/tooling/codelab_rebuild
name: Isolate Example rebuild script
steps:
- name: Remove runners
rmdirs:
- android
- ios
- macos
- linux
- windows
- name: Recreate runners
flutter: create --org dev.flutter --platforms android,ios,macos,linux,windows .
- name: Flutter upgrade
flutter: pub upgrade --major-versions
- name: Flutter build macOS
flutter: build macos
- name: Flutter build macOS
flutter: build ios --simulator
| samples/isolate_example/codelab_rebuild.yaml/0 | {'file_path': 'samples/isolate_example/codelab_rebuild.yaml', 'repo_id': 'samples', 'token_count': 200} |
// Copyright 2021, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
class Credentials {
final String username;
final String password;
Credentials(this.username, this.password);
}
class SignInScreen extends StatefulWidget {
final ValueChanged<Credentials> onSignIn;
const SignInScreen({
required this.onSignIn,
super.key,
});
@override
State<SignInScreen> createState() => _SignInScreenState();
}
class _SignInScreenState extends State<SignInScreen> {
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
@override
Widget build(BuildContext context) => Scaffold(
body: Center(
child: Card(
child: Container(
constraints: BoxConstraints.loose(const Size(600, 600)),
padding: const EdgeInsets.all(8),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Text('Sign in',
style: Theme.of(context).textTheme.headlineMedium),
TextField(
decoration: const InputDecoration(labelText: 'Username'),
controller: _usernameController,
),
TextField(
decoration: const InputDecoration(labelText: 'Password'),
obscureText: true,
controller: _passwordController,
),
Padding(
padding: const EdgeInsets.all(16),
child: TextButton(
onPressed: () async {
widget.onSignIn(Credentials(
_usernameController.value.text,
_passwordController.value.text));
},
child: const Text('Sign in'),
),
),
],
),
),
),
),
);
}
| samples/navigation_and_routing/lib/src/screens/sign_in.dart/0 | {'file_path': 'samples/navigation_and_routing/lib/src/screens/sign_in.dart', 'repo_id': 'samples', 'token_count': 1096} |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:platform_channels/src/add_pet_details.dart';
import 'package:platform_channels/src/event_channel_demo.dart';
import 'package:platform_channels/src/method_channel_demo.dart';
import 'package:platform_channels/src/pet_list_screen.dart';
import 'package:platform_channels/src/platform_image_demo.dart';
void main() {
runApp(const PlatformChannelSample());
}
class PlatformChannelSample extends StatelessWidget {
const PlatformChannelSample({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Platform Channel Sample',
theme: ThemeData(
snackBarTheme: SnackBarThemeData(
backgroundColor: Colors.blue[500],
),
useMaterial3: true,
),
routerConfig: router(),
);
}
}
GoRouter router([String? initialLocation]) {
return GoRouter(
initialLocation: initialLocation ?? '/',
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomePage(),
routes: [
GoRoute(
path: 'methodChannelDemo',
builder: (context, state) => const MethodChannelDemo(),
),
GoRoute(
path: 'eventChannelDemo',
builder: (context, state) => const EventChannelDemo(),
),
GoRoute(
path: 'platformImageDemo',
builder: (context, state) => const PlatformImageDemo(),
),
GoRoute(
path: 'petListScreen',
builder: (context, state) => const PetListScreen(),
routes: [
GoRoute(
path: 'addPetDetails',
builder: (context, state) => const AddPetDetails(),
),
],
),
],
),
],
);
}
class DemoInfo {
final String demoTitle;
final String demoRoute;
DemoInfo(this.demoTitle, this.demoRoute);
}
List<DemoInfo> demoList = [
DemoInfo(
'MethodChannel Demo',
'/methodChannelDemo',
),
DemoInfo(
'EventChannel Demo',
'/eventChannelDemo',
),
DemoInfo(
'Platform Image Demo',
'/platformImageDemo',
),
DemoInfo(
'BasicMessageChannel Demo',
'/petListScreen',
)
];
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Platform Channel Sample'),
),
body: ListView(
children: demoList.map((demoInfo) => DemoTile(demoInfo)).toList(),
),
);
}
}
/// This widget is responsible for displaying the [ListTile] on [HomePage].
class DemoTile extends StatelessWidget {
final DemoInfo demoInfo;
const DemoTile(this.demoInfo, {super.key});
@override
Widget build(BuildContext context) {
return ListTile(
title: Text(demoInfo.demoTitle),
onTap: () {
context.go(demoInfo.demoRoute);
},
);
}
}
| samples/platform_channels/lib/main.dart/0 | {'file_path': 'samples/platform_channels/lib/main.dart', 'repo_id': 'samples', 'token_count': 1310} |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:platform_channels/src/platform_image_demo.dart';
void main() {
group('Platform Image Demo tests', () {
testWidgets('Platform Image test', (tester) async {
tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler(
const BasicMessageChannel<dynamic>(
'platformImageDemo', StandardMessageCodec()),
(dynamic message) async {
var byteData = await rootBundle.load('assets/eat_new_orleans.jpg');
return byteData.buffer.asUint8List();
},
);
await tester.pumpWidget(const MaterialApp(
home: PlatformImageDemo(),
));
// Initially a PlaceHolder is displayed when imageData is null.
expect(find.byType(Placeholder), findsOneWidget);
expect(find.byType(Image), findsNothing);
// Tap on ElevatedButton to get Image.
await tester.tap(find.byType(FilledButton));
await tester.pumpAndSettle();
expect(find.byType(Placeholder), findsNothing);
expect(find.byType(Image), findsOneWidget);
});
});
}
| samples/platform_channels/test/src/platform_image_demo_test.dart/0 | {'file_path': 'samples/platform_channels/test/src/platform_image_demo_test.dart', 'repo_id': 'samples', 'token_count': 493} |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:provider_shopper/models/cart.dart';
import 'package:provider_shopper/models/catalog.dart';
import 'package:provider_shopper/screens/catalog.dart';
Widget createCatalogScreen() => MultiProvider(
providers: [
Provider(create: (context) => CatalogModel()),
ChangeNotifierProxyProvider<CatalogModel, CartModel>(
create: (context) => CartModel(),
update: (context, catalog, cart) {
cart!.catalog = catalog;
return cart;
},
),
],
child: const MaterialApp(
home: MyCatalog(),
),
);
void main() {
final catalogListItems = CatalogModel.itemNames.sublist(0, 3);
group('CatalogScreen Widget Tests', () {
testWidgets('Testing item row counts and text', (tester) async {
await tester.pumpWidget(createCatalogScreen());
// Testing for the items on the screen after modifying
// the model for a fixed number of items.
for (var item in catalogListItems) {
expect(find.text(item), findsWidgets);
}
});
testWidgets('Testing the ADD buttons and check after clicking',
(tester) async {
await tester.pumpWidget(createCatalogScreen());
// Should find ADD buttons on the screen.
expect(find.text('ADD'), findsWidgets);
// Performing the click on the ADD button of the first item in the list.
await tester.tap(find.widgetWithText(TextButton, 'ADD').first);
await tester.pumpAndSettle();
// Verifying if the tapped ADD button has changed to the check icon.
expect(find.byIcon(Icons.check), findsOneWidget);
});
});
}
| samples/provider_shopper/test/catalog_widget_test.dart/0 | {'file_path': 'samples/provider_shopper/test/catalog_widget_test.dart', 'repo_id': 'samples', 'token_count': 705} |
name: simple_shader
description: Using a shader, simply.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
flutter_shaders: ^0.1.0
dev_dependencies:
analysis_defaults:
path: ../analysis_defaults
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
shaders:
- shaders/simple.frag
| samples/simple_shader/pubspec.yaml/0 | {'file_path': 'samples/simple_shader/pubspec.yaml', 'repo_id': 'samples', 'token_count': 156} |
include: package:analysis_defaults/flutter.yaml
# Files under typer/ are partially completed files, and often invalid
analyzer:
exclude:
- typer/**
| samples/simplistic_calculator/analysis_options.yaml/0 | {'file_path': 'samples/simplistic_calculator/analysis_options.yaml', 'repo_id': 'samples', 'token_count': 47} |
import 'package:flutter/material.dart';
import 'app_state.dart';
import 'app_state_manager.dart';
/// The toggle buttons that can be selected.
enum ToggleButtonsState {
bold,
italic,
underline,
}
class FormattingToolbar extends StatelessWidget {
const FormattingToolbar({super.key});
@override
Widget build(BuildContext context) {
final AppStateManager manager = AppStateManager.of(context);
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ToggleButtons(
borderRadius: const BorderRadius.all(Radius.circular(4.0)),
isSelected: [
manager.appState.toggleButtonsState
.contains(ToggleButtonsState.bold),
manager.appState.toggleButtonsState
.contains(ToggleButtonsState.italic),
manager.appState.toggleButtonsState
.contains(ToggleButtonsState.underline),
],
onPressed: (index) => AppStateWidget.of(context)
.updateToggleButtonsStateOnButtonPressed(index),
children: const [
Icon(Icons.format_bold),
Icon(Icons.format_italic),
Icon(Icons.format_underline),
],
),
],
),
);
}
}
| samples/simplistic_editor/lib/formatting_toolbar.dart/0 | {'file_path': 'samples/simplistic_editor/lib/formatting_toolbar.dart', 'repo_id': 'samples', 'token_count': 636} |
// Copyright 2018 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:veggieseasons/styles.dart';
// The widgets in this file present a Cupertino-style settings item to the user.
// In the future, the Cupertino package in the Flutter SDK will include
// dedicated widgets for this purpose, but for now they're done here.
//
// See https://github.com/flutter/flutter/projects/29 for more info.
typedef SettingsItemCallback = FutureOr<void> Function();
class SettingsNavigationIndicator extends StatelessWidget {
const SettingsNavigationIndicator({super.key});
@override
Widget build(BuildContext context) {
return const Icon(
CupertinoIcons.forward,
color: Styles.settingsMediumGray,
size: 21,
);
}
}
class SettingsIcon extends StatelessWidget {
const SettingsIcon({
required this.icon,
this.foregroundColor = CupertinoColors.white,
this.backgroundColor = CupertinoColors.black,
super.key,
});
final Color backgroundColor;
final Color foregroundColor;
final IconData icon;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: backgroundColor,
),
child: Center(
child: Icon(
icon,
color: foregroundColor,
size: 20,
),
),
);
}
}
class SettingsItem extends StatefulWidget {
const SettingsItem({
required this.label,
this.icon,
this.content,
this.subtitle,
this.onPress,
super.key,
});
final String label;
final Widget? icon;
final Widget? content;
final String? subtitle;
final SettingsItemCallback? onPress;
@override
State<SettingsItem> createState() => _SettingsItemState();
}
class _SettingsItemState extends State<SettingsItem> {
bool pressed = false;
@override
Widget build(BuildContext context) {
var themeData = CupertinoTheme.of(context);
var brightness = CupertinoTheme.brightnessOf(context);
return AnimatedContainer(
duration: const Duration(milliseconds: 200),
color: Styles.settingsItemColor(brightness),
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () async {
if (widget.onPress != null) {
setState(() {
pressed = true;
});
await widget.onPress!();
Future.delayed(
const Duration(milliseconds: 150),
() {
setState(() {
pressed = false;
});
},
);
}
},
child: SizedBox(
height: widget.subtitle == null ? 44 : 57,
child: Row(
children: [
if (widget.icon != null)
Padding(
padding: const EdgeInsets.only(
left: 15,
bottom: 2,
),
child: SizedBox(
height: 29,
width: 29,
child: widget.icon,
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.only(
left: 15,
),
child: widget.subtitle != null
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 8.5),
Text(widget.label,
style: themeData.textTheme.textStyle),
const SizedBox(height: 4),
Text(
widget.subtitle!,
style: Styles.settingsItemSubtitleText(themeData),
),
],
)
: Padding(
padding: const EdgeInsets.only(top: 1.5),
child: Text(widget.label,
style: themeData.textTheme.textStyle),
),
),
),
Padding(
padding: const EdgeInsets.only(right: 11),
child: widget.content ?? Container(),
),
],
),
),
),
);
}
}
| samples/veggieseasons/lib/widgets/settings_item.dart/0 | {'file_path': 'samples/veggieseasons/lib/widgets/settings_item.dart', 'repo_id': 'samples', 'token_count': 2313} |
name: example
description: "flutter_web_startup_analyzer example"
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: '>=3.4.0-16.0.dev <4.0.0'
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.6
web_startup_analyzer:
path: ../
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.0
flutter:
uses-material-design: true
| samples/web/_packages/web_startup_analyzer/example/pubspec.yaml/0 | {'file_path': 'samples/web/_packages/web_startup_analyzer/example/pubspec.yaml', 'repo_id': 'samples', 'token_count': 180} |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file
import 'dart:io';
const ansiGreen = 32;
const ansiRed = 31;
const ansiMagenta = 35;
Future<bool> run(
String workingDir, String commandName, List<String> args) async {
var commandDescription = '`${([commandName, ...args]).join(' ')}`';
logWrapped(ansiMagenta, ' Running $commandDescription');
var proc = await Process.start(
commandName,
args,
workingDirectory: '${Directory.current.path}/$workingDir',
mode: ProcessStartMode.inheritStdio,
);
var exitCode = await proc.exitCode;
if (exitCode != 0) {
logWrapped(
ansiRed, ' Failed! ($exitCode) – $workingDir – $commandDescription');
return false;
} else {
logWrapped(ansiGreen, ' Success! – $workingDir – $commandDescription');
return true;
}
}
void logWrapped(int code, String message) {
print('\x1B[${code}m$message\x1B[0m');
}
Iterable<String> listPackageDirs(Directory dir) sync* {
if (File('${dir.path}/pubspec.yaml').existsSync()) {
yield dir.path;
} else {
for (var subDir in dir
.listSync(followLinks: true)
.whereType<Directory>()
.where((d) => !Uri.file(d.path).pathSegments.last.startsWith('.'))) {
yield* listPackageDirs(subDir);
}
}
}
| samples/web/_tool/common.dart/0 | {'file_path': 'samples/web/_tool/common.dart', 'repo_id': 'samples', 'token_count': 513} |
include: package:lints/recommended.yaml
analyzer:
exclude:
- lib/src/data.g.dart
language:
strict-casts: true
strict-inference: true
strict-raw-types: true
linter:
rules:
avoid_types_on_closure_parameters: true
avoid_void_async: true
cancel_subscriptions: true
close_sinks: true
directives_ordering: true
package_api_docs: true
package_prefixed_library_names: true
prefer_final_in_for_each: true
prefer_single_quotes: true
test_types_in_equals: true
throw_in_finally: true
unawaited_futures: true
unnecessary_statements: true
use_enums: true
use_super_parameters: true
| samples/web/samples_index/analysis_options.yaml/0 | {'file_path': 'samples/web/samples_index/analysis_options.yaml', 'repo_id': 'samples', 'token_count': 260} |
github: [felangel]
| sealed_flutter_bloc/.github/FUNDING.yml/0 | {'file_path': 'sealed_flutter_bloc/.github/FUNDING.yml', 'repo_id': 'sealed_flutter_bloc', 'token_count': 8} |
dependency_overrides:
sealed_flutter_bloc:
path: ../ | sealed_flutter_bloc/example/pubspec_overrides.yaml/0 | {'file_path': 'sealed_flutter_bloc/example/pubspec_overrides.yaml', 'repo_id': 'sealed_flutter_bloc', 'token_count': 25} |
import 'package:bloc/bloc.dart' as bloc;
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sealed_unions/sealed_unions.dart';
/// {@macro sealedblocwidgetbuilder}
typedef WidgetSealedJoin9<A, B, C, D, E, F, G, H, I> = Widget Function(
Widget Function(A) mapFirst,
Widget Function(B) mapSecond,
Widget Function(C) mapThird,
Widget Function(D) mapFourth,
Widget Function(E) mapFifth,
Widget Function(F) mapSixth,
Widget Function(G) mapSeventh,
Widget Function(H) mapEighth,
Widget Function(I) mapNinth,
);
/// {@macro sealedblocwidgetbuilder}
typedef SealedBlocWidgetBuilder9<S extends Union9<A, B, C, D, E, F, G, H, I>, A,
B, C, D, E, F, G, H, I>
= Widget Function(
BuildContext context,
WidgetSealedJoin9<A, B, C, D, E, F, G, H, I>,
);
/// {@macro sealedblocbuilder}
class SealedBlocBuilder9<
Bloc extends bloc.BlocBase<State>,
State extends Union9<A, B, C, D, E, F, G, H, I>,
A,
B,
C,
D,
E,
F,
G,
H,
I> extends BlocBuilderBase<Bloc, State> {
/// {@macro sealedblocbuilder}
const SealedBlocBuilder9({
Key? key,
required this.builder,
Bloc? bloc,
BlocBuilderCondition<State>? buildWhen,
}) : super(key: key, bloc: bloc, buildWhen: buildWhen);
/// {@macro sealedblocwidgetbuilder}
final SealedBlocWidgetBuilder9<State, A, B, C, D, E, F, G, H, I> builder;
@override
Widget build(BuildContext context, State state) =>
builder(context, state.join);
}
| sealed_flutter_bloc/lib/src/sealed_bloc_builder/sealed_bloc_builder9.dart/0 | {'file_path': 'sealed_flutter_bloc/lib/src/sealed_bloc_builder/sealed_bloc_builder9.dart', 'repo_id': 'sealed_flutter_bloc', 'token_count': 637} |
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sealed_flutter_bloc/sealed_flutter_bloc.dart';
import 'helpers/helper_bloc5.dart';
void main() {
group('SealedBlocBuilder5', () {
const targetKey1 = Key('__target1__');
const targetKey2 = Key('__target2__');
const targetKey3 = Key('__target3__');
const targetKey4 = Key('__target4__');
const targetKey5 = Key('__target5__');
testWidgets('should render properly', (tester) async {
final bloc = HelperBloc5();
await tester.pumpWidget(
SealedBlocBuilder5<HelperBloc5, HelperState5, State1, State2, State3,
State4, State5>(
bloc: bloc,
builder: (context, states) {
return states(
(first) => const SizedBox(key: targetKey1),
(second) => const SizedBox(key: targetKey2),
(third) => const SizedBox(key: targetKey3),
(fourth) => const SizedBox(key: targetKey4),
(fifth) => const SizedBox(key: targetKey5),
);
},
),
);
expect(find.byKey(targetKey1), findsOneWidget);
bloc.add(HelperEvent5.event2);
await tester.pumpAndSettle();
expect(find.byKey(targetKey2), findsOneWidget);
bloc.add(HelperEvent5.event3);
await tester.pumpAndSettle();
expect(find.byKey(targetKey3), findsOneWidget);
bloc.add(HelperEvent5.event4);
await tester.pumpAndSettle();
expect(find.byKey(targetKey4), findsOneWidget);
bloc.add(HelperEvent5.event5);
await tester.pumpAndSettle();
expect(find.byKey(targetKey5), findsOneWidget);
});
});
}
| sealed_flutter_bloc/test/sealed_bloc_builder5_test.dart/0 | {'file_path': 'sealed_flutter_bloc/test/sealed_bloc_builder5_test.dart', 'repo_id': 'sealed_flutter_bloc', 'token_count': 754} |
import 'package:flutter/material.dart';
import 'package:simple_weather/service/service.dart';
class WeatherPopulated extends StatelessWidget {
const WeatherPopulated({Key key, @required this.weather}) : super(key: key);
final Weather weather;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Stack(
children: [
const _WeatherBackground(),
Align(
alignment: const Alignment(0, -1 / 3),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
_WeatherIcon(condition: weather.condition),
Text(
weather.location,
style: theme.textTheme.headline2.copyWith(
fontWeight: FontWeight.w200,
),
),
Text(
'${weather.temperature.toStringAsPrecision(2)}°C',
style: theme.textTheme.headline3.copyWith(
fontWeight: FontWeight.bold,
),
),
],
),
),
),
],
);
}
}
class _WeatherIcon extends StatelessWidget {
const _WeatherIcon({
Key key,
@required this.condition,
}) : super(key: key);
static const _iconSize = 100.0;
final WeatherCondition condition;
@override
Widget build(BuildContext context) {
return Text(
condition.toEmoji,
style: const TextStyle(fontSize: _iconSize),
);
}
}
extension on WeatherCondition {
String get toEmoji {
switch (this) {
case WeatherCondition.clear:
return '☀️';
case WeatherCondition.rainy:
return '🌧️';
case WeatherCondition.cloudy:
return '☁️';
case WeatherCondition.snowy:
return '🌨️';
case WeatherCondition.unknown:
default:
return '❓';
}
}
}
class _WeatherBackground extends StatelessWidget {
const _WeatherBackground({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
final color = Theme.of(context).primaryColor;
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
stops: [0.25, 0.75, 0.90, 1.0],
colors: [
color,
color.brighten(10),
color.brighten(33),
color.brighten(50),
],
),
),
);
}
}
extension on Color {
Color brighten([int percent = 10]) {
assert(1 <= percent && percent <= 100);
final p = percent / 100;
return Color.fromARGB(
alpha,
red + ((255 - red) * p).round(),
green + ((255 - green) * p).round(),
blue + ((255 - blue) * p).round(),
);
}
}
| simple_weather/lib/app/weather/widgets/weather_populated.dart/0 | {'file_path': 'simple_weather/lib/app/weather/widgets/weather_populated.dart', 'repo_id': 'simple_weather', 'token_count': 1358} |
name: simple_weather
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
google_fonts: ^1.1.0
http: ^0.12.1
json_annotation: ^3.0.1
dev_dependencies:
build_runner: ^1.8.1
json_serializable: ^3.3.0
flutter:
uses-material-design: true
| simple_weather/pubspec.yaml/0 | {'file_path': 'simple_weather/pubspec.yaml', 'repo_id': 'simple_weather', 'token_count': 151} |
import 'dart:ui';
import 'package:meta/meta.dart';
abstract class Layer {
List<LayerProcessor> preProcessors = [];
List<LayerProcessor> postProcessors = [];
Picture _picture;
PictureRecorder _recorder;
Canvas _canvas;
@mustCallSuper
void render(Canvas canvas, {double x = 0.0, double y = 0.0}) {
if (_picture == null) {
return;
}
canvas.save();
canvas.translate(x, y);
preProcessors.forEach((p) => p.process(_picture, canvas));
canvas.drawPicture(_picture);
postProcessors.forEach((p) => p.process(_picture, canvas));
canvas.restore();
}
Canvas get canvas {
assert(_canvas != null,
'Layer is not ready for rendering, call beginRendering first');
return _canvas;
}
void beginRendering() {
_recorder = PictureRecorder();
_canvas = Canvas(_recorder);
}
void finishRendering() {
_picture = _recorder.endRecording();
_recorder = null;
_canvas = null;
}
void drawLayer();
}
abstract class PreRenderedLayer extends Layer {
PreRenderedLayer() {
beginRendering();
drawLayer();
finishRendering();
}
}
abstract class DynamicLayer extends Layer {
@override
void render(Canvas canvas, {double x = 0.0, double y = 0.0}) {
beginRendering();
drawLayer();
finishRendering();
super.render(canvas, x: x, y: y);
}
}
abstract class LayerProcessor {
void process(Picture pic, Canvas canvas);
}
class ShadowProcessor extends LayerProcessor {
Paint _shadowPaint;
final Offset offset;
ShadowProcessor({
this.offset = const Offset(10, 10),
double opacity = 0.9,
Color color = const Color(0xFF000000),
}) {
_shadowPaint = Paint()
..colorFilter =
ColorFilter.mode(color.withOpacity(opacity), BlendMode.srcATop);
}
@override
void process(Picture pic, Canvas canvas) {
canvas.saveLayer(Rect.largest, _shadowPaint);
canvas.translate(offset.dx, offset.dy);
canvas.drawPicture(pic);
canvas.restore();
}
}
| snake-chef/snake_chef/lib/game/layer.dart/0 | {'file_path': 'snake-chef/snake_chef/lib/game/layer.dart', 'repo_id': 'snake-chef', 'token_count': 738} |
import 'package:flutter/material.dart';
import 'package:snake_chef/settings_manager.dart';
import '../widgets/button.dart';
import '../widgets/label.dart';
import '../widgets/pattern_container.dart';
class SettingsScreen extends StatefulWidget {
@override
State createState() {
return _SettingsScreenState();
}
}
class _SettingsScreenState extends State<SettingsScreen> {
bool _isMusicEnabled;
bool _isSfxEnabled;
bool _isGamepadEnabled;
@override
void initState() {
super.initState();
_isMusicEnabled = SettingsManager.isMusicEnabled;
_isSfxEnabled = SettingsManager.isSfxEnabled;
_isGamepadEnabled = SettingsManager.gamePadOptions.enabled;
}
@override
Widget build(ctx) {
return PatternContainer(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Label(
label: 'Settings',
fontColor: Color(0xFF566c86),
fontSize: 60,
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
children: [
Expanded(
flex: 5,
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Label(
label: 'Music:',
fontSize: 42,
fontColor: Color(0xFF333c57),
),
SizedBox(height: 5),
Label(
label: 'Sounds:',
fontSize: 42,
fontColor: Color(0xFF333c57),
),
SizedBox(height: 5),
Label(
label: 'Gamepad:',
fontSize: 42,
fontColor: Color(0xFF333c57),
),
],
),
),
Expanded(
flex: 5,
child: Container(
margin: EdgeInsets.only(left: 15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Button(
buttonType: _isMusicEnabled
? ButtonType.SWITCH_ON
: ButtonType.SWITCH_OFF,
label: '${_isMusicEnabled ? 'on' : 'off'}',
width: 70,
onPressed: () {
setState(() {
_isMusicEnabled = !_isMusicEnabled;
SettingsManager.isMusicEnabled =
_isMusicEnabled;
SettingsManager.save();
});
},
),
SizedBox(height: 5),
Button(
buttonType: _isSfxEnabled
? ButtonType.SWITCH_ON
: ButtonType.SWITCH_OFF,
label: '${_isSfxEnabled ? 'on' : 'off'}',
width: 70,
onPressed: () {
setState(() {
_isSfxEnabled = !_isSfxEnabled;
SettingsManager.isSfxEnabled =
_isSfxEnabled;
SettingsManager.save();
});
},
),
SizedBox(height: 5),
Row(
children: [
Button(
buttonType: _isGamepadEnabled
? ButtonType.SWITCH_ON
: ButtonType.SWITCH_OFF,
label:
'${_isGamepadEnabled ? 'on' : 'off'}',
width: 70,
onPressed: () {
setState(() {
_isGamepadEnabled = !_isGamepadEnabled;
SettingsManager.gamePadOptions.enabled =
_isGamepadEnabled;
SettingsManager.save();
});
},
),
SizedBox(width: 10),
_isGamepadEnabled
? (Button(
buttonType: ButtonType.PLAIN,
label: 'Edit',
width: 150,
onPressed: () {
Navigator.of(ctx)
.pushNamed('/gamepad_config');
},
))
: Container(),
],
),
],
),
),
)
],
),
SizedBox(height: 5),
],
),
),
Button(
buttonType: ButtonType.PRIMARY,
label: 'Back',
onPressed: () {
Navigator.of(ctx).pushNamed('/title');
},
),
SizedBox(height: 20),
],
),
),
);
}
}
| snake-chef/snake_chef/lib/screens/settings.dart/0 | {'file_path': 'snake-chef/snake_chef/lib/screens/settings.dart', 'repo_id': 'snake-chef', 'token_count': 4630} |
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:solar_system/models/base_mesh.dart';
import 'package:solar_system/models/planet.dart';
import 'package:solar_system/params/create_planet_params.dart';
import 'package:solar_system/params/planet_ring_params.dart';
import 'package:solar_system/res/assets/textures.dart';
import 'package:three_dart/three_dart.dart' as three;
const int _sphereSegments = 30;
const int _ringSegments = 32;
const double _ringRotation = -0.5 * math.pi;
class PlanetUtil {
factory PlanetUtil() {
return _instance;
}
PlanetUtil._();
static final PlanetUtil _instance = PlanetUtil._();
static PlanetUtil get instance => _instance;
Future<Planet> initializePlanet(three.Scene scene) async {
return Planet(
mecury: await _createPlanet(
CreatePlanetParams(
size: 3.2,
texture: textureMecury,
position: 28,
),
scene,
),
venus: await _createPlanet(
CreatePlanetParams(
size: 5.8,
texture: textureVenus,
position: 44,
),
scene,
),
saturn: await _createPlanet(
CreatePlanetParams(
size: 10,
texture: textureSaturn,
position: 138,
planetRingParams: const PlanetRingParams(
innerRadius: 10,
outerRadius: 20,
texture: textureSaturnRing,
),
),
scene,
),
earth: await _createPlanet(
CreatePlanetParams(
size: 6,
texture: textureEarth,
position: 62,
),
scene,
),
jupiter: await _createPlanet(
CreatePlanetParams(
size: 12,
texture: textureJupiter,
position: 100,
),
scene,
),
mars: await _createPlanet(
CreatePlanetParams(
size: 4,
texture: textureMars,
position: 78,
),
scene,
),
uranus: await _createPlanet(
CreatePlanetParams(
size: 7,
texture: textureUranus,
position: 176,
planetRingParams: const PlanetRingParams(
innerRadius: 7,
outerRadius: 12,
texture: textureUranus,
),
),
scene,
),
neptune: await _createPlanet(
CreatePlanetParams(
size: 7,
texture: textureNeptune,
position: 200,
),
scene,
),
pluto: await _createPlanet(
CreatePlanetParams(
size: 2.8,
texture: texturePluto,
position: 216,
),
scene,
),
);
}
Future<BaseMesh> _createPlanet(
CreatePlanetParams createPlanetParams,
three.Scene scene,
) async {
final geo = three.SphereGeometry(
createPlanetParams.size,
_sphereSegments,
_sphereSegments,
);
final mecuryTextureLoader = three.TextureLoader(null);
final mat = three.MeshStandardMaterial({
'map': await mecuryTextureLoader.loadAsync(
createPlanetParams.texture,
),
});
final mesh = three.Mesh(geo, mat);
final object3d = three.Object3D()..add(mesh);
if (createPlanetParams.planetRingParams != null) {
final ring = createPlanetParams.planetRingParams;
final ringGeo = three.RingGeometry(
ring!.innerRadius,
ring.outerRadius,
_ringSegments,
);
final ringTextureLoader = three.TextureLoader(null);
final ringMat = three.MeshBasicMaterial({
'map': await ringTextureLoader.loadAsync(
ring.texture,
),
'side': three.DoubleSide,
});
final ringMesh = three.Mesh(ringGeo, ringMat);
object3d.add(ringMesh);
ringMesh.position.x = createPlanetParams.position;
ringMesh.rotation.x = _ringRotation;
}
scene.add(object3d);
mesh.position.x = createPlanetParams.position;
return BaseMesh(
mesh: mesh,
object3d: object3d,
);
}
Future<void> animate({
required Planet planet,
required three.Mesh sun,
required VoidCallback render,
}) async {
sun.rotateY(0.004);
planet.mecury?.rotateMesh(0.004);
planet.venus?.rotateMesh(0.002);
planet.earth?.rotateMesh(0.02);
planet.mars?.rotateMesh(0.018);
planet.jupiter?.rotateMesh(0.04);
planet.saturn?.rotateMesh(0.038);
planet.uranus?.rotateMesh(0.03);
planet.neptune?.rotateMesh(0.032);
planet.pluto?.rotateMesh(0.008);
///
planet.mecury?.rotateObject3D(0.04);
planet.venus?.rotateObject3D(0.015);
planet.earth?.rotateObject3D(0.01);
planet.mars?.rotateObject3D(0.008);
planet.jupiter?.rotateObject3D(0.002);
planet.saturn?.rotateObject3D(0.0009);
planet.uranus?.rotateObject3D(0.0004);
planet.neptune?.rotateObject3D(0.0001);
planet.pluto?.rotateObject3D(0.00007);
render();
Future.delayed(const Duration(milliseconds: 40), () {
animate(
planet: planet,
sun: sun,
render: render,
);
});
}
}
| solar-system/lib/utils/planet_util.dart/0 | {'file_path': 'solar-system/lib/utils/planet_util.dart', 'repo_id': 'solar-system', 'token_count': 2380} |
// Copyright (c) 2014, Google Inc. 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 '../common.dart';
part 'web_simple.g.dart';
/// A generator for a uber-simple web application.
class WebSimpleGenerator extends DefaultGenerator {
WebSimpleGenerator()
: super('web-simple', 'Bare-bones Web App',
'A web app that uses only core Dart libraries.',
categories: const ['dart', 'web']) {
for (var file in decodeConcatenatedData(_data)) {
addTemplateFile(file);
}
setEntrypoint(getFile('web/index.html'));
}
}
| stagehand/lib/src/generators/web_simple.dart/0 | {'file_path': 'stagehand/lib/src/generators/web_simple.dart', 'repo_id': 'stagehand', 'token_count': 234} |
import 'package:__projectName__/__projectName__.dart';
import 'package:test/test.dart';
void main() {
test('calculate', () {
expect(calculate(), 42);
});
}
| stagehand/templates/console-full/test/__projectName___test.dart/0 | {'file_path': 'stagehand/templates/console-full/test/__projectName___test.dart', 'repo_id': 'stagehand', 'token_count': 63} |
import 'dart:async';
import 'package:angular/core.dart';
/// Mock service emulating access to a to-do list stored on a server.
@Injectable()
class TodoListService {
List<String> mockTodoList = <String>[];
Future<List<String>> getTodoList() async => mockTodoList;
}
| stagehand/templates/web-angular/lib/src/todo_list/todo_list_service.dart/0 | {'file_path': 'stagehand/templates/web-angular/lib/src/todo_list/todo_list_service.dart', 'repo_id': 'stagehand', 'token_count': 91} |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'responses.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
SyncResponse _$SyncResponseFromJson(Map json) {
return SyncResponse()
..duration = json['duration'] as String
..events = (json['events'] as List)
?.map((e) => e == null
? null
: Event.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList();
}
QueryChannelsResponse _$QueryChannelsResponseFromJson(Map json) {
return QueryChannelsResponse()
..duration = json['duration'] as String
..channels = (json['channels'] as List)
?.map((e) => e == null ? null : ChannelState.fromJson(e as Map))
?.toList();
}
TranslateMessageResponse _$TranslateMessageResponseFromJson(Map json) {
return TranslateMessageResponse()
..duration = json['duration'] as String
..message = json['message'] == null
? null
: TranslatedMessage.fromJson((json['message'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
));
}
QueryMembersResponse _$QueryMembersResponseFromJson(Map json) {
return QueryMembersResponse()
..duration = json['duration'] as String
..members = (json['members'] as List)
?.map((e) => e == null
? null
: Member.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList();
}
QueryUsersResponse _$QueryUsersResponseFromJson(Map json) {
return QueryUsersResponse()
..duration = json['duration'] as String
..users = (json['users'] as List)
?.map((e) => e == null
? null
: User.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList();
}
QueryReactionsResponse _$QueryReactionsResponseFromJson(Map json) {
return QueryReactionsResponse()
..duration = json['duration'] as String
..reactions = (json['reactions'] as List)
?.map((e) => e == null
? null
: Reaction.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList();
}
QueryRepliesResponse _$QueryRepliesResponseFromJson(Map json) {
return QueryRepliesResponse()
..duration = json['duration'] as String
..messages = (json['messages'] as List)
?.map((e) => e == null
? null
: Message.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList();
}
ListDevicesResponse _$ListDevicesResponseFromJson(Map json) {
return ListDevicesResponse()
..duration = json['duration'] as String
..devices = (json['devices'] as List)
?.map((e) => e == null
? null
: Device.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList();
}
SendFileResponse _$SendFileResponseFromJson(Map json) {
return SendFileResponse()
..duration = json['duration'] as String
..file = json['file'] as String;
}
SendImageResponse _$SendImageResponseFromJson(Map json) {
return SendImageResponse()
..duration = json['duration'] as String
..file = json['file'] as String;
}
SendReactionResponse _$SendReactionResponseFromJson(Map json) {
return SendReactionResponse()
..duration = json['duration'] as String
..message = json['message'] == null
? null
: Message.fromJson((json['message'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
))
..reaction = json['reaction'] == null
? null
: Reaction.fromJson((json['reaction'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
));
}
ConnectGuestUserResponse _$ConnectGuestUserResponseFromJson(Map json) {
return ConnectGuestUserResponse()
..duration = json['duration'] as String
..accessToken = json['access_token'] as String
..user = json['user'] == null
? null
: User.fromJson((json['user'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
));
}
UpdateUsersResponse _$UpdateUsersResponseFromJson(Map json) {
return UpdateUsersResponse()
..duration = json['duration'] as String
..users = (json['users'] as Map)?.map(
(k, e) => MapEntry(
k as String,
e == null
? null
: User.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
))),
);
}
UpdateMessageResponse _$UpdateMessageResponseFromJson(Map json) {
return UpdateMessageResponse()
..duration = json['duration'] as String
..message = json['message'] == null
? null
: Message.fromJson((json['message'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
));
}
SendMessageResponse _$SendMessageResponseFromJson(Map json) {
return SendMessageResponse()
..duration = json['duration'] as String
..message = json['message'] == null
? null
: Message.fromJson((json['message'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
));
}
GetMessageResponse _$GetMessageResponseFromJson(Map json) {
return GetMessageResponse()
..duration = json['duration'] as String
..message = json['message'] == null
? null
: Message.fromJson((json['message'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
))
..channel = json['channel'] == null
? null
: ChannelModel.fromJson((json['channel'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
));
}
SearchMessagesResponse _$SearchMessagesResponseFromJson(Map json) {
return SearchMessagesResponse()
..duration = json['duration'] as String
..results = (json['results'] as List)
?.map((e) => e == null ? null : GetMessageResponse.fromJson(e as Map))
?.toList();
}
GetMessagesByIdResponse _$GetMessagesByIdResponseFromJson(Map json) {
return GetMessagesByIdResponse()
..duration = json['duration'] as String
..messages = (json['messages'] as List)
?.map((e) => e == null
? null
: Message.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList();
}
UpdateChannelResponse _$UpdateChannelResponseFromJson(Map json) {
return UpdateChannelResponse()
..duration = json['duration'] as String
..channel = json['channel'] == null
? null
: ChannelModel.fromJson((json['channel'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
))
..members = (json['members'] as List)
?.map((e) => e == null
? null
: Member.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList()
..message = json['message'] == null
? null
: Message.fromJson((json['message'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
));
}
PartialUpdateChannelResponse _$PartialUpdateChannelResponseFromJson(Map json) {
return PartialUpdateChannelResponse()
..duration = json['duration'] as String
..channel = json['channel'] == null
? null
: ChannelModel.fromJson((json['channel'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
))
..members = (json['members'] as List)
?.map((e) => e == null
? null
: Member.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList();
}
InviteMembersResponse _$InviteMembersResponseFromJson(Map json) {
return InviteMembersResponse()
..duration = json['duration'] as String
..channel = json['channel'] == null
? null
: ChannelModel.fromJson((json['channel'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
))
..members = (json['members'] as List)
?.map((e) => e == null
? null
: Member.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList()
..message = json['message'] == null
? null
: Message.fromJson((json['message'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
));
}
RemoveMembersResponse _$RemoveMembersResponseFromJson(Map json) {
return RemoveMembersResponse()
..duration = json['duration'] as String
..channel = json['channel'] == null
? null
: ChannelModel.fromJson((json['channel'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
))
..members = (json['members'] as List)
?.map((e) => e == null
? null
: Member.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList()
..message = json['message'] == null
? null
: Message.fromJson((json['message'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
));
}
SendActionResponse _$SendActionResponseFromJson(Map json) {
return SendActionResponse()
..duration = json['duration'] as String
..message = json['message'] == null
? null
: Message.fromJson((json['message'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
));
}
AddMembersResponse _$AddMembersResponseFromJson(Map json) {
return AddMembersResponse()
..duration = json['duration'] as String
..channel = json['channel'] == null
? null
: ChannelModel.fromJson((json['channel'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
))
..members = (json['members'] as List)
?.map((e) => e == null
? null
: Member.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList()
..message = json['message'] == null
? null
: Message.fromJson((json['message'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
));
}
AcceptInviteResponse _$AcceptInviteResponseFromJson(Map json) {
return AcceptInviteResponse()
..duration = json['duration'] as String
..channel = json['channel'] == null
? null
: ChannelModel.fromJson((json['channel'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
))
..members = (json['members'] as List)
?.map((e) => e == null
? null
: Member.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList()
..message = json['message'] == null
? null
: Message.fromJson((json['message'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
));
}
RejectInviteResponse _$RejectInviteResponseFromJson(Map json) {
return RejectInviteResponse()
..duration = json['duration'] as String
..channel = json['channel'] == null
? null
: ChannelModel.fromJson((json['channel'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
))
..members = (json['members'] as List)
?.map((e) => e == null
? null
: Member.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList()
..message = json['message'] == null
? null
: Message.fromJson((json['message'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
));
}
EmptyResponse _$EmptyResponseFromJson(Map json) {
return EmptyResponse()..duration = json['duration'] as String;
}
ChannelStateResponse _$ChannelStateResponseFromJson(Map json) {
return ChannelStateResponse()
..duration = json['duration'] as String
..channel = json['channel'] == null
? null
: ChannelModel.fromJson((json['channel'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
))
..messages = (json['messages'] as List)
?.map((e) => e == null
? null
: Message.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList()
..members = (json['members'] as List)
?.map((e) => e == null
? null
: Member.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList()
..watcherCount = json['watcher_count'] as int
..read = (json['read'] as List)
?.map((e) => e == null
? null
: Read.fromJson((e as Map)?.map(
(k, e) => MapEntry(k as String, e),
)))
?.toList();
}
| stream-chat-flutter/packages/stream_chat/lib/src/api/responses.g.dart/0 | {'file_path': 'stream-chat-flutter/packages/stream_chat/lib/src/api/responses.g.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 5794} |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'action.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Action _$ActionFromJson(Map json) {
return Action(
name: json['name'] as String,
style: json['style'] as String,
text: json['text'] as String,
type: json['type'] as String,
value: json['value'] as String,
);
}
Map<String, dynamic> _$ActionToJson(Action instance) => <String, dynamic>{
'name': instance.name,
'style': instance.style,
'text': instance.text,
'type': instance.type,
'value': instance.value,
};
| stream-chat-flutter/packages/stream_chat/lib/src/models/action.g.dart/0 | {'file_path': 'stream-chat-flutter/packages/stream_chat/lib/src/models/action.g.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 230} |
import 'package:json_annotation/json_annotation.dart';
import 'package:stream_chat/src/models/channel_model.dart';
import 'package:stream_chat/src/models/message.dart';
import 'package:stream_chat/src/models/serialization.dart';
import 'package:stream_chat/stream_chat.dart';
part 'event.g.dart';
/// The class that contains the information about an event
@JsonSerializable()
class Event {
/// Constructor used for json serialization
Event({
this.type,
this.cid,
this.connectionId,
this.createdAt,
this.me,
this.user,
this.message,
this.totalUnreadCount,
this.unreadChannels,
this.reaction,
this.online,
this.channel,
this.member,
this.channelId,
this.channelType,
this.parentId,
this.extraData,
}) : isLocal = true;
/// Create a new instance from a json
factory Event.fromJson(Map<String, dynamic> json) =>
_$EventFromJson(Serialization.moveToExtraDataFromRoot(
json,
topLevelFields,
))
..isLocal = false;
/// The type of the event
/// [EventType] contains some predefined constant types
final String type;
/// The channel cid to which the event belongs
final String cid;
/// The channel id to which the event belongs
final String channelId;
/// The channel type to which the event belongs
final String channelType;
/// The connection id in which the event has been sent
final String connectionId;
/// The date of creation of the event
final DateTime createdAt;
/// User object of the health check user
final OwnUser me;
/// User object of the current user
final User user;
/// The message sent with the event
final Message message;
/// The channel sent with the event
final EventChannel channel;
/// The member sent with the event
final Member member;
/// The reaction sent with the event
final Reaction reaction;
/// The number of unread messages for current user
final int totalUnreadCount;
/// User total unread channels
final int unreadChannels;
/// Online status
final bool online;
/// The id of the parent message of a thread
final String parentId;
/// True if the event is generated by this client
bool isLocal;
/// Map of custom channel extraData
@JsonKey(includeIfNull: false)
final Map<String, dynamic> extraData;
/// Known top level fields.
/// Useful for [Serialization] methods.
static final topLevelFields = [
'type',
'cid',
'connection_id',
'created_at',
'me',
'user',
'message',
'total_unread_count',
'unread_channels',
'reaction',
'online',
'channel',
'member',
'channel_id',
'channel_type',
'parent_id',
'is_local',
];
/// Serialize to json
Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot(
_$EventToJson(this),
topLevelFields,
);
}
/// The channel embedded in the event object
@JsonSerializable()
class EventChannel extends ChannelModel {
/// Constructor used for json serialization
EventChannel({
this.members,
String id,
String type,
String cid,
ChannelConfig config,
User createdBy,
bool frozen,
DateTime lastMessageAt,
DateTime createdAt,
DateTime updatedAt,
DateTime deletedAt,
int memberCount,
Map<String, dynamic> extraData,
}) : super(
id: id,
type: type,
cid: cid,
config: config,
createdBy: createdBy,
frozen: frozen,
lastMessageAt: lastMessageAt,
createdAt: createdAt,
updatedAt: updatedAt,
deletedAt: deletedAt,
memberCount: memberCount,
extraData: extraData,
);
/// Create a new instance from a json
factory EventChannel.fromJson(Map<String, dynamic> json) =>
_$EventChannelFromJson(Serialization.moveToExtraDataFromRoot(
json,
topLevelFields,
));
/// A paginated list of channel members
final List<Member> members;
/// Known top level fields.
/// Useful for [Serialization] methods.
static final topLevelFields = [
'members',
...ChannelModel.topLevelFields,
];
/// Serialize to json
@override
Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot(
_$EventChannelToJson(this),
topLevelFields,
);
}
| stream-chat-flutter/packages/stream_chat/lib/src/models/event.dart/0 | {'file_path': 'stream-chat-flutter/packages/stream_chat/lib/src/models/event.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 1550} |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'user.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
User _$UserFromJson(Map json) {
return User(
id: json['id'] as String,
role: json['role'] as String,
createdAt: json['created_at'] == null
? null
: DateTime.parse(json['created_at'] as String),
updatedAt: json['updated_at'] == null
? null
: DateTime.parse(json['updated_at'] as String),
lastActive: json['last_active'] == null
? null
: DateTime.parse(json['last_active'] as String),
online: json['online'] as bool,
extraData: (json['extra_data'] as Map)?.map(
(k, e) => MapEntry(k as String, e),
),
banned: json['banned'] as bool,
teams: (json['teams'] as List)?.map((e) => e as String)?.toList(),
);
}
Map<String, dynamic> _$UserToJson(User instance) {
final val = <String, dynamic>{
'id': instance.id,
};
void writeNotNull(String key, dynamic value) {
if (value != null) {
val[key] = value;
}
}
writeNotNull('role', readonly(instance.role));
writeNotNull('teams', readonly(instance.teams));
writeNotNull('created_at', readonly(instance.createdAt));
writeNotNull('updated_at', readonly(instance.updatedAt));
writeNotNull('last_active', readonly(instance.lastActive));
writeNotNull('online', readonly(instance.online));
writeNotNull('banned', readonly(instance.banned));
writeNotNull('extra_data', instance.extraData);
return val;
}
| stream-chat-flutter/packages/stream_chat/lib/src/models/user.g.dart/0 | {'file_path': 'stream-chat-flutter/packages/stream_chat/lib/src/models/user.g.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 572} |
import 'package:stream_chat/src/models/attachment.dart';
import 'package:stream_chat/src/models/action.dart';
import 'dart:convert';
import 'package:test/test.dart';
void main() {
group('src/models/attachment', () {
const jsonExample = r'''{
"type": "giphy",
"title": "awesome",
"title_link": "https://giphy.com/gifs/nrkp3-dance-happy-3o7TKnCdBx5cMg0qti",
"thumb_url": "https://media0.giphy.com/media/3o7TKnCdBx5cMg0qti/giphy.gif",
"actions": [
{
"name": "image_action",
"text": "Send",
"style": "primary",
"type": "button",
"value": "send"
},
{
"name": "image_action",
"text": "Shuffle",
"style": "default",
"type": "button",
"value": "shuffle"
},
{
"name": "image_action",
"text": "Cancel",
"style": "default",
"type": "button",
"value": "cancel"
}
]
}''';
test('should parse json correctly', () {
final attachment = Attachment.fromJson(json.decode(jsonExample));
expect(attachment.type, "giphy");
expect(attachment.title, "awesome");
expect(attachment.titleLink,
"https://giphy.com/gifs/nrkp3-dance-happy-3o7TKnCdBx5cMg0qti");
expect(attachment.thumbUrl,
"https://media0.giphy.com/media/3o7TKnCdBx5cMg0qti/giphy.gif");
expect(attachment.actions, hasLength(3));
expect(attachment.actions[0], isA<Action>());
});
test('should serialize to json correctly', () {
final channel = Attachment(
type: "image",
title: "soo",
titleLink:
"https://giphy.com/gifs/nrkp3-dance-happy-3o7TKnCdBx5cMg0qti");
expect(
channel.toJson(),
{
'type': 'image',
'title': 'soo',
'title_link':
'https://giphy.com/gifs/nrkp3-dance-happy-3o7TKnCdBx5cMg0qti'
},
);
});
});
}
| stream-chat-flutter/packages/stream_chat/test/src/models/attachment_test.dart/0 | {'file_path': 'stream-chat-flutter/packages/stream_chat/test/src/models/attachment_test.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 920} |
import 'package:flutter/material.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'attachment/attachment.dart';
class ChannelFileDisplayScreen extends StatefulWidget {
/// The sorting used for the channels matching the filters.
/// Sorting is based on field and direction, multiple sorting options can be provided.
/// You can sort based on last_updated, last_message_at, updated_at, created_at or member_count.
/// Direction can be ascending or descending.
final List<SortOption> sortOptions;
/// Pagination parameters
/// limit: the number of users to return (max is 30)
/// offset: the offset (max is 1000)
/// message_limit: how many messages should be included to each channel
final PaginationParams paginationParams;
/// The builder used when the file list is empty.
final WidgetBuilder emptyBuilder;
const ChannelFileDisplayScreen({
this.sortOptions,
this.paginationParams,
this.emptyBuilder,
});
@override
_ChannelFileDisplayScreenState createState() =>
_ChannelFileDisplayScreenState();
}
class _ChannelFileDisplayScreenState extends State<ChannelFileDisplayScreen> {
@override
void initState() {
super.initState();
final messageSearchBloc = MessageSearchBloc.of(context);
messageSearchBloc.search(
filter: {
'cid': {
r'$in': [StreamChannel.of(context).channel.cid]
}
},
messageFilter: {
'attachments.type': {
r'$in': ['file'],
},
},
sort: widget.sortOptions,
pagination: widget.paginationParams,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: StreamChatTheme.of(context).colorTheme.white,
appBar: AppBar(
brightness: Theme.of(context).brightness,
elevation: 1,
centerTitle: true,
title: Text(
'Files',
style: TextStyle(
color: StreamChatTheme.of(context).colorTheme.black,
fontSize: 16.0),
),
leading: Center(
child: InkWell(
onTap: () {
Navigator.of(context).pop();
},
child: Container(
width: 24.0,
height: 24.0,
child: StreamSvgIcon.left(
color: StreamChatTheme.of(context).colorTheme.black,
size: 24.0,
),
),
),
),
backgroundColor: StreamChatTheme.of(context).colorTheme.white,
),
body: _buildMediaGrid(),
);
}
Widget _buildMediaGrid() {
final messageSearchBloc = MessageSearchBloc.of(context);
return StreamBuilder<List<GetMessageResponse>>(
builder: (context, snapshot) {
if (snapshot.data == null) {
return Center(
child: const CircularProgressIndicator(),
);
}
if (snapshot.data.isEmpty) {
if (widget.emptyBuilder != null) {
return widget.emptyBuilder(context);
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
StreamSvgIcon.files(
size: 136.0,
color: StreamChatTheme.of(context).colorTheme.greyGainsboro,
),
SizedBox(height: 16.0),
Text(
'No Files',
style: TextStyle(
fontSize: 14.0,
color: StreamChatTheme.of(context).colorTheme.black,
),
),
SizedBox(height: 8.0),
Text(
'Files sent in this chat will appear here',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14.0,
color: StreamChatTheme.of(context)
.colorTheme
.black
.withOpacity(0.5),
),
),
],
),
);
}
final media = <Attachment, Message>{};
for (var item in snapshot.data) {
item.message.attachments.where((e) => e.type == 'file').forEach((e) {
media[e] = item.message;
});
}
return LazyLoadScrollView(
onEndOfPage: () => messageSearchBloc.loadMore(
filter: {
'cid': {
r'$in': [StreamChannel.of(context).channel.cid]
}
},
messageFilter: {
'attachments.type': {
r'$in': ['file']
},
},
sort: widget.sortOptions,
pagination: widget.paginationParams.copyWith(
offset: messageSearchBloc.messageResponses?.length ?? 0,
),
),
child: ListView.builder(
itemBuilder: (context, position) {
return Padding(
padding: const EdgeInsets.all(1.0),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: FileAttachment(
message: media.values.toList()[position],
attachment: media.keys.toList()[position],
),
),
);
},
itemCount: media.length,
),
);
},
stream: messageSearchBloc.messagesStream,
);
}
}
| stream-chat-flutter/packages/stream_chat_flutter/lib/src/channel_file_display_screen.dart/0 | {'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/lib/src/channel_file_display_screen.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 2758} |
import 'dart:async';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:share_plus/share_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:stream_chat_flutter/src/stream_chat_theme.dart';
import 'package:stream_chat_flutter/src/video_thumbnail_image.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart';
class ImageFooter extends StatefulWidget implements PreferredSizeWidget {
/// Callback to call when pressing the back button.
/// By default it calls [Navigator.pop]
final VoidCallback onBackPressed;
/// Callback to call when the header is tapped.
final VoidCallback onTitleTap;
/// Callback to call when the image is tapped.
final VoidCallback onImageTap;
final int currentPage;
final int totalPages;
final List<Attachment> mediaAttachments;
final Message message;
final ValueChanged<int> mediaSelectedCallBack;
/// Creates a channel header
ImageFooter({
Key key,
this.onBackPressed,
this.onTitleTap,
this.onImageTap,
this.currentPage = 0,
this.totalPages = 0,
this.mediaAttachments,
this.message,
this.mediaSelectedCallBack,
}) : preferredSize = Size.fromHeight(kToolbarHeight),
super(key: key);
@override
_ImageFooterState createState() => _ImageFooterState();
@override
final Size preferredSize;
}
class _ImageFooterState extends State<ImageFooter> {
TextEditingController _searchController;
final TextEditingController _messageController = TextEditingController();
final FocusNode _messageFocusNode = FocusNode();
final List<Channel> _selectedChannels = [];
Function modalSetStateCallback;
@override
void initState() {
super.initState();
_messageFocusNode.addListener(() {
setState(() {});
});
}
@override
void dispose() {
_searchController?.clear();
_searchController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SizedBox.fromSize(
size: Size(
MediaQuery.of(context).size.width,
MediaQuery.of(context).padding.bottom + widget.preferredSize.height,
),
child: MediaQuery.removePadding(
context: context,
removeTop: true,
child: BottomAppBar(
color: StreamChatTheme.of(context).colorTheme.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
kIsWeb
? SizedBox()
: IconButton(
icon: StreamSvgIcon.iconShare(
size: 24.0,
color: StreamChatTheme.of(context).colorTheme.black,
),
onPressed: () async {
final attachment =
widget.mediaAttachments[widget.currentPage];
final url = attachment.imageUrl ??
attachment.assetUrl ??
attachment.thumbUrl;
final type = attachment.type == 'image'
? 'jpg'
: url?.split('?')?.first?.split('.')?.last ?? 'jpg';
final request =
await HttpClient().getUrl(Uri.parse(url));
final response = await request.close();
final bytes =
await consolidateHttpClientResponseBytes(response);
final tmpPath = await getTemporaryDirectory();
final filePath =
'${tmpPath.path}/${attachment.id}.$type';
final file = File(filePath);
await file.writeAsBytes(bytes);
await Share.shareFiles(
[filePath],
mimeTypes: [
'image/$type',
],
);
},
),
InkWell(
onTap: widget.onTitleTap,
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
'${widget.currentPage + 1} of ${widget.totalPages}',
style:
StreamChatTheme.of(context).textTheme.headlineBold,
),
],
),
),
),
IconButton(
icon: StreamSvgIcon.iconGrid(
color: StreamChatTheme.of(context).colorTheme.black,
),
onPressed: () => _showPhotosModal(context),
),
],
),
),
),
);
}
void _showPhotosModal(context) {
showModalBottomSheet(
context: context,
barrierColor: StreamChatTheme.of(context).colorTheme.overlay,
backgroundColor: StreamChatTheme.of(context).colorTheme.white,
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(16.0),
topRight: Radius.circular(16.0),
),
),
builder: (context) {
final crossAxisCount = 3;
final noOfRowToShowInitially =
widget.mediaAttachments.length > crossAxisCount ? 2 : 1;
final size = MediaQuery.of(context).size;
final initialChildSize =
48 + (size.width * noOfRowToShowInitially) / crossAxisCount;
return DraggableScrollableSheet(
expand: false,
initialChildSize: initialChildSize / size.height,
minChildSize: initialChildSize / size.height,
builder: (context, scrollController) {
return SingleChildScrollView(
controller: scrollController,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Stack(
children: [
Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
'Photos',
style: StreamChatTheme.of(context)
.textTheme
.headlineBold,
),
),
),
Align(
alignment: Alignment.centerRight,
child: IconButton(
icon: StreamSvgIcon.close(
color: StreamChatTheme.of(context).colorTheme.black,
),
onPressed: () => Navigator.maybePop(context),
),
),
],
),
Flexible(
child: GridView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: widget.mediaAttachments.length,
padding: const EdgeInsets.all(1),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: crossAxisCount,
mainAxisSpacing: 2.0,
crossAxisSpacing: 2.0,
),
itemBuilder: (context, index) {
Widget media;
final attachment = widget.mediaAttachments[index];
if (attachment.type == 'video') {
media = InkWell(
onTap: () => widget.mediaSelectedCallBack(index),
child: FittedBox(
fit: BoxFit.cover,
child: VideoThumbnailImage(
video: attachment.file?.path ??
attachment.assetUrl,
),
),
);
} else {
media = InkWell(
onTap: () => widget.mediaSelectedCallBack(index),
child: AspectRatio(
aspectRatio: 1.0,
child: CachedNetworkImage(
imageUrl: attachment.imageUrl ??
attachment.assetUrl ??
attachment.thumbUrl,
fit: BoxFit.cover,
),
),
);
}
return Stack(
children: [
media,
Padding(
padding: EdgeInsets.all(8.0),
child: Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.white.withOpacity(0.6),
boxShadow: [
BoxShadow(
blurRadius: 8.0,
color: StreamChatTheme.of(context)
.colorTheme
.black
.withOpacity(0.3),
),
],
),
padding: const EdgeInsets.all(2),
child: UserAvatar(
user: widget.message.user,
constraints:
BoxConstraints.tight(Size(24, 24)),
showOnlineStatus: false,
),
),
),
],
);
},
),
),
],
),
);
},
);
},
);
}
/// Sends the current message
Future sendMessage() async {
var text = _messageController.text.trim();
final attachments = widget.message.attachments;
_messageController.clear();
for (var channel in _selectedChannels) {
final message = Message(
text: text,
attachments: [attachments[widget.currentPage]],
);
await channel.sendMessage(message);
}
_selectedChannels.clear();
Navigator.pop(context);
}
}
/// Used for clipping textfield prefix icon
class IconClipper extends CustomClipper<Path> {
@override
Path getClip(Size size) {
var leftX = size.width / 5;
var rightX = 4 * size.width / 5;
var topY = size.height / 5;
var bottomY = 4 * size.height / 5;
final path = Path();
path.moveTo(leftX, topY);
path.lineTo(leftX, bottomY);
path.lineTo(rightX, bottomY);
path.lineTo(rightX, topY);
path.lineTo(leftX, topY);
path.lineTo(0.0, 0.0);
path.close();
return path;
}
@override
bool shouldReclip(CustomClipper oldClipper) {
return false;
}
}
| stream-chat-flutter/packages/stream_chat_flutter/lib/src/image_footer.dart/0 | {'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/lib/src/image_footer.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 6859} |
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:stream_chat_flutter/src/reaction_icon.dart';
import 'package:stream_chat_flutter/src/stream_svg_icon.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
class ReactionBubble extends StatelessWidget {
const ReactionBubble({
Key key,
@required this.reactions,
@required this.borderColor,
@required this.backgroundColor,
@required this.maskColor,
this.reverse = false,
this.flipTail = false,
this.highlightOwnReactions = true,
this.tailCirclesSpacing = 0,
}) : super(key: key);
final List<Reaction> reactions;
final Color borderColor;
final Color backgroundColor;
final Color maskColor;
final bool reverse;
final bool flipTail;
final bool highlightOwnReactions;
final double tailCirclesSpacing;
@override
Widget build(BuildContext context) {
final reactionIcons = StreamChatTheme.of(context).reactionIcons;
final totalReactions = reactions.length;
final offset = totalReactions > 1 ? 16.0 : 2.0;
return Transform(
transform: Matrix4.rotationY(reverse ? pi : 0),
alignment: Alignment.center,
child: Stack(
alignment: Alignment.center,
children: [
Transform.translate(
offset: Offset(reverse ? offset : -offset, 0),
child: Container(
padding: const EdgeInsets.all(2),
decoration: BoxDecoration(
color: maskColor,
borderRadius: BorderRadius.all(Radius.circular(16)),
),
child: Container(
padding: EdgeInsets.symmetric(
vertical: 4,
horizontal: totalReactions > 1 ? 4 : 0,
),
decoration: BoxDecoration(
border: Border.all(
color: borderColor,
),
color: backgroundColor,
borderRadius: BorderRadius.all(Radius.circular(14)),
),
child: LayoutBuilder(
builder: (context, constraints) {
return Flex(
direction: Axis.horizontal,
mainAxisSize: MainAxisSize.min,
children: [
if (constraints.maxWidth < double.infinity)
...reactions
.take((constraints.maxWidth) ~/ 24)
.map((reaction) {
return _buildReaction(
reactionIcons,
reaction,
context,
);
}).toList(),
if (constraints.maxWidth == double.infinity)
...reactions.map((reaction) {
return _buildReaction(
reactionIcons,
reaction,
context,
);
}).toList(),
],
);
},
),
),
),
),
Positioned(
bottom: 2,
left: reverse ? null : 13,
right: !reverse ? null : 13,
child: _buildReactionsTail(context),
),
],
),
);
}
Widget _buildReaction(
List<ReactionIcon> reactionIcons,
Reaction reaction,
BuildContext context,
) {
final reactionIcon = reactionIcons.firstWhere(
(r) => r.type == reaction.type,
orElse: () => null,
);
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 4.0,
),
child: reactionIcon != null
? StreamSvgIcon(
assetName: reactionIcon.assetName,
width: 16,
height: 16,
color: (!highlightOwnReactions ||
reaction.user.id == StreamChat.of(context).user.id)
? StreamChatTheme.of(context).colorTheme.accentBlue
: StreamChatTheme.of(context)
.colorTheme
.black
.withOpacity(.5),
)
: Icon(
Icons.help_outline_rounded,
size: 16,
color: (!highlightOwnReactions ||
reaction.user.id == StreamChat.of(context).user.id)
? StreamChatTheme.of(context).colorTheme.accentBlue
: StreamChatTheme.of(context)
.colorTheme
.black
.withOpacity(.5),
),
);
}
Widget _buildReactionsTail(BuildContext context) {
final tail = CustomPaint(
painter: ReactionBubblePainter(
backgroundColor,
borderColor,
maskColor,
tailCirclesSpace: tailCirclesSpacing,
),
);
return Transform(
transform: Matrix4.rotationY(flipTail ? 0 : pi),
alignment: Alignment.center,
child: tail,
);
}
}
class ReactionBubblePainter extends CustomPainter {
final Color color;
final Color borderColor;
final Color maskColor;
final double tailCirclesSpace;
ReactionBubblePainter(
this.color,
this.borderColor,
this.maskColor, {
this.tailCirclesSpace = 0,
});
@override
void paint(Canvas canvas, Size size) {
_drawOvalMask(size, canvas);
_drawMask(size, canvas);
_drawOval(size, canvas);
_drawOvalBorder(size, canvas);
_drawArc(size, canvas);
_drawBorder(size, canvas);
}
void _drawOvalMask(Size size, Canvas canvas) {
final paint = Paint()
..color = maskColor
..style = PaintingStyle.fill;
final path = Path();
path.addOval(
Rect.fromCircle(
center: Offset(4, 3) + Offset(tailCirclesSpace, tailCirclesSpace),
radius: 4,
),
);
canvas.drawPath(path, paint);
}
void _drawOvalBorder(Size size, Canvas canvas) {
final paint = Paint()
..color = borderColor
..strokeWidth = 1
..style = PaintingStyle.stroke;
final path = Path();
path.addOval(
Rect.fromCircle(
center: Offset(4, 3) + Offset(tailCirclesSpace, tailCirclesSpace),
radius: 2,
),
);
canvas.drawPath(path, paint);
}
void _drawOval(Size size, Canvas canvas) {
final paint = Paint()
..color = color
..strokeWidth = 1;
final path = Path();
path.addOval(Rect.fromCircle(
center: Offset(4, 3) + Offset(tailCirclesSpace, tailCirclesSpace),
radius: 2,
));
canvas.drawPath(path, paint);
}
void _drawBorder(Size size, Canvas canvas) {
final paint = Paint()
..color = borderColor
..strokeWidth = 1
..style = PaintingStyle.stroke;
final dy = -2.2;
final startAngle = 1.1;
final sweepAngle = 1.2;
final path = Path();
path.addArc(
Rect.fromCircle(
center: Offset(1, dy),
radius: 4,
),
-pi * startAngle,
-pi / sweepAngle,
);
canvas.drawPath(path, paint);
}
void _drawArc(Size size, Canvas canvas) {
final paint = Paint()
..color = color
..strokeWidth = 1;
final dy = -2.2;
final startAngle = 1;
final sweepAngle = 1.3;
final path = Path();
path.addArc(
Rect.fromCircle(
center: Offset(1, dy),
radius: 4,
),
-pi * startAngle,
-pi * sweepAngle,
);
canvas.drawPath(path, paint);
}
void _drawMask(Size size, Canvas canvas) {
final paint = Paint()
..color = maskColor
..strokeWidth = 1
..style = PaintingStyle.fill;
final dy = -2.2;
final startAngle = 1.1;
final sweepAngle = 1.2;
final path = Path();
path.addArc(
Rect.fromCircle(
center: Offset(1, dy),
radius: 6,
),
-pi * startAngle,
-pi / sweepAngle,
);
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
| stream-chat-flutter/packages/stream_chat_flutter/lib/src/reaction_bubble.dart/0 | {'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/lib/src/reaction_bubble.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 4101} |
import 'package:flutter/material.dart';
import 'package:jiffy/jiffy.dart';
import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart';
import 'package:stream_chat_flutter/src/stream_svg_icon.dart';
import 'package:stream_chat_flutter/src/user_list_view.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'stream_chat_theme.dart';
///
/// It shows the current [User] preview.
///
/// The widget uses a [StreamBuilder] to render the user information image as soon as it updates.
///
/// Usually you don't use this widget as it's the default user preview used by [UserListView].
///
/// The widget renders the ui based on the first ancestor of type [StreamChatTheme].
/// Modify it to change the widget appearance.
class UserItem extends StatelessWidget {
/// Instantiate a new UserItem
const UserItem({
Key key,
@required this.user,
this.onTap,
this.onLongPress,
this.onImageTap,
this.selected = false,
this.showLastOnline = true,
}) : super(key: key);
/// Function called when tapping this widget
final void Function(User) onTap;
/// Function called when long pressing this widget
final void Function(User) onLongPress;
/// User displayed
final User user;
/// The function called when the image is tapped
final void Function(User) onImageTap;
/// If true the [UserItem] will show a trailing checkmark
final bool selected;
/// If true the [UserItem] will show the last seen
final bool showLastOnline;
@override
Widget build(BuildContext context) {
return ListTile(
onTap: () {
if (onTap != null) {
onTap(user);
}
},
onLongPress: () {
if (onLongPress != null) {
onLongPress(user);
}
},
leading: UserAvatar(
user: user,
showOnlineStatus: true,
onTap: (user) {
if (onImageTap != null) {
onImageTap(user);
}
},
constraints: BoxConstraints.tightFor(
height: 40,
width: 40,
),
),
trailing: selected
? StreamSvgIcon.checkSend(
color: StreamChatTheme.of(context).colorTheme.accentBlue,
)
: null,
title: Text(
user.name,
style: StreamChatTheme.of(context).textTheme.bodyBold,
),
subtitle: showLastOnline ? _buildLastActive(context) : null,
);
}
Widget _buildLastActive(context) {
return Text(
user.online == true
? 'Online'
: 'Last online ${Jiffy(user.lastActive).fromNow()}',
style: StreamChatTheme.of(context).textTheme.footnote.copyWith(
color: StreamChatTheme.of(context).colorTheme.black.withOpacity(.5)),
);
}
}
| stream-chat-flutter/packages/stream_chat_flutter/lib/src/user_item.dart/0 | {'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/lib/src/user_item.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 1080} |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'mocks.dart';
void main() {
testWidgets(
'it should show basic channel information',
(WidgetTester tester) async {
final client = MockClient();
final clientState = MockClientState();
final channel = MockChannel();
final channelState = MockChannelState();
final lastMessageAt = DateTime.parse('2020-06-22 12:00:00');
when(client.state).thenReturn(clientState);
when(clientState.user).thenReturn(OwnUser(id: 'user-id'));
when(channel.lastMessageAt).thenReturn(lastMessageAt);
when(channel.state).thenReturn(channelState);
when(channel.client).thenReturn(client);
when(channel.isMuted).thenReturn(false);
when(channel.isMutedStream).thenAnswer((i) => Stream.value(false));
when(channel.extraDataStream).thenAnswer((i) => Stream.value({
'name': 'test name',
}));
when(channel.extraData).thenReturn({
'name': 'test name',
});
when(channelState.unreadCount).thenReturn(1);
when(channelState.unreadCountStream).thenAnswer((i) => Stream.value(1));
when(channelState.membersStream).thenAnswer((i) => Stream.value([
Member(
userId: 'user-id',
user: User(id: 'user-id'),
)
]));
when(channelState.members).thenReturn([
Member(
userId: 'user-id',
user: User(id: 'user-id'),
),
]);
when(channelState.messages).thenReturn([
Message(
text: 'hello',
user: User(id: 'other-user'),
)
]);
when(channelState.messagesStream).thenAnswer((i) => Stream.value([
Message(
text: 'hello',
user: User(id: 'other-user'),
)
]));
await tester.pumpWidget(MaterialApp(
home: StreamChat(
client: client,
child: StreamChannel(
channel: channel,
child: Scaffold(
body: ChannelPreview(
channel: channel,
),
),
),
),
));
expect(find.text('22/06/2020'), findsOneWidget);
expect(find.text('test name'), findsOneWidget);
expect(find.text('1'), findsOneWidget);
expect(find.text('hello'), findsOneWidget);
expect(find.byType(ChannelImage), findsOneWidget);
},
);
}
| stream-chat-flutter/packages/stream_chat_flutter/test/src/channel_preview_test.dart/0 | {'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/test/src/channel_preview_test.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 1158} |
import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';
import 'package:stream_chat/stream_chat.dart';
import 'stream_chat_core.dart';
/// Widget dedicated to the management of a users list with pagination.
///
/// [UsersBloc] can be access at anytime by using the static [of] method
/// using Flutter's [BuildContext].
///
/// API docs: https://getstream.io/chat/docs/flutter-dart/init_and_users/
class UsersBloc extends StatefulWidget {
/// Instantiate a new [UsersBloc]. The parameter [child] must be supplied and
/// not null.
const UsersBloc({
Key key,
@required this.child,
}) : assert(child != null),
super(key: key);
/// The widget child
final Widget child;
@override
UsersBlocState createState() => UsersBlocState();
/// Use this method to get the current [UsersBlocState] instance
static UsersBlocState of(BuildContext context) {
UsersBlocState state;
state = context.findAncestorStateOfType<UsersBlocState>();
if (state == null) {
throw Exception('You must have a UsersBloc widget as ancestor');
}
return state;
}
}
/// The current state of the [UsersBloc]
class UsersBlocState extends State<UsersBloc>
with AutomaticKeepAliveClientMixin {
/// The current users list
List<User> get users => _usersController.value;
/// The current users list as a stream
Stream<List<User>> get usersStream => _usersController.stream;
final BehaviorSubject<List<User>> _usersController = BehaviorSubject();
final BehaviorSubject<bool> _queryUsersLoadingController =
BehaviorSubject.seeded(false);
/// The stream notifying the state of queryUsers call
Stream<bool> get queryUsersLoading => _queryUsersLoadingController.stream;
/// The Query Users method allows you to search for users and see if they are
/// online/offline.
/// [API Reference](https://getstream.io/chat/docs/flutter-dart/query_users/?language=dart)
Future<void> queryUsers({
Map<String, dynamic> filter,
List<SortOption> sort,
Map<String, dynamic> options,
PaginationParams pagination,
}) async {
final client = StreamChatCore.of(context).client;
if (client.state?.user == null ||
_queryUsersLoadingController.value == true) {
return;
}
_queryUsersLoadingController.add(true);
try {
final clear = pagination == null ||
pagination.offset == null ||
pagination.offset == 0;
final oldUsers = List<User>.from(users ?? []);
final usersResponse = await client.queryUsers(
filter: filter,
sort: sort,
options: options,
pagination: pagination,
);
if (clear) {
_usersController.add(usersResponse.users);
} else {
final temp = oldUsers + usersResponse.users;
_usersController.add(temp);
}
_queryUsersLoadingController.add(false);
} catch (err, stackTrace) {
_queryUsersLoadingController.addError(err, stackTrace);
}
}
@override
Widget build(BuildContext context) {
super.build(context);
return widget.child;
}
@override
void dispose() {
_usersController.close();
_queryUsersLoadingController.close();
super.dispose();
}
@override
bool get wantKeepAlive => true;
}
| stream-chat-flutter/packages/stream_chat_flutter_core/lib/src/users_bloc.dart/0 | {'file_path': 'stream-chat-flutter/packages/stream_chat_flutter_core/lib/src/users_bloc.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 1118} |
import 'package:moor/moor.dart';
import 'package:stream_chat/stream_chat.dart';
import 'package:stream_chat_persistence/src/db/moor_chat_database.dart';
import 'package:stream_chat_persistence/src/entity/connection_events.dart';
import 'package:stream_chat_persistence/src/entity/users.dart';
import 'package:stream_chat_persistence/src/mapper/mapper.dart';
part 'connection_event_dao.g.dart';
/// The Data Access Object for operations in [ConnectionEvents] table.
@UseDao(tables: [ConnectionEvents, Users])
class ConnectionEventDao extends DatabaseAccessor<MoorChatDatabase>
with _$ConnectionEventDaoMixin {
/// Creates a new connection event dao instance
ConnectionEventDao(MoorChatDatabase db) : super(db);
/// Get the latest stored connection event
Future<Event> get connectionEvent => select(connectionEvents)
.map((eventEntity) => eventEntity.toEvent())
.getSingle();
/// Get the latest stored lastSyncAt
Future<DateTime> get lastSyncAt =>
select(connectionEvents).getSingle().then((r) => r?.lastSyncAt);
/// Update stored connection event with latest data
Future<void> updateConnectionEvent(Event event) async =>
transaction(() async {
final connectionInfo = await select(connectionEvents).getSingle();
await into(connectionEvents).insert(
ConnectionEventEntity(
id: 1,
lastSyncAt: connectionInfo?.lastSyncAt,
lastEventAt: event.createdAt ?? connectionInfo?.lastEventAt,
totalUnreadCount:
event.totalUnreadCount ?? connectionInfo?.totalUnreadCount,
ownUser: event.me?.toJson() ?? connectionInfo?.ownUser,
unreadChannels:
event.unreadChannels ?? connectionInfo?.unreadChannels,
),
mode: InsertMode.insertOrReplace,
);
});
/// Update stored lastSyncAt with latest data
Future<int> updateLastSyncAt(DateTime lastSyncAt) async =>
(update(connectionEvents)..where((tbl) => tbl.id.equals(1))).write(
ConnectionEventsCompanion(
lastSyncAt: Value(lastSyncAt),
),
);
}
| stream-chat-flutter/packages/stream_chat_persistence/lib/src/dao/connection_event_dao.dart/0 | {'file_path': 'stream-chat-flutter/packages/stream_chat_persistence/lib/src/dao/connection_event_dao.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 778} |
import 'package:stream_chat/stream_chat.dart';
import 'package:stream_chat_persistence/src/db/moor_chat_database.dart';
/// Useful mapping functions for [ConnectionEventEntity]
extension ConnectionEventX on ConnectionEventEntity {
/// Maps a [ConnectionEventEntity] into [Event]
Event toEvent() => Event(
me: ownUser != null ? OwnUser.fromJson(ownUser) : null,
totalUnreadCount: totalUnreadCount,
unreadChannels: unreadChannels,
);
}
| stream-chat-flutter/packages/stream_chat_persistence/lib/src/mapper/event_mapper.dart/0 | {'file_path': 'stream-chat-flutter/packages/stream_chat_persistence/lib/src/mapper/event_mapper.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 161} |
include: package:very_good_analysis/analysis_options.yaml | stream_listener/packages/flutter_stream_listener/analysis_options.yaml/0 | {'file_path': 'stream_listener/packages/flutter_stream_listener/analysis_options.yaml', 'repo_id': 'stream_listener', 'token_count': 16} |
import 'dart:async';
import 'dart:ui';
import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flame_behaviors/flame_behaviors.dart';
import 'package:super_dash/game/game.dart';
enum DashState {
idle,
running,
phoenixIdle,
phoenixRunning,
deathPit,
deathFaint,
jump,
phoenixJump,
phoenixDoubleJump,
}
class PlayerStateBehavior extends Behavior<Player> {
DashState? _state;
late final Map<DashState, PositionComponent> _stateMap;
DashState get state => _state ?? DashState.idle;
static const _needResetStates = {
DashState.deathPit,
DashState.deathFaint,
DashState.jump,
DashState.phoenixJump,
DashState.phoenixDoubleJump,
};
void updateSpritePaintColor(Color color) {
for (final component in _stateMap.values) {
if (component is HasPaint) {
(component as HasPaint).paint.color = color;
}
}
}
void fadeOut({VoidCallback? onComplete}) {
final component = _stateMap[state];
if (component != null && component is HasPaint) {
component.add(
OpacityEffect.fadeOut(
EffectController(duration: .5),
onComplete: onComplete,
),
);
}
}
void fadeIn({VoidCallback? onComplete}) {
final component = _stateMap[state];
if (component != null && component is HasPaint) {
component.add(
OpacityEffect.fadeIn(
EffectController(duration: .5, startDelay: .8),
onComplete: onComplete,
),
);
}
}
set state(DashState state) {
if (state != _state) {
final current = _stateMap[_state];
if (current != null) {
current.removeFromParent();
if (_needResetStates.contains(_state)) {
if (current is SpriteAnimationComponent) {
current.animationTicker?.reset();
}
}
}
final replacement = _stateMap[state];
if (replacement != null) {
parent.add(replacement);
}
_state = state;
}
}
@override
FutureOr<void> onLoad() async {
await super.onLoad();
final [
idleAnimation,
runningAnimation,
phoenixIdleAnimation,
phoenixRunningAnimation,
deathPitAnimation,
deathFaintAnimation,
jumpAnimation,
phoenixJumpAnimation,
phoenixDoubleJumpAnimation,
] = await Future.wait(
[
parent.gameRef.loadSpriteAnimation(
'anim/spritesheet_dash_idle.png',
SpriteAnimationData.sequenced(
amount: 18,
stepTime: 0.042,
textureSize: Vector2.all(parent.gameRef.tileSize),
),
),
parent.gameRef.loadSpriteAnimation(
'anim/spritesheet_dash_run.png',
SpriteAnimationData.sequenced(
amount: 16,
stepTime: 0.042,
textureSize: Vector2.all(parent.gameRef.tileSize),
),
),
parent.gameRef.loadSpriteAnimation(
'anim/spritesheet_phoenixDash_idle.png',
SpriteAnimationData.sequenced(
amount: 18,
stepTime: 0.042,
textureSize: Vector2.all(parent.gameRef.tileSize),
),
),
parent.gameRef.loadSpriteAnimation(
'anim/spritesheet_phoenixDash_run.png',
SpriteAnimationData.sequenced(
amount: 16,
stepTime: 0.042,
textureSize: Vector2.all(parent.gameRef.tileSize),
),
),
parent.gameRef.loadSpriteAnimation(
'anim/spritesheet_dash_deathPit.png',
SpriteAnimationData.sequenced(
amount: 24,
stepTime: 0.042,
textureSize: Vector2.all(parent.gameRef.tileSize),
amountPerRow: 8,
loop: false,
),
),
parent.gameRef.loadSpriteAnimation(
'anim/spritesheet_dash_deathFaint.png',
SpriteAnimationData.sequenced(
amount: 24,
stepTime: 0.042,
textureSize: Vector2.all(parent.gameRef.tileSize),
amountPerRow: 8,
loop: false,
),
),
parent.gameRef.loadSpriteAnimation(
'anim/spritesheet_dash_jump.png',
SpriteAnimationData.sequenced(
amount: 16,
stepTime: 0.042,
textureSize: Vector2.all(parent.gameRef.tileSize),
loop: false,
),
),
parent.gameRef.loadSpriteAnimation(
'anim/spritesheet_phoenixDash_jump.png',
SpriteAnimationData.sequenced(
amount: 16,
stepTime: 0.042,
textureSize: Vector2(
parent.gameRef.tileSize,
parent.gameRef.tileSize * 2,
),
amountPerRow: 8,
loop: false,
),
),
parent.gameRef.loadSpriteAnimation(
'anim/spritesheet_phoenixDash_doublejump.png',
SpriteAnimationData.sequenced(
amount: 16,
stepTime: 0.042,
textureSize: Vector2.all(parent.gameRef.tileSize),
loop: false,
),
),
],
);
final paint = Paint()..isAntiAlias = false;
final centerPosition = parent.size / 2 - Vector2(0, parent.size.y / 2);
_stateMap = {
DashState.idle: SpriteAnimationComponent(
animation: idleAnimation,
anchor: Anchor.center,
position: centerPosition.clone(),
paint: paint,
),
DashState.running: SpriteAnimationComponent(
animation: runningAnimation,
anchor: Anchor.center,
position: centerPosition.clone(),
paint: paint,
),
DashState.phoenixIdle: SpriteAnimationComponent(
animation: phoenixIdleAnimation,
anchor: Anchor.center,
position: centerPosition.clone(),
paint: paint,
),
DashState.phoenixRunning: SpriteAnimationComponent(
animation: phoenixRunningAnimation,
anchor: Anchor.center,
position: centerPosition.clone(),
paint: paint,
),
DashState.deathPit: SpriteAnimationComponent(
animation: deathPitAnimation,
anchor: Anchor.center,
position: centerPosition.clone(),
paint: paint,
),
DashState.deathFaint: SpriteAnimationComponent(
animation: deathFaintAnimation,
anchor: Anchor.center,
position: centerPosition.clone(),
paint: paint,
),
DashState.jump: SpriteAnimationComponent(
animation: jumpAnimation,
anchor: Anchor.center,
position: centerPosition.clone(),
paint: paint,
),
DashState.phoenixJump: SpriteAnimationComponent(
animation: phoenixJumpAnimation,
anchor: Anchor.center,
position: centerPosition.clone(),
paint: paint,
),
DashState.phoenixDoubleJump: SpriteAnimationComponent(
animation: phoenixDoubleJumpAnimation,
anchor: Anchor.center,
position: centerPosition.clone(),
paint: paint,
),
};
state = DashState.idle;
}
}
| super_dash/lib/game/behaviors/player_state_behavior.dart/0 | {'file_path': 'super_dash/lib/game/behaviors/player_state_behavior.dart', 'repo_id': 'super_dash', 'token_count': 3256} |
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flame/cache.dart';
import 'package:flame/components.dart';
import 'package:flame/events.dart';
import 'package:flame/sprite.dart';
import 'package:flame/text.dart';
import 'package:flame_tiled/flame_tiled.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:leap/leap.dart';
import 'package:super_dash/audio/audio.dart';
import 'package:super_dash/game/game.dart';
import 'package:super_dash/score/score.dart';
bool _tsxPackingFilter(Tileset tileset) {
return !(tileset.source ?? '').startsWith('anim');
}
Paint _layerPaintFactory(double opacity) {
return Paint()
..color = Color.fromRGBO(255, 255, 255, opacity)
..isAntiAlias = false;
}
class SuperDashGame extends LeapGame
with TapDetector, HasKeyboardHandlerComponents {
SuperDashGame({
required this.gameBloc,
required this.audioController,
this.customBundle,
this.inMapTester = false,
}) : super(
tileSize: 64,
configuration: const LeapConfiguration(
tiled: TiledOptions(
atlasMaxX: 4048,
atlasMaxY: 4048,
tsxPackingFilter: _tsxPackingFilter,
layerPaintFactory: _layerPaintFactory,
atlasPackingSpacingX: 4,
atlasPackingSpacingY: 4,
),
),
);
static final _cameraViewport = Vector2(592, 1024);
static const prefix = 'assets/map/';
static const _sections = [
'flutter_runnergame_map_A.tmx',
'flutter_runnergame_map_B.tmx',
'flutter_runnergame_map_C.tmx',
];
static const _sectionsBackgroundColor = [
(Color(0xFFDADEF6), Color(0xFFEAF0E3)),
(Color(0xFFEBD6E1), Color(0xFFC9C8E9)),
(Color(0xFF002052), Color(0xFF0055B4)),
];
final GameBloc gameBloc;
final AssetBundle? customBundle;
final AudioController audioController;
final List<VoidCallback> _inputListener = [];
late final SpriteSheet itemsSpritesheet;
final bool inMapTester;
GameState get state => gameBloc.state;
Player? get player => world.firstChild<Player>();
List<Tileset> get tilesets => leapMap.tiledMap.tileMap.map.tilesets;
Tileset get itemsTileset {
return tilesets.firstWhere(
(tileset) => tileset.name == 'tile_items_v2',
);
}
Tileset get enemiesTileset {
return tilesets.firstWhere(
(tileset) => tileset.name == 'tile_enemies_v2',
);
}
void addInputListener(VoidCallback listener) {
_inputListener.add(listener);
}
void removeInputListener(VoidCallback listener) {
_inputListener.remove(listener);
}
void _triggerInputListeners() {
for (final listener in _inputListener) {
listener();
}
}
@override
void onTapDown(TapDownInfo info) {
super.onTapDown(info);
_triggerInputListeners();
overlays.remove('tapToJump');
}
@override
Future<void> onLoad() async {
await super.onLoad();
if (inMapTester) {
_addMapTesterFeatures();
}
if (kIsWeb && audioController.isMusicEnabled) {
audioController.startMusic();
}
camera = CameraComponent.withFixedResolution(
width: _cameraViewport.x,
height: _cameraViewport.y,
)..world = world;
images = Images(
prefix: prefix,
bundle: customBundle,
);
itemsSpritesheet = SpriteSheet(
image: await images.load('objects/tile_items_v2.png'),
srcSize: Vector2.all(tileSize),
);
await loadWorldAndMap(
images: images,
prefix: prefix,
bundle: customBundle,
tiledMapPath: _sections.first,
);
_setSectionBackground();
final player = Player(
levelSize: leapMap.tiledMap.size.clone(),
cameraViewport: _cameraViewport,
);
unawaited(
world.addAll([player]),
);
await _addSpawners();
_addTreeHouseFrontLayer();
_addTreeHouseSign();
add(
KeyboardListenerComponent(
keyDown: {
LogicalKeyboardKey.space: (_) {
_triggerInputListeners();
overlays.remove('tapToJump');
return false;
},
},
keyUp: {
LogicalKeyboardKey.space: (_) {
return false;
},
},
),
);
}
void _addTreeHouseSign() {
world.add(
TreeSign(
position: Vector2(
448,
1862,
),
),
);
}
void _addTreeHouseFrontLayer() {
final layer = leapMap.tiledMap.tileMap.renderableLayers.last;
world.add(TreeHouseFront(renderFront: layer.render));
}
void _setSectionBackground() {
final colors = _sectionsBackgroundColor[state.currentSection];
camera.backdrop = RectangleComponent(
size: size.clone(),
paint: Paint()
..shader = ui.Gradient.linear(
Offset.zero,
Offset(size.x, size.y),
[
colors.$1,
colors.$2,
],
),
);
}
void gameOver() {
gameBloc.add(const GameOver());
// Removed since the result didn't ended up good.
// Leaving in comment if we decide to bring it back.
// audioController.stopBackgroundSfx();
world.firstChild<Player>()?.removeFromParent();
_resetEntities();
Future<void>.delayed(
const Duration(seconds: 1),
() async {
await loadWorldAndMap(
images: images,
prefix: prefix,
bundle: customBundle,
tiledMapPath: _sections.first,
);
if (isLastSection || isFirstSection) {
_addTreeHouseFrontLayer();
}
if (isFirstSection) {
_addTreeHouseSign();
}
final newPlayer = Player(
levelSize: leapMap.tiledMap.size.clone(),
cameraViewport: _cameraViewport,
);
await world.add(newPlayer);
await newPlayer.mounted;
await _addSpawners();
overlays.add('tapToJump');
},
);
if (buildContext != null) {
final score = gameBloc.state.score;
Navigator.of(buildContext!).push(
ScorePage.route(score: score),
);
}
}
void _resetEntities() {
children.whereType<ObjectGroupProximityBuilder<Player>>().forEach(
(spawner) => spawner.removeFromParent(),
);
world.firstChild<TreeHouseFront>()?.removeFromParent();
world.firstChild<TreeSign>()?.removeFromParent();
leapMap.children
.whereType<Enemy>()
.forEach((enemy) => enemy.removeFromParent());
leapMap.children
.whereType<Item>()
.forEach((enemy) => enemy.removeFromParent());
}
Future<void> _addSpawners() async {
await addAll([
ObjectGroupProximityBuilder<Player>(
proximity: _cameraViewport.x * 1.5,
tileLayerName: 'items',
tileset: itemsTileset,
componentBuilder: Item.new,
),
ObjectGroupProximityBuilder<Player>(
proximity: _cameraViewport.x * 1.5,
tileLayerName: 'enemies',
tileset: enemiesTileset,
componentBuilder: Enemy.new,
),
]);
}
Future<void> _loadNewSection() async {
final nextSectionIndex = state.currentSection + 1 < _sections.length
? state.currentSection + 1
: 0;
final nextSection = _sections[nextSectionIndex];
_resetEntities();
await loadWorldAndMap(
images: images,
prefix: prefix,
bundle: customBundle,
tiledMapPath: nextSection,
);
if (isFirstSection) {
_addTreeHouseSign();
}
if (isLastSection || isFirstSection) {
_addTreeHouseFrontLayer();
}
await _addSpawners();
}
@override
void onMapUnload(LeapMap map) {
player?.velocity.setZero();
}
@override
void onMapLoaded(LeapMap map) {
player?.loadSpawnPoint();
player?.loadRespawnPoints();
player?.walking = true;
player?.spritePaintColor(Colors.white);
player?.isPlayerTeleporting = false;
_setSectionBackground();
}
void sectionCleared() {
if (isLastSection) {
player?.spritePaintColor(Colors.transparent);
player?.walking = false;
}
_loadNewSection();
gameBloc
..add(GameScoreIncreased(by: 1000 * state.currentLevel))
..add(GameSectionCompleted(sectionCount: _sections.length));
}
bool get isLastSection => state.currentSection == _sections.length - 1;
bool get isFirstSection => state.currentSection == 0;
void addCameraDebugger() {
if (descendants().whereType<CameraDebugger>().isEmpty) {
final player = world.firstChild<Player>()!;
final cameraDebugger = CameraDebugger(
position: player.position.clone(),
);
world.add(cameraDebugger);
final anchor = PlayerCameraAnchor(
levelSize: leapMap.tiledMap.size.clone(),
cameraViewport: _cameraViewport,
);
cameraDebugger.add(anchor);
camera.follow(anchor);
final proximityBuilders =
descendants().whereType<ObjectGroupProximityBuilder<Player>>();
for (final proximityBuilder in proximityBuilders) {
proximityBuilder.currentReference = cameraDebugger;
}
player.removeFromParent();
}
}
void toggleInvincibility() {
player?.isPlayerInvincible = !(player?.isPlayerInvincible ?? false);
}
void teleportPlayerToEnd() {
player?.x = leapMap.tiledMap.size.x - (player?.size.x ?? 0) * 10 * 4;
if (state.currentSection == 2) {
player?.y = (player?.y ?? 0) - (tileSize * 4);
}
}
void showHitBoxes() {
void show() {
descendants()
.whereType<PhysicalEntity>()
.where(
(element) =>
element is Player || element is Item || element is Enemy,
)
.forEach((entity) => entity.debugMode = true);
}
show();
add(
TimerComponent(
period: 1,
repeat: true,
onTick: show,
),
);
}
void _addMapTesterFeatures() {
add(FpsComponent());
add(
FpsTextComponent(
position: Vector2(0, 0),
textRenderer: TextPaint(
style: const TextStyle(
color: Colors.white,
fontSize: 20,
),
),
),
);
}
}
| super_dash/lib/game/super_dash_game.dart/0 | {'file_path': 'super_dash/lib/game/super_dash_game.dart', 'repo_id': 'super_dash', 'token_count': 4337} |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:super_dash/constants/constants.dart';
import 'package:super_dash/game/game.dart';
import 'package:super_dash/game_intro/game_intro.dart';
import 'package:super_dash/gen/assets.gen.dart';
import 'package:super_dash/l10n/l10n.dart';
import 'package:url_launcher/url_launcher.dart';
class GameIntroPage extends StatefulWidget {
const GameIntroPage({super.key});
@override
State<GameIntroPage> createState() => _GameIntroPageState();
}
class _GameIntroPageState extends State<GameIntroPage> {
@override
void didChangeDependencies() {
super.didChangeDependencies();
precacheImage(Assets.images.gameBackground.provider(), context);
}
void _onDownload() {
final isAndroid = defaultTargetPlatform == TargetPlatform.android;
launchUrl(Uri.parse(isAndroid ? Urls.playStoreLink : Urls.appStoreLink));
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: DecoratedBox(
decoration: BoxDecoration(
image: DecorationImage(
image: context.isSmall
? Assets.images.introBackgroundMobile.provider()
: Assets.images.introBackgroundDesktop.provider(),
fit: BoxFit.cover,
),
),
child: isMobileWeb
? _MobileWebNotAvailableIntroPage(onDownload: _onDownload)
: const _IntroPage(),
),
);
}
bool get isMobileWeb =>
kIsWeb &&
(defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS);
}
class _IntroPage extends StatelessWidget {
const _IntroPage();
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
return Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 390),
child: Column(
children: [
const Spacer(),
Assets.images.gameLogo.image(
width: context.isSmall ? 282 : 380,
),
const Spacer(flex: 4),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Text(
l10n.gameIntroPageHeadline,
textAlign: TextAlign.center,
style: theme.textTheme.titleMedium?.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(height: 32),
GameElevatedButton(
label: l10n.gameIntroPagePlayButtonText,
onPressed: () => Navigator.of(context).push(Game.route()),
),
const Spacer(),
const Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
AudioButton(),
LeaderboardButton(),
InfoButton(),
HowToPlayButton(),
],
),
const SizedBox(height: 32),
],
),
),
);
}
}
class _MobileWebNotAvailableIntroPage extends StatelessWidget {
const _MobileWebNotAvailableIntroPage({
required this.onDownload,
});
final VoidCallback onDownload;
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final textTheme = theme.textTheme;
return Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 390),
child: Column(
children: [
const Spacer(),
Assets.images.gameLogo.image(width: 282),
const Spacer(flex: 4),
const SizedBox(height: 24),
Text(
l10n.downloadAppMessage,
textAlign: TextAlign.center,
style: textTheme.headlineSmall?.copyWith(
color: Colors.white,
),
),
const SizedBox(height: 24),
GameElevatedButton.icon(
label: l10n.downloadAppLabel,
icon: const Icon(
Icons.download,
color: Colors.white,
),
onPressed: onDownload,
),
const Spacer(),
const BottomBar(),
const SizedBox(height: 32),
],
),
),
);
}
}
| super_dash/lib/game_intro/view/game_intro_page.dart/0 | {'file_path': 'super_dash/lib/game_intro/view/game_intro_page.dart', 'repo_id': 'super_dash', 'token_count': 2127} |
import 'package:flutter/material.dart';
import 'package:super_dash/leaderboard/leaderboard.dart';
import 'package:super_dash/score/game_over/game_over.dart';
import 'package:super_dash/score/score.dart';
List<Page<void>> onGenerateScorePages(
ScoreState state,
List<Page<void>> pages,
) {
return switch (state.status) {
ScoreStatus.gameOver => [GameOverPage.page()],
ScoreStatus.inputInitials => [InputInitialsPage.page()],
ScoreStatus.scoreOverview => [ScoreOverviewPage.page()],
ScoreStatus.leaderboard => [LeaderboardPage.page()],
};
}
| super_dash/lib/score/routes/routes.dart/0 | {'file_path': 'super_dash/lib/score/routes/routes.dart', 'repo_id': 'super_dash', 'token_count': 191} |
import 'package:flutter/foundation.dart';
bool get isDesktop =>
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.windows ||
defaultTargetPlatform == TargetPlatform.linux;
| super_dash/lib/utils/utils.dart/0 | {'file_path': 'super_dash/lib/utils/utils.dart', 'repo_id': 'super_dash', 'token_count': 60} |
include: package:very_good_analysis/analysis_options.5.1.0.yaml
| super_dash/packages/app_ui/analysis_options.yaml/0 | {'file_path': 'super_dash/packages/app_ui/analysis_options.yaml', 'repo_id': 'super_dash', 'token_count': 23} |
import 'package:flutter/material.dart';
/// {@template game_button}
/// Common elevated button for the screens in the game.
/// {@endtemplate}
class GameElevatedButton extends StatelessWidget {
/// {@macro game_button}
GameElevatedButton({
required String label,
VoidCallback? onPressed,
this.gradient,
super.key,
}) : _child = FilledButton(
onPressed: onPressed,
child: Text(label),
);
/// {@macro game_button}
GameElevatedButton.icon({
required String label,
required Icon icon,
VoidCallback? onPressed,
this.gradient,
super.key,
}) : _child = FilledButton.icon(
icon: icon,
label: Text(label),
onPressed: onPressed,
);
final Widget _child;
/// The gradient to use for the background.
final Gradient? gradient;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Container(
width: 200,
decoration: BoxDecoration(
gradient: gradient ??
const LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color(0xFFADD7CD),
Color(0xFF57AEA5),
],
),
border: Border.all(color: Colors.white24),
borderRadius: BorderRadius.circular(94),
),
child: Theme(
data: theme.copyWith(
filledButtonTheme: FilledButtonThemeData(
style: FilledButton.styleFrom(
backgroundColor: Colors.transparent,
shadowColor: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(94),
),
padding: const EdgeInsets.symmetric(vertical: 22),
textStyle: theme.textTheme.labelLarge?.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
),
child: _child,
),
);
}
}
| super_dash/packages/app_ui/lib/src/widgets/game_elevated_button.dart/0 | {'file_path': 'super_dash/packages/app_ui/lib/src/widgets/game_elevated_button.dart', 'repo_id': 'super_dash', 'token_count': 958} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:super_dash/audio/songs.dart';
void main() {
group('Song', () {
test('toString returns correctly', () {
expect(
Song('SONG.mp3', 'SONG').toString(),
equals('Song<SONG.mp3>'),
);
});
});
}
| super_dash/test/audio/songs_test.dart/0 | {'file_path': 'super_dash/test/audio/songs_test.dart', 'repo_id': 'super_dash', 'token_count': 143} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:super_dash/leaderboard/bloc/leaderboard_bloc.dart';
void main() {
group('LeaderboardTop10Requested', () {
test(
'supports value equality',
() => expect(
LeaderboardTop10Requested(),
LeaderboardTop10Requested(),
),
);
});
}
| super_dash/test/leaderboard/bloc/leaderboard_event_test.dart/0 | {'file_path': 'super_dash/test/leaderboard/bloc/leaderboard_event_test.dart', 'repo_id': 'super_dash', 'token_count': 151} |
import 'challenge_widget.dart';
class Challenge {
String id;
String title;
int difficultyLevel;
ChallengeWidget child;
}
| super_flutter_maker/game/lib/models/challenge.dart/0 | {'file_path': 'super_flutter_maker/game/lib/models/challenge.dart', 'repo_id': 'super_flutter_maker', 'token_count': 40} |
import 'package:flutter/material.dart';
import './empty_state.dart';
import '../../models/challenge_widget.dart';
import '../../util.dart';
import 'edit_dialog.dart';
class BuilderView extends StatefulWidget {
final ChallengeWidget currentWidget;
final void Function(ChallengeWidget) updateCallback;
BuilderView(this.currentWidget, this.updateCallback);
@override
_BuilderViewState createState() => _BuilderViewState();
}
class _BuilderViewState extends State<BuilderView> {
ChallengeWidget selectedWidget;
Widget slider(BuildContext context) {
return Container(
height: 132,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
Container(width: 8.0),
...ChallengeWidget.all(this.addWidget),
Container(width: 8.0),
],
),
);
}
void addWidget(ChallengeWidget w) {
if (widget.currentWidget == null) {
widget.updateCallback(w);
} else if (selectedWidget != null && selectedWidget.hasSingleChild) {
selectedWidget.setPropertyValue('child', w);
widget.updateCallback(widget.currentWidget);
} else if (selectedWidget != null && selectedWidget.hasMultipleChildren) {
final currentChildren =
selectedWidget.getProperty('children').getAsChallengeWidgetList() ?? [];
selectedWidget.setPropertyValue('children', [...currentChildren, w]);
widget.updateCallback(widget.currentWidget);
}
}
void doSelect(ChallengeWidget select) {
setState(() => selectedWidget = select);
}
void doRemove(ChallengeWidget removed) {
ChallengeWidget current = widget.currentWidget;
if (current == removed) {
current = null;
} else {
_clearOf(current, removed);
}
doSelect(null);
widget.updateCallback(current);
}
void _clearOf(ChallengeWidget current, ChallengeWidget removed) {
if (current.hasSingleChild) {
ChallengeWidget widget = current.childProperty?.getAsChallengeWidget();
if (widget == removed) {
current.setPropertyValue('child', null);
} else if (widget != null) {
_clearOf(widget, removed);
}
} else if (current.hasMultipleChildren) {
List<ChallengeWidget> children =
current.childrenProperty?.getAsChallengeWidgetList();
final newChildren = children.where((w) => w != removed);
current.setPropertyValue('children', newChildren.toList());
}
}
void doEdit(ChallengeWidget w) {
showDialog(
context: context,
builder: (BuildContext context) =>
EditDialog(widget: w, doUpdateParent: () => this.setState(() {})),
);
}
Widget _content() {
return widget.currentWidget
?.toBuilderWidget(selectedWidget, doSelect, doEdit, doRemove) ??
EmptyState();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: Container(
color: Colors.cyan,
child: SingleChildScrollView(child: pad(_content())),
),
),
slider(context),
],
);
}
}
| super_flutter_maker/game/lib/screens/game_screen/builder_view.dart/0 | {'file_path': 'super_flutter_maker/game/lib/screens/game_screen/builder_view.dart', 'repo_id': 'super_flutter_maker', 'token_count': 1137} |
export 'core/app_exceptions.dart';
export 'core/app_log.dart';
export 'core/environment.dart';
export 'core/error_handling/error_boundary.dart';
export 'core/error_handling/error_reporter.dart';
export 'core/error_handling/handle_uncaught_error.dart';
| tailor_made/lib/core.dart/0 | {'file_path': 'tailor_made/lib/core.dart', 'repo_id': 'tailor_made', 'token_count': 91} |
import 'package:cloud_firestore/cloud_firestore.dart';
typedef DynamicMap = Map<String, dynamic>;
typedef MapQuery = Query<DynamicMap>;
typedef MapQuerySnapshot = QuerySnapshot<DynamicMap>;
typedef MapQueryDocumentSnapshot = QueryDocumentSnapshot<DynamicMap>;
typedef MapDocumentSnapshot = DocumentSnapshot<DynamicMap>;
typedef MapDocumentReference = DocumentReference<DynamicMap>;
typedef MapCollectionReference = CollectionReference<DynamicMap>;
typedef CloudTimestamp = Timestamp;
typedef CloudValue = FieldValue;
| tailor_made/lib/data/network/firebase/models.dart/0 | {'file_path': 'tailor_made/lib/data/network/firebase/models.dart', 'repo_id': 'tailor_made', 'token_count': 151} |
import 'package:tailor_made/domain.dart';
class PaymentsMockImpl extends Payments {
@override
Stream<List<PaymentEntity>> fetchAll(String userId) async* {}
}
| tailor_made/lib/data/repositories/payments/payments_mock_impl.dart/0 | {'file_path': 'tailor_made/lib/data/repositories/payments/payments_mock_impl.dart', 'repo_id': 'tailor_made', 'token_count': 52} |
import 'create_image_data.dart';
import 'image_entity.dart';
sealed class ImageOperation {}
class CreateImageOperation implements ImageOperation {
const CreateImageOperation({required this.data});
final CreateImageData data;
}
class ModifyImageOperation implements ImageOperation {
const ModifyImageOperation({required this.data});
final ImageEntity data;
}
| tailor_made/lib/domain/entities/image_operation.dart/0 | {'file_path': 'tailor_made/lib/domain/entities/image_operation.dart', 'repo_id': 'tailor_made', 'token_count': 95} |
import '../entities/payment_entity.dart';
abstract class Payments {
Stream<List<PaymentEntity>> fetchAll(String userId);
}
| tailor_made/lib/domain/repositories/payments.dart/0 | {'file_path': 'tailor_made/lib/domain/repositories/payments.dart', 'repo_id': 'tailor_made', 'token_count': 40} |
class AppRoutes {
static const String dashboard = '/dashboard';
static const String start = '/start';
static const String verify = '/verify';
static const String home = '/home';
static const String storeNameDialog = '/store_name_dialog';
static const String contact = '/contact';
static const String editContacts = '/edit_contacts';
static const String contactsMeasurement = '/contacts_measurement';
static const String contacts = '/contacts';
static const String contactsList = '/contacts_list';
static const String createContact = '/create_contact';
static const String job = '/job';
static const String jobs = '/jobs';
static const String createJob = '/create_job';
static const String payment = '/payment';
static const String payments = '/payments';
static const String createPayment = '/create_payment';
static const String galleryImage = '/gallery_image';
static const String gallery = '/gallery';
static const String measurements = '/measurements';
static const String manageMeasurements = '/manage_measurements';
static const String tasks = '/tasks';
static const String createMeasurements = '/create_measurements';
static const String createMeasurementItem = '/create_measurement_item';
}
| tailor_made/lib/presentation/routing/app_routes.dart/0 | {'file_path': 'tailor_made/lib/presentation/routing/app_routes.dart', 'repo_id': 'tailor_made', 'token_count': 314} |
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:tailor_made/presentation/theme.dart';
import '../../../utils.dart';
class RateLimitPage extends StatelessWidget {
const RateLimitPage({super.key, required this.onSkippedPremium, required this.onSignUp});
final VoidCallback onSkippedPremium;
final VoidCallback onSignUp;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final TextStyle textTheme = theme.textTheme.bodyLarge!;
final ColorScheme colorScheme = theme.colorScheme;
final L10n l10n = context.l10n;
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SpinKitFadingCube(color: colorScheme.outlineVariant),
const SizedBox(height: 48.0),
Text(
l10n.usagePolicyTitle,
style: textTheme.copyWith(color: Colors.black87, fontWeight: AppFontWeight.bold),
textAlign: TextAlign.center,
),
const SizedBox(height: 16.0),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 64.0),
child: Text(
l10n.usagePolicyMessage,
style: textTheme.copyWith(color: colorScheme.outline),
textAlign: TextAlign.center,
),
),
const SizedBox(height: 32.0),
TextButton(
style: TextButton.styleFrom(
foregroundColor: colorScheme.outline,
),
onPressed: onSkippedPremium,
child: Text(l10n.usagePolicyNoCaption),
),
const SizedBox(height: 8.0),
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: colorScheme.secondary,
shape: const StadiumBorder(),
),
onPressed: onSignUp,
icon: const Icon(Icons.done),
label: Text(l10n.usagePolicyYesCaption),
),
],
),
);
}
}
| tailor_made/lib/presentation/screens/homepage/widgets/rate_limit.dart/0 | {'file_path': 'tailor_made/lib/presentation/screens/homepage/widgets/rate_limit.dart', 'repo_id': 'tailor_made', 'token_count': 977} |
import 'package:equatable/equatable.dart';
import 'package:tailor_made/domain.dart';
sealed class ImageFormValue {}
class ImageCreateFormValue with EquatableMixin implements ImageFormValue {
ImageCreateFormValue(this.data);
final CreateImageData data;
@override
List<Object> get props => <Object>[data];
}
class ImageModifyFormValue with EquatableMixin implements ImageFormValue {
ImageModifyFormValue(this.data);
final ImageEntity data;
@override
List<Object> get props => <Object>[data];
}
| tailor_made/lib/presentation/screens/jobs/widgets/image_form_value.dart/0 | {'file_path': 'tailor_made/lib/presentation/screens/jobs/widgets/image_form_value.dart', 'repo_id': 'tailor_made', 'token_count': 153} |
export 'utils/app_date.dart';
export 'utils/app_device.dart';
export 'utils/app_money.dart';
export 'utils/app_sliver_separator_builder_delegate.dart';
export 'utils/app_status_bar.dart';
export 'utils/app_version_builder.dart';
export 'utils/contacts_sort_type.dart';
export 'utils/extensions.dart';
export 'utils/image_utils.dart';
export 'utils/input_validator.dart';
export 'utils/jobs_sort_type.dart';
export 'utils/show_child_dialog.dart';
export 'utils/show_choice_dialog.dart';
export 'utils/show_image_choice_dialog.dart';
| tailor_made/lib/presentation/utils.dart/0 | {'file_path': 'tailor_made/lib/presentation/utils.dart', 'repo_id': 'tailor_made', 'token_count': 197} |
import 'package:flutter/material.dart';
import 'app_clear_button.dart';
class AppBackButton extends StatelessWidget {
const AppBackButton({super.key, this.color, this.onPop});
final Color? color;
final VoidCallback? onPop;
@override
Widget build(BuildContext context) {
return AppClearButton(
onPressed: onPop ?? () => Navigator.maybePop(context),
child: Icon(
Icons.arrow_back_ios,
color: color,
size: 18.0,
),
);
}
}
| tailor_made/lib/presentation/widgets/app_back_button.dart/0 | {'file_path': 'tailor_made/lib/presentation/widgets/app_back_button.dart', 'repo_id': 'tailor_made', 'token_count': 191} |
import 'dart:io' show File;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tailor_made/presentation/theme.dart';
import 'package:tailor_made/presentation/utils.dart';
import 'touchable_opacity.dart';
class UploadPhoto extends StatelessWidget {
const UploadPhoto({super.key, this.size = const Size.square(86.0), required this.onPickImage});
final ValueSetter<File> onPickImage;
final Size size;
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
final Color color = colorScheme.primary;
return Align(
alignment: Alignment.centerLeft,
child: Container(
height: size.height,
width: size.width,
decoration: BoxDecoration(
color: colorScheme.primary.withOpacity(.2),
borderRadius: BorderRadius.circular(4.0),
border: Border.all(color: colorScheme.primary),
),
child: TouchableOpacity(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Icon(Icons.add_circle, color: color),
const SizedBox(height: 2.0),
Text(
'Add\nPhoto',
style: Theme.of(context).textTheme.labelMedium!.copyWith(
fontWeight: AppFontWeight.semibold,
color: color,
),
textAlign: TextAlign.center,
),
],
),
onPressed: () => _handlePressed(context),
),
),
);
}
void _handlePressed(BuildContext context) async {
final ImageSource? source = await showImageChoiceDialog(context: context);
if (source == null) {
return;
}
try {
final XFile? pickedFile = await ImagePicker().pickImage(source: source);
if (pickedFile == null) {
return;
}
final File file = await ImageUtils(pickedFile.path).resize(width: 1500);
onPickImage(file);
} on PlatformException catch (e) {
debugPrint(e.toString());
}
}
}
| tailor_made/lib/presentation/widgets/upload_photo.dart/0 | {'file_path': 'tailor_made/lib/presentation/widgets/upload_photo.dart', 'repo_id': 'tailor_made', 'token_count': 1006} |
import 'dart:convert';
import 'package:broadcast_bloc/broadcast_bloc.dart';
import 'package:chat_data_source/chat_data_source.dart';
/// Defines a ChatCubit class that extends the BroadcastCubit<String> class.
class ChatCubit extends BroadcastCubit<String> {
/// Constructs a ChatCubit object and calls the super constructor with an
/// empty string as the initial state.
ChatCubit() : super('');
/// Defines a sendMessage method that takes an event string and a
/// chatDatasource object as arguments.
void sendMessage(String event, ChatDatasource chatDatasource) {
// Checks if the event string contains the 'sender' substring.
if (event.contains('sender')) {
// If the event is a message sent by a sender, decode the event as a
//Message object using JSON decoding and pass it to the chatDatasource's
//sendMessage method.
chatDatasource.sendMessage(
Message.fromJson(jsonDecode(event) as Map<String, dynamic>),
);
}
// Emits the event string to all listeners.
emit(event);
}
}
| talk-stream-backend/lib/chat/cubit/chat_cubit.dart/0 | {'file_path': 'talk-stream-backend/lib/chat/cubit/chat_cubit.dart', 'repo_id': 'talk-stream-backend', 'token_count': 340} |
// ignore_for_file: public_member_api_docs
import 'dart:convert';
import 'dart:io';
import '../../../src/models/user.dart';
class UserService {
UserService(this._fileName) {
_createFileIfNotExists();
}
final String _fileName;
Future<List<User>> getUsers([String? userId]) async {
final file = File(_fileName);
final users = <User>[];
final fileExists = await file.exists();
if (fileExists) {
final contents = await file.readAsString();
final json = (jsonDecode(contents) as List)
.map(
(content) => content as Map<String, dynamic>,
)
.toList();
for (final userJson in json) {
users.add(
User(
id: userJson['id'] as String,
name: userJson['name'] as String,
password: userJson['password'] as String,
email: userJson['email'] as String,
profileImage: userJson['profileImage'] as String,
),
);
}
}
if (userId != null)
return users.where((user) => user.id != userId).toList();
return users;
}
Future<void> addUser(User user) async {
final file = File(_fileName);
final users = <User>[];
if (await file.exists()) {
final contents = await file.readAsString();
final json = (jsonDecode(contents) as List).map((content) {
final decodedValue = content as Map<String, dynamic>;
return decodedValue;
}).toList();
for (final userJson in json) {
users.add(
User(
id: userJson['id'] as String,
name: userJson['name'] as String,
password: userJson['password'] as String,
email: userJson['email'] as String,
profileImage: userJson['profileImage'] as String,
),
);
}
}
users.add(user);
await file.writeAsString(jsonEncode(users.map((e) => e.toJson()).toList()));
}
Future<void> updateUser(User user) async {
final file = File(_fileName);
final users = <User>[];
if (await file.exists()) {
final contents = await file.readAsString();
final json = (jsonDecode(contents) as List)
.map((content) => content as Map<String, dynamic>)
.toList();
for (final userJson in json) {
users.add(
User(
id: userJson['id'] as String,
name: userJson['name'] as String,
password: userJson['password'] as String,
email: userJson['email'] as String,
profileImage: userJson['profileImage'] as String,
),
);
}
}
users
..removeWhere((u) => u.email == user.email)
..add(user);
await file.writeAsString(jsonEncode(users.map((e) => e.toJson()).toList()));
}
Future<void> _createFileIfNotExists() async {
final file = File(_fileName);
if (!await file.exists()) {
await file.create(recursive: true);
await file.writeAsString('[]');
}
}
}
| talk-stream-backend/packages/auth_data_source/lib/core/services/src/user_service.dart/0 | {'file_path': 'talk-stream-backend/packages/auth_data_source/lib/core/services/src/user_service.dart', 'repo_id': 'talk-stream-backend', 'token_count': 1331} |
import 'package:auth_data_source/auth_data_source.dart';
import 'package:chat_data_source/chat_data_source.dart';
import 'package:chat_data_source/core/services/services.dart';
class ChatDatasourceImplementation extends ChatDatasource {
ChatDatasourceImplementation({
this.databaseFileName = 'chat.json',
required this.userService,
}) : chatService = ChatService(databaseFileName, userService);
final ChatService chatService;
final UserService userService;
final String databaseFileName;
@override
Future<List<Chat>> getChats(String userId) async {
return (await chatService.getChatRooms(
userId,
));
}
@override
Future<Message> sendMessage(Message message) async {
final updMessage = message.copyWith(
roomId: chatService.generateChatRoomId(
message.members!.first,
message.members!.last,
));
await chatService.saveMessage(updMessage);
return updMessage;
}
}
| talk-stream-backend/packages/chat_data_source/lib/src/implementation/chat_data_source_implementation.dart/0 | {'file_path': 'talk-stream-backend/packages/chat_data_source/lib/src/implementation/chat_data_source_implementation.dart', 'repo_id': 'talk-stream-backend', 'token_count': 315} |
export 'src/go_router_service.dart';
export 'src/http_service.dart';
export 'src/web_socket_service.dart';
| talk-stream/lib/app/core/services/services.dart/0 | {'file_path': 'talk-stream/lib/app/core/services/services.dart', 'repo_id': 'talk-stream', 'token_count': 41} |
export 'cubits/signin_cubit.dart';
export 'cubits/signup_cubit.dart';
export 'models/models.dart';
export 'view/auth_page.dart';
export 'view/mobile_sign_in_page.dart';
export 'view/mobile_sign_up_page.dart';
export 'view/web_auth_page.dart';
export 'view/widgets/web_sign_in_widget.dart';
export 'view/widgets/web_sign_up_widget.dart';
| talk-stream/lib/auth/auth.dart/0 | {'file_path': 'talk-stream/lib/auth/auth.dart', 'repo_id': 'talk-stream', 'token_count': 140} |
import 'dart:async';
import 'dart:developer';
import 'package:bloc/bloc.dart';
import 'package:flutter/widgets.dart';
import 'package:talk_stream/app/core/locator.dart';
class AppBlocObserver extends BlocObserver {
const AppBlocObserver();
@override
void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) {
super.onChange(bloc, change);
log('onChange(${bloc.runtimeType}, $change)');
}
@override
void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) {
log('onError(${bloc.runtimeType}, $error, $stackTrace)');
super.onError(bloc, error, stackTrace);
}
}
Future<void> bootstrap(FutureOr<Widget> Function() builder) async {
WidgetsFlutterBinding.ensureInitialized();
setupLocator();
FlutterError.onError = (details) {
log(details.exceptionAsString(), stackTrace: details.stack);
};
Bloc.observer = const AppBlocObserver();
await runZonedGuarded(
() async => runApp(await builder()),
(error, stackTrace) => log(error.toString(), stackTrace: stackTrace),
);
}
| talk-stream/lib/bootstrap.dart/0 | {'file_path': 'talk-stream/lib/bootstrap.dart', 'repo_id': 'talk-stream', 'token_count': 380} |
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:talk_stream/app/src/constants/app_routes.dart';
import 'package:talk_stream/app/view/widgets/margins/y_margin.dart';
import 'package:talk_stream/auth/cubits/auth_cubit.dart';
import 'package:talk_stream/chat/cubits/all_users_cubit.dart';
import 'package:talk_stream/chat/view/widgets/chat_item_widget.dart';
class MobileAllUsersPage extends StatelessWidget {
const MobileAllUsersPage({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<AuthCubit, AuthState>(
builder: (context, state) {
if (state is AuthAuthenticated && state.user.id != null) {
return BlocProvider(
create: (context) => AllUsersCubit()..fetchAllUsers(state.user.id!),
lazy: false,
child: const MobileAllUsersView(),
);
}
return const Scaffold(
body: Center(
child: Text(
'An error occurred trying to authenticate user',
),
),
);
},
);
}
}
class MobileAllUsersView extends StatelessWidget {
const MobileAllUsersView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
'All Users',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w900,
),
),
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16,
),
child: Column(
children: [
const YMargin(16),
Expanded(
child: BlocBuilder<AllUsersCubit, AllUsersState>(
builder: (context, state) {
if (state is AllUsersLoaded) {
return ListView.separated(
itemBuilder: (_, index) {
final user = state.users[index];
return ChatItemWidget(
onTap: () {
context.push(
AppRoutes.mobileChatDetails,
extra: {
'user': user,
},
);
},
title: user.name?.toLowerCase(),
description: user.email,
profileImage: MemoryImage(
Uint8List.fromList(
user.profileImage!.codeUnits,
),
),
);
},
separatorBuilder: (_, __) => const YMargin(20),
itemCount: state.users.length,
);
} else if (state is AllUsersLoading) {
return const Center(
child: SizedBox(
height: 18,
width: 18,
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation(Color(0xFF1F1F1F)),
strokeWidth: 2,
),
),
);
} else if (state is AllUsersError) {
return Text(state.errorMessage);
}
return const Offstage();
},
),
)
],
),
),
),
);
}
}
| talk-stream/lib/chat/view/mobile_all_users_page.dart/0 | {'file_path': 'talk-stream/lib/chat/view/mobile_all_users_page.dart', 'repo_id': 'talk-stream', 'token_count': 2295} |
import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
part 'splash_state.dart';
class SplashCubit extends Cubit<SplashState> {
SplashCubit() : super(SplashInitial());
Future<void> splashDelay() async {
emit(SplashLoading());
await Future<dynamic>.delayed(
const Duration(seconds: 2),
);
emit(SplashLoaded());
}
}
| talk-stream/lib/splash/cubit/splash_cubit.dart/0 | {'file_path': 'talk-stream/lib/splash/cubit/splash_cubit.dart', 'repo_id': 'talk-stream', 'token_count': 135} |
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:convert';
class ClientError {
ClientError({
required this.message,
});
final String message;
Map<String, dynamic> toMap() {
return <String, dynamic>{
'message': message,
};
}
factory ClientError.fromMap(Map<String, dynamic> map) {
return ClientError(
message: map['message'] as String,
);
}
String toJson() => json.encode(toMap());
factory ClientError.fromJson(String source) =>
ClientError.fromMap(json.decode(source) as Map<String, dynamic>);
}
| teamship-dart-frog/lib/data/models/client_error.dart/0 | {'file_path': 'teamship-dart-frog/lib/data/models/client_error.dart', 'repo_id': 'teamship-dart-frog', 'token_count': 210} |
import 'package:dart_frog/dart_frog.dart';
import 'package:team_ship_dart_frog/middlewares/bearer_auth_middleware.dart';
import 'package:team_ship_dart_frog/middlewares/db_middleware.dart';
Handler middleware(Handler handler) =>
handler.use(requestLogger()).use(dbMiddleware).use(bearerAuthMiddleware);
| teamship-dart-frog/routes/_middleware.dart/0 | {'file_path': 'teamship-dart-frog/routes/_middleware.dart', 'repo_id': 'teamship-dart-frog', 'token_count': 110} |
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:test/test.dart';
import 'package:test_coverage/test_coverage.dart';
void main() {
final stubPath = path.join(Directory.current.path, 'test', 'stub_package');
final stubDir = Directory(stubPath);
group('findTestFiles', () {
test('finds only test files', () {
final result = findTestFiles(stubDir);
expect(result, hasLength(2));
final filenames =
result.map((f) => f.path.split(path.separator).last).toList();
expect(filenames, contains('a_test.dart'));
expect(filenames, contains('b_test.dart'));
expect(filenames, isNot(contains('c.dart')));
});
});
group('smoke test', () {
final coverageDir = Directory(path.join(stubPath, 'coverage'));
final Directory savedCurrent = Directory.current;
final testFile = File(path.join(stubPath, 'test', '.test_coverage.dart'));
final lcovFile = File(path.join(coverageDir.path, 'lcov.info'));
final badgeFile = File(path.join(stubPath, 'coverage_badge.svg'));
setUp(() {
Process.runSync('pub', ['get'], workingDirectory: stubPath);
if (testFile.existsSync()) testFile.deleteSync();
if (coverageDir.existsSync()) coverageDir.deleteSync(recursive: true);
if (badgeFile.existsSync()) badgeFile.deleteSync();
// Set working directory for current process because Lcov formatter
// relies on it to resolve absolute paths for dart files in stub_package.
Directory.current = stubPath;
});
tearDown(() {
Directory.current = savedCurrent.path;
});
test('run', () async {
final files = findTestFiles(stubDir);
generateMainScript(stubDir, files);
expect(testFile.existsSync(), isTrue);
final content = testFile.readAsStringSync();
expect(content, contains("a_test.main();"));
expect(content, contains("nested_b_test.main();"));
// Set custom port so that when running test_coverage for this test
// we can start another Observatory for stub_package on the default port.
await runTestsAndCollect(stubPath, '8585');
expect(lcovFile.existsSync(), isTrue);
final coverageValue = calculateLineCoverage(lcovFile);
expect(coverageValue, 1.0);
generateBadge(stubDir, coverageValue);
expect(badgeFile.existsSync(), isTrue);
});
});
group('$TestFileInfo', () {
test('for file', () {
final a = File(path.join(stubPath, 'test', 'a_test.dart'));
final info = TestFileInfo.forFile(a);
expect(info.alias, 'a_test');
expect(info.import, "import 'a_test.dart' as a_test;");
expect(info.testFile, a);
});
test('for nested file', () {
final b = File(path.join(stubPath, 'test', 'nested', 'b_test.dart'));
final info = TestFileInfo.forFile(b);
expect(info.alias, 'nested_b_test');
expect(info.import, "import 'nested/b_test.dart' as nested_b_test;");
expect(info.testFile, b);
});
});
}
| test-coverage/test/test_coverage_test.dart/0 | {'file_path': 'test-coverage/test/test_coverage_test.dart', 'repo_id': 'test-coverage', 'token_count': 1161} |
# See https://pub.dev/packages/mono_repo
sdk:
- dev
- pubspec
stages:
- analyze_and_format:
- group:
- format
- analyze: --fatal-infos
sdk:
- dev
- unit_test:
- test: -p chrome,vm,node
os:
- linux
- windows
| test/integration_tests/spawn_hybrid/mono_pkg.yaml/0 | {'file_path': 'test/integration_tests/spawn_hybrid/mono_pkg.yaml', 'repo_id': 'test', 'token_count': 114} |
// Copyright (c) 2022, 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.
String literal(Object? o) {
if (o == null || o is num || o is bool) return '<$o>';
// TODO Truncate long strings?
// TODO: handle strings with embedded `'`
// TODO: special handling of multi-line strings?
if (o is String) return "'$o'";
// TODO Truncate long collections?
return '$o';
}
Iterable<String> indent(Iterable<String> lines) => lines.map((l) => ' $l');
| test/pkgs/checks/lib/src/describe.dart/0 | {'file_path': 'test/pkgs/checks/lib/src/describe.dart', 'repo_id': 'test', 'token_count': 189} |
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as p;
import 'package:test_api/src/backend/runtime.dart'; // ignore: implementation_imports
import 'package:test_core/src/util/io.dart'; // ignore: implementation_imports
import '../executable_settings.dart';
import 'browser.dart';
import 'default_settings.dart';
/// A class for running an instance of Safari.
///
/// Any errors starting or running the process are reported through [onExit].
class Safari extends Browser {
@override
final name = 'Safari';
Safari(url, {ExecutableSettings? settings})
: super(() =>
_startBrowser(url, settings ?? defaultSettings[Runtime.safari]!));
/// Starts a new instance of Safari open to the given [url], which may be a
/// [Uri] or a [String].
static Future<Process> _startBrowser(url, ExecutableSettings settings) async {
var dir = createTempDir();
// Safari will only open files (not general URLs) via the command-line
// API, so we create a dummy file to redirect it to the page we actually
// want it to load.
var redirect = p.join(dir, 'redirect.html');
File(redirect).writeAsStringSync(
'<script>location = ${jsonEncode(url.toString())}</script>');
var process = await Process.start(
settings.executable, settings.arguments.toList()..add(redirect));
unawaited(process.exitCode
.then((_) => Directory(dir).deleteSync(recursive: true)));
return process;
}
}
| test/pkgs/test/lib/src/runner/browser/safari.dart/0 | {'file_path': 'test/pkgs/test/lib/src/runner/browser/safari.dart', 'repo_id': 'test', 'token_count': 550} |
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
@TestOn('vm')
import 'dart:convert';
import 'package:test/test.dart';
import 'package:test_core/src/util/exit_codes.dart' as exit_codes;
import 'package:test_descriptor/test_descriptor.dart' as d;
import '../../io.dart';
void main() {
setUpAll(precompileTestExecutable);
test('ignores an empty file', () async {
await d.file('global_test.yaml', '').create();
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("success", () {});
}
''').create();
var test = await runTest(['test.dart'],
environment: {'DART_TEST_CONFIG': 'global_test.yaml'});
expect(test.stdout, emitsThrough(contains('+1: All tests passed!')));
await test.shouldExit(0);
});
test('uses supported test configuration', () async {
await d
.file('global_test.yaml', jsonEncode({'verbose_trace': true}))
.create();
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("failure", () => throw "oh no");
}
''').create();
var test = await runTest(['test.dart'],
environment: {'DART_TEST_CONFIG': 'global_test.yaml'});
expect(test.stdout, emitsThrough(contains('dart:async')));
await test.shouldExit(1);
});
test('uses supported runner configuration', () async {
await d.file('global_test.yaml', jsonEncode({'reporter': 'json'})).create();
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("success", () {});
}
''').create();
var test = await runTest(['test.dart'],
environment: {'DART_TEST_CONFIG': 'global_test.yaml'});
expect(test.stdout, emitsThrough(contains('"testStart"')));
await test.shouldExit(0);
});
test('local configuration takes precedence', () async {
await d
.file('global_test.yaml', jsonEncode({'verbose_trace': true}))
.create();
await d
.file('dart_test.yaml', jsonEncode({'verbose_trace': false}))
.create();
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("failure", () => throw "oh no");
}
''').create();
var test = await runTest(['test.dart'],
environment: {'DART_TEST_CONFIG': 'global_test.yaml'});
expect(test.stdout, neverEmits(contains('dart:isolate-patch')));
await test.shouldExit(1);
});
group('disallows local-only configuration:', () {
for (var field in [
'skip', 'retry', 'test_on', 'paths', 'filename', 'names', 'tags', //
'plain_names', 'include_tags', 'exclude_tags', 'pub_serve', 'add_tags',
'define_platforms', 'allow_duplicate_test_names',
]) {
test('for $field', () async {
await d.file('global_test.yaml', jsonEncode({field: null})).create();
await d.file('test.dart', '''
import 'package:test/test.dart';
void main() {
test("success", () {});
}
''').create();
var test = await runTest(['test.dart'],
environment: {'DART_TEST_CONFIG': 'global_test.yaml'});
expect(
test.stderr,
containsInOrder(
["of global_test.yaml: $field isn't supported here.", '^^']));
await test.shouldExit(exit_codes.data);
});
}
});
}
| test/pkgs/test/test/runner/configuration/global_test.dart/0 | {'file_path': 'test/pkgs/test/test/runner/configuration/global_test.dart', 'repo_id': 'test', 'token_count': 1504} |
// Copyright (c) 2020, 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:convert';
import 'package:path/path.dart' as p;
import 'package:test/test.dart';
import 'package:test_core/src/runner/version.dart';
import 'package:test_descriptor/test_descriptor.dart' as d;
/// Asserts that the outputs from running tests with a JSON reporter match the
/// given expectations.
///
/// Verifies that [outputLines] matches each set of matchers in [expected],
/// includes the [testPid] from the test process, and ends with [done].
Future<void> expectJsonReport(
List<String> outputLines,
int testPid,
List<List<Object /*Map|Matcher*/ >> expected,
Map<Object, Object> done) async {
// Ensure the output is of the same length, including start, done and all
// suites messages.
expect(outputLines,
hasLength(expected.fold<int>(3, (int a, m) => a + m.length)));
dynamic decodeLine(String l) => jsonDecode(l)
..remove('time')
..remove('stackTrace');
// Should contain all suites message.
expect(outputLines.map(decodeLine), containsAll([allSuitesJson()]));
// A single start event is emitted first.
final start = {
'type': 'start',
'protocolVersion': '0.1.1',
'runnerVersion': testVersion,
'pid': testPid,
};
expect(decodeLine(outputLines.first), equals(start));
// A single done event is emitted last.
expect(decodeLine(outputLines.last), equals(done));
for (var value in expected) {
expect(outputLines.map(decodeLine), containsAllInOrder(value));
}
}
/// Returns the event emitted by the JSON reporter providing information about
/// all suites.
///
/// The [count] defaults to 1.
Map<String, Object> allSuitesJson({int count = 1}) {
return {'type': 'allSuites', 'count': count};
}
/// Returns the event emitted by the JSON reporter indicating that a suite has
/// begun running.
///
/// The [platform] defaults to `"vm"`, the [path] defaults to `"test.dart"`.
Map<String, Object> suiteJson(int id,
{String platform = 'vm', String path = 'test.dart'}) {
return {
'type': 'suite',
'suite': {
'id': id,
'platform': platform,
'path': path,
}
};
}
/// Returns the event emitted by the JSON reporter indicating that a group has
/// begun running.
///
/// If [skip] is `true`, the group is expected to be marked as skipped without a
/// reason. If it's a [String], the group is expected to be marked as skipped
/// with that reason.
///
/// The [testCount] parameter indicates the number of tests in the group. It
/// defaults to 1.
Map<String, Object> groupJson(int id,
{String? name,
int? suiteID,
int? parentID,
Object? skip,
int? testCount,
int? line,
int? column}) {
if ((line == null) != (column == null)) {
throw ArgumentError(
'line and column must either both be null or both be passed');
}
return {
'type': 'group',
'group': {
'id': id,
'name': name ?? '',
'suiteID': suiteID ?? 0,
'parentID': parentID,
'metadata': metadataJson(skip: skip),
'testCount': testCount ?? 1,
'line': line,
'column': column,
'url': line == null
? null
: p.toUri(p.join(d.sandbox, 'test.dart')).toString()
}
};
}
/// Returns the event emitted by the JSON reporter indicating that a test has
/// begun running.
///
/// If [parentIDs] is passed, it's the IDs of groups containing this test. If
/// [skip] is `true`, the test is expected to be marked as skipped without a
/// reason. If it's a [String], the test is expected to be marked as skipped
/// with that reason.
Map<String, Object> testStartJson(int id, String name,
{int? suiteID,
Iterable<int>? groupIDs,
int? line,
int? column,
String? url,
Object? skip,
int? rootLine,
int? rootColumn,
String? rootUrl}) {
if ((line == null) != (column == null)) {
throw ArgumentError(
'line and column must either both be null or both be passed');
}
url ??=
line == null ? null : p.toUri(p.join(d.sandbox, 'test.dart')).toString();
var expected = {
'type': 'testStart',
'test': {
'id': id,
'name': name,
'suiteID': suiteID ?? 0,
'groupIDs': groupIDs ?? [2],
'metadata': metadataJson(skip: skip),
'line': line,
'column': column,
'url': url,
}
};
var testObj = expected['test'] as Map<String, dynamic>;
if (rootLine != null) {
testObj['root_line'] = rootLine;
}
if (rootColumn != null) {
testObj['root_column'] = rootColumn;
}
if (rootUrl != null) {
testObj['root_url'] = rootUrl;
}
return expected;
}
/// Returns the event emitted by the JSON reporter indicating that a test
/// printed [message].
Matcher printJson(int id, dynamic /*String|Matcher*/ message,
{String type = 'print'}) {
return allOf(
hasLength(4),
containsPair('type', 'print'),
containsPair('testID', id),
containsPair('message', message),
containsPair('messageType', type),
);
}
/// Returns the event emitted by the JSON reporter indicating that a test
/// emitted [error].
///
/// The [isFailure] parameter indicates whether the error was a [TestFailure] or
/// not.
Map<String, Object> errorJson(int id, String error, {bool isFailure = false}) {
return {
'type': 'error',
'testID': id,
'error': error,
'isFailure': isFailure
};
}
/// Returns the event emitted by the JSON reporter indicating that a test
/// finished.
///
/// The [result] parameter indicates the result of the test. It defaults to
/// `"success"`.
///
/// The [hidden] parameter indicates whether the test should not be displayed
/// after finishing. The [skipped] parameter indicates whether the test was
/// skipped.
Map<String, Object> testDoneJson(int id,
{String result = 'success', bool hidden = false, bool skipped = false}) {
return {
'type': 'testDone',
'testID': id,
'result': result,
'hidden': hidden,
'skipped': skipped
};
}
/// Returns the event emitted by the JSON reporter indicating that the entire
/// run finished.
Map<String, Object> doneJson({bool success = true}) =>
{'type': 'done', 'success': success};
/// Returns the serialized metadata corresponding to [skip].
Map<String, Object?> metadataJson({skip}) {
if (skip == true) {
return {'skip': true, 'skipReason': null};
} else if (skip is String) {
return {'skip': true, 'skipReason': skip};
} else {
return {'skip': false, 'skipReason': null};
}
}
| test/pkgs/test/test/runner/json_reporter_utils.dart/0 | {'file_path': 'test/pkgs/test/test/runner/json_reporter_utils.dart', 'repo_id': 'test', 'token_count': 2296} |
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
@TestOn('vm')
import 'package:test/test.dart';
import 'package:test_descriptor/test_descriptor.dart' as d;
import '../io.dart';
void main() {
setUpAll(precompileTestExecutable);
test('only runs the tests marked as solo', () async {
await d.file('test.dart', '''
import 'dart:async';
import 'package:test/test.dart';
void main() {
test("passes", () {
expect(true, isTrue);
}, solo: true);
test("failed", () {
throw 'some error';
});
}
''').create();
var test = await runTest(['test.dart']);
expect(test.stdout, emitsThrough(contains('+1 ~1: All tests passed!')));
await test.shouldExit(0);
});
test('only runs groups marked as solo', () async {
await d.file('test.dart', '''
import 'dart:async';
import 'package:test/test.dart';
void main() {
group('solo', () {
test("first pass", () {
expect(true, isTrue);
});
test("second pass", () {
expect(true, isTrue);
});
}, solo: true);
group('no solo', () {
test("failure", () {
throw 'some error';
});
test("another failure", () {
throw 'some error';
});
});
}
''').create();
var test = await runTest(['test.dart']);
expect(test.stdout, emitsThrough(contains('+2 ~1: All tests passed!')));
await test.shouldExit(0);
});
}
| test/pkgs/test/test/runner/solo_test.dart/0 | {'file_path': 'test/pkgs/test/test/runner/solo_test.dart', 'repo_id': 'test', 'token_count': 878} |
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
@Deprecated('package:test_api is not intended for general use. '
'Please use package:test.')
library test_api.backend;
export 'src/backend/metadata.dart' show Metadata;
export 'src/backend/platform_selector.dart' show PlatformSelector;
export 'src/backend/remote_exception.dart' show RemoteException;
export 'src/backend/remote_listener.dart' show RemoteListener;
export 'src/backend/runtime.dart' show Runtime;
export 'src/backend/stack_trace_formatter.dart' show StackTraceFormatter;
export 'src/backend/stack_trace_mapper.dart' show StackTraceMapper;
export 'src/backend/suite_platform.dart' show SuitePlatform;
| test/pkgs/test_api/lib/backend.dart/0 | {'file_path': 'test/pkgs/test_api/lib/backend.dart', 'repo_id': 'test', 'token_count': 260} |
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'group.dart';
import 'message.dart';
import 'state.dart';
import 'suite.dart';
import 'test.dart';
/// A runnable instance of a test.
///
/// This is distinct from [Test] in order to keep [Test] immutable. Running a
/// test requires state, and [LiveTest] provides a view of the state of the test
/// as it runs.
///
/// If the state changes, [state] will be updated before [onStateChange] fires.
/// Likewise, if an error is caught, it will be added to [errors] before being
/// emitted via [onError]. If an error causes a state change, [onStateChange]
/// will fire before [onError]. If an error or other state change causes the
/// test to complete, [onComplete] will complete after [onStateChange] and
/// [onError] fire.
abstract class LiveTest {
/// The suite within which this test is being run.
Suite get suite;
/// The groups within which this test is being run, from the outermost to the
/// innermost.
///
/// This will always contain at least the implicit top-level group.
List<Group> get groups;
/// The running test.
Test get test;
/// The current state of the running test.
///
/// This starts as [Status.pending] and [Result.success]. It will be updated
/// before [onStateChange] fires.
///
/// Note that even if this is marked [Status.complete], the test may still be
/// running code asynchronously. A test is considered complete either once it
/// hits its first error or when all [expectAsync] callbacks have been called
/// and any returned [Future] has completed, but it's possible for further
/// processing to happen, which may cause further errors. It's even possible
/// for a test that was marked [Status.complete] and [Result.success] to be
/// marked as [Result.error] later.
State get state;
/// Returns whether this test has completed.
///
/// This is equivalent to [state.status] being [Status.complete].
///
/// Note that even if this returns `true`, the test may still be
/// running code asynchronously. A test is considered complete either once it
/// hits its first error or when all [expectAsync] callbacks have been called
/// and any returned [Future] has completed, but it's possible for further
/// processing to happen, which may cause further errors.
bool get isComplete => state.status == Status.complete;
// A stream that emits a new [State] whenever [state] changes.
//
// This will only ever emit a [State] if it's different than the previous
// [state]. It will emit an event after [state] has been updated. Note that
// since this is an asynchronous stream, it's possible for [state] not to
// match the [State] that it emits within the [Stream.listen] callback.
Stream<State> get onStateChange;
/// An unmodifiable list of all errors that have been caught while running
/// this test.
///
/// This will be updated before [onError] fires. These errors are not
/// guaranteed to have the same types as when they were thrown; for example,
/// they may need to be serialized across isolate boundaries. The stack traces
/// will be [Chain]s.
List<AsyncError> get errors;
/// A stream that emits a new [AsyncError] whenever an error is caught.
///
/// This will be emit an event after [errors] is updated. These errors are not
/// guaranteed to have the same types as when they were thrown; for example,
/// they may need to be serialized across isolate boundaries. The stack traces
/// will be [Chain]s.
Stream<AsyncError> get onError;
/// A stream that emits messages produced by the test.
Stream<Message> get onMessage;
/// A [Future] that completes once the test is complete.
///
/// This will complete after [onStateChange] has fired, and after [onError]
/// has fired if the test completes because of an error. It's the same as the
/// [Future] returned by [run].
///
/// Note that even once this completes, the test may still be running code
/// asynchronously. A test is considered complete either once it hits its
/// first error or when all [expectAsync] callbacks have been called and any
/// returned [Future] has completed, but it's possible for further processing
/// to happen, which may cause further errors.
Future get onComplete;
/// The name of this live test without any group prefixes.
String get individualName {
var group = groups.last;
if (group.name.isEmpty) return test.name;
if (!test.name.startsWith(group.name)) return test.name;
// The test will have the same name as the group for virtual tests created
// to represent skipping the entire group.
if (test.name.length == group.name.length) return '';
return test.name.substring(group.name.length + 1);
}
/// Loads a copy of this [LiveTest] that's able to be run again.
LiveTest copy() => test.load(suite, groups: groups);
/// Signals that this test should start running as soon as possible.
///
/// A test may not start running immediately for various reasons specific to
/// the means by which it's defined. Until it starts running, [state] will
/// continue to be marked [Status.pending].
///
/// This returns the same [Future] as [onComplete]. It may not be called more
/// than once.
Future run();
/// Signals that this test should stop emitting events and release any
/// resources it may have allocated.
///
/// Once [close] is called, [onComplete] will complete if it hasn't already
/// and [onStateChange] and [onError] will close immediately. This means that,
/// if the test was running at the time [close] is called, it will never emit
/// a [Status.complete] state-change event. Once a test is closed, [expect]
/// and [expectAsync] will throw a [ClosedException] to help the test
/// terminate as quickly as possible.
///
/// This doesn't automatically happen after the test completes because there
/// may be more asynchronous work going on in the background that could
/// produce new errors.
///
/// Returns a [Future] that completes once all resources are released *and*
/// the test has completed. This allows the caller to wait until the test's
/// tear-down logic has run.
Future close();
}
| test/pkgs/test_api/lib/src/backend/live_test.dart/0 | {'file_path': 'test/pkgs/test_api/lib/src/backend/live_test.dart', 'repo_id': 'test', 'token_count': 1709} |
// Copyright (c) 2021, 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.
/// An exception thrown when a test assertion fails.
class TestFailure implements Exception {
final String? message;
TestFailure(this.message);
@override
String toString() => message.toString();
}
| test/pkgs/test_api/lib/src/backend/test_failure.dart/0 | {'file_path': 'test/pkgs/test_api/lib/src/backend/test_failure.dart', 'repo_id': 'test', 'token_count': 109} |
// Copyright (c) 2021, 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.
@Deprecated('Moved to src/expect/expect.dart')
library test_api.src.frontend.expect;
// Temporary re-export to avoid churn in analyzer tests.
export '../expect/expect.dart';
| test/pkgs/test_api/lib/src/frontend/expect.dart/0 | {'file_path': 'test/pkgs/test_api/lib/src/frontend/expect.dart', 'repo_id': 'test', 'token_count': 117} |
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:test/test.dart';
import 'package:test_api/fake.dart' as test_api;
void main() {
late _FakeSample fake;
setUp(() {
fake = _FakeSample();
});
test('method invocation', () {
expect(() => fake.f(), throwsA(TypeMatcher<UnimplementedError>()));
});
test('getter', () {
expect(() => fake.x, throwsA(TypeMatcher<UnimplementedError>()));
});
test('setter', () {
expect(() => fake.x = 0, throwsA(TypeMatcher<UnimplementedError>()));
});
test('operator', () {
expect(() => fake + 1, throwsA(TypeMatcher<UnimplementedError>()));
});
}
class _Sample {
void f() {}
int get x => 0;
set x(int value) {}
int operator +(int other) => 0;
}
class _FakeSample extends test_api.Fake implements _Sample {}
| test/pkgs/test_api/test/frontend/fake_test.dart/0 | {'file_path': 'test/pkgs/test_api/test/frontend/fake_test.dart', 'repo_id': 'test', 'token_count': 339} |
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'dart:math' as math;
import 'package:async/async.dart';
import '../util/io.dart';
/// An interactive console for taking user commands.
class Console {
/// The registered commands.
final _commands = <String, _Command>{};
/// The pending next line of standard input, if we're waiting on one.
CancelableOperation? _nextLine;
/// Whether the console is currently running.
bool _running = false;
/// The terminal escape for red text, or the empty string if this is Windows
/// or not outputting to a terminal.
final String _red;
/// The terminal escape for bold text, or the empty string if this is
/// Windows or not outputting to a terminal.
final String _bold;
/// The terminal escape for removing test coloring, or the empty string if
/// this is Windows or not outputting to a terminal.
final String _noColor;
/// Creates a new [Console].
///
/// If [color] is true, this uses Unix terminal colors.
Console({bool color = true})
: _red = color ? '\u001b[31m' : '',
_bold = color ? '\u001b[1m' : '',
_noColor = color ? '\u001b[0m' : '' {
registerCommand('help', 'Displays this help information.', _displayHelp);
}
/// Registers a command to be run whenever the user types [name].
///
/// The [description] should be a one-line description of the command to print
/// in the help output. The [body] callback will be called when the user types
/// the command, and may return a [Future].
void registerCommand(
String name, String description, dynamic Function() body) {
if (_commands.containsKey(name)) {
throw ArgumentError('The console already has a command named "$name".');
}
_commands[name] = _Command(name, description, body);
}
/// Starts running the console.
///
/// This prints the initial prompt and loops while waiting for user input.
void start() {
_running = true;
unawaited(() async {
while (_running) {
stdout.write('> ');
_nextLine = stdinLines.cancelable((queue) => queue.next);
var commandName = await _nextLine!.value;
_nextLine = null;
var command = _commands[commandName];
if (command == null) {
stderr.writeln(
'${_red}Unknown command $_bold$commandName$_noColor$_red.'
'$_noColor');
} else {
await command.body();
}
}
}());
}
/// Stops the console running.
void stop() {
_running = false;
if (_nextLine != null) {
stdout.writeln();
_nextLine!.cancel();
}
}
/// Displays the help info for the console commands.
void _displayHelp() {
var maxCommandLength =
_commands.values.map((command) => command.name.length).reduce(math.max);
for (var command in _commands.values) {
var name = command.name.padRight(maxCommandLength + 4);
print('$_bold$name$_noColor${command.description}');
}
}
}
/// An individual console command.
class _Command {
/// The name of the command.
final String name;
/// The single-line description of the command.
final String description;
/// The callback to run when the command is invoked.
final Function body;
_Command(this.name, this.description, this.body);
}
| test/pkgs/test_core/lib/src/runner/console.dart/0 | {'file_path': 'test/pkgs/test_core/lib/src/runner/console.dart', 'repo_id': 'test', 'token_count': 1183} |
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:test_api/src/backend/suite_platform.dart'; // ignore: implementation_imports
import 'environment.dart';
import 'runner_suite.dart';
import 'suite.dart';
/// A class that defines a platform for which test suites can be loaded.
///
/// A minimal plugin must define [loadChannel], which connects to a client in
/// which the tests are defined. This is enough to support most of the test
/// runner's functionality.
///
/// In order to support interactive debugging, a plugin must override [load] as
/// well, which returns a [RunnerSuite] that can contain a custom [Environment]
/// and control debugging metadata such as [RunnerSuite.isDebugging] and
/// [RunnerSuite.onDebugging]. The plugin must create this suite by calling the
/// [deserializeSuite] helper function.
///
/// A platform plugin can be registered by passing it to [Loader.new]'s
/// `plugins` parameter.
abstract class PlatformPlugin {
/// Loads the runner suite for the test file at [path] using [platform], with
/// [suiteConfig] encoding the suite-specific configuration.
///
/// By default, this just calls [loadChannel] and passes its result to
/// [deserializeSuite]. However, it can be overridden to provide more
/// fine-grained control over the [RunnerSuite], including providing a custom
/// implementation of [Environment].
///
/// Subclasses overriding this method must call [deserializeSuite] in
/// `platform_helpers.dart` to obtain a [RunnerSuiteController]. They must
/// pass the opaque [message] parameter to the [deserializeSuite] call.
Future<RunnerSuite?> load(String path, SuitePlatform platform,
SuiteConfiguration suiteConfig, Map<String, Object?> message);
Future closeEphemeral() async {}
Future close() async {}
}
| test/pkgs/test_core/lib/src/runner/platform.dart/0 | {'file_path': 'test/pkgs/test_core/lib/src/runner/platform.dart', 'repo_id': 'test', 'token_count': 522} |
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'package:collection/collection.dart';
/// An unmodifiable [Set] view backed by an arbitrary [Iterable].
///
/// Note that contrary to most APIs that take iterables, this does not convert
/// its argument to another collection before use. This means that if it's
/// lazily-generated, that generation will happen for every operation.
///
/// Note also that set operations that are usually expected to be `O(1)` or
/// `O(log(n))`, such as [contains], may be `O(n)` for many underlying iterable
/// types. As such, this should only be used for small iterables.
class IterableSet<E> with SetMixin<E>, UnmodifiableSetMixin<E> {
/// The base iterable that set operations forward to.
final Iterable<E> _base;
@override
int get length => _base.length;
@override
Iterator<E> get iterator => _base.iterator;
/// Creates a [Set] view of [base].
IterableSet(this._base);
@override
bool contains(Object? element) => _base.contains(element);
@override
E? lookup(Object? element) {
for (var e in _base) {
if (e == element) return e;
}
return null;
}
@override
Set<E> toSet() => _base.toSet();
}
| test/pkgs/test_core/lib/src/runner/util/iterable_set.dart/0 | {'file_path': 'test/pkgs/test_core/lib/src/runner/util/iterable_set.dart', 'repo_id': 'test', 'token_count': 428} |
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
class PrintSink implements StringSink {
final _buffer = StringBuffer();
@override
void write(Object? obj) {
_buffer.write(obj);
_flush();
}
@override
void writeAll(Iterable objects, [String separator = '']) {
_buffer.writeAll(objects, separator);
_flush();
}
@override
void writeCharCode(int charCode) {
_buffer.writeCharCode(charCode);
_flush();
}
@override
void writeln([Object? obj = '']) {
_buffer.writeln(obj ?? '');
_flush();
}
/// [print] if the content available ends with a newline.
void _flush() {
if ('$_buffer'.endsWith('\n')) {
print(_buffer);
_buffer.clear();
}
}
}
| test/pkgs/test_core/lib/src/util/print_sink.dart/0 | {'file_path': 'test/pkgs/test_core/lib/src/util/print_sink.dart', 'repo_id': 'test', 'token_count': 314} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.