code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
// Dart
import 'dart:convert';
import 'package:http/http.dart' as http;
class Example {
Future<String> _getIPAddress() {
final url = Uri.https('httpbin.org', '/ip');
return http.get(url).then((response) {
final ip = jsonDecode(response.body)['origin'] as String;
return ip;
});
}
}
void main() {
final example = Example();
example
._getIPAddress()
.then((ip) => print(ip))
.catchError((error) => print(error));
}
| website/examples/get-started/flutter-for/react_native_devs/lib/futures.dart/0 | {'file_path': 'website/examples/get-started/flutter-for/react_native_devs/lib/futures.dart', 'repo_id': 'website', 'token_count': 184} |
import 'package:flutter/material.dart';
// #docregion Main
void main() {
runApp(const MyApp());
}
// #enddocregion Main
// #docregion MyApp
class MyApp extends StatelessWidget {
/// This widget is the root of your application.
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const Center(
child: Text(
'Hello World!',
textDirection: TextDirection.ltr,
),
);
}
}
// #enddocregion MyApp
| website/examples/get-started/flutter-for/xamarin_devs/lib/main.dart/0 | {'file_path': 'website/examples/get-started/flutter-for/xamarin_devs/lib/main.dart', 'repo_id': 'website', 'token_count': 173} |
name: integration_test_example
publish_to: none
version: 0.0.1
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
dev_dependencies:
example_utils:
path: ../example_utils
integration_test:
sdk: flutter
flutter_test:
sdk: flutter
flutter_driver:
sdk: flutter
test: ^1.24.6
flutter:
uses-material-design: true
| website/examples/integration_test/pubspec.yaml/0 | {'file_path': 'website/examples/integration_test/pubspec.yaml', 'repo_id': 'website', 'token_count': 152} |
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/date_symbol_data_custom.dart' as date_symbol_data_custom;
import 'package:intl/date_symbols.dart' as intl;
import 'package:intl/intl.dart' as intl;
/// A custom set of date patterns for the `nn` locale.
///
/// These are not accurate and are just a clone of the date patterns for the
/// `no` locale to demonstrate how one would write and use custom date patterns.
// #docregion Date
const nnLocaleDatePatterns = {
'd': 'd.',
'E': 'ccc',
'EEEE': 'cccc',
'LLL': 'LLL',
// #enddocregion Date
'LLLL': 'LLLL',
'M': 'L.',
'Md': 'd.M.',
'MEd': 'EEE d.M.',
'MMM': 'LLL',
'MMMd': 'd. MMM',
'MMMEd': 'EEE d. MMM',
'MMMM': 'LLLL',
'MMMMd': 'd. MMMM',
'MMMMEEEEd': 'EEEE d. MMMM',
'QQQ': 'QQQ',
'QQQQ': 'QQQQ',
'y': 'y',
'yM': 'M.y',
'yMd': 'd.M.y',
'yMEd': 'EEE d.MM.y',
'yMMM': 'MMM y',
'yMMMd': 'd. MMM y',
'yMMMEd': 'EEE d. MMM y',
'yMMMM': 'MMMM y',
'yMMMMd': 'd. MMMM y',
'yMMMMEEEEd': 'EEEE d. MMMM y',
'yQQQ': 'QQQ y',
'yQQQQ': 'QQQQ y',
'H': 'HH',
'Hm': 'HH:mm',
'Hms': 'HH:mm:ss',
'j': 'HH',
'jm': 'HH:mm',
'jms': 'HH:mm:ss',
'jmv': 'HH:mm v',
'jmz': 'HH:mm z',
'jz': 'HH z',
'm': 'm',
'ms': 'mm:ss',
's': 's',
'v': 'v',
'z': 'z',
'zzzz': 'zzzz',
'ZZZZ': 'ZZZZ',
};
/// A custom set of date symbols for the `nn` locale.
///
/// These are not accurate and are just a clone of the date symbols for the
/// `no` locale to demonstrate how one would write and use custom date symbols.
// #docregion Date2
const nnDateSymbols = {
'NAME': 'nn',
'ERAS': <dynamic>[
'f.Kr.',
'e.Kr.',
],
// #enddocregion Date2
'ERANAMES': <dynamic>[
'før Kristus',
'etter Kristus',
],
'NARROWMONTHS': <dynamic>[
'J',
'F',
'M',
'A',
'M',
'J',
'J',
'A',
'S',
'O',
'N',
'D',
],
'STANDALONENARROWMONTHS': <dynamic>[
'J',
'F',
'M',
'A',
'M',
'J',
'J',
'A',
'S',
'O',
'N',
'D',
],
'MONTHS': <dynamic>[
'januar',
'februar',
'mars',
'april',
'mai',
'juni',
'juli',
'august',
'september',
'oktober',
'november',
'desember',
],
'STANDALONEMONTHS': <dynamic>[
'januar',
'februar',
'mars',
'april',
'mai',
'juni',
'juli',
'august',
'september',
'oktober',
'november',
'desember',
],
'SHORTMONTHS': <dynamic>[
'jan.',
'feb.',
'mar.',
'apr.',
'mai',
'jun.',
'jul.',
'aug.',
'sep.',
'okt.',
'nov.',
'des.',
],
'STANDALONESHORTMONTHS': <dynamic>[
'jan',
'feb',
'mar',
'apr',
'mai',
'jun',
'jul',
'aug',
'sep',
'okt',
'nov',
'des',
],
'WEEKDAYS': <dynamic>[
'søndag',
'mandag',
'tirsdag',
'onsdag',
'torsdag',
'fredag',
'lørdag',
],
'STANDALONEWEEKDAYS': <dynamic>[
'søndag',
'mandag',
'tirsdag',
'onsdag',
'torsdag',
'fredag',
'lørdag',
],
'SHORTWEEKDAYS': <dynamic>[
'søn.',
'man.',
'tir.',
'ons.',
'tor.',
'fre.',
'lør.',
],
'STANDALONESHORTWEEKDAYS': <dynamic>[
'søn.',
'man.',
'tir.',
'ons.',
'tor.',
'fre.',
'lør.',
],
'NARROWWEEKDAYS': <dynamic>[
'S',
'M',
'T',
'O',
'T',
'F',
'L',
],
'STANDALONENARROWWEEKDAYS': <dynamic>[
'S',
'M',
'T',
'O',
'T',
'F',
'L',
],
'SHORTQUARTERS': <dynamic>[
'K1',
'K2',
'K3',
'K4',
],
'QUARTERS': <dynamic>[
'1. kvartal',
'2. kvartal',
'3. kvartal',
'4. kvartal',
],
'AMPMS': <dynamic>[
'a.m.',
'p.m.',
],
'DATEFORMATS': <dynamic>[
'EEEE d. MMMM y',
'd. MMMM y',
'd. MMM y',
'dd.MM.y',
],
'TIMEFORMATS': <dynamic>[
'HH:mm:ss zzzz',
'HH:mm:ss z',
'HH:mm:ss',
'HH:mm',
],
'AVAILABLEFORMATS': null,
'FIRSTDAYOFWEEK': 0,
'WEEKENDRANGE': <dynamic>[
5,
6,
],
'FIRSTWEEKCUTOFFDAY': 3,
'DATETIMEFORMATS': <dynamic>[
'{1} {0}',
'{1} \'kl\'. {0}',
'{1}, {0}',
'{1}, {0}',
],
};
// #docregion Delegate
class _NnMaterialLocalizationsDelegate
extends LocalizationsDelegate<MaterialLocalizations> {
const _NnMaterialLocalizationsDelegate();
@override
bool isSupported(Locale locale) => locale.languageCode == 'nn';
@override
Future<MaterialLocalizations> load(Locale locale) async {
final String localeName = intl.Intl.canonicalizedLocale(locale.toString());
// The locale (in this case `nn`) needs to be initialized into the custom
// date symbols and patterns setup that Flutter uses.
date_symbol_data_custom.initializeDateFormattingCustom(
locale: localeName,
patterns: nnLocaleDatePatterns,
symbols: intl.DateSymbols.deserializeFromMap(nnDateSymbols),
);
return SynchronousFuture<MaterialLocalizations>(
NnMaterialLocalizations(
localeName: localeName,
// The `intl` library's NumberFormat class is generated from CLDR data
// (see https://github.com/dart-lang/i18n/blob/main/pkgs/intl/lib/number_symbols_data.dart).
// Unfortunately, there is no way to use a locale that isn't defined in
// this map and the only way to work around this is to use a listed
// locale's NumberFormat symbols. So, here we use the number formats
// for 'en_US' instead.
decimalFormat: intl.NumberFormat('#,##0.###', 'en_US'),
twoDigitZeroPaddedFormat: intl.NumberFormat('00', 'en_US'),
// DateFormat here will use the symbols and patterns provided in the
// `date_symbol_data_custom.initializeDateFormattingCustom` call above.
// However, an alternative is to simply use a supported locale's
// DateFormat symbols, similar to NumberFormat above.
fullYearFormat: intl.DateFormat('y', localeName),
compactDateFormat: intl.DateFormat('yMd', localeName),
shortDateFormat: intl.DateFormat('yMMMd', localeName),
mediumDateFormat: intl.DateFormat('EEE, MMM d', localeName),
longDateFormat: intl.DateFormat('EEEE, MMMM d, y', localeName),
yearMonthFormat: intl.DateFormat('MMMM y', localeName),
shortMonthDayFormat: intl.DateFormat('MMM d'),
),
);
}
@override
bool shouldReload(_NnMaterialLocalizationsDelegate old) => false;
}
// #enddocregion Delegate
/// A custom set of localizations for the 'nn' locale. In this example, only
/// the value for openAppDrawerTooltip was modified to use a custom message as
/// an example. Everything else uses the American English (en_US) messages
/// and formatting.
class NnMaterialLocalizations extends GlobalMaterialLocalizations {
const NnMaterialLocalizations({
super.localeName = 'nn',
required super.fullYearFormat,
required super.compactDateFormat,
required super.shortDateFormat,
required super.mediumDateFormat,
required super.longDateFormat,
required super.yearMonthFormat,
required super.shortMonthDayFormat,
required super.decimalFormat,
required super.twoDigitZeroPaddedFormat,
});
// #docregion Getters
@override
String get moreButtonTooltip => r'More';
@override
String get aboutListTileTitleRaw => r'About $applicationName';
@override
String get alertDialogLabel => r'Alert';
// #enddocregion Getters
@override
String get anteMeridiemAbbreviation => r'AM';
@override
String get backButtonTooltip => r'Back';
@override
String get cancelButtonLabel => r'CANCEL';
@override
String get closeButtonLabel => r'CLOSE';
@override
String get closeButtonTooltip => r'Close';
@override
String get collapsedIconTapHint => r'Expand';
@override
String get continueButtonLabel => r'CONTINUE';
@override
String get copyButtonLabel => r'COPY';
@override
String get cutButtonLabel => r'CUT';
@override
String get deleteButtonTooltip => r'Delete';
@override
String get dialogLabel => r'Dialog';
@override
String get drawerLabel => r'Navigation menu';
@override
String get expandedIconTapHint => r'Collapse';
@override
String get firstPageTooltip => r'First page';
@override
String get hideAccountsLabel => r'Hide accounts';
@override
String get lastPageTooltip => r'Last page';
@override
String get licensesPageTitle => r'Licenses';
@override
String get modalBarrierDismissLabel => r'Dismiss';
@override
String get nextMonthTooltip => r'Next month';
@override
String get nextPageTooltip => r'Next page';
@override
String get okButtonLabel => r'OK';
@override
// A custom drawer tooltip message.
String get openAppDrawerTooltip => r'Custom Navigation Menu Tooltip';
// #docregion Raw
@override
String get pageRowsInfoTitleRaw => r'$firstRow–$lastRow of $rowCount';
@override
String get pageRowsInfoTitleApproximateRaw =>
r'$firstRow–$lastRow of about $rowCount';
// #enddocregion Raw
@override
String get pasteButtonLabel => r'PASTE';
@override
String get popupMenuLabel => r'Popup menu';
@override
String get menuBarMenuLabel => r'Menu Bar Label';
@override
String get postMeridiemAbbreviation => r'PM';
@override
String get previousMonthTooltip => r'Previous month';
@override
String get previousPageTooltip => r'Previous page';
@override
String get refreshIndicatorSemanticLabel => r'Refresh';
@override
String? get remainingTextFieldCharacterCountFew => null;
@override
String? get remainingTextFieldCharacterCountMany => null;
@override
String get remainingTextFieldCharacterCountOne => r'1 character remaining';
@override
String get remainingTextFieldCharacterCountOther =>
r'$remainingCount characters remaining';
@override
String? get remainingTextFieldCharacterCountTwo => null;
@override
String get remainingTextFieldCharacterCountZero => r'No characters remaining';
@override
String get reorderItemDown => r'Move down';
@override
String get reorderItemLeft => r'Move left';
@override
String get reorderItemRight => r'Move right';
@override
String get reorderItemToEnd => r'Move to the end';
@override
String get reorderItemToStart => r'Move to the start';
@override
String get reorderItemUp => r'Move up';
@override
String get rowsPerPageTitle => r'Rows per page:';
@override
ScriptCategory get scriptCategory => ScriptCategory.englishLike;
@override
String get searchFieldLabel => r'Search';
@override
String get selectAllButtonLabel => r'SELECT ALL';
@override
String? get selectedRowCountTitleFew => null;
@override
String? get selectedRowCountTitleMany => null;
@override
String get selectedRowCountTitleOne => r'1 item selected';
@override
String get selectedRowCountTitleOther => r'$selectedRowCount items selected';
@override
String? get selectedRowCountTitleTwo => null;
@override
String get selectedRowCountTitleZero => r'No items selected';
@override
String get showAccountsLabel => r'Show accounts';
@override
String get showMenuTooltip => r'Show menu';
@override
String get signedInLabel => r'Signed in';
@override
String get tabLabelRaw => r'Tab $tabIndex of $tabCount';
@override
TimeOfDayFormat get timeOfDayFormatRaw => TimeOfDayFormat.h_colon_mm_space_a;
@override
String get timePickerHourModeAnnouncement => r'Select hours';
@override
String get timePickerMinuteModeAnnouncement => r'Select minutes';
@override
String get viewLicensesButtonLabel => r'VIEW LICENSES';
@override
List<String> get narrowWeekdays =>
const <String>['S', 'M', 'T', 'W', 'T', 'F', 'S'];
@override
int get firstDayOfWeekIndex => 0;
static const LocalizationsDelegate<MaterialLocalizations> delegate =
_NnMaterialLocalizationsDelegate();
@override
String get calendarModeButtonLabel => r'Switch to calendar';
@override
String get dateHelpText => r'mm/dd/yyyy';
@override
String get dateInputLabel => r'Enter Date';
@override
String get dateOutOfRangeLabel => r'Out of range.';
@override
String get datePickerHelpText => r'SELECT DATE';
@override
String get dateRangeEndDateSemanticLabelRaw => r'End date $fullDate';
@override
String get dateRangeEndLabel => r'End Date';
@override
String get dateRangePickerHelpText => 'SELECT RANGE';
@override
String get dateRangeStartDateSemanticLabelRaw => 'Start date \$fullDate';
@override
String get dateRangeStartLabel => 'Start Date';
@override
String get dateSeparator => '/';
@override
String get dialModeButtonLabel => 'Switch to dial picker mode';
@override
String get inputDateModeButtonLabel => 'Switch to input';
@override
String get inputTimeModeButtonLabel => 'Switch to text input mode';
@override
String get invalidDateFormatLabel => 'Invalid format.';
@override
String get invalidDateRangeLabel => 'Invalid range.';
@override
String get invalidTimeLabel => 'Enter a valid time';
@override
String get licensesPackageDetailTextOther => '\$licenseCount licenses';
@override
String get saveButtonLabel => 'SAVE';
@override
String get selectYearSemanticsLabel => 'Select year';
@override
String get timePickerDialHelpText => 'SELECT TIME';
@override
String get timePickerHourLabel => 'Hour';
@override
String get timePickerInputHelpText => 'ENTER TIME';
@override
String get timePickerMinuteLabel => 'Minute';
@override
String get unspecifiedDate => 'Date';
@override
String get unspecifiedDateRange => 'Date Range';
@override
String get keyboardKeyAlt => 'Alt';
@override
String get keyboardKeyAltGraph => 'AltGr';
@override
String get keyboardKeyBackspace => 'Backspace';
@override
String get keyboardKeyCapsLock => 'Caps Lock';
@override
String get keyboardKeyChannelDown => 'Channel Down';
@override
String get keyboardKeyChannelUp => 'Channel Up';
@override
String get keyboardKeyControl => 'Ctrl';
@override
String get keyboardKeyDelete => 'Del';
@override
String get keyboardKeyEject => 'Eject';
@override
String get keyboardKeyEnd => 'End';
@override
String get keyboardKeyEscape => 'Esc';
@override
String get keyboardKeyFn => 'Fn';
@override
String get keyboardKeyHome => 'Home';
@override
String get keyboardKeyInsert => 'Insert';
@override
String get keyboardKeyMeta => 'Meta';
@override
String get keyboardKeyMetaMacOs => 'Command';
@override
String get keyboardKeyMetaWindows => 'Win';
@override
String get keyboardKeyNumLock => 'Num Lock';
@override
String get keyboardKeyNumpad0 => 'Num 0';
@override
String get keyboardKeyNumpad1 => 'Num 1';
@override
String get keyboardKeyNumpad2 => 'Num 2';
@override
String get keyboardKeyNumpad3 => 'Num 3';
@override
String get keyboardKeyNumpad4 => 'Num 4';
@override
String get keyboardKeyNumpad5 => 'Num 5';
@override
String get keyboardKeyNumpad6 => 'Num 6';
@override
String get keyboardKeyNumpad7 => 'Num 7';
@override
String get keyboardKeyNumpad8 => 'Num 8';
@override
String get keyboardKeyNumpad9 => 'Num 9';
@override
String get keyboardKeyNumpadAdd => 'Num +';
@override
String get keyboardKeyNumpadComma => 'Num ,';
@override
String get keyboardKeyNumpadDecimal => 'Num .';
@override
String get keyboardKeyNumpadDivide => 'Num /';
@override
String get keyboardKeyNumpadEnter => 'Num Enter';
@override
String get keyboardKeyNumpadEqual => 'Num =';
@override
String get keyboardKeyNumpadMultiply => 'Num *';
@override
String get keyboardKeyNumpadParenLeft => 'Num (';
@override
String get keyboardKeyNumpadParenRight => 'Num )';
@override
String get keyboardKeyNumpadSubtract => 'Num -';
@override
String get keyboardKeyPageDown => 'PgDown';
@override
String get keyboardKeyPageUp => 'PgUp';
@override
String get keyboardKeyPower => 'Power';
@override
String get keyboardKeyPowerOff => 'Power Off';
@override
String get keyboardKeyPrintScreen => 'Print Screen';
@override
String get keyboardKeyScrollLock => 'Scroll Lock';
@override
String get keyboardKeySelect => 'Select';
@override
String get keyboardKeyShift => 'Shift';
@override
String get keyboardKeySpace => 'Space';
@override
String get scrimOnTapHintRaw => r'Close $modalRouteContentName';
@override
String get bottomSheetLabel => 'Bottom Sheet';
@override
String get currentDateLabel => 'Today';
@override
String get scrimLabel => 'Scrim';
@override
String get collapsedHint => 'Expanded';
@override
String get expandedHint => 'Collapsed';
@override
String get expansionTileCollapsedHint => 'double tap to expand';
@override
String get expansionTileCollapsedTapHint => 'Expand for more details';
@override
String get expansionTileExpandedHint => 'double tap to collapse';
@override
String get expansionTileExpandedTapHint => 'Collapse';
@override
String get scanTextButtonLabel => 'Scan text';
@override
String get lookUpButtonLabel => 'Look Up';
@override
String get menuDismissLabel => 'Dismiss menu';
@override
String get searchWebButtonLabel => 'Search web';
@override
String get shareButtonLabel => 'Share...';
}
| website/examples/internationalization/add_language/lib/nn_intl.dart/0 | {'file_path': 'website/examples/internationalization/add_language/lib/nn_intl.dart', 'repo_id': 'website', 'token_count': 6564} |
// Basic Flutter widget test.
// Learn more at https://docs.flutter.dev/testing/overview#widget-tests.
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:layout/main.dart';
void main() {
testWidgets('Example app smoke test', (tester) async {
await tester.pumpWidget(const MyApp());
// A FlutterError shouldn't normally occur during a smoke test, but it
// is expected for this not-quite-finished app.
final error = tester.takeException();
expect(error, isFlutterError);
final flutterError = error as FlutterError;
expect(
flutterError.message,
matches(RegExp(r'A RenderFlex overflowed by \d+ pixels on the bottom\.')),
);
expect(find.text('Strawberry Pavlova Recipe'), findsOneWidget);
});
}
| website/examples/layout/pavlova/test/widget_test.dart/0 | {'file_path': 'website/examples/layout/pavlova/test/widget_test.dart', 'repo_id': 'website', 'token_count': 272} |
import 'package:flutter/material.dart';
class SomeWidget extends StatelessWidget {
const SomeWidget(this.child, {super.key});
final Widget child;
@override
Widget build(BuildContext context) {
return child;
}
}
| website/examples/state_mgmt/simple/lib/src/common.dart/0 | {'file_path': 'website/examples/state_mgmt/simple/lib/src/common.dart', 'repo_id': 'website', 'token_count': 73} |
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: AppHome(),
),
);
}
class AppHome extends StatelessWidget {
const AppHome({super.key});
@override
Widget build(BuildContext context) {
return Material(
child: Center(
child: TextButton(
onPressed: () {
debugDumpFocusTree();
},
child: const Text('Dump Focus Tree'),
),
),
);
}
}
| website/examples/testing/code_debugging/lib/dump_focus_tree.dart/0 | {'file_path': 'website/examples/testing/code_debugging/lib/dump_focus_tree.dart', 'repo_id': 'website', 'token_count': 210} |
// ignore_for_file: directives_ordering
import './error_handler.dart';
// #docregion Main
import 'package:flutter/material.dart';
import 'dart:ui';
Future<void> main() async {
await myErrorsHandler.initialize();
FlutterError.onError = (details) {
FlutterError.presentError(details);
myErrorsHandler.onErrorDetails(details);
};
PlatformDispatcher.instance.onError = (error, stack) {
myErrorsHandler.onError(error, stack);
return true;
};
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
builder: (context, widget) {
Widget error = const Text('...rendering error...');
if (widget is Scaffold || widget is Navigator) {
error = Scaffold(body: Center(child: error));
}
ErrorWidget.builder = (errorDetails) => error;
if (widget != null) return widget;
throw StateError('widget is null');
},
);
}
}
// #enddocregion Main
| website/examples/testing/errors/lib/main.dart/0 | {'file_path': 'website/examples/testing/errors/lib/main.dart', 'repo_id': 'website', 'token_count': 381} |
// Copyright 2023 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'URL Launcher',
theme: ThemeData(
useMaterial3: true,
colorSchemeSeed: Colors.purple,
),
home: const MyHomePage(title: 'URL Launcher'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<void>? _launched;
Future<void> _launchInBrowser(Uri url) async {
if (!await launchUrl(
url,
mode: LaunchMode.externalApplication,
)) {
throw Exception('Could not launch $url');
}
}
Future<void> _launchInWebView(Uri url) async {
if (!await launchUrl(
url,
mode: LaunchMode.inAppWebView,
)) {
throw Exception('Could not launch $url');
}
}
Widget _launchStatus(BuildContext context, AsyncSnapshot<void> snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return const Text('');
}
}
@override
Widget build(BuildContext context) {
final Uri toLaunch = Uri(
scheme: 'https',
host: 'docs.flutter.dev',
path: 'testing/native-debugging');
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16),
child: Text(toLaunch.toString()),
),
FilledButton(
onPressed: () => setState(() {
_launched = _launchInBrowser(toLaunch);
}),
child: const Text('Launch in browser'),
),
const Padding(padding: EdgeInsets.all(16)),
FilledButton(
onPressed: () => setState(() {
_launched = _launchInWebView(toLaunch);
}),
child: const Text('Launch in app'),
),
const Padding(padding: EdgeInsets.all(16.0)),
FutureBuilder<void>(future: _launched, builder: _launchStatus),
],
),
),
);
}
}
| website/examples/testing/native_debugging/lib/main.dart/0 | {'file_path': 'website/examples/testing/native_debugging/lib/main.dart', 'repo_id': 'website', 'token_count': 1175} |
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../app_model.dart';
class ScrollViewWithScrollbars extends StatefulWidget {
const ScrollViewWithScrollbars({
super.key,
required this.child,
this.axis = Axis.vertical,
});
final Widget child;
final Axis axis;
@override
State<ScrollViewWithScrollbars> createState() =>
_ScrollViewWithScrollbarsState();
}
class _ScrollViewWithScrollbarsState extends State<ScrollViewWithScrollbars> {
final ScrollController _scrollController = ScrollController();
@override
Widget build(BuildContext context) {
return Scrollbar(
controller: _scrollController,
thumbVisibility: context.select<AppModel, bool>((m) => m.touchMode),
child: SingleChildScrollView(
scrollDirection: widget.axis,
controller: _scrollController,
child: widget.child,
),
);
}
}
| website/examples/ui/layout/adaptive_app_demos/lib/widgets/scroll_view_with_scrollbars.dart/0 | {'file_path': 'website/examples/ui/layout/adaptive_app_demos/lib/widgets/scroll_view_with_scrollbars.dart', 'repo_id': 'website', 'token_count': 312} |
import 'package:flutter/rendering.dart';
void showBaselines() {
debugPaintBaselinesEnabled = true;
}
| website/examples/visual_debugging/lib/show_baselines.dart/0 | {'file_path': 'website/examples/visual_debugging/lib/show_baselines.dart', 'repo_id': 'website', 'token_count': 35} |
- title: Get started
children:
- title: Install Flutter
permalink: /get-started/install
- title: Test drive
permalink: /get-started/test-drive
- title: Write your first app
permalink: /get-started/codelab
- title: Learn more
permalink: /get-started/learn-more
- divider
- title: From another platform?
children:
- title: Flutter for Android devs
permalink: /get-started/flutter-for/android-devs
- title: Flutter for SwiftUI devs
permalink: /get-started/flutter-for/swiftui-devs
- title: Flutter for UIKit devs
permalink: /get-started/flutter-for/uikit-devs
- title: Flutter for React Native devs
permalink: /get-started/flutter-for/react-native-devs
- title: Flutter for web devs
permalink: /get-started/flutter-for/web-devs
- title: Flutter for Xamarin.Forms devs
permalink: /get-started/flutter-for/xamarin-forms-devs
- divider
- title: Introduction to declarative UI
permalink: /get-started/flutter-for/declarative
- title: Flutter versus Swift concurrency
permalink: /get-started/flutter-for/dart-swift-concurrency
- title: "Dart language overview"
permalink: https://dart.dev/overview
- title: Stay up to date
permalink: /release
children:
- title: Upgrade
permalink: /release/upgrade
- title: SDK archive
permalink: /release/archive
- divider
- title: What's new
permalink: /release/whats-new
- title: Release notes
permalink: /release/release-notes
- title: Breaking changes
permalink: /release/breaking-changes
- title: Compatibility policy
permalink: /release/compatibility-policy
- title: Samples & codelabs
children:
- title: Flutter Gallery
permalink: https://gallery.flutter.dev
- title: Samples and demos
permalink: https://flutter.github.io/samples/
- title: Cookbook
permalink: /cookbook
- title: Codelabs
permalink: /codelabs
- title: App solutions
children:
- title: Games
children:
- title: Overview
permalink: /resources/games-toolkit
- title: Add achievements and leaderboards
permalink: /cookbook/games/achievements-leaderboard
- title: Add advertising
permalink: /cookbook/plugins/google-mobile-ads
- title: Add multiplayer support
permalink: /cookbook/games/firestore-multiplayer
- title: Add in-app purchases
permalink: https://codelabs.developers.google.com/codelabs/flutter-in-app-purchases#0
- title: Add user authentication
permalink: https://firebase.google.com/codelabs/firebase-auth-in-flutter-apps#0
- title: Debug using Crashlytics
permalink: https://firebase.google.com/docs/crashlytics/get-started?platform=flutter
- title: News
children:
- title: Build a news app
permalink: /resources/news-toolkit
- title: Monetization
children:
- title: Overview
permalink: https://flutter.dev/monetization
- title: Add in-app purchases
permalink: https://codelabs.developers.google.com/codelabs/flutter-in-app-purchases#0
- title: Maps
children:
- title: Add maps to your app
permalink: https://developers.google.com/maps/flutter-package
- divider
- header: User interface
- title: Introduction
permalink: /ui
- title: Widget catalog
permalink: /ui/widgets
- title: Layout
permalink: /ui/layout
children:
- title: Introduction
permalink: /ui/layout
match-page-url-exactly: true
- title: Build a layout
permalink: /ui/layout/tutorial
- title: Lists & grids
permalink: /ui/layout/lists
children:
- title: Create and use lists
permalink: /cookbook/lists/basic-list
- title: Create a horizontal list
permalink: /cookbook/lists/horizontal-list
- title: Create a grid view
permalink: /cookbook/lists/grid-lists
- title: Create lists with different types of items
permalink: /cookbook/lists/mixed-list
- title: Create lists with spaced items
permalink: /cookbook/lists/spaced-items
- title: Work with long lists
permalink: /cookbook/lists/long-lists
- title: Scrolling
permalink: /ui/layout/scrolling
children:
- title: Overview
permalink: /ui/layout/scrolling
- title: Use slivers to achieve fancy scrolling
permalink: /ui/layout/scrolling/slivers
- title: Place a floating app bar above a list
permalink: /cookbook/lists/floating-app-bar
- title: Create a scrolling parallax effect
permalink: /cookbook/effects/parallax-scrolling
# TODO(parlough): Rename this to 'Responsive design'
# and add 'Adaptive design' under 'Design & theming'.
- title: Adaptive design
permalink: /ui/layout/responsive
children:
- title: Adaptive and responsive app design
permalink: /ui/layout/responsive/adaptive-responsive
- title: Build an adaptive app
permalink: /ui/layout/responsive/building-adaptive-apps
- title: Update app UI based on orientation
permalink: /cookbook/design/orientation
- title: Design & theming
permalink: /ui/design
children:
- title: Share styles with themes
permalink: /cookbook/design/themes
- title: Material design
permalink: /ui/design/material
- title: Migrate to Material 3
permalink: /release/breaking-changes/material-3-migration
- title: Text
permalink: /ui/design/text
children:
- title: Fonts & typography
permalink: /ui/design/text/typography
- title: Use a custom font
permalink: /cookbook/design/fonts
- title: Export fonts from a package
permalink: /cookbook/design/package-fonts
- title: Google Fonts package
permalink: https://pub.dev/packages/google_fonts
# Consider renaming this 'Custom drawing & graphics'
# once more docs are added
- title: Custom graphics
permalink: /ui/design/graphics
children:
- title: Use custom fragment shaders
permalink: /ui/design/graphics/fragment-shaders
- title: Interactivity
permalink: /ui/interactivity
children:
- title: Add interactivity to your app
permalink: /ui/interactivity
match-page-url-exactly: true
- title: Gestures
permalink: /ui/interactivity/gestures
children:
- title: Introduction
permalink: /ui/interactivity/gestures
match-page-url-exactly: true
- title: Handle taps
permalink: /cookbook/gestures/handling-taps
- title: Drag an object outside an app
permalink: /ui/interactivity/gestures/drag-outside
- title: Drag a UI element within an app
permalink: /cookbook/effects/drag-a-widget
- title: Add Material touch ripples
permalink: /cookbook/gestures/ripples
- title: Implement swipe to dismiss
permalink: /cookbook/gestures/dismissible
- title: Input & forms
permalink: /ui/interactivity/input
children:
- title: Create and style a text field
permalink: /cookbook/forms/text-input
- title: Retrieve the value of a text field
permalink: /cookbook/forms/retrieve-input
- title: Handle changes to a text field
permalink: /cookbook/forms/text-field-changes
- title: Manage focus in text fields
permalink: /cookbook/forms/focus
- title: Build a form with validation
permalink: /cookbook/forms/validation
- title: Display a snackbar
permalink: /cookbook/design/snackbars
- title: Implement actions & shortcuts
permalink: /ui/interactivity/actions-and-shortcuts
- title: Manage keyboard focus
permalink: /ui/interactivity/focus
- title: Assets & media
permalink: /ui/assets
children:
- title: Add assets and images
permalink: /ui/assets/assets-and-images
- title: Display images from the internet
permalink: /cookbook/images/network-image
- title: Fade in images with a placeholder
permalink: /cookbook/images/fading-in-images
- title: Play and pause a video
permalink: /cookbook/plugins/play-video
- title: Navigation & routing
permalink: /ui/navigation
children:
- title: Overview
permalink: /ui/navigation
match-page-url-exactly: true
- title: Add tabs to your app
permalink: /cookbook/design/tabs
- title: Navigate to a new screen and back
permalink: /cookbook/navigation/navigation-basics
- title: Send data to a new screen
permalink: /cookbook/navigation/passing-data
- title: Return data from a screen
permalink: /cookbook/navigation/returning-data
- title: Add a drawer to a screen
permalink: /cookbook/design/drawer
- title: Setup deep linking
permalink: /ui/navigation/deep-linking
- title: Setup app links for Android
permalink: /cookbook/navigation/set-up-app-links
- title: Setup universal links for iOS
permalink: /cookbook/navigation/set-up-universal-links
- title: Configure web URL strategies
permalink: /ui/navigation/url-strategies
- title: Animations & transitions
permalink: /ui/animations
children:
- title: Introduction
permalink: /ui/animations
match-page-url-exactly: true
- title: Tutorial
permalink: /ui/animations/tutorial
- title: Implicit animations
permalink: /ui/animations/implicit-animations
- title: Animate the properties of a container
permalink: /cookbook/animation/animated-container
- title: Fade a widget in and out
permalink: /cookbook/animation/opacity-animation
- title: Hero animations
permalink: /ui/animations/hero-animations
- title: Animate a page route transition
permalink: /cookbook/animation/page-route-animation
- title: Animate using a physic simulation
permalink: /cookbook/animation/physics-simulation
- title: Staggered animations
permalink: /ui/animations/staggered-animations
- title: Create a staggered menu animation
permalink: /cookbook/effects/staggered-menu-animation
- title: API overview
permalink: /ui/animations/overview
- title: Accessibility & internationalization
permalink: /ui/accessibility-and-internationalization
children:
- title: Accessibility
permalink: /ui/accessibility-and-internationalization/accessibility
- title: Internationalization
permalink: /ui/accessibility-and-internationalization/internationalization
- divider
- header: Beyond UI
- title: Data & backend
permalink: /data-and-backend
children:
- title: State management
permalink: /data-and-backend/state-mgmt
children:
- title: Introduction
permalink: /data-and-backend/state-mgmt/intro
- title: Think declaratively
permalink: /data-and-backend/state-mgmt/declarative
- title: Ephemeral vs app state
permalink: /data-and-backend/state-mgmt/ephemeral-vs-app
- title: Simple app state management
permalink: /data-and-backend/state-mgmt/simple
- title: Options
permalink: /data-and-backend/state-mgmt/options
- title: Networking & http
permalink: /data-and-backend/networking
children:
- title: Overview
permalink: /data-and-backend/networking
match-page-url-exactly: true
- title: Fetch data from the internet
permalink: /cookbook/networking/fetch-data
- title: Make authenticated requests
permalink: /cookbook/networking/authenticated-requests
- title: Send data to the internet
permalink: /cookbook/networking/send-data
- title: Update data over the internet
permalink: /cookbook/networking/update-data
- title: Delete data on the internet
permalink: /cookbook/networking/delete-data
- title: Communicate with WebSockets
permalink: /cookbook/networking/web-sockets
- title: Serialization
permalink: /data-and-backend/serialization
children:
- title: JSON serialization
permalink: /data-and-backend/serialization/json
- title: Parse JSON in the background
permalink: /cookbook/networking/background-parsing
- title: Persistence
permalink: /data-and-backend/persistence
children:
- title: Store key-value data on disk
permalink: /cookbook/persistence/key-value
- title: Read and write files
permalink: /cookbook/persistence/reading-writing-files
- title: Persist data with SQLite
permalink: /cookbook/persistence/sqlite
- title: Firebase
permalink: /data-and-backend/firebase
- title: Google APIs
permalink: /data-and-backend/google-apis
- title: Platform integration
permalink: /platform-integration
children:
- title: Supported platforms
permalink: /reference/supported-platforms
- title: Build desktop apps with Flutter
permalink: /platform-integration/desktop
- title: Write platform-specific code
permalink: /platform-integration/platform-channels
- title: Automatic platform adaptations
permalink: /platform-integration/platform-adaptations
- title: Android
permalink: /platform-integration/android
children:
- title: Add a splash screen
permalink: /platform-integration/android/splash-screen
- title: Bind to native code
permalink: /platform-integration/android/c-interop
- title: Host a native Android view
permalink: /platform-integration/android/platform-views
- title: Restore state on Android
permalink: /platform-integration/android/restore-state-android
- title: Target ChromeOS with Android
permalink: /platform-integration/android/chromeos
- title: iOS
permalink: /platform-integration/ios
children:
- title: Leverage Apple's system libraries
permalink: /platform-integration/ios/apple-frameworks
- title: Add a launch screen
permalink: /platform-integration/ios/launch-screen
- title: Add iOS App Clip support
permalink: /platform-integration/ios/ios-app-clip
- title: Add iOS app extensions
permalink: /platform-integration/ios/app-extensions
- title: Bind to native code
permalink: /platform-integration/ios/c-interop
- title: Host a native iOS view
permalink: /platform-integration/ios/platform-views
- title: Enable debugging on iOS
permalink: /platform-integration/ios/ios-debugging
- title: Restore state on iOS
permalink: /platform-integration/ios/restore-state-ios
- title: Linux
permalink: /platform-integration/linux
children:
- title: Build a Linux app
permalink: /platform-integration/linux/building
- title: macOS
permalink: /platform-integration/macos
children:
- title: Build a macOS app
permalink: /platform-integration/macos/building
- title: C interop
permalink: /platform-integration/macos/c-interop
- title: Web
permalink: /platform-integration/web
children:
- title: Build a web app
permalink: /platform-integration/web/building
- title: Web FAQ
permalink: /platform-integration/web/faq
- title: Web renderers
permalink: /platform-integration/web/renderers
- title: Custom app initialization
permalink: /platform-integration/web/initialization
- title: Displaying images on the web
permalink: /platform-integration/web/web-images
- title: Windows
permalink: /platform-integration/windows
children:
- title: Build a Windows app
permalink: /platform-integration/windows/building
- title: Packages & plugins
permalink: /packages-and-plugins
children:
- title: Use packages & plugins
permalink: /packages-and-plugins/using-packages
- title: Develop packages & plugins
permalink: /packages-and-plugins/developing-packages
- divider
- title: Flutter Favorites
permalink: /packages-and-plugins/favorites
- title: Package repository
permalink: https://pub.dev/flutter
- title: Testing & debugging
permalink: /testing
children:
- header: Testing
- title: Testing overview
permalink: /testing/overview
match-page-url-exactly: true
- title: Unit testing
children:
- title: Introduction
permalink: /cookbook/testing/unit/introduction
- title: Mock dependencies
permalink: /cookbook/testing/unit/mocking
- title: Widget testing
children:
- title: Introduction
permalink: /cookbook/testing/widget/introduction
- title: Find widgets
permalink: /cookbook/testing/widget/finders
- title: Simulate scrolling
permalink: /cookbook/testing/widget/scrolling
- title: Simulate user interaction
permalink: /cookbook/testing/widget/tap-drag
- title: Integration testing
children:
- title: Introduction
permalink: /cookbook/testing/integration/introduction
match-page-url-exactly: true
- title: Write and run an integration test
permalink: /testing/integration-tests
- title: Profile an integration test
permalink: /cookbook/testing/integration/profiling
- title: Test a plugin
permalink: /testing/testing-plugins
- title: Handle plugin code in tests
permalink: /testing/plugins-in-tests
- header: Debugging
- title: Debugging tools
permalink: /testing/debugging
- title: Debug your app programmatically
permalink: /testing/code-debugging
- title: Use a native language debugger
permalink: /testing/native-debugging
- title: Flutter's build modes
permalink: /testing/build-modes
- title: Common Flutter errors
permalink: /testing/common-errors
- title: Handle errors
permalink: /testing/errors
match-page-url-exactly: true
- title: Report errors to a service
permalink: /cookbook/maintenance/error-reporting
- title: Performance & optimization
permalink: /perf
children:
- title: Overview
permalink: /perf
match-page-url-exactly: true
- title: Impeller
permalink: /perf/impeller
- title: Performance best practices
permalink: /perf/best-practices
- title: App size
permalink: /perf/app-size
- title: Deferred components
permalink: /perf/deferred-components
# - title: Memory
# permalink: /perf/memory
# - title: Power usage
# permalink: /perf/power
- title: Rendering performance
permalink: /perf/rendering-performance
- title: Performance profiling
permalink: /perf/ui-performance
- title: Performance profiling for web
permalink: /perf/web-performance
- title: Shader compilation jank
permalink: /perf/shader
- title: Performance metrics
permalink: /perf/metrics
- title: Concurrency and isolates
permalink: /perf/isolates
- title: Performance FAQ
permalink: /perf/faq
- title: Appendix
permalink: /perf/appendix
- title: Deployment
permalink: /deployment
children:
- title: Obfuscate Dart code
permalink: /deployment/obfuscate
- title: Create flavors of an app
permalink: /deployment/flavors
- title: Build and release an Android app
permalink: /deployment/android
- title: Build and release an iOS app
permalink: /deployment/ios
- title: Build and release a macOS app
permalink: /deployment/macos
- title: Build and release a Linux app
permalink: /deployment/linux
- title: Build and release a Windows app
permalink: /deployment/windows
- title: Build and release a web app
permalink: /deployment/web
- title: Set up continuous deployment
permalink: /deployment/cd
- title: Add to an existing app
permalink: /add-to-app
children:
- title: Introduction
permalink: /add-to-app
match-page-url-exactly: true
- title: Add to an Android app
permalink: /add-to-app/android
children:
- title: Set up Android project
permalink: /add-to-app/android/project-setup
- title: Add a single Flutter screen
permalink: /add-to-app/android/add-flutter-screen
- title: Add a Flutter Fragment
permalink: /add-to-app/android/add-flutter-fragment
- title: Add a Flutter View
permalink: /add-to-app/android/add-flutter-view
- title: Use a Flutter plugin
permalink: /add-to-app/android/plugin-setup
- title: Add to an iOS app
permalink: /add-to-app/ios
children:
- title: Set up iOS project
permalink: /add-to-app/ios/project-setup
- title: Add a single Flutter screen
permalink: /add-to-app/ios/add-flutter-screen
- title: Debug embedded Flutter module
permalink: /add-to-app/debugging
- title: Add multiple Flutter instances
permalink: /add-to-app/multiple-flutters
- title: Loading sequence and performance
permalink: /add-to-app/performance
- divider
- title: Tools & editors
permalink: /tools
children:
- title: Android Studio & IntelliJ
permalink: /tools/android-studio
- title: Visual Studio Code
permalink: /tools/vs-code
- title: DevTools
permalink: /tools/devtools
children:
- title: Overview
permalink: /tools/devtools/overview
- title: Install from Android Studio & IntelliJ
permalink: /tools/devtools/android-studio
- title: Install from VS Code
permalink: /tools/devtools/vscode
- title: Install from command line
permalink: /tools/devtools/cli
- title: Flutter inspector
permalink: /tools/devtools/inspector
- title: Performance view
permalink: /tools/devtools/performance
- title: CPU Profiler view
permalink: /tools/devtools/cpu-profiler
- title: Memory view
permalink: /tools/devtools/memory
- title: Debug console view
permalink: /tools/devtools/console
- title: Network view
permalink: /tools/devtools/network
- title: Debugger
permalink: /tools/devtools/debugger
- title: Logging view
permalink: /tools/devtools/logging
- title: App size tool
permalink: /tools/devtools/app-size
- title: DevTools extensions
permalink: /tools/devtools/extensions
- title: Release notes
permalink: /tools/devtools/release-notes
- title: SDK overview
permalink: /tools/sdk
- title: Flutter's pubspec options
permalink: /tools/pubspec
- title: Automated fixes
permalink: /tools/flutter-fix
- title: Code formatting
permalink: /tools/formatting
- title: Flutter concepts
children:
- title: Architectural overview
permalink: /resources/architectural-overview
- title: Inside Flutter
permalink: /resources/inside-flutter
- title: Understanding constraints
permalink: /ui/layout/constraints
- title: Flutter's build modes
permalink: /testing/build-modes
- title: Hot reload
permalink: /tools/hot-reload
- title: Resources
permalink: /resources
children:
- header: Learning
- title: FAQ
permalink: /resources/faq
- title: Books
permalink: /resources/books
- title: Videos
permalink: /resources/videos
- title: Courses
permalink: /resources/courses
- title: Learn Dart
permalink: /resources/bootstrap-into-dart
- header: Contributing
- title: Create useful bug reports
permalink: /resources/bug-reports
- title: Contribute to Flutter
permalink: https://github.com/flutter/flutter/blob/main/CONTRIBUTING.md
- title: Design documents
permalink: /resources/design-docs
- title: Reference
permalink: /reference
expanded: true
children:
- title: Who is Dash?
permalink: /dash
- title: Widget index
permalink: /reference/widgets
- title: API reference
permalink: https://api.flutter.dev
- title: flutter CLI reference
permalink: /reference/flutter-cli
| website/src/_data/sidenav.yml/0 | {'file_path': 'website/src/_data/sidenav.yml', 'repo_id': 'website', 'token_count': 9723} |
import 'dart:convert';
import 'dart:io';
void main() {
final firebaseFile = File('firebase.json');
if (!firebaseFile.existsSync()) {
_errorAndExit(
'Error: Cannot find the firebase.json file in the current directory.',
);
}
try {
final firebaseConfigString = firebaseFile.readAsStringSync();
final firebaseConfig =
jsonDecode(firebaseConfigString) as Map<String, Object?>;
final hostingConfig = firebaseConfig['hosting'] as Map<String, Object?>?;
if (hostingConfig == null) {
_errorAndExit(
"The firebase.json file is missing a top-level 'hosting' entry.",
);
}
final redirects = hostingConfig['redirects'];
if (redirects == null) {
stdout.writeln(
'There are no redirects specified within the firebase.json file.',
);
return;
}
if (redirects is! List<Object?>) {
_errorAndExit(
"The firebase.json file's 'redirect' entry is not a list.",
);
}
if (redirects.isEmpty) {
return;
}
final sources = <String>{};
var duplicatesFound = 0;
for (final redirect in redirects) {
if (redirect is! Map<String, Object?>) {
_errorAndExit(
"Each redirect must be a map containing a 'source' or 'regex' field.",
);
}
final source = redirect['source'] ?? redirect['regex'];
if (source == null) {
_errorAndExit(
'The firebase.json file has a '
"redirect missing a 'source' or 'regex'.",
);
}
if (source is! String) {
_errorAndExit(
'The firebase.json redirect $redirect has a '
"'source' or 'regex' specified which is not a string.",
);
}
if (source.isEmpty) {
_errorAndExit(
'The firebase.json redirect $redirect has an '
"empty 'source' or 'regex'.",
);
}
if (sources.contains(source)) {
stderr.writeln(
"Multiple redirects share the '$source' source.",
);
duplicatesFound += 1;
}
sources.add(source);
final destination = redirect['destination'];
if (destination == null) {
_errorAndExit(
'The firebase.json file has a '
"redirect missing a 'destination'.",
);
}
if (destination is! String) {
_errorAndExit(
'The firebase.json redirect $redirect has a '
"'destination' specified which is not a string.",
);
}
if (destination.isEmpty) {
_errorAndExit(
'The firebase.json redirect $redirect has '
"an empty 'destination'.",
);
}
}
if (duplicatesFound > 0) {
_errorAndExit(
'$duplicatesFound duplicate sources found'
'in the firebase.json redirects.',
);
}
} catch (e) {
_errorAndExit(
'Encountered an error when loading the firebase.json file:',
e,
);
}
}
Never _errorAndExit(String error, [Object? exception]) {
stderr.write('Error: ');
stderr.writeln(error);
if (exception != null) {
stderr.writeln(exception.toString());
}
exit(1);
}
| website/tool/dart_tools/bin/verify_firebase_json.dart/0 | {'file_path': 'website/tool/dart_tools/bin/verify_firebase_json.dart', 'repo_id': 'website', 'token_count': 1392} |
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({
Key? key,
required this.title,
this.incrementBy = 1,
this.countLabel,
this.iconData,
this.showToolTip = true,
}) : super(key: key);
final String title;
final int incrementBy;
final String? countLabel;
final IconData? iconData;
final bool showToolTip;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter += widget.incrementBy;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
widget.countLabel ??
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: widget.showToolTip ? 'Increment' : null,
child: Icon(widget.iconData ?? Icons.add),
),
);
}
}
| widgetbook/examples/knobs_example/lib/main.dart/0 | {'file_path': 'widgetbook/examples/knobs_example/lib/main.dart', 'repo_id': 'widgetbook', 'token_count': 778} |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:meal_app/app.dart';
import 'package:meal_app/blocs/meal/meal_bloc.dart';
import 'package:meal_app/repositories/meal_repository.dart';
void main() {
runApp(MultiRepositoryProvider(
providers: [
RepositoryProvider(
create: (context) => MealRepository(),
),
],
child: MultiBlocProvider(
providers: [
BlocProvider<MealBloc>(
create: (context) => MealBloc(
mealRepository: context.read<MealRepository>(),
)..add(
LoadMeals(),
),
),
],
child: App(),
),
));
}
| widgetbook/examples/widgetbook_annotation_example/lib/main.dart/0 | {'file_path': 'widgetbook/examples/widgetbook_annotation_example/lib/main.dart', 'repo_id': 'widgetbook', 'token_count': 320} |
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:widgetbook/src/knobs/knobs.dart';
/// Checkbox used within knobs to make the returned value null
class NullableCheckbox<T> extends StatelessWidget {
const NullableCheckbox({
Key? key,
required this.cachedValue,
required this.value,
required this.label,
}) : super(key: key);
/// The label of the corresponding knob
final String label;
/// The value that was used before the knob was turned to null
final T cachedValue;
/// The current value of the knob
final T? value;
@override
Widget build(BuildContext context) {
return Tooltip(
message: 'No Value',
child: Checkbox(
key: Key('$label-nullableCheckbox'),
value: value == null,
onChanged: (v) {
T? newValue;
switch (v) {
case null:
case true:
newValue = null;
break;
case false:
newValue = cachedValue;
}
context.read<KnobsNotifier>().update(label, newValue);
},
),
);
}
}
| widgetbook/packages/widgetbook/lib/src/knobs/nullable_checkbox.dart/0 | {'file_path': 'widgetbook/packages/widgetbook/lib/src/knobs/nullable_checkbox.dart', 'repo_id': 'widgetbook', 'token_count': 474} |
import 'package:widgetbook/widgetbook.dart';
/// helper to obtain all WidgetElements in the navigation tree.
class WidgetHelper {
static List<WidgetbookComponent> getAllWidgetElementsFromCategories(
List<WidgetbookCategory> categories) {
final widgets = <WidgetbookComponent>[];
for (final category in categories) {
widgets.addAll(
getAllWidgetElementsFromCategory(category),
);
}
return widgets;
}
static List<WidgetbookComponent> getAllWidgetElementsFromCategory(
WidgetbookCategory category) {
final widgetList = List<WidgetbookComponent>.from(
category.widgets,
)..addAll(
getAllWidgetElementsFromFolders(category.folders),
);
return widgetList;
}
static List<WidgetbookComponent> getAllWidgetElementsFromFolders(
List<WidgetbookFolder> folders) {
final widgetList = <WidgetbookComponent>[];
for (final folder in folders) {
widgetList.addAll(
getAllWidgetElementsFromFolder(folder),
);
}
return widgetList;
}
static List<WidgetbookComponent> getAllWidgetElementsFromFolder(
WidgetbookFolder folder) {
final widgetList = List<WidgetbookComponent>.from(folder.widgets)
..addAll(
getAllWidgetElementsFromFolders(folder.folders),
);
return widgetList;
}
}
| widgetbook/packages/widgetbook/lib/src/models/organizers/organizer_helper/widget_helper.dart/0 | {'file_path': 'widgetbook/packages/widgetbook/lib/src/models/organizers/organizer_helper/widget_helper.dart', 'repo_id': 'widgetbook', 'token_count': 469} |
import 'package:widgetbook/src/models/model.dart';
abstract class Repository<Item extends Model> {
// Item operations
String addItem(Item item);
void setItem(Item item);
Item getItem(String id);
bool doesItemExist(String id);
void updateItem(Item item);
void deleteItem(Item item);
// List operations
Stream<List<Item>> getStreamOfItems();
void closeStream();
void deleteAll();
void addAll(Iterable<Item> items);
}
| widgetbook/packages/widgetbook/lib/src/repositories/repository.dart/0 | {'file_path': 'widgetbook/packages/widgetbook/lib/src/repositories/repository.dart', 'repo_id': 'widgetbook', 'token_count': 136} |
import 'package:flutter/material.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'translate_state.freezed.dart';
@freezed
class TranslateState with _$TranslateState {
factory TranslateState({
@Default(Offset.zero) Offset offset,
}) = _TranslateState;
}
| widgetbook/packages/widgetbook/lib/src/translate/translate_state.dart/0 | {'file_path': 'widgetbook/packages/widgetbook/lib/src/translate/translate_state.dart', 'repo_id': 'widgetbook', 'token_count': 98} |
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:widgetbook/src/models/organizers/organizers.dart';
import 'package:widgetbook/src/navigation/preview_provider.dart';
import 'package:widgetbook/src/utils/utils.dart';
import 'package:widgetbook/src/widgets/tiles/spaced_tile.dart';
class StoryTile extends StatefulWidget {
const StoryTile({
Key? key,
required this.useCase,
required this.level,
}) : super(key: key);
final WidgetbookUseCase useCase;
final int level;
@override
_StoryTileState createState() => _StoryTileState();
}
class _StoryTileState extends State<StoryTile> {
@override
Widget build(BuildContext context) {
return SpacedTile(
level: widget.level,
organizer: widget.useCase,
iconData: Icons.auto_stories,
iconColor: Styles.storyColor,
onClicked: () {
context.read<PreviewProvider>().selectUseCase(widget.useCase);
},
);
}
}
| widgetbook/packages/widgetbook/lib/src/widgets/tiles/story_tile.dart/0 | {'file_path': 'widgetbook/packages/widgetbook/lib/src/widgets/tiles/story_tile.dart', 'repo_id': 'widgetbook', 'token_count': 351} |
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:widgetbook/src/constants/radii.dart';
import 'package:widgetbook/src/navigation/preview_provider.dart';
import 'package:widgetbook/src/utils/utils.dart';
import 'package:widgetbook/src/workbench/preview.dart';
import 'package:widgetbook/src/workbench/workbench_controls.dart';
class Workbench<CustomTheme> extends StatelessWidget {
const Workbench({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final state = context.watch<PreviewProvider>().state;
final useCase = state.selectedUseCase;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
WorkbenchControls<CustomTheme>(),
const SizedBox(
height: 16,
),
Expanded(
child: Container(
decoration: BoxDecoration(
borderRadius: Radii.defaultRadius,
color: context.colorScheme.surface,
),
child: useCase == null
? Container()
: Preview<CustomTheme>(useCase: useCase),
),
),
],
);
}
}
| widgetbook/packages/widgetbook/lib/src/workbench/workbench.dart/0 | {'file_path': 'widgetbook/packages/widgetbook/lib/src/workbench/workbench.dart', 'repo_id': 'widgetbook', 'token_count': 508} |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
extension WidgetTesterExtension on WidgetTester {
Future<void> pumpWidgetWithMaterialApp(
Widget widget,
) async {
return pumpWidget(
MaterialApp(
home: Scaffold(
body: widget,
),
),
);
}
}
| widgetbook/packages/widgetbook/test/helper/widget_test_helper.dart/0 | {'file_path': 'widgetbook/packages/widgetbook/test/helper/widget_test_helper.dart', 'repo_id': 'widgetbook', 'token_count': 143} |
import 'package:flutter_test/flutter_test.dart';
import 'package:widgetbook/src/models/model.dart';
import 'package:widgetbook/src/repositories/memory_repository.dart';
class _Item extends Model {
_Item({
required String id,
required this.value,
}) : super(
id: id,
);
final int value;
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is _Item && other.id == id;
}
@override
int get hashCode => id.hashCode;
}
class _MemoryRepository extends MemoryRepository<_Item> {
_MemoryRepository({Map<String, _Item>? initialConfiguration})
: super(
initialConfiguration: initialConfiguration,
);
Map<String, _Item> getMemory() {
return memory;
}
}
void main() {
const defaultId = '1';
const alternateId = '2';
group(
'$MemoryRepository',
() {
test(
'adds item when addItem is called',
() async {
final repository = _MemoryRepository();
final stream = repository.getStreamOfItems();
expect(
stream,
emitsInOrder(
<dynamic>[
<_Item>[],
<_Item>[
_Item(
id: defaultId,
value: 0,
),
],
emitsDone,
],
),
);
repository.addItem(
_Item(
id: defaultId,
value: 0,
),
);
await repository.closeStream();
expect(
repository.memory,
equals(
<String, _Item>{
defaultId: _Item(
id: defaultId,
value: 0,
),
},
),
);
},
);
test(
'removes item when deleteItem is called',
() async {
final repository = _MemoryRepository(
initialConfiguration: <String, _Item>{
defaultId: _Item(
id: defaultId,
value: 0,
),
},
);
final stream = repository.getStreamOfItems();
expect(
stream,
emitsInOrder(
<dynamic>[
<_Item>[
_Item(
id: defaultId,
value: 0,
),
],
<_Item>[],
emitsDone,
],
),
);
repository.deleteItem(
_Item(
id: defaultId,
value: 0,
),
);
await repository.closeStream();
expect(
repository.memory,
equals(
<String, _Item>{},
),
);
},
);
test(
'changes existing item when setItem is called',
() async {
final repository = _MemoryRepository(
initialConfiguration: <String, _Item>{
defaultId: _Item(
id: defaultId,
value: 0,
),
},
);
final stream = repository.getStreamOfItems();
expect(
stream,
emitsInOrder(
<dynamic>[
<_Item>[
_Item(
id: defaultId,
value: 0,
),
],
<_Item>[
_Item(
id: defaultId,
value: 1,
),
],
emitsDone,
],
),
);
repository.setItem(
_Item(
id: defaultId,
value: 1,
),
);
await repository.closeStream();
expect(
repository.memory,
equals(
<String, _Item>{
defaultId: _Item(
id: defaultId,
value: 1,
),
},
),
);
},
);
test(
'adds item when setItem is called',
() async {
final repository = _MemoryRepository();
final stream = repository.getStreamOfItems();
expect(
stream,
emitsInOrder(
<dynamic>[
<_Item>[],
<_Item>[
_Item(
id: defaultId,
value: 0,
),
],
emitsDone,
],
),
);
repository.setItem(
_Item(
id: defaultId,
value: 0,
),
);
await repository.closeStream();
expect(
repository.memory,
equals(
<String, _Item>{
defaultId: _Item(
id: defaultId,
value: 0,
),
},
),
);
},
);
test(
'returns true when doesItemExist is called with item in memory',
() async {
final repository = _MemoryRepository(
initialConfiguration: <String, _Item>{
defaultId: _Item(
id: defaultId,
value: 0,
),
},
);
final result = repository.doesItemExist(defaultId);
expect(
result,
isTrue,
);
},
);
test(
'returns false when doesItemExist is called with item not in memory',
() async {
final repository = _MemoryRepository();
final result = repository.doesItemExist(defaultId);
expect(
result,
false,
);
},
);
test(
'returns item when getItem is called',
() async {
final repository = _MemoryRepository(
initialConfiguration: <String, _Item>{
defaultId: _Item(
id: defaultId,
value: 0,
),
},
);
final result = repository.getItem(defaultId);
expect(
result,
equals(
_Item(
id: defaultId,
value: 0,
),
),
);
},
);
test(
'removes all items when deleteAll is called',
() async {
final repository = _MemoryRepository(
initialConfiguration: <String, _Item>{
defaultId: _Item(
id: defaultId,
value: 0,
),
alternateId: _Item(
id: alternateId,
value: 1,
),
},
);
final stream = repository.getStreamOfItems();
expect(
stream,
emitsInOrder(
<dynamic>[
<_Item>[
_Item(
id: defaultId,
value: 0,
),
_Item(
id: alternateId,
value: 1,
),
],
<_Item>[],
emitsDone,
],
),
);
repository.deleteAll();
await repository.closeStream();
expect(
repository.memory,
equals(
<String, _Item>{},
),
);
},
);
test(
'removes all items when deleteAll is called',
() async {
final repository = _MemoryRepository();
final stream = repository.getStreamOfItems();
expect(
stream,
emitsInOrder(
<dynamic>[
<_Item>[],
<_Item>[
_Item(
id: defaultId,
value: 0,
),
_Item(
id: alternateId,
value: 1,
),
],
emitsDone,
],
),
);
repository.addAll([
_Item(
id: defaultId,
value: 0,
),
_Item(
id: alternateId,
value: 1,
),
]);
await repository.closeStream();
expect(
repository.memory,
equals(
<String, _Item>{
defaultId: _Item(
id: defaultId,
value: 0,
),
alternateId: _Item(
id: alternateId,
value: 1,
),
},
),
);
},
);
},
);
}
| widgetbook/packages/widgetbook/test/src/repositories/memory_repository_test.dart/0 | {'file_path': 'widgetbook/packages/widgetbook/test/src/repositories/memory_repository_test.dart', 'repo_id': 'widgetbook', 'token_count': 5616} |
// ignore_for_file: require_trailing_commas, non_constant_identifier_names
part of 'device.dart';
// Generated manually with https://fluttershapemaker.com/
class _FramePainter extends CustomPainter {
const _FramePainter();
@override
void paint(Canvas canvas, Size size) {
final path_0 = Path();
path_0.moveTo(0, 62.55);
path_0.cubicTo(0, 28.0046, 28.0046, 0, 62.55, 0);
path_0.lineTo(765.195, 0);
path_0.cubicTo(799.74, 0, 827.745, 28.0046, 827.745, 62.55);
path_0.lineTo(827.745, 1726.38);
path_0.cubicTo(827.745, 1760.93, 799.74, 1788.93, 765.195, 1788.93);
path_0.lineTo(62.55, 1788.93);
path_0.cubicTo(28.0046, 1788.93, 0, 1760.93, 0, 1726.38);
path_0.lineTo(0, 62.55);
path_0.close();
final paint_0_fill = Paint()..style = PaintingStyle.fill;
paint_0_fill.color = const Color(0xff3A4245);
canvas.drawPath(path_0, paint_0_fill);
final path_1 = Path();
path_1.moveTo(12.51, 62.5497);
path_1.cubicTo(12.51, 34.9134, 34.9137, 12.5098, 62.55, 12.5098);
path_1.lineTo(765.195, 12.5098);
path_1.cubicTo(792.831, 12.5098, 815.235, 34.9134, 815.235, 62.5498);
path_1.lineTo(815.235, 1726.38);
path_1.cubicTo(815.235, 1754.02, 792.831, 1776.42, 765.195, 1776.42);
path_1.lineTo(62.55, 1776.42);
path_1.cubicTo(34.9137, 1776.42, 12.51, 1754.02, 12.51, 1726.38);
path_1.lineTo(12.51, 62.5497);
path_1.close();
final paint_1_fill = Paint()..style = PaintingStyle.fill;
paint_1_fill.color = const Color(0xff121515);
canvas.drawPath(path_1, paint_1_fill);
final path_2 = Path();
path_2.moveTo(827.745, 650.52);
path_2.lineTo(829.83, 650.52);
path_2.cubicTo(832.133, 650.52, 834, 652.142, 834, 654.142);
path_2.lineTo(834, 755.318);
path_2.cubicTo(834, 757.318, 832.133, 758.94, 829.83, 758.94);
path_2.lineTo(827.745, 758.94);
path_2.lineTo(827.745, 650.52);
path_2.close();
final paint_2_fill = Paint()..style = PaintingStyle.fill;
paint_2_fill.color = const Color(0xff121515);
canvas.drawPath(path_2, paint_2_fill);
final path_3 = Path();
path_3.moveTo(827.745, 346.11);
path_3.lineTo(829.83, 346.11);
path_3.cubicTo(832.133, 346.11, 834, 349.197, 834, 353.006);
path_3.lineTo(834, 545.629);
path_3.cubicTo(834, 549.437, 832.133, 552.525, 829.83, 552.525);
path_3.lineTo(827.745, 552.525);
path_3.lineTo(827.745, 346.11);
path_3.close();
final paint_3_fill = Paint()..style = PaintingStyle.fill;
paint_3_fill.color = const Color(0xff121515);
canvas.drawPath(path_3, paint_3_fill);
final path_4 = Path();
path_4.moveTo(413.872, 91.7401);
path_4.cubicTo(425.963, 91.7401, 435.765, 81.9385, 435.765, 69.8476);
path_4.cubicTo(435.765, 57.7567, 425.963, 47.9551, 413.872, 47.9551);
path_4.cubicTo(401.782, 47.9551, 391.98, 57.7567, 391.98, 69.8476);
path_4.cubicTo(391.98, 81.9385, 401.782, 91.7401, 413.872, 91.7401);
path_4.close();
final paint_4_fill = Paint()..style = PaintingStyle.fill;
paint_4_fill.color = const Color(0xff262C2D);
canvas.drawPath(path_4, paint_4_fill);
final path_5 = Path();
path_5.moveTo(413.873, 83.5302);
path_5.cubicTo(421.429, 83.5302, 427.555, 77.4042, 427.555, 69.8474);
path_5.cubicTo(427.555, 62.2906, 421.429, 56.1646, 413.873, 56.1646);
path_5.cubicTo(406.316, 56.1646, 400.19, 62.2906, 400.19, 69.8474);
path_5.cubicTo(400.19, 77.4042, 406.316, 83.5302, 413.873, 83.5302);
path_5.close();
final paint_5_fill = Paint()..style = PaintingStyle.fill;
paint_5_fill.color = const Color(0xff121515);
canvas.drawPath(path_5, paint_5_fill);
final path_6 = Path();
path_6.moveTo(413.873, 67.1108);
path_6.cubicTo(415.384, 67.1108, 416.609, 65.8856, 416.609, 64.3743);
path_6.cubicTo(416.609, 62.8629, 415.384, 61.6377, 413.873, 61.6377);
path_6.cubicTo(412.361, 61.6377, 411.136, 62.8629, 411.136, 64.3743);
path_6.cubicTo(411.136, 65.8856, 412.361, 67.1108, 413.873, 67.1108);
path_6.close();
final paint_6_fill = Paint()..style = PaintingStyle.fill;
paint_6_fill.color = const Color(0xff636F73);
canvas.drawPath(path_6, paint_6_fill);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false;
}
}
| widgetbook/packages/widgetbook_device_frame/lib/src/devices/android/samsung_galaxy_note20/frame.g.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_device_frame/lib/src/devices/android/samsung_galaxy_note20/frame.g.dart', 'repo_id': 'widgetbook', 'token_count': 2124} |
part of 'device.dart';
class GenericLaptopFramePainter extends CustomPainter {
const GenericLaptopFramePainter({
required this.platform,
required this.windowPosition,
this.outerBodyColor = defaultOuterBodyColor,
this.innerBodyColor = defaultInnerBodyColor,
this.outerBodyRadius = defaultOuterBodyRadius,
this.innerBodyRadius = defaultInnerBodyRadius,
this.innerBodyInsets = defaultInnerBodyInsets,
this.screenInsets = defaultScreenInsets,
this.screenRadius = defaultScreenRadius,
this.windowRadius = defaultWindowRadius,
this.bodyHeight = defaultBodyHeight,
this.bodyPadHeight = defaultBodyPadHeight,
this.bodyInsets = defaultBodyInsets,
this.cameraBorderColor = defaultCameraBorderColor,
this.cameraInnerColor = defaultCameraInnerColor,
this.cameraReflectColor = defaultCameraReflectColor,
this.cameraRadius = defaultCameraRadius,
this.cameraBorderWidth = defaultCameraBorderWidth,
this.baseBodyBottomColor = defaultBaseBodyBottomColor,
this.baseBodyTopColor = defaultBaseBodyTopColor,
this.baseBodyPadColor = defaultBaseBodyPadColor,
});
Size calculateFrameSize(Size screenSize) {
return Size(
screenSize.width +
innerBodyInsets.horizontal +
screenInsets.horizontal +
defaultBodyInsets * 2,
screenSize.height +
innerBodyInsets.vertical +
screenInsets.vertical +
bodyHeight +
bodyPadHeight,
);
}
Size get effectiveWindowSize {
return Size(
windowPosition.width,
windowPosition.height - barHeight,
);
}
double get barHeight {
switch (platform) {
case TargetPlatform.macOS:
return 30;
default:
return 40;
}
}
Offset get _windowLocation {
return Offset(
defaultBodyInsets +
innerBodyInsets.left +
screenInsets.left +
windowPosition.left,
innerBodyInsets.top + screenInsets.top + windowPosition.top,
);
}
Path createScreenPath(Size screenSize) {
final result = Path();
result.addRRect(
RRect.fromRectAndCorners(
(_windowLocation + Offset(0, barHeight)) & effectiveWindowSize,
bottomLeft: windowRadius,
bottomRight: windowRadius,
),
);
return result;
}
final Rect windowPosition;
final TargetPlatform platform;
final Color outerBodyColor;
final Radius outerBodyRadius;
final Color innerBodyColor;
final Radius innerBodyRadius;
final Radius screenRadius;
final Radius windowRadius;
final EdgeInsets innerBodyInsets;
final EdgeInsets screenInsets;
final double bodyHeight;
final double bodyPadHeight;
final double bodyInsets;
final Color cameraBorderColor;
final Color cameraInnerColor;
final Color cameraReflectColor;
final double cameraRadius;
final double cameraBorderWidth;
final Color baseBodyTopColor;
final Color baseBodyBottomColor;
final Color baseBodyPadColor;
static const Color defaultBaseBodyTopColor = Color(0xff3A4245);
static const Color defaultBaseBodyBottomColor = Color(0xff323434);
static const Color defaultBaseBodyPadColor = Color(0xff222626);
static const Color defaultOuterBodyColor = Color(0xff3A4245);
static const Radius defaultOuterBodyRadius = Radius.circular(30);
static const Color defaultInnerBodyColor = Color(0xff121515);
static const Radius defaultInnerBodyRadius = Radius.circular(20);
static const Radius defaultScreenRadius = Radius.circular(10);
static const Radius defaultWindowRadius = Radius.circular(6);
static const double defaultBodyHeight = 60;
static const double defaultBodyPadHeight = 16;
static const double defaultBodyInsets = 200;
static const Color defaultCameraBorderColor = Color(0xff262C2D);
static const Color defaultCameraInnerColor = Color(0xff121515);
static const Color defaultCameraReflectColor = Color(0xff465256);
static const double defaultCameraRadius = 8.0;
static const double defaultCameraBorderWidth = 5.0;
static const EdgeInsets defaultInnerBodyInsets = EdgeInsets.only(
left: 6,
top: 6,
right: 6,
bottom: 0,
);
static const EdgeInsets defaultScreenInsets = EdgeInsets.only(
left: 20,
top: 80,
right: 20,
bottom: 100,
);
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()..style = PaintingStyle.fill;
final bounds = Rect.fromLTWH(
defaultBodyInsets,
0,
size.width - defaultBodyInsets * 2,
size.height - bodyPadHeight - bodyHeight,
);
canvas.drawRRect(
RRect.fromRectAndCorners(
bounds,
topLeft: outerBodyRadius,
topRight: outerBodyRadius,
),
paint..color = outerBodyColor,
);
final innerBounds = Rect.fromCenter(
center: bounds.center,
width: bounds.width - innerBodyInsets.horizontal,
height: bounds.height - innerBodyInsets.vertical,
);
canvas.drawRRect(
RRect.fromRectAndCorners(
innerBounds,
topLeft: innerBodyRadius,
topRight: innerBodyRadius,
),
paint..color = innerBodyColor,
);
canvas.drawCamera(
paint: paint,
center: Offset(
bounds.center.dx,
innerBodyInsets.top + (screenInsets.top / 2),
),
borderColor: cameraBorderColor,
borderWidth: cameraBorderWidth,
innerColor: cameraInnerColor,
radius: cameraRadius,
reflectColor: cameraReflectColor,
);
// Body
final padRadius = Radius.circular(bodyPadHeight);
canvas.drawRRect(
RRect.fromRectAndCorners(
Offset(
outerBodyRadius.x + bodyPadHeight * 4,
bounds.bottom + bodyHeight - 1,
) &
Size(
size.width - 2 * outerBodyRadius.x - bodyPadHeight * 8,
bodyPadHeight + 1,
),
bottomLeft: padRadius,
bottomRight: padRadius,
),
paint..color = baseBodyPadColor,
);
canvas.drawRRect(
RRect.fromRectAndCorners(
Offset(0, bounds.bottom + bodyHeight * 0.2 - 1) &
Size(size.width, bodyHeight * 0.8 + 1),
bottomLeft: outerBodyRadius,
bottomRight: outerBodyRadius,
),
paint..color = baseBodyBottomColor,
);
canvas.drawRRect(
RRect.fromRectAndCorners(
Offset(0, bounds.bottom) & Size(size.width, bodyHeight * 0.2),
topLeft: Radius.circular(innerBodyRadius.x * 0.5),
topRight: Radius.circular(innerBodyRadius.x * 0.5),
),
paint..color = baseBodyTopColor,
);
const bodyNotchWidth = 300.0;
canvas.drawRRect(
RRect.fromRectAndCorners(
Offset(
bounds.center.dx - bodyNotchWidth * 0.5,
bounds.bottom + bodyHeight * 0.2 - 1,
) &
Size(bodyNotchWidth, bodyHeight * 0.2),
bottomLeft: Radius.circular(bodyHeight * 0.2),
bottomRight: Radius.circular(bodyHeight * 0.2),
),
paint..color = baseBodyTopColor,
);
final screenBounds = Rect.fromLTWH(
defaultBodyInsets + innerBodyInsets.left + screenInsets.left,
innerBodyInsets.top + screenInsets.top,
bounds.width - innerBodyInsets.horizontal - screenInsets.horizontal,
bounds.height - innerBodyInsets.vertical - screenInsets.vertical,
);
canvas.clipRRect(
RRect.fromRectAndRadius(
screenBounds,
screenRadius,
),
);
canvas.drawDefaultWallpaper(
platform: platform,
bounds: screenBounds,
);
final windowPath = Path()
..addRRect(
RRect.fromRectAndRadius(
_windowLocation & effectiveWindowSize,
windowRadius,
),
);
canvas.drawPath(
windowPath,
Paint()
..blendMode = BlendMode.multiply
..color = const Color(0xFF3F2548).withOpacity(0.6)
..maskFilter = const MaskFilter.blur(
BlurStyle.outer,
56,
),
);
canvas.drawWindowBar(
platform: platform,
bounds: _windowLocation &
Size(
windowPosition.width,
barHeight,
),
windowRadius: windowRadius,
);
}
@override
bool shouldRepaint(covariant GenericLaptopFramePainter oldDelegate) {
return false;
}
}
| widgetbook/packages/widgetbook_device_frame/lib/src/devices/generic/laptop/frame.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_device_frame/lib/src/devices/generic/laptop/frame.dart', 'repo_id': 'widgetbook', 'token_count': 3289} |
part of 'device.dart';
// Generated manually with https://fluttershapemaker.com/
final _screenPath = Path()
..moveTo(329.809, 99.021)
..cubicTo(308.338, 99.021, 290.596, 81.7495, 290.596, 60.4441)
..lineTo(290.596, 49.9231)
..cubicTo(290.596, 44.1125, 286.132, 39.1958, 280.277, 39.1958)
..lineTo(187.994, 39.1958)
..cubicTo(145.528, 39.1958, 124.295, 39.1958, 107.406, 45.727)
..cubicTo(81.9318, 55.5778, 61.7934, 75.7075, 51.9383, 101.17)
..cubicTo(45.4043, 118.052, 45.4043, 139.276, 45.4043, 181.724)
..lineTo(45.4043, 1588.28)
..cubicTo(45.4043, 1630.72, 45.4043, 1651.95, 51.9383, 1668.83)
..cubicTo(61.7934, 1694.29, 81.9318, 1714.42, 107.406, 1724.27)
..cubicTo(124.295, 1730.8, 145.528, 1730.8, 187.994, 1730.8)
..lineTo(685.006, 1730.8)
..cubicTo(727.472, 1730.8, 748.705, 1730.8, 765.594, 1724.27)
..cubicTo(791.068, 1714.42, 811.207, 1694.29, 821.062, 1668.83)
..cubicTo(827.596, 1651.95, 827.596, 1630.72, 827.596, 1588.28)
..lineTo(827.596, 181.724)
..cubicTo(827.596, 139.276, 827.596, 118.052, 821.062, 101.17)
..cubicTo(811.207, 75.7075, 791.068, 55.5778, 765.594, 45.727)
..cubicTo(748.705, 39.1958, 727.472, 39.1958, 685.006, 39.1958)
..lineTo(596.723, 39.1958)
..cubicTo(590.868, 39.1958, 586.404, 44.1125, 586.404, 49.9231)
..lineTo(586.404, 60.4441)
..cubicTo(586.404, 81.7495, 568.662, 99.021, 547.191, 99.021)
..lineTo(329.809, 99.021)
..close()
..fillType = PathFillType.evenOdd;
| widgetbook/packages/widgetbook_device_frame/lib/src/devices/ios/iphone_13_pro_max/screen.g.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_device_frame/lib/src/devices/ios/iphone_13_pro_max/screen.g.dart', 'repo_id': 'widgetbook', 'token_count': 773} |
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'theme.freezed.dart';
/// The theme gives a [style] to all its descentant device frames.
///
/// The only customizable visuals are the keyboard style.
class DeviceFrameTheme extends InheritedWidget {
/// Give a [style] to all descentant in [child] device frames.
const DeviceFrameTheme({
Key? key,
required this.style,
required Widget child,
}) : super(
key: key,
child: child,
);
/// The style of the device frame.
final DeviceFrameStyle style;
/// The data from the closest instance of this class that encloses the given
/// [context].
static DeviceFrameStyle of(BuildContext context) {
final widget =
context.dependOnInheritedWidgetOfExactType<DeviceFrameTheme>();
return widget?.style ?? DeviceFrameStyle.dark();
}
@override
bool updateShouldNotify(DeviceFrameTheme oldWidget) {
return oldWidget.style != style;
}
}
/// The device frame style only allows to update the [keyboardStyle] for now.
///
/// See also:
///
/// * [DeviceKeyboardStyle] to customize the virtual on screen keyboard.
@freezed
abstract class DeviceFrameStyle with _$DeviceFrameStyle {
/// Create a [DeviceFrameStyle] with the given [keyboardStyle].
const factory DeviceFrameStyle({
required DeviceKeyboardStyle keyboardStyle,
}) = _DeviceFrameStyle;
/// A default dark theme.
factory DeviceFrameStyle.dark({DeviceKeyboardStyle? keyboardStyle}) =>
DeviceFrameStyle(
keyboardStyle: keyboardStyle ?? DeviceKeyboardStyle.dark(),
);
}
/// The keyboard style allows to customize the virtual onscreen keyboard visuals.
@freezed
abstract class DeviceKeyboardStyle with _$DeviceKeyboardStyle {
/// Creates a new style for the virtual keyboard.
const factory DeviceKeyboardStyle({
required Color backgroundColor,
required Color button1BackgroundColor,
required Color button1ForegroundColor,
required Color button2BackgroundColor,
required Color button2ForegroundColor,
}) = _DeviceKeyboardStyle;
/// A default dark theme for the virtual keyboard.
factory DeviceKeyboardStyle.dark() => const DeviceKeyboardStyle(
backgroundColor: Color(0xDD2B2B2D),
button1BackgroundColor: Color(0xFF6D6D6E),
button1ForegroundColor: Colors.white,
button2BackgroundColor: Color(0xFF4A4A4B),
button2ForegroundColor: Colors.white,
);
}
| widgetbook/packages/widgetbook_device_frame/lib/src/theme.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_device_frame/lib/src/theme.dart', 'repo_id': 'widgetbook', 'token_count': 798} |
import 'package:widgetbook_annotation/widgetbook_annotation.dart';
import 'package:widgetbook_generator/code_generators/instances/instance.dart';
import 'package:widgetbook_generator/code_generators/properties/property.dart';
/// An instance for [DeviceSize]
class DeviceSizeInstance extends Instance {
/// Creates a new instance of [DeviceSizeInstance]
DeviceSizeInstance({
required DeviceSize deviceSize,
}) : super(
name: 'DeviceSize',
properties: [
Property.double(key: 'height', value: deviceSize.height),
Property.double(key: 'width', value: deviceSize.width),
],
);
}
| widgetbook/packages/widgetbook_generator/lib/code_generators/instances/device_size_instance.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_generator/lib/code_generators/instances/device_size_instance.dart', 'repo_id': 'widgetbook', 'token_count': 229} |
import 'package:widgetbook_annotation/widgetbook_annotation.dart';
import 'package:widgetbook_generator/code_generators/instances/app_info_instance.dart';
import 'package:widgetbook_generator/code_generators/instances/device_instance.dart';
import 'package:widgetbook_generator/code_generators/instances/double_instance.dart';
import 'package:widgetbook_generator/code_generators/instances/frame_instance.dart';
import 'package:widgetbook_generator/code_generators/instances/function_call_instance.dart';
import 'package:widgetbook_generator/code_generators/instances/instance.dart';
import 'package:widgetbook_generator/code_generators/instances/list_instance.dart';
import 'package:widgetbook_generator/code_generators/instances/theme_instance.dart';
import 'package:widgetbook_generator/code_generators/instances/variable_instance.dart';
import 'package:widgetbook_generator/code_generators/instances/widgetbook_category_instance.dart';
import 'package:widgetbook_generator/code_generators/properties/property.dart';
/// An instance for Widgetbook
class WidgetbookInstance extends Instance {
/// Creates a new instance of [WidgetbookInstance]
WidgetbookInstance({
required AppInfoInstance appInfoInstance,
required WidgetbookConstructor constructor,
required List<WidgetbookCategoryInstance> categories,
required List<ThemeInstance> themes,
String? type,
List<DeviceInstance> devices = const <DeviceInstance>[],
List<FrameInstance> frames = const <FrameInstance>[],
List<DoubleInstance> textScaleFactors = const <DoubleInstance>[],
VariableInstance? locales,
VariableInstance? localizationDelegates,
VariableInstance? deviceFrameBuilder,
VariableInstance? localizationBuilder,
VariableInstance? scaffoldBuilder,
VariableInstance? useCaseBuilder,
FunctionCallInstance? themeBuilder,
}) : super(
name: 'Widgetbook',
namedConstructor: constructor.toCode,
genericParameters: type != null ? [type] : [],
properties: [
Property(key: 'appInfo', instance: appInfoInstance),
if (locales != null)
Property(key: 'supportedLocales', instance: locales),
if (localizationDelegates != null)
Property(
key: 'localizationsDelegates',
instance: localizationDelegates),
Property(key: 'themes', instance: ListInstance(instances: themes)),
if (devices.isNotEmpty)
Property(
key: 'devices',
instance: ListInstance(instances: devices),
),
if (frames.isNotEmpty)
Property(
key: 'frames',
instance: ListInstance(instances: frames),
),
if (textScaleFactors.isNotEmpty)
Property(
key: 'textScaleFactors',
instance: ListInstance(instances: textScaleFactors),
),
Property(
key: 'categories',
instance: ListInstance(instances: categories),
),
if (deviceFrameBuilder != null)
Property(
key: 'deviceFrameBuilder',
instance: deviceFrameBuilder,
),
if (localizationBuilder != null)
Property(
key: 'localizationBuilder',
instance: localizationBuilder,
),
if (scaffoldBuilder != null)
Property(
key: 'scaffoldBuilder',
instance: scaffoldBuilder,
),
if (useCaseBuilder != null)
Property(
key: 'useCaseBuilder',
instance: useCaseBuilder,
),
if (themeBuilder != null)
Property(
key: 'themeBuilder',
instance: themeBuilder,
)
],
);
}
| widgetbook/packages/widgetbook_generator/lib/code_generators/instances/widgetbook_instance.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_generator/lib/code_generators/instances/widgetbook_instance.dart', 'repo_id': 'widgetbook', 'token_count': 1676} |
import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
import 'package:widgetbook_generator/extensions/element_extensions.dart';
import 'package:widgetbook_generator/json_formatter.dart';
import 'package:widgetbook_generator/models/widgetbook_data.dart';
abstract class BuilderFunctionResolver<T> extends GeneratorForAnnotation<T> {
const BuilderFunctionResolver({
required this.createData,
});
final WidgetbookData Function(
String name,
String importStatement,
List<String> dependencies,
) createData;
@override
String generateForAnnotatedElement(
Element element,
ConstantReader annotation,
BuildStep buildStep,
) {
if (element.isPrivate) {
throw InvalidGenerationSourceError(
'Widgetbook annotations cannot be applied to private getter or methods',
element: element,
);
}
final data = createData(
element.name!,
element.importStatement,
element.dependencies,
);
return [data].toJson();
}
}
| widgetbook/packages/widgetbook_generator/lib/resolvers/builder_function_resolver.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_generator/lib/resolvers/builder_function_resolver.dart', 'repo_id': 'widgetbook', 'token_count': 368} |
import 'package:test/test.dart';
import 'package:widgetbook_generator/code_generators/instances/app_info_instance.dart';
import 'package:widgetbook_generator/code_generators/properties/property.dart';
import '../instance_helper.dart';
void main() {
group(
'$AppInfoInstance',
() {
const appInfoName = 'Recipe App';
final instance = AppInfoInstance(name: appInfoName);
testName('AppInfo', instance: instance);
test(
'.properties returns one property',
() {
expect(
instance.properties,
equals(
[
Property.string(
key: 'name',
value: appInfoName,
),
],
),
);
},
);
},
);
}
| widgetbook/packages/widgetbook_generator/test/src/code_generators/instances/app_info_instance_test.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_generator/test/src/code_generators/instances/app_info_instance_test.dart', 'repo_id': 'widgetbook', 'token_count': 390} |
import 'package:test/test.dart';
import 'package:widgetbook_generator/code_generators/instances/list_instance.dart';
import 'package:widgetbook_generator/code_generators/instances/widgetbook_category_instance.dart';
import 'package:widgetbook_generator/code_generators/instances/widgetbook_folder_instance.dart';
import 'package:widgetbook_generator/code_generators/instances/widgetbook_widget_instance.dart';
import 'package:widgetbook_generator/code_generators/properties/property.dart';
import 'package:widgetbook_generator/services/tree_service.dart';
import '../instance_helper.dart';
void main() {
group(
'$WidgetbookCategoryInstance',
() {
final folder = Folder(name: 'Folder');
final folder1 = Folder(
name: 'Folder1',
);
final folder2 = Folder(
name: 'Folder2',
);
final folders = [
folder1,
folder2,
];
final widget1 = Widget('Widget1');
final widget2 = Widget('Widget2');
final widgets = [
widget1,
widget2,
];
folder.subFolders
..putIfAbsent(
folder1.name,
() => folder1,
)
..putIfAbsent(
folder2.name,
() => folder2,
);
folder.widgets
..putIfAbsent(widget1.name, () => widget1)
..putIfAbsent(widget2.name, () => widget2);
const categoryName = 'stories';
testName(
'WidgetbookCategory',
instance: WidgetbookCategoryInstance(name: categoryName),
);
test(
".name returns 'stories'",
() {
final instance = WidgetbookCategoryInstance(
name: categoryName,
folders: folders,
widgets: widgets,
);
expect(
instance.properties,
equals(
[
Property.string(key: 'name', value: categoryName),
Property(
key: 'folders',
instance: ListInstance<WidgetbookFolderInstance>(
instances: [
WidgetbookFolderInstance(folder: folder1),
WidgetbookFolderInstance(folder: folder2),
],
),
),
Property(
key: 'widgets',
instance: ListInstance<WidgetbookComponentInstance>(
instances: [
WidgetbookComponentInstance(
name: widget1.name,
stories: widget1.stories,
),
WidgetbookComponentInstance(
name: widget2.name,
stories: widget2.stories,
),
],
),
),
],
));
},
);
},
);
}
| widgetbook/packages/widgetbook_generator/test/src/code_generators/instances/widgetbook_category_instance_test.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_generator/test/src/code_generators/instances/widgetbook_category_instance_test.dart', 'repo_id': 'widgetbook', 'token_count': 1544} |
import 'package:widgetbook_models/src/devices/device.dart';
import 'package:widgetbook_models/src/devices/device_size.dart';
import 'package:widgetbook_models/src/devices/resolution.dart';
/// Collection of all general desktops
class Desktop {
/// A 720p desktop
static const Device desktop720p = Device.desktop(
name: 'Desktop 720p',
resolution: Resolution(
nativeSize: DeviceSize(width: 1280, height: 720),
scaleFactor: 2,
),
);
/// A 1080p desktop
static const Device desktop1080p = Device.desktop(
name: 'Desktop 1080p',
resolution: Resolution(
nativeSize: DeviceSize(width: 1920, height: 1080),
scaleFactor: 2,
),
);
/// A 1440p desktop
static const Device desktop1440p = Device.desktop(
name: 'Desktop 1440p',
resolution: Resolution(
nativeSize: DeviceSize(width: 2560, height: 1440),
scaleFactor: 2,
),
);
/// A 4k desktop
static const Device desktop4k = Device.desktop(
name: 'Desktop 4k',
resolution: Resolution(
nativeSize: DeviceSize(width: 3840, height: 2160),
scaleFactor: 2,
),
);
/// A 8k desktop
static const Device desktop8k = Device.desktop(
name: 'Desktop 8k',
resolution: Resolution(
nativeSize: DeviceSize(width: 7680, height: 4320),
scaleFactor: 2,
),
);
}
| widgetbook/packages/widgetbook_models/lib/src/devices/desktop_screens.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_models/lib/src/devices/desktop_screens.dart', 'repo_id': 'widgetbook', 'token_count': 470} |
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:widgetbook_challenge/core/enums/request_status.dart';
import 'package:widgetbook_challenge/core/exceptions/custom_exception.dart';
import 'package:widgetbook_challenge/form/services/name_form_service.dart';
/// The Name Form Widget
class NameForm extends ConsumerStatefulWidget {
/// Creates instance of the Name Form Widget
const NameForm({Key? key}) : super(key: key);
@override
ConsumerState<NameForm> createState() => _NameFormState();
}
class _NameFormState extends ConsumerState<NameForm> {
final GlobalKey<FormState> _formKey = GlobalKey();
String? name;
RequestStatus requestStatus = RequestStatus.success;
String message = '';
Future<void> submit() async {
if (!_formKey.currentState!.validate()) {
return;
}
_formKey.currentState!.save();
setState(() {
requestStatus = RequestStatus.loading;
message = '';
});
try {
final responseMessage =
await ref.read(nameFormServiceProvider).submit(name!);
setState(() {
requestStatus = RequestStatus.success;
message = responseMessage;
});
} catch (e) {
setState(() {
requestStatus = RequestStatus.error;
message =
e is CustomException ? e.message : 'An unexpected error occurred!';
});
}
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextFormField(
onSaved: (value) {
name = value;
},
decoration: const InputDecoration(
hintText: 'Name',
),
validator: (String? value) {
if (value == null || value.isEmpty) {
return 'Name field is required';
}
return null;
},
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: requestStatus == RequestStatus.loading ? null : submit,
child: requestStatus == RequestStatus.loading
? const CircularProgressIndicator.adaptive()
: const Text('Submit'),
),
const SizedBox(height: 10),
Text(
message,
style: TextStyle(
color: requestStatus == RequestStatus.error
? Colors.red
: Colors.green,
),
),
],
),
);
}
}
| widgetbook_challenge/lib/form/views/widgets/name_form.dart/0 | {'file_path': 'widgetbook_challenge/lib/form/views/widgets/name_form.dart', 'repo_id': 'widgetbook_challenge', 'token_count': 1144} |
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:widgetbook_challenge/api/widgetbook_api.dart';
import 'package:widgetbook_challenge/core/api_provider.dart';
void main() {
test('is instance of WidgetbookApi', () {
final providerContainer = ProviderContainer();
addTearDown(providerContainer.dispose);
expect(
providerContainer.read(apiProvider),
isA<WidgetbookApi>(),
);
});
}
| widgetbook_challenge/test/core/api_provider_test.dart/0 | {'file_path': 'widgetbook_challenge/test/core/api_provider_test.dart', 'repo_id': 'widgetbook_challenge', 'token_count': 173} |
import 'package:first_desktop_application/app-level/constants/strings.dart';
import 'package:flutter/material.dart';
class AppTheme {
AppTheme._();
static const Color _lightPrimaryColor = Colors.orange;
static const Color _lightOnPrimaryColor = Colors.black;
static const Color _darkPrimaryColor = Colors.black;
static const Color _darkPrimaryAppBarColor = Colors.white;
static final lightTheme = ThemeData(
appBarTheme: const AppBarTheme(
color: _lightPrimaryColor,
iconTheme: IconThemeData(color: _lightOnPrimaryColor),
),
textTheme: const TextTheme(
bodyText2: TextStyle(color: Colors.black),
),
fontFamily: AppLevelStrings.fontFamily,
);
static final darkTheme = ThemeData(
// scaffoldBackgroundColor: _darkPrimaryColor,
appBarTheme: const AppBarTheme(
color: _darkPrimaryAppBarColor,
iconTheme: IconThemeData(color: _darkPrimaryColor),
),
fontFamily: AppLevelStrings.fontFamily,
snackBarTheme: const SnackBarThemeData(
behavior: SnackBarBehavior.floating,
backgroundColor: _lightPrimaryColor,
),
// TEXTS
textTheme: const TextTheme(
bodyText2: TextStyle(color: Colors.black),
headline1: TextStyle(
color: _darkPrimaryColor,
fontSize: 96.0,
letterSpacing: -1.5,
),
headline2: TextStyle(
color: _darkPrimaryColor,
fontSize: 60.0,
letterSpacing: -0.5,
),
headline3: TextStyle(
color: _darkPrimaryColor,
fontSize: 48.0,
letterSpacing: 0.0,
),
headline4: TextStyle(
color: _darkPrimaryColor,
fontSize: 34.0,
letterSpacing: 0.25,
),
headline5: TextStyle(
letterSpacing: 0.0,
fontSize: 25.0,
),
headline6: TextStyle(
letterSpacing: 0.15,
fontSize: 20.0,
),
),
);
}
| Experiments_with_Desktop/first_desktop_application/lib/app-level/styles/themes.dart/0 | {'file_path': 'Experiments_with_Desktop/first_desktop_application/lib/app-level/styles/themes.dart', 'repo_id': 'Experiments_with_Desktop', 'token_count': 776} |
import 'package:first_desktop_application/flipping/data/demo_data.dart';
import 'package:flutter/material.dart';
enum SummaryTheme { dark, light }
class FlightSummary extends StatelessWidget {
final BoardingPassData boardingPass;
final SummaryTheme theme;
final bool isOpen;
const FlightSummary({
Key key,
this.boardingPass,
this.theme = SummaryTheme.light,
this.isOpen = false,
}) : super(key: key);
Color get mainTextColor {
Color textColor;
if (theme == SummaryTheme.dark) textColor = Colors.white;
if (theme == SummaryTheme.light) textColor = const Color(0xFF083e64);
return textColor;
}
Color get secondaryTextColor {
Color textColor;
if (theme == SummaryTheme.dark) textColor = const Color(0xff61849c);
if (theme == SummaryTheme.light) textColor = const Color(0xFF838383);
return textColor;
}
Color get separatorColor {
Color color;
if (theme == SummaryTheme.light) color = const Color(0xffeaeaea);
if (theme == SummaryTheme.dark) color = const Color(0xff396583);
return color;
}
TextStyle get bodyTextStyle => TextStyle(
color: mainTextColor,
fontSize: 13,
fontFamily: 'Oswald',
);
@override
Widget build(BuildContext context) {
return Container(
decoration: _getBackgroundDecoration(),
width: double.infinity,
height: double.infinity,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_buildLogoHeader(),
_buildSeparationLine(),
_buildTicketHeader(context),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 18.0),
child: Stack(
children: [
Align(
alignment: Alignment.centerLeft,
child: _buildTicketOrigin(),
),
Align(
child: _buildTicketDuration(),
),
Align(
alignment: Alignment.centerRight,
child: _buildTicketDestination(),
)
],
),
),
_buildBottomIcon()
],
),
),
);
}
Decoration _getBackgroundDecoration() {
if (theme == SummaryTheme.light) {
return BoxDecoration(
borderRadius: BorderRadius.circular(4.0),
color: Colors.white,
);
}
return BoxDecoration(
borderRadius: BorderRadius.circular(4.0),
image: const DecorationImage(
image: AssetImage('assets/images/bg_blue.png'),
fit: BoxFit.cover,
),
);
}
Widget _buildTicketOrigin() {
return Column(
children: [
Text(
boardingPass.origin.code.toUpperCase(),
style: bodyTextStyle.copyWith(fontSize: 42),
),
Text(
boardingPass.origin.city,
style: bodyTextStyle.copyWith(color: secondaryTextColor),
),
],
);
}
Widget _buildLogoHeader() {
//
if (theme == SummaryTheme.light) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 4.0),
child: Image.asset('assets/images/flutter-logo.png', width: 8),
),
Text('Fluttair'.toUpperCase(),
style: TextStyle(
color: mainTextColor,
fontFamily: 'OpenSans',
fontSize: 10,
fontWeight: FontWeight.bold,
letterSpacing: 1.5,
))
],
);
}
return Padding(
padding: const EdgeInsets.only(top: 2.0),
child: Image.asset('assets/images/logo_white.png', height: 12),
);
}
Widget _buildSeparationLine() {
return Container(
width: double.infinity,
height: 1,
color: separatorColor,
);
}
Widget _buildTicketHeader(BuildContext context) {
//
const _style = TextStyle(
fontFamily: 'OpenSans',
fontWeight: FontWeight.bold,
fontSize: 11,
color: Color(0xFFe46565),
);
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(boardingPass.passengerName.toUpperCase(), style: _style),
Text(
'BOARDING ${boardingPass.boardingTime.format(context)}',
style: _style,
),
],
);
}
Widget _buildBottomIcon() {
IconData icon;
if (theme == SummaryTheme.light) icon = Icons.keyboard_arrow_down;
if (theme == SummaryTheme.dark) icon = Icons.keyboard_arrow_up;
return Icon(
icon,
color: mainTextColor,
size: 18,
);
}
Widget _buildTicketDuration() {
String planeRoutePath;
if (theme == SummaryTheme.light) {
planeRoutePath = 'assets/images/planeroute_blue.png';
}
if (theme == SummaryTheme.dark) {
planeRoutePath = 'assets/images/planeroute_white.png';
}
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SizedBox(
width: 120,
height: 58,
child: Stack(
alignment: Alignment.center,
children: [
Image.asset(planeRoutePath, fit: BoxFit.cover),
if (theme == SummaryTheme.light)
Image.asset(
'assets/images/airplane_blue.png',
height: 20,
fit: BoxFit.contain,
),
if (theme == SummaryTheme.dark)
_AnimatedSlideToRight(
isOpen: isOpen,
child: Image.asset(
'assets/images/airplane_white.png',
height: 20,
fit: BoxFit.contain,
),
)
],
),
),
Text(
boardingPass.duration.toString(),
textAlign: TextAlign.center,
style: bodyTextStyle,
),
],
);
}
Widget _buildTicketDestination() {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
boardingPass.destination.code.toUpperCase(),
style: bodyTextStyle.copyWith(fontSize: 42),
),
Text(
boardingPass.destination.city,
style: bodyTextStyle.copyWith(color: secondaryTextColor),
),
],
);
}
}
class _AnimatedSlideToRight extends StatefulWidget {
final Widget child;
final bool isOpen;
const _AnimatedSlideToRight({Key key, this.child, @required this.isOpen})
: super(key: key);
@override
_AnimatedSlideToRightState createState() => _AnimatedSlideToRightState();
}
class _AnimatedSlideToRightState extends State<_AnimatedSlideToRight>
with SingleTickerProviderStateMixin {
AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this, duration: const Duration(milliseconds: 1700));
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (widget.isOpen) _controller.forward(from: 0);
return SlideTransition(
position:
Tween(begin: const Offset(-2, 0), end: const Offset(1, 0)).animate(
CurvedAnimation(curve: Curves.easeOutQuad, parent: _controller),
),
child: widget.child,
);
}
}
| Experiments_with_Desktop/first_desktop_application/lib/flipping/widgets/flight_summary.dart/0 | {'file_path': 'Experiments_with_Desktop/first_desktop_application/lib/flipping/widgets/flight_summary.dart', 'repo_id': 'Experiments_with_Desktop', 'token_count': 3539} |
import 'dart:ffi' as ffi;
import 'package:ffi/ffi.dart';
typedef hello_world_func = ffi.Void Function();
// Dart type definition for calling the C foreign function
typedef HelloWorld = void Function();
// C header typedef:
typedef SystemC = ffi.Void Function();
// Dart header typedef
typedef SystemDart = void Function();
typedef SystemCHello = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> str);
typedef SystemDartHello = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> str);
void main() {
// final instance = LibraryTest();
// instance.openFromCLI();
// instance.filesFromCLI();
// instance.helloFromCLI();
}
class LibraryTest {
void openFromFlutter() {
final sysLib = ffi.DynamicLibrary.open('libhello.dylib');
final HelloWorld hello = sysLib
.lookup<ffi.NativeFunction<hello_world_func>>('hello_world')
.asFunction();
// Call the function
hello();
}
String inputFromFlutterToC(String input) {
final sysLib = ffi.DynamicLibrary.open('libfetchtemp.dylib');
final helloFromC =
sysLib.lookupFunction<SystemCHello, SystemDartHello>('sayHello');
// Pass input
final name = input.toNativeUtf8();
// Call the function
final res = helloFromC(name);
// Convert resp into string
final strRes = res.toDartString();
// ignore: avoid_print
print(strRes);
return strRes;
}
void filesFromFlutter() {
final sysLib = ffi.DynamicLibrary.open('libfetchtemp.dylib');
final tempFiles =
sysLib.lookupFunction<SystemC, SystemDart>('fetchtemp_files');
// Call the function
tempFiles();
}
void openFromCLI() {
final sysLib = ffi.DynamicLibrary.open('./dylib/libhello.dylib');
final hello = sysLib.lookupFunction<SystemC, SystemDart>('hello_world');
// final HelloWorld hello = sysLib
// .lookup<ffi.NativeFunction<hello_world_func>>('hello_world')
// .asFunction();
// Call the function
hello();
}
void filesFromCLI() {
final sysLib = ffi.DynamicLibrary.open('./dylib/libfetchtemp.dylib');
final tempFiles =
sysLib.lookupFunction<SystemC, SystemDart>('fetchtemp_files');
// Call the function
tempFiles();
}
void helloFromCLI() {
final sysLib = ffi.DynamicLibrary.open('./dylib/libfetchtemp.dylib');
final helloFromC =
sysLib.lookupFunction<SystemCHello, SystemDartHello>('sayHello');
// Pass input
final name = 'Aseem'.toNativeUtf8();
// Call the function
final res = helloFromC(name);
// Convert resp into string
final strRes = res.toDartString();
// ignore: avoid_print
print(strRes);
}
}
| Experiments_with_Desktop/first_desktop_application/lib/library/library.dart/0 | {'file_path': 'Experiments_with_Desktop/first_desktop_application/lib/library/library.dart', 'repo_id': 'Experiments_with_Desktop', 'token_count': 973} |
import 'package:flutter/rendering.dart';
extension TextStyleExtension on TextStyle {
TextStyle get bold => copyWith(fontWeight: FontWeight.bold);
TextStyle get italic => copyWith(fontStyle: FontStyle.italic);
TextStyle get normal => copyWith(fontWeight: FontWeight.normal);
TextStyle c(Color value) => copyWith(color: value);
TextStyle letterSpace(double value) => copyWith(letterSpacing: value);
TextStyle size(double value) => copyWith(fontSize: value);
TextStyle get u => copyWith(decoration: TextDecoration.underline);
}
| Experiments_with_Desktop/first_desktop_application/lib/shared/extensions/textstyle_extension.dart/0 | {'file_path': 'Experiments_with_Desktop/first_desktop_application/lib/shared/extensions/textstyle_extension.dart', 'repo_id': 'Experiments_with_Desktop', 'token_count': 159} |
import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:stacked/stacked.dart';
import 'package:xafe/app/authentication/domain/params/post_params/post_params.dart';
import 'package:xafe/app/authentication/domain/usecases/login_user.dart';
import 'package:xafe/core/error/helpers/helpers.dart';
import 'package:xafe/main_screen.dart';
import 'package:xafe/src/utils/navigation/navigation.dart';
class LoginViewmodel extends BaseViewModel {
LoginViewmodel(
this._loginUser,
);
final LoginUser _loginUser;
Future loginUser({
EmailPasswordParams params,
BuildContext context,
}) {
setBusy(true);
return _loginUser(params)
..then(
(result) {
result.fold(
(failure) {
setBusy(false);
Fluttertoast.showToast(
msg: mapFailureMessage(failure),
);
},
(data) {
setBusy(false);
return pushAndRemoveUntil(
context,
MainScreen(),
);
},
).then(
(value) => setBusy(false),
);
},
);
}
}
| Xafe/lib/app/authentication/presentation/logic/viewmodels/login_viewmodel.dart/0 | {'file_path': 'Xafe/lib/app/authentication/presentation/logic/viewmodels/login_viewmodel.dart', 'repo_id': 'Xafe', 'token_count': 580} |
import 'package:dartz/dartz.dart';
import 'package:xafe/app/budget/domain/repository/budget_repo.dart';
import 'package:xafe/app/home/data/models/expense_model.dart';
import 'package:xafe/core/error/failures.dart';
class CreateBudgetExpense {
CreateBudgetExpense(this._repository);
final BudgetRepo _repository;
Future<Either<Failure, void>> call({
ExpenseModel params,
String budgetId,
}) async =>
await _repository.createBudgetExpense(
params,
budgetId,
);
}
| Xafe/lib/app/budget/domain/usecases/create_budget_expense.dart/0 | {'file_path': 'Xafe/lib/app/budget/domain/usecases/create_budget_expense.dart', 'repo_id': 'Xafe', 'token_count': 198} |
import 'package:firebase_auth/firebase_auth.dart';
import 'package:xafe/app/categories/data/datasource/categories_datasource.dart';
import 'package:xafe/app/categories/data/model/category_model.dart';
import 'package:xafe/core/config/firebase/firebase.dart';
@override
class CategoriesDataSourceImpl extends CategoriesDataSource {
CategoriesDataSourceImpl(this.xafeFireStoreService);
final XafeFireStoreService xafeFireStoreService;
@override
Future<void> createCategory(CategoryModel params) {
final response = xafeFireStoreService.createInnerDocument(
collectionName: 'users',
docId: FirebaseAuth.instance.currentUser.uid,
innerCollectionName: 'categories',
innerDocId: params.categoryId,
data: params.toJson(),
);
return response;
}
@override
Stream<List<CategoryModel>> listenToCategories(String uId) {
return xafeFireStoreService
.listenToInnerCollection(
collectionName: 'users',
docId: FirebaseAuth.instance.currentUser.uid,
innerCollectionName: 'categories',
)
.map(
(snapshot) => snapshot.docs
.map(
(docSnapshot) => CategoryModel.fromJson(
docSnapshot.data(),
),
)
.toList(),
);
}
@override
Future<void> deleteCategory(String categoryId) {
final response = xafeFireStoreService.deleteInnerDocument(
docId: FirebaseAuth.instance.currentUser.uid,
collectionName: 'users',
innerCollectionName: 'categories',
innerDocId: categoryId,
);
return response;
}
}
| Xafe/lib/app/categories/data/datasource/impl/categories_datasource_impl.dart/0 | {'file_path': 'Xafe/lib/app/categories/data/datasource/impl/categories_datasource_impl.dart', 'repo_id': 'Xafe', 'token_count': 655} |
import 'package:dartz/dartz.dart';
import 'package:xafe/app/home/data/models/expense_model.dart';
import 'package:xafe/app/home/domain/repository/home_repo.dart';
import 'package:xafe/core/error/failures.dart';
class AddAnExpense {
AddAnExpense(this._repository);
final HomeRepo _repository;
Future<Either<Failure, void>> call(ExpenseModel params) async =>
await _repository.addAnExpense(params);
}
| Xafe/lib/app/home/domain/usecases/add_an_expense.dart/0 | {'file_path': 'Xafe/lib/app/home/domain/usecases/add_an_expense.dart', 'repo_id': 'Xafe', 'token_count': 154} |
import 'package:flutter/material.dart';
///General [Colors]
const Color kColorAppBlack = Color(0xFF0F0627);
const Color kColorShopTopUp = Color(0xFF0C2344);
const Color kColorAppGrey = Color(0xFF9A96A4);
const Color kColorBlue = Color(0xFF0047FF);
const Color kColorBlackish = Color(0xFF757886);
const Color kColorAltStroke = Color(0xFFF8F8F9);
///Natural [Colors]
const Color kColorWhite = Color(0xFFFFFFFF);
const Color kColorBlack = Color(0xFF0E2838);
| Xafe/lib/src/res/values/colors/colors.dart/0 | {'file_path': 'Xafe/lib/src/res/values/colors/colors.dart', 'repo_id': 'Xafe', 'token_count': 170} |
import 'package:amplify_authenticator/amplify_authenticator.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:{{project_name.snakeCase()}}/profile/bloc/profile_page_bloc.dart';
import 'package:{{project_name.snakeCase()}}/profile/bloc/profile_page_events.dart';
import 'package:{{project_name.snakeCase()}}/profile/bloc/profile_page_state.dart';
import 'package:{{project_name.snakeCase()}}/profile/domain/user_repository.dart';
class ProfilePage extends StatelessWidget {
const ProfilePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Account'),
),
body: BlocProvider<ProfilePageBloc>(
create: (_) =>
ProfilePageBloc(userRepository: context.read<UserRepository>())
..add(const UserRequested()),
child: BlocBuilder<ProfilePageBloc, ProfilePageState>(
builder: (context, state) {
if (state.status == ProfilePageStatus.success) {
final user = state.user;
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 16),
Text(
'Welcome ${user?.username}!',
style: Theme.of(context).textTheme.headlineMedium,
),
const SizedBox(height: 16),
const SignOutButton(),
],
),
);
} else if (state.status == ProfilePageStatus.failure) {
return const Center(
child: Text('Failed to fetch user data'),
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
),
);
}
}
| amplify_starter/__brick__/{{project_name}}/lib/profile/ui/profile_page.dart/0 | {'file_path': 'amplify_starter/__brick__/{{project_name}}/lib/profile/ui/profile_page.dart', 'repo_id': 'amplify_starter', 'token_count': 1008} |
name: mydartanalyzer
publish_to: "none"
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
plugin:
path: ../plugin
analyzer_plugin:
path: ../analyzer_plugin
analyzer: ^1.4.0
executables:
mydartanalyzer: main
| analyzer_plugins/packages/mydartanalyzer/pubspec.yaml/0 | {'file_path': 'analyzer_plugins/packages/mydartanalyzer/pubspec.yaml', 'repo_id': 'analyzer_plugins', 'token_count': 104} |
import 'package:appsflyer_sdk/appsflyer_sdk.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late AppsflyerSdk instance;
String selectedMethod = "";
const MethodChannel methodChannel = MethodChannel('af-api');
const MethodChannel callbacksChannel = MethodChannel('callbacks');
const EventChannel eventChannel = EventChannel('af-events');
const MethodChannel eventMethodChannel = MethodChannel('af-events');
setUp(() {
//test map options way
instance = AppsflyerSdk.private(methodChannel, eventChannel,
mapOptions: {'afDevKey': 'sdfhj2342cx'});
methodChannel.setMockMethodCallHandler((methodCall) async {
String method = methodCall.method;
if (method == 'initSdk') {
selectedMethod = method;
}
});
eventMethodChannel.setMockMethodCallHandler((methodCall) async {
String method = methodCall.method;
if (method == 'listen') {
selectedMethod = method;
}
});
});
test('check initSdk call', () async {
await instance.initSdk(
registerConversionDataCallback: true,
registerOnAppOpenAttributionCallback: true,
registerOnDeepLinkingCallback: false
);
expect('initSdk', selectedMethod);
});
group('AppsFlyerSdk', () {
setUp(() {
//test map options way
instance = AppsflyerSdk.private(methodChannel, eventChannel,
mapOptions: {'afDevKey': 'sdfhj2342cx'});
callbacksChannel.setMockMethodCallHandler((call) async {
String method = call.method;
if (method == 'startListening') {
selectedMethod = method;
}
});
methodChannel.setMockMethodCallHandler((methodCall) async {
String method = methodCall.method;
switch (method) {
case 'setOneLinkCustomDomain':
case 'logCrossPromotionAndOpenStore':
case 'logCrossPromotionImpression':
case 'setAppInviteOneLinkID':
case 'generateInviteLink':
case 'setSharingFilterForAllPartners':
case 'setSharingFilter':
case 'getSDKVersion':
case 'getAppsFlyerUID':
case 'validateAndLogInAppAndroidPurchase':
case 'setMinTimeBetweenSessions':
case 'getHostPrefix':
case 'getHostName':
case 'setCollectIMEI':
case 'setCollectAndroidId':
case 'setUserEmailsWithCryptType':
case 'setUserEmails':
case 'setAdditionalData':
case 'waitForCustomerUserId':
case 'setCustomerUserId':
case 'enableLocationCollection':
case 'setAndroidIdData':
case 'setImeiData':
case 'updateServerUninstallToken':
case 'stop':
case 'setIsUpdate':
case 'setCurrencyCode':
case 'setHost':
case 'logEvent':
case 'initSdk':
selectedMethod = methodCall.method;
break;
}
});
});
tearDown(() {
methodChannel.setMockMethodCallHandler(null);
});
test('check logEvent call', () async {
await instance.logEvent("eventName", {"key": "val"});
expect(selectedMethod, 'logEvent');
});
test('check setHost call', () async {
instance.setHost("", "");
expect(selectedMethod, 'setHost');
});
test('check setCurrencyCode call', () async {
instance.setCurrencyCode("currencyCode");
expect(selectedMethod, 'setCurrencyCode');
});
test('check setIsUpdate call', () async {
instance.setIsUpdate(true);
expect(selectedMethod, 'setIsUpdate');
});
test('check stop call', () async {
instance.stop(true);
expect(selectedMethod, 'stop');
});
test('check updateServerUninstallToken call', () async {
instance.updateServerUninstallToken("token");
expect(selectedMethod, 'updateServerUninstallToken');
});
test('check setOneLinkCustomDomain call', () async {
instance.setOneLinkCustomDomain(["brandDomains"]);
expect(selectedMethod, 'setOneLinkCustomDomain');
});
test('check logCrossPromotionAndOpenStore call', () async {
instance.logCrossPromotionAndOpenStore("appId", "campaign", null);
expect(selectedMethod, 'logCrossPromotionAndOpenStore');
});
test('check logCrossPromotionImpression call', () async {
instance.logCrossPromotionImpression("appId", "campaign", null);
expect(selectedMethod, 'logCrossPromotionImpression');
});
test('check setAppInviteOneLinkID call', () async {
instance.setAppInviteOneLinkID("oneLinkID", (msg) {});
expect(selectedMethod, 'setAppInviteOneLinkID');
});
test('check generateInviteLink call', () async {
instance.generateInviteLink(null, (msg) {}, (err) {});
expect(selectedMethod, 'generateInviteLink');
});
test('check setSharingFilterForAllPartners call', () async {
instance.setSharingFilterForAllPartners();
expect(selectedMethod, 'setSharingFilterForAllPartners');
});
test('check setSharingFilter call', () async {
instance.setSharingFilter(["filters"]);
expect(selectedMethod, 'setSharingFilter');
});
test('check getSDKVersion call', () async {
instance.getSDKVersion();
expect(selectedMethod, 'getSDKVersion');
});
test('check getAppsFlyerUID call', () async {
instance.getAppsFlyerUID();
expect(selectedMethod, 'getAppsFlyerUID');
});
test('check validateAndLogInAppPurchase call', () async {
instance.validateAndLogInAppAndroidPurchase(
"publicKey", "signature", "purchaseData", "price", "currency", null);
expect(selectedMethod, 'validateAndLogInAppAndroidPurchase');
});
test('check setMinTimeBetweenSessions call', () async {
instance.setMinTimeBetweenSessions(1);
expect(selectedMethod, 'setMinTimeBetweenSessions');
});
test('check getHostPrefix call', () async {
instance.getHostPrefix();
expect(selectedMethod, 'getHostPrefix');
});
test('check getHostName call', () async {
instance.getHostName();
expect(selectedMethod, 'getHostName');
});
test('check setCollectIMEI call', () async {
instance.setCollectIMEI(true);
expect(selectedMethod, 'setCollectIMEI');
});
test('check setCollectAndroidId call', () async {
instance.setCollectAndroidId(true);
expect(selectedMethod, 'setCollectAndroidId');
});
test('check setUserEmailsWithCryptType call', () async {
instance.setUserEmails(["emails"], EmailCryptType.EmailCryptTypeNone);
expect(selectedMethod, 'setUserEmailsWithCryptType');
});
test('check setUserEmails call', () async {
instance.setUserEmails(["emails"]);
expect(selectedMethod, 'setUserEmails');
});
test('check setAdditionalData call', () async {
instance.setAdditionalData(null);
expect(selectedMethod, 'setAdditionalData');
});
test('check waitForCustomerUserId call', () async {
instance.waitForCustomerUserId(false);
expect(selectedMethod, 'waitForCustomerUserId');
});
test('check setCustomerUserId call', () async {
instance.setCustomerUserId("id");
expect(selectedMethod, 'setCustomerUserId');
});
test('check enableLocationCollection call', () async {
instance.enableLocationCollection(false);
expect(selectedMethod, 'enableLocationCollection');
});
test('check setImeiData call', () async {
instance.setImeiData("imei");
expect(selectedMethod, 'setImeiData');
});
test('check setAndroidIdData call', () async {
instance.setAndroidIdData("androidId");
expect(selectedMethod, 'setAndroidIdData');
});
});
}
| appsflyer-flutter-plugin/test/appsflyer_sdk_test.dart/0 | {'file_path': 'appsflyer-flutter-plugin/test/appsflyer_sdk_test.dart', 'repo_id': 'appsflyer-flutter-plugin', 'token_count': 2953} |
export 'audio/audio_cubit.dart';
| article-hub/flame-game/sample/lib/game/cubit/cubit.dart/0 | {'file_path': 'article-hub/flame-game/sample/lib/game/cubit/cubit.dart', 'repo_id': 'article-hub', 'token_count': 14} |
// ignore_for_file: cascade_invocations
import 'package:audioplayers/audioplayers.dart';
import 'package:flame/extensions.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:sample/game/entities/unicorn/behaviors/behaviors.dart';
import 'package:sample/game/game.dart';
import 'package:sample/l10n/l10n.dart';
class _MockAppLocalizations extends Mock implements AppLocalizations {}
class _MockAudioPlayer extends Mock implements AudioPlayer {}
class _VeryGoodFlameGame extends VeryGoodFlameGame {
_VeryGoodFlameGame({required super.l10n, required super.effectPlayer});
@override
Future<void> onLoad() async {}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final l10n = _MockAppLocalizations();
final flameTester = FlameTester(
() => _VeryGoodFlameGame(l10n: l10n, effectPlayer: _MockAudioPlayer()),
);
group('Unicorn', () {
setUp(() {
when(() => l10n.counterText(any())).thenReturn('counterText');
});
flameTester.test('has all behaviors', (game) async {
final unicorn = Unicorn(position: Vector2.all(1));
await game.ensureAdd(unicorn);
expect(unicorn.findBehavior<TappingBehavior>(), isNotNull);
});
flameTester.test('loads correctly', (game) async {
final unicorn = Unicorn(position: Vector2.all(1));
await game.ensureAdd(unicorn);
expect(unicorn.isAnimationPlaying(), equals(false));
});
group('animation', () {
flameTester.test('plays animation', (game) async {
final unicorn = Unicorn.test(position: Vector2.all(1));
await game.ensureAdd(unicorn);
unicorn.playAnimation();
expect(unicorn.animation.currentIndex, equals(0));
game.update(0.1);
expect(unicorn.animation.currentIndex, equals(1));
expect(unicorn.isAnimationPlaying(), equals(true));
});
flameTester.test(
'reset animation back to frame one and stops it',
(game) async {
final unicorn = Unicorn.test(position: Vector2.all(1));
await game.ensureAdd(unicorn);
unicorn.playAnimation();
game.update(0.1);
expect(unicorn.animation.currentIndex, equals(1));
expect(unicorn.isAnimationPlaying(), equals(true));
unicorn.resetAnimation();
expect(unicorn.isAnimationPlaying(), equals(false));
expect(unicorn.animation.currentIndex, equals(0));
game.update(0.1);
expect(unicorn.animation.currentIndex, equals(0));
expect(unicorn.isAnimationPlaying(), equals(false));
},
);
});
});
}
| article-hub/flame-game/sample/test/game/entities/unicorn/unicorn_test.dart/0 | {'file_path': 'article-hub/flame-game/sample/test/game/entities/unicorn/unicorn_test.dart', 'repo_id': 'article-hub', 'token_count': 1033} |
include: package:pedantic/analysis_options.yaml
analyzer:
errors:
todo: ignore
# Lint provided by pkg:pedantic – should fix this!
unawaited_futures: ignore
linter:
rules:
- prefer_generic_function_type_aliases
- prefer_typing_uninitialized_variables
- unnecessary_const
- unnecessary_new
| async/analysis_options.yaml/0 | {'file_path': 'async/analysis_options.yaml', 'repo_id': 'async', 'token_count': 115} |
// 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';
/// A non-periodic timer that can be restarted any number of times.
///
/// Once restarted (via [reset]), the timer counts down from its original
/// duration again.
class RestartableTimer implements Timer {
/// The duration of the timer.
final Duration _duration;
/// The callback to call when the timer fires.
final ZoneCallback _callback;
/// The timer for the current or most recent countdown.
///
/// This timer is canceled and overwritten every time this [RestartableTimer]
/// is reset.
Timer _timer;
/// Creates a new timer.
///
/// The [callback] function is invoked after the given [duration]. Unlike a
/// normal non-periodic [Timer], [callback] may be called more than once.
RestartableTimer(this._duration, this._callback)
: _timer = Timer(_duration, _callback);
@override
bool get isActive => _timer.isActive;
/// Restarts the timer so that it counts down from its original duration
/// again.
///
/// This restarts the timer even if it has already fired or has been canceled.
void reset() {
_timer.cancel();
_timer = Timer(_duration, _callback);
}
@override
void cancel() {
_timer.cancel();
}
/// The number of durations preceding the most recent timer event on the most
/// recent countdown.
///
/// Calls to [reset] will also reset the tick so subsequent tick values may
/// not be strictly larger than previous values.
@override
int get tick => _timer.tick;
}
| async/lib/src/restartable_timer.dart/0 | {'file_path': 'async/lib/src/restartable_timer.dart', 'repo_id': 'async', 'token_count': 478} |
// 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 '../stream_sink_transformer.dart';
/// A [StreamSinkTransformer] that wraps a pre-existing [StreamTransformer].
class StreamTransformerWrapper<S, T> implements StreamSinkTransformer<S, T> {
/// The wrapped transformer.
final StreamTransformer<S, T> _transformer;
const StreamTransformerWrapper(this._transformer);
@override
StreamSink<S> bind(StreamSink<T> sink) =>
_StreamTransformerWrapperSink<S, T>(_transformer, sink);
}
/// A sink created by [StreamTransformerWrapper].
class _StreamTransformerWrapperSink<S, T> implements StreamSink<S> {
/// The controller through which events are passed.
///
/// This is used to create a stream that can be transformed by the wrapped
/// transformer.
final _controller = StreamController<S>(sync: true);
/// The original sink that's being transformed.
final StreamSink<T> _inner;
@override
Future get done => _inner.done;
_StreamTransformerWrapperSink(
StreamTransformer<S, T> transformer, this._inner) {
_controller.stream
.transform(transformer)
.listen(_inner.add, onError: _inner.addError, onDone: () {
// Ignore any errors that come from this call to [_inner.close]. The
// user can access them through [done] or the value returned from
// [this.close], and we don't want them to get top-leveled.
_inner.close().catchError((_) {});
});
}
@override
void add(S event) {
_controller.add(event);
}
@override
void addError(error, [StackTrace stackTrace]) {
_controller.addError(error, stackTrace);
}
@override
Future addStream(Stream<S> stream) => _controller.addStream(stream);
@override
Future close() {
_controller.close();
return _inner.done;
}
}
| async/lib/src/stream_sink_transformer/stream_transformer_wrapper.dart/0 | {'file_path': 'async/lib/src/stream_sink_transformer/stream_transformer_wrapper.dart', 'repo_id': 'async', 'token_count': 649} |
// 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 'package:async/async.dart';
import 'package:test/test.dart';
import 'utils.dart';
void main() {
group('constructors', () {
test('done defaults to a completed future', () {
var sink = NullStreamSink();
expect(sink.done, completes);
});
test('a custom future may be passed to done', () async {
var completer = Completer();
var sink = NullStreamSink(done: completer.future);
var doneFired = false;
sink.done.then((_) {
doneFired = true;
});
await flushMicrotasks();
expect(doneFired, isFalse);
completer.complete();
await flushMicrotasks();
expect(doneFired, isTrue);
});
test('NullStreamSink.error passes an error to done', () {
var sink = NullStreamSink.error('oh no');
expect(sink.done, throwsA('oh no'));
});
});
group('events', () {
test('are silently dropped before close', () {
var sink = NullStreamSink();
sink.add(1);
sink.addError('oh no');
});
test('throw StateErrors after close', () {
var sink = NullStreamSink();
expect(sink.close(), completes);
expect(() => sink.add(1), throwsStateError);
expect(() => sink.addError('oh no'), throwsStateError);
expect(() => sink.addStream(Stream.empty()), throwsStateError);
});
group('addStream', () {
test('listens to the stream then cancels immediately', () async {
var sink = NullStreamSink();
var canceled = false;
var controller = StreamController(onCancel: () {
canceled = true;
});
expect(sink.addStream(controller.stream), completes);
await flushMicrotasks();
expect(canceled, isTrue);
});
test('returns the cancel future', () async {
var completer = Completer();
var sink = NullStreamSink();
var controller = StreamController(onCancel: () => completer.future);
var addStreamFired = false;
sink.addStream(controller.stream).then((_) {
addStreamFired = true;
});
await flushMicrotasks();
expect(addStreamFired, isFalse);
completer.complete();
await flushMicrotasks();
expect(addStreamFired, isTrue);
});
test('pipes errors from the cancel future through addStream', () async {
var sink = NullStreamSink();
var controller = StreamController(onCancel: () => throw 'oh no');
expect(sink.addStream(controller.stream), throwsA('oh no'));
});
test('causes events to throw StateErrors until the future completes',
() async {
var sink = NullStreamSink();
var future = sink.addStream(Stream.empty());
expect(() => sink.add(1), throwsStateError);
expect(() => sink.addError('oh no'), throwsStateError);
expect(() => sink.addStream(Stream.empty()), throwsStateError);
await future;
sink.add(1);
sink.addError('oh no');
expect(sink.addStream(Stream.empty()), completes);
});
});
});
test('close returns the done future', () {
var sink = NullStreamSink.error('oh no');
expect(sink.close(), throwsA('oh no'));
});
}
| async/test/null_stream_sink_test.dart/0 | {'file_path': 'async/test/null_stream_sink_test.dart', 'repo_id': 'async', 'token_count': 1342} |
// 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 'package:async/async.dart';
import 'package:test/test.dart';
import 'utils.dart';
void main() {
group('with no callbacks', () {
test('forwards cancellation', () async {
var isCanceled = false;
var cancelCompleter = Completer();
var controller = StreamController(onCancel: expectAsync0(() {
isCanceled = true;
return cancelCompleter.future;
}));
var subscription = controller.stream
.transform(subscriptionTransformer())
.listen(expectAsync1((_) {}, count: 0));
var cancelFired = false;
subscription.cancel().then(expectAsync1((_) {
cancelFired = true;
}));
await flushMicrotasks();
expect(isCanceled, isTrue);
expect(cancelFired, isFalse);
cancelCompleter.complete();
await flushMicrotasks();
expect(cancelFired, isTrue);
// This shouldn't call the onCancel callback again.
expect(subscription.cancel(), completes);
});
test('forwards pausing and resuming', () async {
var controller = StreamController();
var subscription = controller.stream
.transform(subscriptionTransformer())
.listen(expectAsync1((_) {}, count: 0));
subscription.pause();
await flushMicrotasks();
expect(controller.isPaused, isTrue);
subscription.pause();
await flushMicrotasks();
expect(controller.isPaused, isTrue);
subscription.resume();
await flushMicrotasks();
expect(controller.isPaused, isTrue);
subscription.resume();
await flushMicrotasks();
expect(controller.isPaused, isFalse);
});
test('forwards pausing with a resume future', () async {
var controller = StreamController();
var subscription = controller.stream
.transform(subscriptionTransformer())
.listen(expectAsync1((_) {}, count: 0));
var completer = Completer();
subscription.pause(completer.future);
await flushMicrotasks();
expect(controller.isPaused, isTrue);
completer.complete();
await flushMicrotasks();
expect(controller.isPaused, isFalse);
});
});
group('with a cancel callback', () {
test('invokes the callback when the subscription is canceled', () async {
var isCanceled = false;
var callbackInvoked = false;
var controller = StreamController(onCancel: expectAsync0(() {
isCanceled = true;
}));
var subscription = controller.stream.transform(
subscriptionTransformer(handleCancel: expectAsync1((inner) {
callbackInvoked = true;
inner.cancel();
return null;
}))).listen(expectAsync1((_) {}, count: 0));
await flushMicrotasks();
expect(callbackInvoked, isFalse);
expect(isCanceled, isFalse);
subscription.cancel();
await flushMicrotasks();
expect(callbackInvoked, isTrue);
expect(isCanceled, isTrue);
});
test('invokes the callback once and caches its result', () async {
var completer = Completer();
var controller = StreamController();
var subscription = controller.stream
.transform(subscriptionTransformer(
handleCancel: expectAsync1((inner) => completer.future)))
.listen(expectAsync1((_) {}, count: 0));
var cancelFired1 = false;
subscription.cancel().then(expectAsync1((_) {
cancelFired1 = true;
}));
var cancelFired2 = false;
subscription.cancel().then(expectAsync1((_) {
cancelFired2 = true;
}));
await flushMicrotasks();
expect(cancelFired1, isFalse);
expect(cancelFired2, isFalse);
completer.complete();
await flushMicrotasks();
expect(cancelFired1, isTrue);
expect(cancelFired2, isTrue);
});
});
group('with a pause callback', () {
test('invokes the callback when pause is called', () async {
var pauseCount = 0;
var controller = StreamController();
var subscription = controller.stream
.transform(subscriptionTransformer(
handlePause: expectAsync1((inner) {
pauseCount++;
inner.pause();
}, count: 3)))
.listen(expectAsync1((_) {}, count: 0));
await flushMicrotasks();
expect(pauseCount, equals(0));
subscription.pause();
await flushMicrotasks();
expect(pauseCount, equals(1));
subscription.pause();
await flushMicrotasks();
expect(pauseCount, equals(2));
subscription.resume();
subscription.resume();
await flushMicrotasks();
expect(pauseCount, equals(2));
subscription.pause();
await flushMicrotasks();
expect(pauseCount, equals(3));
});
test("doesn't invoke the callback when the subscription has been canceled",
() async {
var controller = StreamController();
var subscription = controller.stream
.transform(subscriptionTransformer(
handlePause: expectAsync1((_) {}, count: 0)))
.listen(expectAsync1((_) {}, count: 0));
subscription.cancel();
subscription.pause();
subscription.pause();
subscription.pause();
});
});
group('with a resume callback', () {
test('invokes the callback when resume is called', () async {
var resumeCount = 0;
var controller = StreamController();
var subscription = controller.stream
.transform(subscriptionTransformer(
handleResume: expectAsync1((inner) {
resumeCount++;
inner.resume();
}, count: 3)))
.listen(expectAsync1((_) {}, count: 0));
await flushMicrotasks();
expect(resumeCount, equals(0));
subscription.resume();
await flushMicrotasks();
expect(resumeCount, equals(1));
subscription.pause();
subscription.pause();
await flushMicrotasks();
expect(resumeCount, equals(1));
subscription.resume();
await flushMicrotasks();
expect(resumeCount, equals(2));
subscription.resume();
await flushMicrotasks();
expect(resumeCount, equals(3));
});
test('invokes the callback when a resume future completes', () async {
var resumed = false;
var controller = StreamController();
var subscription = controller.stream.transform(
subscriptionTransformer(handleResume: expectAsync1((inner) {
resumed = true;
inner.resume();
}))).listen(expectAsync1((_) {}, count: 0));
var completer = Completer();
subscription.pause(completer.future);
await flushMicrotasks();
expect(resumed, isFalse);
completer.complete();
await flushMicrotasks();
expect(resumed, isTrue);
});
test("doesn't invoke the callback when the subscription has been canceled",
() async {
var controller = StreamController();
var subscription = controller.stream
.transform(subscriptionTransformer(
handlePause: expectAsync1((_) {}, count: 0)))
.listen(expectAsync1((_) {}, count: 0));
subscription.cancel();
subscription.resume();
subscription.resume();
subscription.resume();
});
});
group('when the outer subscription is canceled but the inner is not', () {
StreamSubscription subscription;
setUp(() {
var controller = StreamController();
subscription = controller.stream
.transform(subscriptionTransformer(handleCancel: (_) => null))
.listen(expectAsync1((_) {}, count: 0),
onError: expectAsync2((_, __) {}, count: 0),
onDone: expectAsync0(() {}, count: 0));
subscription.cancel();
controller.add(1);
controller.addError('oh no!');
controller.close();
});
test("doesn't call a new onData", () async {
subscription.onData(expectAsync1((_) {}, count: 0));
await flushMicrotasks();
});
test("doesn't call a new onError", () async {
subscription.onError(expectAsync2((_, __) {}, count: 0));
await flushMicrotasks();
});
test("doesn't call a new onDone", () async {
subscription.onDone(expectAsync0(() {}, count: 0));
await flushMicrotasks();
});
test('isPaused returns false', () {
expect(subscription.isPaused, isFalse);
});
test('asFuture never completes', () async {
subscription.asFuture().then(expectAsync1((_) {}, count: 0));
await flushMicrotasks();
});
});
}
| async/test/subscription_transformer_test.dart/0 | {'file_path': 'async/test/subscription_transformer_test.dart', 'repo_id': 'async', 'token_count': 3404} |
import 'package:atlas/atlas.dart';
import 'package:flutter/foundation.dart';
/// The `CameraPosition` represents the position of the map "camera",
/// the view point from which the world is shown in the map view.
/// Aggregates the camera's `target` geographical location and the its `zoom` level.
class CameraPosition {
/// The camera's `target` position as `LatLng`.
final LatLng target;
/// The camera's zoom level as a `double`.
final double zoom;
const CameraPosition({
@required this.target,
this.zoom = 0.0,
}) : assert(target != null);
}
| atlas/packages/atlas/lib/src/camera_position.dart/0 | {'file_path': 'atlas/packages/atlas/lib/src/camera_position.dart', 'repo_id': 'atlas', 'token_count': 171} |
import 'package:atlas/atlas.dart';
import 'package:flutter_test/flutter_test.dart';
main() {
group('LatLngBounds', () {
test('should throw AssertionError if northeast is null', () {
try {
LatLngBounds(
northeast: null,
southwest: LatLng(latitude: 0, longitude: 0),
);
fail('should throw AssertionError');
} catch (error) {
expect(error, isAssertionError);
}
});
test('should throw AssertionError if southwest is null', () {
try {
LatLngBounds(
northeast: LatLng(latitude: 0, longitude: 0),
southwest: null,
);
fail('should throw AssertionError');
} catch (error) {
expect(error, isAssertionError);
}
});
});
}
| atlas/packages/atlas/test/lat_lng_bounds_test.dart/0 | {'file_path': 'atlas/packages/atlas/test/lat_lng_bounds_test.dart', 'repo_id': 'atlas', 'token_count': 352} |
import 'dart:async';
import 'dart:ui';
import 'package:flutter/widgets.dart';
import 'package:atlas/atlas.dart';
import 'package:google_atlas/google_atlas.dart';
import 'package:google_atlas/src/utils/utils.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart' as GoogleMaps;
/// `Atlas` Provider for Google Maps
class GoogleAtlas extends Provider {
@override
Set<MapType> get supportedMapTypes => {
MapType.normal,
MapType.satellite,
MapType.terrain,
};
@override
Widget build({
@required CameraPosition initialCameraPosition,
@required Set<Marker> markers,
@required Set<Circle> circles,
@required Set<Polygon> polygons,
@required Set<Polyline> polylines,
@required bool showMyLocation,
@required bool showMyLocationButton,
@required MapType mapType,
@required bool showTraffic,
ArgumentCallback<LatLng> onTap,
ArgumentCallback<LatLng> onLongPress,
ArgumentCallback<AtlasController> onMapCreated,
ArgumentCallback<CameraPosition> onCameraPositionChanged,
}) {
return GoogleMapsProvider(
initialCameraPosition: initialCameraPosition,
markers: markers,
showMyLocation: showMyLocation,
showMyLocationButton: showMyLocationButton,
mapType: mapType,
showTraffic: showTraffic,
onTap: onTap,
onLongPress: onLongPress,
onMapCreated: onMapCreated,
);
}
}
class GoogleMapsProvider extends StatefulWidget {
final CameraPosition initialCameraPosition;
final Set<Marker> markers;
final bool showMyLocation;
final bool showMyLocationButton;
final MapType mapType;
final bool showTraffic;
final ArgumentCallback<LatLng> onTap;
final ArgumentCallback<LatLng> onLongPress;
final ArgumentCallback<AtlasController> onMapCreated;
GoogleMapsProvider({
@required this.initialCameraPosition,
@required this.markers,
@required this.showMyLocation,
@required this.showMyLocationButton,
@required this.mapType,
@required this.showTraffic,
this.onTap,
this.onLongPress,
this.onMapCreated,
});
State<GoogleMapsProvider> createState() => _GoogleMapsProviderState();
}
class _GoogleMapsProviderState extends State<GoogleMapsProvider> {
CameraPosition get initialCameraPosition => widget.initialCameraPosition;
Set<Marker> get markers => widget.markers;
bool get showMyLocation => widget.showMyLocation;
bool get showMyLocationButton => widget.showMyLocationButton;
MapType get mapType => widget.mapType;
bool get showTraffic => widget.showTraffic;
ArgumentCallback<LatLng> get onTap => widget.onTap;
ArgumentCallback<LatLng> get onLongPress => widget.onLongPress;
ArgumentCallback<AtlasController> get onMapCreated => widget.onMapCreated;
@override
Widget build(BuildContext context) {
return FutureBuilder<Set<GoogleMaps.Marker>>(
future: _toGoogleMarkers(markers),
initialData: Set<GoogleMaps.Marker>(),
builder: (context, snapshot) {
return GoogleMaps.GoogleMap(
myLocationEnabled: showMyLocation,
myLocationButtonEnabled: showMyLocationButton,
mapType: _toGoogleMapType(mapType),
trafficEnabled: showTraffic,
initialCameraPosition:
CameraUtils.toGoogleCameraPosition(initialCameraPosition),
markers: snapshot.hasError ? Set<GoogleMaps.Marker>() : snapshot.data,
onTap: _toGoogleOnTap(onTap),
onLongPress: _toGoogleOnLongPress(onLongPress),
onMapCreated: _onMapCreated,
);
},
);
}
/// Converts an `Atlas.Marker` to a `GoogleMaps.Marker`
Future<Set<GoogleMaps.Marker>> _toGoogleMarkers(Set<Marker> markers) async {
Set<GoogleMaps.Marker> googleMarkers = Set();
for (Marker marker in markers) {
googleMarkers.add(
GoogleMaps.Marker(
markerId: GoogleMaps.MarkerId(marker.id),
position: GoogleMaps.LatLng(
marker.position.latitude,
marker.position.longitude,
),
onTap: marker.onTap,
icon: marker.icon == null
? null
: await _toBitmapDescriptor(marker.icon),
),
);
}
return googleMarkers;
}
/// Converts an `Atlas.MapIcon` to an `GoogleMaps.BitmapDescriptor`
Future<GoogleMaps.BitmapDescriptor> _toBitmapDescriptor(
MarkerIcon markerIcon,
) async {
final ImageConfiguration imageConfiguration = ImageConfiguration(
devicePixelRatio: window.devicePixelRatio,
);
GoogleMaps.BitmapDescriptor bitmapDescriptor;
try {
bitmapDescriptor = await GoogleMaps.BitmapDescriptor.fromAssetImage(
imageConfiguration,
markerIcon.assetName,
);
} catch (_) {}
return bitmapDescriptor;
}
/// Converts a `GoogleMaps.onTap` to an `Atlas.onTap` callback.
void Function(GoogleMaps.LatLng) _toGoogleOnTap(
ArgumentCallback<LatLng> onTap,
) {
return (GoogleMaps.LatLng position) {
onTap?.call(LatLngUtils.fromGoogleLatLng(position));
};
}
/// Converts a `GoogleMaps.onLongPress` to an `Atlas.onLongPress` callback.
void Function(GoogleMaps.LatLng) _toGoogleOnLongPress(
ArgumentCallback<LatLng> onLongPress,
) {
return (GoogleMaps.LatLng position) {
onLongPress?.call(LatLngUtils.fromGoogleLatLng(position));
};
}
/// Converts an `Atlas.MapType` enum to a `GoogleMaps.MapType` enum.
GoogleMaps.MapType _toGoogleMapType(MapType atlasMapType) {
switch (atlasMapType) {
case MapType.normal:
return GoogleMaps.MapType.normal;
break;
case MapType.satellite:
return GoogleMaps.MapType.satellite;
break;
case MapType.hybrid:
return GoogleMaps.MapType.hybrid;
break;
case MapType.terrain:
return GoogleMaps.MapType.terrain;
break;
default:
return GoogleMaps.MapType.normal;
}
}
/// Callback method where GoogleMaps passes the map controller
void _onMapCreated(GoogleMaps.GoogleMapController controller) async {
onMapCreated?.call(
GoogleAtlasController(controller: controller),
);
}
}
| atlas/packages/google_atlas/lib/src/google_atlas.dart/0 | {'file_path': 'atlas/packages/google_atlas/lib/src/google_atlas.dart', 'repo_id': 'atlas', 'token_count': 2306} |
name: stale
on:
schedule:
- cron: "0 0 * * *" # pick a cron here, this is every day
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: luanpotter/changes-requested@master
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
# these are optional, if you want to configure:
days-until-close: 30
trigger-label: stale
closing-comment: This issue was closed by the stale bot due to inactivity.
dry-run: false
| audioplayers/.github/workflows/stale.yml/0 | {'file_path': 'audioplayers/.github/workflows/stale.yml', 'repo_id': 'audioplayers', 'token_count': 224} |
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import '../../platform_features.dart';
import '../../test_utils.dart';
import '../app_source_test_data.dart';
import '../app_test_utils.dart';
import 'properties.dart';
Future<void> testStreamsTab(
WidgetTester tester,
AppSourceTestData audioSourceTestData,
PlatformFeatures features,
) async {
printWithTimeOnFailure('Test Streams Tab');
await tester.tap(find.byKey(const Key('streamsTab')));
await tester.pumpAndSettle();
// Stream position is tracked as soon as source is loaded
if (!audioSourceTestData.isLiveStream) {
// Display position before playing
await tester.testPosition(Duration.zero);
}
if (features.hasDurationEvent && !audioSourceTestData.isVBR) {
// Display duration before playing
await tester.testDuration(audioSourceTestData.duration);
}
// Sources take some time to get initialized
const timeout = Duration(seconds: 8);
await tester.pumpAndSettle();
await tester.scrollToAndTap(const Key('play_button'));
await tester.pump();
// Cannot test more precisely as it is dependent on pollInterval
// and updateInterval of native implementation.
if (audioSourceTestData.isLiveStream ||
audioSourceTestData.duration! > const Duration(seconds: 2)) {
// Test player state: playing
if (features.hasPlayerStateEvent) {
// Only test, if there's enough time to be able to check playing state.
await tester.testPlayerState(PlayerState.playing, timeout: timeout);
await tester.testOnPlayerState(PlayerState.playing, timeout: timeout);
}
// Test if onPositionText is set.
await tester.testPosition(
Duration.zero,
matcher: (Duration? position) => greaterThan(position ?? Duration.zero),
timeout: timeout,
);
await tester.testOnPosition(
Duration.zero,
matcher: greaterThan,
timeout: timeout,
);
}
if (features.hasDurationEvent && !audioSourceTestData.isLiveStream) {
// Test if onDurationText is set.
await tester.testOnDuration(
audioSourceTestData.duration!,
timeout: timeout,
);
}
const sampleDuration = Duration(seconds: 3);
await tester.pump(sampleDuration);
// Test player states: pause, stop, completed
if (features.hasPlayerStateEvent) {
if (!audioSourceTestData.isLiveStream) {
if (audioSourceTestData.duration! < const Duration(seconds: 2)) {
await tester.testPlayerState(PlayerState.completed, timeout: timeout);
await tester.testOnPlayerState(PlayerState.completed, timeout: timeout);
} else if (audioSourceTestData.duration! > const Duration(seconds: 5)) {
await tester.scrollToAndTap(const Key('pause_button'));
await tester.pumpAndSettle();
await tester.testPlayerState(PlayerState.paused);
await tester.testOnPlayerState(PlayerState.paused);
await tester.stopStream();
await tester.testPlayerState(PlayerState.stopped);
await tester.testOnPlayerState(PlayerState.stopped);
} else {
// Cannot say for sure, if it's stopped or completed, so we just stop
await tester.stopStream();
}
} else {
await tester.stopStream();
await tester.testPlayerState(PlayerState.stopped, timeout: timeout);
await tester.testOnPlayerState(PlayerState.stopped, timeout: timeout);
}
}
// Display duration & position after completion / stop
// FIXME(Gustl22): Linux does not support duration after completion event
if (features.hasDurationEvent &&
(kIsWeb || defaultTargetPlatform != TargetPlatform.linux)) {
await tester.testDuration(audioSourceTestData.duration);
if (!audioSourceTestData.isLiveStream) {
await tester.testOnDuration(
audioSourceTestData.duration!,
timeout: timeout,
);
}
}
if (!audioSourceTestData.isLiveStream) {
await tester.testPosition(Duration.zero);
}
}
extension StreamWidgetTester on WidgetTester {
// Precision for position & duration:
// Android: millisecond
// Windows: millisecond
// Linux: millisecond
// Web: millisecond
// Darwin: millisecond
Future<void> stopStream() async {
final st = StackTrace.current.toString();
await scrollToAndTap(const Key('stop_button'));
await waitOneshot(const Key('toast-player-stopped-0'), stackTrace: st);
await pumpAndSettle();
}
Future<void> testOnDuration(
Duration duration, {
Duration timeout = const Duration(seconds: 10),
}) async {
printWithTimeOnFailure('Test OnDuration: $duration');
final st = StackTrace.current.toString();
await waitFor(
() async => expectWidgetHasDuration(
const Key('onDurationText'),
matcher: (Duration? actual) => durationRangeMatcher(
actual,
duration,
deviation: const Duration(milliseconds: 500),
),
),
timeout: timeout,
stackTrace: st,
);
}
Future<void> testOnPosition(
Duration position, {
Matcher Function(Duration) matcher = equals,
Duration timeout = const Duration(seconds: 10),
}) async {
printWithTimeOnFailure('Test OnPosition: $position');
final st = StackTrace.current.toString();
await waitFor(
() async => expectWidgetHasDuration(
const Key('onPositionText'),
matcher: matcher(position),
),
pollInterval: const Duration(milliseconds: 250),
timeout: timeout,
stackTrace: st,
);
}
Future<void> testOnPlayerState(
PlayerState playerState, {
Duration timeout = const Duration(seconds: 10),
}) async {
printWithTimeOnFailure('Test OnState: $playerState');
final st = StackTrace.current.toString();
await waitFor(
() async => expectWidgetHasText(
const Key('onStateText'),
matcher: equals(playerState.toString()),
),
pollInterval: const Duration(milliseconds: 250),
timeout: timeout,
stackTrace: st,
);
}
}
| audioplayers/packages/audioplayers/example/integration_test/app/tabs/stream_tab.dart/0 | {'file_path': 'audioplayers/packages/audioplayers/example/integration_test/app/tabs/stream_tab.dart', 'repo_id': 'audioplayers', 'token_count': 2109} |
import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:audioplayers_example/utils.dart';
import 'package:flutter/material.dart';
class StreamWidget extends StatefulWidget {
final AudioPlayer player;
const StreamWidget({
required this.player,
super.key,
});
@override
State<StreamWidget> createState() => _StreamWidgetState();
}
class _StreamWidgetState extends State<StreamWidget> {
Duration? streamDuration;
Duration? streamPosition;
PlayerState? streamState;
late List<StreamSubscription> streams;
AudioPlayer get player => widget.player;
@override
void initState() {
super.initState();
// Use initial values from player
streamState = player.state;
player.getDuration().then((it) => setState(() => streamDuration = it));
player.getCurrentPosition().then(
(it) => setState(() => streamPosition = it),
);
streams = <StreamSubscription>[
player.onDurationChanged
.listen((it) => setState(() => streamDuration = it)),
player.onPlayerStateChanged
.listen((it) => setState(() => streamState = it)),
player.onPositionChanged
.listen((it) => setState(() => streamPosition = it)),
];
}
@override
void dispose() {
super.dispose();
streams.forEach((it) => it.cancel());
}
@override
void setState(VoidCallback fn) {
// Subscriptions only can be closed asynchronously,
// therefore events can occur after widget has been disposed.
if (mounted) {
super.setState(fn);
}
}
@override
Widget build(BuildContext context) {
return Column(
children: [
const ListTile(title: Text('Streams')),
ListTile(
title: Text(
streamDuration?.toString() ?? '-',
key: const Key('onDurationText'),
),
subtitle: const Text('Duration Stream'),
leading: const Icon(Icons.timelapse),
),
ListTile(
title: Text(
streamPosition?.toString() ?? '-',
key: const Key('onPositionText'),
),
subtitle: const Text('Position Stream'),
leading: const Icon(Icons.timer),
),
ListTile(
title: Text(
streamState?.toString() ?? '-',
key: const Key('onStateText'),
),
subtitle: const Text('State Stream'),
leading: Icon(streamState?.getIcon() ?? Icons.stop),
),
],
);
}
}
| audioplayers/packages/audioplayers/example/lib/components/stream_widget.dart/0 | {'file_path': 'audioplayers/packages/audioplayers/example/lib/components/stream_widget.dart', 'repo_id': 'audioplayers', 'token_count': 1004} |
import 'dart:convert';
import 'dart:typed_data';
import 'package:audioplayers/audioplayers.dart';
import 'package:file/memory.dart';
import 'package:flutter_test/flutter_test.dart';
class FakeAudioCache extends AudioCache {
List<String> called = [];
FakeAudioCache({super.prefix, super.cacheId});
@override
Future<Uri> fetchToMemory(String fileName) async {
called.add(fileName);
return super.fetchToMemory(fileName);
}
@override
Future<ByteData> loadAsset(String path) async {
return ByteData.sublistView(utf8.encode(path));
}
@override
Future<String> getTempDir() async => '/';
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
AudioCache.fileSystem = MemoryFileSystem.test();
});
group('AudioCache', () {
test('sets cache', () async {
final cache = FakeAudioCache();
await cache.load('audio.mp3');
expect(cache.loadedFiles['audio.mp3'], isNotNull);
expect(cache.called, hasLength(1));
cache.called.clear();
await cache.load('audio.mp3');
expect(cache.called, hasLength(0));
});
test('clear cache', () async {
final cache = FakeAudioCache();
await cache.load('audio.mp3');
expect(cache.loadedFiles['audio.mp3'], isNotNull);
await cache.clearAll();
expect(cache.loadedFiles, <String, Uri>{});
await cache.load('audio.mp3');
expect(cache.loadedFiles.isNotEmpty, isTrue);
await cache.clear('audio.mp3');
expect(cache.loadedFiles, <String, Uri>{});
});
test('Use different location for two audio caches', () async {
const fileName = 'audio.mp3';
final cacheA = FakeAudioCache(cacheId: 'cache-path-A');
await cacheA.load(fileName);
expect(cacheA.loadedFiles[fileName]?.path, '//cache-path-A/audio.mp3');
final cacheB = FakeAudioCache(cacheId: 'cache-path-B');
await cacheB.load(fileName);
expect(cacheB.loadedFiles[fileName]?.path, '//cache-path-B/audio.mp3');
await cacheA.clearAll();
await cacheB.clearAll();
});
});
}
| audioplayers/packages/audioplayers/test/audio_cache_test.dart/0 | {'file_path': 'audioplayers/packages/audioplayers/test/audio_cache_test.dart', 'repo_id': 'audioplayers', 'token_count': 793} |
import 'dart:async';
import 'package:audioplayers_platform_interface/src/api/audio_context.dart';
import 'package:audioplayers_platform_interface/src/api/global_audio_event.dart';
import 'package:audioplayers_platform_interface/src/global_audioplayers_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'util.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final platform = GlobalAudioplayersPlatformInterface.instance;
final methodCalls = <MethodCall>[];
void clear() {
methodCalls.clear();
}
MethodCall popCall() {
return methodCalls.removeAt(0);
}
MethodCall popLastCall() {
expect(methodCalls, hasLength(1));
return popCall();
}
group('Global Method Channel', () {
setUp(() {
clear();
createNativeMethodHandler(
channel: 'xyz.luan/audioplayers.global',
handler: (MethodCall methodCall) async {
methodCalls.add(methodCall);
return null;
},
);
});
test('set AudioContext for Windows', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.windows;
await platform.setGlobalAudioContext(AudioContext());
final call = popLastCall();
expect(call.method, 'setAudioContext');
expect(call.args, <String, dynamic>{});
});
test('set AudioContext for macOS', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.macOS;
await platform.setGlobalAudioContext(AudioContext());
final call = popLastCall();
expect(call.method, 'setAudioContext');
expect(call.args, <String, dynamic>{});
});
test('set AudioContext for Linux', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.linux;
await platform.setGlobalAudioContext(AudioContext());
final call = popLastCall();
expect(call.method, 'setAudioContext');
expect(call.args, <String, dynamic>{});
});
test('set AudioContext for Android', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
await platform.setGlobalAudioContext(AudioContext());
final call = popLastCall();
expect(call.method, 'setAudioContext');
expect(call.args, {
'isSpeakerphoneOn': false,
'audioMode': 0,
'stayAwake': false,
'contentType': 2,
'usageType': 1,
'audioFocus': 1,
});
});
test('set AudioContext for iOS', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
await platform.setGlobalAudioContext(AudioContext());
final call = popLastCall();
expect(call.method, 'setAudioContext');
expect(call.args, {'category': 'playback', 'options': []});
});
});
group('Global Event Channel', () {
test('emit global events', () async {
final eventController = StreamController<ByteData>.broadcast();
createNativeEventStream(
channel: 'xyz.luan/audioplayers.global/events',
byteDataStream: eventController.stream,
);
expect(
platform.getGlobalEventStream(),
emitsInOrder(<GlobalAudioEvent>[
const GlobalAudioEvent(
eventType: GlobalAudioEventType.log,
logMessage: 'someLogMessage',
),
]),
);
final byteDataList = <Map<String, dynamic>>[
<String, dynamic>{
'event': 'audio.onLog',
'value': 'someLogMessage',
},
];
for (final byteData in byteDataList) {
eventController.add(
const StandardMethodCodec().encodeSuccessEnvelope(byteData),
);
}
await eventController.close();
});
});
}
| audioplayers/packages/audioplayers_platform_interface/test/global_platform_test.dart/0 | {'file_path': 'audioplayers/packages/audioplayers_platform_interface/test/global_platform_test.dart', 'repo_id': 'audioplayers', 'token_count': 1428} |
import 'package:benckmark/_bloc_lib/_shared/entitity.dart';
import 'package:benckmark/_bloc_lib/_shared/item.entity.dart';
import 'items.events.dart';
import 'items.state.dart';
class ItemsBloc extends EntityBloc<EntityEvent, ItemsState> {
@override
ItemsState get initialState => ItemsState(sampleItems);
@override
Stream<ItemsState> mapEventToState(EntityEvent event) async* {
if (event is AddItemEvent) {
final List<Item> items = List.from(state.entities)..add(event.item);
yield ItemsState(items);
} else if (event is AddItemsEvent) {
final List<Item> items = List.from(state.entities)..addAll(event.items);
yield ItemsState(items);
} else if (event is RemoveItemsEvent) {
final List<Item> items = List.from(state.entities);
items.removeWhere((item) => event.itemIds.contains(item.id));
yield ItemsState(items);
}
}
}
| benchmarks/state_managers/lib/_bloc_lib/_blocs/items/items.bloc.dart/0 | {'file_path': 'benchmarks/state_managers/lib/_bloc_lib/_blocs/items/items.bloc.dart', 'repo_id': 'benchmarks', 'token_count': 325} |
import 'package:flutter/foundation.dart';
import 'package:benckmark/item.dart';
class AppState with ChangeNotifier {
List<Item> _items = sampleItems;
List<Item> get items => _items;
void addItem(Item item) {
_items.add(item);
notifyListeners();
}
}
| benchmarks/state_managers/lib/_provider/_state.dart/0 | {'file_path': 'benchmarks/state_managers/lib/_provider/_state.dart', 'repo_id': 'benchmarks', 'token_count': 95} |
import 'package:flame/components/component.dart';
import 'package:ordered_set/comparing.dart';
import 'package:ordered_set/ordered_set.dart';
import 'components/block.dart';
import 'components/end_card.dart';
import 'components/hud.dart';
import 'components/player.dart';
import 'components/shooter.dart';
import 'components/tutorial.dart';
class QueryableOrderedSet<T, E> extends OrderedSet<T> {
final Map<E, bool Function(T)> _fns = {};
final Map<E, List<T>> _cache = {};
QueryableOrderedSet([int compare(T e1, T e2)]) : super(compare);
void register(E e, bool Function(T) query) {
_fns[e] = query;
_cache[e] = _filter(_fns[e]);
}
List<T> query(E e) {
return _cache[e];
}
@override
bool add(T t) {
if (super.add(t)) {
_fns.keys.forEach((e) {
if (_fns[e](t)) {
_cache[e].add(t);
}
});
return true;
}
return false;
}
@override
List<T> removeWhere(bool test(T element)) {
_cache.values.forEach((v) => v.removeWhere(test));
return super.removeWhere(test);
}
@override
bool remove(T e) {
_cache.values.forEach((v) => v.remove(e));
return super.remove(e);
}
@override
void clear() {
_cache.values.forEach((v) => v.clear());
super.clear();
}
List<T> _filter(bool Function(T) query) => where(query).toList();
}
enum Queries {
BaseBlock,
Player,
Shooter,
Hud,
EndCard,
Tutorial,
}
class QueryableOrderedSetImpl extends QueryableOrderedSet<Component, Queries> {
QueryableOrderedSetImpl() : super(Comparing.on((c) => c.priority())) {
register(Queries.BaseBlock, (e) => e is BaseBlock);
register(Queries.Player, (e) => e is Player);
register(Queries.Shooter, (e) => e is Shooter);
register(Queries.Hud, (e) => e is Hud);
register(Queries.EndCard, (e) => e is EndCard);
register(Queries.Tutorial, (e) => e is Tutorial);
}
Iterable<Shooter> shooters() {
return _postFilter<Shooter>(Queries.Shooter);
}
Iterable<BaseBlock> blocks() {
return _postFilter<BaseBlock>(Queries.BaseBlock);
}
Player player() {
return _firstOrNull<Player>(Queries.Player);
}
Hud hud() {
return _firstOrNull<Hud>(Queries.Hud);
}
EndCard endCard() {
return _firstOrNull<EndCard>(Queries.EndCard);
}
Tutorial tutorial() {
return _firstOrNull<Tutorial>(Queries.Tutorial);
}
bool has(Queries q) {
return _postFilter(q).isNotEmpty;
}
T _firstOrNull<T>(Queries e) {
if (!has(e)) {
return null;
}
return _postFilter<T>(e).first;
}
Iterable<T> _postFilter<T>(Queries e) {
return query(e).cast();
}
}
| bgug/lib/queryable_ordered_set.dart/0 | {'file_path': 'bgug/lib/queryable_ordered_set.dart', 'repo_id': 'bgug', 'token_count': 1074} |
import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;
import 'package:json_annotation/json_annotation.dart';
part 'skin_list.g.dart';
@JsonSerializable()
class Skin {
final String name;
final String file;
final int cost;
Skin(this.name, this.file, this.cost);
factory Skin.fromJson(Map<String, dynamic> json) => _$SkinFromJson(json);
Map<String, dynamic> toJson() => _$SkinToJson(this);
}
@JsonSerializable()
class SkinList {
final List<Skin> skins;
SkinList(this.skins);
factory SkinList.fromJson(Map<String, dynamic> json) => _$SkinListFromJson(json);
Map<String, dynamic> toJson() => _$SkinListToJson(this);
static Future<SkinList> fetch() async {
final jsonStr = await rootBundle.loadString('assets/store-skins.json');
return SkinList.fromJson(json.decode(jsonStr));
}
}
| bgug/lib/skin_list.dart/0 | {'file_path': 'bgug/lib/skin_list.dart', 'repo_id': 'bgug', 'token_count': 302} |
import 'dart:ffi' as ffi;
import 'dart:io';
import 'dart:typed_data' as typed; // For Platform.isX
import 'package:ffi/ffi.dart' as ext_ffi;
final ffi.DynamicLibrary bitmapFFILib = Platform.isAndroid
? ffi.DynamicLibrary.open("libbitmap.so")
: ffi.DynamicLibrary.process();
typedef BitmapFFIExecution = void Function(
ffi.Pointer<ffi.Uint8> startingPointer,
typed.Uint8List pointerList,
);
class FFIImpl {
FFIImpl(this.ffiExecution);
final BitmapFFIExecution ffiExecution;
void execute(typed.Uint8List sourceBmp) {
final ffi.Pointer<ffi.Uint8> startingPointer = ext_ffi.calloc<ffi.Uint8>(
sourceBmp.length,
);
final pointerList = startingPointer.asTypedList(sourceBmp.length);
pointerList.setAll(0, sourceBmp);
ffiExecution(startingPointer, pointerList);
sourceBmp.setAll(0, pointerList);
ext_ffi.calloc.free(startingPointer);
}
}
| bitmap/lib/src/ffi.dart/0 | {'file_path': 'bitmap/lib/src/ffi.dart', 'repo_id': 'bitmap', 'token_count': 359} |
name: ci
on:
pull_request:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: noop
run: echo 'noop'
| bloc.js/.github/workflows/ci.yaml/0 | {'file_path': 'bloc.js/.github/workflows/ci.yaml', 'repo_id': 'bloc.js', 'token_count': 81} |
export 'complex_list_page.dart';
| bloc/examples/flutter_complex_list/lib/complex_list/view/view.dart/0 | {'file_path': 'bloc/examples/flutter_complex_list/lib/complex_list/view/view.dart', 'repo_id': 'bloc', 'token_count': 12} |
import 'package:bloc/bloc.dart';
/// {@template counter_observer}
/// [BlocObserver] for the counter application which
/// observes all state changes.
/// {@endtemplate}
class CounterObserver extends BlocObserver {
/// {@macro counter_observer}
const CounterObserver();
@override
void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) {
super.onChange(bloc, change);
// ignore: avoid_print
print('${bloc.runtimeType} $change');
}
}
| bloc/examples/flutter_counter/lib/counter_observer.dart/0 | {'file_path': 'bloc/examples/flutter_counter/lib/counter_observer.dart', 'repo_id': 'bloc', 'token_count': 155} |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_dynamic_form/new_car/new_car.dart';
import 'package:flutter_dynamic_form/new_car_repository.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class MockNewCarRepository extends Mock implements NewCarRepository {}
class MockNewCarBloc extends MockBloc<NewCarEvent, NewCarState>
implements NewCarBloc {}
extension on WidgetTester {
Future<void> pumpNewCarPage(NewCarRepository newCarRepository) {
return pumpWidget(
MaterialApp(
home: Scaffold(
body: RepositoryProvider.value(
value: newCarRepository,
child: const NewCarPage(),
),
),
),
);
}
Future<void> pumpNewCarForm(NewCarBloc newCarBloc) {
return pumpWidget(
MaterialApp(
home: Scaffold(
body: BlocProvider.value(
value: newCarBloc,
child: const NewCarForm(),
),
),
),
);
}
}
void main() {
const brandDropdownButtonKey = Key('newCarForm_brand_dropdownButton');
const modelDropdownButtonKey = Key('newCarForm_model_dropdownButton');
const yearDropdownButtonKey = Key('newCarForm_year_dropdownButton');
late NewCarRepository newCarRepository;
late NewCarBloc newCarBloc;
const mockBrands = ['Chevy', 'Toyota', 'Honda'];
final mockBrand = mockBrands[0];
const mockModels = ['Malibu', 'Impala'];
final mockModel = mockModels[0];
const mockYears = ['2008', '2020'];
final mockYear = mockYears[0];
setUp(() {
newCarRepository = MockNewCarRepository();
newCarBloc = MockNewCarBloc();
});
tearDown(resetMocktailState);
group('NewCarPage', () {
testWidgets('renders NewCarForm', (tester) async {
when(() => newCarRepository.fetchBrands()).thenAnswer(
(_) async => ['honda'],
);
await tester.pumpNewCarPage(newCarRepository);
expect(find.byType(NewCarForm), findsOneWidget);
verify(() => newCarRepository.fetchBrands()).called(1);
});
});
group('NewCarForm', () {
testWidgets('displays SnackBar after a submission', (tester) async {
when(() => newCarBloc.state).thenReturn(
const NewCarState.initial().copyWith(
brand: mockBrand,
model: mockModel,
year: mockYear,
),
);
await tester.pumpNewCarForm(newCarBloc);
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(find.byType(SnackBar), findsOneWidget);
expect(
find.text('Submitted $mockBrand $mockModel $mockYear'),
findsOneWidget,
);
});
testWidgets('cannot submit blank form', (tester) async {
when(() => newCarBloc.state).thenReturn(const NewCarState.initial());
await tester.pumpNewCarForm(newCarBloc);
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(find.byType(SnackBar), findsNothing);
});
testWidgets('can select a brand via DropdownButton', (tester) async {
when(() => newCarBloc.state).thenReturn(
const NewCarState.initial().copyWith(brands: mockBrands),
);
await tester.pumpNewCarForm(newCarBloc..add(const NewCarFormLoaded()));
await tester.tap(find.byKey(brandDropdownButtonKey));
await tester.pumpAndSettle();
await tester.tap(find.text(mockBrand).last);
verify(
() => newCarBloc.add(NewCarBrandChanged(brand: mockBrand)),
).called(1);
});
testWidgets('can select a model via DropdownButton', (tester) async {
when(() => newCarBloc.state).thenReturn(
const NewCarState.initial().copyWith(models: mockModels),
);
await tester.pumpNewCarForm(newCarBloc);
await tester.tap(find.byKey(modelDropdownButtonKey));
await tester.pumpAndSettle();
await tester.tap(find.text(mockModel).last);
verify(
() => newCarBloc.add(NewCarModelChanged(model: mockModel)),
).called(1);
});
testWidgets('can select a year via DropdownButton', (tester) async {
when(() => newCarBloc.state).thenReturn(
const NewCarState.initial().copyWith(years: mockYears),
);
await tester.pumpNewCarForm(newCarBloc);
await tester.tap(find.byKey(yearDropdownButtonKey));
await tester.pumpAndSettle();
await tester.tap(find.text(mockYear).last);
verify(() => newCarBloc.add(NewCarYearChanged(year: mockYear))).called(1);
});
});
}
| bloc/examples/flutter_dynamic_form/test/new_car/view/new_car_page_test.dart/0 | {'file_path': 'bloc/examples/flutter_dynamic_form/test/new_car/view/new_car_page_test.dart', 'repo_id': 'bloc', 'token_count': 1889} |
export 'avatar.dart';
| bloc/examples/flutter_firebase_login/lib/home/widgets/widgets.dart/0 | {'file_path': 'bloc/examples/flutter_firebase_login/lib/home/widgets/widgets.dart', 'repo_id': 'bloc', 'token_count': 9} |
library authentication_repository;
export 'src/authentication_repository.dart';
export 'src/models/models.dart';
| bloc/examples/flutter_firebase_login/packages/authentication_repository/lib/authentication_repository.dart/0 | {'file_path': 'bloc/examples/flutter_firebase_login/packages/authentication_repository/lib/authentication_repository.dart', 'repo_id': 'bloc', 'token_count': 36} |
name: form_inputs
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.19.0 <3.0.0"
dependencies:
formz: ^0.4.0
dev_dependencies:
very_good_analysis: ^3.1.0
| bloc/examples/flutter_firebase_login/packages/form_inputs/pubspec.yaml/0 | {'file_path': 'bloc/examples/flutter_firebase_login/packages/form_inputs/pubspec.yaml', 'repo_id': 'bloc', 'token_count': 85} |
// ignore_for_file: prefer_const_constructors
import 'package:authentication_repository/authentication_repository.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_firebase_login/sign_up/sign_up.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class MockAuthenticationRepository extends Mock
implements AuthenticationRepository {}
void main() {
group('SignUpPage', () {
test('has a route', () {
expect(SignUpPage.route(), isA<MaterialPageRoute<void>>());
});
testWidgets('renders a SignUpForm', (tester) async {
await tester.pumpWidget(
RepositoryProvider<AuthenticationRepository>(
create: (_) => MockAuthenticationRepository(),
child: MaterialApp(home: SignUpPage()),
),
);
expect(find.byType(SignUpForm), findsOneWidget);
});
});
}
| bloc/examples/flutter_firebase_login/test/sign_up/view/sign_up_page_test.dart/0 | {'file_path': 'bloc/examples/flutter_firebase_login/test/sign_up/view/sign_up_page_test.dart', 'repo_id': 'bloc', 'token_count': 346} |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'job.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Job _$JobFromJson(Map<String, dynamic> json) {
return Job(
id: json['id'] as String,
title: json['title'] as String,
locationNames: json['locationNames'] as String?,
isFeatured: json['isFeatured'] as bool? ?? false,
);
}
| bloc/examples/flutter_graphql_jobs/lib/api/models/job.g.dart/0 | {'file_path': 'bloc/examples/flutter_graphql_jobs/lib/api/models/job.g.dart', 'repo_id': 'bloc', 'token_count': 134} |
export 'posts_list.dart';
export 'posts_page.dart';
| bloc/examples/flutter_infinite_list/lib/posts/view/view.dart/0 | {'file_path': 'bloc/examples/flutter_infinite_list/lib/posts/view/view.dart', 'repo_id': 'bloc', 'token_count': 20} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_infinite_list/posts/posts.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('PostsPage', () {
testWidgets('renders PostList', (tester) async {
await tester.pumpWidget(MaterialApp(home: PostsPage()));
await tester.pumpAndSettle();
expect(find.byType(PostsList), findsOneWidget);
});
});
}
| bloc/examples/flutter_infinite_list/test/posts/view/posts_page_test.dart/0 | {'file_path': 'bloc/examples/flutter_infinite_list/test/posts/view/posts_page_test.dart', 'repo_id': 'bloc', 'token_count': 170} |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_login/authentication/authentication.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key});
static Route<void> route() {
return MaterialPageRoute<void>(builder: (_) => const HomePage());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Builder(
builder: (context) {
final userId = context.select(
(AuthenticationBloc bloc) => bloc.state.user.id,
);
return Text('UserID: $userId');
},
),
ElevatedButton(
child: const Text('Logout'),
onPressed: () {
context
.read<AuthenticationBloc>()
.add(AuthenticationLogoutRequested());
},
),
],
),
),
);
}
}
| bloc/examples/flutter_login/lib/home/view/home_page.dart/0 | {'file_path': 'bloc/examples/flutter_login/lib/home/view/home_page.dart', 'repo_id': 'bloc', 'token_count': 571} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_login/login/login.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
const username = 'mock-username';
const password = 'mock-password';
group('LoginEvent', () {
group('LoginUsernameChanged', () {
test('supports value comparisons', () {
expect(LoginUsernameChanged(username), LoginUsernameChanged(username));
});
});
group('LoginPasswordChanged', () {
test('supports value comparisons', () {
expect(LoginPasswordChanged(password), LoginPasswordChanged(password));
});
});
group('LoginSubmitted', () {
test('supports value comparisons', () {
expect(LoginSubmitted(), LoginSubmitted());
});
});
});
}
| bloc/examples/flutter_login/test/login/bloc/login_event_test.dart/0 | {'file_path': 'bloc/examples/flutter_login/test/login/bloc/login_event_test.dart', 'repo_id': 'bloc', 'token_count': 273} |
export 'bloc/cart_bloc.dart';
export 'models/models.dart';
export 'view/cart_page.dart';
| bloc/examples/flutter_shopping_cart/lib/cart/cart.dart/0 | {'file_path': 'bloc/examples/flutter_shopping_cart/lib/cart/cart.dart', 'repo_id': 'bloc', 'token_count': 36} |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_shopping_cart/cart/cart.dart';
import 'package:flutter_shopping_cart/catalog/catalog.dart';
import 'package:flutter_test/flutter_test.dart';
class MockCartBloc extends MockBloc<CartEvent, CartState> implements CartBloc {}
class MockCatalogBloc extends MockBloc<CatalogEvent, CatalogState>
implements CatalogBloc {}
extension PumpApp on WidgetTester {
Future<void> pumpApp({
CartBloc? cartBloc,
CatalogBloc? catalogBloc,
required Widget child,
}) {
return pumpWidget(
MaterialApp(
home: MultiBlocProvider(
providers: [
if (cartBloc != null)
BlocProvider.value(value: cartBloc)
else
BlocProvider(create: (_) => MockCartBloc()),
if (catalogBloc != null)
BlocProvider.value(value: catalogBloc)
else
BlocProvider(create: (_) => MockCatalogBloc()),
],
child: child,
),
),
);
}
}
| bloc/examples/flutter_shopping_cart/test/helper.dart/0 | {'file_path': 'bloc/examples/flutter_shopping_cart/test/helper.dart', 'repo_id': 'bloc', 'token_count': 492} |
import 'package:todos_repository/todos_repository.dart';
enum TodosViewFilter { all, activeOnly, completedOnly }
extension TodosViewFilterX on TodosViewFilter {
bool apply(Todo todo) {
switch (this) {
case TodosViewFilter.all:
return true;
case TodosViewFilter.activeOnly:
return !todo.isCompleted;
case TodosViewFilter.completedOnly:
return todo.isCompleted;
}
}
Iterable<Todo> applyAll(Iterable<Todo> todos) {
return todos.where(apply);
}
}
| bloc/examples/flutter_todos/lib/todos_overview/models/todos_view_filter.dart/0 | {'file_path': 'bloc/examples/flutter_todos/lib/todos_overview/models/todos_view_filter.dart', 'repo_id': 'bloc', 'token_count': 214} |
name: todos_repository
description: A repository that handles todo related requests.
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.19.0 <3.0.0"
dependencies:
todos_api:
path: ../todos_api
dev_dependencies:
mocktail: ^0.3.0
test: ^1.21.4
very_good_analysis: ^3.0.2
| bloc/examples/flutter_todos/packages/todos_repository/pubspec.yaml/0 | {'file_path': 'bloc/examples/flutter_todos/packages/todos_repository/pubspec.yaml', 'repo_id': 'bloc', 'token_count': 129} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_todos/stats/stats.dart';
void main() {
group('StatsEvent', () {
group('StatsSubscriptionRequested', () {
test('supports value equality', () {
expect(
StatsSubscriptionRequested(),
equals(StatsSubscriptionRequested()),
);
});
test('props are correct', () {
expect(
StatsSubscriptionRequested().props,
equals(<Object?>[]),
);
});
});
});
}
| bloc/examples/flutter_todos/test/stats/bloc/stats_event_test.dart/0 | {'file_path': 'bloc/examples/flutter_todos/test/stats/bloc/stats_event_test.dart', 'repo_id': 'bloc', 'token_count': 245} |
export 'weather.dart';
| bloc/examples/flutter_weather/lib/weather/models/models.dart/0 | {'file_path': 'bloc/examples/flutter_weather/lib/weather/models/models.dart', 'repo_id': 'bloc', 'token_count': 8} |
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
part 'weather.g.dart';
enum WeatherCondition {
clear,
rainy,
cloudy,
snowy,
unknown,
}
@JsonSerializable()
class Weather extends Equatable {
const Weather({
required this.location,
required this.temperature,
required this.condition,
});
factory Weather.fromJson(Map<String, dynamic> json) =>
_$WeatherFromJson(json);
Map<String, dynamic> toJson() => _$WeatherToJson(this);
final String location;
final double temperature;
final WeatherCondition condition;
@override
List<Object> get props => [location, temperature, condition];
}
| bloc/examples/flutter_weather/packages/weather_repository/lib/src/models/weather.dart/0 | {'file_path': 'bloc/examples/flutter_weather/packages/weather_repository/lib/src/models/weather.dart', 'repo_id': 'bloc', 'token_count': 219} |
// ignore_for_file: prefer_const_constructors
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_weather/search/search.dart';
import 'package:flutter_weather/settings/settings.dart';
import 'package:flutter_weather/theme/theme.dart';
import 'package:flutter_weather/weather/weather.dart';
import 'package:mocktail/mocktail.dart';
import 'package:weather_repository/weather_repository.dart' hide Weather;
import '../../helpers/hydrated_bloc.dart';
class MockWeatherRepository extends Mock implements WeatherRepository {}
class MockThemeCubit extends MockCubit<Color> implements ThemeCubit {}
class MockWeatherCubit extends MockCubit<WeatherState>
implements WeatherCubit {}
void main() {
initHydratedStorage();
group('WeatherPage', () {
late WeatherRepository weatherRepository;
setUp(() {
weatherRepository = MockWeatherRepository();
});
testWidgets('renders WeatherView', (tester) async {
await tester.pumpWidget(
RepositoryProvider.value(
value: weatherRepository,
child: MaterialApp(home: WeatherPage()),
),
);
expect(find.byType(WeatherView), findsOneWidget);
});
});
group('WeatherView', () {
final weather = Weather(
temperature: Temperature(value: 4.2),
condition: WeatherCondition.cloudy,
lastUpdated: DateTime(2020),
location: 'London',
);
late ThemeCubit themeCubit;
late WeatherCubit weatherCubit;
setUp(() {
themeCubit = MockThemeCubit();
weatherCubit = MockWeatherCubit();
});
testWidgets('renders WeatherEmpty for WeatherStatus.initial',
(tester) async {
when(() => weatherCubit.state).thenReturn(WeatherState());
await tester.pumpWidget(
BlocProvider.value(
value: weatherCubit,
child: MaterialApp(home: WeatherView()),
),
);
expect(find.byType(WeatherEmpty), findsOneWidget);
});
testWidgets('renders WeatherLoading for WeatherStatus.loading',
(tester) async {
when(() => weatherCubit.state).thenReturn(
WeatherState(
status: WeatherStatus.loading,
),
);
await tester.pumpWidget(
BlocProvider.value(
value: weatherCubit,
child: MaterialApp(home: WeatherView()),
),
);
expect(find.byType(WeatherLoading), findsOneWidget);
});
testWidgets('renders WeatherPopulated for WeatherStatus.success',
(tester) async {
when(() => weatherCubit.state).thenReturn(
WeatherState(
status: WeatherStatus.success,
weather: weather,
),
);
await tester.pumpWidget(
BlocProvider.value(
value: weatherCubit,
child: MaterialApp(home: WeatherView()),
),
);
expect(find.byType(WeatherPopulated), findsOneWidget);
});
testWidgets('renders WeatherError for WeatherStatus.failure',
(tester) async {
when(() => weatherCubit.state).thenReturn(
WeatherState(
status: WeatherStatus.failure,
),
);
await tester.pumpWidget(
BlocProvider.value(
value: weatherCubit,
child: MaterialApp(home: WeatherView()),
),
);
expect(find.byType(WeatherError), findsOneWidget);
});
testWidgets('state is cached', (tester) async {
when<dynamic>(() => hydratedStorage.read('$WeatherCubit')).thenReturn(
WeatherState(
status: WeatherStatus.success,
weather: weather,
temperatureUnits: TemperatureUnits.fahrenheit,
).toJson(),
);
await tester.pumpWidget(
BlocProvider.value(
value: WeatherCubit(MockWeatherRepository()),
child: MaterialApp(home: WeatherView()),
),
);
expect(find.byType(WeatherPopulated), findsOneWidget);
});
testWidgets('navigates to SettingsPage when settings icon is tapped',
(tester) async {
when(() => weatherCubit.state).thenReturn(WeatherState());
await tester.pumpWidget(
BlocProvider.value(
value: weatherCubit,
child: MaterialApp(home: WeatherView()),
),
);
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
expect(find.byType(SettingsPage), findsOneWidget);
});
testWidgets('navigates to SearchPage when search button is tapped',
(tester) async {
when(() => weatherCubit.state).thenReturn(WeatherState());
await tester.pumpWidget(
BlocProvider.value(
value: weatherCubit,
child: MaterialApp(home: WeatherView()),
),
);
await tester.tap(find.byType(FloatingActionButton));
await tester.pumpAndSettle();
expect(find.byType(SearchPage), findsOneWidget);
});
testWidgets('calls updateTheme when whether changes', (tester) async {
whenListen(
weatherCubit,
Stream<WeatherState>.fromIterable([
WeatherState(),
WeatherState(status: WeatherStatus.success, weather: weather),
]),
);
when(() => weatherCubit.state).thenReturn(
WeatherState(
status: WeatherStatus.success,
weather: weather,
),
);
await tester.pumpWidget(
MultiBlocProvider(
providers: [
BlocProvider.value(value: themeCubit),
BlocProvider.value(value: weatherCubit),
],
child: MaterialApp(home: WeatherView()),
),
);
verify(() => themeCubit.updateTheme(weather)).called(1);
});
testWidgets('triggers refreshWeather on pull to refresh', (tester) async {
when(() => weatherCubit.state).thenReturn(
WeatherState(
status: WeatherStatus.success,
weather: weather,
),
);
when(() => weatherCubit.refreshWeather()).thenAnswer((_) async {});
await tester.pumpWidget(
BlocProvider.value(
value: weatherCubit,
child: MaterialApp(home: WeatherView()),
),
);
await tester.fling(
find.text('London'),
const Offset(0, 500),
1000,
);
await tester.pumpAndSettle();
verify(() => weatherCubit.refreshWeather()).called(1);
});
testWidgets('triggers fetch on search pop', (tester) async {
when(() => weatherCubit.state).thenReturn(WeatherState());
when(() => weatherCubit.fetchWeather(any())).thenAnswer((_) async {});
await tester.pumpWidget(
BlocProvider.value(
value: weatherCubit,
child: MaterialApp(home: WeatherView()),
),
);
await tester.tap(find.byType(FloatingActionButton));
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), 'Chicago');
await tester.tap(find.byKey(const Key('searchPage_search_iconButton')));
await tester.pumpAndSettle();
verify(() => weatherCubit.fetchWeather('Chicago')).called(1);
});
});
}
| bloc/examples/flutter_weather/test/weather/view/weather_page_test.dart/0 | {'file_path': 'bloc/examples/flutter_weather/test/weather/view/weather_page_test.dart', 'repo_id': 'bloc', 'token_count': 3002} |
import 'package:angular_github_search/src/github_search.dart';
import 'package:common_github_search/common_github_search.dart';
import 'package:ngdart/angular.dart';
@Component(
selector: 'search-body',
templateUrl: 'search_body_component.html',
directives: [
coreDirectives,
SearchResultsComponent,
],
)
class SearchBodyComponent {
@Input()
late GithubSearchState state;
bool get isEmpty => state is SearchStateEmpty;
bool get isLoading => state is SearchStateLoading;
bool get isSuccess => state is SearchStateSuccess;
bool get isError => state is SearchStateError;
List<SearchResultItem> get items =>
isSuccess ? (state as SearchStateSuccess).items : [];
String get error => isError ? (state as SearchStateError).error : '';
}
| bloc/examples/github_search/angular_github_search/lib/src/search_form/search_body/search_body_component.dart/0 | {'file_path': 'bloc/examples/github_search/angular_github_search/lib/src/search_form/search_body/search_body_component.dart', 'repo_id': 'bloc', 'token_count': 231} |
export 'src/github_cache.dart';
export 'src/github_client.dart';
export 'src/github_repository.dart';
export 'src/github_search_bloc/github_search_bloc.dart';
export 'src/github_search_bloc/github_search_event.dart';
export 'src/github_search_bloc/github_search_state.dart';
export 'src/models/models.dart';
| bloc/examples/github_search/common_github_search/lib/common_github_search.dart/0 | {'file_path': 'bloc/examples/github_search/common_github_search/lib/common_github_search.dart', 'repo_id': 'bloc', 'token_count': 114} |
include: package:very_good_analysis/analysis_options.3.1.0.yaml
analyzer:
exclude: [build/**]
linter:
rules:
public_member_api_docs: false
| bloc/examples/github_search/flutter_github_search/analysis_options.yaml/0 | {'file_path': 'bloc/examples/github_search/flutter_github_search/analysis_options.yaml', 'repo_id': 'bloc', 'token_count': 57} |
export './counter_bloc.dart';
export './counter_error_bloc.dart';
export './counter_exception_bloc.dart';
export './merge_bloc.dart';
export './on_error_bloc.dart';
export './on_event_error_bloc.dart';
export './on_exception_bloc.dart';
export './on_transition_error_bloc.dart';
| bloc/packages/bloc/test/blocs/counter/counter.dart/0 | {'file_path': 'bloc/packages/bloc/test/blocs/counter/counter.dart', 'repo_id': 'bloc', 'token_count': 116} |
// ignore_for_file: deprecated_member_use_from_same_package
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
import 'cubits/cubits.dart';
class MockBlocObserver extends Mock implements BlocObserver {}
class FakeBlocBase<S> extends Fake implements BlocBase<S> {}
class FakeChange<S> extends Fake implements Change<S> {}
void main() {
group('Cubit', () {
group('constructor', () {
late BlocObserver observer;
setUp(() {
observer = MockBlocObserver();
});
test('triggers onCreate on observer', () {
BlocOverrides.runZoned(() {
final cubit = CounterCubit();
// ignore: invalid_use_of_protected_member
verify(() => observer.onCreate(cubit)).called(1);
}, blocObserver: observer);
});
});
group('initial state', () {
test('is correct', () {
expect(CounterCubit().state, 0);
});
});
group('addError', () {
late BlocObserver observer;
setUp(() {
observer = MockBlocObserver();
});
test('triggers onError', () async {
BlocOverrides.runZoned(() {
final expectedError = Exception('fatal exception');
final expectedStackTrace = StackTrace.current;
final errors = <Object>[];
final stackTraces = <StackTrace>[];
final cubit = CounterCubit(
onErrorCallback: (error, stackTrace) {
errors.add(error);
stackTraces.add(stackTrace);
},
// ignore: invalid_use_of_protected_member
)..addError(expectedError, expectedStackTrace);
expect(errors.length, equals(1));
expect(errors.first, equals(expectedError));
expect(stackTraces.length, equals(1));
expect(stackTraces.first, isNotNull);
expect(stackTraces.first, isNot(StackTrace.empty));
verify(
// ignore: invalid_use_of_protected_member
() => observer.onError(cubit, expectedError, expectedStackTrace),
).called(1);
}, blocObserver: observer);
});
});
group('onChange', () {
late BlocObserver observer;
setUpAll(() {
registerFallbackValue(FakeBlocBase<dynamic>());
registerFallbackValue(FakeChange<dynamic>());
});
setUp(() {
observer = MockBlocObserver();
});
test('is not called for the initial state', () async {
await BlocOverrides.runZoned(() async {
final changes = <Change<int>>[];
final cubit = CounterCubit(onChangeCallback: changes.add);
await cubit.close();
expect(changes, isEmpty);
// ignore: invalid_use_of_protected_member
verifyNever(() => observer.onChange(any(), any()));
}, blocObserver: observer);
});
test('is called with correct change for a single state change', () async {
await BlocOverrides.runZoned(() async {
final changes = <Change<int>>[];
final cubit = CounterCubit(onChangeCallback: changes.add)
..increment();
await cubit.close();
expect(
changes,
const [Change<int>(currentState: 0, nextState: 1)],
);
verify(
// ignore: invalid_use_of_protected_member
() => observer.onChange(
cubit,
const Change<int>(currentState: 0, nextState: 1),
),
).called(1);
}, blocObserver: observer);
});
test('is called with correct changes for multiple state changes',
() async {
await BlocOverrides.runZoned(() async {
final changes = <Change<int>>[];
final cubit = CounterCubit(onChangeCallback: changes.add)
..increment()
..increment();
await cubit.close();
expect(
changes,
const [
Change<int>(currentState: 0, nextState: 1),
Change<int>(currentState: 1, nextState: 2),
],
);
verify(
// ignore: invalid_use_of_protected_member
() => observer.onChange(
cubit,
const Change<int>(currentState: 0, nextState: 1),
),
).called(1);
verify(
// ignore: invalid_use_of_protected_member
() => observer.onChange(
cubit,
const Change<int>(currentState: 1, nextState: 2),
),
).called(1);
}, blocObserver: observer);
});
});
group('emit', () {
test('throws StateError if cubit is closed', () {
var didThrow = false;
runZonedGuarded(() {
final cubit = CounterCubit();
expectLater(
cubit.stream,
emitsInOrder(<Matcher>[equals(1), emitsDone]),
);
cubit
..increment()
..close()
..increment();
}, (error, _) {
didThrow = true;
expect(
error,
isA<StateError>().having(
(e) => e.message,
'message',
'Cannot emit new states after calling close',
),
);
});
expect(didThrow, isTrue);
});
test('emits states in the correct order', () async {
final states = <int>[];
final cubit = CounterCubit();
final subscription = cubit.stream.listen(states.add);
cubit.increment();
await cubit.close();
await subscription.cancel();
expect(states, [1]);
});
test('can emit initial state only once', () async {
final states = <int>[];
final cubit = SeededCubit(initialState: 0);
final subscription = cubit.stream.listen(states.add);
cubit
..emitState(0)
..emitState(0);
await cubit.close();
await subscription.cancel();
expect(states, [0]);
});
test(
'can emit initial state and '
'continue emitting distinct states', () async {
final states = <int>[];
final cubit = SeededCubit(initialState: 0);
final subscription = cubit.stream.listen(states.add);
cubit
..emitState(0)
..emitState(1);
await cubit.close();
await subscription.cancel();
expect(states, [0, 1]);
});
test('does not emit duplicate states', () async {
final states = <int>[];
final cubit = SeededCubit(initialState: 0);
final subscription = cubit.stream.listen(states.add);
cubit
..emitState(1)
..emitState(1)
..emitState(2)
..emitState(2)
..emitState(3)
..emitState(3);
await cubit.close();
await subscription.cancel();
expect(states, [1, 2, 3]);
});
});
group('listen', () {
test('returns a StreamSubscription', () {
final cubit = CounterCubit();
final subscription = cubit.stream.listen((_) {});
expect(subscription, isA<StreamSubscription<int>>());
subscription.cancel();
cubit.close();
});
test('does not receive current state upon subscribing', () async {
final states = <int>[];
final cubit = CounterCubit()..stream.listen(states.add);
await cubit.close();
expect(states, isEmpty);
});
test('receives single async state', () async {
final states = <int>[];
final cubit = FakeAsyncCounterCubit()..stream.listen(states.add);
await cubit.increment();
await cubit.close();
expect(states, [equals(1)]);
});
test('receives multiple async states', () async {
final states = <int>[];
final cubit = FakeAsyncCounterCubit()..stream.listen(states.add);
await cubit.increment();
await cubit.increment();
await cubit.increment();
await cubit.close();
expect(states, [equals(1), equals(2), equals(3)]);
});
test('can call listen multiple times', () async {
final states = <int>[];
final cubit = CounterCubit()
..stream.listen(states.add)
..stream.listen(states.add)
..increment();
await cubit.close();
expect(states, [equals(1), equals(1)]);
});
});
group('close', () {
late MockBlocObserver observer;
setUp(() {
observer = MockBlocObserver();
});
test('triggers onClose on observer', () async {
await BlocOverrides.runZoned(() async {
final cubit = CounterCubit();
await cubit.close();
// ignore: invalid_use_of_protected_member
verify(() => observer.onClose(cubit)).called(1);
}, blocObserver: observer);
});
test('emits done (sync)', () {
final cubit = CounterCubit()..close();
expect(cubit.stream, emitsDone);
});
test('emits done (async)', () async {
final cubit = CounterCubit();
await cubit.close();
expect(cubit.stream, emitsDone);
});
});
group('isClosed', () {
test('returns true after cubit is closed', () async {
final cubit = CounterCubit();
expect(cubit.isClosed, isFalse);
await cubit.close();
expect(cubit.isClosed, isTrue);
});
});
});
}
| bloc/packages/bloc/test/cubit_test_legacy.dart/0 | {'file_path': 'bloc/packages/bloc/test/cubit_test_legacy.dart', 'repo_id': 'bloc', 'token_count': 4406} |
import 'package:bloc/bloc.dart';
/// Process events one at a time by maintaining a queue of added events
/// and processing the events sequentially.
///
/// **Note**: there is no event handler overlap and every event is guaranteed
/// to be handled in the order it was received.
EventTransformer<Event> sequential<Event>() {
return (events, mapper) => events.asyncExpand(mapper);
}
| bloc/packages/bloc_concurrency/lib/src/sequential.dart/0 | {'file_path': 'bloc/packages/bloc_concurrency/lib/src/sequential.dart', 'repo_id': 'bloc', 'token_count': 105} |
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:mocktail/mocktail.dart';
/// Creates a stub response for the `listen` method on a [bloc].
/// Use [whenListen] if you want to return a canned `Stream` of states
/// for a [bloc] instance.
///
/// [whenListen] also handles stubbing the `state` of the [bloc] to stay
/// in sync with the emitted state.
///
/// Return a canned state stream of `[0, 1, 2, 3]`
/// when `counterBloc.stream.listen` is called.
///
/// ```dart
/// whenListen(counterBloc, Stream.fromIterable([0, 1, 2, 3]));
/// ```
///
/// Assert that the `counterBloc` state `Stream` is the canned `Stream`.
///
/// ```dart
/// await expectLater(
/// counterBloc.stream,
/// emitsInOrder(
/// <Matcher>[equals(0), equals(1), equals(2), equals(3), emitsDone],
/// )
/// );
/// expect(counterBloc.state, equals(3));
/// ```
///
/// Optionally provide an [initialState] to stub the state of the [bloc]
/// before any subscriptions.
///
/// ```dart
/// whenListen(
/// counterBloc,
/// Stream.fromIterable([0, 1, 2, 3]),
/// initialState: 0,
/// );
///
/// expect(counterBloc.state, equals(0));
/// ```
void whenListen<State>(
BlocBase<State> bloc,
Stream<State> stream, {
State? initialState,
}) {
final broadcastStream = stream.asBroadcastStream();
if (initialState != null) {
when(() => bloc.state).thenReturn(initialState);
}
when(() => bloc.stream).thenAnswer(
(_) => broadcastStream.map((state) {
when(() => bloc.state).thenReturn(state);
return state;
}),
);
}
| bloc/packages/bloc_test/lib/src/when_listen.dart/0 | {'file_path': 'bloc/packages/bloc_test/lib/src/when_listen.dart', 'repo_id': 'bloc', 'token_count': 553} |
import 'dart:async';
import 'package:bloc/bloc.dart';
class AsyncCounterCubit extends Cubit<int> {
AsyncCounterCubit() : super(0);
Future<void> increment() async {
await Future<void>.delayed(const Duration(microseconds: 1));
emit(state + 1);
}
}
| bloc/packages/bloc_test/test/cubits/async_counter_cubit.dart/0 | {'file_path': 'bloc/packages/bloc_test/test/cubits/async_counter_cubit.dart', 'repo_id': 'bloc', 'token_count': 97} |
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
/// Signature for the `selector` function which
/// is responsible for returning a selected value, [T], based on [state].
typedef BlocWidgetSelector<S, T> = T Function(S state);
/// {@template bloc_selector}
/// [BlocSelector] is analogous to [BlocBuilder] but allows developers to
/// filter updates by selecting a new value based on the bloc state.
/// Unnecessary builds are prevented if the selected value does not change.
///
/// **Note**: the selected value must be immutable in order for [BlocSelector]
/// to accurately determine whether [builder] should be called again.
///
/// ```dart
/// BlocSelector<BlocA, BlocAState, SelectedState>(
/// selector: (state) {
/// // return selected state based on the provided state.
/// },
/// builder: (context, state) {
/// // return widget here based on the selected state.
/// },
/// )
/// ```
/// {@endtemplate}
class BlocSelector<B extends StateStreamable<S>, S, T> extends StatefulWidget {
/// {@macro bloc_selector}
const BlocSelector({
Key? key,
required this.selector,
required this.builder,
this.bloc,
}) : super(key: key);
/// The [bloc] that the [BlocSelector] will interact with.
/// If omitted, [BlocSelector] will automatically perform a lookup using
/// [BlocProvider] and the current [BuildContext].
final B? bloc;
/// The [builder] function which will be invoked
/// when the selected state changes.
/// The [builder] takes the [BuildContext] and selected `state` and
/// must return a widget.
/// This is analogous to the [builder] function in [BlocBuilder].
final BlocWidgetBuilder<T> builder;
/// The [selector] function which will be invoked on each widget build
/// and is responsible for returning a selected value of type [T] based on
/// the current state.
final BlocWidgetSelector<S, T> selector;
@override
State<BlocSelector<B, S, T>> createState() => _BlocSelectorState<B, S, T>();
}
class _BlocSelectorState<B extends StateStreamable<S>, S, T>
extends State<BlocSelector<B, S, T>> {
late B _bloc;
late T _state;
@override
void initState() {
super.initState();
_bloc = widget.bloc ?? context.read<B>();
_state = widget.selector(_bloc.state);
}
@override
void didUpdateWidget(BlocSelector<B, S, T> oldWidget) {
super.didUpdateWidget(oldWidget);
final oldBloc = oldWidget.bloc ?? context.read<B>();
final currentBloc = widget.bloc ?? oldBloc;
if (oldBloc != currentBloc) {
_bloc = currentBloc;
_state = widget.selector(_bloc.state);
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final bloc = widget.bloc ?? context.read<B>();
if (_bloc != bloc) {
_bloc = bloc;
_state = widget.selector(_bloc.state);
}
}
@override
Widget build(BuildContext context) {
if (widget.bloc == null) {
// Trigger a rebuild if the bloc reference has changed.
// See https://github.com/felangel/bloc/issues/2127.
context.select<B, bool>((bloc) => identical(_bloc, bloc));
}
return BlocListener<B, S>(
bloc: _bloc,
listener: (context, state) {
final selectedState = widget.selector(state);
if (_state != selectedState) setState(() => _state = selectedState);
},
child: widget.builder(context, _state),
);
}
}
| bloc/packages/flutter_bloc/lib/src/bloc_selector.dart/0 | {'file_path': 'bloc/packages/flutter_bloc/lib/src/bloc_selector.dart', 'repo_id': 'bloc', 'token_count': 1185} |
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
part 'freezed_cubit.freezed.dart';
part 'freezed_cubit.g.dart';
class FreezedCubit extends HydratedCubit<Tree?> {
FreezedCubit() : super(null);
void setQuestion(Tree tree) => emit(tree);
@override
Map<String, dynamic>? toJson(Tree? state) => state?.toJson();
@override
Tree fromJson(Map<String, dynamic> json) => Tree.fromJson(json);
}
@freezed
class Question with _$Question {
const factory Question({
int? id,
String? question,
}) = _Question;
factory Question.fromJson(Map<String, dynamic> json) =>
_$QuestionFromJson(json);
}
@freezed
class Tree with _$Tree {
const factory Tree({
Question? question,
Tree? left,
Tree? right,
}) = _QTree;
factory Tree.fromJson(Map<String, dynamic> json) => _$TreeFromJson(json);
}
| bloc/packages/hydrated_bloc/test/cubits/freezed_cubit.dart/0 | {'file_path': 'bloc/packages/hydrated_bloc/test/cubits/freezed_cubit.dart', 'repo_id': 'bloc', 'token_count': 333} |
import 'package:replay_bloc/replay_bloc.dart';
class CounterCubit extends ReplayCubit<int> {
CounterCubit({
int? limit,
this.shouldReplayCallback,
}) : super(0, limit: limit);
final bool Function(int)? shouldReplayCallback;
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
@override
bool shouldReplay(int state) {
return shouldReplayCallback?.call(state) ?? super.shouldReplay(state);
}
}
class CounterCubitMixin extends Cubit<int> with ReplayCubitMixin<int> {
CounterCubitMixin({int? limit}) : super(0) {
if (limit != null) {
this.limit = limit;
}
}
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
}
| bloc/packages/replay_bloc/test/cubits/counter_cubit.dart/0 | {'file_path': 'bloc/packages/replay_bloc/test/cubits/counter_cubit.dart', 'repo_id': 'bloc', 'token_count': 254} |
import 'package:test/test.dart';
import 'package:bloc_test/bloc_test.dart';
import '../counter_bloc.dart';
void main() {
group('CounterBloc', () {
blocTest(
'emits [0] when no events are added',
build: () => CounterBloc(),
expect: [0],
);
blocTest(
'emits [0, 1] when CounterEvent.increment is added',
build: () => CounterBloc(),
act: (counterBloc) => counterBloc.add(CounterEvent.increment),
expect: [0, 1],
);
blocTest(
'emits [0, -1] when CounterEvent.decrement is added',
build: () => CounterBloc(),
act: (counterBloc) => counterBloc.add(CounterEvent.decrement),
expect: [0, -1],
);
});
}
| bloc_library_basics_and_beyond/example/test/counter_bloc_test.dart/0 | {'file_path': 'bloc_library_basics_and_beyond/example/test/counter_bloc_test.dart', 'repo_id': 'bloc_library_basics_and_beyond', 'token_count': 299} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.